path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
app/components/TeamManagement/index.js | seanng/web-server | /**
*
* TeamManagement
*
*/
import React from 'react';
// import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
function TeamManagement() {
return (
<div>
<FormattedMessage {...messages.header} />
</div>
);
}
TeamManagement.propTypes = {
};
export default TeamManagement;
|
app/components/List/index.js | iPhaeton/Selectors-study | import React from 'react';
import Ul from './Ul';
import Wrapper from './Wrapper';
function List(props) {
const ComponentToRender = props.component;
let content = (<div></div>);
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) => (
<ComponentToRender key={`item-${index}`} item={item} />
));
} else {
// Otherwise render a single component
content = (<ComponentToRender />);
}
return (
<Wrapper>
<Ul>
{content}
</Ul>
</Wrapper>
);
}
List.propTypes = {
component: React.PropTypes.func.isRequired,
items: React.PropTypes.array,
};
export default List;
|
src/containers/rulelistContainer.js | koromiko/Repeat | import React from 'react'
import RuleList from '../components/ruleList'
class RulelistContainer extends React.Component {
constructor(props){
super();
this.handleRuleHover = this.handleRuleHover.bind(this);
this.handleRuleSelected = this.handleRuleSelected.bind(this);
}
handleRuleHover(ruleID){
}
handleRuleSelected(ruleID){
const { ruleList } = this.props;
const { reActivated } = this.props;
if( ruleID ){
let obj = ruleList.find( (x)=>{return x.id===ruleID} );
reActivated(obj.re);
}else{
reActivated(undefined)
}
}
render () {
const { activatedReTexts, ruleList } = this.props;
return (<div>
<RuleList rulsList={ruleList}
handleRuleHover={this.handleRuleHover}
handleRuleSelected={this.handleRuleSelected}
activatedReTexts={activatedReTexts}
/>
</div>)
}
}
export default RulelistContainer;
|
packages/react-devtools-shell/src/app/InspectableElements/SimpleValues.js | TheBlasfem/react | /**
* 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.
*
* @flow
*/
import React from 'react';
export default function SimpleValues() {
return (
<ChildComponent
string="abc"
emptyString=""
number={123}
undefined={undefined}
null={null}
nan={NaN}
infinity={Infinity}
true={true}
false={false}
/>
);
}
function ChildComponent(props: any) {
return null;
}
|
shared/routes.js | WillHearn/apoc | import { Route, IndexRoute } from 'react-router';
import React from 'react';
import App from './container/App';
import PostContainer from './container/PostContainer/PostContainer';
import PostDetailView from './container/PostDetailView/PostDetailView';
const routes = (
<Route path="/" component={App} >
<IndexRoute component={PostContainer} />
<Route path="/post/:slug" component={PostDetailView}/>
</Route>
);
export default routes;
|
src/common/TraceResult/TraceResult.js | Syncano/syncano-dashboard | import React from 'react';
const styles = {
root: {
padding: 25,
color: '#fff',
whiteSpace: 'pre-wrap',
font: '12px/normal \'Monaco\', monospace',
backgroundColor: '#4C4A43'
},
errorContainer: {
borderTop: '1px solid rgba(255, 255, 255, .1)'
}
};
const TraceResult = ({ result, error, style, ...other }) => {
const renderError = () => {
if (error) {
return (
<div
className="vm-2-t vp-2-t"
style={styles.errorContainer}
>
{error}
</div>
);
}
return null;
};
return (
<div
{...other}
style={{ ...styles.root, ...style }}
>
<div>{result}</div>
{renderError()}
</div>
);
};
export default TraceResult;
|
src/components/TilesPanel.js | longyarnz/WelFurnish-E-Commerce | import React, { Component } from 'react';
import TilesContainer from './TilesContainer';
export default class TilesPanel extends Component {
render() {
return (
<section className="tile-panel">
<div className="block">
<TilesContainer tilesList={this.props.tilesList} />
</div>
</section>
);
}
}
|
app/components/TextSpanner/components/Spanner.js | Goodly/TextThresher | import React from 'react';
import PropTypes from 'prop-types';
import { EditorState } from '../model/EditorState';
import { DisplayState } from '../model/DisplayState';
const debug = require('debug')('thresher:TextSpanner');
export class Spanner extends React.Component {
constructor(props) {
super(props);
}
static propTypes = {
editorState: PropTypes.instanceOf(EditorState).isRequired,
displayState: PropTypes.instanceOf(DisplayState).isRequired,
blockPropsFn: PropTypes.func,
mergeStyleFn: PropTypes.func,
wrapSpanFn: PropTypes.func,
}
static defaultProps = {
blockPropsFn: ((block, sequence_number) => {}),
mergeStyleFn: ((orderedLayers) => {}),
wrapSpanFn: ((span) => span)
};
render() {
const editorState = this.props.editorState;
const displayState = this.props.displayState;
const blockPropsFn = this.props.blockPropsFn;
const mergeStyleFn = this.props.mergeStyleFn;
const wrapSpanFn = this.props.wrapSpanFn;
const text = editorState.getText();
function renderSpans(block) {
let spans = editorState.getSpans(block);
return (spans.map( (span, i) => {
let orderedLayers = displayState.getOrderedLayersFor(span.spanAnnotations);
let mergedStyle = mergeStyleFn(orderedLayers);
return (wrapSpanFn(
<span key={span.key}
data-offset-start={span.start}
data-offset-end={span.end}
style={mergedStyle}>
{text.substring(span.start, span.end)}
</span>,
orderedLayers
));
}));
};
function renderBlock(block, i) {
const mergeProps = blockPropsFn(block, i);
return React.cloneElement(
<div key={block.key}
data-offset-start={block.start}
data-offset-end={block.end}>
{renderSpans(block)}
</div>,
mergeProps
);
};
return (
<div>
{displayState.getBlockList().map( (block, i) => {
return renderBlock(block, i);
})}
</div>
);
}
}
|
app/modules/humnos/components/Lists.bak.js | arizto/humnos-mobile | 'use strict';
import React, { Component } from 'react';
import { InteractionManager, View, ListView, VirtualizedList, Text, ActivityIndicator, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { List } from 'immutable';
import * as configs from '../../../constants/configs';
import { connect } from 'react-redux';
import BackButton from '../../../components/icons/BackButton';
import EmptyItem from '../../../components/EmptyItem';
import Row from './Row';
import Detail from './Detail';
class Lists extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerLeft: (
<BackButton onPress={() => navigation.goBack()} color={configs.color.font.accent}/>
),
}
}
constructor(props) {
super(props);
this.state = {
ds : new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
getRowData: (dataBlob, sID, rID) => dataBlob[sID].get(rID)
}),
//data: List([]),
data: [],
loading: true,
loadingFooter: false,
loading2: false,
}
this.requestAnimationFrame = requestAnimationFrame.bind(this);
this.goToDetail = this.goToDetail.bind(this);
this.renderFooter = this.renderFooter.bind(this);
this.renderItem = this.renderItem.bind(this);
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.setState({
loading: false,
loadingFooter: false,
//data: this.props.humnos.get('lists'),
data: this.props.humnos.get('lists').toArray()
//ds: this.state.ds.cloneWithRows(this.props.humnos.get('lists'), this.props.humnos.get('lists').keySeq().toArray())
});
});
}
componentWillReceiveProps(nextProps) {
if( nextProps.lagu.get('status') === 'GET_LIST_DONE' )
{
this.requestAnimationFrame(() => {
this.setState({
loading: false,
loadingFooter: false,
ds: this.state.ds.cloneWithRows(nextProps.lagu.get('lists'), nextProps.lagu.get('lists').keySeq().toArray())
});
});
}
}
goToDetail(item, index) {
InteractionManager.runAfterInteractions(() => {
this.props.toRoute({
name: 'Detail',
component: Detail,
hideNavigationBar: true,
passProps: { item: item, current_index: index }
})
});
}
renderFooter() {
return <View style={{paddingBottom: 50}} />;
}
renderRow = (item: Object, sectionID, rowID) => {
var background = ( item.id % 2 ) === 0 ? '#FFFFFF' : '#FAFAFA';
return (
<Row key={rowID} background={background} data={item} onPress={() => this.goToDetail(item, rowID) } />
);
};
renderItem({ item, index }) {
//console.log(item);
var background = ( index % 2 ) === 0 ? '#FFFFFF' : '#FAFAFA';
return (
<Row key={index} background={background} data={item} onPress={() => this.goToDetail(item, rowID) } />
);
}
getValueFromKey(key, data) {
return data.get ? data.get(key) : data[key];
}
render() {
if( !this.state.loading )
{
/*
var content = (this.state.ds.getRowCount() === 0) ?
<EmptyItem text="Belum ada lagu"/> :
<ListView
style={styles.contentContainer}
initialListSize={10}
scrollRenderAheadDistance={250}
pageSize={10}
removeClippedSubviews={true}
dataSource={this.state.ds}
renderRow={this.renderRow}
renderFooter={this.renderFooter}/>;
*/
var content = (this.props.humnos.get('lists').size === 0) ?
<EmptyItem text="Belum ada lagu"/> :
<VirtualizedList
style={styles.contentContainer}
initialNumToRender={10}
maxToRenderPerBatch={10}
data={this.state.data}
//getItem={(items, index) => this.getValueFromKey(index, items)}
getItemCount={(items) => (items.size || items.length || 0)}
keyExtractor={(item, index) => String(index)}
renderItem={this.renderItem}
renderFooter={this.renderFooter}/>;
return (
<View style={styles.container}>
{content}
</View>
);
}
return (
<View style={configs.styles.center}>
<ActivityIndicator size="large" style={[configs.styles.center, configs.styles.large]} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E0E0E0'
},
contentContainer: {
marginTop: 5
}
});
export default connect(state => ({
humnos: state.get('humnos')
})
)(Lists);
|
docs/src/app/components/pages/components/AppBar/Page.js | lawrence-yu/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import appBarReadmeText from './README';
import AppBarExampleIcon from './ExampleIcon';
import appBarExampleIconCode from '!raw!./ExampleIcon';
import AppBarExampleIconButton from './ExampleIconButton';
import appBarExampleIconButtonCode from '!raw!./ExampleIconButton';
import AppBarExampleComposition from './ExampleComposition';
import appBarExampleIconComposition from '!raw!./ExampleComposition';
import appBarCode from '!raw!material-ui/AppBar/AppBar';
const AppBarPage = () => (
<div>
<Title render={(previousTitle) => `App Bar - ${previousTitle}`} />
<MarkdownElement text={appBarReadmeText} />
<CodeExample
code={appBarExampleIconCode}
title="Simple example"
>
<AppBarExampleIcon />
</CodeExample>
<CodeExample
code={appBarExampleIconButtonCode}
title="Buttons example"
>
<AppBarExampleIconButton />
</CodeExample>
<CodeExample
code={appBarExampleIconComposition}
title="Composition example"
>
<AppBarExampleComposition />
</CodeExample>
<PropTypeDescription code={appBarCode} />
</div>
);
export default AppBarPage;
|
src/client/components/navbar.js | peppesilletti/webpack-project | import React from 'react'
import { NavLink } from 'react-router-dom'
const Navbar = () => {
return(
<nav style={{ "width": "100%", "backgroundColor": 'grey' }}>
<button><NavLink to="/">Go To Home Route</NavLink></button>
<button><NavLink to="/test">Go To Test Route</NavLink></button>
<span><strong>THIS NAVBAR CAN BE CHANGED WITH WATHEVER YOU LIKE FOR NAVIGATION</strong></span>
</nav>
)
}
export default Navbar
|
packages/react-router-website/modules/components/App.js | justjavac/react-router-CN | import React from 'react'
// don't want the shimmed one
// eslint-disable-next-line
import BrowserRouter from '../../../react-router-dom/BrowserRouter'
// this stuff is shimmed, see ReactRouterDOMShim.js for more details
import { Switch, Route } from 'react-router-dom'
import DelegateMarkdownLinks from './DelegateMarkdownLinks'
import Home from './Home'
import Environment from './Environment'
const base = document.querySelector('base')
const baseHref = base ? base.getAttribute('href') : '/'
const App = () => (
<BrowserRouter basename={baseHref.replace(/\/$/, '')}>
<DelegateMarkdownLinks>
<Switch>
<Route path="/" exact={true} component={Home}/>
<Route path="/:environment" component={Environment}/>
</Switch>
</DelegateMarkdownLinks>
</BrowserRouter>
)
export default App
|
src/Chip.js | gregchamberlain/react-chips | import React from 'react'
import PropTypes from 'prop-types';
import Radium from 'radium';
import themeable from 'react-themeable';
import { chipTheme } from './theme';
const Chip = ({ selected, theme, onRemove, children }) => {
// if someone provided a theme, try and merge between the original and provided
const mergedTheme = deepMerge(chipTheme, theme);
const themr = themeable(mergedTheme);
return (
<div {...themr(1, 'chip', selected ? 'chipSelected' : '')}>
{children}
<span
{...themr(2, 'chipRemove')}
onClick={onRemove}> ×</span>
</div>
);
}
Chip.propTypes = {
theme: PropTypes.object,
selected: PropTypes.bool,
onRemove: PropTypes.func,
}
Chip.defaultProps = {
theme: chipTheme,
selected: false,
}
// from https://stackoverflow.com/a/49798508/1824521
const deepMerge = (...sources) => {
let acc = {}
for (const source of sources) {
if (source instanceof Array) {
if (!(acc instanceof Array)) {
acc = []
}
acc = [...acc, ...source]
} else if (source instanceof Object) {
for (let [key, value] of Object.entries(source)) {
if (value instanceof Object && key in acc) {
value = deepMerge(acc[key], value)
}
acc = { ...acc, [key]: value }
}
}
}
return acc
}
export default Radium(Chip);
|
src/users/Student.js | GoldStarPDX/GoldStar | import React, { Component } from 'react';
import Header from '../app/Header';
import { Switch, Route } from 'react-router-dom';
import ProfileContainer from '../profile/ProfileContainer';
export default class Student extends Component {
render() {
const { status } = this.props;
return (
<div>
<Header />
<Switch>
<Route exact path="/Student" render={() => <ProfileContainer status={status} />} />
</Switch>
</div>
);
}
} |
pages/error/index.js | GoldenCrow/productforge-dementia-app | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import history from '../../core/history';
import Link from '../../components/Link';
import s from './styles.css';
class ErrorPage extends React.Component {
static propTypes = {
error: React.PropTypes.object,
};
componentDidMount() {
document.title = this.props.error && this.props.error.status === 404 ?
'Page Not Found' : 'Error';
}
goBack = event => {
event.preventDefault();
history.goBack();
};
render() {
if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console
const [code, title] = this.props.error && this.props.error.status === 404 ?
['404', 'Page not found'] :
['Error', 'Oups, something went wrong'];
return (
<div className={s.container}>
<main className={s.content}>
<h1 className={s.code}>{code}</h1>
<p className={s.title}>{title}</p>
{code === '404' &&
<p className={s.text}>
The page you're looking for does not exist or an another error occurred.
</p>
}
<p className={s.text}>
<a href="/" onClick={this.goBack}>Go back</a>, or head over to the
<Link to="/">home page</Link> to choose a new direction.
</p>
</main>
</div>
);
}
}
export default ErrorPage;
|
src/components/common/svg-icons/action/loyalty.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLoyalty = (props) => (
<SvgIcon {...props}>
<path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7zm11.77 8.27L13 19.54l-4.27-4.27C8.28 14.81 8 14.19 8 13.5c0-1.38 1.12-2.5 2.5-2.5.69 0 1.32.28 1.77.74l.73.72.73-.73c.45-.45 1.08-.73 1.77-.73 1.38 0 2.5 1.12 2.5 2.5 0 .69-.28 1.32-.73 1.77z"/>
</SvgIcon>
);
ActionLoyalty = pure(ActionLoyalty);
ActionLoyalty.displayName = 'ActionLoyalty';
ActionLoyalty.muiName = 'SvgIcon';
export default ActionLoyalty;
|
react-flux-mui/js/material-ui/src/svg-icons/notification/network-locked.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationNetworkLocked = (props) => (
<SvgIcon {...props}>
<path d="M19.5 10c.17 0 .33.03.5.05V1L1 20h13v-3c0-.89.39-1.68 1-2.23v-.27c0-2.48 2.02-4.5 4.5-4.5zm2.5 6v-1.5c0-1.38-1.12-2.5-2.5-2.5S17 13.12 17 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z"/>
</SvgIcon>
);
NotificationNetworkLocked = pure(NotificationNetworkLocked);
NotificationNetworkLocked.displayName = 'NotificationNetworkLocked';
NotificationNetworkLocked.muiName = 'SvgIcon';
export default NotificationNetworkLocked;
|
src/components/App.js | Marsellus47/parking | import React from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import NotFoundPage from './common/NotFoundPage';
import Header from './common/Header';
import HomePage from './home/HomePage';
import SearchPage from './search/SearchPage';
import AddPage from './add/AddPage';
import LoginPage from './account/LoginPage';
class App extends React.Component {
render() {
return (
<Router>
<div>
<Header />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/search" component={SearchPage} />
<Route path="/add" component={AddPage} />
<Route path="/login" component={LoginPage} />
<Route component={NotFoundPage}/>
</Switch>
</div>
</Router>
);
}
}
export default App; |
packages/mineral-ui-icons/src/IconCropSquare.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 IconCropSquare(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H6V6h12v12z"/>
</g>
</Icon>
);
}
IconCropSquare.displayName = 'IconCropSquare';
IconCropSquare.category = 'image';
|
docs/src/Root.js | omerts/react-bootstrap | import React from 'react';
import Router from 'react-router';
const Root = React.createClass({
statics: {
/**
* Get the list of pages that are renderable
*
* @returns {Array}
*/
getPages() {
return [
'index.html',
'introduction.html',
'getting-started.html',
'components.html',
'support.html'
];
}
},
getDefaultProps() {
return {
assetBaseUrl: ''
};
},
childContextTypes: {
metadata: React.PropTypes.object
},
getChildContext(){
return { metadata: this.props.propData };
},
render() {
// Dump out our current props to a global object via a script tag so
// when initialising the browser environment we can bootstrap from the
// same props as what each page was rendered with.
let browserInitScriptObj = {
__html:
`window.INITIAL_PROPS = ${JSON.stringify(this.props)};
// console noop shim for IE8/9
(function (w) {
var noop = function () {};
if (!w.console) {
w.console = {};
['log', 'info', 'warn', 'error'].forEach(function (method) {
w.console[method] = noop;
});
}
}(window));`
};
let head = {
__html: `<title>React-Bootstrap</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet">
<link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>
<![endif]-->`
};
return (
<html>
<head dangerouslySetInnerHTML={head} />
<body>
<Router.RouteHandler propData={this.props.propData} />
<script dangerouslySetInnerHTML={browserInitScriptObj} />
<script src={`${this.props.assetBaseUrl}/assets/bundle.js`} />
</body>
</html>
);
}
});
export default Root;
|
client/containers/HomePage/__tests__/Components/Header.spec.js | Vandivier/document-hello-world-docker-test | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { FormattedMessage } from 'react-intl';
import { Header } from '../../components/Header/Header';
import { intl } from '../../../../util/react-intl-test-helper';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
test('renders the header properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.truthy(wrapper.find('Link').first().containsMatchingElement(<FormattedMessage id="siteTitle" />));
t.is(wrapper.find('a').length, 1);
});
test('doesn\'t add post in pages other than home', t => {
const router = {
isActive: sinon.stub().returns(false),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.is(wrapper.find('a').length, 0);
});
test('toggleAddPost called properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const toggleAddPost = sinon.spy();
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={toggleAddPost} />,
{
context: {
router,
intl,
},
}
);
wrapper.find('a').first().simulate('click');
t.truthy(toggleAddPost.calledOnce);
});
|
src/ActionViewer.js | soup-js/omnistream | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { reactiveComponent } from './reactiveComponent.js';
const STYLE = {
'wordWrap': 'break-word',
'border': '1px solid rgb(235, 235, 235)',
'padding': '5px',
'bottom': '80',
'position': 'relative',
'minHeight': '20px',
'maxWidth': '900px',
'fontSize': '1.15em',
'backgroundColor': '#fefefe',
}
function ActionViewer(props) {
const {action} = props;
return (
<div className='timeline-action' style={STYLE}>
<span>{JSON.stringify(action)}</span>
</div>
)
}
export default reactiveComponent(ActionViewer, 'draggingState$'); |
Libraries/Components/MapView/MapView.js | tgoldenberg/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule MapView
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const Image = require('Image');
const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');
const processColor = require('processColor');
const resolveAssetSource = require('resolveAssetSource');
const requireNativeComponent = require('requireNativeComponent');
type Event = Object;
/**
* State an annotation on the map.
*/
export type AnnotationDragState = $Enum<{
/**
* Annotation is not being touched.
*/
idle: string,
/**
* Annotation dragging has began.
*/
starting: string,
/**
* Annotation is being dragged.
*/
dragging: string,
/**
* Annotation dragging is being canceled.
*/
canceling: string,
/**
* Annotation dragging has ended.
*/
ending: string,
}>;
/**
* **This component is only supported on iOS.**
*
* `MapView` is used to display embeddable maps and annotations using
* `MKMapView`.
*
* For a cross-platform solution, check out
* [react-native-maps](https://github.com/airbnb/react-native-maps)
* by Airbnb.
*
* ```
* import React, { Component } from 'react';
* import { MapView } from 'react-native';
*
* class MapMyRide extends Component {
* render() {
* return (
* <MapView
* style={{height: 200, margin: 40}}
* showsUserLocation={true}
* />
* );
* }
* }
* ```
*
*/
const MapView = React.createClass({
mixins: [NativeMethodsMixin],
propTypes: {
...View.propTypes,
/**
* Used to style and layout the `MapView`.
*/
style: View.propTypes.style,
/**
* If `true` the app will ask for the user's location and display it on
* the map. Default value is `false`.
*
* **NOTE**: You'll need to add the `NSLocationWhenInUseUsageDescription`
* key in Info.plist to enable geolocation, otherwise it will fail silently.
*/
showsUserLocation: React.PropTypes.bool,
/**
* If `true` the map will follow the user's location whenever it changes.
* Note that this has no effect unless `showsUserLocation` is enabled.
* Default value is `true`.
*/
followUserLocation: React.PropTypes.bool,
/**
* If `false` points of interest won't be displayed on the map.
* Default value is `true`.
*/
showsPointsOfInterest: React.PropTypes.bool,
/**
* If `false`, compass won't be displayed on the map.
* Default value is `true`.
*/
showsCompass: React.PropTypes.bool,
/**
* If `false` the user won't be able to pinch/zoom the map.
* Default value is `true`.
*/
zoomEnabled: React.PropTypes.bool,
/**
* When this property is set to `true` and a valid camera is associated with
* the map, the camera's heading angle is used to rotate the plane of the
* map around its center point.
*
* When this property is set to `false`, the
* camera's heading angle is ignored and the map is always oriented so
* that true north is situated at the top of the map view
*/
rotateEnabled: React.PropTypes.bool,
/**
* When this property is set to `true` and a valid camera is associated
* with the map, the camera's pitch angle is used to tilt the plane
* of the map.
*
* When this property is set to `false`, the camera's pitch
* angle is ignored and the map is always displayed as if the user
* is looking straight down onto it.
*/
pitchEnabled: React.PropTypes.bool,
/**
* If `false` the user won't be able to change the map region being displayed.
* Default value is `true`.
*/
scrollEnabled: React.PropTypes.bool,
/**
* The map type to be displayed.
*
* - `standard`: Standard road map (default).
* - `satellite`: Satellite view.
* - `hybrid`: Satellite view with roads and points of interest overlaid.
*/
mapType: React.PropTypes.oneOf([
'standard',
'satellite',
'hybrid',
]),
/**
* The region to be displayed by the map.
*
* The region is defined by the center coordinates and the span of
* coordinates to display.
*/
region: React.PropTypes.shape({
/**
* Coordinates for the center of the map.
*/
latitude: React.PropTypes.number.isRequired,
longitude: React.PropTypes.number.isRequired,
/**
* Distance between the minimum and the maximum latitude/longitude
* to be displayed.
*/
latitudeDelta: React.PropTypes.number,
longitudeDelta: React.PropTypes.number,
}),
/**
* Map annotations with title and subtitle.
*/
annotations: React.PropTypes.arrayOf(React.PropTypes.shape({
/**
* The location of the annotation.
*/
latitude: React.PropTypes.number.isRequired,
longitude: React.PropTypes.number.isRequired,
/**
* Whether the pin drop should be animated or not
*/
animateDrop: React.PropTypes.bool,
/**
* Whether the pin should be draggable or not
*/
draggable: React.PropTypes.bool,
/**
* Event that fires when the annotation drag state changes.
*/
onDragStateChange: React.PropTypes.func,
/**
* Event that fires when the annotation gets was tapped by the user
* and the callout view was displayed.
*/
onFocus: React.PropTypes.func,
/**
* Event that fires when another annotation or the mapview itself
* was tapped and a previously shown annotation will be closed.
*/
onBlur: React.PropTypes.func,
/**
* Annotation title and subtile.
*/
title: React.PropTypes.string,
subtitle: React.PropTypes.string,
/**
* Callout views.
*/
leftCalloutView: React.PropTypes.element,
rightCalloutView: React.PropTypes.element,
detailCalloutView: React.PropTypes.element,
/**
* The pin color. This can be any valid color string, or you can use one
* of the predefined PinColors constants. Applies to both standard pins
* and custom pin images.
*
* Note that on iOS 8 and earlier, only the standard PinColor constants
* are supported for regular pins. For custom pin images, any tintColor
* value is supported on all iOS versions.
*/
tintColor: ColorPropType,
/**
* Custom pin image. This must be a static image resource inside the app.
*/
image: Image.propTypes.source,
/**
* Custom pin view. If set, this replaces the pin or custom pin image.
*/
view: React.PropTypes.element,
/**
* annotation id
*/
id: React.PropTypes.string,
/**
* Deprecated. Use the left/right/detailsCalloutView props instead.
*/
hasLeftCallout: deprecatedPropType(
React.PropTypes.bool,
'Use `leftCalloutView` instead.'
),
hasRightCallout: deprecatedPropType(
React.PropTypes.bool,
'Use `rightCalloutView` instead.'
),
onLeftCalloutPress: deprecatedPropType(
React.PropTypes.func,
'Use `leftCalloutView` instead.'
),
onRightCalloutPress: deprecatedPropType(
React.PropTypes.func,
'Use `rightCalloutView` instead.'
),
})),
/**
* Map overlays
*/
overlays: React.PropTypes.arrayOf(React.PropTypes.shape({
/**
* Polyline coordinates
*/
coordinates: React.PropTypes.arrayOf(React.PropTypes.shape({
latitude: React.PropTypes.number.isRequired,
longitude: React.PropTypes.number.isRequired
})),
/**
* Line attributes
*/
lineWidth: React.PropTypes.number,
strokeColor: ColorPropType,
fillColor: ColorPropType,
/**
* Overlay id
*/
id: React.PropTypes.string
})),
/**
* Maximum size of the area that can be displayed.
*/
maxDelta: React.PropTypes.number,
/**
* Minimum size of the area that can be displayed.
*/
minDelta: React.PropTypes.number,
/**
* Insets for the map's legal label, originally at bottom left of the map.
*/
legalLabelInsets: EdgeInsetsPropType,
/**
* Callback that is called continuously when the user is dragging the map.
*/
onRegionChange: React.PropTypes.func,
/**
* Callback that is called once, when the user is done moving the map.
*/
onRegionChangeComplete: React.PropTypes.func,
/**
* Deprecated. Use annotation `onFocus` and `onBlur` instead.
*/
onAnnotationPress: React.PropTypes.func,
/**
* @platform android
*/
active: React.PropTypes.bool,
},
statics: {
/**
* Standard iOS MapView pin color constants, to be used with the
* `annotation.tintColor` property. On iOS 8 and earlier these are the
* only supported values when using regular pins. On iOS 9 and later
* you are not obliged to use these, but they are useful for matching
* the standard iOS look and feel.
*/
PinColors: {
RED: '#ff3b30',
GREEN: '#4cd964',
PURPLE: '#c969e0',
},
},
render: function() {
let children = [], {annotations, overlays, followUserLocation} = this.props;
annotations = annotations && annotations.map((annotation: Object) => {
let {
id,
image,
tintColor,
view,
leftCalloutView,
rightCalloutView,
detailCalloutView,
} = annotation;
if (!view && image && tintColor) {
view = <Image
style={{
tintColor: processColor(tintColor),
}}
source={image}
/>;
image = undefined;
}
if (view) {
if (image) {
console.warn('`image` and `view` both set on annotation. Image will be ignored.');
}
var viewIndex = children.length;
children.push(React.cloneElement(view, {
// $FlowFixMe - An array of styles should be fine
style: [styles.annotationView, view.props.style || {}]
}));
}
if (leftCalloutView) {
var leftCalloutViewIndex = children.length;
children.push(React.cloneElement(leftCalloutView, {
style: [styles.calloutView, leftCalloutView.props.style || {}]
}));
}
if (rightCalloutView) {
var rightCalloutViewIndex = children.length;
children.push(React.cloneElement(rightCalloutView, {
style: [styles.calloutView, rightCalloutView.props.style || {}]
}));
}
if (detailCalloutView) {
var detailCalloutViewIndex = children.length;
children.push(React.cloneElement(detailCalloutView, {
style: [styles.calloutView, detailCalloutView.props.style || {}]
}));
}
const result = {
...annotation,
tintColor: tintColor && processColor(tintColor),
image,
viewIndex,
leftCalloutViewIndex,
rightCalloutViewIndex,
detailCalloutViewIndex,
view: undefined,
leftCalloutView: undefined,
rightCalloutView: undefined,
detailCalloutView: undefined,
};
result.id = id || encodeURIComponent(JSON.stringify(result));
result.image = image && resolveAssetSource(image);
return result;
});
overlays = overlays && overlays.map((overlay: Object) => {
const {id, fillColor, strokeColor} = overlay;
const result = {
...overlay,
strokeColor: strokeColor && processColor(strokeColor),
fillColor: fillColor && processColor(fillColor),
};
result.id = id || encodeURIComponent(JSON.stringify(result));
return result;
});
const findByAnnotationId = (annotationId: string) => {
if (!annotations) {
return null;
}
for (let i = 0, l = annotations.length; i < l; i++) {
if (annotations[i].id === annotationId) {
return annotations[i];
}
}
return null;
};
// TODO: these should be separate events, to reduce bridge traffic
let onPress, onAnnotationDragStateChange, onAnnotationFocus, onAnnotationBlur;
if (annotations) {
onPress = (event: Event) => {
if (event.nativeEvent.action === 'annotation-click') {
// TODO: Remove deprecated onAnnotationPress API call later.
this.props.onAnnotationPress &&
this.props.onAnnotationPress(event.nativeEvent.annotation);
} else if (event.nativeEvent.action === 'callout-click') {
const annotation = findByAnnotationId(event.nativeEvent.annotationId);
if (annotation) {
// Pass the right function
if (event.nativeEvent.side === 'left' && annotation.onLeftCalloutPress) {
annotation.onLeftCalloutPress(event.nativeEvent);
} else if (event.nativeEvent.side === 'right' && annotation.onRightCalloutPress) {
annotation.onRightCalloutPress(event.nativeEvent);
}
}
}
};
onAnnotationDragStateChange = (event: Event) => {
const annotation = findByAnnotationId(event.nativeEvent.annotationId);
if (annotation) {
// Call callback
annotation.onDragStateChange &&
annotation.onDragStateChange(event.nativeEvent);
}
};
onAnnotationFocus = (event: Event) => {
const annotation = findByAnnotationId(event.nativeEvent.annotationId);
if (annotation && annotation.onFocus) {
annotation.onFocus(event.nativeEvent);
}
};
onAnnotationBlur = (event: Event) => {
const annotation = findByAnnotationId(event.nativeEvent.annotationId);
if (annotation && annotation.onBlur) {
annotation.onBlur(event.nativeEvent);
}
};
}
// TODO: these should be separate events, to reduce bridge traffic
if (this.props.onRegionChange || this.props.onRegionChangeComplete) {
var onChange = (event: Event) => {
if (event.nativeEvent.continuous) {
this.props.onRegionChange &&
this.props.onRegionChange(event.nativeEvent.region);
} else {
this.props.onRegionChangeComplete &&
this.props.onRegionChangeComplete(event.nativeEvent.region);
}
};
}
// followUserLocation defaults to true if showUserLocation is set
if (followUserLocation === undefined) {
followUserLocation = this.props.showUserLocation;
}
return (
<RCTMap
{...this.props}
annotations={annotations}
children={children}
followUserLocation={followUserLocation}
overlays={overlays}
onPress={onPress}
onChange={onChange}
onAnnotationDragStateChange={onAnnotationDragStateChange}
onAnnotationFocus={onAnnotationFocus}
onAnnotationBlur={onAnnotationBlur}
/>
);
},
});
const styles = StyleSheet.create({
annotationView: {
position: 'absolute',
backgroundColor: 'transparent',
},
calloutView: {
position: 'absolute',
backgroundColor: 'white',
},
});
const RCTMap = requireNativeComponent('RCTMap', MapView, {
nativeOnly: {
onAnnotationDragStateChange: true,
onAnnotationFocus: true,
onAnnotationBlur: true,
onChange: true,
onPress: true
}
});
module.exports = MapView;
|
src/main.js | techcoop/techcoop.group | 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()
|
src/App.js | Dremora/mondo-hackathon-webapp | import React, { Component } from 'react';
import gaussian from 'gaussian'
import _ from 'lodash'
import moment from 'moment'
import 'whatwg-fetch'
import ChartWrapper from './ChartWrapper';
import body from './data'
export class App extends Component {
constructor() {
super(...arguments)
this.state = {
loading: true,
currentDate: new Date(),
period: 'week'
}
}
componentWillMount() {
const accountId = this.props.location.query['account-id']
const transactionId = this.props.location.query['transaction-id']
fetch('http://mondo.instatswetrust.com/v1/transactions/detailed?account-id=' +
accountId + '&transaction-id=' + transactionId)
.then(response => response.json()
, ::console.error)
.then(body => {
let processStats = stats => _.sortBy(stats.expenses.map(({ key, stats }) => {
return {
timestamp: key / 1000,
amount: Math.abs(stats.sum)
}
}), 'timestamp')
// let data = body.map(({created, amount}) => ({
// date: moment(created).startOf('day').unix(),
// amount: amount
// }))
// data = _.groupBy(data, 'date')
this.setState({
periodData: {
week: processStats(body.aggs.week),
month: processStats(body.aggs.month),
year: processStats(body.aggs.year)
},
loading: false
})
});
}
changePeriod(period) {
this.setState({
period: period
})
}
render() {
let { periodData, currentDate, period } = this.state
if (this.state.loading) {
return <span>Loading...</span>
}
let data = periodData[period]
// data = _.map(data, (entries, timestamp) => ({
// timestamp,
// amount: _.reduce(entries, (acc, { amount }) => amount > 0 ? acc : acc - amount, 0)
// }))
// data = data.filter((value, key))
// let beginningOfMonth = moment(currentDate).startOf('month').unix()
// let endOfMonth = moment(currentDate).endOf('month').unix()
// data = data.filter(({amount, timestamp}) => (
// timestamp >= beginningOfMonth && timestamp <= endOfMonth
// ))
let weekAmount = _.sum(periodData.week, 'amount')
let monthAmount = _.sum(periodData.month, 'amount')
let yearAmount = _.sum(periodData.year, 'amount')
let accumulatedData = []
let previous = { y: 0 }
_.each(data, ({amount, timestamp}) => {
let newEntry = {
x: Number(timestamp),
y: previous.y + amount
}
accumulatedData.push(newEntry)
previous = newEntry
})
return (
<div>
<div>
<ChartWrapper
currentDate={currentDate}
period={period}
onPeriodChange={::this.changePeriod}
data={data}
weekAmount={weekAmount}
monthAmount={monthAmount}
yearAmount={yearAmount}
accumulatedData={accumulatedData}
/>
</div>
</div>
);
}
} |
src/pages/Editor/pages/MapEditor/containers/MapContainer/components/DatamapBox/components/HoverInfo.js | caspg/datamaps.co | import React from 'react'
import PropTypes from 'prop-types'
import { grey300 } from '@src/styles/colors'
HoverInfo.propTypes = {
position: PropTypes.object.isRequired,
active: PropTypes.bool.isRequired,
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
}
function HoverInfo(props) {
const hoverInfoStyle = {
left: props.position.get('x') + 20,
top: props.position.get('y') - 90 + 20, // 90px == height of header
display: props.active ? 'block' : 'none',
}
return (
<div className="HoverInfo" style={hoverInfoStyle}>
<p>{props.name}</p>
<p>{props.value}</p>
<style jsx>{`
.HoverInfo {
position: fixed;
min-width: 100px;
min-height: 50px;
border: 1px solid ${grey300};
background-color: white;
box-shadow: 1px 1px 5px ${grey300};
padding: 10px;
}
`}</style>
</div>
)
}
export default HoverInfo
|
src/parser/rogue/outlaw/modules/core/ComboPoints.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import resourceSuggest from 'parser/shared/modules/resourcetracker/ResourceSuggest';
import ComboPointTracker from '../../../shared/resources/ComboPointTracker';
class ComboPoints extends Analyzer {
static dependencies = {
comboPointTracker: ComboPointTracker,
};
makeExtraSuggestion(spell) {
return <>Avoid wasting combo points when casting <SpellLink id={spell.id} />.</>;
}
suggestions(when) {
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.MARKED_FOR_DEATH_TALENT, // 5 CP
minor: 0,
avg: 0.05,
major: 0.1,
extraSuggestion: this.makeExtraSuggestion(SPELLS.MARKED_FOR_DEATH_TALENT),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.SINISTER_STRIKE, // 1 CP + 35% chance for another
minor: 0,
avg: 0.05,
major: 0.1,
extraSuggestion: this.makeExtraSuggestion(SPELLS.SINISTER_STRIKE),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.AMBUSH, // 2 CP
minor: 0,
avg: 0.1,
major: 0.2,
extraSuggestion: this.makeExtraSuggestion(SPELLS.AMBUSH),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.PISTOL_SHOT, // 1 CP, 2 with proc and Quick Draw
minor: 0,
avg: 0.05,
major: 0.1,
extraSuggestion: this.makeExtraSuggestion(SPELLS.PISTOL_SHOT),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.GHOSTLY_STRIKE_TALENT, // 1 CP
minor: 0,
avg: 0.05,
major: 0.1,
extraSuggestion: this.makeExtraSuggestion(SPELLS.GHOSTLY_STRIKE_TALENT),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.CHEAP_SHOT, // 2 CP
minor: 0,
avg: 0.1,
major: 0.2,
extraSuggestion: this.makeExtraSuggestion(SPELLS.CHEAP_SHOT),
});
resourceSuggest(when, this.comboPointTracker, {
spell: SPELLS.GOUGE, // 1 CP
minor: 0,
avg: 0.1,
major: 0.2,
extraSuggestion: this.makeExtraSuggestion(SPELLS.GOUGE),
});
}
}
export default ComboPoints;
|
src/CollapsibleMixin.js | rapilabs/react-bootstrap | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
let warned = false;
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState(){
let defaultExpanded = this.props.defaultExpanded != null ?
this.props.defaultExpanded :
this.props.expanded != null ?
this.props.expanded :
false;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillMount(){
if ( !warned ){
deprecationWarning('CollapsibleMixin', 'Collapse Component');
warned = true;
}
},
componentWillUpdate(nextProps, nextState){
let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = '0';
if(!willExpanded){
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate(prevProps, prevState){
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate(){
},
_checkStartAnimation(){
if(!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
let result;
if(this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState){
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if(wasExpanded !== isExpanded){
if(wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand(){
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let complete = () => {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing:false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse(){
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener(node, complete){
TransitionEvents.addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener(node, complete){
TransitionEvents.removeEndEventListener(node, complete);
},
dimension(){
return (typeof this.getCollapsibleDimension === 'function') ?
this.getCollapsibleDimension() :
'height';
},
isExpanded(){
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet(className) {
let classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(subClasses => {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes.in = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
export default CollapsibleMixin;
|
pages/blog/test-article-two.js | trungtin/mymy | import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div>
<h1>Test Article 2</h1>
<p>Coming soon.</p>
</div>
);
}
}
|
node_modules/rebass/src/Toolbar.js | HasanSa/hackathon |
import React from 'react'
import Base from './Base'
import config from './config'
/**
* Toolbar component that vertically centers children with display flex
*/
const Toolbar = (props, { rebass }) => {
const { scale, colors } = { ...config, ...rebass }
return (
<Base
{...props}
className='Toolbar'
baseStyle={{
display: 'flex',
alignItems: 'center',
minHeight: 48,
paddingLeft: scale[1],
paddingRight: scale[1],
color: colors.white,
backgroundColor: colors.primary
}} />
)
}
Toolbar.contextTypes = {
rebass: React.PropTypes.object
}
export default Toolbar
|
src/components/NotFound.js | mehmettugrulsahin/cotd-react-es6 | import React from 'react';
class NotFound extends React.Component {
render() {
return (
<h2>not Found!!!</h2>
)
}
}
export default NotFound; |
features/taskboard/components/taskContainer.js | zymokey/mission-park | import React from 'react';
import { connect } from 'react-redux';
import Task from './task';
// import * as actionCreators from '../actions/taskActions';
import Spinner from '../../common/components/spinner';
class TaskContainer extends React.Component {
constructor(props){
super(props);
}
render(){
let fetchedTasks = [];
let tasklistId = this.props.tasklistId;
let projectId = this.props.projectId;
fetchedTasks = this.props.tasks.map(function(task){
return <Task key={task._id} task={task} tasklistId={tasklistId} projectId={projectId} />;
});
return(
<div className="task-container">
<Spinner show={this.props.taskLoading}/>
{fetchedTasks}
</div>
)
}
}
const mapStateToProps = state => {
const tbt = state.taskboard.task;
return {
tasks: tbt.tasks,
taskLoading: tbt.taskLoading
}
}
// const mapDispatchToProps = dispatch => ({
// });
export default connect(mapStateToProps, null)(TaskContainer); |
packages/icons/src/md/communication/PhonelinkLock.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdPhonelinkLock(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M37 2H17c-2.2 0-4 1.8-4 4v6h4V8h20v32H17v-4h-4v6c0 2.2 1.8 4 4 4h20c2.2 0 4-1.8 4-4V6c0-2.2-1.8-4-4-4zM20.6 22c1.2 0 2.4 1.2 2.4 2.6v7c0 1.2-1.2 2.4-2.6 2.4h-11C8.2 34 7 32.8 7 31.4v-7C7 23.2 8.2 22 9.4 22v-3c0-2.8 2.8-5 5.6-5s5.6 2.2 5.6 5v3zM18 22v-3c0-1.6-1.4-2.6-3-2.6s-3 1-3 2.6v3h6z" />
</IconBase>
);
}
export default MdPhonelinkLock;
|
src/js/components/nodes/NodesListView/NodesListView.js | knowncitizen/tripleo-ui | /**
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import React from 'react';
import { ListView } from 'patternfly-react';
import NodeListItem from './NodeListItem';
export default class NodesListView extends React.Component {
render() {
return (
<ListView id="NodesListView_listView">
{this.props.nodes
.toList()
.map(node => (
<NodeListItem
fetchNodeIntrospectionData={this.props.fetchNodeIntrospectionData}
node={node}
key={node.get('uuid')}
inProgress={this.props.nodesInProgress.includes(node.get('uuid'))}
/>
))}
</ListView>
);
}
}
NodesListView.propTypes = {
fetchNodeIntrospectionData: PropTypes.func.isRequired,
nodes: ImmutablePropTypes.map.isRequired,
nodesInProgress: ImmutablePropTypes.set.isRequired
};
|
src/routes/error/index.js | luznlun/kkRoom | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import ErrorPage from './ErrorPage';
export default {
path: '/error',
action({ error }) {
return {
title: error.name,
description: error.message,
component: <ErrorPage error={error} />,
status: error.status || 500,
};
},
};
|
src/svg-icons/navigation/menu.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationMenu = (props) => (
<SvgIcon {...props}>
<path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</SvgIcon>
);
NavigationMenu = pure(NavigationMenu);
NavigationMenu.displayName = 'NavigationMenu';
NavigationMenu.muiName = 'SvgIcon';
export default NavigationMenu;
|
src/Column.js | BobNisco/react-yarg | 'use strict';
import React from 'react';
import Radium from 'radium';
import Utilities from './Utilities';
let styles = {
columnMixin: (columnCount, props) => {
return Object.assign({
position: 'relative',
boxSizing: 'border-box',
minHeight: '1px',
float: 'left',
marginLeft: ((props) => {
if (props.offset) {
return Utilities.WidthMixin(columnCount, props.offset);
}
return null;
})(props),
}, Utilities.ResponsiveWidthMixin(columnCount, props))
},
};
class Column extends React.Component {
render() {
return (
<div className={Utilities.MakeClassName('column ', this.props.className)} style={styles.columnMixin(this.context.columns, this.props)}>
{this.props.children}
</div>
)
}
}
Column.propTypes = {
width: React.PropTypes.number.isRequired,
offset: React.PropTypes.number,
smallWidth: React.PropTypes.number,
mediumWidth: React.PropTypes.number,
largeWidth: React.PropTypes.number,
xlargeWidth: React.PropTypes.number,
xxlargeWidth: React.PropTypes.number,
xxxlargeWidth: React.PropTypes.number,
};
Column.contextTypes = {
columns: React.PropTypes.number.isRequired,
};
Column = Radium(Column);
export default Column;
|
src/svg-icons/action/extension.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionExtension = (props) => (
<SvgIcon {...props}>
<path d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7 1.49 0 2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"/>
</SvgIcon>
);
ActionExtension = pure(ActionExtension);
ActionExtension.displayName = 'ActionExtension';
ActionExtension.muiName = 'SvgIcon';
export default ActionExtension;
|
src/utils/index.js | taikongfeizhu/webpack-develop-startkit | import React from 'react'
import { COLUMNS, UNKNOW_COLUMN } from 'constant'
import _ from 'lodash'
import { Select, Radio } from 'antd'
const Option = Select.Option
const _findItem = (list = [], value, key = 'name') => {
return list.find((item, index) => {
return '' + item[key] === '' + value
})
}
let util = {
buildColumns (list = [], opts = {}) {
return list.map((item, index) => {
let column = {}
if (_.isString(item)) {
column = { ...(COLUMNS[item] || UNKNOW_COLUMN) }
} else {
column = { ...(COLUMNS[item.key] || UNKNOW_COLUMN), ...item }
}
if (opts[column.key]) {
column = Object.assign(column, opts[column.key])
}
return column
})
},
buildOptions (list = [], opts = {}) {
let { makeValue, makeLabel, valueField = 'id', labelField = 'name' } = opts
return list.map((item, index) => {
let key = item[valueField]
let value = makeValue ? makeValue(item, index) : item[valueField]
let label = makeLabel ? makeLabel(item, index) : item[labelField]
return (
<Option
key={key || index}
data-id={key}
value={_.isNumber(value) ? ('' + value) : value}
>
{label}
</Option>
)
})
},
buildRadios (list = [], opts = {}) {
let { makeValue, makeLabel, valueField = 'id', labelField = 'name' } = opts
return list.map((item, index) => {
let key = item[valueField]
let value = makeValue ? makeValue(item, index) : item[valueField]
let label = makeLabel ? makeLabel(item, index) : item[labelField]
return (
<Radio
key={key || index}
data-id={key}
value={_.isNumber(value) ? ('' + value) : value}
>
{label}
</Radio>
)
})
},
formatSuccessData (source, init = []) {
return source.success ? source.data : init
},
findItem (list = [], value, key = 'name') {
if (_.isArray(value)) {
return _.filter(list, (item) => {
return value.find((v) => ('' + item[key] === '' + v))
})
}
return _findItem(list, value, key)
},
selectFilter (key = 'value') {
return (input, option) => (
option.props[key].toLowerCase().indexOf(input.toLowerCase()) >= 0
)
},
num2str (value) {
return _.isArray(value) ? value.map(util.num2str) : (
_.isUndefined(value) ? undefined : '' + value
)
},
makeFileds (fieldsValue) {
let result = {}
_.forEach(fieldsValue, (value, key) => {
result[key] = { value: value || undefined }
})
return result
},
formatList2Tree (list) {
if (!list.length) return []
_.forEach(list, (i) => {
if (i.tripartite_types && i.tripartite_types.length > 0) {
i.children = i.tripartite_types
_.forEach(i.children, (o, index) => {
o.id = '' + i.apply_id + 'index' + index
})
}
})
return list
},
formatMsg (msg) {
return (
<p dangerouslySetInnerHTML={{ __html: msg }} />
)
},
processingDatainStockReview (subject, review) {
let _data = subject.map(item => {
item.data = []
return item
})
review && review.data && review.data.forEach(item => {
const getDataIndexByReviewData = () => {
const _id = item.contract_subject_id
for (let i = 0; i < _data.length; i++) {
if (_data && _data[i].id === _id) return i
}
return -1
}
const _index = getDataIndexByReviewData()
if (_index >= 0) {
_data[_index].data.push(item)
}
})
return _data
},
processingDatainBusinessReview (list) {
return list && list.map(item => {
return ({
...item,
children: item.tripartite_types && item.tripartite_types.length > 1 && item.tripartite_types.map(i => {
return ({
'tripartite_type_name': i.tripartite_type_name,
'contract_serials': i.contract_serials && i.contract_serials.map(o => {
return {
start: o.start,
end: o.end
}
}),
'applicant_name': item.applicant_name,
'claim_num': i.claim_num,
'status': item.status
})
}) || []
})
})
},
processingDatainBusinessCharts (stock, contractTypes) {
const subjectLen = stock && stock.length || 0
const typeLen = contractTypes && contractTypes.length || 0
const result = []
for (let i = 0; i < typeLen; i++) {
const _t = []
for (let j = 0; j < subjectLen; j++) {
_t.push(0)
}
result.push(_t)
}
_.forEach(stock, (singleData, index) => {
const subIndex = index
_.forEach(singleData.tripartite_types, (d) => {
const _v = d.stock
const conIndex = _.findIndex(contractTypes, { id: d.tripartite_type })
if (subIndex !== -1 && result[conIndex] !== undefined &&
result[conIndex][subIndex] !== undefined) {
result[conIndex][subIndex] += _v
}
})
})
return result
}
}
export default util
|
src/routes/Measurements/components/MeasurementViewer.js | TheTorProject/ooni-wui | import React from 'react'
import { FormattedMessage } from 'react-intl'
import Modal from 'react-modal'
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'
import MeasurementDetails from './MeasurementDetails'
import {
formatViewButton,
formatDate,
rowClassNameFormat
} from '../../../util/table'
import { getPrettyNettestName } from '../../../util/nettest'
const MeasurementViewer = ({
selectedMeasurements,
onRowClick,
onBackClick,
onCloseClick,
onToggleNormal,
isMeasurementOpen,
openMeasurement,
visibleMeasurements,
showNormal
}) => {
let tableOptions = {
onRowClick: (row) => {
onRowClick(selectedMeasurements.id, row.idx)
}
}
return (
<div>
{selectedMeasurements.results.length > 1 &&
<div>
<div className='text-xs-left'>
<a className='text-primary clickable' onClick={onBackClick}>
<FormattedMessage
id='measurements.measurementViewer.returnButton'
defaultMessage='{iconArrowLeft} Return'
values={{
iconArrowLeft: <i className='fa fa-arrow-circle-o-left' />
}}
/>
</a>
</div>
<div className='text-xs-center'>
<h1>{getPrettyNettestName(selectedMeasurements.test_name)}</h1>
<div className='result-metadata'>
{formatDate(selectedMeasurements.test_start_time)}
{' | '}
<FormattedMessage
id='measurements.measurementViewer.location'
defaultMessage='Location: {countryCode} ({asNumber})'
values={{
countryCode: selectedMeasurements.country_code,
asNumber: selectedMeasurements.asn
}}
/>
</div>
</div>
<BootstrapTable
tableStyle={{ border: 'none' }}
containerStyle={{ border: 'none' }}
trClassName={rowClassNameFormat}
data={visibleMeasurements}>
<TableHeaderColumn dataAlign='center' dataField='url'>
<strong>
<FormattedMessage
id='measurements.measurementViewer.url'
defaultMessage='URL'
/> (
<a href='#' onClick={(evt) => onToggleNormal(evt)}>
{showNormal
? <FormattedMessage
id='measurements.measurementViewer.hideNormal'
defaultMessage='Hide normal'
/>
: <FormattedMessage
id='measurements.measurementViewer.showNormal'
defaultMessage='Show normal'
/>
}
</a>
)</strong>
</TableHeaderColumn>
<TableHeaderColumn width='100' dataAlign='center' dataField='anomaly'
dataFormat={formatViewButton(tableOptions.onRowClick)}>
<strong>
<FormattedMessage
id='measurements.measurementViewer.result'
defaultMessage='Result'
/>
</strong>
</TableHeaderColumn>
<TableHeaderColumn dataField='idx' isKey hidden />
</BootstrapTable>
</div>
}
<Modal
className='Modal__Bootstrap modal-dialog'
onRequestClose={onCloseClick}
contentLabel='Measurement details'
isOpen={isMeasurementOpen}>
<div className='modal-content'>
<div className='modal-header' style={{ borderBottom: '0', padding: '0' }}>
<button type='button' className='close' onClick={onCloseClick}>
<span aria-hidden='true'>×</span>
<span className='sr-only'>Close</span>
</button>
</div>
<div className='modal-body modal-body-no-header'>
<MeasurementDetails
measurement={openMeasurement} />
</div>
<div className='modal-footer text-xs-center'>
<button className='btn btn-primary' onClick={onCloseClick}>
<FormattedMessage
id='measurements.measurementViewer.returnButtonNoIcon'
defaultMessage='Return'
/>
</button>
</div>
</div>
</Modal>
</div>
)
}
MeasurementViewer.propTypes = {
selectedMeasurements: React.PropTypes.object,
visibleMeasurements: React.PropTypes.array,
onRowClick: React.PropTypes.func,
onBackClick: React.PropTypes.func,
onCloseClick: React.PropTypes.func,
onToggleNormal: React.PropTypes.func,
isMeasurementOpen: React.PropTypes.bool,
openMeasurement: React.PropTypes.object,
showNormal: React.PropTypes.bool
}
export default MeasurementViewer
|
src/SafeAnchor.js | thealjey/react-bootstrap | import React from 'react';
import createChainedFunction from './utils/createChainedFunction';
/**
* Note: This is intended as a stop-gap for accessibility concerns that the
* Bootstrap CSS does not address as they have styled anchors and not buttons
* in many cases.
*/
export default class SafeAnchor extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
if (this.props.href === undefined) {
event.preventDefault();
}
}
render() {
return (
<a role={this.props.href ? undefined : 'button'}
{...this.props}
onClick={createChainedFunction(this.props.onClick, this.handleClick)}
href={this.props.href || ''}/>
);
}
}
SafeAnchor.propTypes = {
href: React.PropTypes.string,
onClick: React.PropTypes.func
};
|
src/about/index.js | marchisbogdan/licenta-front | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import s from './styles.css';
import { title, html } from './index.md';
class AboutPage extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout className={s.content}>
<h1>{title}</h1>
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: html }}
/>
</Layout>
);
}
}
export default AboutPage;
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js | tharakawj/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(limit) {
let i = 1;
while (i <= limit) {
yield { id: i, name: i };
i++;
}
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
const users = [];
for (let user of load(4)) {
users.push(user);
}
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-generators">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
src/js/components/date-selectors.js | donnierayjones/dayone-js-html | import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import $ from 'jquery';
import DateSelector from './date-selector';
export default class DateSelectors extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
}
onChange() {
var fromValue = $('input[name="from"]', ReactDOM.findDOMNode(this)).val();
var toValue = $('input[name="to"]', ReactDOM.findDOMNode(this)).val();
this.props.onChange(moment(fromValue), moment(toValue));
}
render() {
return (
<div>
<h4>Creation Date</h4>
<DateSelector name="from" label="From" date={this.props.from} onChange={this.onChange} />
<DateSelector name="to" label="To" date={this.props.to} onChange={this.onChange} />
</div>
);
}
}
|
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionsTableSchema.js | johnpmitsch/katello | /* eslint-disable import/prefer-default-export */
import React from 'react';
import { Icon } from 'patternfly-react';
import { translate as __ } from 'foremanReact/common/I18n';
import { entitlementsInlineEditFormatter } from '../../../../move_to_foreman/components/common/table/formatters/EntitlementsInlineEditFormatter';
import { subscriptionTypeFormatter } from './SubscriptionTypeFormatter';
import { subscriptionNameFormatter } from './SubscriptionNameFormatter';
import {
headerFormatter,
cellFormatter,
selectionHeaderCellFormatter,
collapseableAndSelectionCellFormatter,
} from '../../../../move_to_foreman/components/common/table';
function getEntitlementsFormatter(inlineEditController, canManageSubscriptionAllocations) {
if (canManageSubscriptionAllocations) {
return entitlementsInlineEditFormatter(inlineEditController);
}
return cellFormatter;
}
export const createSubscriptionsTableSchema = (
inlineEditController,
selectionController,
groupingController,
hasPermission,
) => [
{
property: 'select',
header: {
label: __('Select all rows'),
formatters: [label => selectionHeaderCellFormatter(selectionController, label)],
},
cell: {
formatters: [
(value, additionalData) => {
// eslint-disable-next-line no-param-reassign
additionalData.disabled = additionalData.rowData.available === -1;
return collapseableAndSelectionCellFormatter(
groupingController,
selectionController,
additionalData,
);
},
],
},
},
{
property: 'id',
header: {
label: __('Name'),
formatters: [headerFormatter],
},
cell: {
formatters: [subscriptionNameFormatter]
,
},
},
{
property: 'type',
header: {
label: __('Type'),
formatters: [headerFormatter],
},
cell: {
formatters: [subscriptionTypeFormatter],
},
},
{
property: 'product_id',
header: {
label: __('SKU'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'contract_number',
header: {
label: __('Contract'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
}, // TODO: use date formatter from tomas' PR
{
property: 'start_date',
header: {
label: __('Start Date'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'end_date',
header: {
label: __('End Date'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'virt_who',
header: {
label: __('Requires Virt-Who'),
formatters: [headerFormatter],
},
cell: {
formatters: [
(value, { rowData }) => (
<td>
<Icon type="fa" name={rowData.virt_who ? 'check' : 'minus'} />
</td>
),
],
},
},
{
property: 'consumed',
header: {
label: __('Consumed'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'quantity',
header: {
label: __('Entitlements'),
formatters: [headerFormatter],
},
cell: {
formatters: [getEntitlementsFormatter(inlineEditController, hasPermission)],
},
},
];
|
dva/dva-quickstart/src/components/Example.js | imuntil/React | import React from 'react';
const Example = () => {
return (
<div>
Example
</div>
);
};
Example.propTypes = {
};
export default Example;
|
examples/star-wars/js/app.js | liuxiong332/graphql-client | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import TotalReducer from './reducers/totalReducer';
import StarWarsApp from './components/StarWarsApp';
class ReducerComponent extends React.Component {
initWithReducer(reducer) {
var onHandleChange = (newRd) => {
this.subscription.dispose();
this.subscription = newRd.subscribe(onHandleChange);
this.setState({reducer: newRd});
};
this.subscription = reducer.subscribe(onHandleChange);
this.setState({reducer});
}
dispose() {
this.subscription.dispose();
}
}
class Wrapper extends ReducerComponent {
componentWillMount() {
this.initWithReducer(new TotalReducer);
}
componentWillUnmount() {
this.dispose();
}
render() {
let reducer = this.state.reducer;
let factions = reducer.get('factions');
let shipInput = reducer.get('shipInput');
return (
<StarWarsApp factions={factions} shipInput={shipInput}
onNameChange={shipInput.changeShipName.bind(shipInput)}
onSelectionChange={shipInput.changeFactionId.bind(shipInput)}
onAddShip={shipInput.addShip.bind(shipInput)}
/>
);
}
}
ReactDOM.render(
<Wrapper />,
document.getElementById('root')
);
|
packages/showcase/misc/gradient-example.js | uber/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import {
XYPlot,
XAxis,
YAxis,
VerticalGridLines,
HorizontalGridLines,
AreaSeries,
GradientDefs,
Borders
} from 'react-vis';
export default function GradientExample() {
return (
<XYPlot xDomain={[1.2, 3]} yDomain={[11, 26]} width={300} height={300}>
<GradientDefs>
<linearGradient id="CoolGradient" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stopColor="red" stopOpacity={0.4} />
<stop offset="100%" stopColor="blue" stopOpacity={0.3} />
</linearGradient>
</GradientDefs>
<VerticalGridLines />
<HorizontalGridLines />
<AreaSeries
color={'url(#CoolGradient)'}
data={[
{x: 1, y: 10, y0: 1},
{x: 2, y: 25, y0: 5},
{x: 3, y: 15, y0: 3}
]}
/>
<Borders
style={{
bottom: {fill: '#fff'},
left: {fill: 'url(#CoolGradient)', opacity: 0.3},
right: {fill: '#fff'},
top: {fill: '#fff'}
}}
/>
<XAxis />
<YAxis />
<AreaSeries
data={[
{x: 1, y: 5, y0: 6},
{x: 2, y: 20, y0: 11},
{x: 3, y: 10, y0: 9}
]}
/>
</XYPlot>
);
}
|
src/Switch.js | esbenp/react-native-clean-form | import React from 'react'
import { Switch as BaseSwitch, View } from 'react-native'
import styled from 'styled-components'
import defaultTheme from './Theme'
const Switch = styled(BaseSwitch)`
`
Switch.propTypes = BaseSwitch.propTypes
Switch.defaultProps = Object.assign({}, BaseSwitch.defaultProps, {
theme: defaultTheme,
componentName: 'Switch',
})
export default Switch
|
docs/src/app/components/pages/components/Popover/ExampleAnimation.js | kasra-co/material-ui | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import {Popover, PopoverAnimationVertical} from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
export default class PopoverExampleAnimation extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onTouchTap={this.handleTouchTap}
label="Click me"
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
animation={PopoverAnimationVertical}
>
<Menu>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</Popover>
</div>
);
}
}
|
app/index.js | y-takey/shokushu | import { ipcRenderer } from 'electron';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import routes from './routes';
import configureStore from './store/configureStore';
import { exportJSON, importJSON } from './actions/HomeActions';
import './app.css';
const store = configureStore();
ipcRenderer.on(
'export-json', (event) => store.dispatch(exportJSON())
).on(
'import-json', (event) => store.dispatch(importJSON())
)
render(
<Provider store={store}>
<Router>
{routes}
</Router>
</Provider>,
document.getElementById('root')
);
if (process.env.NODE_ENV !== 'production') {
// Use require because imports can't be conditional.
// In production, you should ensure process.env.NODE_ENV
// is envified so that Uglify can eliminate this
// module and its dependencies as dead code.
// require('./createDevToolsWindow')(store);
}
|
src/PlayerListPlayer.js | Brianzchen/tabletennis-handicap | import React from 'react';
export default class PlayerListPlayer extends React.Component {
render() {
const playerName = (
this.state.edit ?
(<form onSubmit={this.saveName}>
<input ref={o => { this.input = o; }} type={`text`} placeholder={this.props.player.name} onChange={this.handleNameChange} />
</form>) :
<span onClick={this.editPlayerName}>{this.props.player.name}</span>
);
return (
<div>
<div>
{playerName}
</div>
<div>
{this.props.player.rank}
</div>
</div>
);
}
constructor(props) {
super(props);
this.state = {
edit: false,
name: ``,
};
}
componentDidUpdate() {
this.input && this.input.focus();
}
handleNameChange = event => {
this.setState({
name: event.target.value,
});
}
saveName = event => {
event.preventDefault();
if (this.state.name.trim().length > 0) {
const name = this.state.name.substring(0, 1).toUpperCase() + this.state.name.substring(1).toLowerCase();
this.props.database.ref(`players/${this.props.player.id}/`).update({
name,
}, () => {
this.setState({
edit: false,
});
});
}
}
editPlayerName = () => {
this.setState({
edit: true,
});
}
}
PlayerListPlayer.propTypes = {
player: React.PropTypes.shape({
name: React.PropTypes.string.isRequired,
rank: React.PropTypes.string.isRequired,
id: React.PropTypes.string.isRequired,
}).isRequired,
database: React.PropTypes.object.isRequired,
};
|
es6/Menu/Menu.js | yurizhang/ishow | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import { default as Component } from '../Common/plugs/index.js'; //提供style, classname方法
import '../Common/css/Menu.css';
import '../Common/css/Icon.css';
var Menu = function (_Component) {
_inherits(Menu, _Component);
function Menu(props) {
_classCallCheck(this, Menu);
var _this = _possibleConstructorReturn(this, (Menu.__proto__ || Object.getPrototypeOf(Menu)).call(this, props));
_this.instanceType = 'Menu';
_this.state = {
activeIndex: props.defaultActive,
openedMenus: props.defaultOpeneds ? props.defaultOpeneds.slice(0) : [],
menuItems: {},
submenus: {}
};
return _this;
}
_createClass(Menu, [{
key: 'getChildContext',
value: function getChildContext() {
return {
component: this
};
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.openActiveItemMenus();
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (props.defaultActive !== this.props.defaultActive || props.defaultActive !== this.state.activeIndex) {
this.defaultActiveChanged(props.defaultActive);
}
if (props.defaultOpeneds !== this.props.defaultOpeneds) {
this.defaultOpenedsChanged(props.defaultOpeneds);
}
}
}, {
key: 'openMenu',
value: function openMenu(index, indexPath) {
var openedMenus = this.state.openedMenus;
if (openedMenus.indexOf(index) !== -1) return;
// 将不在该菜单路径下的其余菜单收起
if (this.props.uniqueOpened) {
openedMenus = openedMenus.filter(function (index) {
return indexPath.indexOf(index) !== -1;
});
}
openedMenus.push(index);
this.setState({ openedMenus: openedMenus });
}
}, {
key: 'closeMenu',
value: function closeMenu(index) {
var openedMenus = this.state.openedMenus;
openedMenus.splice(openedMenus.indexOf(index), 1);
this.setState({ openedMenus: openedMenus });
}
}, {
key: 'handleSubmenuClick',
value: function handleSubmenuClick(index, indexPath) {
var isOpened = this.state.openedMenus.indexOf(index) !== -1;
if (isOpened) {
this.closeMenu(index);
if (this.props.onClose) {
this.props.onClose(index, indexPath);
}
} else {
this.openMenu(index, indexPath);
if (this.props.onOpen) {
this.props.onOpen(index, indexPath);
}
}
}
}, {
key: 'handleSelect',
value: function handleSelect(index, indexPath, instance) {
var _this2 = this;
var _state = this.state,
activeIndex = _state.activeIndex,
openedMenus = _state.openedMenus,
submenus = _state.submenus;
activeIndex = index;
if (this.props.onSelect) {
this.props.onSelect(index, indexPath, instance);
}
if (this.props.mode === 'horizontal') {
for (var key in submenus) {
submenus[key].onItemSelect(index, indexPath);
}
openedMenus = [];
}
this.setState({ activeIndex: activeIndex, openedMenus: openedMenus }, function () {
if (_this2.props.mode === 'vertical') {
_this2.openActiveItemMenus();
}
});
}
}, {
key: 'openActiveItemMenus',
value: function openActiveItemMenus() {
var _this3 = this;
var _state2 = this.state,
activeIndex = _state2.activeIndex,
menuItems = _state2.menuItems,
submenus = _state2.submenus;
if (!menuItems[activeIndex]) return;
if (activeIndex && this.props.mode === 'vertical') {
var indexPath = menuItems[activeIndex].indexPath();
// 展开该菜单项的路径上所有子菜单
indexPath.forEach(function (index) {
var submenu = submenus[index];
submenu && _this3.openMenu(index, submenu.indexPath());
});
}
}
}, {
key: 'defaultActiveChanged',
value: function defaultActiveChanged(value) {
var _this4 = this;
var menuItems = this.state.menuItems;
this.setState({ activeIndex: value }, function () {
if (!menuItems[value]) return;
var menuItem = menuItems[value];
var indexPath = menuItem.indexPath();
_this4.handleSelect(value, indexPath, menuItem);
});
}
}, {
key: 'defaultOpenedsChanged',
value: function defaultOpenedsChanged(value) {
this.setState({
openedMenus: value
});
}
}, {
key: 'render',
value: function render() {
return React.createElement(
'ul',
{
style: this.style(),
className: this.className("ishow-menu", {
'ishow-menu--horizontal': this.props.mode === 'horizontal',
'ishow-menu--dark': this.props.theme === 'dark'
})
},
this.props.children
);
}
}]);
return Menu;
}(Component);
export default Menu;
Menu.childContextTypes = {
component: PropTypes.any
};
Menu.propTypes = {
mode: PropTypes.string,
defaultActive: PropTypes.string,
defaultOpeneds: PropTypes.arrayOf(PropTypes.any),
theme: PropTypes.string,
uniqueOpened: PropTypes.bool,
menuTrigger: PropTypes.string,
onSelect: PropTypes.func,
onOpen: PropTypes.func,
onClose: PropTypes.func
};
Menu.defaultProps = {
mode: 'vertical',
theme: 'light',
menuTrigger: 'hover'
}; |
cm19/ReactJS/your-first-react-app-exercises-master/exercise-16/friends/Friends.entry.js | Brandon-J-Campbell/codemash | import React from 'react';
import getFriendsFromApi from './get-friends-from-api';
import Friends from './Friends';
export default class FriendsEntry extends React.Component {
state = {
friends: []
}
async componentDidMount() {
const friends = await getFriendsFromApi();
this.setState({
friends
});
}
render() {
return <Friends friends={this.state.friends} />;
}
}
|
test/helpers/shallowRenderHelper.js | txw132130/react-gallery | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
packages/strapi-generate-plugin/files/admin/src/components/Button/index.js | lucusteen/strap | /**
*
* Button
*
*/
import React from 'react';
import styles from './styles.scss';
class Button extends React.Component {
// eslint-disable-line react/prefer-stateless-function
render() {
return (
<button className={`btn btn-primary ${styles.button}`} {...this.props}>
{this.props.label}
</button>
);
}
}
Button.propTypes = {
label: React.PropTypes.string.isRequired,
};
export default Button;
|
example/examples/PolylineCreator.js | j0ergo/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
let id = 0;
class PolylineCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
polylines: [],
editing: null,
};
}
finish() {
const { polylines, editing } = this.state;
this.setState({
polylines: [...polylines, editing],
editing: null,
});
}
onPanDrag(e) {
const { editing } = this.state;
if (!editing) {
this.setState({
editing: {
id: id++,
coordinates: [e.nativeEvent.coordinate],
},
});
} else {
this.setState({
editing: {
...editing,
coordinates: [
...editing.coordinates,
e.nativeEvent.coordinate,
],
},
});
}
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={this.state.region}
scrollEnabled={false}
onPanDrag={e => this.onPanDrag(e)}
>
{this.state.polylines.map(polyline => (
<MapView.Polyline
key={polyline.id}
coordinates={polyline.coordinates}
strokeColor="#000"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
))}
{this.state.editing &&
<MapView.Polyline
key="editingPolyline"
coordinates={this.state.editing.coordinates}
strokeColor="#F00"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
}
</MapView>
<View style={styles.buttonContainer}>
{this.state.editing && (
<TouchableOpacity
onPress={() => this.finish()}
style={[styles.bubble, styles.button]}
>
<Text>Finish</Text>
</TouchableOpacity>
)}
</View>
</View>
);
}
}
PolylineCreator.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
width: 80,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'row',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
module.exports = PolylineCreator;
|
ui/src/core/components/PluginWrapper.js | mkacper/erlangpl | // @flow
import React, { Component } from 'react';
import { ReflexContainer, ReflexSplitter, ReflexElement } from 'react-reflex';
import 'react-reflex/styles.css';
import Loader from './Loader';
import SidePanel from './SidePanel';
import { Container, Content } from './styled';
type Props = {
sidePanel?: React$Element<*>,
className?: string,
loading?: boolean,
loaderText?: string,
children?: React$Element<*>
};
class PluginWrapper extends Component {
state: { panel: boolean };
constructor(props: Props) {
super(props);
this.state = {
panel: props.sidePanel ? true : false
};
}
static defaultProps = {
className: '',
loaderText: 'Loading...',
loading: false
};
render() {
if (this.props.loading) {
return <Loader text={this.props.loaderText} />;
}
const content = (
<Content>
{this.props.children}
</Content>
);
// NOTE: when no side panel we don't need Relfex
if (!this.state.panel) {
return (
<Container>
{content}
</Container>
);
}
return (
<Container className={this.props.className}>
<ReflexContainer orientation="vertical">
<ReflexElement flex={0.75}>
{content}
</ReflexElement>
<ReflexSplitter
style={{
borderColor: '#181a1f'
}}
/>
<ReflexElement flex={0.25}>
<SidePanel>
{this.props.sidePanel}
</SidePanel>
</ReflexElement>
</ReflexContainer>
</Container>
);
}
}
export default PluginWrapper;
|
app/javascript/mastodon/features/notifications/components/clear_column_button.js | Nyoho/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
export default class ClearColumnButton extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func.isRequired,
};
render () {
return (
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button>
);
}
}
|
js/components/pages/HomePage.react.js | jfrost2420/student_response_front | /*
* HomePage
* This is the first thing users see of our App
*/
import { asyncChangeProjectName, asyncChangeOwnerName } from '../../actions/AppActions';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
class HomePage extends Component {
constructor(props) {
super(props);
//this.state = FooterStore.getState();
//this.onChange = this.onChange.bind(this);
}
componentDidMount() {
//FooterStore.listen(this.onChange);
//FooterActions.getTopCharacters();
console.log('componentDidMount...');
}
componentWillUnmount() {
//FooterStore.unlisten(this.onChange);
console.log('componentWillUnmount...');
}
onChange(state) {
this.setState(state);
}
render() {
const dispatch = this.props.dispatch;
const { projectName, ownerName } = this.props.data;
return (
<div className="container">
<h1>Hello World!</h1>
<h2>This is the demo for the <span className="home__text--red">{ projectName }</span> by <a href={'https://twitter.com/' + ownerName} >@{ ownerName }</a></h2>
<label className="home__label">Change to your project name:
<input className="home__input" type="text" onChange={(evt) => { dispatch(asyncChangeProjectName(evt.target.value)); }} defaultValue="React.js Boilerplate" value={projectName} />
</label>
<label className="home__label">Change to your name:
<input className="home__input" type="text" onChange={(evt) => { dispatch(asyncChangeOwnerName(evt.target.value)); }} defaultValue="mxstbr" value={ownerName} />
</label>
<Link className="btn" to="/readme">Setup</Link>
<button type="button" className="btn btn-primary">Primary</button>
<div className="container">
{ this.props.children }
</div>
</div>
);
}
}
// REDUX STUFF
// Which props do we want to inject, given the global state?
function select(state) {
return {
data: state
};
}
// Wrap the component to inject dispatch and state into it
export default connect(select)(HomePage);
|
admin/client/App/components/Navigation/Mobile/index.js | rafmsou/keystone | /**
* The mobile navigation, displayed on screens < 768px
*/
import React from 'react';
import Transition from 'react-addons-css-transition-group';
import MobileSectionItem from './SectionItem';
const ESCAPE_KEY_CODE = 27;
const MobileNavigation = React.createClass({
displayName: 'MobileNavigation',
propTypes: {
brand: React.PropTypes.string,
currentListKey: React.PropTypes.string,
currentSectionKey: React.PropTypes.string,
sections: React.PropTypes.array.isRequired,
signoutUrl: React.PropTypes.string,
},
getInitialState () {
return {
barIsVisible: false,
};
},
// Handle showing and hiding the menu based on the window size when
// resizing
componentDidMount () {
this.handleResize();
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
},
handleResize () {
this.setState({
barIsVisible: window.innerWidth < 768,
});
},
// Toggle the menu
toggleMenu () {
this[this.state.menuIsVisible ? 'hideMenu' : 'showMenu']();
},
// Show the menu
showMenu () {
this.setState({
menuIsVisible: true,
});
// Make the body unscrollable, so you can only scroll in the menu
document.body.style.overflow = 'hidden';
document.body.addEventListener('keyup', this.handleEscapeKey, false);
},
// Hide the menu
hideMenu () {
this.setState({
menuIsVisible: false,
});
// Make the body scrollable again
document.body.style.overflow = null;
document.body.removeEventListener('keyup', this.handleEscapeKey, false);
},
// If the escape key was pressed, hide the menu
handleEscapeKey (event) {
if (event.which === ESCAPE_KEY_CODE) {
this.hideMenu();
}
},
renderNavigation () {
if (!this.props.sections || !this.props.sections.length) return null;
return this.props.sections.map((section) => {
// Get the link and the classname
const href = section.lists[0].external ? section.lists[0].path : `${Keystone.adminPath}/${section.lists[0].path}`;
const className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'MobileNavigation__section is-active' : 'MobileNavigation__section';
// Render a SectionItem
return (
<MobileSectionItem
key={section.key}
className={className}
href={href}
lists={section.lists}
currentListKey={this.props.currentListKey}
onClick={this.toggleMenu}
>
{section.label}
</MobileSectionItem>
);
});
},
// Render a blockout
renderBlockout () {
if (!this.state.menuIsVisible) return null;
return <div className="MobileNavigation__blockout" onClick={this.toggleMenu} />;
},
// Render the sidebar menu
renderMenu () {
if (!this.state.menuIsVisible) return null;
return (
<nav className="MobileNavigation__menu">
<div className="MobileNavigation__sections">
{this.renderNavigation()}
</div>
</nav>
);
},
render () {
if (!this.state.barIsVisible) return null;
return (
<div className="MobileNavigation">
<div className="MobileNavigation__bar">
<button
type="button"
onClick={this.toggleMenu}
className="MobileNavigation__bar__button MobileNavigation__bar__button--menu"
>
<span className={'MobileNavigation__bar__icon octicon octicon-' + (this.state.menuIsVisible ? 'x' : 'three-bars')} />
</button>
<span className="MobileNavigation__bar__label">
{this.props.brand}
</span>
<a
href={this.props.signoutUrl}
className="MobileNavigation__bar__button MobileNavigation__bar__button--signout"
>
<span className="MobileNavigation__bar__icon octicon octicon-sign-out" />
</a>
</div>
<div className="MobileNavigation__bar--placeholder" />
<Transition
transitionName="MobileNavigation__menu"
transitionEnterTimeout={260}
transitionLeaveTimeout={200}
>
{this.renderMenu()}
</Transition>
<Transition
transitionName="react-transitiongroup-fade"
transitionEnterTimeout={0}
transitionLeaveTimeout={0}
>
{this.renderBlockout()}
</Transition>
</div>
);
},
});
module.exports = MobileNavigation;
|
src/svg-icons/action/redeem.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRedeem = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/>
</SvgIcon>
);
ActionRedeem = pure(ActionRedeem);
ActionRedeem.displayName = 'ActionRedeem';
export default ActionRedeem;
|
src/components/LaborRightsSingle/index.js | goodjoblife/GoodJobShare | import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import ReactPixel from 'react-facebook-pixel';
import R from 'ramda';
import { compose, setStatic } from 'recompose';
import Loader from 'common/Loader';
import { Section } from 'common/base';
import {
formatTitle,
formatCanonicalPath,
formatUrl,
} from 'utils/helmetHelper';
import { isUiNotFoundError } from 'utils/errors';
import NotFound from 'common/NotFound';
import CallToActionFolder from 'common/CallToAction/CallToActionFolder';
import FanPageBlock from 'common/FanPageBlock';
import { withPermission } from 'common/permission-context';
import Body from './Body';
import Footer from './Footer';
import { queryMenu, queryEntry } from '../../actions/laborRights';
import {
isFetching,
isUnfetched,
isError,
isFetched,
} from '../../constants/status';
import { SITE_NAME } from '../../constants/helmetData';
import PIXEL_CONTENT_CATEGORY from '../../constants/pixelConstants';
import { paramsSelector } from 'common/routing/selectors';
import styles from './LaborRightsSingle.module.css';
const idSelector = R.compose(
params => params.id,
paramsSelector,
);
class LaborRightsSingle extends React.Component {
componentDidMount() {
this.props.queryMenuIfUnfetched();
this.props.queryEntryIfUnfetched(idSelector(this.props));
this.props.fetchPermission();
// send Facebook Pixel 'ViewContent' event
ReactPixel.track('ViewContent', {
content_ids: [this.props.match.params.id],
content_category: PIXEL_CONTENT_CATEGORY.VIEW_LABOR_RIGHT,
});
}
componentDidUpdate(prevProps) {
this.props.queryMenuIfUnfetched();
this.props.queryEntryIfUnfetched(idSelector(this.props));
// send Facebook Pixel 'ViewContent' event if goto reading another labor rights unit
if (idSelector(prevProps) !== idSelector(this.props)) {
ReactPixel.track('ViewContent', {
content_ids: [idSelector(this.props)],
content_category: PIXEL_CONTENT_CATEGORY.VIEW_LABOR_RIGHT,
});
}
}
render() {
const { id, title, description, content, coverUrl, nPublicPages } = this
.props.entry
? this.props.entry
: {};
const { seoTitle = title || '', seoDescription, seoText } = this.props.entry
? this.props.entry
: {};
const { entryStatus, entryError } = this.props;
return (
<Section>
<Helmet>
<title itemProp="name" lang="zh-TW">
{seoTitle}
</title>
<meta name="description" content={seoDescription} />
<meta
property="og:title"
content={formatTitle(seoTitle, SITE_NAME)}
/>
<meta property="og:description" content={seoDescription} />
<meta property="og:image" content={formatUrl(coverUrl)} />
<meta
property="og:url"
content={formatCanonicalPath(`/labor-rights/${id}`)}
/>
<link
rel="canonical"
href={formatCanonicalPath(`/labor-rights/${id}`)}
/>
</Helmet>
{R.anyPass([isFetching, isUnfetched])(entryStatus) && <Loader />}
{isError(entryStatus) && isUiNotFoundError(entryError) && <NotFound />}
{isFetched(entryStatus) && (
<div>
<Body
title={title}
seoText={seoText}
description={description}
content={content}
/>
<FanPageBlock className={styles.fanPageBlock} />
{nPublicPages < 0 && (
<Section marginTop>
<CallToActionFolder />
</Section>
)}
<Footer
id={id}
prev={this.props.prevEntry}
next={this.props.nextEntry}
/>
</div>
)}
</Section>
);
}
}
LaborRightsSingle.propTypes = {
match: PropTypes.shape({
params: PropTypes.object.isRequired,
}),
entry: PropTypes.object,
entryStatus: PropTypes.string.isRequired,
entryError: PropTypes.object,
prevEntry: PropTypes.object,
nextEntry: PropTypes.object,
queryMenuIfUnfetched: PropTypes.func.isRequired,
queryEntryIfUnfetched: PropTypes.func.isRequired,
fetchPermission: PropTypes.func.isRequired,
};
const ssr = setStatic('fetchData', ({ store: { dispatch }, ...props }) => {
const id = idSelector(props);
return Promise.all([dispatch(queryMenu()), dispatch(queryEntry(id))]);
});
const hoc = compose(
ssr,
withPermission,
);
export default hoc(LaborRightsSingle);
|
frontend/src/MovieFile/Extras/ExtraFileTableContent.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import IconButton from 'Components/Link/IconButton';
import Table from 'Components/Table/Table';
import TableBody from 'Components/Table/TableBody';
import { icons } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
import ExtraFileRow from './ExtraFileRow';
import styles from './ExtraFileTableContent.css';
const columns = [
{
name: 'relativePath',
label: translate('RelativePath'),
isVisible: true
},
{
name: 'extension',
label: translate('Extension'),
isVisible: true
},
{
name: 'type',
label: translate('Type'),
isVisible: true
},
{
name: 'action',
label: React.createElement(IconButton, { name: icons.ADVANCED_SETTINGS }),
isVisible: true
}
];
class ExtraFileTableContent extends Component {
//
// Render
render() {
const {
items
} = this.props;
return (
<div>
{
!items.length &&
<div className={styles.blankpad}>
No extra files to manage.
</div>
}
{
!!items.length &&
<Table columns={columns}>
<TableBody>
{
items.map((item) => {
return (
<ExtraFileRow
key={item.id}
{...item}
/>
);
})
}
</TableBody>
</Table>
}
</div>
);
}
}
ExtraFileTableContent.propTypes = {
movieId: PropTypes.number,
items: PropTypes.arrayOf(PropTypes.object).isRequired
};
export default ExtraFileTableContent;
|
lib/ui/src/modules/ui/components/left_panel/stories.js | enjoylife/storybook | import PropTypes from 'prop-types';
import React from 'react';
import { baseFonts } from '../theme';
const listStyle = {
...baseFonts,
};
const listStyleType = {
listStyleType: 'none',
paddingLeft: 0,
};
const kindStyle = {
fontSize: 15,
padding: '10px 0px',
cursor: 'pointer',
borderBottom: '1px solid #EEE',
};
const storyStyle = {
fontSize: 13,
padding: '8px 0px 8px 10px',
cursor: 'pointer',
};
class Stories extends React.Component {
constructor(...args) {
super(...args);
this.renderKind = this.renderKind.bind(this);
this.renderStory = this.renderStory.bind(this);
}
fireOnKind(kind) {
const { onSelectStory } = this.props;
if (onSelectStory) onSelectStory(kind, null);
}
fireOnStory(story) {
const { onSelectStory, selectedKind } = this.props;
if (onSelectStory) onSelectStory(selectedKind, story);
}
renderStory(story) {
const { selectedStory } = this.props;
const style = { display: 'block', ...storyStyle };
const props = {
onClick: this.fireOnStory.bind(this, story),
};
if (story === selectedStory) {
style.fontWeight = 'bold';
}
return (
<li key={story}>
<a
title={`Open ${story}`}
style={style}
onClick={props.onClick}
role="menuitem"
tabIndex="0"
>
{story}
</a>
</li>
);
}
renderKind({ kind, stories }) {
const { selectedKind } = this.props;
const style = { display: 'block', ...kindStyle };
const onClick = this.fireOnKind.bind(this, kind);
if (kind === selectedKind) {
style.fontWeight = 'bold';
return (
<li key={kind}>
<a title={`Open ${kind}`} style={style} onClick={onClick} role="menuitem" tabIndex="0">
{kind}
</a>
<div>
<ul style={listStyleType} role="menu">
{stories.map(this.renderStory)}
</ul>
</div>
</li>
);
}
return (
<li key={kind}>
<a title={`Open ${kind}`} style={style} onClick={onClick} role="menuitem" tabIndex="0">
{kind}
</a>
</li>
);
}
render() {
const { stories } = this.props;
return (
<div style={listStyle}>
<ul style={listStyleType} role="menu">
{stories.map(this.renderKind)}
</ul>
</div>
);
}
}
Stories.defaultProps = {
stories: [],
onSelectStory: null,
};
Stories.propTypes = {
stories: PropTypes.arrayOf(
PropTypes.shape({
kind: PropTypes.string,
stories: PropTypes.array,
})
),
selectedKind: PropTypes.string.isRequired,
selectedStory: PropTypes.string.isRequired,
onSelectStory: PropTypes.func,
};
export default Stories;
|
src/cell/explain.js | HVF/franchise | import React from 'react'
import ReactDOM from 'react-dom'
import classList from 'classnames'
export class ExplainVisualizer extends React.Component {
static key = 'explain'
static desc = 'Explain Visualizer'
static icon = <i className="fa fa-cogs" />
static test(result) {
return result.columns[0] === 'QUERY PLAN'
}
render() {
// <PlanView root={this.props.result.values[0][0][0]} />
let result = this.props.result
if (typeof result.values[0][0] != 'object') {
return (
<div className="single-row">
Run with <code>EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON)</code> to
use Postgres Explain Visualizer
</div>
)
}
// console.log(result.values[0][0][0])
return (
<div className="single-row">
<PlanView roots={result.values[0][0]} />
</div>
)
}
}
function PlanView({ roots }) {
return (
<div className="plan">
<ul>
{roots.map((k, i) => (
<li key={i}>
<PlanNode plan={k.Plan} />
</li>
))}
</ul>
</div>
)
}
function PlanNode({ plan }) {
return (
<div className="plan-node-root">
<div className="plan-node">
<header>
<h4>{plan['Node Type']}</h4>
<span>
<span className="node-duration">
{plan['Actual Total Time']}
<span className="text-muted">s | </span>
<strong>42</strong>
<span className="text-muted">%</span>
</span>
</span>
</header>
</div>
{plan.Plans ? (
<ul>
{plan.Plans.map((k, i) => (
<li key={i}>
<PlanNode plan={k} />
</li>
))}
</ul>
) : null}
</div>
)
}
|
src/withLocalState.js | zaptree/pyradux | import React, { Component } from 'react';
import Provider from './Provider';
import PropTypes from 'prop-types';
export default function withLocalState({createStore, ...options}, WrappedComponent) {
class WithLocalStateComponent extends Component {
constructor(props, context){
super(props, context);
this.createStore = createStore || context.createStore;
if(!this.createStore){
throw new Error('No createStore method available to create local store');
}
if(!options.reducer){
throw new Error('withLocalState expects the reducer property to be set');
}
this.store = this.createStore(options);
}
render() {
return (
<Provider store={this.store} createStore={this.createStore} storeContext={this.props.storeContext}>
<WrappedComponent {...this.props} />
</Provider>
);
}
}
WithLocalStateComponent.contextTypes = {
createStore: PropTypes.func
};
return WithLocalStateComponent
}
|
node_modules/react-bootstrap/es/Popover.js | C0deSamurai/muzjiks | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])),
/**
* Sets the direction the Popover is positioned towards.
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "top" position value for the Popover.
*/
positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "left" position value for the Popover.
*/
positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "top" position value for the Popover arrow.
*/
arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "left" position value for the Popover arrow.
*/
arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* Title content
*/
title: React.PropTypes.node
};
var defaultProps = {
placement: 'right'
};
var Popover = function (_React$Component) {
_inherits(Popover, _React$Component);
function Popover() {
_classCallCheck(this, Popover);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Popover.prototype.render = function render() {
var _extends2;
var _props = this.props,
placement = _props.placement,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
title = _props.title,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2));
var outerStyle = _extends({
display: 'block',
top: positionTop,
left: positionLeft
}, style);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'tooltip',
className: classNames(className, classes),
style: outerStyle
}),
React.createElement('div', { className: 'arrow', style: arrowStyle }),
title && React.createElement(
'h3',
{ className: prefix(bsProps, 'title') },
title
),
React.createElement(
'div',
{ className: prefix(bsProps, 'content') },
children
)
);
};
return Popover;
}(React.Component);
Popover.propTypes = propTypes;
Popover.defaultProps = defaultProps;
export default bsClass('popover', Popover); |
geonode/monitoring/frontend/monitoring/src/components/cels/health-check/index.js | tomkralidis/geonode | /*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# 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 PropTypes from 'prop-types';
import { connect } from 'react-redux';
import HoverPaper from '../../atoms/hover-paper';
import styles from './styles';
const mapStateToProps = (state) => ({
alertList: state.alertList.response,
errorList: state.errorList.response,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps)
class HealthCheck extends React.Component {
static propTypes = {
alertList: PropTypes.object,
errorList: PropTypes.object,
style: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
}
render() {
const alertList = this.props.alertList;
const alertNumber = alertList && alertList.data
? alertList.data.problems.length
: 0;
const alertStyle = alertNumber > 0
? { backgroundColor: '#ffa031', color: '#fff' }
: {};
const errorNumber = this.props.errorList
? this.props.errorList.exceptions.length
: 0;
const errorStyle = errorNumber > 0
? { backgroundColor: '#d12b2b', color: '#fff' }
: {};
const style = {
...styles.content,
...this.props.style,
...alertStyle,
...errorStyle,
};
return (
<HoverPaper style={style}>
<h3>Health Check</h3>
<div style={styles.stat}>
{alertNumber} alerts<br />
{errorNumber} errors
</div>
</HoverPaper>
);
}
}
export default HealthCheck;
|
examples/official-storybook/stories/addon-info/forward-ref.stories.js | storybooks/react-storybook | import React from 'react';
import { withInfo } from '@storybook/addon-info';
import ForwardedRefButton from '../../components/ForwardedRefButton';
import ForwardedRefButtonWDisplayName from '../../components/ForwardedRefButtonWDisplayName';
export default {
title: 'Addons/Info/ForwardRef',
decorators: [withInfo],
};
export const DisplaysCorrectly = () => <ForwardedRefButton label="Forwarded Ref Button" />;
DisplaysCorrectly.story = { name: 'Displays forwarded ref components correctly' };
export const DisplayName = () => (
<ForwardedRefButtonWDisplayName label="Forwarded Ref Button w/ Display Name" />
);
DisplayName.story = { name: 'Uses forwardRef displayName if available' };
|
src/shared/components/linkButton/linkButton.js | OperationCode/operationcode_frontend | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Link as ScrollLink, Events as ScrollEvent } from 'react-scroll';
import ReactGA from 'react-ga';
import styles from './linkButton.css';
const LinkButton = ({
link,
text,
theme,
scrollLink,
isExternal,
...otherProps
}) => {
/* ******************** */
/* SCROLL LINK BUTTON */
/* ******************** */
if (scrollLink) {
// Report scroll link button clicks to Google Analytics
if (process.env.NODE_ENV === 'production') {
ScrollEvent.scrollEvent.register('begin', () => {
ReactGA.event({
category: 'Scroll Button Clicked',
action: `Clicked to view ${link} from ${window.location.pathname}`,
});
});
}
return (
<ScrollLink
className={`${styles.linkButton} ${styles[theme]}`}
to={link}
smooth
duration={400}
{...otherProps}
>
{text}
</ScrollLink>
);
}
/* ******************** */
/* EXTERNAL LINK BUTTON */
/* ******************** */
if (isExternal) {
if (process.env.NODE_ENV === 'production') {
return (
<ReactGA.OutboundLink
to={link}
eventLabel={`OUTBOUND [${text} Button Click] to ${link} from ${window
.location.pathname}`}
target="_blank"
rel="noopener noreferrer"
className={`${styles.linkButton} ${styles[theme]}`}
>
{text}
</ReactGA.OutboundLink>
);
}
return (
<a
href={link}
target="_blank"
rel="noopener noreferrer"
className={`${styles.linkButton} ${styles[theme]}`}
>
{text}
</a>
);
}
/* ******************** */
/* INTERNAL LINK BUTTON */
/* ******************** */
return (
<Link
className={`${styles.linkButton} ${styles[theme]}`}
to={link}
{...otherProps}
>
{text}
</Link>
);
};
LinkButton.propTypes = {
link: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
theme: PropTypes.string,
scrollLink: PropTypes.bool,
isExternal: PropTypes.bool,
};
LinkButton.defaultProps = {
theme: 'blue',
scrollLink: false,
isExternal: false,
};
export default LinkButton;
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch03/03_04/finish/src/components/SkiDayCount.js | yevheniyc/Autodidact | import React from 'react'
import '../stylesheets/ui.scss'
export const SkiDayCount = React.createClass({
percentToDecimal(decimal) {
return ((decimal * 100) + '%')
},
calcGoalProgress(total, goal) {
return this.percentToDecimal(total/goal)
},
render() {
return (
<div className="ski-day-count">
<div className="total-days">
<span>{this.props.total}</span>
<span>days</span>
</div>
<div className="powder-days">
<span>{this.props.powder}</span>
<span>days</span>
</div>
<div className="backcountry-days">
<span>{this.props.backcountry}</span>
<span>days</span>
</div>
<div>
<span>
{this.calcGoalProgress(
this.props.total,
this.props.goal
)}
</span>
</div>
</div>
)
}
}) |
src/client/common/components/SimpleList.js | jmicmoore/merit-badge-university | import React from 'react';
import PropTypes from 'prop-types';
class SimpleList extends React.Component{
render(){
const propertyName = this.props.propertyName;
const dataList = this.props.dataList;
return (
<div className="form-group">
<label htmlFor={propertyName}>{this.props.displayName}</label>
<ul id={propertyName} className="list-group">
{
dataList.map( item => {return(<li key={item} className="list-group-item">{item}</li>);})
}
</ul>
</div>
);
}
};
SimpleList.propTypes = {
propertyName: PropTypes.string.isRequired,
displayName: PropTypes.string.isRequired,
dataList: PropTypes.array.isRequired
};
export default SimpleList; |
ee/app/engagement-dashboard/client/components/data/Histogram.js | VoiSmart/Rocket.Chat | import { ResponsiveBar } from '@nivo/bar';
import { Box, Flex } from '@rocket.chat/fuselage';
import React from 'react';
import { polychromaticColors } from './colors';
export function Histogram() {
return <Flex.Item align='stretch' grow={1} shrink={0}>
<Box style={{ position: 'relative' }}>
<Box style={{ position: 'absolute', width: '100%', height: '100%' }}>
<ResponsiveBar
data={[
{
utc: '-3',
users: Math.round(100 * Math.random()),
},
{
utc: '-5',
users: Math.round(100 * Math.random()),
},
{
utc: '+2',
users: Math.round(100 * Math.random()),
},
{
utc: '+8',
users: Math.round(100 * Math.random()),
},
{
utc: '-6',
users: Math.round(100 * Math.random()),
},
{
utc: '16',
users: Math.round(100 * Math.random()),
},
]}
indexBy='utc'
keys={['users']}
groupMode='grouped'
layout='horizontal'
padding={0.25}
margin={{ left: 64, bottom: 20 }}
colors={[polychromaticColors[2]]}
enableLabel={false}
enableGridX
enableGridY={false}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 0,
tickPadding: 5,
tickRotation: 0,
format: (users) => `${ users }%`,
}}
axisLeft={{
tickSize: 0,
tickPadding: 5,
tickRotation: 0,
format: (utc) => `UTF ${ utc }`,
}}
animate={true}
motionStiffness={90}
motionDamping={15}
theme={{
font: 'inherit',
fontStyle: 'normal',
fontWeight: 600,
fontSize: 10,
lineHeight: 12,
letterSpacing: 0.2,
color: '#9EA2A8',
grid: {
line: {
stroke: '#CBCED1',
strokeWidth: 1,
strokeDasharray: '4 1.5',
},
},
}}
/>
</Box>
</Box>
</Flex.Item>;
}
|
example/main.js | bgrsquared/d3-react-squared-c3-loader | require('babel/polyfill');
import React from 'react';
import ReactDOM from 'react-dom';
// load example component
import C3Example from './c3example';
ReactDOM.render(<C3Example/>, document.getElementById('app'));
|
screens/ProductDetailScreen/Feature.js | nattatorn-dev/expo-with-realworld | import React from 'react'
import { TouchableOpacity, Text, View } from 'react-native'
import PropTypes from 'prop-types'
import styles from './FeatureStyle'
const Feature = ( { description, index, onPressFeature, title } ) => (
<View style={styles.containerStyle}>
<View style={{ flexDirection: 'row' }}>
<View style={styles.prefix}>
<Text style={styles.textIndent}>{''}</Text>
</View>
<View style={{ flexDirection: 'column' }}>
<View style={styles.sectionTitle}>
<View style={styles.rowTitle}>
<Text style={styles.textTitle}>{title}</Text>
</View>
</View>
<View style={styles.sectionDescription}>
<View style={styles.rowDescription}>
<Text
multiline={true}
numberOfLines={2}
style={styles.textDescription}
>
{description}
</Text>
</View>
<View style={styles.rowMores}>
<TouchableOpacity onPress={() => onPressFeature( index )}>
<Text style={styles.textMores}>{'more'}</Text>
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
)
Feature.propTypes = {
description: PropTypes.string.isRequired,
index: PropTypes.number.isRequired,
onPressFeature: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
}
export default Feature
|
src/client/components/ResourceDisplayComponent.js | mitola/awesome-game | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import List, { ListItem, ListItemIcon, ListItemText, ListItemSecondaryAction} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import InfoIcon from 'material-ui-icons/Info';
import AddToQueueIcon from 'material-ui-icons/AddToQueue';
import ListSubheader from 'material-ui/List/ListSubheader';
import Button from 'material-ui/Button';
import Chip from 'material-ui/Chip';
const styles = theme => ({
root: {
width: '100%',
maxWidth: 1000,
background: theme.palette.background.paper,
},
});
function ResourceDisplayComponent(props) {
const classes = props.classes;
return (
<div className={classes.row}>
<Chip label="Resource 1" className={classes.chip} />
<Chip label="Resource 2" className={classes.chip} />
<List className={classes.root}>
<ListItemText primary="Reasource 1" />
<ListItemText primary="Reasource 2" />
<ListItemText primary="Reasource 3" />
</List>
</div>
);
}
ResourceDisplayComponent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ResourceDisplayComponent); |
src/utils/helper.js | phodal/growth-ng | import React from 'react';
import { Platform, Linking } from 'react-native';
import { Icon } from 'react-native-elements';
import { Actions } from 'react-native-router-flux';
class Helper {
static openLink(link) {
Linking.canOpenURL(link).then((supported) => {
if (supported) {
Linking.openURL(link);
}
});
}
static getProfessionalSkilltree() {
let url = 'http://phodal.github.io/motree';
if (Platform.OS === 'android') {
url = 'market://details?id=ren.growth.skilltree';
} else if (Platform.OS === 'ios') {
url = 'https://itunes.apple.com/cn/app/growth-ji-neng-shu-phodal/id1193898864?mt=8';
}
Linking.canOpenURL(url).then((supported) => {
if (supported) {
Linking.openURL(url);
}
});
}
static getMoreFeatures() {
Helper.openLink('https://github.com/phodal/growth-ng/issues');
}
static openFreeBookGitHub() {
Helper.openLink('https://github.com/justjavac/free-programming-books-zh_CN');
}
static openMDNRegex() {
Helper.openLink('https://github.com/justjavac/free-programming-books-zh_CN');
}
static openDPGitHub() {
Helper.openLink('https://github.com/kamranahmedse/design-patterns-for-humans');
}
static openAlgorithmGitHub() {
Helper.openLink('https://github.com/parkjs814/AlgorithmVisualizer');
}
static gotoLogin() {
return (
<Icon
name={'md-person'} type={'ionicon'} color={'#fff'}
onPress={() => Actions.forumUserCenter()}
/>
);
}
}
export default Helper;
|
app/js/views/forms.js | maxmechanic/resumaker | import React from 'react';
import resumeStructures from './resume-structures';
import { capitalize } from 'lodash';
const buildForm = ([section, attributes]) => props => {
const handleSubmit = (e) => {
e.preventDefault();
props.handleSubmit(section, e.target);
};
return (
<form onSubmit={handleSubmit}>
{
attributes.map(({attribute: attr, placeholder}) => (
<div className="form-group">
<label htmlFor={attr}>{capitalize(attr)}</label>
<input type="text" placeholder={placeholder} className="form-control" name={attr} />
</div>
))
}
<button type="submit" className="btn btn-default btn-lg btn-block">Save</button>
</form>
)
};
export default resumeStructures.map(r => ({section: r[0], component: buildForm(r)})); |
app/containers/App.js | StatEngine/spade | // @flow
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import injectTapEventPlugin from 'react-tap-event-plugin';
import type { Children } from 'react'
injectTapEventPlugin();
export default class App extends Component {
props: {
children: Children
};
render() {
const maxHeight = window.innerHeight - 64;
return (
<MuiThemeProvider>
<div>
<AppBar
title="Spade"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
<div style={{ maxHeight: maxHeight, overflow: 'auto' }}>
{this.props.children}
</div>
</div>
</MuiThemeProvider>
);
}
}
|
ui/js/dfv/src/admin/edit-pod/edit-pod-name.js | pods-framework/pods | import React from 'react';
import PropTypes from 'prop-types';
// WordPress dependencies
import { __ } from '@wordpress/i18n';
// Pods dependencies
import Sluggable from 'dfv/src/components/sluggable';
const EditPodName = ( {
podName,
setPodName,
isEditable,
} ) => {
return (
<h2>
{ __( 'Edit Pod: ', 'pods' ) }
{ '\u00A0' /* */ }
{ isEditable ? (
<Sluggable
value={ podName }
updateValue={ setPodName }
/>
) : (
<strong>
{ podName }
</strong>
) }
</h2>
);
};
EditPodName.propTypes = {
podName: PropTypes.string.isRequired,
setPodName: PropTypes.func.isRequired,
isEditable: PropTypes.bool.isRequired,
};
export default EditPodName;
|
src/components/home.js | thbgh/antdPro | /**
* @Author: THB
* @Date: 2017-07-26 20:50:59 PM Wednesday
* @Email: [email protected]
* @Filename: home.js
* @Last modified by: THB
* @Last modified time: 2017-09-04 14:36:30 PM Monday
*/
import React, { Component } from 'react';
import './home.less';
import Complete from './autoComplete';
import Ccascader from './cascader';
import CCheckbox from './checkbox';
import Datep from './datePicker';
import Sselect from './select';
import Uupload from './upload';
import Ccollapse from './collapse';
import Ttree from './tree';
import Mmodal from './modal';
import { Row, Col } from 'antd';
import {
Menu,
Dropdown,
Icon,
message,
Button,
Steps,
Carousel,
Tooltip,
Progress
} from 'antd';
import { Rate } from 'antd';
import { Switch } from 'antd';
import { Anchor } from 'antd';
import { BackTop } from 'antd';
const { Link, AnchorLink } = Anchor;
const Step = Steps.Step;
export default class Home extends Component {
onSelect = (selectedKeys, info) => {
console.log('selected', selectedKeys, info);
};
onCheck = (checkedKeys, info) => {
console.log('onCheckhahahahhqa', checkedKeys, info);
};
render() {
const onClick = function({ item, key, keyPath }) {
message.info(`Click on item ${item.props.dataValue}`);
console.log(item.props.dataValue);
};
const menu = (
<Menu onClick={onClick}>
<Menu.Item key="1" dataValue="1st menu item">
1st menu item
</Menu.Item>
<Menu.Item key="2" dataValue="2nd menu item">
2nd memu item
</Menu.Item>
<Menu.Item key="3" dataValue="3rd menu item">
3rd menu item
</Menu.Item>
</Menu>
);
const onChangeSwitch = checked => {
console.log(`switch to ${checked}`);
};
return (
<div>
<BackTop />
{/* <Anchor>
<Link href="#components-anchor-demo-basic" title="Basic demo" />
<Link href="#components-anchor-demo-fixed" title="Fixed demo" />
<Link href="#API" title="API">
<Link href="#Anchor-Props" title="Anchor Props" />
<Link href="#Link-Props" title="Link Props" />
</Link>
</Anchor> */}
<Anchor>
<Link href="#xxx">xxxx</Link>
<Link href="#yyy">yyyy</Link>
</Anchor>
<div id="xxx">xxxxxxxxx</div>
{/* <div id="yyy">yyyyyyyyy</div> */}
{/* <div>
<BackTop />
Scroll down to see the bottom-right
<strong style={{ color: 'rgba(64, 64, 64, 0.6)' }}> gray </strong>
button.
</div> */}
<div style={{ textAlign: 'center' }} className="title">
<a href="#components-anchor-demo-basic" className="anchor">
#
</a>
<h1>Home</h1>
<h2>这是我的antd项目</h2>
</div>
<br />
<br />
<div className="gutter-example">
<Row gutter={16}>
<Col className="gutter-row" span={6}>
<div className="gutter-box">
col-6
<h1>Home</h1>
<h2>这是我的antd项目</h2>
</div>
</Col>
<Col className="gutter-row" span={6}>
<div className="gutter-box">col-6</div>
</Col>
<Col className="gutter-row" span={6}>
<div className="gutter-box">col-6</div>
</Col>
<Col className="gutter-row" span={6}>
<div className="gutter-box">col-6</div>
</Col>
</Row>
</div>
<br />
<br />
<Dropdown overlay={menu} trigger={['click']}>
<Button className="ant-dropdown-link">
Hover me, Click menu item <Icon type="down" />
</Button>
</Dropdown>
<br />
<br />
<Steps>
<Step status="finish" title="Login" icon={<Icon type="user" />} />
<Step
status="process"
title="Verification"
icon={<Icon type="solution" />}
/>
<Step status="wait" title="Pay" icon={<Icon type="credit-card" />} />
<Step status="wait" title="Done" icon={<Icon type="smile-o" />} />
</Steps>
<br />
<br />
<Complete />
<br />
<br />
<Ccascader />
<br />
<br />
<CCheckbox />
<br />
<br />
<Datep />
<br />
<br />
<Rate allowHalf defaultValue={2.5} />
<br />
<br />
<Sselect />
<br />
<br />
<div>
<Switch
checkedChildren="开"
unCheckedChildren="关"
onChange={onChangeSwitch}
/>
<br />
<Switch
checkedChildren="1"
unCheckedChildren="0"
onChange={onChangeSwitch}
/>
<br />
</div>
<div id="yyy">yyyyyyyyy</div>
<br />
<br />
<Uupload />
<br />
<br />
<Ccollapse />
{/* <Carousel autoplay>
<div><h3>1</h3></div>
<div><h3>2</h3></div>
<div><h3>3</h3></div>
<div><h3>4</h3></div>
</Carousel> */}
<Tooltip placement="topLeft" title="Prompt Text" arrowPointAtCenter>
<Button>Arrow points to center / 箭头指向中心</Button>
</Tooltip>
<br />
<br />
<Ttree />
<br />
<br />
<Mmodal />
<br />
<br />
<div>
<Progress
type="circle"
percent={75}
format={percent => `${percent} Days`}
/>
<Progress type="circle" percent={100} format={() => 'Done'} />
</div>
{/* <div style={{position:"fixed",left:0,right:0,top:0,bottom:0,backgroundColor:" rgba(0, 0, 0, 0.43)"}}>
<p style={{color:"red"}}>弹出浮层</p>
</div> */}
<p style={{ color: 'red' }}>弹出浮层,已经隐藏</p>
{/* <div className="musk-container">
<p className="musk-container-content" style={{color:"red"}}>弹出浮层</p>
</div> */}
</div>
);
}
}
|
src/layout/SKLayout.js | ShaneKing/sk-antd | import {Layout} from 'antd';
import React from 'react';
import {SK} from 'sk-js';
import OriginLayout from './OriginLayout';
import AntdComp from '../AntdComp';
export default class SKLayout extends AntdComp {
static SK_COMP_NAME = 'SKLayout';
static defaultProps = SK.extends(true, {}, AntdComp.defaultProps, OriginLayout.defaultProps, {
compTag: Layout,
});
static propTypes = SK.extends(true, {}, AntdComp.propTypes, OriginLayout.propTypes, {});
constructor(...args) {
super(...args);
this.SK_COMP_NAME = SKLayout.SK_COMP_NAME;
}
}
|
packages/leaflet/src/components/Legend.js | wq/wq.app | import React from 'react';
import PropTypes from 'prop-types';
import { LayersControl } from 'react-leaflet';
const { BaseLayer, Overlay } = LayersControl;
export default function Legend({ position, collapsed, children }) {
if (!position) {
position = 'topright';
}
if (collapsed === undefined) {
collapsed = true;
}
return (
<LayersControl position={position} collapsed={collapsed}>
{children}
</LayersControl>
);
}
Legend.propTypes = {
position: PropTypes.object,
collapsed: PropTypes.bool,
children: PropTypes.node
};
export function BasemapToggle({ name, active, children, ...rest }) {
return (
<BaseLayer name={name} checked={active} {...rest}>
{children}
</BaseLayer>
);
}
BasemapToggle.propTypes = {
name: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node
};
export function OverlayToggle({ name, active, children, ...rest }) {
return (
<Overlay name={name} checked={active} {...rest}>
{children}
</Overlay>
);
}
OverlayToggle.propTypes = {
name: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node
};
|
src/reducers/panes.js | LaserWeb/LaserWeb4 | /**
* Panes reducer.
* @module
*/
// React
import React from 'react'
// Actions
import * as panesActions from '../actions/panes'
export const PANES_INITIALSTATE='cam'
/**
* Handle visible state.
* @function
* @protected
* @param {Array} panes The current panes collection.
* @param {module:lib/redux-action~Action} action The action to execute.
* @return {Array} The new panes collection.
*/
function handleVisible(state = {}, action) {
let visible = state.visible !== undefined ? state.visible : true
switch (action.type) {
case panesActions.selectPane.TYPE:
return !visible || action.payload.id !== state.selected;
default:
return visible
}
}
function handleSelected(state = PANES_INITIALSTATE, action) {
switch (action.type) {
case panesActions.selectPane.TYPE:
return action.payload.id;
default:
return state;
}
}
/**
* Handle dock state.
* @function
* @param {Object} state The current state.
* @param {module:lib/redux-action~Action} action The action to execute.
* @return {Array} The new state.
*/
function panes(state = {}, action) {
return {
visible: handleVisible(state, action),
selected: handleSelected(state.selected, action),
}
}
// Exports
export default panes
|
public/src/redux/todos/index.js | codelegant/myReact | /**
* Author: 赖传峰
* Email: [email protected]
* homepage: laichuanfeng.com
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import todoApp from './reducers/index';
import App from './components/App';
ReactDOM.render(
<Provider store={createStore(todoApp)}>
<App />
</Provider>
, document.getElementById('container')); |
app/app.js | olivia-leach/jaylivia-react | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./assets/images/hotel.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/woodstock.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/camping.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/emerson.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/bestwestern.jpeg';
import '!file-loader?name=[name].[ext]!./assets/images/kates.jpg';
// import '!file-loader?name=[name].[ext]!./assets/images/rsvp.png';
import '!file-loader?name=[name].[ext]!./assets/images/rosie.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/rosie2.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/proposal.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/thelodge.jpg';
import '!file-loader?name=[name].[ext]!./assets/images/woods.jpg';
import '!file-loader?name=[name].[ext]!./assets/theLodge.pdf';
import '!file-loader?name=[name].[ext]!./assets/images/paper.jpg';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
import './global-styles';
// import styles
import 'stylesheets/style.scss';
// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const ralewayObserver = new FontFaceObserver('Raleway', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
ralewayObserver.load().then(() => {
document.body.classList.add('fontLoaded');
}, () => {
document.body.classList.remove('fontLoaded');
});
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(System.import('intl'));
}))
.then(() => Promise.all([
System.import('intl/locale-data/jsonp/de.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
app/components/pages/NotFound.js | dariobanfi/react-avocado-starter | import React, { Component } from 'react';
import PropTypes from 'prop-types';
class NotFound extends Component {
componentWillMount() {
const { staticContext } = this.props;
if (staticContext) {
staticContext.missed = true;
}
}
render() {
return <div>Sorry, that page was not found.</div>;
}
}
NotFound.propTypes = {
// eslint-disable-next-line react/forbid-prop-types
staticContext: PropTypes.object
};
NotFound.defaultProps = {
staticContext: {}
};
export default NotFound;
|
src/svg-icons/device/sd-storage.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSdStorage = (props) => (
<SvgIcon {...props}>
<path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 6h-2V4h2v4zm3 0h-2V4h2v4zm3 0h-2V4h2v4z"/>
</SvgIcon>
);
DeviceSdStorage = pure(DeviceSdStorage);
DeviceSdStorage.displayName = 'DeviceSdStorage';
DeviceSdStorage.muiName = 'SvgIcon';
export default DeviceSdStorage;
|
src/widget/SearchBar.js | Cowboy1995/JZWXZ | /**
* Copyright (c) 2017-present, Liu Jinyong
* All rights reserved.
*
* https://github.com/huanxsd/MeiTuan
* @flow
*/
import React, { Component } from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity, Text, Image, Keyboard } from 'react-native';
import { screen, system, tool } from '../common'
class SearchBar extends Component {
props: {
onSubmitEditing: Function,
text: string,
onChangeText: Function,
onSubmit: Function,
style: Object
}
state: {
text: string
}
constructor(props: Object) {
super(props);
this.state = {
text: this.props.text,
};
}
onChangeText(text: string) {
this.setState({ text: text });
this.props.onChangeText && this.props.onChangeText()
}
onSubmitEditing() {
if (this.props.onSubmit) {
this.props.onSubmit(this.state.text);
}
}
click() {
if (system.isIOS) {
//取消
} else {
//搜索
this.onSubmitEditing();
}
Keyboard.dismiss();
}
render() {
return (
<View style={[styles.container, this.props.style]}>
<View style={styles.inputContainer}>
<Image
style={styles.icon}
source={require('../img/Home/search_icon.png')}
/>
<TextInput
ref='input'
style={styles.input}
placeholder='搜索'
returnKeyType='search'
onSubmitEditing={this.onSubmitEditing.bind(this)}
onChangeText={(text) => { this.onChangeText(text) }}
underlineColorAndroid='transparent'
/>
</View>
<TouchableOpacity
onPress={this.click.bind(this)}
style={styles.cancelBtn}>
<Text style={styles.cancelText}>
{system.isIOS ? '取消' : '搜索'}
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 32,
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 7,
},
inputContainer: {
flex: 1,
height: 32,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#e4e4e4',
borderRadius: 5,
},
icon: {
marginLeft: 10,
width: 21,
height: 21,
},
cancelBtn: {
width: 55,
justifyContent: 'center',
alignItems: 'center',
},
cancelText: {
color: '#4683ca',
fontSize: 14,
},
input: {
flex: 1,
marginHorizontal: 5,
}
});
export default SearchBar; |
src/svg-icons/device/signal-cellular-connected-no-internet-3-bar.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet3Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M17 22V7L2 22h15zm3-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet3Bar = pure(DeviceSignalCellularConnectedNoInternet3Bar);
DeviceSignalCellularConnectedNoInternet3Bar.displayName = 'DeviceSignalCellularConnectedNoInternet3Bar';
export default DeviceSignalCellularConnectedNoInternet3Bar;
|
examples/js/nextjs/pages/_app.js | bugsnag/bugsnag-js | import React from 'react'
import App, { Container } from 'next/app'
import Bugsnag from '../lib/bugsnag'
import Error from './_error'
const ErrorBoundary = Bugsnag.getPlugin('react')
export default class MyApp extends App {
static async getInitialProps ({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
render () {
const { Component, pageProps } = this.props
return (
<ErrorBoundary FallbackComponent={Error}>
<Container>
<Component {...pageProps} />
</Container>
</ErrorBoundary>
)
}
}
|
src/scrollWrapper/index.js | denisraslov/react-spreadsheet-table | import React from 'react';
import PropTypes from 'prop-types';
import Grid from '../grid';
import ScrollDummy from './../scrollDummy';
import slice from 'lodash.slice';
import throttleWithRAF from './../kit/throttleWithRAF';
import tablePropTypes from './../kit/tablePropTypes';
import styles from './styles.css';
const RESERVE_ROWS_COUNT = 3;
class SpreadsheetGridScrollWrapper extends React.PureComponent {
constructor(props) {
super(props);
this.onScroll = this.onScroll.bind(this);
this.onResize = this.onResize.bind(this);
this.setScrollState = this.setScrollState.bind(this);
this.startColumnResize = this.startColumnResize.bind(this);
this.processColumnResize = this.processColumnResize.bind(this);
this.tableEl = React.createRef()
this.scrollDummyEl = React.createRef()
this.scrollWrapperEl = React.createRef()
this.grid = React.createRef()
this.state = {
first: 0,
last: this.calculateInitialLast(),
offset: 0,
columnWidthValues: {}
};
// if requestAnimationFrame is available, use it to throttle refreshState
if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
this.setScrollState = throttleWithRAF(this.setScrollState);
}
}
componentDidMount() {
this.freezeTable();
if (this.props.isColumnsResizable) {
document.addEventListener('mousemove', this.processColumnResize, false);
document.addEventListener('mouseup', () => {
this.resizingCell = null;
}, false);
}
window.addEventListener('resize', this.onResize, false);
this.setScrollState();
}
componentDidUpdate(prevProps) {
const { columns, rows } = this.props;
// If columns has been changed, recalculate their width values.
if (prevProps.columns !== columns) {
this.freezeTable();
}
if (rows !== prevProps.rows) {
this.setScrollState();
}
}
componentWillUnmount() {
if (this.props.isColumnsResizable) {
document.removeEventListener('mousemove', this.processColumnResize, false);
document.removeEventListener('mouseup', () => {
this.resizingCell = null;
}, false);
}
window.removeEventListener('resize', this.onResize, false);
}
resetScroll() {
this.scrollWrapperEl.current.scrollTop = 0;
this.setScrollState();
}
focusCell(nextFocusedCell) {
this.grid.current.focusCell(nextFocusedCell);
}
freezeTable() {
const table = this.tableEl.current;
// There is no grid when Jest is running tests
if (table) {
const cells = table.querySelectorAll('.SpreadsheetGrid__headCell');
const { columns } = this.props;
let columnWidthValues = columns
.reduce(((widths, column) => {
widths[column.id] = column.width;
return widths;
}), {})
let sumOfWidth = 0;
Object.keys(columnWidthValues).forEach((id) => {
sumOfWidth += columnWidthValues[id];
});
if (Math.round(sumOfWidth) > 100) {
console.error('react-spreadsheet-grid ERROR: The sum of column width values in ' +
'the "columnWidthValues" property is more then 100 percents! ' +
'The values are not being used in this condition!');
columnWidthValues = {};
}
let restTableWidth = 100;
let restColumnsCount = cells.length;
const preparedColumnWidthValues = {};
cells.forEach((cell, i) => {
const id = this.props.columns[i].id;
if (columnWidthValues[id]) {
preparedColumnWidthValues[id] = columnWidthValues[id];
restTableWidth -= columnWidthValues[id];
restColumnsCount--;
}
});
cells.forEach((cell, i) => {
const id = this.props.columns[i].id;
if (!columnWidthValues[id]) {
preparedColumnWidthValues[id] = restTableWidth / restColumnsCount;
}
});
this.setState({
columnWidthValues: preparedColumnWidthValues
});
}
}
startColumnResize(e) {
this.resizingCell = e.currentTarget.offsetParent;
this.resizingCell.startOffset = this.resizingCell.offsetWidth - e.pageX;
this.nextResizingCell = this.resizingCell.nextSibling;
this.nextResizingCell.startOffset =
document.body.offsetWidth -
this.nextResizingCell.offsetWidth -
e.pageX;
}
processColumnResize(e, nextCell) {
let direction;
let sibling;
const table = this.tableEl.current;
const tableWidth = table.offsetWidth;
const columns = this.props.columns;
if (this.currentCoords <= e.pageX) {
direction = 'toRight';
}
if (this.resizingCell) {
const columnWidthValues = Object.assign({}, this.state.columnWidthValues);
if (direction === 'toRight') {
const diff = this.resizingCell.startOffset + e.pageX - this.resizingCell.offsetWidth;
if (this.currentCoords) {
sibling = nextCell || this.resizingCell.nextSibling;
}
if (this.resizingCell.offsetWidth + diff > 100 &&
sibling.offsetWidth - diff > 100) {
const prevValue1 = columnWidthValues[columns[this.resizingCell.dataset.index].id];
const newValue1 = (this.resizingCell.offsetWidth + diff) * 100 / tableWidth;
columnWidthValues[columns[this.resizingCell.dataset.index].id] = newValue1;
columnWidthValues[columns[sibling.dataset.index].id] -= newValue1 - prevValue1;
this.setState({
columnWidthValues
});
} else {
let cell;
if (nextCell) {
cell = nextCell.nextSibling;
} else {
cell = this.resizingCell.nextSibling.nextSibling;
}
if (cell) {
this.processColumnResize(e, cell);
}
}
} else {
if (this.currentCoords) {
sibling = nextCell || this.resizingCell;
}
const diff = document.body.offsetWidth -
e.pageX -
this.nextResizingCell.startOffset -
this.nextResizingCell.offsetWidth;
if (sibling.offsetWidth - diff > 100 &&
this.nextResizingCell.offsetWidth + diff > 100) {
const prevValue1 = columnWidthValues[columns[sibling.dataset.index].id];
const newValue1 = (parseInt(sibling.offsetWidth, 10) - diff) * 100 / tableWidth;
columnWidthValues[columns[sibling.dataset.index].id] = newValue1;
columnWidthValues[columns[this.nextResizingCell.dataset.index].id] -= newValue1 - prevValue1;
this.setState({
columnWidthValues
});
} else {
let cell;
if (nextCell) {
cell = nextCell.previousSibling;
} else {
cell = this.resizingCell.previousSibling;
}
if (cell) {
this.processColumnResize(e, cell);
}
}
}
if (this.props.onColumnResize) {
this.props.onColumnResize(columnWidthValues);
}
}
this.currentCoords = e.pageX;
}
calculateInitialLast() {
return this.props.isScrollable
? Math.ceil(window.outerHeight / this.props.rowHeight) + RESERVE_ROWS_COUNT
: this.props.rows.length;
}
calculateLast(first) {
const wrapper = this.scrollWrapperEl.current;
const visibleHeight = wrapper
? wrapper.parentNode.offsetHeight + 200
: 0;
return first + Math.ceil(visibleHeight / this.props.rowHeight);
}
setScrollState() {
const scrollWrapperEl = this.scrollWrapperEl.current;
const scrollDummyEl = this.scrollDummyEl.current;
const rows = this.props.rows;
if (!this.props.isScrollable) {
return;
}
const scrollTop = Math.max(
scrollWrapperEl.scrollTop,
0);
const first = Math.max(0, Math.floor(scrollTop / this.props.rowHeight) - RESERVE_ROWS_COUNT);
const last = Math.min(rows.length, this.calculateLast(first) + RESERVE_ROWS_COUNT);
let newState = {
hasScroll: scrollWrapperEl.scrollHeight > scrollWrapperEl.offsetHeight &&
// Check if the scroll has a width
scrollWrapperEl.offsetWidth > scrollDummyEl.offsetWidth
}
if (first !== this.state.first || last !== this.state.last) {
newState = {
...newState,
...{
first,
last,
offset: first * this.props.rowHeight
}
};
}
this.setState(newState);
if (this.props.onScroll) {
this.props.onScroll(scrollTop);
}
if (this.props.onScrollReachesBottom &&
scrollWrapperEl.offsetHeight + scrollWrapperEl.scrollTop >= scrollWrapperEl.scrollHeight) {
this.props.onScrollReachesBottom();
}
}
onResize() {
this.setScrollState();
}
onScroll() {
this.setScrollState();
}
getHeaderStyle() {
if (this.state.hasScroll) {
return {
overflowY: 'scroll'
};
}
}
getDisabledCells(rows, startIndex) {
const disabledCells = [];
const disabledCellChecker = this.props.disabledCellChecker;
if (disabledCellChecker) {
rows.forEach((row, x) => {
this.props.columns.forEach((column, y) => {
if (disabledCellChecker(row, column.id)) {
disabledCells.push({ x: startIndex + x, y });
}
});
});
}
return disabledCells;
}
getScrollWrapperClassName() {
return 'SpreadsheetGridScrollWrapper' +
(this.props.isScrollable ? ' SpreadsheetGridScrollWrapper_scrollable' : '');
}
renderResizer() {
return (
<div
className="SpreadsheetGrid__resizer"
onMouseDown={this.startColumnResize}
style={{
height: this.props.headerHeight + 'px'
}}
/>
);
}
renderHeader() {
const columns = this.props.columns;
const { columnWidthValues } = this.state;
return (
<div
className="SpreadsheetGrid__header"
style={this.getHeaderStyle()}
>
{
columns.map((column, i) => {
return (
<div
key={i}
className="SpreadsheetGrid__headCell"
data-index={i}
style={{
height: this.props.headerHeight + 'px',
width: columnWidthValues
? columnWidthValues[columns[i].id] + '%'
: 'auto'
}}
>
{typeof column.title === 'string' ? column.title : column.title()}
{this.props.isColumnsResizable && i !== columns.length - 1 &&
this.renderResizer()}
</div>
);
})
}
</div>
);
}
render() {
const rows = slice(
this.props.rows,
this.state.first,
this.state.last
);
return (
<div
className="SpreadsheetGridContainer"
ref={this.tableEl}
>
{this.renderHeader()}
<div
className={this.getScrollWrapperClassName()}
onScroll={this.onScroll}
ref={this.scrollWrapperEl}
style={{
height: this.props.isScrollable
? `calc(100% - ${this.props.headerHeight}px)`
: 'auto'
}}
>
<ScrollDummy
rows={this.props.rows}
headerHeight={this.props.headerHeight}
rowHeight={this.props.rowHeight}
refEl={this.scrollDummyEl}
/>
{
<Grid
{...this.props}
ref={this.grid}
rows={rows}
allRows={this.props.rows}
rowsCount={this.props.rows.length}
startIndex={this.state.first}
offset={this.state.offset}
columnWidthValues={this.state.columnWidthValues}
disabledCells={this.getDisabledCells(rows, this.state.first)}
/>
}
</div>
</div>
);
}
}
SpreadsheetGridScrollWrapper.propTypes = Object.assign({}, tablePropTypes, {
// scroll
isScrollable: PropTypes.bool,
onScroll: PropTypes.func,
onScrollReachesBottom: PropTypes.func,
// resize
isColumnsResizable: PropTypes.bool,
onColumnResize: PropTypes.func
});
SpreadsheetGridScrollWrapper.defaultProps = {
rows: [],
isColumnsResizable: false,
placeholder: 'There are no rows',
headerHeight: 40,
rowHeight: 48,
isScrollable: true,
focusOnSingleClick: false
};
export default SpreadsheetGridScrollWrapper; |
src/hoc/withSpinner.js | Pavel-DV/ChronoMint | import React from 'react'
import {CircularProgress} from 'material-ui'
type propsType = {
isFetching: boolean
}
const withSpinner = (Component) => {
class Wrapped extends React.Component {
props: propsType;
render () {
const {isFetching, ...restProps} = this.props
return isFetching
? (<div style={{textAlign: 'center', height: '100vh', position: 'relative'}}>
<CircularProgress style={{position: 'relative', top: '50%', transform: 'translateY(-50%)'}} />
</div>)
: <Component {...restProps} />
}
}
return Wrapped
}
export default withSpinner
|
docs/src/app/components/pages/components/FlatButton/ExampleSimple.js | andrejunges/material-ui | import React from 'react';
import FlatButton from 'material-ui/FlatButton';
const FlatButtonExampleSimple = () => (
<div>
<FlatButton label="Default" />
<FlatButton label="Primary" primary={true} />
<FlatButton label="Secondary" secondary={true} />
<FlatButton label="Disabled" disabled={true} />
</div>
);
export default FlatButtonExampleSimple;
|
packages/spust-koa/src/GraphiQL.js | michalkvasnicak/spust | // @flow
import React from 'react';
import { graphiqlKoa } from 'graphql-server-koa';
import Middleware from './Middleware';
export type Props = {
endpointURL: string,
path: string,
};
export default class GraphiQL extends React.Component<Props, Props, void> {
static defaultProps = {
endpointURL: '/graphql',
path: '/graphiql',
};
render() {
const { endpointURL, path } = this.props;
return (
<Middleware
use={async (ctx, { finish, skip }) => {
if (ctx.path !== path) {
skip();
}
if (ctx.method !== 'GET') {
ctx.status = 405;
finish();
}
await graphiqlKoa({ endpointURL })(ctx, () => {});
// do not call next middleware functions
finish();
}}
/>
);
}
}
|
packages/xo-web/src/xo-app/sr/tab-advanced.js | vatesfr/xo-web | import _ from 'intl'
import Copiable from 'copiable'
import defined from '@xen-orchestra/defined'
import React from 'react'
import SortedTable from 'sorted-table'
import TabButton from 'tab-button'
import { addSubscriptions, connectStore, formatSize } from 'utils'
import { Container, Row, Col } from 'grid'
import { CustomFields } from 'custom-fields'
import { createGetObjectsOfType } from 'selectors'
import { createSelector } from 'reselect'
import { createSrUnhealthyVdiChainsLengthSubscription, deleteSr } from 'xo'
import { flowRight, isEmpty, keys, sum, values } from 'lodash'
// ===================================================================
const COLUMNS = [
{
itemRenderer: _ => <span>{_.name_label}</span>,
name: _('srUnhealthyVdiNameLabel'),
sortCriteria: 'name_label',
},
{
itemRenderer: vdi => formatSize(vdi.size),
name: _('srUnhealthyVdiSize'),
sortCriteria: 'size',
},
{
itemRenderer: (vdi, chains) => chains[vdi.uuid],
name: _('srUnhealthyVdiDepth'),
sortCriteria: (vdi, chains) => chains[vdi.uuid],
},
{
itemRenderer: _ => <Copiable tagName='div'>{_.uuid}</Copiable>,
name: _('srUnhealthyVdiUuid'),
sortCriteria: 'uuid',
},
]
const UnhealthyVdiChains = flowRight(
addSubscriptions(props => ({
chains: createSrUnhealthyVdiChainsLengthSubscription(props.sr),
})),
connectStore(() => ({
vdis: createGetObjectsOfType('VDI').pick(createSelector((_, props) => props.chains, keys)),
}))
)(({ chains, vdis }) =>
isEmpty(vdis) ? null : (
<div>
<hr />
<h3>{_('srUnhealthyVdiTitle', { total: sum(values(chains)) })}</h3>
<SortedTable collection={vdis} columns={COLUMNS} stateUrlParam='s_unhealthy_vdis' userData={chains} />
</div>
)
)
export default ({ sr }) => (
<Container>
<Row>
<Col className='text-xs-right'>
<TabButton btnStyle='danger' handler={deleteSr} handlerParam={sr} icon='sr-remove' labelId='srRemoveButton' />
</Col>
</Row>
<Row>
<Col>
<table className='table'>
<tbody>
<tr>
<th>{_('provisioning')}</th>
<td>{defined(sr.allocationStrategy, _('unknown'))}</td>
</tr>
<tr>
<th>{_('customFields')}</th>
<td>
<CustomFields object={sr.id} />
</td>
</tr>
</tbody>
</table>
</Col>
</Row>
<Row>
<Col>
<UnhealthyVdiChains sr={sr} />
</Col>
</Row>
</Container>
)
|
example/components/zoom-control.js | boromisp/react-leaflet | import React, { Component } from 'react';
import { Map, TileLayer, ZoomControl } from '../../src';
export default class ZoomControlExample extends Component {
render() {
return (
<Map center={[51.505, -0.09]} zoom={13} zoomControl={false}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<ZoomControl position='topright' />
</Map>
);
}
}
|
actor-apps/app-web/src/app/components/modals/MyProfile.react.js | way1989/actor-platform | //import _ from 'lodash';
import React from 'react';
import { KeyCodes } from 'constants/ActorAppConstants';
import MyProfileActions from 'actions/MyProfileActions';
import MyProfileStore from 'stores/MyProfileStore';
import AvatarItem from 'components/common/AvatarItem.react';
import Modal from 'react-modal';
//import classNames from 'classnames';
import { Styles, TextField, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
profile: MyProfileStore.getProfile(),
name: MyProfileStore.getName(),
isOpen: MyProfileStore.isModalOpen(),
isNameEditable: false
};
};
class MyProfile extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
this.unsubscribe();
document.removeEventListener('keydown', this.onKeyDown, false);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
this.unsubscribe = MyProfileStore.listen(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
},
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7',
disabledTextColor: 'rgba(0,0,0,.4)'
}
});
}
onClose = () => {
MyProfileActions.modalClose();
}
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
onChange = () => {
this.setState(getStateFromStores());
}
onNameChange = event => {
this.setState({name: event.target.value});
}
onNameSave = () => {
MyProfileActions.setName(this.state.name);
this.onClose();
}
render() {
let isOpen = this.state.isOpen;
let profile = this.state.profile;
if (profile !== null && isOpen === true) {
return (
<Modal className="modal-new modal-new--profile"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 340}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person</a>
<h4 className="modal-new__header__title">Profile</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onNameSave}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body row">
<AvatarItem image={profile.bigAvatar}
placeholder={profile.placeholder}
size="big"
title={profile.name}/>
<div className="col-xs">
<div className="name">
<TextField className="login__form__input"
floatingLabelText="Username"
fullWidth
onChange={this.onNameChange}
type="text"
value={this.state.name}/>
</div>
<div className="phone">
<TextField className="login__form__input"
disabled
floatingLabelText="Phone number"
fullWidth
type="tel"
value={this.state.profile.phones[0].number}/>
</div>
{/*
<ul className="modal-new__body__list hide">
<li>
<a>
Send message
</a>
</li>
<li>
<a className="color--red">
Block user
</a>
</li>
</ul>
*/}
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default MyProfile;
|
packages/bonde-admin/src/components/navigation/sidebar/sidebar.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage } from 'react-intl'
import * as paths from '@/paths'
import * as mobilizationUtils from '@/mobilizations/utils'
import { Loading } from '@/components/await'
import { Sidenav, SidenavList, SidenavListItem } from '@/components/navigation/sidenav'
import crossStorage from '@/cross-storage-client'
const Sidebar = ({ children, loading, mobilization, user, community }) => loading ? <Loading /> : (
<div className='top-0 right-0 bottom-0 left-0 flex flex-column absolute'>
<Sidenav community={community}>
{!mobilization ? (
<SidenavList className='bg-lighten-2'>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.community-settings.item.mobilizations'
defaultMessage='Mobilizações'
/>
}
icon='list'
href={paths.mobilizations()}
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.community-settings.item.info'
defaultMessage='Comunidade'
/>
}
icon='info-circle'
href={paths.communityInfo()}
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.community-settings.item.metrics'
defaultMessage='Métricas'
/>
}
icon='line-chart'
href={paths.communityReport()}
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.community-settings.item.domains'
defaultMessage='Domínios'
/>
}
icon='cogs'
href={paths.communityDomain()}
/>
</SidenavList>
) : (
<SidenavList className='bg-lighten-2'>
{!mobilizationUtils.isLaunched(mobilization) ? (
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.launch'
defaultMessage='PUBLICAR BONDE'
/>
}
icon='rocket'
href={paths.mobilizationLaunch(mobilization.id)}
className='launch-button rounded'
/>
) : (
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.launched'
defaultMessage='BONDE público'
/>
}
icon='check'
className='launched-item'
href='/#'
/>
)}
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.edit'
defaultMessage='Editar mobilização'
/>
}
icon='pencil'
href={paths.editMobilization(mobilization.id)}
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.add-block'
defaultMessage='Adicionar conteúdo'
/>
}
icon='plus'
href={paths.createBlock({ id: mobilization.id })}
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.open-at-new-tab'
defaultMessage='Ver em uma nova aba'
/>
}
icon='external-link'
linkType='anchor'
href={paths.mobilization(mobilization)}
target='_blank'
/>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.mobilization-settings.item.config'
defaultMessage='Configurações'
/>
}
icon='cog'
href={paths.basicsMobilization(mobilization.id)}
/>
</SidenavList>
)}
<SidenavList style={{ position: 'absolute', bottom: 0 }}>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.footer.account'
defaultMessage='Minha Conta'
/>
}
icon='user'
href={paths.editAccount()}
>
<div className='white h6'>{user.email}</div>
</SidenavListItem>
<SidenavListItem
text={
<FormattedMessage
id='components.navigation--sidebar.footer.sign-out'
defaultMessage='Sair'
/>
}
icon='sign-out'
className='caps'
linkType='anchor'
href='#'
onClick={(e) => {
e.preventDefault()
crossStorage
.onConnect()
.then(() => {
crossStorage
.del('auth', 'community')
.then(() => {
const domain = process.env.REACT_APP_DOMAIN_ADMIN_CANARY || 'http://admin-canary.bonde.devel:5002'
window.location.href = `${domain}/auth/login`
})
})
}}
/>
</SidenavList>
</Sidenav>
<div className='flex flex-auto' style={{ marginLeft: 80 }}>
{children}
</div>
</div>
)
Sidebar.propTypes = {
loading: PropTypes.bool.isRequired,
user: PropTypes.object.isRequired,
mobilization: PropTypes.object
}
export default Sidebar
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.