path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
fields/types/location/LocationColumn.js | rafmsou/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country'];
var LocationColumn = React.createClass({
displayName: 'LocationColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !Object.keys(value).length) return null;
const output = [];
SUB_FIELDS.map((i) => {
if (value[i]) {
output.push(value[i]);
}
});
return (
<ItemsTableValue field={this.props.col.type} title={output.join(', ')}>
{output.join(', ')}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = LocationColumn;
|
src/component/flight-container/index.js | aesthetiques/alaska-airlines-fe | import React from 'react'
import {connect} from 'react-redux'
import FlightItem from '../flight-item'
import * as utils from '../../lib/utils'
class FlightContainer extends React.Component{
render(){
return(
<div className="flight-container">
<FlightItem />
</div>
)
}
}
let mapStateToProps = state => ({
locations: state.location,
})
let mapDispatchToProps = dispatch => ({})
export default connect(mapStateToProps, mapDispatchToProps)(FlightContainer) |
app/components/Link.js | alexindigo/ndash | import React, { Component } from 'react';
import { TouchableOpacity } from 'react-native';
import { openUrl, shareUrl } from '../helpers/url';
export default class Link extends Component {
render() {
const {url, style, ...props} = this.props;
return (
<TouchableOpacity
style={[{flex: 1}, style]}
{...props}
onPress={() => openUrl(url, this.props.onError)}
onLongPress={() => shareUrl(url, this.props.onError, this.props.onShare)}
/>
);
}
}
|
plugins/Wallet/js/components/receivebutton.js | NebulousLabs/Sia-UI | import React from 'react'
const ReceiveButton = ({ actions }) => {
const handleReceiveButtonClick = () => actions.showReceivePrompt()
return (
<div
className='wallet-button receive-button'
onClick={handleReceiveButtonClick}
>
<i className='fa fa-download fa-2x' />
<span>Receive Siacoin</span>
</div>
)
}
export default ReceiveButton
|
src/routes/order/send/index.js | terryli1643/daoke-react-c | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import OrderForm from '../../../components/order/Form'
const Send = ({ order, contact, dispatch }) => {
const { currentItem, modalType, modalVisible } = order
const { recipientContacts, senderContacts } = contact
const commentsModalProps = {
visible: modalVisible,
onOk (value) {
dispatch({
type: 'record/setCurrentItem',
payload: {
currentItem: {
remark: value,
},
},
})
dispatch({
type: 'record/hideModal',
})
},
onCancel () {
dispatch({
type: 'record/hideModal',
})
},
}
const formProps = {
commentsModalProps,
currentItem,
dispatch,
modalVisible,
modalType,
recipientContacts,
senderContacts,
}
return (
<OrderForm {...formProps} />
)
}
Send.propTypes = {
form: PropTypes.object,
dispatch: PropTypes.func,
order: PropTypes.object,
contact: PropTypes.object,
}
export default connect(({ order, contact }) => ({ order, contact }))(Send)
|
examples/src/auth/app.js | arnogeurts/ReactReduxForm | "use strict";
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import createStore from '../base/create-store';
import AuthForm from './auth-form';
import Layout from './layout';
ReactDOM.render(
<Provider store={createStore(AuthForm.reducer)}>
<Layout/>
</Provider>,
document.getElementById('app')
);
|
frontend/src/InteractiveSearch/InteractiveSearchTable.js | Radarr/Radarr | import React from 'react';
import InteractiveSearchContentConnector from './InteractiveSearchContentConnector';
function InteractiveSearchTable(props) {
return (
<InteractiveSearchContentConnector
searchPayload={props}
/>
);
}
InteractiveSearchTable.propTypes = {
};
export default InteractiveSearchTable;
|
src/components/pages/Home.js | StillLearnin/time-clock-ui | import React from 'react';
import { Component } from 'react';
import TimeLog from '../time-log/TimeLog';
import PunchPanel from '../punch-panel/PunchPanel'
import css from './Home.css'
export default class Home extends Component {
render() {
return (
<div className={css.homeBody}>
<div className={css.containerLeft}>
<PunchPanel {...this.props} />
</div>
<div className={css.containerRight}>
<TimeLog {...this.props} />
</div>
</div>
);
}
}
|
client-src/js/components/list-edit-component.js | MatthewNichols/ThePickupList | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {
e.preventDefault();
console.log("saveClickHandler", this);
this.props.addNewList(this.state.listName);
this.context.router.push('/');
}
cancelClickHandler(e) {
e.preventDefault();
this.context.router.push('/');
}
render() {
let screenTitle = this.props.params.listId ? "Edit List" : "Add new List";
return (
<div>
<h3>{screenTitle}</h3>
<input type="text"
placeholder="Name of List"
onChange={event => this.setState({listName: event.target.value})}
/>
<div className="footer">
<a onClick={this.cancelClickHandler.bind(this)} href="#">Cancel</a>
<a onClick={this.saveClickHandler.bind(this)} href="#">Save</a>
</div>
</div>
)
}
}
ListEdit.contextTypes = {
router: React.PropTypes.object.isRequired
};
function mapDispatchToProps(dispatch) {
"use strict";
return bindActionCreators({addNewList}, dispatch);
}
export default connect(null, mapDispatchToProps)(ListEdit); |
app/javascript/mastodon/features/ui/index.js | verniy6462/mastodon | import React from 'react';
import classNames from 'classnames';
import Redirect from 'react-router-dom/Redirect';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose } from '../../actions/compose';
import { refreshHomeTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
Blocks,
Mutes,
} from './util/async-components';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const mapStateToProps = state => ({
systemFontUi: state.getIn(['meta', 'system_font_ui']),
isComposing: state.getIn(['compose', 'is_composing']),
});
@connect(mapStateToProps)
export default class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
}
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
systemFontUi: PropTypes.bool,
isComposing: PropTypes.bool,
};
state = {
width: window.innerWidth,
draggingOver: false,
};
handleResize = debounce(() => {
this.setState({ width: window.innerWidth });
}, 500, {
trailing: true,
});
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type); // eslint-disable-line no-console
}
}
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(refreshHomeTimeline());
this.props.dispatch(refreshNotifications());
}
shouldComponentUpdate (nextProps) {
if (nextProps.isComposing !== this.props.isComposing) {
// Avoid expensive update just to toggle a class
this.node.classList.toggle('is-composing', nextProps.isComposing);
return false;
}
// Why isn't this working?!?
// return super.shouldComponentUpdate(nextProps, nextState);
return true;
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = (c) => {
this.node = c;
}
render () {
const { width, draggingOver } = this.state;
const { children } = this.props;
const className = classNames('ui', {
'system-font': this.props.systemFontUi,
});
return (
<div className={className} ref={this.setRef}>
<TabsBar />
<ColumnsAreaContainer singleColumn={isMobile(width)}>
<WrappedSwitch>
<Redirect from='/' to='/getting-started' exact />
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} />
<WrappedRoute path='/timelines/public/local' component={CommunityTimeline} content={children} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} />
<WrappedRoute path='/notifications' component={Notifications} content={children} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
<WrappedRoute path='/blocks' component={Blocks} content={children} />
<WrappedRoute path='/mutes' component={Mutes} content={children} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
);
}
}
|
Example/components/TabView.js | charpeni/react-native-router-flux | import React from 'react';
import {PropTypes} from "react";
import {StyleSheet, Text, View, ViewPropTypes} from "react-native";
import Button from 'react-native-button';
import { Actions } from 'react-native-router-flux';
const contextTypes = {
drawer: React.PropTypes.object,
};
const propTypes = {
name: PropTypes.string,
sceneStyle: ViewPropTypes.style,
title: PropTypes.string,
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 2,
borderColor: 'red',
},
});
const TabView = (props) => {
return (
<View style={[styles.container, props.sceneStyle ]}>
<Text>Tab title:{props.title} name:{props.name}</Text>
{props.name === 'tab1_1' &&
<Button onPress={()=>Actions.tab1_2()}>next screen for tab1_1</Button>
}
{props.name === 'tab2_1' &&
<Button onPress={()=>Actions.tab2_2()}>next screen for tab2_1</Button>
}
<Button onPress={Actions.pop}>Back</Button>
<Button onPress={() => { Actions.tab1(); }}>Switch to tab1</Button>
<Button onPress={() => { Actions.tab2(); }}>Switch to tab2</Button>
<Button onPress={() => { Actions.tab3(); }}>Switch to tab3</Button>
<Button onPress={() => { Actions.tab4(); }}>Switch to tab4</Button>
<Button onPress={() => { Actions.tab5(); }}>Switch to tab5</Button>
<Button onPress={() => { Actions.echo(); }}>push clone scene (EchoView)</Button>
</View>
);
};
TabView.contextTypes = contextTypes;
TabView.propTypes = propTypes;
export default TabView;
|
src/parser/priest/shadow/modules/checklist/Component.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Checklist from 'parser/shared/modules/features/Checklist';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement';
class ShadowPriestChecklist extends React.PureComponent {
static propTypes = {
castEfficiency: PropTypes.object.isRequired,
combatant: PropTypes.shape({
hasTalent: PropTypes.func.isRequired,
hasTrinket: PropTypes.func.isRequired,
}).isRequired,
thresholds: PropTypes.object.isRequired,
};
render() {
const { combatant, castEfficiency, thresholds } = this.props;
const DotUptime = props => (
<Requirement
name={(
<React.Fragment>
<SpellLink id={props.id} icon /> uptime
</React.Fragment>
)}
thresholds={props.thresholds}
/>
);
const AbilityRequirement = props => (
<GenericCastEfficiencyRequirement
castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
{...props}
/>
);
const VoidFormStacks = props => {
const requirements = [];
for (let voidFormIndex = 0; voidFormIndex < props.voidform.voidforms.length; voidFormIndex++) {
const thresholds = props.voidform.suggestionStackThresholds(props.voidform.voidforms[voidFormIndex]);
// If you end the fight in voidform, we want to mark that voidform as green.
if (props.voidform.voidforms[voidFormIndex].excluded) {
thresholds.isLessThan = { minor: 0 };
}
requirements.push(<Requirement
key={voidFormIndex}
name={`Voidform #${voidFormIndex + 1} stacks`}
thresholds={thresholds}
/>);
}
return requirements;
};
return (
<Checklist>
<Rule
name="Maintain your DoTs on the boss"
description={(
<React.Fragment>
Both <SpellLink id={SPELLS.SHADOW_WORD_PAIN.id} /> and <SpellLink id={SPELLS.VAMPIRIC_TOUCH.id} /> duration extends when the target or a nearby target gets hit by <SpellLink id={SPELLS.VOID_BOLT.id} />.
Due to this, you often only need to apply these spells to new targets and refresh them on targets that are too far away from your primary target.
</React.Fragment>
)}
>
<DotUptime id={SPELLS.SHADOW_WORD_PAIN.id} thresholds={thresholds.shadowWordPain} />
<DotUptime id={SPELLS.VAMPIRIC_TOUCH.id} thresholds={thresholds.vampiricTouch} />
{combatant.hasTalent(SPELLS.SIPHON_LIFE_TALENT.id) && <DotUptime id={SPELLS.SIPHON_LIFE_TALENT.id} thresholds={thresholds.siphonLife} />}
</Rule>
<Rule
name="Use core spells as often as possible"
description={(
<React.Fragment>
Spells such as <SpellLink id={SPELLS.VOID_BOLT.id} />, <SpellLink id={SPELLS.MIND_BLAST.id} />, or <SpellLink id={SPELLS.SHADOW_WORD_VOID_TALENT.id} /> are your most important spells. Try to cast them as much as possible.
</React.Fragment>
)}
>
<AbilityRequirement spell={SPELLS.VOID_BOLT.id} />
{combatant.hasTalent(SPELLS.SHADOW_WORD_VOID_TALENT.id) ?
<AbilityRequirement spell={SPELLS.SHADOW_WORD_VOID_TALENT.id} /> :
<AbilityRequirement spell={SPELLS.MIND_BLAST.id} />
}
</Rule>
<Rule
name="Use cooldowns effectively"
description={(
<React.Fragment>
Cooldowns are an important part of your rotation, you should be using them as often as possible.
</React.Fragment>
)}
>
{combatant.hasTalent(SPELLS.MINDBENDER_TALENT_SHADOW.id) ?
<AbilityRequirement spell={SPELLS.MINDBENDER_TALENT_SHADOW.id} /> :
<AbilityRequirement spell={SPELLS.SHADOWFIEND.id} />
}
{combatant.hasTalent(SPELLS.DARK_ASCENSION_TALENT.id) && (
<AbilityRequirement spell={SPELLS.DARK_ASCENSION_TALENT.id} />
)}
{combatant.hasTalent(SPELLS.SHADOW_CRASH_TALENT.id) && (
<AbilityRequirement spell={SPELLS.SHADOW_CRASH_TALENT.id} />
)}
</Rule>
<Rule
name={(
<React.Fragment>Maximize <SpellLink id={SPELLS.VOIDFORM.id} /> stacks</React.Fragment>
)}
description={(
<React.Fragment>
Your Voidforms are an important part of your overall damage.
Try to get at least 20 stacks every Voidform with proper <SpellLink id={SPELLS.VOID_BOLT.id} /> and <SpellLink id={SPELLS.MIND_BLAST.id} /> usage.
Use <SpellLink id={SPELLS.MINDBENDER_TALENT_SHADOW.id} /> on cooldown (even outside of Voidform).
</React.Fragment>
)}
>
<Requirement
name={(
<React.Fragment>
<SpellLink id={SPELLS.VOIDFORM.id} icon /> uptime
</React.Fragment>
)}
thresholds={thresholds.voidform.suggestionUptimeThresholds}
/>
<VoidFormStacks voidform={thresholds.voidform} />
</Rule>
<Rule
name="Minimize casting downtime"
description={(
<React.Fragment>
Try to minimize your time not casting. Use your core spells on cooldown and fillers when they are not available. If you know you have an upcoming position requirement, stutterstep with each <SpellLink id={SPELLS.VOID_BOLT.id} /> cast towards that location. During high movement you can use <SpellLink id={SPELLS.SHADOW_WORD_PAIN.id} /> as a filler.
</React.Fragment>
)}
>
<Requirement name="Downtime" thresholds={thresholds.downtime} />
</Rule>
<PreparationRule thresholds={thresholds} />
</Checklist>
);
}
}
export default ShadowPriestChecklist;
|
src/svg-icons/file/folder.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileFolder = (props) => (
<SvgIcon {...props}>
<path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/>
</SvgIcon>
);
FileFolder = pure(FileFolder);
FileFolder.displayName = 'FileFolder';
FileFolder.muiName = 'SvgIcon';
export default FileFolder;
|
src/molecules/archive/pagination/stories.js | dsmjs/components | /* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import React from 'react';
import storyRouter from 'storybook-router';
import {linkTo} from '@storybook/addon-links';
import Pagination from '.';
export default {
title: 'Molecules/Archive/Pagination',
decorators: [
storyRouter({
'/archive': linkTo('Molecules/Archive/Pagination', 'default'),
'/archive/page-2': linkTo('Molecules/Archive/Pagination', 'page-2')
})
]
};
export const Default = () => <Pagination totalPages={20} currentPage={1} />;
Default.story = {
name: 'default'
};
export const Page2 = () => <Pagination totalPages={20} currentPage={2} />;
Page2.story = {
name: 'page-2'
};
|
Html.js | spanias/isomorphic-react-base-app | /**
* Copyright 2015, Digital Optimization Group, LLC.
* Copyrights licensed under the APACHE 2 License. See the accompanying LICENSE file for terms.
*/
import React from 'react';
class HtmlComponent extends React.Component {
render() {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
{ this.props.css.map((href, k) =>
<link key={k} rel="stylesheet" type="text/css" href={href} />)
}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{__html: this.props.markup}}></div>
<script dangerouslySetInnerHTML={{__html: this.props.state}}></script>
{ this.props.script.map((src, k) => <script key={k} src={src} />) }
</body>
</html>
)
}
}
export default HtmlComponent;
|
src/components/current.js | shootermantes/rome-weather | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
// Action Creators
import getCurrentData from '../actions/getCurrentData';
import getFiveDay from '../actions/getFiveDay';
import changeUnit from '../actions/changeUnit';
import convertData from '../actions/convertData';
import getPollutCO from '../actions/getPollutCO';
import getPollutNO from '../actions/getPollutNO';
import getAlerts from '../actions/getAlerts';
// Component
import Pollut from './pollut';
export class Current extends Component {
constructor(props) {
super(props)
this.state = {value: this.props.unit};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount(){
this.props.dispatch(getCurrentData("Imperial"));
this.props.dispatch(getFiveDay("Imperial"));
this.props.dispatch(getPollutCO());
}
componentWillMount(){
this.props.dispatch(changeUnit(<span>℉</span>))
}
handleChange(event) {
let data = {
temp: this.props.currentTemp,
humidity: this.props.currentHumidity,
hi: this.props.currentHi,
lo: this.props.currentLow,
unit: event.target.value
}
// This Changes the values celcius, fahrenheit or both. Also changes the units
if(event.target.value ==="F" && (!(typeof(this.props.currentTemp)==="string")) ){
// Initial units
this.props.dispatch(changeUnit(<span>℉</span>)) // changes unit of measure symbol
this.props.dispatch(convertData(data)) // converts data to selected unit or both
this.props.dispatch(getAlerts('F')) // Updates alerts temps on unit change
this.props.dispatch(getFiveDay("Imperial"));
} else if(event.target.value === "C" && (!(typeof(this.props.currentTemp)==="string"))){
// change units to Celcius
this.props.dispatch(changeUnit(<span>℃</span>))
this.props.dispatch(convertData(data))
this.props.dispatch(getAlerts('C'))
this.props.dispatch(getFiveDay("Metric"));
} else if(event.target.value === "Both"){
// Changes to both units
this.props.dispatch(changeUnit(<span>℉/℃</span>))
this.props.dispatch(convertData(data))
this.props.dispatch(getAlerts('Both'))
} else {
switch(event.target.value){
case 'F':
this.props.dispatch(getCurrentData("Imperial"));
this.props.dispatch(changeUnit(<span>℉</span>))
this.props.dispatch(getAlerts('F'))
return
case 'C':
this.props.dispatch(getCurrentData("Metric"));
this.props.dispatch(changeUnit(<span>℃</span>))
this.props.dispatch(getAlerts('C'))
return
}
}
}
render() {
var currentTemp;
var currentHumidity;
var currentHi;
var currentLow;
if(!this.props.currentTemp && this.props.currentTemp===undefined){
currentTemp = "Wait..."
} else if(typeof(this.props.currentTemp)===Number){
currentTemp = this.props.currentTemp.toString();
currentHumidity = this.props.currentHumidity.toString();
currentHi = this.props.currentHi.toString();
currentLow = this.props.currentLow.toString();
} else {
currentTemp = this.props.currentTemp;
currentHumidity = this.props.currentHumidity;
currentHi = this.props.currentHi;
currentLow = this.props.currentLow
}
return (
<div className="current-container">
<div className="current-weather">
<div className="current-temp">{currentTemp}<span className="current-symb">{this.props.unit}</span></div>
<div className="current-range">
<span className="current-hi">hi: {currentHi}°/</span><span>lo: {currentLow}°</span>
</div>
<div className="current-humidity">hum: {currentHumidity}%</div>
</div>
<select value={this.state.value} onChange={this.handleChange}>
<option value="F">F°</option>
<option value="C">C°</option>
<option value="Both">F°/C°</option>
</select>
<Pollut co={this.props.co} no={this.props.no}/>
</div>
);
}
}
function mapStateToProps(state, props) {
return {
currentTemp: state.currentTemp.temp,
currentHumidity: state.currentTemp.humidity,
currentHi: state.currentTemp.hi,
currentLow: state.currentTemp.lo,
unit: state.changeUnit.unit,
co: state.getPollut.co,
no: state.getPollut.no
}
}
export default connect(mapStateToProps)(Current)
|
src/components/History.js | Montana-Code-School/LifeCoach | import React from 'react';
import { inject, observer } from 'mobx-react';
import ReactBootstrapSlider from 'react-bootstrap-slider';
import dateFormat from 'dateformat';
class History extends React.Component{
constructor() {
super();
this.changeHistoryIndex = this.changeHistoryIndex.bind(this);
this.setTicksArr = this.setTicksArr.bind(this);
}
componentDidMount(){
this.props.wheelStore.loadHistoryCanvas();
}
changeHistoryIndex(e){
this.props.wheelStore.historyIndex = e.target.value - 1;
this.props.wheelStore.loadHistoryCanvas();
}
setTicksArr(){
this.props.wheelStore.loadHistoryCanvas();
let ticksArr = [];
for (let i=1; i <= this.props.wheelStore.wheels.length; i++) {
ticksArr.push(i);
}
return ticksArr;
}
render(){
if(this.props.wheelStore.wheels.length > 0){
let wheelArray = this.props.wheelStore.wheels;
let index = this.props.wheelStore.historyIndex;
let ticksArr = this.setTicksArr();
return (
<div className="container">
<h2 className="jumbotronHeader2">History</h2>
<div style={{display:'flex', justifyContent:'space-around', alignItems:'center', marginTop:'2vh'}}>
<div style={{border:'1px solid black', borderRadius:'15px', background:'#ededed', padding:'15px'}}>
<div className="canvasCenter">
<h3 className="subheader">
{dateFormat(wheelArray[index].date,
"dddd, mmmm dS, yyyy")}
</h3>
<canvas id="Canvas1" width="500" height="500">Your browser does not support canvas.</canvas>
</div>
<div className="history-slider">
<h2 className="bodyText">Your History</h2>
<ReactBootstrapSlider
value={index + 1}
change={this.changeHistoryIndex}
step={this.props.wheelStore.step}
max={wheelArray.length}
min={this.props.wheelStore.min}
ticks = {ticksArr}
orientation="horizontal"/>
</div>
</div>
</div>
</div>
);
}
else {
return (
<div className="parentHist">
<div className="container">
<h1 className="jumbotronHeader2">History</h1>
<div className="subheader3">Head over to the Wheel Of Life page to begin your self-assessment! </div>
</div>
</div>
);
}
}
}
History.propTypes = {
wheelStore: React.PropTypes.object
};
export default inject('wheelStore')(observer(History));
|
test/regressions/tests/List/SimpleListItem.js | dsslimshaddy/material-ui | // @flow
import React from 'react';
import { ListItem, ListItemText } from 'material-ui/List';
export default function SimpleListItem() {
return (
<div style={{ background: '#fff', width: 300 }}>
<ListItem>
<ListItemText primary="Primary" />
</ListItem>
<ListItem>
<ListItemText primary="Primary" secondary="Secondary" />
</ListItem>
<ListItem dense>
<ListItemText primary="Primary" />
</ListItem>
<ListItem dense>
<ListItemText primary="Primary" secondary="Secondary" />
</ListItem>
</div>
);
}
|
Realization/frontend/czechidm-core/src/content/modals/Profile.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import classnames from 'classnames';
import Joi from 'joi';
import _ from 'lodash';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Utils from '../../utils';
import {
ProfileManager,
IdentityManager,
DataManager,
SecurityManager,
ConfigurationManager,
NotificationConfigurationManager
} from '../../redux';
import { LocalizationService } from '../../services';
import TwoFactorAuthenticationTypeEnum from '../../enums/TwoFactorAuthenticationTypeEnum';
const identityManager = new IdentityManager();
const profileManager = new ProfileManager();
const securityManager = new SecurityManager();
const notificationConfigurationManager = new NotificationConfigurationManager();
/**
* Flag icon in enum select box.
*
* @author Radek Tomiška
* @since 10.2.0
*/
class FlagOptionDecorator extends Basic.SelectBox.OptionDecorator {
renderIcon(entity) {
const lgnClassName = classnames(
'flag',
entity.value
);
//
return (
<span className={ lgnClassName } style={{ marginRight: 7 }}/>
);
}
}
/**
* Flag icon in enum select box.
*
* @author Radek Tomiška
* @since 10.2.0
*/
class FlagValueDecorator extends Basic.SelectBox.ValueDecorator {
renderIcon(entity) {
const lgnClassName = classnames(
'flag',
entity.value
);
//
return (
<span className={ lgnClassName } style={{ marginRight: 7 }}/>
);
}
}
/**
* Identity profile - modal dialog.
*
* @author Radek Tomiška
* @since 10.2.0
*/
class Profile extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.state = {
showTwoFactorConfirm: null,
twoFactorRegistration: null
};
}
componentDidMount() {
super.componentDidMount();
//
this.context.store.dispatch(notificationConfigurationManager.fetchSupportedNotificationTypes());
}
_getIdentityIdentifier() {
const { profile, userContext } = this.props;
//
if (profile._embedded && profile._embedded.identity) {
return profile._embedded.identity.username;
}
if (!profile.identity) {
// profile is not created yet => new will be created by logged identity
return userContext.username;
}
return profile.identity;
}
onSave(entity = {}, event) {
if (event) {
event.preventDefault();
}
if (!this.refs.form.isFormValid()) {
return;
}
const json = { ...this.refs.form.getData(), ...entity };
//
if (Utils.Entity.isNew(json)) {
json.identity = this.props.userContext.id;
this.context.store.dispatch(profileManager.createEntity(json, null, (createdEntity, error) => {
this._afterSave(createdEntity, error);
}));
} else {
this.context.store.dispatch(profileManager.patchEntity(json, null, (patchedEntity, error) => {
this._afterSave(patchedEntity, error);
}));
}
}
_afterSave(profile, error) {
if (error) {
this.addError(error);
return;
}
//
// if updated profile is logged identity profile => dispach changes
this.context.store.dispatch(securityManager.setCurrentProfile(profile));
this.addMessage({ level: 'success', key: 'core-profile-save-success', message: this.i18n('message.success.update') });
// new profile can be created => nee need to set id into form
this.refs.form.setData(profile);
}
onChangeTwoFactorAuthenticationType(option) {
const json = this.refs.form.getData();
//
if (!option) {
if (json.twoFactorAuthenticationType) {
this.refs['confirm-delete-two-factor'].show(
this.i18n(`content.identity.profile.twoFactor.confirmDelete.message`),
this.i18n(`content.identity.profile.twoFactor.confirmDelete.title`)
).then(() => {
this.onSave({ twoFactorAuthenticationType: null });
}, () => {
// Rejected
});
}
} else if (option.value === json.twoFactorAuthenticationType) {
return false;
} else if (Utils.Entity.isNew(json)) {
json.identity = this.props.userContext.id;
this.context.store.dispatch(profileManager.createEntity(json, null, (createdEntity, error) => {
if (error) {
this.addError(error);
return;
}
this.context.store.dispatch(securityManager.setCurrentProfile(createdEntity));
this.refs.form.setData(createdEntity);
this._showTwoFactorAuthenticationConfirm(createdEntity, option.value);
}));
} else {
this._showTwoFactorAuthenticationConfirm(json, option.value);
}
//
return false;
}
_showTwoFactorAuthenticationConfirm(profile, twoFactorAuthenticationType) {
switch (twoFactorAuthenticationType) {
case 'APPLICATION':
case 'NOTIFICATION': {
this.context.store.dispatch(profileManager.twoFactorAuthenticationInit(
profile.id,
twoFactorAuthenticationType,
(twoFactorRegistration, error) => {
if (error) {
this.addError(error);
return;
}
this.setState({
showTwoFactorConfirm: twoFactorAuthenticationType,
twoFactorRegistration,
profile
}, () => {
if (this.refs.verificationCode) {
this.refs.verificationCode.focus();
}
});
}
));
break;
}
default: {
this.onSave({ twoFactorAuthenticationType });
}
}
}
onTwoFactorConfirm(twoFactorAuthenticationType, event) {
if (event) {
event.preventDefault();
}
if (!this.refs.form.isFormValid()) {
return;
}
const json = this.refs.form.getData();
this.context.store.dispatch(profileManager.twoFactorAuthenticationConfirm(
json.id,
{
verificationSecret: this.state.twoFactorRegistration.verificationSecret,
verificationCode: json.verificationCode,
twoFactorAuthenticationType
},
(updatedProfile, error) => {
if (error) {
this.addError(error);
return;
}
this.setState({
showTwoFactorConfirm: null,
twoFactorRegistration: null,
profile: null
}, () => {
this.context.store.dispatch(securityManager.setCurrentProfile(updatedProfile));
this.addMessage({ level: 'success', key: 'core-profile-save-success', message: this.i18n('message.success.update') });
this.refs.form.setData(updatedProfile);
});
}
));
}
_supportedLanguageOptions() {
const supportedLanguages = LocalizationService.getSupportedLanguages();
//
if (!supportedLanguages || supportedLanguages.length === 0) {
return [];
}
//
return supportedLanguages.map(lng => {
return {
value: lng,
niceLabel: lng
};
});
}
/**
* Dropzone component function called after select file
* @param file selected file (multiple is not allowed)
*/
_onDrop(files) {
if (this.refs.dropzone.state.isDragReject) {
this.addMessage({
message: this.i18n('content.identity.profile.fileRejected'),
level: 'warning'
});
return;
}
files.forEach((file) => {
const fileName = file.name.toLowerCase();
if (!fileName.endsWith('.jpg') && !fileName.endsWith('.jpeg') && !fileName.endsWith('.png') && !fileName.endsWith('.gif')) {
this.addMessage({
message: this.i18n('content.identity.profile.fileRejected', {name: file.name}),
level: 'warning'
});
return;
}
const objectURL = URL.createObjectURL(file);
this.setState({
cropperSrc: objectURL,
showCropper: true,
fileName: file.name
});
});
}
deleteImage() {
this.refs['confirm-delete'].show(
this.i18n(`content.identity.profile.deleteImage.message`),
this.i18n(`content.identity.profile.deleteImage.title`)
).then(() => {
this.context.store.dispatch(identityManager.deleteProfileImage(this._getIdentityIdentifier()));
}, () => {
// Rejected
});
}
_showCropper() {
this.setState({
showCropper: true
});
}
_closeCropper() {
this.setState({
showCropper: false
});
}
_crop() {
this.refs.cropper.crop((formData) => {
// append selected fileName
formData.fileName = this.state.fileName;
formData.name = this.state.fileName;
formData.append('fileName', this.state.fileName);
//
this.context.store.dispatch(identityManager.uploadProfileImage(this._getIdentityIdentifier(), formData, (profile, error) => {
if (error) {
this.addError(error);
return;
}
// new profile can be created => wee need to set id into form
this.refs.form.setData(profile);
}));
});
this._closeCropper();
}
render() {
const {
rendered,
show,
onHide,
showLoading,
profile,
_permissions,
userContext,
sizeOptions,
_imageUrl,
_imageLoading,
_supportedNotificationTypes
} = this.props;
const {
showCropper,
cropperSrc,
showTwoFactorConfirm,
twoFactorRegistration
} = this.state;
//
if (!rendered) {
return null;
}
//
const supportedLanguageOptions = this._supportedLanguageOptions();
// disable notification method, if sms gateway is not configured
const supportTwoFactorNotificationAuthenticationType = _.includes(_supportedNotificationTypes, 'sms') || this.isDevelopment();
//
return (
<Basic.Div>
<Basic.Confirm ref="confirm-delete" level="danger"/>
<Basic.Confirm ref="confirm-delete-two-factor" level="warning"/>
<Basic.Modal
show={ show }
onHide={ onHide }
keyboard
backdrop="static"
bsSize="sm"
fullWidth={ false }
onEnter={ () => this.context.store.dispatch(identityManager.fetchProfile(userContext.username)) }>
<Basic.Modal.Header
closeButton
icon="user"
text={
showTwoFactorConfirm
?
this.i18n('entity.Profile.twoFactorAuthenticationType.label')
:
this.i18n('content.identity.profile-setting.header')
}/>
<Basic.Modal.Body>
<form onSubmit={ showTwoFactorConfirm ? this.onTwoFactorConfirm.bind(this, showTwoFactorConfirm) : this.onSave.bind(this) }>
<Basic.AbstractForm
ref="form"
data={ profile }
readOnly={ !profileManager.canSave(profile, _permissions) }
showLoading={ showLoading }>
<div className={ showTwoFactorConfirm ? 'hidden' : '' }>
<div style={{ marginTop: 5, marginBottom: 20 }}>
<div className="profile-image-wrapper">
<Basic.Div style={{ marginBottom: 15, fontWeight: 700 }}>
{ this.i18n('entity.Profile.image.label') }
</Basic.Div>
<Advanced.ImageDropzone
ref="dropzone"
accept="image/*"
multiple={ false }
onDrop={ this._onDrop.bind(this) }
showLoading={ _imageLoading }
readOnly={ !profileManager.canSave(profile, _permissions) }>
<img className="img-thumbnail" alt="profile" src={ _imageUrl } />
</Advanced.ImageDropzone>
<Basic.Fab color="inherit" className={ cropperSrc && _imageUrl ? 'btn-edit' : 'hidden' } size="small">
<Basic.Button
type="button"
buttonSize="xs"
rendered={ !!(cropperSrc && _imageUrl) }
titlePlacement="right"
onClick={ this._showCropper.bind(this) }
icon="edit"/>
</Basic.Fab>
<Basic.Fab
level="danger"
className={ _imageUrl && profileManager.canSave(profile, _permissions) ? 'btn-remove' : 'hidden' }
size="small">
<Basic.Button
type="button"
level="danger"
buttonSize="xs"
style={{ color: 'white' }}
rendered={ !!(_imageUrl && profileManager.canSave(profile, _permissions)) }
titlePlacement="left"
onClick={ this.deleteImage.bind(this) }
icon="fa:trash"/>
</Basic.Fab>
</div>
</div>
<Basic.EnumSelectBox
ref="preferredLanguage"
label={ this.i18n('entity.Profile.preferredLanguage.label') }
helpBlock={ this.i18n('entity.Profile.preferredLanguage.help') }
hidden={ supportedLanguageOptions.length === 0 }
options={ supportedLanguageOptions }
clearable={ false }
emptyOptionLabel={ false }
optionComponent={ FlagOptionDecorator }
valueComponent={ FlagValueDecorator }
onChange={ (option) => this.onSave({ preferredLanguage: option.value }) }/>
<Basic.EnumSelectBox
ref="twoFactorAuthenticationType"
label={ this.i18n('entity.Profile.twoFactorAuthenticationType.label') }
helpBlock={ this.i18n('entity.Profile.twoFactorAuthenticationType.help') }
options={[
{
niceLabel: TwoFactorAuthenticationTypeEnum.getNiceLabel(
TwoFactorAuthenticationTypeEnum.findKeyBySymbol(TwoFactorAuthenticationTypeEnum.APPLICATION)
),
value: TwoFactorAuthenticationTypeEnum.findKeyBySymbol(TwoFactorAuthenticationTypeEnum.APPLICATION),
description: this.i18n('core:enums.TwoFactorAuthenticationTypeEnum.helpBlock.APPLICATION')
},
{
niceLabel: TwoFactorAuthenticationTypeEnum.getNiceLabel(
TwoFactorAuthenticationTypeEnum.findKeyBySymbol(TwoFactorAuthenticationTypeEnum.NOTIFICATION)
),
value: TwoFactorAuthenticationTypeEnum.findKeyBySymbol(TwoFactorAuthenticationTypeEnum.NOTIFICATION),
disabled: !supportTwoFactorNotificationAuthenticationType,
description:
supportTwoFactorNotificationAuthenticationType
?
this.i18n('core:enums.TwoFactorAuthenticationTypeEnum.helpBlock.NOTIFICATION')
:
this.i18n('content.identity.profile.twoFactor.notification.disabled')
},
]}
useSymbol={ false }
onChange={ this.onChangeTwoFactorAuthenticationType.bind(this) }/>
<Basic.EnumSelectBox
ref="defaultPageSize"
label={ this.i18n('entity.Profile.defaultPageSize.label') }
helpBlock={ this.i18n('entity.Profile.defaultPageSize.help') }
options={
sizeOptions.map(option => {
return {
value: option,
niceLabel: option
};
})
}
onChange={ (option) => this.onSave({ defaultPageSize: option ? option.value : null }) }/>
<Basic.Checkbox
ref="navigationCollapsed"
label={ this.i18n('entity.Profile.navigationCollapsed.label') }
helpBlock={ this.i18n('entity.Profile.navigationCollapsed.help') }
onChange={ (event) => this.onSave({ navigationCollapsed: event.currentTarget.checked }) }/>
<Basic.Checkbox
ref="systemInformation"
label={ this.i18n('entity.Profile.systemInformation.label') }
helpBlock={ this.i18n('entity.Profile.systemInformation.help') }
onChange={ (event) => this.onSave({ systemInformation: event.currentTarget.checked }) }/>
</div>
<div className={ showTwoFactorConfirm ? '' : 'hidden' }>
<Basic.Div className="text-center" rendered={ showTwoFactorConfirm === 'APPLICATION' }>
<Basic.Alert level="info">
{ this.i18n('content.identity.profile.twoFactor.application.help', { escape: false }) }
</Basic.Alert>
{
!twoFactorRegistration
||
<img src={ twoFactorRegistration.qrcode } alt="qr-code"/>
}
<br />
<p>
{ this.i18n('content.identity.profile.twoFactor.application.code.enter') }
<Basic.Popover
trigger={ ['click'] }
className="abstract-entity-info-popover"
value={ (<strong>{ twoFactorRegistration ? twoFactorRegistration.verificationSecret : '' }</strong>) }>
<span style={{ color: '#31708f', margin: '0px 5px', cursor: 'pointer' }}>
{ this.i18n('content.identity.profile.twoFactor.application.code.code') }
</span>
</Basic.Popover>
{ this.i18n('content.identity.profile.twoFactor.application.code.instead') }
</p>
<br />
<br />
</Basic.Div>
<Basic.Alert level="info" rendered={ showTwoFactorConfirm === 'NOTIFICATION' }>
{ this.i18n('content.identity.profile.twoFactor.notification.help', { escape: false }) }
</Basic.Alert>
<Basic.TextField
ref="verificationCode"
label={
showTwoFactorConfirm === 'APPLICATION'
?
this.i18n('content.identity.profile.twoFactor.application.verificationCode.label')
:
this.i18n('content.identity.profile.twoFactor.notification.verificationCode.label')
}
placeholder={
showTwoFactorConfirm === 'APPLICATION'
?
this.i18n('content.identity.profile.twoFactor.application.verificationCode.placeholder')
:
this.i18n('content.identity.profile.twoFactor.notification.verificationCode.placeholder')
}
helpBlock={
showTwoFactorConfirm === 'APPLICATION'
?
this.i18n('content.identity.profile.twoFactor.application.verificationCode.help')
:
this.i18n('content.identity.profile.twoFactor.notification.verificationCode.help')
}
required={ showTwoFactorConfirm !== null }
validation={
showTwoFactorConfirm !== null
?
Joi
.number()
.integer()
.required()
.min(0)
.max(999999)
:
Joi.any().allow(null)
}/>
</div>
</Basic.AbstractForm>
{/* onEnter action - is needed because footer submit button is outside form */}
<input type="submit" className="hidden"/>
</form>
</Basic.Modal.Body>
<Basic.Modal.Footer>
<Basic.Button
level="link"
showLoading={ showLoading }
onClick={ onHide }
rendered={ !showTwoFactorConfirm }>
{ this.i18n('button.close') }
</Basic.Button>
<Basic.Button
level="link"
showLoading={ showLoading }
onClick={ () => this.setState({ showTwoFactorConfirm: null }, () => this.refs.verificationCode.setValue('')) }
rendered={ showTwoFactorConfirm }>
{ this.i18n('button.cancel') }
</Basic.Button>
<Basic.Button
type="submit"
level="success"
showLoading={ showLoading }
onClick={ this.onTwoFactorConfirm.bind(this, showTwoFactorConfirm) }
rendered={ showTwoFactorConfirm }>
{ this.i18n('button.enable.label') }
</Basic.Button>
</Basic.Modal.Footer>
</Basic.Modal>
<Basic.Modal
bsSize="default"
show={ showCropper }
onHide={ this._closeCropper.bind(this) }
backdrop="static" >
<Basic.Modal.Body>
<Advanced.ImageCropper
ref="cropper"
src={ cropperSrc }/>
</Basic.Modal.Body>
<Basic.Modal.Footer>
<Basic.Button
level="link"
onClick={ this._closeCropper.bind(this) }
showLoading={ showLoading }>
{ this.i18n('button.close') }
</Basic.Button>
<Basic.Button
level="info"
onClick={ this._crop.bind(this) }
showLoading={ showLoading }>
{ this.i18n('button.crop') }
</Basic.Button>
</Basic.Modal.Footer>
</Basic.Modal>
</Basic.Div>
);
}
}
Profile.propTypes = {
...Basic.AbstractContent.propTypes,
/**
* Modal is shown.
*/
show: PropTypes.bool,
/**
* onHide callback
*/
onHide: PropTypes.func
};
Profile.defaultProps = {
...Basic.AbstractContent.defaultProps
};
function select(state) {
const identifier = state.security.userContext.username;
const profileUiKey = identityManager.resolveProfileUiKey(identifier);
const profile = DataManager.getData(state, profileUiKey);
//
return {
userContext: state.security.userContext,
profile,
showLoading: DataManager.isShowLoading(state, profileUiKey)
|| (profile ? profileManager.isShowLoading(state, null, profile.id) : false),
_permissions: profile ? profileManager.getPermissions(state, null, profile.id) : [],
sizeOptions: ConfigurationManager.getSizeOptions(state),
_imageLoading: DataManager.isShowLoading(state, profileUiKey),
_imageUrl: profile ? profile.imageUrl : null,
_supportedNotificationTypes: DataManager.getData(state, NotificationConfigurationManager.SUPPORTED_NOTIFICATION_TYPES)
};
}
export default connect(select)(Profile);
|
src/svg-icons/hardware/keyboard-arrow-down.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardArrowDown = (props) => (
<SvgIcon {...props}>
<path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z"/>
</SvgIcon>
);
HardwareKeyboardArrowDown = pure(HardwareKeyboardArrowDown);
HardwareKeyboardArrowDown.displayName = 'HardwareKeyboardArrowDown';
HardwareKeyboardArrowDown.muiName = 'SvgIcon';
export default HardwareKeyboardArrowDown;
|
packages/mineral-ui-icons/src/IconPieChartOutlined.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconPieChartOutlined(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm1 2.07c3.61.45 6.48 3.33 6.93 6.93H13V4.07zM4 12c0-4.06 3.07-7.44 7-7.93v15.87c-3.93-.5-7-3.88-7-7.94zm9 7.93V13h6.93A8.002 8.002 0 0 1 13 19.93z"/>
</g>
</Icon>
);
}
IconPieChartOutlined.displayName = 'IconPieChartOutlined';
IconPieChartOutlined.category = 'editor';
|
imports/client/ui/pages/Admin/AdminTable/Roles.js | focallocal/fl-maps | import React from 'react';
import { parseData } from './helper'
import RoleSelect from './../RoleSelect/index.js'
const Roles = ({ user, changeUserRole }) => {
const roles = parseData('role', user);
const UserName = parseData('user', user);
return (
<RoleSelect rolesData={roles} UserName={UserName} user={user} changeUserRole={changeUserRole} />
)
}
export default Roles;
|
src/applications/static-pages/facilities/createFacilityMapSatelliteMainOffice.js | department-of-veterans-affairs/vets-website | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { fetchMainSatelliteLocationFacility } from './actions';
import widgetTypes from '../widgetTypes';
export default async function createFacilityMapSatelliteMainOffice(store) {
let facilityID = '';
const mapWidget = document.querySelector(
`[data-widget-type="${widgetTypes.FACILITY_MAP_SATELLITE_MAIN_OFFICE}"]`,
);
if (mapWidget && !facilityID) {
facilityID = mapWidget.dataset.facility;
}
if (facilityID) {
store.dispatch(fetchMainSatelliteLocationFacility(facilityID));
if (mapWidget) {
const {
default: FacilityMapSatelliteMainWidget,
} = await import(/* webpackChunkName: "facility-detail" */ './FacilityMapSatelliteMainWidget');
ReactDOM.render(
<Provider store={store}>
<FacilityMapSatelliteMainWidget facilityID={facilityID} />
</Provider>,
mapWidget,
);
}
}
}
|
packages/component/src/ConnectivityStatus/Connected.js | billba/botchat | import { hooks } from 'botframework-webchat-api';
import React from 'react';
import ScreenReaderText from '../ScreenReaderText';
const { useLocalizer } = hooks;
const ConnectivityStatusConnected = () => {
const localize = useLocalizer();
return <ScreenReaderText text={localize('CONNECTIVITY_STATUS_ALT', localize('CONNECTIVITY_STATUS_ALT_CONNECTED'))} />;
};
export default ConnectivityStatusConnected;
|
fields/explorer/components/FieldType.js | dvdcastro/keystone | import React from 'react';
import Markdown from 'react-markdown';
import Col from './Col';
import Row from './Row';
import FieldSpec from './FieldSpec';
const ExplorerFieldType = React.createClass({
getInitialState () {
return {
readmeIsVisible: !!this.props.readme,
filter: this.props.FilterComponent.getDefaultValue(),
value: this.props.value,
};
},
componentWillReceiveProps (newProps) {
if (this.props.params.type === newProps.params.type) return;
this.setState({
filter: newProps.FilterComponent.getDefaultValue(),
readmeIsVisible: newProps.readme
? this.state.readmeIsVisible
: false,
value: newProps.value,
});
},
onFieldChange (e) {
var logValue = typeof e.value === 'string' ? `"${e.value}"` : e.value;
console.log(`${this.props.params.type} field value changed:`, logValue);
this.setState({
value: e.value,
});
},
onFilterChange (value) {
console.log(`${this.props.params.type} filter value changed:`, value);
this.setState({
filter: value,
});
},
toggleReadme () {
this.setState({ readmeIsVisible: !this.state.readmeIsVisible });
},
render () {
const { FieldComponent, FilterComponent, readme, toggleSidebar } = this.props;
const { readmeIsVisible } = this.state;
const specs = Array.isArray(this.props.spec) ? this.props.spec : [this.props.spec];
return (
<div className="fx-page">
<div className="fx-page__header">
<div className="fx-page__header__title">
<button
className="fx-page__header__button fx-page__header__button--sidebar mega-octicon octicon-three-bars"
onClick={toggleSidebar}
type="button"
/>
{FieldComponent.type}
</div>
{!!readme && (
<button
className="fx-page__header__button fx-page__header__button--readme mega-octicon octicon-file-text"
onClick={this.toggleReadme}
title={readmeIsVisible ? 'Hide Readme' : 'Show Readme'}
type="button"
/>
)}
</div>
<div className="fx-page__content">
<Row>
<Col>
<div className="fx-page__content__inner">
{specs.map((spec, i) => (
<FieldSpec
key={spec.path}
i={i}
FieldComponent={FieldComponent}
FilterComponent={FilterComponent}
spec={spec}
readmeIsVisible={readmeIsVisible}
/>
))}
</div>
</Col>
{!!readmeIsVisible && (
<Col width={380}>
<Markdown
className="Markdown"
source={readme}
/>
</Col>
)}
</Row>
</div>
</div>
);
},
});
module.exports = ExplorerFieldType;
|
main.ios.js | tedsf/tiptap | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
Image,
ScrollView,
AlertIOS,
Modal,
AsyncStorage,
DeviceEventEmitter,
} from 'react-native';
import { Button } from 'native-base';
import NavigationBar from 'react-native-navbar';
import Beacons from 'react-native-ibeacon';
var region = {
identifier: 'TipTap',
uuid: 'c617d2c3-25a7-45d3-96c5-51a9e3731862'
};
Beacons.requestWhenInUseAuthorization();
Beacons.startMonitoringForRegion(region);
Beacons.startRangingBeaconsInRegion(region);
Beacons.startUpdatingLocation();
class TipMaker extends Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false,
}
}
onTip(num) {
// TODO: This function should be called upon confirmation of a successful payment. It is currently called too soon.
fetch("https://tiptap-api.herokuapp.com/tips", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}, body: JSON.stringify({tip: {amount: num, tippee_id: this.props.tippeeId, processed: true}})})
.then((response) => response.json())
.done();
}
render(){
return (
<View>
<Modal
animationType={ 'slide' }
transparent={ true }
visible={(this.state.modalVisible)}>
<View
style={{
flex: 1,
backgroundColor: '#f5fcff',
alignItems: 'center',
justifyContent: 'center',
padding: 20,
}}>
<TouchableHighlight onPress={
() => {
this.setState({modalVisible: false});
(AlertIOS.alert(
"Thanks for your tip!",
"-Team TipTap"
));
}}>
<Image
source={{uri:'https://developer.apple.com/library/safari/documentation/UserExperience/Conceptual/MobileHIG/Art/apple_pay_payment_sheet_2x.png'}}
style={{width: 315, height:385 }}
/>
</TouchableHighlight>
</View>
</Modal>
<Button success block onPress={() => {
this.setState({modalVisible: true})
this.onTip(1)
}}>
$1
</Button>
<Button success block onPress={() => {
this.setState({modalVisible: true})
this.onTip(5)
}}>
$5
</Button>
<Button success block onPress={() => {
this.setState({modalVisible: true})
this.onTip(10)
}}>
$10
</Button>
</View>
);
}
}
class Tippee extends Component {
render(){
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{this.props.firstName} {this.props.lastName}
</Text>
<Image
style={{
width: 300 ,
height: 200 ,
}}
resizeMode={ "contain" }
source={{uri:this.props.photoUrl}}
/>
</View>
);
}
}
class TipableTippee extends Component {
render(){
return (
<ScrollView>
<Tippee
firstName={ this.props.firstName }
lastName={ this.props.lastName }
photoUrl={ this.props.photoUrl }
/>
<Text>{'\n'}</Text>
{(this.props.tippeeId) ? (
<TipMaker
tippeeId={ this.props.tippeeId }
paymentUrl={ this.props.paymentUrl }
/>
): null }
<Text>{'\n'}{'\n'}</Text>
</ScrollView>
);
}
}
class NearestTipableTippee extends Component {
constructor(props) {
super(props);
this.state = {
tippeeId: '',
firstName: '',
lastName: '',
photoUrl: '',
paymentUrl: '',
}
}
componentDidMount () {
DeviceEventEmitter.addListener(
'beaconsDidRange',
(data) => {
if (data.beacons[0]) {
// TODO: This app is currently hard coded to support the first beacon in the beacons array only.
// TODO: This fetch presumes that minor value of the first beacon = the relevant tippee_id, which will break if any tippee has more than one beacon or the tippee_id is greater than 2 bytes. This fetch should more explicitly request the tippee data associated with the beacon based on its major and minor values.
fetch("https://tiptap-api.herokuapp.com/tippees/" + data.beacons[0].minor, {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState({tippeeId: responseData.id})
this.setState({firstName: responseData.first_name})
this.setState({lastName: responseData.last_name})
this.setState({photoUrl: responseData.photo_url})
this.setState({paymentUrl: responseData.payment_url})
})
.done()
}
else {
this.setState({tippeeId: ''})
this.setState({firstName: 'No users are in your area'})
this.setState({lastName: ''})
this.setState({photoUrl: 'http://i.imgur.com/CGB5Uv9.png'})
this.setState({paymentUrl: ''})
}
}
)
}
render(){
return (
<TipableTippee
tippeeId={ this.state.tippeeId }
firstName={ this.state.firstName }
lastName={ this.state.lastName }
photoUrl={ this.state.photoUrl }
paymentUrl={ this.state.paymentUrl }
/>
);
}
}
class Main extends Component {
constructor(props) {
super(props);
this.state = {
beacons: [],
}
}
componentDidMount() {
AsyncStorage.getItem(
'beacons',
(error, result) => {
this.setState({beacons: JSON.parse(result)})
}
);
}
navigate(routeName) {
this.props.navigator.push({
name: routeName
});
}
render() {
return (
<View>
<NavigationBar
title={{ title: 'TipTap!' , tintColor: 'black' , }}
rightButton={{ title: 'Get Tips', tintColor: 'black', handler: this.navigate.bind(this,
(this.state.beacons && this.state.beacons.length > 0) ? "active" : "registration"
)}}
style={{ backgroundColor: "#D3D3D3" , }}
statusBar={{ tintColor: "white", hideAnimation: 'none' }}
/>
<NearestTipableTippee />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
export default Main
|
actor-apps/app-web/src/app/components/ActivitySection.react.js | zwensoft/actor-platform | import React from 'react';
import classNames from 'classnames';
import { ActivityTypes } from 'constants/ActorAppConstants';
import ActivityStore from 'stores/ActivityStore';
import UserProfile from 'components/activity/UserProfile.react';
import GroupProfile from 'components/activity/GroupProfile.react';
const getStateFromStores = () => {
return {
activity: ActivityStore.getActivity(),
isOpen: ActivityStore.isOpen()
};
};
class ActivitySection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
ActivityStore.removeChangeListener(this.onChange);
}
render() {
const { activity, isOpen } = this.state;
if (activity !== null) {
const activityClassName = classNames('activity', {
'activity--shown': isOpen
});
let activityBody;
switch (activity.type) {
case ActivityTypes.USER_PROFILE:
activityBody = <UserProfile user={activity.user}/>;
break;
case ActivityTypes.GROUP_PROFILE:
activityBody = <GroupProfile group={activity.group}/>;
break;
default:
}
return (
<section className={activityClassName}>
{activityBody}
</section>
);
} else {
return null;
}
}
onChange = () => {
this.setState(getStateFromStores());
};
}
export default ActivitySection;
|
src/svg-icons/places/casino.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesCasino = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.5 18c-.83 0-1.5-.67-1.5-1.5S6.67 15 7.5 15s1.5.67 1.5 1.5S8.33 18 7.5 18zm0-9C6.67 9 6 8.33 6 7.5S6.67 6 7.5 6 9 6.67 9 7.5 8.33 9 7.5 9zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm0-9c-.83 0-1.5-.67-1.5-1.5S15.67 6 16.5 6s1.5.67 1.5 1.5S17.33 9 16.5 9z"/>
</SvgIcon>
);
PlacesCasino = pure(PlacesCasino);
PlacesCasino.displayName = 'PlacesCasino';
PlacesCasino.muiName = 'SvgIcon';
export default PlacesCasino;
|
client/src/components/Profile/deleteProfileModal.js | Darkrender/raptor-ads | import React from 'react';
import { Button, Header, Modal } from 'semantic-ui-react';
const DeleteProfileModal = ({onDeleteClick}) =>
<Modal
trigger={
<Button
className="ui red right floated button"
type="button"
>
Delete Profile
</Button>
}
>
<Header icon="trash outline" content="Delete Profile" />
<Modal.Content>
<p>Are you sure you want to delete your profile?</p>
</Modal.Content>
<Modal.Actions>
<Button>
Cancel
</Button>
<Button
onClick={() => onDeleteClick()}
color="red"
>
Yes, I am sure.
</Button>
</Modal.Actions>
</Modal>;
export default DeleteProfileModal;
|
src/pages/Main/index.js | JSLancerTeam/crystal-dashboard | import React from 'react';
import { Route, Router } from 'react-router-dom';
import { connect } from 'react-redux';
import cx from 'classnames';
import { setMobileNavVisibility } from '../../reducers/Layout';
import { withRouter } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
import SideBar from '../../components/SideBar';
import ThemeOptions from '../../components/ThemeOptions';
import MobileMenu from '../../components/MobileMenu';
/**
* Pages
*/
import Dashboard from '../Dashboard';
import Components from '../Components';
import UserProfile from '../UserProfile';
import MapsPage from '../MapsPage';
import Forms from '../Forms';
import Charts from '../Charts';
import Calendar from '../Calendar';
import Tables from '../Tables';
const Main = ({
mobileNavVisibility,
hideMobileMenu,
history
}) => {
history.listen(() => {
if (mobileNavVisibility === true) {
hideMobileMenu();
}
});
return (
<div className={cx({
'nav-open': mobileNavVisibility === true
})}>
<div className="wrapper">
<div className="close-layer" onClick={hideMobileMenu}></div>
<SideBar />
<div className="main-panel">
<Header />
<Route exact path="/" component={Dashboard} />
<Route path="/components" component={Components} />
<Route path="/profile" component={UserProfile} />
<Route path="/forms" component={Forms} />
<Route path="/tables" component={Tables} />
<Route path="/maps" component={MapsPage} />
<Route path="/charts" component={Charts} />
<Route path="/calendar" component={Calendar} />
<Footer />
</div>
</div>
</div>
)
};
const mapStateToProp = state => ({
mobileNavVisibility: state.Layout.mobileNavVisibility
});
const mapDispatchToProps = (dispatch, ownProps) => ({
hideMobileMenu: () => dispatch(setMobileNavVisibility(false))
});
export default withRouter(connect(mapStateToProp, mapDispatchToProps)(Main)); |
src/components/searchbox/searchbox.js | ebn646/react-moviesearch | import React from 'react'
class SearchBox extends React.Component{
render(){
return(
<h1>Here are your search results.</h1>
)
}
} |
src/scenes/centralHub.js | Andrey11/golfmanager | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Text,
TextInput,
View,
ScrollView,
Image,
InteractionManager,
Picker,
TouchableHighlight,
Modal
} from 'react-native';
import { FriendActionTypes } from '../utilities/const';
import * as RightButtonMapper from '../navigation/rightButtonMapper';
import GiftedSpinner from 'react-native-gifted-spinner';
import Button from '../components/button';
import IconButton from '../components/iconButton';
import TeeBoxParScore from '../components/teeBoxParScore';
import CourseTypePicker from '../components/courseTypePicker';
import Course from './course';
import Settings from './settings';
import Round from './round';
import AddFriend from './friends';
import styles from '../styles/basestyles.js';
export default class centralHub extends Component {
constructor (props) {
super(props);
this.state = {
renderPlaceholderOnly: true
};
this.showSettings = this.showSettings.bind(this);
this.addRound = this.addRound.bind(this);
this.addFriend = this.addFriend.bind(this);
this.addCourse = this.addCourse.bind(this);
}
componentDidMount () {
RightButtonMapper.bindButton(this.props.navigator, this.showSettings);
InteractionManager.runAfterInteractions(() => {
this.setState({renderPlaceholderOnly: false});
});
}
onAddCourse () {
}
onCourseTypePickerChange (index) {
this.setState({courseTypeIndex: index});
}
showSettings () {
// let bgImageSource = require('../images/golf_bg_9.png');
this.props.navigator.push({
component: Settings,
// sceneBackgroundImage: bgImageSource,
passProps: {
navHeaderTitle: '',
leftButton: true,
rightButton: true,
sceneType: 'SETTINGS',
rightButtonName: 'SAVE SETTINGS'
}
});
}
addRound () {
this.props.navigator.push({
component: Round,
passProps: {
navHeaderTitle: '',
leftButton: true,
rightButton: true,
rightButtonName: 'SAVE ROUND',
actionType: FriendActionTypes.ADD_GOLFER_TO_ROUND,
}
});
}
addCourse () {
this.props.navigator.push({
component: Course,
passProps: {
navHeaderTitle: '',
leftButton: true,
rightButton: true,
rightButtonName: 'SAVE COURSE'
}
});
}
addFriend () {
this.props.navigator.push({
component: AddFriend,
passProps: {
navHeaderTitle: 'Add Friend',
leftButton: true,
rightButton: false,
actionType: FriendActionTypes.ADD_NEW_FRIEND,
}
});
}
render () {
if (this.state.renderPlaceholderOnly) {
return this._renderPlaceholderView();
}
return (
<View>
<IconButton
iconSource={require('../images/ic_golf_course.png')}
underlayColor={'rgba(0, 145, 27, 0.8)'}
onButtonPressed={this.addCourse}
touchableHighlightStyle={styles.add_round_button} />
<IconButton
iconSource={require('../images/ic_person.png')}
underlayColor={'rgba(0, 145, 27, 0.8)'}
onButtonPressed={this.addFriend}
touchableHighlightStyle={styles.add_round_button} />
<IconButton
iconSource={require('../images/ic_group_work.png')}
underlayColor={'rgba(0, 145, 27, 0.8)'}
onButtonPressed={this.addRound}
touchableHighlightStyle={styles.add_round_button} />
</View>
);
}
_renderPlaceholderView() {
// TODO: Create a proper loader
return (
<View style={styles.start_page__body}>
<Text style={styles.start_page__text}>Loading</Text>
<GiftedSpinner />
</View>
);
}
}
AppRegistry.registerComponent('centralHub', () => centralHub);
|
index.js | sharmad-nachnolkar/react-component-lib | import React from 'react'
import ReactDOM from 'react-dom'
import MultiSelect from './components/Multiselect/Multiselect.jsx'
import Calendar from './components/Calendar/Calendar.jsx'
/*var msProps = {
dataSource:[
{key:'apple',value:'a'},
{key:'oranges',value:'o'},
{key:'mangoes',value:'m'},
{key:'bananas',value:'b'},
{key:'pears',value:'p'}
],
placeHolder:'Select a fruit...',
labelText: 'Your Fruit',
customClass:'large-width',
multiSelect:false
}
ReactDOM.render(<MultiSelect {...msProps}/>, document.querySelector("#content"))
ReactDOM.render(<Calendar customClass='large-width'/>, document.querySelector("#content2"))
*/
module.exports = {
MultiSelect:MultiSelect,
Calendar:Calendar
} |
client/src/core-components/submit-button.js | opensupports/opensupports | // VENDOR LIBS
import React from 'react';
import _ from 'lodash';
import classNames from 'classnames';
// CORE LIBS
import Button from 'core-components/button';
import Loading from 'core-components/loading';
class SubmitButton extends React.Component {
static contextTypes = {
loading: React.PropTypes.bool
};
static propTypes = {
children: React.PropTypes.node
};
static defaultProps = {
type: 'primary'
};
render() {
return (
<Button {...this.getProps()}>
{(this.context.loading) ? this.renderLoading() : this.props.children}
</Button>
);
}
renderLoading() {
return (
<Loading className="submit-button__loader" />
);
}
getProps() {
return _.extend({}, this.props, {
disabled: this.context.loading,
className: this.getClass()
});
}
getClass() {
let classes = {
'submit-button': true,
'submit-button_loading': this.context.loading
};
classes[this.props.className] = (this.props.className);
return classNames(classes);
}
}
export default SubmitButton;
|
docs/src/theme/DocItem/index.js | kmagiera/react-native-gesture-handler | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 Head from '@docusaurus/Head';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import DocPaginator from '@theme/DocPaginator';
import DocVersionSuggestions from '@theme/DocVersionSuggestions';
import TOC from '@theme/TOC';
import clsx from 'clsx';
import styles from './styles.module.css';
import {
useActivePlugin,
useVersions,
useActiveVersion,
} from '@theme/hooks/useDocs';
function DocItem(props) {
const { siteConfig = {} } = useDocusaurusContext();
const { url: siteUrl, title: siteTitle } = siteConfig;
const { content: DocContent } = props;
const { metadata } = DocContent;
const {
description,
title,
permalink,
editUrl,
lastUpdatedAt,
lastUpdatedBy,
} = metadata;
const {
frontMatter: {
image: metaImage,
keywords,
hide_title: hideTitle,
hide_table_of_contents: hideTableOfContents = true,
},
} = DocContent;
const { pluginId } = useActivePlugin({
failfast: true,
});
const versions = useVersions(pluginId);
const version = useActiveVersion(pluginId); // If site is not versioned or only one version is included
// we don't show the version badge
// See https://github.com/facebook/docusaurus/issues/3362
const showVersionBadge = versions.length > 1;
const metaTitle = title ? `${title} | ${siteTitle}` : siteTitle;
const metaImageUrl = useBaseUrl(metaImage, {
absolute: true,
});
return (
<>
<Head>
<title>{metaTitle}</title>
<meta property="og:title" content={metaTitle} />
{description && <meta name="description" content={description} />}
{description && (
<meta property="og:description" content={description} />
)}
{keywords && keywords.length && (
<meta name="keywords" content={keywords.join(',')} />
)}
{metaImage && <meta property="og:image" content={metaImageUrl} />}
{metaImage && <meta property="twitter:image" content={metaImageUrl} />}
{metaImage && (
<meta name="twitter:image:alt" content={`Image for ${title}`} />
)}
{permalink && <meta property="og:url" content={siteUrl + permalink} />}
{permalink && <link rel="canonical" href={siteUrl + permalink} />}
</Head>
<div
className={clsx('container padding-vert--lg', styles.docItemWrapper)}>
<div className="row">
<div
className={clsx('col', {
[styles.docItemCol]: !hideTableOfContents,
})}>
<DocVersionSuggestions />
<div className={styles.docItemContainer}>
<article>
{showVersionBadge && (
<div>
<span className="badge badge--secondary">
Version: {version.label}
</span>
</div>
)}
{!hideTitle && (
<header>
<h1 className={styles.docTitle}>{title}</h1>
</header>
)}
<div className="markdown">
<DocContent />
</div>
</article>
{/* {(editUrl || lastUpdatedAt || lastUpdatedBy) && (
<div className="margin-vert--xl">
<div className="row">
<div className="col">
{editUrl && (
<a
href={editUrl}
target="_blank"
rel="noreferrer noopener">
<svg
fill="currentColor"
height="1.2em"
width="1.2em"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 40 40"
style={{
marginRight: '0.3em',
verticalAlign: 'sub',
}}>
<g>
<path d="m34.5 11.7l-3 3.1-6.3-6.3 3.1-3q0.5-0.5 1.2-0.5t1.1 0.5l3.9 3.9q0.5 0.4 0.5 1.1t-0.5 1.2z m-29.5 17.1l18.4-18.5 6.3 6.3-18.4 18.4h-6.3v-6.2z" />
</g>
</svg>
Edit this page
</a>
)}
</div>
{(lastUpdatedAt || lastUpdatedBy) && (
<div className="col text--right">
<em>
<small>
Last updated{' '}
{lastUpdatedAt && (
<>
on{' '}
<time
dateTime={new Date(
lastUpdatedAt * 1000
).toISOString()}
className={styles.docLastUpdatedAt}>
{new Date(
lastUpdatedAt * 1000
).toLocaleDateString()}
</time>
{lastUpdatedBy && ' '}
</>
)}
{lastUpdatedBy && (
<>
by <strong>{lastUpdatedBy}</strong>
</>
)}
{process.env.NODE_ENV === 'development' && (
<div>
<small>
{' '}
(Simulated during dev for better perf)
</small>
</div>
)}
</small>
</em>
</div>
)}
</div>
</div>
)} */}
{/* <div className="margin-vert--lg">
<DocPaginator metadata={metadata} />
</div> */}
</div>
</div>
{!hideTableOfContents && DocContent.rightToc && (
<div className="col col--3">
<TOC headings={DocContent.rightToc} />
</div>
)}
</div>
</div>
</>
);
}
export default DocItem;
|
examples/star-wars/js/components/StarWarsShip.js | tmitchel2/relay | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
import Relay from 'react-relay';
class StarWarsShip extends React.Component {
render() {
var {ship} = this.props;
return <div>{ship.name}</div>;
}
}
export default Relay.createContainer(StarWarsShip, {
fragments: {
ship: () => Relay.QL`
fragment on Ship {
name
}
`,
},
});
|
docs/app/Examples/addons/Radio/States/RadioExampleDisabled.js | shengnian/shengnian-ui-react | import React from 'react'
import { Form, Radio } from 'shengnian-ui-react'
const RadioExampleDisabled = () => (
<Form>
<Form.Field>
<Radio label='Disabled' disabled />
</Form.Field>
<Form.Field>
<Radio toggle label='Disabled' disabled />
</Form.Field>
</Form>
)
export default RadioExampleDisabled
|
src/components/topic/snapshots/foci/builder/search/SearchStoryPreviewContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withFilteredAsyncData from '../../../../FilteredAsyncDataContainer';
import withHelp from '../../../../../common/hocs/HelpfulContainer';
import { fetchTopicProviderStories } from '../../../../../../actions/topicActions';
import DataCard from '../../../../../common/DataCard';
import TopicStoryTableContainer from '../../../../TopicStoryTableContainer';
import messages from '../../../../../../resources/messages';
import { FETCH_INVALID } from '../../../../../../lib/fetchConstants';
import { searchValuesToQuery } from './SearchStoryCountPreviewContainer';
const NUM_TO_SHOW = 20;
const localMessages = {
title: { id: 'topic.summary.stories.title', defaultMessage: 'Sample Stories' },
helpTitle: { id: 'topic.summary.stories.help.title', defaultMessage: 'About Matching Top Stories' },
};
const SearchStoryPreviewContainer = (props) => {
const { stories, helpButton } = props;
return (
<DataCard>
<h2>
<FormattedMessage {...localMessages.title} />
{helpButton}
</h2>
<TopicStoryTableContainer stories={stories.slice(0, NUM_TO_SHOW)} />
</DataCard>
);
};
SearchStoryPreviewContainer.propTypes = {
// from the composition chain
intl: PropTypes.object.isRequired,
helpButton: PropTypes.node.isRequired,
// from parent
topicId: PropTypes.number.isRequired,
searchValues: PropTypes.object.isRequired,
// from state
fetchStatus: PropTypes.string.isRequired,
stories: PropTypes.array,
};
const mapStateToProps = state => ({
fetchStatus: state.topics.selected.provider.stories.fetchStatuses.focusBuilder || FETCH_INVALID,
stories: state.topics.selected.provider.stories.results.focusBuilder ? state.topics.selected.provider.stories.results.focusBuilder.stories : {},
});
const fetchAsyncData = (dispatch, { topicId, searchValues, filters }) => dispatch(fetchTopicProviderStories(topicId, {
uid: 'focusBuilder',
// subtopics work at the snapshot level, make sure to search the whole snapshot (not the timespan the user might have selected)
snapshotId: filters.snapshotId,
timespanId: null,
focusId: null,
q: searchValuesToQuery(searchValues),
}));
export default
injectIntl(
connect(mapStateToProps)(
withHelp(localMessages.helpTitle, messages.storiesTableHelpText)(
withFilteredAsyncData(fetchAsyncData, ['searchValues'])(
SearchStoryPreviewContainer
)
)
)
);
|
app/react-icons/fa/magnet.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaMagnet extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m37.3 18.6v2.8q0 4.5-2.2 8.1t-6.1 5.6-8.9 2-8.8-2-6.1-5.6-2.2-8.1v-2.8q0-0.6 0.4-1t1-0.5h8.6q0.6 0 1 0.5t0.4 1v2.8q0 1.2 0.6 2t1.1 1.3 1.6 0.7 1.5 0.3 0.9 0 1 0 1.5-0.3 1.5-0.7 1.2-1.3 0.6-2v-2.8q0-0.6 0.4-1t1-0.5h8.6q0.5 0 1 0.5t0.4 1z m-22.9-14.3v8.6q0 0.5-0.4 1t-1 0.4h-8.6q-0.6 0-1-0.4t-0.4-1v-8.6q0-0.6 0.4-1t1-0.4h8.6q0.6 0 1 0.4t0.4 1z m22.9 0v8.6q0 0.5-0.4 1t-1 0.4h-8.6q-0.6 0-1-0.4t-0.4-1v-8.6q0-0.6 0.4-1t1-0.4h8.6q0.5 0 1 0.4t0.4 1z"/></g>
</IconBase>
);
}
}
|
src/main/resources/static/bower_components/jqwidgets/jqwidgets-react/react_jqxmaskedinput.js | dhawal9035/WebPLP | /*
jQWidgets v4.5.0 (2017-Jan)
Copyright (c) 2011-2017 jQWidgets.
License: http://jqwidgets.com/license/
*/
import React from 'react';
let jqxMaskedInput = React.createClass ({
getInitialState: function () {
return { value: '' };
},
componentDidMount: function () {
let options = this.manageAttributes();
this.createComponent(options);
},
manageAttributes: function () {
let properties = ['disabled','height','mask','promptChar','readOnly','rtl','theme','textAlign','value','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
},
createComponent : function (options) {
if(!this.style) {
for (let style in this.props.style) {
$('#' +this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
$('#' +this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
$('#' +this.componentSelector).html(this.props.template);
}
$('#' +this.componentSelector).jqxMaskedInput(options);
},
generateID : function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
},
setOptions: function (options) {
$('#' +this.componentSelector).jqxMaskedInput('setOptions', options);
},
getOptions: function () {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = $('#' +this.componentSelector).jqxMaskedInput(arguments[i]);
}
return resultToReturn;
},
on: function (name,callbackFn) {
$('#' +this.componentSelector).on(name,callbackFn);
},
off: function (name) {
$('#' +this.componentSelector).off(name);
},
disabled: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("disabled", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("disabled");
}
},
height: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("height", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("height");
}
},
mask: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("mask", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("mask");
}
},
promptChar: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("promptChar", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("promptChar");
}
},
readOnly: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("readOnly", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("readOnly");
}
},
rtl: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("rtl", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("rtl");
}
},
theme: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("theme", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("theme");
}
},
textAlign: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("textAlign", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("textAlign");
}
},
value: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("value", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("value");
}
},
width: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("width", arg)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("width");
}
},
clear: function () {
$("#" +this.componentSelector).jqxMaskedInput("clear");
},
destroy: function () {
$("#" +this.componentSelector).jqxMaskedInput("destroy");
},
focus: function () {
$("#" +this.componentSelector).jqxMaskedInput("focus");
},
val: function (value) {
if (value !== undefined) {
$("#" +this.componentSelector).jqxMaskedInput("val", value)
} else {
return $("#" +this.componentSelector).jqxMaskedInput("val");
}
},
render: function () {
let id = 'jqxMaskedInput' + this.generateID() + this.generateID();
this.componentSelector = id; return (
<div id={id}>{this.value ? null : this.props.value}{this.props.children}</div>
)
}
});
module.exports = jqxMaskedInput;
|
mobile/App/Components/SearchBar.js | JasonQSong/SoulDistance | import React from 'react'
import { Text, TextInput, TouchableOpacity } from 'react-native'
import styles from './Styles/SearchBarStyle'
import I18n from 'react-native-i18n'
import { Colors, Metrics } from '../Themes/'
import * as Animatable from 'react-native-animatable'
import Icon from 'react-native-vector-icons/FontAwesome'
export default class SearchBar extends React.Component {
static propTypes = {
onSearch: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
searchTerm: React.PropTypes.string
}
render () {
const { onSearch, onCancel, searchTerm } = this.props
const onSubmitEditing = () => onSearch(searchTerm)
return (
<Animatable.View animation='slideInRight' duration={250} style={styles.container}>
<Icon name='search' size={Metrics.icons.tiny} style={styles.searchIcon} />
<TextInput
ref='searchText'
autoFocus
placeholder={I18n.t('search')}
placeholderTextColor={Colors.snow}
underlineColorAndroid='transparent'
style={styles.searchInput}
value={this.props.searchTerm}
onChangeText={onSearch}
autoCapitalize='none'
onSubmitEditing={onSubmitEditing}
returnKeyType={'search'}
autoCorrect={false}
selectionColor={Colors.snow}
/>
<TouchableOpacity onPress={onCancel} style={styles.cancelButton}>
<Text style={styles.buttonLabel}>{I18n.t('cancel')}</Text>
</TouchableOpacity>
</Animatable.View>
)
}
}
|
src/components/Layout/Header/Header.js | jumpalottahigh/jumpalottahigh.github.io | import React from 'react'
import { Link } from 'gatsby'
import './Header.css'
import logo from './logo.png'
import github from './github.svg'
import twitter from './twitter.svg'
const activeStyle = {
transform: 'scale(1.054)',
borderBottom: '2px solid #fff',
}
const Header = () => (
<header className="header">
<nav className="brand">
<Link exact="true" to="/">
<img src={logo} alt="Georgi Yanev logo" style={{ height: '40px' }} />
</Link>
</nav>
<nav className="main">
<Link exact="true" to="/" activeStyle={activeStyle}>
Home
</Link>
<Link to="/about/" activeStyle={activeStyle}>
About
</Link>
<a className="blog" href="https://blog.georgi-yanev.com">
Blog
</a>
</nav>
<nav className="social">
<a href="https://github.com/jumpalottahigh">
<img src={github} alt="GitHub logo" />
</a>
<a href="https://twitter.com/jumpalottahigh">
<img src={twitter} alt="Twitter logo" />
</a>
</nav>
</header>
)
export default Header
|
src/templates/manual-template.js | inkdropapp/docs | import React from 'react'
import PropTypes from 'prop-types'
import { graphql, Link } from 'gatsby'
import ManualLayout from '../components/manual-layout'
export default function Template({
data, // this prop will be injected by the GraphQL query below.
pageContext
}) {
const { pageByPath } = data
const { frontmatter, html, tableOfContents } = pageByPath
const { next, prev } = pageContext
return (
<ManualLayout currentPageTitle={frontmatter.title}>
<h1>{frontmatter.title}</h1>
{frontmatter.toc && (
<div
className="toc"
dangerouslySetInnerHTML={{ __html: tableOfContents }}
/>
)}
<div dangerouslySetInnerHTML={{ __html: html }} />
<div className="sibling-page-links">
{prev && (
<Link to={prev.frontmatter.path} className="page-link">
<i className="angle double left icon" /> Prev:{' '}
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={next.frontmatter.path} className="page-link next-page">
Next: {next.frontmatter.title}{' '}
<i className="angle double right icon" />
</Link>
)}
</div>
</ManualLayout>
)
}
Template.propTypes = {
data: PropTypes.object,
pageContext: PropTypes.object
}
export const pageQuery = graphql`
query($path: String!) {
pageByPath: markdownRemark(frontmatter: { path: { eq: $path } }) {
html
tableOfContents(pathToSlugField: "frontmatter.path")
frontmatter {
path
title
toc
}
}
}
`
|
packages/component/src/BasicSendBox.js | billba/botchat | import { Constants } from 'botframework-webchat-core';
import { hooks } from 'botframework-webchat-api';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import DictationInterims from './SendBox/DictationInterims';
import MicrophoneButton from './SendBox/MicrophoneButton';
import SendButton from './SendBox/SendButton';
import SuggestedActions from './SendBox/SuggestedActions';
import TextBox from './SendBox/TextBox';
import UploadButton from './SendBox/UploadButton';
import useStyleSet from './hooks/useStyleSet';
import useStyleToEmotionObject from './hooks/internal/useStyleToEmotionObject';
import useWebSpeechPonyfill from './hooks/useWebSpeechPonyfill';
const {
DictateState: { DICTATING, STARTING }
} = Constants;
const { useActivities, useDirection, useDictateState, useStyleOptions } = hooks;
const ROOT_STYLE = {
'& > .main': {
display: 'flex'
}
};
const DICTATION_INTERIMS_STYLE = { flex: 10000 };
const MICROPHONE_BUTTON_STYLE = { flex: 1 };
const TEXT_BOX_STYLE = { flex: 10000 };
// TODO: [P3] We should consider exposing core/src/definitions and use it instead
function activityIsSpeakingOrQueuedToSpeak({ channelData: { speak } = {} }) {
return !!speak;
}
function useSendBoxSpeechInterimsVisible() {
const [activities] = useActivities();
const [dictateState] = useDictateState();
return [
(dictateState === STARTING || dictateState === DICTATING) &&
!activities.filter(activityIsSpeakingOrQueuedToSpeak).length
];
}
const BasicSendBox = ({ className }) => {
const [{ hideUploadButton }] = useStyleOptions();
const [{ sendBox: sendBoxStyleSet }] = useStyleSet();
const [{ SpeechRecognition } = {}] = useWebSpeechPonyfill();
const [direction] = useDirection();
const [speechInterimsVisible] = useSendBoxSpeechInterimsVisible();
const styleToEmotionObject = useStyleToEmotionObject();
const dictationInterimsClassName = styleToEmotionObject(DICTATION_INTERIMS_STYLE) + '';
const microphoneButtonClassName = styleToEmotionObject(MICROPHONE_BUTTON_STYLE) + '';
const rootClassName = styleToEmotionObject(ROOT_STYLE) + '';
const textBoxClassName = styleToEmotionObject(TEXT_BOX_STYLE) + '';
const supportSpeechRecognition = !!SpeechRecognition;
return (
<div
className={classNames(sendBoxStyleSet + '', rootClassName, (className || '') + '')}
dir={direction}
role="form"
>
<SuggestedActions />
<div className="main">
{!hideUploadButton && <UploadButton />}
{speechInterimsVisible ? (
<DictationInterims className={dictationInterimsClassName} />
) : (
<TextBox className={textBoxClassName} />
)}
<div>
{supportSpeechRecognition ? <MicrophoneButton className={microphoneButtonClassName} /> : <SendButton />}
</div>
</div>
</div>
);
};
BasicSendBox.defaultProps = {
className: ''
};
BasicSendBox.propTypes = {
className: PropTypes.string
};
export default BasicSendBox;
export { useSendBoxSpeechInterimsVisible };
|
frontend/src/components/organizationProfile/profile/organizationProfileHeaderOptions.js | unicef/un-partner-portal | import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import DropdownMenu from '../../common/dropdownMenu';
import PrintButton from '../buttons/printButton';
const OrganizationProfileHeaderOptions = (props) => {
const { params: { id } } = props;
return (
<DropdownMenu
options={
[
{
name: 'print',
content: <PrintButton id={id} />,
},
]
}
/>
);
};
OrganizationProfileHeaderOptions.propTypes = {
params: PropTypes.object,
};
export default withRouter(OrganizationProfileHeaderOptions);
|
src/scripts/components/panel/Panel.component.story.js | kodokojo/kodokojo-ui-commons | /**
* Kodo Kojo - Software factory done right
* Copyright © 2017 Kodo Kojo (infos@kodokojo.io)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import { Provider } from 'react-redux'
import { storiesOf, action } from '@kadira/storybook'
// contexte
import configureStore from '../../store/configureStore'
// component to story
import Panel from './Panel.component'
const initialState = {}
const store = configureStore(initialState)
storiesOf('Panel', module)
.add('default', () => (
<Provider store={store}>
<Panel>
<div>children</div>
</Panel>
</Provider>
))
|
packages/react/src/components/SearchFilterButton/SearchFilterButton.js | carbon-design-system/carbon-components | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Filter16 } from '@carbon/icons-react';
import { settings } from 'carbon-components';
import PropTypes from 'prop-types';
import React from 'react';
import { warning } from '../../internal/warning';
const { prefix } = settings;
let didWarnAboutDeprecation = false;
/**
* The filter button for `<Search>`.
*/
const SearchFilterButton = ({ labelText, iconDescription, ...other }) => {
if (__DEV__) {
warning(
didWarnAboutDeprecation,
'The SearchFilterButton component has been deprecated and will be removed in the next major release of `carbon-components-react`'
);
didWarnAboutDeprecation = true;
}
return (
<button
className={`${prefix}--search-button`}
type="button"
aria-label={labelText}
title={labelText}
{...other}>
<Filter16
className={`${prefix}--search-filter`}
aria-label={iconDescription}
/>
</button>
);
};
SearchFilterButton.propTypes = {
/**
* The icon description.
*/
iconDescription: PropTypes.string,
/**
* The a11y label text.
*/
labelText: PropTypes.string,
};
SearchFilterButton.defaultProps = {
labelText: 'Search',
iconDescription: 'filter',
};
export default SearchFilterButton;
|
src/js/components/About.js | caseypt/ebird-hotspot-viewer | import React from 'react';
export default function About() {
return (
<div>
<p>
This application was developed by Casey Thomas as part of an R+D project at <a href="http://www.azavea.com">Azavea</a>.
</p>
<p>
The source code is available on <a href="https://github.com/caseypt/ebird-hotspot-viewer">Github</a>.
</p>
</div>
);
}
|
imports/ui/components/Sidebar/Sidebar.js | jamiebones/Journal_Publication | import React from 'react';
import { Button , Row , Col , Modal , } from 'react-bootstrap';
import './Sidebar.scss';
class Sidebar extends React.Component {
render() {
return (
<Modal className='Sidebar left'
show={ this.props.isVisible } onHide={this.props.onHide}
autoFocus keyboard
>
<Modal.Header closeButton>
<Modal.Title>Journal Menu</Modal.Title>
</Modal.Header>
<Modal.Body>
{ this.props.children }
</Modal.Body>
</Modal>
);
}
}
export default Sidebar; |
src/components/AboutPage/AboutPage.js | chunkai1312/universal-react-redux-starter-kit | import React from 'react'
import Helmet from 'react-helmet'
const AboutPage = props => {
return (
<div>
<Helmet title="About" />About
</div>
)
}
export default AboutPage
|
projects/chess-part2/viz/src/index.js | ebemunk/blog | import React from 'react'
import ReactDOM from 'react-dom'
import 'react-vis/dist/style.css'
const render = (component, selector) =>
ReactDOM.render(component, document.querySelector(selector))
import GameEndMaterialDiff from './sections/GameEndMaterialDiff'
import GameEndMaterialCount from './sections/GameEndMaterialCount'
import BranchingFactor from './sections/BranchingFactor'
import Ratings from './sections/Ratings'
import Years from './sections/Years'
render(<BranchingFactor />, '#BranchingFactor')
render(<GameEndMaterialDiff />, '#GameEndMaterialDiff')
render(<GameEndMaterialCount />, '#GameEndMaterialCount')
render(<Ratings />, '#Ratings')
render(<Years />, '#Years')
import BoardViz from './components/BoardViz'
import data from './data'
render(
<BoardViz data={data.Heatmaps.MateDeliverySquares} />,
'#MateDeliverySquares',
)
render(<BoardViz data={data.Heatmaps.MateSquares} filter="K" />, '#MateSquares')
render(
<BoardViz data={data.Heatmaps.StalemateSquares} filter="K" />,
'#StalemateSquares',
)
render(
<BoardViz data={data.Heatmaps.EnPassantSquares} filter="P" />,
'#EnPassantSquares',
)
render(
<BoardViz data={data.Heatmaps.PromotionSquares} filter="AllNBRQ" />,
'#PromotionSquares',
)
render(<BoardViz data={data.Heatmaps.FirstBlood} />, '#FirstBlood')
import Scouts from './sections/Scout'
render(<Scouts filter={['Pv', 'PPv', 'PPPv']} />, '#imbaP')
render(<Scouts filter={['Nv', 'Bv', 'Rv', 'Qv']} />, '#imbaPiece')
render(<Scouts filter={['NvP', 'NvPP', 'NvPPP', 'NvPPPP']} />, '#imbaN')
render(<Scouts filter={['BvP', 'BvPP', 'BvPPP', 'BvPPPP']} />, '#imbaB')
render(<Scouts filter={['NvB', 'NvR', 'NvQ', 'BvR', 'BvQ']} />, '#imbaMinor')
render(<Scouts filter={['RvN', 'RvB', 'RvPPP']} />, '#imbaExchange')
render(<Scouts filter={['NBvR', 'NNvR', 'BBvR']} />, '#imba2mr')
render(<Scouts filter={['QvR', 'QvRR']} />, '#imbaMajor')
import PawnPaths from './sections/PawnPaths'
render(<PawnPaths />, '#PawnPaths')
import Positions from './sections/Positions'
render(<Positions />, '#Positions')
|
docs/app/components/layout/home/index.js | sylvesteraswin/react-zvui-framework | import React from 'react';
import { Link } from 'react-router';
const Home = () => (
<article>
Hello world!
</article>
);
export default Home;
|
src/AffixMixin.js | albertojacini/react-bootstrap | import React from 'react';
import domUtils from './utils/domUtils';
import EventListener from './utils/EventListener';
const AffixMixin = {
propTypes: {
offset: React.PropTypes.number,
offsetTop: React.PropTypes.number,
offsetBottom: React.PropTypes.number
},
getInitialState() {
return {
affixClass: 'affix-top'
};
},
getPinnedOffset(DOMNode) {
if (this.pinnedOffset) {
return this.pinnedOffset;
}
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, '');
DOMNode.className += DOMNode.className.length ? ' affix' : 'affix';
this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset;
return this.pinnedOffset;
},
checkPosition() {
let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom,
affix, affixType, affixPositionTop;
// TODO: or not visible
if (!this.isMounted()) {
return;
}
DOMNode = React.findDOMNode(this);
scrollHeight = domUtils.getDocumentHeight();
scrollTop = window.pageYOffset;
position = domUtils.getOffset(DOMNode);
if (this.affixed === 'top') {
position.top += scrollTop;
}
offsetTop = this.props.offsetTop != null ?
this.props.offsetTop : this.props.offset;
offsetBottom = this.props.offsetBottom != null ?
this.props.offsetBottom : this.props.offset;
if (offsetTop == null && offsetBottom == null) {
return;
}
if (offsetTop == null) {
offsetTop = 0;
}
if (offsetBottom == null) {
offsetBottom = 0;
}
if (this.unpin != null && (scrollTop + this.unpin <= position.top)) {
affix = false;
} else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) {
affix = 'bottom';
} else if (offsetTop != null && (scrollTop <= offsetTop)) {
affix = 'top';
} else {
affix = false;
}
if (this.affixed === affix) {
return;
}
if (this.unpin != null) {
DOMNode.style.top = '';
}
affixType = 'affix' + (affix ? '-' + affix : '');
this.affixed = affix;
this.unpin = affix === 'bottom' ?
this.getPinnedOffset(DOMNode) : null;
if (affix === 'bottom') {
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom');
affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top;
}
this.setState({
affixClass: affixType,
affixPositionTop
});
},
checkPositionWithEventLoop() {
setTimeout(this.checkPosition, 0);
},
componentDidMount() {
this._onWindowScrollListener =
EventListener.listen(window, 'scroll', this.checkPosition);
this._onDocumentClickListener =
EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop);
},
componentWillUnmount() {
if (this._onWindowScrollListener) {
this._onWindowScrollListener.remove();
}
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
},
componentDidUpdate(prevProps, prevState) {
if (prevState.affixClass === this.state.affixClass) {
this.checkPositionWithEventLoop();
}
}
};
export default AffixMixin;
|
src/main.js | jeffaustin81/cropcompass-ui | import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import { createStore, applyMiddleware } from 'redux'
import AppContainer from './containers/AppContainer'
import CropCompassReducer from './Reducers/rootReducer'
import thunk from 'redux-thunk';
// ========================================================
// Browser History Setup
// ========================================================
// ========================================================
// Store and History Instantiation
// ========================================================
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
// ========================================================
// Browser History Setup
// ========================================================
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
})
// ========================================================
// Store and History Instantiation
// ========================================================
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
let initialState = {
countyName: {name: "Multnomah", fips: "41051"},
cropName: "Wheat",
cropList: [],
countyList: [],
sortMapBy: "numberOfFarms",
showJournalism: false,
exportsHistory: [],
selectedYear: "2010",
countyData: {subsidies: [], commoditiesByAcre: [], commoditiesByHarvestHistory: [], commoditiesByHarvestThisYear: []},
cropImageName: "hazelnut",
cycleFlag: false,
exportCrop: "",
showSources: false,
top5Exports: [],
diversityList: [],
revenue: [],
showMenus: {cropMenu: false, countyMenu: false},
allPossibleCrops: [],
showHugeCropList: false,
}
let createStoreWithMiddleware = applyMiddleware(thunk)(createStore)
let store = createStoreWithMiddleware(
CropCompassReducer,
initialState,
window.devToolsExtension ? window.devToolsExtension() : f => f
)
// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEBUG__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = (routerKey = null) => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer
store={store}
/>,
MOUNT_NODE
)
}
// Enable HMR and catch runtime errors in RedBox
// This code is excluded from production bundle
if (__DEV__ && module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp(Math.random())
} catch (error) {
renderError(error)
}
}
module.hot.accept(['./routes/index'], () => render())
}
// ========================================================
// Go!
// ========================================================
render()
|
src/svg-icons/maps/ev-station.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsEvStation = (props) => (
<SvgIcon {...props}>
<path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z"/>
</SvgIcon>
);
MapsEvStation = pure(MapsEvStation);
MapsEvStation.displayName = 'MapsEvStation';
MapsEvStation.muiName = 'SvgIcon';
export default MapsEvStation;
|
src/svg-icons/action/help.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHelp = (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 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
</SvgIcon>
);
ActionHelp = pure(ActionHelp);
ActionHelp.displayName = 'ActionHelp';
export default ActionHelp;
|
transforms/__testfixtures__/React-PropTypes-to-prop-types/mixed-import-and-require.input.js | reactjs/react-codemod | import React from 'react';
require('styles.css');
class MyClass extends React.Component {}
MyClass.propTypes = {
foo: React.PropTypes.string
}; |
src/App.js | CaiFanglin/react-redux-tabs | import React, { Component } from 'react';
import './App.css';
import Container from './components/Container.js';
import { connect, Provider } from 'react-redux';
import { bindActionCreators, createStore, applyMiddleware } from 'redux';
import Reducer from './redux/reducers.js';
import * as acts from './redux/actions.js';
import thunkMiddleware from 'redux-thunk';
import 'babel-polyfill'
const store = applyMiddleware(thunkMiddleware)(createStore)(Reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
const Comp = connect(
state => ({state}),
dispatch => ({
actions: bindActionCreators(acts, dispatch)
})
)(Container);
class App extends Component {
render() {
return (
<Provider store={store}>
<Comp/>
</Provider>
);
}
}
export default App;
|
client/components/ui/impl/material/ContentBlock.js | axax/lunuc | import React from 'react'
import styled from '@emotion/styled'
const StyledContentBlock = styled('div')(({ theme }) => ({
marginBottom: theme.spacing(4)
}))
class ContentBlock extends React.PureComponent {
render() {
return <StyledContentBlock {...this.props} />
}
}
export default ContentBlock
|
node_modules/react-router/es/Route.js | iEnder/React-Blog | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
func = _React$PropTypes.func;
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
/* eslint-disable react/require-render-return */
var Route = React.createClass({
displayName: 'Route',
statics: {
createRouteFromReactElement: createRouteFromReactElement
},
propTypes: {
path: string,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Route; |
src/PlaylistHeader.js | billyryanwill/amplify | import React from 'react';
const PlaylistHeader = () => {
return (
<section>
</section>
)
}
export default PlaylistHeader;
|
src/lib/reactors/Bookmarks/Bookmarks.js | EsriJapan/photospot-finder | // Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import { DropdownButton, Glyphicon } from 'react-bootstrap';
import Bookmark from './Bookmark';
class Bookmarks extends React.Component {
constructor (props) {
super(props);
}
render () {
const bookmarks = this.props.bookmarks;
const title = (<Glyphicon glyph="bookmark" />);
const BookmarkList = bookmarks.map(function (b, i) {
const name = b.name;
const bounds = b.bounds;
return (
<Bookmark
key={b.name + i}
name={b.name}
bounds={b.bounds}
onClickBookmark={this.props.onClickBookmark}
/>
);
}.bind(this));
return (
<DropdownButton title={title} id="react-webmap-bookmarks-dropdown">
{BookmarkList}
</DropdownButton>
);
}
}
Bookmarks.propTypes = {
bookmarks: React.PropTypes.array,
onClickBookmark: React.PropTypes.func
};
Bookmarks.defaultProps = {
bookmarks: []
};
Bookmarks.displayName = 'Bookmarks';
export default Bookmarks;
|
app/app/components/AdminPanel/ApiKeys/ApiKeysContainer.js | lycha/masters-thesis | import React from 'react';
import store from '../../../store';
import { connect } from 'react-redux';
import {getApiKeys, deleteApiKey, addApiKey} from '../../../api/ApiKeysApi';
import ApiKeysList from './ApiKeysList'
import AddApiKey from './AddApiKey'
class ApiKeysContainer extends React.Component {
componentDidMount() {
getApiKeys();
}
addNew(apiKey) {
addApiKey(apiKey);
}
render() {
return (
<section id="main-content">
<section className="wrapper">
<div className="row mt">
<div className="col-lg-12">
<div className="form-panel">
<AddApiKey addNew={this.addNew}
expirationDate={this.props.expirationDate}
ref="child"/>
</div>
</div>
</div>
<div className="row mt">
<div className="col-lg-12">
<div className="content-panel">
<h4><i className="fa fa-angle-right"></i> API Keys</h4>
<hr />
<table className="table table-striped table-advance table-hover">
<thead>
<tr>
<th><i className="fa fa-bookmark"></i> id</th>
<th><i className="fa fa-question-circle"></i> Name</th>
<th><i className="fa fa-bookmark"></i> Description</th>
<th><i className="fa fa-question-circle"></i> Expiration date</th>
<th><i className="fa fa-question-circle"></i> Key</th>
<th></th>
</tr>
</thead>
<ApiKeysList apiKeys={this.props.apiKeys}
deleteApiKey={deleteApiKey} />
</table>
</div>
</div>
</div>
</section>
</section>
);
}
}
const mapStateToProps = function(store) {
return {
apiKeys: store.apiKeysState.apiKeys,
expirationDate: store.apiKeysState.expirationDate
};
};
export default connect(mapStateToProps)(ApiKeysContainer);
|
app/javascript/mastodon/features/account/components/account_note.js | danhunsaker/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Textarea from 'react-textarea-autosize';
import { is } from 'immutable';
const messages = defineMessages({
placeholder: { id: 'account_note.placeholder', defaultMessage: 'Click to add a note' },
});
class InlineAlert extends React.PureComponent {
static propTypes = {
show: PropTypes.bool,
};
state = {
mountMessage: false,
};
static TRANSITION_DELAY = 200;
componentWillReceiveProps (nextProps) {
if (!this.props.show && nextProps.show) {
this.setState({ mountMessage: true });
} else if (this.props.show && !nextProps.show) {
setTimeout(() => this.setState({ mountMessage: false }), InlineAlert.TRANSITION_DELAY);
}
}
render () {
const { show } = this.props;
const { mountMessage } = this.state;
return (
<span aria-live='polite' role='status' className='inline-alert' style={{ opacity: show ? 1 : 0 }}>
{mountMessage && <FormattedMessage id='generic.saved' defaultMessage='Saved' />}
</span>
);
}
}
export default @injectIntl
class AccountNote extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
value: PropTypes.string,
onSave: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
value: null,
saving: false,
saved: false,
};
componentWillMount () {
this._reset();
}
componentWillReceiveProps (nextProps) {
const accountWillChange = !is(this.props.account, nextProps.account);
const newState = {};
if (accountWillChange && this._isDirty()) {
this._save(false);
}
if (accountWillChange || nextProps.value === this.state.value) {
newState.saving = false;
}
if (this.props.value !== nextProps.value) {
newState.value = nextProps.value;
}
this.setState(newState);
}
componentWillUnmount () {
if (this._isDirty()) {
this._save(false);
}
}
setTextareaRef = c => {
this.textarea = c;
}
handleChange = e => {
this.setState({ value: e.target.value, saving: false });
};
handleKeyDown = e => {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this._save();
if (this.textarea) {
this.textarea.blur();
}
} else if (e.keyCode === 27) {
e.preventDefault();
this._reset(() => {
if (this.textarea) {
this.textarea.blur();
}
});
}
}
handleBlur = () => {
if (this._isDirty()) {
this._save();
}
}
_save (showMessage = true) {
this.setState({ saving: true }, () => this.props.onSave(this.state.value));
if (showMessage) {
this.setState({ saved: true }, () => setTimeout(() => this.setState({ saved: false }), 2000));
}
}
_reset (callback) {
this.setState({ value: this.props.value }, callback);
}
_isDirty () {
return !this.state.saving && this.props.value !== null && this.state.value !== null && this.state.value !== this.props.value;
}
render () {
const { account, intl } = this.props;
const { value, saved } = this.state;
if (!account) {
return null;
}
return (
<div className='account__header__account-note'>
<label htmlFor={`account-note-${account.get('id')}`}>
<FormattedMessage id='account.account_note_header' defaultMessage='Note' /> <InlineAlert show={saved} />
</label>
<Textarea
id={`account-note-${account.get('id')}`}
className='account__header__account-note__content'
disabled={this.props.value === null || value === null}
placeholder={intl.formatMessage(messages.placeholder)}
value={value || ''}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleBlur}
ref={this.setTextareaRef}
/>
</div>
);
}
}
|
src/components/common/RoundText.js | serlo-org/serlo-abc | import { path } from 'ramda';
import React, { Component } from 'react';
import { Animated, View } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import {
WHITE,
WHITE_TRANSPARENT,
PRIMARY_WEAK,
TRANSPARENT,
RED,
GREEN
} from '../../styles/colors';
import { DEFAULT } from '../../styles/text';
const AnimatedIcon = Animated.createAnimatedComponent(MaterialIcons);
class RoundText extends Component {
constructor(props) {
super(props);
this.state = {
size:
typeof props.size !== undefined
? new Animated.Value(props.size)
: undefined,
fontSize: new Animated.Value(this.getBaseFontSize(props))
};
}
getBaseFontSize = props =>
path(['textStyle', 'fontSize'], props) || DEFAULT.fontSize;
componentWillReceiveProps(nextProps) {
const scaleFactor = 1.2;
if (
this.props.size !== nextProps.size ||
this.getBaseFontSize(this.props) !== this.getBaseFontSize(nextProps) ||
this.props.highlighted !== nextProps.highlighted
) {
const baseFontSize = this.getBaseFontSize(nextProps);
Animated.parallel([
Animated.timing(this.state.size, {
toValue: nextProps.highlighted
? scaleFactor * nextProps.size
: nextProps.size
}),
Animated.timing(this.state.fontSize, {
toValue: nextProps.highlighted
? scaleFactor * baseFontSize
: baseFontSize
})
]).start();
}
}
render() {
const {
highlighted,
crossedOut,
text,
isIcon,
style,
textStyle,
wrong,
correct,
missingCorrect
} = this.props;
const { size, fontSize } = this.state;
return (
<View
style={[
{
backgroundColor: wrong ? RED : WHITE_TRANSPARENT,
borderRadius: 9999,
borderColor: highlighted && !wrong ? PRIMARY_WEAK : WHITE
},
style,
highlighted && { backgroundColor: correct ? GREEN : WHITE },
wrong && { backgroundColor: RED },
!highlighted &&
missingCorrect && { borderColor: GREEN, borderWidth: 10 }
]}
>
<Animated.View
style={{
overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center',
...(size !== undefined ? { height: size, width: size } : {})
}}
>
{isIcon ? (
<AnimatedIcon
style={[
DEFAULT,
highlighted && { color: PRIMARY_WEAK },
{ backgroundColor: TRANSPARENT, marginTop: 5 },
(wrong || correct) && { color: WHITE },
textStyle,
{ fontSize }
]}
name={text}
/>
) : (
<Animated.Text
style={[
DEFAULT,
highlighted && { color: PRIMARY_WEAK },
{ backgroundColor: TRANSPARENT, marginTop: 5 },
(wrong || correct) && { color: WHITE },
textStyle,
{ fontSize }
]}
>
{text}
</Animated.Text>
)}
{crossedOut && (
<Animated.View
style={{
position: 'absolute',
height: 3.5,
...(size !== undefined ? { width: size } : {}),
borderRadius: 1,
backgroundColor: highlighted && !wrong ? PRIMARY_WEAK : WHITE,
transform: [{ rotate: '-45deg' }],
opacity: 0.8
}}
/>
)}
</Animated.View>
</View>
);
}
}
export default RoundText;
|
frontend/src/screens/monitor/widgets/stages/stages.js | linea-it/qlf | import React, { Component } from 'react';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import _ from 'lodash';
import Card from '@material-ui/core/Card';
import PropTypes from 'prop-types';
import Tooltip from '@material-ui/core/Tooltip';
import { withStyles } from '@material-ui/core/styles';
import LinearProgress from '@material-ui/core/LinearProgress';
import flavors from '../../../../flavors';
const headerSize = '1vw';
const styles = {
flex: { display: 'flex', flexDirection: 'row', alignItems: 'center' },
leftCol: { marginRight: '1vw', marginLeft: '1vw', marginTop: '1vh' },
rightCol: { flex: 1, marginLeft: '1vw', marginRight: '1vw' },
card: {
borderLeft: 'solid 4px green',
flex: '1',
marginRight: '1vw',
marginBottom: '10px',
},
arm: {
color: '#9E9E9E',
fontWeight: 'bold',
fontSize: '1.2vw',
},
header: {
fontSize: headerSize,
height: 0,
padding: 0,
whiteSpace: 'normal',
paddingRight: '0px',
textAlign: 'center',
},
loading: {
height: '100%',
},
barColorPrimary: {
backgroundColor: 'gray',
},
colorPrimary: {
backgroundColor: 'lightgray',
},
tooltipText: {
fontSize: '1.5vh',
},
};
class Stages extends Component {
static propTypes = {
arm: PropTypes.string.isRequired,
openDialog: PropTypes.func.isRequired,
status: PropTypes.array.isRequired,
renderHeader: PropTypes.bool.isRequired,
classes: PropTypes.object,
pipelineRunning: PropTypes.string,
flavor: PropTypes.string,
};
state = {
columnHeight: 0,
openDialog: true,
completed: 0,
};
handleToggle = (event, toggled) => {
this.setState({
[event.target.name]: toggled,
});
};
handleChange = event => {
this.setState({ height: event.target.value });
};
getColor = row => {
switch (row) {
case 'success_stage':
return { backgroundColor: 'green', padding: '0.5vh' };
case 'processing_stage':
// return { backgroundColor: 'blue', padding: 4 };
return {
padding: 0,
};
case 'error_stage':
return { backgroundColor: 'red', padding: '0.5vh' };
default:
return { padding: '0.5vh' };
}
};
renderTableHeader = flavor => {
if (this.props.arm !== 'b') return;
return (
<TableHead>
<TableRow style={{ height: this.state.columnHeight }}>
{flavors[flavor].step_list.map((step, idx) => {
return (
<TableCell key={`stageHeader${idx}`} style={styles.header}>
{step.display_name}
</TableCell>
);
})}
</TableRow>
</TableHead>
);
};
timer = null;
componentDidMount() {
this.timer = setInterval(this.progress, 2000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
progress = () => {
const { completed } = this.state;
if (this.props.pipelineRunning !== 'Running') return;
if (completed === 100) {
this.setState({ completed: 0 });
} else {
const diff = 22;
this.setState({ completed: Math.min(completed + diff, 100) });
}
};
render() {
const flavor = this.props.flavor ? this.props.flavor : 'science';
const flavorStages = flavors[flavor].step_list.map(step => step.name);
const stage_status = _.map(_.range(10), function() {
const stage = {};
flavorStages.map(stg => {
stage[stg] = '';
return null;
});
return stage;
});
if (this.props.status.length > 0) {
this.props.status.map(row => {
const index = Object.keys(row)[0];
flavorStages.map((stg, idx) => {
stage_status[index][stg] = row[index][idx];
return null;
});
return null;
});
}
return (
<div>
<Card style={styles.card}>
<div style={styles.flex}>
<div style={styles.leftCol}>
<div style={styles.flex}>
<span style={styles.arm}>{this.props.arm}</span>
</div>
</div>
<div style={styles.rightCol}>
<div style={styles.flex}>
<Table id="stages" height={this.state.height} width={'10px'}>
{this.renderTableHeader(flavor)}
<TableBody>
{stage_status.map((row, index) => (
<Tooltip
key={index}
title={`Camera ${this.props.arm}${index}`}
placement="top"
classes={{ tooltip: this.props.classes.tooltipText }}
>
<TableRow
hover
style={{
height: this.state.columnHeight,
cursor: 'pointer',
}}
onClick={() =>
this.props.openDialog(index, this.props.arm)
}
>
{flavorStages.map(stg => {
return (
<TableCell
key={stg}
style={{
fontSize: 0,
height: '0.3vh',
padding: 0,
...this.getColor(row[stg]),
}}
>
{row[stg] === 'processing_stage' ? (
<LinearProgress
style={styles.loading}
variant="determinate"
value={this.state.completed}
classes={{
barColorPrimary: this.props.classes
.barColorPrimary,
colorPrimary: this.props.classes
.colorPrimary,
}}
/>
) : null}
</TableCell>
);
})}
</TableRow>
</Tooltip>
))}
</TableBody>
</Table>
</div>
</div>
</div>
</Card>
</div>
);
}
}
export default withStyles(styles)(Stages);
|
src/app/homelessness/HomelessnessVeterans.js | cityofasheville/simplicity2 | import React from 'react';
import PropTypes from 'prop-types';
import BarChart from '../../shared/visualization/BarChart';
import PageHeader from '../../shared/PageHeader';
import ButtonGroup from '../../shared/ButtonGroup';
import LinkButton from '../../shared/LinkButton';
import Icon from '../../shared/Icon';
import { IM_BED } from '../../shared/iconConstants';
import HomelessnessVeteransInflowOutflow from './HomelessnessVeteransInflowOutflow';
import HomelessnessVeteransExitTime from './HomelessnessVeteransExitTime';
import HomelessnessVeteransEnrollment from './HomelessnessVeteransEnrollment';
import HomelessnessVeteransChronicAssignments from './HomelessnessVeteransChronicAssignments';
const dataKeys = [
'Incoming',
//'Remaining to be housed',
'Outgoing',
];
// todo get this data from graphql
const data = [
{
month: '4/2016',
Incoming: 40,
'Remaining to be housed': 103,
Outgoing: -27,
'Net change': 13,
},
{
month: '5/2016',
Incoming: 45,
'Remaining to be housed': 124,
Outgoing: -30,
'Net change': 5,
},
{
month: '6/2016',
Incoming: 42,
'Remaining to be housed': 126,
Outgoing: -44,
'Net change': -2,
},
{
month: '7/2016',
Incoming: 32,
'Remaining to be housed': 117,
Outgoing: -31,
'Net change': 1,
},
{
month: '8/2016',
Incoming: 35,
'Remaining to be housed': 112,
Outgoing: -33,
'Net change': 2,
},
{
month: '9/2016',
Incoming: 38,
'Remaining to be housed': 105,
Outgoing: -35,
'Net change': 3,
},
{
month: '10/2016',
Incoming: 40,
'Remaining to be housed': 108,
Outgoing: -41,
'Net change': -1,
},
{
month: '11/2016',
Incoming: 39,
'Remaining to be housed': 105,
Outgoing: -50,
'Net change': -11,
},
{
month: '12/2016',
Incoming: 32,
'Remaining to be housed': 84,
Outgoing: -37,
'Net change': -5,
},
{
month: '1/2017',
Incoming: 35,
'Remaining to be housed': 100,
Outgoing: -31,
'Net change': 4,
},
{
month: '2/2017',
Incoming: 25,
'Remaining to be housed': 89,
Outgoing: -41,
'Net change': -16,
},
{
month: '3/2017',
Incoming: 30,
'Remaining to be housed': 95,
Outgoing: -24,
'Net change': 6,
},
// { month: 4/2017, 'Remaining to be housed': 96, },
// { month: 5/2017, 'Remaining to be housed': 99 },
];
const HomelessnessVeterans = (props) => (
<div>
<div className="row" style={{ marginTop: '15px' }}>
<div className="col-sm-12">
<div className="alert alert-danger h1" style={{ marginBottom: '0px' }}>
Warning: this dashboard is out of date! We're working on updating and refreshing it. Please contact help@ashevillenc.gov if you have any questions.
</div>
</div>
</div>
<PageHeader h1="Ending Veteran Homelessness" dataLinkPath="/homelessness/data" externalLink="http://www.ashevillenc.gov/civicax/filebank/blobdload.aspx?blobid=27777" externalLinkText="Five Year Strategic Plan on Homelessness in Buncombe County" icon={<Icon path={IM_BED} size={50} />}>
<ButtonGroup>
<LinkButton pathname="/homelessness" query={{ entity: props.location.query.entity, id: props.location.query.id, label: props.location.query.label, hideNavbar: props.location.query.hideNavbar }} positionInGroup="left">Overview</LinkButton>
<LinkButton pathname="/homelessness/veterans" query={{ entity: props.location.query.entity, id: props.location.query.id, label: props.location.query.label, hideNavbar: props.location.query.hideNavbar }} positionInGroup="right" active>Veterans</LinkButton>
</ButtonGroup>
</PageHeader>
<div className="row" style={{ marginTop: '15px' }}>
<div className="col-sm-12">
<a href="http://www.nc211.org" title="NC 211 homelessness resourses" target="_blank">
<div className="alert alert-warning" style={{ marginBottom: '0px' }}>
Are you homeless? Do you need help finding housing? Click here for resources.
</div>
</a>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<h2>How are homeless Veterans being helped?</h2>
<p>
Buncombe County is comprised of many agencies and organizations assisting and serving our Veteran homeless population in conjunction with the VA Medical Center. Outreach specialists identify areas throughout the community where homeless Veterans congregate and camp. Veterans are identified and assessed using a standardized vulnerability index tool to help identify the most appropriate housing intervention available for that Veteran. Agency representatives meet weekly to review referrals and ensure that every eligible homeless Veteran is matched with an appropriate housing intervention. Homeless military Veterans of low and extremely low income in Buncombe County are eligible for case management, service referral or may receive housing assistance through VA funded programs.
</p>
</div>
</div>
<HomelessnessVeteransInflowOutflow />
<hr />
<HomelessnessVeteransExitTime />
<hr />
<HomelessnessVeteransEnrollment />
<hr />
<HomelessnessVeteransChronicAssignments />
</div>
);
HomelessnessVeterans.propTypes = {
showLongDesc: PropTypes.bool, // eslint-disable-line
location: PropTypes.object, // eslint-disable-line react/forbid-prop-types
};
HomelessnessVeterans.defaultProps = {
showLongDesc: false,
};
export default HomelessnessVeterans;
|
app/javascript/mastodon/containers/compose_container.js | tootsuite/mastodon | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { hydrateStore } from '../actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import Compose from '../features/standalone/compose';
import initialState from '../initial_state';
import { fetchCustomEmojis } from '../actions/custom_emojis';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
const store = configureStore();
if (initialState) {
store.dispatch(hydrateStore(initialState));
}
store.dispatch(fetchCustomEmojis());
export default class TimelineContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<Compose />
</Provider>
</IntlProvider>
);
}
}
|
src/svg-icons/communication/stay-current-portrait.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayCurrentPortrait = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
CommunicationStayCurrentPortrait = pure(CommunicationStayCurrentPortrait);
CommunicationStayCurrentPortrait.displayName = 'CommunicationStayCurrentPortrait';
CommunicationStayCurrentPortrait.muiName = 'SvgIcon';
export default CommunicationStayCurrentPortrait;
|
old_boilerplate/js/app.js | hbaughman/audible-temptations | /**
*
* app.js
*
* This is the entry file for the application, mostly just setup and boilerplate
* code. Routes are configured at the end of this file!
*
*/
// Load the ServiceWorker, the Cache polyfill, the manifest.json file and the .htaccess file
import 'file?name=[name].[ext]!../serviceworker.js';
import 'file?name=[name].[ext]!../manifest.json';
import 'file?name=[name].[ext]!../.htaccess';
// Check for ServiceWorker support before trying to install it
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js').then(() => {
// Registration was successful
}).catch(() => {
// Registration failed
});
} else {
// No ServiceWorker Support
}
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import FontFaceObserver from 'fontfaceobserver';
import createHistory from 'history/lib/createBrowserHistory';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// Observer loading of Open Sans (to remove open sans, remove the <link> tag in the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add the js-open-sans-loaded class to the body
openSansObserver.check().then(() => {
document.body.classList.add('js-open-sans-loaded');
}, () => {
document.body.classList.remove('js-open-sans-loaded');
});
// Import the pages
import App from './components/App.react';
import Home from './components/pages/Home';
import Auth from './components/pages/Auth';
import ReadmePage from './components/pages/ReadmePage.react';
import NotFoundPage from './components/pages/NotFound.react';
// Import the CSS file, which HtmlWebpackPlugin transfers to the build folder
import '../css/main.css';
// Create the store with the redux-thunk middleware, which allows us
// to do asynchronous things in the actions
import rootReducer from './reducers/rootReducer';
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(rootReducer);
// Make reducers hot reloadable, see http://stackoverflow.com/questions/34243684/make-redux-reducers-and-other-non-components-hot-loadable
if (module.hot) {
module.hot.accept('./reducers/rootReducer', () => {
const nextRootReducer = require('./reducers/rootReducer').default;
store.replaceReducer(nextRootReducer);
});
}
// Mostly boilerplate, except for the Routes. These are the pages you can go to,
// which are all wrapped in the App component, which contains the navigation etc
ReactDOM.render(
<Provider store={store}>
<Router history={createHistory()}>
<Route component={App}>
<Route path="/" component={Home} />
<Route path="auth" component={Auth} />
<Route path="/readme" component={ReadmePage} />
<Route path="*" component={NotFoundPage} />
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
|
techCurriculum/ui/solutions/3.1/src/index.js | jennybkim/engineeringessentials | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import '../stylesheet.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
blueocean-material-icons/src/js/components/svg-icons/action/translate.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionTranslate = (props) => (
<SvgIcon {...props}>
<path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</SvgIcon>
);
ActionTranslate.displayName = 'ActionTranslate';
ActionTranslate.muiName = 'SvgIcon';
export default ActionTranslate;
|
salt-frontend/react/dashboard/src/portlets/pageHtml/index.js | syakuis/salt-framework | import React from 'react';
import ContextMenu from '../../components/ContextMenu';
import AlloyEditorComponent from '../../components/AlloyEditorComponent';
export default class PageHtml extends React.Component {
constructor(props) {
super(props);
}
static getInfo() {
return {
title: '에디터 포틀릿',
image: null
}
}
static getDefault() {
return {
title: '에디터 포틀릿',
image: null,
options: {
padding: 5,
w: 4,
h: 4,
x: 0,
y: Infinity,
static: false,
isDraggable: true,
isResizable: true
}
};
}
render() {
let padding = this.props.padding;
if (padding <= 0) {
padding = 5;
}
return (
<div style={{ width: '100%', height: '100%', padding: padding }}>
<ContextMenu idx={this.props.idx} isContextMenuShow={this.props.isContextMenuShow} />
<AlloyEditorComponent container="editable"/>
</div>
)
}
} |
frontend/node_modules/react-router/es/Route.js | goodman001/20170927express | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _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 warning from 'warning';
import invariant from 'invariant';
import React from 'react';
import PropTypes from 'prop-types';
import matchPath from './matchPath';
var isEmptyChildren = function isEmptyChildren(children) {
return React.Children.count(children) === 0;
};
/**
* The public API for matching a single path and rendering.
*/
var Route = function (_React$Component) {
_inherits(Route, _React$Component);
function Route() {
var _temp, _this, _ret;
_classCallCheck(this, Route);
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.state = {
match: _this.computeMatch(_this.props, _this.context.router)
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Route.prototype.getChildContext = function getChildContext() {
return {
router: _extends({}, this.context.router, {
route: {
location: this.props.location || this.context.router.route.location,
match: this.state.match
}
})
};
};
Route.prototype.computeMatch = function computeMatch(_ref, router) {
var computedMatch = _ref.computedMatch,
location = _ref.location,
path = _ref.path,
strict = _ref.strict,
exact = _ref.exact,
sensitive = _ref.sensitive;
if (computedMatch) return computedMatch; // <Switch> already computed the match for us
invariant(router, 'You should not use <Route> or withRouter() outside a <Router>');
var route = router.route;
var pathname = (location || route.location).pathname;
return path ? matchPath(pathname, { path: path, strict: strict, exact: exact, sensitive: sensitive }) : route.match;
};
Route.prototype.componentWillMount = function componentWillMount() {
warning(!(this.props.component && this.props.render), 'You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored');
warning(!(this.props.component && this.props.children && !isEmptyChildren(this.props.children)), 'You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored');
warning(!(this.props.render && this.props.children && !isEmptyChildren(this.props.children)), 'You should not use <Route render> and <Route children> in the same route; <Route children> will be ignored');
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) {
warning(!(nextProps.location && !this.props.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.');
warning(!(!nextProps.location && this.props.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.');
this.setState({
match: this.computeMatch(nextProps, nextContext.router)
});
};
Route.prototype.render = function render() {
var match = this.state.match;
var _props = this.props,
children = _props.children,
component = _props.component,
render = _props.render;
var _context$router = this.context.router,
history = _context$router.history,
route = _context$router.route,
staticContext = _context$router.staticContext;
var location = this.props.location || route.location;
var props = { match: match, location: location, history: history, staticContext: staticContext };
return component ? // component prop gets first priority, only called if there's a match
match ? React.createElement(component, props) : null : render ? // render prop is next, only called if there's a match
match ? render(props) : null : children ? // children come last, always called
typeof children === 'function' ? children(props) : !isEmptyChildren(children) ? React.Children.only(children) : null : null;
};
return Route;
}(React.Component);
Route.propTypes = {
computedMatch: PropTypes.object, // private, from <Switch>
path: PropTypes.string,
exact: PropTypes.bool,
strict: PropTypes.bool,
sensitive: PropTypes.bool,
component: PropTypes.func,
render: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
location: PropTypes.object
};
Route.contextTypes = {
router: PropTypes.shape({
history: PropTypes.object.isRequired,
route: PropTypes.object.isRequired,
staticContext: PropTypes.object
})
};
Route.childContextTypes = {
router: PropTypes.object.isRequired
};
export default Route; |
src/components/header/MobileSearch.js | MyronBatiuk/react-shopify-storefront | import React, { Component } from 'react';
export default class MobileSearch extends Component {
render(){
return (
<div className="mobile-search" role="search">
<input className="mobile-search__input" name="q" placeholder="Search"
aria-label="Search"/>
<button className="mobile-search__submit" onClick={this.clickHandle}>
<svg aria-hidden="true" focusable="false" role="presentation" className="icon icon-search" viewBox="0 0 37 40">
<path
d="M35.6 36l-9.8-9.8c4.1-5.4 3.6-13.2-1.3-18.1-5.4-5.4-14.2-5.4-19.7 0-5.4 5.4-5.4 14.2 0 19.7 2.6 2.6 6.1 4.1 9.8 4.1 3 0 5.9-1 8.3-2.8l9.8 9.8c.4.4.9.6 1.4.6s1-.2 1.4-.6c.9-.9.9-2.1.1-2.9zm-20.9-8.2c-2.6 0-5.1-1-7-2.9-3.9-3.9-3.9-10.1 0-14C9.6 9 12.2 8 14.7 8s5.1 1 7 2.9c3.9 3.9 3.9 10.1 0 14-1.9 1.9-4.4 2.9-7 2.9z"></path>
</svg>
</button>
</div>
)
}
} |
src/routes.js | kyleturco/redux-tutorial | import React from 'react'
import { Route, IndexRoute } from 'react-router'
import Home from './components/common/HomePage'
import About from './components/common/AboutPage'
import Book from './components/book/BookPage'
import App from './components/App'
export default (
<Route path='/' component={App}>
<IndexRoute component={Home}></IndexRoute>
<Route path='/about' component={About}></Route>
<Route path='/book' component={Book}></Route>
</Route>
)
|
app/src/Frontend/libs/weui/components/mediabox/mediabox_info.js | ptphp/ptphp | /**
* Created by n7best
*/
import React from 'react';
import classNames from 'classnames';
import MediaBoxInfoMeta from './mediabox_info_meta';
export default class MediaBoxInfo extends React.Component {
static propTypes = {
data: React.PropTypes.array,
};
static defaultProps = {
data: [],
};
renderData(metas) {
return metas.map((meta,i) => {
return <MediaBoxInfoMeta key={i} extra={meta.extra}>{meta.label}</MediaBoxInfoMeta>;
});
}
render() {
const {children, data, className, ...others} = this.props;
const cls = classNames({
weui_media_info: true
}, className);
return (
<ul className={cls} {...others}>
{data.length > 0 ? this.renderData(data) : children}
</ul>
);
}
}; |
src/components/ChartTypePicker/index.js | DataSF/open-data-explorer | import React from 'react'
import PropTypes from 'prop-types'
import { Panel } from 'react-bootstrap'
import {CirclePicker } from 'react-color';
import './@ChartTypePicker.css'
const ChartTypePicker = ({chartTypes, chartType, onChange, onChangeChartColor, isGroupBy}) => {
let options = chartTypes.map((type, idx) => {
return (
<label className='radio-inline' key={type.key}>
<input type='radio' name='chartTypeOptions' id={'chartType' + idx} value={type.key} onChange={() => onChange(type.key)} checked={chartType === type.key} />
{type.name}
</label>
)
})
return (
<Panel collapsible defaultExpanded bsStyle='primary' header={<h4>Choose a chart type <span className='glyphicon collapse-icon' aria-hidden></span></h4>}>
<div className={'chart-picker'}>
{options}
</div>
<Choose>
<When condition={!isGroupBy}>
<div className={'color-picker'}>
<CirclePicker
onChange={onChangeChartColor} />
</div>
</When>
</Choose>
</Panel>
)
}
ChartTypePicker.propTypes = {
chartTypes: PropTypes.array,
onChange: PropTypes.func
}
export default ChartTypePicker
|
app/components/Seat/index.js | VonIobro/ab-web | /**
* Created by jzobro 20170517
*/
import React from 'react';
import PropTypes from 'prop-types';
import Seat from './Seat';
import ButtonJoinSeat from './ButtonJoinSeat';
import ButtonOpenSeat from './ButtonOpenSeat';
import { STATUS_MSG } from '../../app.config';
const SeatComponent = (props) => {
const {
isTaken,
myPos,
open,
pos,
pending,
myPending,
reserved,
} = props;
if (open) {
if ((myPos === undefined && !myPending) || pending || reserved) {
if (pending) {
return (
<Seat {...props} {...pending} />
);
}
if (reserved) {
return (
<Seat
{...props}
seatStatus={STATUS_MSG.sittingIn}
signerAddr={reserved.signerAddr}
blocky={reserved.blocky}
stackSize={Number(reserved.amount)}
/>
);
}
return (
<ButtonJoinSeat
onClickHandler={() => isTaken(open, myPos, pending, pos)}
{...props}
/>
);
}
if (typeof myPos === 'number' || myPending) {
return <ButtonOpenSeat {...props} />;
}
}
return <Seat {...props} />;
};
SeatComponent.propTypes = {
isTaken: PropTypes.func,
myPos: PropTypes.number,
open: PropTypes.bool,
pos: PropTypes.number,
pending: PropTypes.any,
myPending: PropTypes.any,
reserved: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
};
export default SeatComponent;
|
app/containers/AboutContainer.js | orballo/game-of-life | 'use strict'
import React from 'react'
import About from '../components/About.js'
const AboutContainer = React.createClass({
getInitialState() {
return {
isAboutHidden: true
}
},
componentDidMount() {
window.addEventListener('keydown', (e) => {
if (e.keyCode === 73) { // I key binding
if (!e.ctrlKey) this._showAbout()
} else if (e.keyCode === 27) { // Escape key binding
if (!this.state.isAboutHidden) this._showAbout()
}
})
},
_showAbout () {
let isHidden = this.state.isAboutHidden
this.setState({
isAboutHidden: !isHidden
})
},
render () {
return (
<About
isHidden={this.state.isAboutHidden}
showAbout={this._showAbout} />
)
}
})
export default AboutContainer
|
collect-webapp/frontend/src/common/components/ValidationTooltip.js | openforis/collect | import React from 'react'
import { UncontrolledTooltip } from 'reactstrap'
import classnames from 'classnames'
import PropTypes from 'prop-types'
import Validation from 'model/Validation'
const ValidationTooltip = (props) => {
const { validation, target } = props
const { errorMessage, warningMessage } = validation
const className = classnames({ error: validation.hasErrors(), warning: validation.hasWarnings() })
if (validation.isEmpty()) return null
return (
<UncontrolledTooltip target={target} placement="top-start" popperClassName={className}>
{errorMessage || warningMessage}
</UncontrolledTooltip>
)
}
ValidationTooltip.propTypes = {
validation: PropTypes.instanceOf(Validation),
}
ValidationTooltip.defaultProps = {
validation: new Validation(),
}
export default ValidationTooltip
|
src/encoded/static/components/static-pages/StatisticsPageView.js | hms-dbmi/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { memoizedUrlParse } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import StaticPage from './StaticPage';
const dynamicImports = {};
export default class StatisticsPageView extends React.PureComponent {
static defaultProps = {
'defaultTab' : 'submissions'
};
static viewOptions = {
'submissions' : {
'title' : "Submissions Statistics",
'icon' : 'upload fas',
'tip' : "View statistics related to submission and release of Experiment Set",
// Now set upon load:
// 'aggregationsToChartData' : _.pick(aggregationsToChartData,
// 'expsets_released', 'expsets_released_internal',
// 'expsets_released_vs_internal', 'files_released',
// 'file_volume_released'
// )
},
'usage' : {
'title' : "Usage Statistics",
'icon' : 'users fas',
'tip' : "View statistics related to usage of the 4DN Data Portal",
// Now set upon load:
// 'aggregationsToChartData' : _.pick(aggregationsToChartData,
// 'sessions_by_country', 'fields_faceted', /* 'browse_search_queries', 'other_search_queries', */
// 'experiment_set_views', 'file_downloads'
// ),
'shouldReaggregate' : function(pastProps, nextProps){
// Compare object references
if (pastProps.countBy !== nextProps.countBy) return true;
}
}
};
constructor(props){
super(props);
this.maybeUpdateCurrentTabFromHref = this.maybeUpdateCurrentTabFromHref.bind(this);
this.renderSubmissionsSection = this.renderSubmissionsSection.bind(this);
this.renderUsageSection = this.renderUsageSection.bind(this);
this.renderTopMenu = this.renderTopMenu.bind(this);
this.state = { 'currentTab' : props.defaultTab };
}
componentDidMount(){
this.maybeUpdateCurrentTabFromHref();
if (!dynamicImports.UsageStatsView) {
setTimeout(()=>{
// Load in stats page components/code separately (code-splitting)
// FOR DEVELOPMENT:
// include `/* webpackMode: "eager" */`, since `npm run dev-quick` won't re-compile dynamic imports correctly.
// "statistics-page-components" is aliased to './components/StatisticsPageViewBody' in webpack.config.js
import(
/* webpackChunkName: "statistics-page-components" */
"statistics-page-components"
).then((loadedModule) => {
_.extend(dynamicImports, loadedModule);
this.setState({ mounted: true });
});
});
} else {
onComplete();
}
}
componentDidUpdate(pastProps){
const { href } = this.props;
if (href !== pastProps.href){
this.maybeUpdateCurrentTabFromHref();
}
}
maybeUpdateCurrentTabFromHref(){
const { href } = this.props;
this.setState(function({ currentTab }){
const hrefParts = href && memoizedUrlParse(href);
const hash = hrefParts && hrefParts.hash && hrefParts.hash.replace('#', '');
if (hash && hash !== currentTab && hash.charAt(0) !== '!'){
if (typeof StatisticsPageView.viewOptions[hash] !== 'undefined'){
return { 'currentTab' : hash };
}
}
});
}
renderSubmissionsSection(){
// GroupByController is on outside here because SubmissionStatsViewController detects if props.currentGroupBy has changed in orded to re-fetch aggs.
const { browseBaseState } = this.props;
const groupByOptions = { 'award.project' : <span><i className="icon icon-fw fas icon-university mr-1"/>Project</span> };
let initialGroupBy = 'award.project';
if (browseBaseState !== 'all'){
_.extend(groupByOptions, {
'award.center_title' : <span><i className="icon icon-fw fas icon-university mr-1"/>Center</span>,
'lab.display_title' : <span><i className="icon icon-fw fas icon-users mr-1"/>Lab</span>,
'experiments_in_set.experiment_type.display_title' : <span><i className="icon icon-fw fas icon-chart-bar mr-1"/>Experiment Type</span>
});
initialGroupBy = 'award.center_title';
}
return (
<dynamicImports.GroupByController {...{ groupByOptions, initialGroupBy }}>
<dynamicImports.SubmissionStatsViewController {..._.pick(this.props, 'session', 'browseBaseState', 'windowWidth')}>
<dynamicImports.StatsChartViewAggregator aggregationsToChartData={dynamicImports.submissionsAggsToChartData}>
<dynamicImports.SubmissionsStatsView />
</dynamicImports.StatsChartViewAggregator>
</dynamicImports.SubmissionStatsViewController>
</dynamicImports.GroupByController>
);
}
renderUsageSection(){
const { shouldReaggregate } = StatisticsPageView.viewOptions.usage;
const groupByOptions = {
'monthly' : <span>Previous 12 Months</span>,
'daily' : <span>Previous 30 Days</span>
};
return (
<dynamicImports.GroupByController groupByOptions={groupByOptions} initialGroupBy="daily">
<dynamicImports.UsageStatsViewController {..._.pick(this.props, 'session', 'windowWidth', 'href')}>
<dynamicImports.StatsChartViewAggregator {...{ shouldReaggregate }} aggregationsToChartData={dynamicImports.usageAggsToChartData}>
<dynamicImports.UsageStatsView />
</dynamicImports.StatsChartViewAggregator>
</dynamicImports.UsageStatsViewController>
</dynamicImports.GroupByController>
);
}
renderTopMenu(){
const { currentTab } = this.state;
const submissionsObj = StatisticsPageView.viewOptions.submissions;
const usageObj = StatisticsPageView.viewOptions.usage;
return (
<div className="chart-section-control-wrapper row">
<div className="col-sm-6">
<a className={"select-section-btn" + (currentTab === 'submissions' ? ' active' : '')}
href="#submissions" data-tip={currentTab === 'submissions' ? null : submissionsObj.tip} data-target-offset={110}>
{ submissionsObj.icon ? <i className={"mr-07 text-medium icon icon-fw icon-" + submissionsObj.icon}/> : null }
{ submissionsObj.title }
</a>
</div>
<div className="col-sm-6">
<a className={"select-section-btn" + (currentTab === 'usage' ? ' active' : '')}
href="#usage" data-tip={currentTab === 'usage' ? null : usageObj.tip} data-target-offset={100}>
{ usageObj.icon ? <i className={"mr-07 text-medium icon icon-fw icon-" + usageObj.icon}/> : null }
{ usageObj.title }
</a>
</div>
</div>
);
}
render(){
const { currentTab, mounted = false } = this.state;
let body = null;
if (mounted) {
body = currentTab === 'usage' ? this.renderUsageSection() : this.renderSubmissionsSection();
}
return (
<StaticPage.Wrapper>
{ this.renderTopMenu() }
<hr/>
{ body }
</StaticPage.Wrapper>
);
}
} |
src/client/components/shared/Header/Header.js | JoeKarlsson/react-redux-boilerplate | import React from 'react';
import {
NavLink,
} from 'react-router-dom';
import './Header.scss';
const activeStyles = {
color: 'red',
};
const Header = () => {
return (
<div className="header_bar">
<header>
<NavLink className="header_logo" to="/">Home</NavLink>
<ul className="header_nav" role="navigation">
<li><NavLink to="/about" activeStyle={activeStyles}>About</NavLink></li>
</ul>
</header>
</div>
);
};
export default Header;
|
docs/components/components/CardDocumentation.js | nikgraf/belle | import React, { Component } from 'react';
import { Card } from 'belle';
import Code from '../Code';
const basicCodeExample = `<!-- basic card example -->
<Card style={{ borderTop: '1px solid #f2f2f2' }}>
Add any content here like paragraphs, images or other components …
</Card>`;
const imageCodeExample = `<!-- image card example -->
<Card style={{ borderTop: '1px solid #f2f2f2',
width: 265,
padding: '20px 0' }}>
<img src="images/ngorongoro_caldera_small.jpg"
width="100%" />
</Card>`;
export default class CardDocumentation extends Component {
render() {
return (
<div>
<h2 style={{ marginTop: 0, marginBottom: 40 }}>Card</h2>
<Card style={{ borderTop: '1px solid #f2f2f2' }}>
Add any content here like paragraphs, images or other components …
</Card>
<Code value={ basicCodeExample } style={{ marginTop: 40 }} />
<p style={{ marginTop: 40 }}>
<i>Note</i>: The card is designed to work on non-white areas. To provide a
nice appearance on white areas please change the box-shadow or borders.
</p>
<h3>Properties</h3>
<p>
Any property valid for a HTML div like
<span style={{ color: 'grey' }}> style, id, className, …</span>
</p>
<h3>More Examples</h3>
<h4>Card with a full-width image</h4>
<Card style={{ borderTop: '1px solid #f2f2f2',
width: 265,
padding: '20px 0',
}}
>
<img
src="images/ngorongoro_caldera_small.jpg"
width="100%"
/>
</Card>
<Code value={ imageCodeExample } style={{ marginTop: 40 }} />
</div>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/template/src/features/syntax/Promises.js | jdcrensh/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load() {
return Promise.resolve([
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
]);
}
export default class Promises extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
load().then(users => {
this.setState({ users });
});
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-promises">
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
|
src/Main/Fight.js | mwwscott0/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SkullIcon from 'Icons/Skull';
import CancelIcon from 'Icons/Cancel';
import DIFFICULTIES from 'common/DIFFICULTIES';
import ProgressBar from './ProgressBar';
const formatDuration = (duration) => {
const seconds = Math.floor(duration % 60);
return `${Math.floor(duration / 60)}:${seconds < 10 ? `0${seconds}` : seconds}`;
};
const Fight = ({ difficulty, name, kill, start_time, end_time, wipes, fightPercentage, ...others }) => {
const duration = Math.round((end_time - start_time) / 1000);
delete others.boss;
delete others.bossPercentage;
delete others.partial;
delete others.fightPercentage;
delete others.lastPhaseForPercentageDisplay;
const Icon = kill ? SkullIcon : CancelIcon;
return (
<div className="flex" {...others}>
<div className="flex-sub fight-boss-name">
{DIFFICULTIES[difficulty]} {name} {!kill && `(Wipe ${wipes})`}
</div>
<div className={`flex-main ${kill ? 'kill' : 'wipe'}`}>
<Icon style={{ fontSize: '1.8em', display: 'inline-block', marginBottom: '-0.25em' }} />
{' '}{formatDuration(duration)}
<ProgressBar percentage={kill ? 100 : (10000 - fightPercentage) / 100} height={8} />
</div>
</div>
);
};
Fight.propTypes = {
id: PropTypes.number.isRequired,
difficulty: PropTypes.number.isRequired,
boss: PropTypes.number.isRequired,
start_time: PropTypes.number.isRequired,
end_time: PropTypes.number.isRequired,
wipes: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
kill: PropTypes.bool.isRequired,
fightPercentage: PropTypes.number,
};
export default Fight;
|
docs/src/app/components/pages/components/Badge/ExampleContent.js | w01fgang/material-ui | import React from 'react';
import Badge from 'material-ui/Badge';
import IconButton from 'material-ui/IconButton';
import UploadIcon from 'material-ui/svg-icons/file/cloud-upload';
import FolderIcon from 'material-ui/svg-icons/file/folder-open';
const BadgeExampleContent = () => (
<div>
<Badge
badgeContent={<IconButton tooltip="Backup"><UploadIcon /></IconButton>}
>
<FolderIcon />
</Badge>
<Badge
badgeContent="©"
badgeStyle={{fontSize: 20}}
>
Company Name
</Badge>
</div>
);
export default BadgeExampleContent;
|
app/javascript/mastodon/features/public_timeline/index.js | mstdn-jp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { onlyMedia, columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
return {
hasUnread: state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`, 'unread']) > 0,
onlyMedia: (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']),
};
};
@connect(mapStateToProps)
@injectIntl
export default class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('PUBLIC', { other: { onlyMedia } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia) {
const { dispatch, onlyMedia } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia }));
}
handleSettingChanged = (key, checked) => {
const { columnId } = this.props;
if (!columnId && key[0] === 'other' && key[1] === 'onlyMedia') {
this.context.router.history.replace(`/timelines/public${checked ? '/media' : ''}`);
}
}
render () {
const { intl, columnId, hasUnread, multiColumn, onlyMedia } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer onChange={this.handleSettingChanged} columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />}
/>
</Column>
);
}
}
|
examples/counter/WrangledCounter.js | limscoder/react-wrangler | import React from 'react';
import Path from '../../src/Path';
import Counter from './Counter';
const counterPath = 'counter.current';
function LoadingCounter(props) {
return (
<div style={{ margin: '20px' }}>
{
typeof props.count === 'undefined' ?
<span>simulating async operation...</span> : <Counter {...props} />
}
</div>
);
}
LoadingCounter.propTypes = Counter.propTypes;
function onIncrement(store) {
store.setPath(counterPath, store.getPath(counterPath) + 1);
}
function onDecrement(store) {
store.setPath(counterPath, store.getPath(counterPath) - 1);
}
function onReset(store) {
store.setPath(counterPath, 0);
}
export default function WrangledCounter() {
// map path values to prop names
const mapPathsToProps = { count: counterPath };
// map callback functions to prop names
const mapCallbacksToProps = {
onIncrement,
onDecrement,
onReset,
};
return (
<Path component={LoadingCounter}
mapPathsToProps={mapPathsToProps}
mapCallbacksToProps={mapCallbacksToProps} />
);
}
|
src/main.js | dannyrdalton/example_react_redux_form_builder | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.__INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
console.error(error)
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
client/util/react-intl-test-helper.js | Hitzk0pf/BetterBackPacking | /**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme';
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('../../Intl/localizationData/en');
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
export const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
const nodeWithIntlProp = node => {
return React.cloneElement(node, { intl });
};
export const shallowWithIntl = node => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
};
export const mountWithIntl = node => {
return mount(nodeWithIntlProp(node), {
context: { intl },
childContextTypes: { intl: intlShape },
});
};
|
app/routes.js | arixse/ReactNeteaseCloudMusic | import React from 'react';
import { Router, Route, IndexRoute, Redirect } from 'react-router';
import Cloud from './containers/Cloud';
import CloudDetail from './containers/CloudDetail';
import SearchBar from './containers/SearchBar';
import PlayDetail from './containers/PlayDetail';
import Header from './containers/Header';
export default (
<Router>
<Route path="/" component={Cloud}>
<IndexRoute component={Header} />
<Route path="/detail/:title" component={CloudDetail} />
<Route path="/search" component={SearchBar} />
<Route path="/play/:id" component={PlayDetail} />
<Redirect from="*" to="/" />
</Route>
</Router>
);
|
templates/frontOffice/modern/components/React/ErrorBoundary/index.js | lopes-vincent/thelia | import Alert from '../Alert';
import React from 'react';
export default class ErrorBoundary extends React.Component {
constructor() {
super();
this.state = {
error: null
};
}
componentDidCatch(error) {
console.error(error);
this.setState({ error });
}
render() {
if (this.state.error) {
if (typeof this.props.fallback === 'function') {
return this.props.fallback(this.state.error?.message);
} else if (this.props.fallback) {
return this.props.fallback;
}
return <Alert type="error" title="Error" />;
}
return this.props.children;
}
}
|
srcjs/components/notification.js | spapas/react-tutorial | import React from 'react';
import { Notification } from 'react-notification';
import { connect } from 'react-redux'
import { hideNotification } from '../actions'
import * as colors from '../util/colors'
const NotificationContainer = (props) => {
let { message, notification_type } = props.notification;
let { onHide } = props;
let isActive = message?true:false;
let color;
switch(notification_type) {
case 'SUCCESS':
color = colors.success
break;
case 'ERROR':
color = colors.danger
break;
case 'INFO':
color = colors.info
break;
}
return <Notification
isActive={isActive}
message={message?message:''}
dismissAfter={5000}
onDismiss={ ()=>onHide() }
action='X'
onClick={ ()=>onHide() }
style={{
bar: {
background: color,
color: 'black',
fontSize: '2rem',
},
active: {
left: '3rem',
},
action: {
color: '#FFCCBC',
fontSize: '3rem',
border: '1 pt solid black'
}
}}
/>
}
let mapStateToProps = state => ({
notification: state.notification
})
let mapDispatchToProps = dispatch => ({
onHide: () => {
dispatch(hideNotification())
}
})
export default connect(mapStateToProps, mapDispatchToProps)(NotificationContainer);
|
app/javascript/mastodon/features/notifications/components/notification.js | PlantsNetwork/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusContainer from '../../../containers/status_container';
import AccountContainer from '../../../containers/account_container';
import { FormattedMessage } from 'react-intl';
import Permalink from '../../../components/permalink';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
export default class Notification extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
};
handleMoveUp = () => {
const { notification, onMoveUp } = this.props;
onMoveUp(notification.get('id'));
}
handleMoveDown = () => {
const { notification, onMoveDown } = this.props;
onMoveDown(notification.get('id'));
}
handleOpen = () => {
const { notification } = this.props;
if (notification.get('status')) {
this.context.router.history.push(`/statuses/${notification.get('status')}`);
} else {
this.handleOpenProfile();
}
}
handleOpenProfile = () => {
const { notification } = this.props;
this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`);
}
handleMention = e => {
e.preventDefault();
const { notification, onMention } = this.props;
onMention(notification.get('account'), this.context.router.history);
}
getHandlers () {
return {
moveUp: this.handleMoveUp,
moveDown: this.handleMoveDown,
open: this.handleOpen,
openProfile: this.handleOpenProfile,
mention: this.handleMention,
reply: this.handleMention,
};
}
renderFollow (account, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-follow focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-user-plus' />
</div>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</div>
<AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderMention (notification) {
return (
<StatusContainer
id={notification.get('status')}
withDismiss
hidden={this.props.hidden}
onMoveDown={this.handleMoveDown}
onMoveUp={this.handleMoveUp}
/>
);
}
renderFavourite (notification, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-favourite focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-star star-icon' />
</div>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} />
</div>
</HotKeys>
);
}
renderReblog (notification, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-reblog focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-retweet' />
</div>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
}
return null;
}
}
|
demo/layout/Higlight.js | f0zze/rosemary-ui | import hljs from 'highlight.js';
import React from 'react';
import ReactDOM from 'react-dom';
const Highlight = React.createClass({
getDefaultProps: function() {
return {
innerHTML: false,
className: null
};
},
componentDidMount: function() {
this.highlightCode();
},
componentDidUpdate: function() {
this.highlightCode();
},
highlightCode: function() {
let domNode = ReactDOM.findDOMNode(this);
let nodes = domNode.querySelectorAll('pre code');
if (nodes.length > 0) {
for (let i = 0; i < nodes.length; i=i+1) {
hljs.highlightBlock(nodes[i]);
}
}
},
render: function() {
if (this.props.innerHTML) {
return <div dangerouslySetInnerHTML={{__html: this.props.children}} className={this.props.className || null}></div>;
} else {
return <pre><code className={this.props.className}>{this.props.children}</code></pre>;
}
}
});
export default Highlight;
|
sample-app/src/App.js | opentok/accelerator-core-js | /* Let CRA handle linting for sample app */
import React, { Component } from 'react';
import Spinner from 'react-spinner';
import classNames from 'classnames';
import 'opentok-solutions-css';
import Core from './ot-core/core';
import logo from './logo.svg';
import config from './config.json';
import './App.css';
let otCore;
const otCoreOptions = {
credentials: {
apiKey: config.apiKey,
sessionId: config.sessionId,
token: config.token,
},
// A container can either be a query selector or an HTML Element
streamContainers(pubSub, type, data, streamId) {
return {
publisher: {
camera: '#cameraPublisherContainer',
screen: '#screenPublisherContainer',
},
subscriber: {
camera: '#cameraSubscriberContainer',
screen: '#screenSubscriberContainer',
},
}[pubSub][type];
},
controlsContainer: '#controls',
packages: ['textChat', 'screenSharing', 'annotation'],
communication: {
callProperites: null, // Using default
},
textChat: {
name: ['David', 'Paul', 'Emma', 'George', 'Amanda'][Math.random() * 5 | 0], // eslint-disable-line no-bitwise
waitingMessage: 'Messages will be delivered when other users arrive',
container: '#chat',
},
screenSharing: {
extensionID: config.extensionID,
annotation: true,
externalWindow: false,
dev: true,
screenProperties: {
insertMode: 'append',
width: '100%',
height: '100%',
showControls: false,
style: {
buttonDisplayMode: 'off',
},
videoSource: 'window',
fitMode: 'contain' // Using default
},
},
annotation: {
absoluteParent: {
publisher: '.App-video-container',
subscriber: '.App-video-container'
}
},
};
/**
* Build classes for container elements based on state
* @param {Object} state
*/
const containerClasses = (state) => {
const { active, meta, localAudioEnabled, localVideoEnabled } = state;
const sharingScreen = meta ? !!meta.publisher.screen : false;
const viewingSharedScreen = meta ? meta.subscriber.screen : false;
const activeCameraSubscribers = meta ? meta.subscriber.camera : 0;
const activeCameraSubscribersGt2 = activeCameraSubscribers > 2;
const activeCameraSubscribersOdd = activeCameraSubscribers % 2;
const screenshareActive = viewingSharedScreen || sharingScreen;
return {
controlClass: classNames('App-control-container', { hidden: !active }),
localAudioClass: classNames('ots-video-control circle audio', { hidden: !active, muted: !localAudioEnabled }),
localVideoClass: classNames('ots-video-control circle video', { hidden: !active, muted: !localVideoEnabled }),
localCallClass: classNames('ots-video-control circle end-call', { hidden: !active }),
cameraPublisherClass: classNames('video-container', { hidden: !active, small: !!activeCameraSubscribers || screenshareActive, left: screenshareActive }),
screenPublisherClass: classNames('video-container', { hidden: !active || !sharingScreen }),
cameraSubscriberClass: classNames('video-container', { hidden: !active || !activeCameraSubscribers },
{ 'active-gt2': activeCameraSubscribersGt2 && !screenshareActive },
{ 'active-odd': activeCameraSubscribersOdd && !screenshareActive },
{ small: screenshareActive }
),
screenSubscriberClass: classNames('video-container', { hidden: !viewingSharedScreen || !active }),
};
};
const connectingMask = () =>
<div className="App-mask">
<Spinner />
<div className="message with-spinner">Connecting</div>
</div>;
const startCallMask = start =>
<div className="App-mask">
<button className="message button clickable" onClick={start}>Click to Start Call </button>
</div>;
class App extends Component {
constructor(props) {
super(props);
this.state = {
connected: false,
active: false,
publishers: null,
subscribers: null,
meta: null,
localAudioEnabled: true,
localVideoEnabled: true,
};
this.startCall = this.startCall.bind(this);
this.endCall = this.endCall.bind(this);
this.toggleLocalAudio = this.toggleLocalAudio.bind(this);
this.toggleLocalVideo = this.toggleLocalVideo.bind(this);
}
componentDidMount() {
otCore = new Core(otCoreOptions);
otCore.connect().then(() => this.setState({ connected: true }));
const events = [
'subscribeToCamera',
'unsubscribeFromCamera',
'subscribeToScreen',
'unsubscribeFromScreen',
'startScreenShare',
'endScreenShare',
];
events.forEach(event => otCore.on(event, ({ publishers, subscribers, meta }) => {
this.setState({ publishers, subscribers, meta });
}));
}
startCall() {
otCore.startCall()
.then(({ publishers, subscribers, meta }) => {
this.setState({ publishers, subscribers, meta, active: true });
}).catch(error => console.log(error));
}
endCall() {
otCore.endCall();
this.setState({ active: false });
}
toggleLocalAudio() {
otCore.toggleLocalAudio(!this.state.localAudioEnabled);
this.setState({ localAudioEnabled: !this.state.localAudioEnabled });
}
toggleLocalVideo() {
otCore.toggleLocalVideo(!this.state.localVideoEnabled);
this.setState({ localVideoEnabled: !this.state.localVideoEnabled });
}
render() {
const { connected, active } = this.state;
const {
localAudioClass,
localVideoClass,
localCallClass,
controlClass,
cameraPublisherClass,
screenPublisherClass,
cameraSubscriberClass,
screenSubscriberClass,
} = containerClasses(this.state);
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>OpenTok Accelerator Core</h1>
</div>
<div className="App-main">
<div className="App-video-container">
{ !connected && connectingMask() }
{ connected && !active && startCallMask(this.startCall)}
<div id="cameraPublisherContainer" className={cameraPublisherClass} />
<div id="screenPublisherContainer" className={screenPublisherClass} />
<div id="cameraSubscriberContainer" className={cameraSubscriberClass} />
<div id="screenSubscriberContainer" className={screenSubscriberClass} />
</div>
<div id="controls" className={controlClass}>
<div className={localAudioClass} onClick={this.toggleLocalAudio} />
<div className={localVideoClass} onClick={this.toggleLocalVideo} />
<div className={localCallClass} onClick={this.endCall} />
</div>
<div id="chat" className="App-chat-container" />
</div>
</div>
);
}
}
export default App;
|
packages/reactor-tests/src/tests/rel/RelDialog.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Dialog, Button } from '@extjs/ext-react';
export default class RelDialog extends Component {
state = {
displayed: true
}
close = () => {
this.setState({ displayed: false });
}
render() {
return (
<Dialog itemId="dialog" displayed={this.state.displayed} title="Dialog">
<Button text="Button" itemId="button" handler={this.close}/>
</Dialog>
);
}
} |
information/blendle-frontend-react-source/app/containers/navigation/NavigationBarContainer.js | BramscoChill/BlendleParser | import React, { Component } from 'react';
import altConnect from 'higher-order-components/altConnect';
import { isExpired } from 'selectors/subscriptions';
import DefaultNavigationBar from 'components/navigation/DefaultNavigationBar';
import AuthStore from 'stores/AuthStore';
import ModuleNavigationStore from 'stores/ModuleNavigationStore';
import PremiumSubscriptionStore from 'stores/PremiumSubscriptionStore';
class NavigationBarContainer extends Component {
state = {
searchOpen: false,
};
onToggleSearch = () => {
this.setState({ searchOpen: !this.state.searchOpen });
};
render() {
const searchOpen = this.state.searchOpen;
return (
<DefaultNavigationBar
{...this.props}
searchOpen={searchOpen}
onToggleSearch={this.onToggleSearch}
/>
);
}
}
function mapStateToProps(
{
authState: { user },
premiumSubscriptionState: { subscription },
moduleNavigationState: { activeModule },
},
{ searchOpen },
) {
const isLoggedIn = Boolean(user);
return {
isLoggedIn,
searchOpen,
hasPremiumSubscription: subscription ? !isExpired(subscription) : false,
isOnSearchRoute: activeModule === 'search',
};
}
mapStateToProps.stores = { AuthStore, PremiumSubscriptionStore, ModuleNavigationStore };
export default altConnect(mapStateToProps)(NavigationBarContainer);
// WEBPACK FOOTER //
// ./src/js/app/containers/navigation/NavigationBarContainer.js |
src/components/TrendAnalysis/SearchSiteSelect.js | wrleskovec/thoughtcrime | import React from 'react';
import _ from 'lodash';
export default class SearchSiteSelect extends React.Component {
constructor(props) {
super(props);
this.onFocus = this.onFocus.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onSelectSite = this.onSelectSite.bind(this);
this.onKeyUp = _.debounce(this.onKeyUp.bind(this), 100);
}
onFocus(e) {
if (e.target.value.trim() !== '') {
const { listGroup } = this.refs;
listGroup.style.display = 'block';
}
}
onBlur() {
// onBlur has a race condition with onClick so it needs to be delayed
setTimeout(() => {
const { listGroup } = this.refs;
listGroup.style.display = 'none';
}, 100);
}
onKeyUp() {
const { handleOnChange } = this.props;
const { searchField, listGroup } = this.refs;
const value = searchField.value.trim();
if (value) {
listGroup.style.display = 'block';
handleOnChange(value);
}
}
onSelectSite(e) {
const { handleAddSite } = this.props;
const siteName = e.target.innerHTML.trim();
handleAddSite(siteName);
}
render() {
const { searchResults } = this.props;
return (
<div className="col-md-6">
<div className="dropdown-search">
<label htmlFor="siteSearchDropDown">Add Site: </label>
<div id="siteSearchDropDown" className="form-group">
<input
type="text" className="form-control" onFocus={this.onFocus}
onKeyUp={this.onKeyUp} onBlur={this.onBlur} ref="searchField"
/>
</div>
<ul className="list-group" ref="listGroup">
{searchResults.map(site => (
<li className="list-group-item">
<a onClick={this.onSelectSite}>{site}</a>
</li>
))}
</ul>
</div>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.