path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
internals/templates/app.js | jesus9ias/solar_system | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
src/backup/components/List.js | zzzzail/order-system-front-end-demo | import React from 'react';
import {connect} from 'react-redux';
const List = ({name, text}) => {
return (
<div className="list">
<div>{name}</div>
<div>{text}</div>
</div>
)
}
export default connect()(List)
|
demo/demo.js | spudly/react-deck | import Deck from '../src/Deck';
import cards from './cards.json';
import Card from 'react-card';
import React from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
class DeckDemo extends React.Component {
constructor (props) {
super(props);
this.state = {
activeIndex: 0,
activeFlipped: false
};
}
render () {
return (
<div>
<Deck>
{this._getSortedCards().map(this._renderCard, this)}
</Deck>
<button type='button' onClick={this._flip.bind(this)}>Flip Active Card</button>
<button type='button' onClick={this._prev.bind(this)}>Previous</button>
<button type='button' onClick={this._next.bind(this)}>Next</button>
</div>
);
}
_getSortedCards () {
return cards
.slice(this.state.activeIndex)
.concat(cards.slice(0, this.state.activeIndex))
.slice(0, 10) // for performance
.reverse();
}
_renderCard (card, i, cards) {
const className = classnames('index-card', {
'card-flipped': i === cards.length - 1 && this.state.activeFlipped
});
return (
<Card key={card.front} className={className}>
<Card.Front>
<h1>{card.front}</h1>
</Card.Front>
<Card.Back>
<p>{card.back}</p>
</Card.Back>
</Card>
);
}
_prev () {
const idx = this.state.activeIndex;
this.setState({activeIndex: (cards.length + idx - 1) % cards.length});
}
_next () {
const idx = this.state.activeIndex;
this.setState({activeIndex: (idx + 1) % cards.length});
}
_flip () {
this.setState({activeFlipped: !this.state.activeFlipped});
}
}
ReactDOM.render(<DeckDemo />, document.querySelector('#container'));
|
tp-3/juan-pablo-gonzalez/src/shared/components/dataModifier/DataModifier.js | jpgonzalezquinteros/sovos-reactivo-2017 | import React from 'react';
import PropTypes from 'prop-types';
import TinMask from './components/tinMask/TinMask';
import TinType from './components/tinType/TinType';
const type = {
TINMASK: TinMask,
TINTYPE: TinType
};
const DataModifier = props => (
React.createElement(type[props.modifierType.toUpperCase()],
{
records: props.records
})
);
DataModifier.propTypes = {
modifierType: PropTypes.string.isRequired,
records: PropTypes.object.isRequired
};
export default DataModifier;
|
spec/javascripts/jsx/speed_grader/AssessmentAuditTray/components/AuditTrail/DateEventGroupSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import timezone from 'timezone'
import newYork from 'timezone/America/New_York'
import DateEventGroup from 'jsx/speed_grader/AssessmentAuditTray/components/AuditTrail/DateEventGroup'
import {buildEvent} from 'jsx/speed_grader/AssessmentAuditTray/__tests__/AuditTrailSpecHelpers'
import buildAuditTrail from 'jsx/speed_grader/AssessmentAuditTray/buildAuditTrail'
QUnit.module('AssessmentAuditTray DateEventGroup', suiteHooks => {
let $container
let props
let timezoneSnapshot
suiteHooks.beforeEach(() => {
$container = document.body.appendChild(document.createElement('div'))
const auditEvents = [
buildEvent({id: '4901', userId: '1101', createdAt: '2018-09-01T16:34:00Z'}),
buildEvent({id: '4902', userId: '1101', createdAt: '2018-09-01T16:45:00Z'}),
buildEvent({id: '4903', userId: '1101', createdAt: '2018-09-01T16:56:00Z'})
]
const users = [{id: '1101', name: 'A stupefying student', role: 'student'}]
const externalTools = []
const quizzes = []
const auditTrail = buildAuditTrail({auditEvents, users, externalTools, quizzes})
props = {
dateEventGroup: auditTrail.creatorEventGroups[0].dateEventGroups[0]
}
timezoneSnapshot = timezone.snapshot()
timezone.changeZone(newYork, 'America/New_York')
})
suiteHooks.afterEach(() => {
ReactDOM.unmountComponentAtNode($container)
$container.remove()
timezone.restore(timezoneSnapshot)
})
function mountComponent() {
ReactDOM.render(<DateEventGroup {...props} />, $container)
}
test('displays the starting date and time in the timezone of the current user', () => {
mountComponent()
const $heading = $container.querySelector('h4')
equal($heading.textContent, 'September 1 starting at 12:34pm')
})
test('displays a list of all events', () => {
mountComponent()
const $events = $container.querySelectorAll('ul li')
strictEqual($events.length, 3)
})
})
|
src/components/Navbar.js | YannickBochatay/JSYG-starterkit | import React from 'react'
import { Link } from 'react-router'
import { FormattedMessage } from "react-intl"
import LangChoice from "../containers/LangChoice"
class Item extends React.Component {
render() {
let style = {
li:{
display:"inline-block",
padding:"0 10px"
}
}
return (
<li style={style.li}>
<Link to={this.props.link}>
<FormattedMessage id={this.props.label}/>
</Link>
</li>
)
}
}
export default class GlobalNav extends React.Component {
render() {
let style = {
ul : {
listStyleType:"none",
display:"inline-block"
}
}
return (
<nav>
<ul style={style.ul}>
<Item link="/" label="Home"/>
<Item link="comments" label="Comments"/>
<Item link="todo" label="To do"/>
<Item link="reddit" label="Reddit"/>
</ul>
<ul style={style.ul}>
<LangChoice lang="French" locale="fr"/>
<LangChoice lang="English" locale="en"/>
</ul>
</nav>
)
}
}
|
examples/basic/src/components/PushButton/PushButton.js | bluetidepro/react-styleguidist | import React from 'react';
import PropTypes from 'prop-types';
import './PushButton.css';
/**
* An example-less button with custom display name.
* @visibleName Push Button 🎉
*/
export default function PushButton({ color, size, children }) {
const styles = {
color,
fontSize: PushButton.sizes[size],
};
return (
<button className="push-button" style={styles}>
{children}
</button>
);
}
PushButton.propTypes = {
/**
* PushButton label.
*/
children: PropTypes.string.isRequired,
color: PropTypes.string,
size: PropTypes.oneOf(['small', 'normal', 'large']),
};
PushButton.defaultProps = {
color: '#333',
size: 'normal',
};
PushButton.sizes = {
small: '10px',
normal: '14px',
large: '18px',
};
|
wrappers/md.js | mongus/mongus.com | import React from 'react'
import 'css/markdown-styles.css'
import Helmet from "react-helmet"
import { config } from 'config'
module.exports = React.createClass({
propTypes () {
return {
router: React.PropTypes.object,
}
},
render () {
const post = this.props.route.page.data
return (
<div className="markdown">
<Helmet
title={`${config.siteTitle} | ${post.title}`}
/>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.body }} />
</div>
)
},
});
|
client/src/components/map-container.js | josephstein/drone-flights | import React from 'react'
import _ from 'lodash'
import { connect } from 'react-redux'
import { fetchFlights } from '../actions'
import Map from './map'
class MapContainer extends React.Component {
componentDidMount() {
this.props.fetchFlights()
}
render() {
return (
<Map flights={this.props.flights} />
)
}
}
function mapStateToProps(state) {
return { flights: state.flights }
}
export default connect(mapStateToProps, { fetchFlights })(MapContainer)
|
src/components/Transformer.js | lxgreen/flickr-viewr | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Transformer extends Component {
constructor(props) {
super(props);
this.state = {
position: this.props.defaultPosition,
rotation: this.props.defaultRotation,
initialAngle: 0,
center: {
x: 0,
y: 0
},
dragStartPosition: {
x: 0,
y: 0
}
};
}
onDragStart = (e) => {
e.preventDefault();
};
onContextMenu = (e) => {
e.preventDefault();
};
onMouseDown = (e) => {
// external mouse down
this.props.onMouseDown(this.props.imageId);
// only LMB is processed
if (e.button) return e.preventDefault();
// dispatch buttons: LMB for dragging, shift + LMB for rotation
if (e.shiftKey) this.handleStartRotate(e);
else this.handleStartDrag(e);
return e.preventDefault();
};
handleStartRotate = (e) => {
// get element boundaries
const ref = ReactDOM.findDOMNode(this);
const box = ref.getBoundingClientRect();
const {top, left, height, width} = box;
// element center
const center = {
x: left + (width / 2),
y: top + (height / 2)
};
// distance from center
const x = e.clientX - center.x;
const y = e.clientY - center.y;
// save center and initial angle
this.setState({
center: center,
initialAngle: Math.atan2(y,x)
});
e.target.addEventListener('mousemove', this.onRotate);
e.target.addEventListener('mouseup', this.onRotateStop);
e.target.addEventListener('mouseleave', this.onRotateStop);
e.preventDefault();
};
onRotate = (e) => {
// get current pointer distance from center
const x = e.clientX - this.state.center.x;
const y = e.clientY - this.state.center.y;
// calculate angle delta from initial value
const delta = Math.atan2(y, x) - this.state.initialAngle;
// divided by 8 for smoother rotation
this.setState({
rotation: this.state.rotation + delta / 8
});
e.preventDefault();
};
onRotateStop = (e) => {
if (this.state.rotation !== this.props.defaultRotation) {
this.props.onRotateStop({
rotation: this.state.rotation,
id: this.props.imageId
});
}
e.target.removeEventListener('mousemove', this.onRotate);
e.target.removeEventListener('mouseup', this.onRotateStop);
e.target.removeEventListener('mouseup', this.onRotateStop);
e.preventDefault();
};
handleStartDrag = (e) => {
// save distance from the current position to pointer
this.setState({
dragStartPosition: {
x: e.pageX - this.state.position.x,
y: e.pageY - this.state.position.y
}
});
e.target.addEventListener('mousemove', this.onDrag);
e.target.addEventListener('mouseup', this.onDragStop);
e.target.addEventListener('mouseleave', this.onDragStop);
e.preventDefault();
};
onDrag = (e) => {
this.setState({
position: {
x: e.pageX - this.state.dragStartPosition.x,
y: e.pageY - this.state.dragStartPosition.y
}
});
e.preventDefault();
};
onDragStop = (e) => {
if (this.state.position.x !== this.props.defaultPosition.x ||
this.state.position.y !== this.props.defaultPosition.y) {
this.props.onDragStop({
location: this.state.position,
id: this.props.imageId
});
}
e.target.removeEventListener('mousemove', this.onDrag);
e.target.removeEventListener('mouseup', this.onDragStop);
e.target.removeEventListener('mouseleave', this.onDragStop);
e.preventDefault();
};
render() {
const dragRotateStyle = {
transform: `translate3d(${this.state.position.x}px, ${this.state.position.y}px, 0) rotateZ(${this.state.rotation}rad)`
};
// apply transformations on child element
return React.cloneElement(React.Children.only(this.props.children), {
style: dragRotateStyle,
onMouseDown: this.onMouseDown,
onDragStart: this.onDragStart,
onContextMenu: this.onContextMenu
});
}
}
Transformer.defaultProps = {
position: {x: 0, y: 0},
rotation: 0,
onMouseDown: () => {},
onDragStop: () => {},
onRotateStop: () => {}
};
export default Transformer; |
react-events-page/src/index.js | picatic/picatic-examples | import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Home from './Home'
import App from './App'
ReactDOM.render(
<Router>
<div>
<Route exact path="/" component={Home} />
<Route path="/:slug" component={App} />
</div>
</Router>,
document.getElementById('root')
)
|
examples/passing-props-to-children/app.js | rdjpalmer/react-router | import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'
import './app.css'
const App = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
}
},
addTaco() {
let name = prompt('taco name?')
this.setState({
tacos: this.state.tacos.concat({ name })
})
},
handleRemoveTaco(removedTaco) {
this.setState({
tacos: this.state.tacos.filter(function (taco) {
return taco.name != removedTaco
})
})
this.context.router.push('/')
},
render() {
let links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
)
})
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
)
}
})
const Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name)
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
)
}
})
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'))
|
client/src/index.js | serban-petrescu/candidate-management | import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/App';
import reducers from './reducers';
import $ from 'jquery';
import './less/main.less'
window.$ = $;
window.jQuery = $;
require('bootstrap');
/**
* Middleware with ReduxPromise applied means that the promise sent from actions
to the reducer will be intercepted by ReduxPromise module and the payload will be redd from the promise
and sent to the reducer as an object and not as a Promise.
*/
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
/***
* Provider is used to pass the store down from react-redux
* The Provider exposes the store you pass through as a prop
* on the context, so the component can specify the context-type and then use
* this context store to subscribe to the store updates and dispatch actions.
* We render the App component in the place of div element having the id of root
*/
<Provider store={createStoreWithMiddleware(reducers)}>
<App/>
</Provider>,
document.getElementById('root')
); |
components/Search.js | sturquier/hyne | import React, { Component } from 'react';
import { View, TextInput, Button, TouchableOpacity } from 'react-native';
import { StackNavigator } from 'react-navigation';
import Result from './Result';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
city: 'Paris'
}
}
setCity(text) {
this.setState({
city: text
})
}
/* Submit method() redirects on Result component with 'this.state.city' argument */
submit() {
this.props.navigation.navigate('Result', {city: this.state.city})
}
render() {
return (
<View style={{margin :30}}>
<TextInput
underlineColorAndroid='transparent'
onChangeText={(text) => this.setCity(text)}
value={this.state.city}
style={{
borderColor:"#1A237E",
borderWidth:1,
paddingHorizontal: 10
}}
/>
<TouchableOpacity
/* Custom button "Rechercher" with TouchableOpacity wrapper */
style={{marginTop: 10}}>
<Button
color= "#1A237E"
/* Call submit() method when clicking on button */
onPress={() => this.submit()}
title="Rechercher"
/>
</TouchableOpacity>
</View>
);
}
};
export default StackNavigator({
Search: {
screen: Search,
navigationOptions: {
title: 'Rechercher une ville',
headerStyle: {
backgroundColor: "#3F51B5"
}
}
},
Result: { screen: Result }
}); |
app/renderer/views/DisplayMovies/MovieDetail/Title.js | blenoski/movie-night | import React from 'react'
import styled from 'styled-components'
export default ({ title }) => {
return <TitleReadOnly>{title}</TitleReadOnly>
}
const TitleReadOnly = styled.h1`
color: rgba(255, 255, 255, 1);
`
|
src/modules/connect/connectMain/ConnectView.js | Florenz23/sangoo_04 | import React, { Component } from 'react';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text, Thumbnail, Left, Right, Body } from 'native-base';
import { LiestView } from 'realm/react-native'
import styles from '../styles/styles';
import realm from "../db_ini"
import { findInDb, findInDbTagText } from '../../../db/db_helper'
import { base64Icon, donny } from '../../../db/base64img'
const showContactDetail = (navigate,setRecentContactId,contactId) => {
navigate({routeName: 'ConnectDetail'})
setRecentContactId(contactId)
}
//TODO user ListView from realm
const ConnectView = (props) => {
const { navigate, setRecentContactId, contactId } = props
let datas = realm.objects('User')
const uri = "./donny-copy.png"
return (
<Container style={styles.container}>
<Content style={{marginTop:10}}>
<List
dataArray={datas} renderRow={data =>
<ListItem avatar onPress={() => showContactDetail(navigate,setRecentContactId,data.userId)}>
<Left>
<Thumbnail source={{uri: findInDbTagText(data.userData[0].personalData,"tagDescription","Image")}} />
</Left>
<Body>
<Text>
{findInDb(data.userData[0].personalData,"tagDescription","Vorname").tagText}
</Text>
<Text numberOfLines={1} note>
{data.publicSharedData[0].hashTagData[0].tagDescription}
{": "}
{data.publicSharedData[0].hashTagData[0].tagText}
</Text>
</Body>
<Right>
<Icon ios='md-add' android="md-add" style={{fontSize: 25, color: 'black'}}/>
</Right>
</ListItem>
}
/>
</Content>
</Container>
)
}
export default ConnectView;
|
internals/templates/containers/App/index.js | emise/hoosit | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
src/star/ui/acceptBidbutton/AcceptBidButton.js | flysonic10/initial-celestial-offering | import React from 'react'
class AcceptBidButton extends React.Component {
render() {
let starIndex = this.props.starIndex;
let minAmount = this.props.minAmount;
return(
<button onClick={(event) => this.props.onAcceptBid(event, starIndex, minAmount)}>Accept Bid</button>
)
}
}
export default AcceptBidButton
|
packages/components/src/Layout/TwoColumns/TwoColumns.component.js | Talend/ui | import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import omit from 'lodash/omit';
import TabBar from '../../TabBar';
import WithDrawer from '../../WithDrawer';
import Inject from '../../Inject';
import theme from './TwoColumns.scss';
/**
* @param {object} props react props
* @example
<TwoColumns name="Hello world"></TwoColumns>
*/
function TwoColumns({ one, drawers, children, tabs, getComponent, ...props }) {
const containerCSS = classnames('tc-layout-two-columns', theme.container);
const sidemenuCSS = classnames('tc-layout-two-columns-left', theme.sidemenu);
const mainCSS = classnames('tc-layout-two-columns-main', theme.main);
const style = {
overflow: 'auto',
height: '100%',
display: 'flex',
flexDirection: 'column',
};
const safeOne = Inject.getReactElement(getComponent, one);
return (
<div className={containerCSS} {...omit(props, 'getComponents')}>
<div className={sidemenuCSS} id="tc-layout-side-menu" tabIndex="-1">
{safeOne}
</div>
<div className={mainCSS} role="main" id="tc-layout-main" tabIndex="-1">
<WithDrawer drawers={drawers}>
{tabs && <TabBar {...tabs} />}
<div style={style}>{children}</div>
</WithDrawer>
</div>
</div>
);
}
TwoColumns.displayName = 'TwoColumns';
TwoColumns.propTypes = {
one: Inject.getReactElement.propTypes,
children: PropTypes.node,
drawers: PropTypes.arrayOf(PropTypes.node),
tabs: PropTypes.shape(TabBar.propTypes),
getComponent: PropTypes.func,
};
export default TwoColumns;
|
web/src/index.js | undemaduc/undemaduc | /* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { AppContainer } from 'react-hot-loader';
import Root from './components/Root';
import configureStore from './store/configureStore';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
if (module.hot) {
module.hot.accept('./components/Root', () => {
const NewRoot = require('./components/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
});
}
|
src/layouts/Navbar/components/Navbar.js | dziksu/songs-manager | import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { firebase, helpers, firebaseConnect } from 'react-redux-firebase';
import "./Navbar.scss";
const { isLoaded, isEmpty, pathToJS, dataToJS } = helpers;
class NavbarLayout extends Component{
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.toggleDropdown = this.toggleDropdown.bind(this);
this.state = {
isOpen: false,
dropdownOpen: false
};
}
toggle() {
this.setState({
...this.state,
isOpen: !this.state.isOpen
});
}
toggleDropdown() {
this.setState({
...this.state,
dropdownOpen: !this.state.dropdownOpen
});
}
getNavbarLinksIfNotLoggeedIn(){
return(
<ul id="nav-mobile" className="right">
<li><Link className="nav-link" to="/account/login">Log In</Link></li>
</ul>
);
}
getNavbarLinksIfLoggedIn(){
const userName = this.props.auth ? this.props.auth.email : 'loading'
return(
<ul id="nav-mobile" className="right hide-on-med-and-down">
<li><Link to="/song/create" className='menu-item'>Add song</Link></li>
<li>
<a href='#'><span onClick={this.logOutUser.bind(this)}>{userName}</span></a>
</li>
<li>
<a href='#'><span onClick={this.logOutUser.bind(this)}>Log out</span></a>
</li>
</ul>
);
}
getNavbarLinks(){
if(!isEmpty(this.props.auth)) return this.getNavbarLinksIfLoggedIn()
return this.getNavbarLinksIfNotLoggeedIn()
}
logOutUser(){
this.props.firebase.logout()
window.location.replace('/')
}
render() {
return (
<nav>
<div className="nav-wrapper">
<Link to='/' className='brand-logo'>
Songs Manager
</Link>
{this.getNavbarLinks()}
</div>
</nav>
);
}
}
const fbWrappedComponent = firebase()(NavbarLayout);
export default connect(({firebase}) => ({
auth: pathToJS(firebase, 'auth'),
profile: pathToJS(firebase, 'profile')
}))(fbWrappedComponent); |
app/components/active_sensors/active_sensors.js | friend0/react_sensor_app | import React from 'react';
import SearchBar from '../common/SearchBar';
import Robot from './Robot';
import List from '../common/List';
const axios = require('../../../node_modules/axios');
export default class Live extends React.Component {
constructor() {
super();
this.getRobots = this.getRobots.bind(this);
this.searchFilter = this.searchFilter.bind(this);
this.initRobots = this.initRobots.bind(this);
Live.strcmp = Live.strcmp.bind(this);
this.state = {
robots: [],
filteredRobots: [],
search: 'Search',
NoSearch: true
};
}
updateSearch(event) {
this.setState({NoSearch: false});
// console.log('Update');
this.setState({search: event.target.value});
this.searchFilter(event);
// console.log(this.state.search);
}
initRobots(robot) {
const hostname = robot.hostname;
const ip = robot.ip_address;
return (<Robot hostname={hostname} ip={ip} {...robot}/>);
}
componentDidMount() {
axios.get('/api/get-robots',
{
proxy: {
host: 'localhost',
port: 6001
},
headers: {
Accept: 'application/json'
},
responseType: 'json'
})
.then(response => {
const robs = response.data.map(this.initRobots);
this.setState({
robots: robs,
filteredRobots: robs
});
})
.catch(function(error) {
console.log(error);
});
}
getRobots() {
axios.get('/api/get-robots',
{
proxy: {
host: 'localhost',
port: 6001
},
headers: {
Accept: 'application/json'
},
responseType: 'json'
})
.then(function(response) {
const robs = response.data.map(this.searchFilter);
this.setState({
robots: robs,
filteredRobots: robs
});
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
}
searchFilter() {
const search = this.state.search;
const regex = new RegExp(search, 'i');
const NoSearch = this.state.NoSearch;
const filtered = this.state.robots.filter(function(datum) {
let robot = datum.props;
console.log(robot);
return ((robot.hostname.search(regex) > -1) || NoSearch);
});
console.log("Filtered Robots");
console.log(filtered);
this.setState({
filteredRobots: filtered
});
}
static strcmp(a, b) {
if (a < b) {
return -1;
}
return a > b ? 1 : 0;
}
render() {
const containerStyle = {
marginTop: '60px'
};
const headerStyle = {
color: '#C7C9CA'
};
// const strcmp = this.strcmp;
// Need to map only the robots that match whats in search
return (
<section className="latest-bills">
<header className="section-header">
<h3 className="title" style={headerStyle}>Active Sensors</h3>
</header>
<div className="container" style={containerStyle}>
<SearchBar value={this.state.search} onChange={this.updateSearch.bind(this)}/>
</div>
<section className="section-content">
<List items={this.state.filteredRobots} itemType={Robot}/>
</section>
</section>
);
}
}
|
chrome/extension/devpanel/index.js | crysislinux/chrome-react-perf | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import Root from '../../../app/containers/Root';
import configureStore from '../../../app/store/configureStore';
const store = configureStore();
render(
<Root store={store} />,
document.getElementById('root')
);
|
src/encoded/static/components/item-pages/UserView.js | 4dn-dcic/fourfront | /** @preventMunge */
/* ^ see http://stackoverflow.com/questions/30110437/leading-underscore-transpiled-wrong-with-es6-classes */
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import Modal from 'react-bootstrap/esm/Modal';
import FormControl from 'react-bootstrap/esm/FormControl';
import { console, object, JWT, ajax, navigate, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { LocalizedTime } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/LocalizedTime';
import { Alerts } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/Alerts';
import { EditableField, FieldSet } from '@hms-dbmi-bgm/shared-portal-components/es/components/forms/components/EditableField';
import { PageTitleContainer, TitleAndSubtitleUnder, StaticPageBreadcrumbs, pageTitleViews, OnlyTitle } from './../PageTitle';
import { store } from './../../store';
import { FormattedInfoBlock } from './components/FormattedInfoBlock';
// eslint-disable-next-line no-unused-vars
import { Item } from './../util/typedefs';
/**
* Contains the User profile page view as well as Impersonate User form.
* Only the User view is exported.
*
* @module item-pages/user
*/
/**
* Component which fetches, saves, and show access keys that user may use to submit
* experiments and other data.
*
* @memberof module:item-pages/user
* @namespace
* @type {Component}
* @private
*/
class SyncedAccessKeyTable extends React.PureComponent {
static propTypes = {
'access_keys' : PropTypes.array,
'user' : PropTypes.shape({
'@id' : PropTypes.string.isRequired,
'uuid' : PropTypes.string.isRequired,
'email' : PropTypes.string,
'first_name' : PropTypes.string,
'last_name' : PropTypes.string,
'groups' : PropTypes.array,
'status' : PropTypes.string,
'timezone' : PropTypes.string,
'job_title' : PropTypes.string,
'submits_for' : PropTypes.array
})
};
constructor(props){
super(props);
_.bindAll(this, 'syncAccessKeysFromSearch', 'handleCreate', 'handleResetSecret',
'showNewSecret', 'handleDelete', 'hideModal');
this.state = {
'access_keys' : null,
'loadingStatus' : 'loading',
'modal' : null
};
}
componentDidMount(){
this.syncAccessKeysFromSearch();
}
syncAccessKeysFromSearch(){
const { user } = this.props;
const { loadingStatus } = this.state;
if (!user || !user.uuid || !object.isUUID(user.uuid)){
logger.error("No user, or invalid user.uuid supplied.");
throw new Error("No user, or invalid user.uuid supplied.");
}
const requestSucceeded = (resp) => {
// Use for both load success+fail ajax callback in case of 404 (no results)
if (!resp || !Array.isArray(resp['@graph'])){
this.setState({ 'loadingStatus' : 'failed', 'access_keys' : null });
}
this.setState({
'loadingStatus' :' loaded',
'access_keys' : resp['@graph']
});
};
const loadFxn = () => {
const hrefToRequest = '/search/?type=AccessKey&limit=500&user.uuid=' + user.uuid;
ajax.load(hrefToRequest, requestSucceeded, 'GET', requestSucceeded);
};
if (loadingStatus !== 'loading'){
this.setState({ 'loadingStatus' : 'loading' }, loadFxn);
} else {
loadFxn();
}
}
/**
* Add new access key for user via AJAX.
*
* @param {MouseEvent} e - Click event.
*/
handleCreate(e) {
ajax.load('/access-keys/', (resp)=>{
const [ newKey ] = resp['@graph'];
this.setState(function({ access_keys : prevKeys }){
const nextKeys = prevKeys.slice(0);
nextKeys.unshift(newKey); // Add to start of list.
return { 'access_keys' : nextKeys };
}, () => {
this.showNewSecret(resp);
});
}, 'POST', (err)=>{
Alerts.queue({
'title' : "Adding access key failed",
"message" : "Check your internet connection or if you have been logged out due to expired session.",
"style" : 'danger'
});
}, "{}");
}
showNewSecret(response, reset = false) {
const { secret_access_key, access_key_id } = response;
const modalTitle = "Your secret key has been " + (reset ? "reset" : "created" );
this.setState({ 'modal' : (
<Modal show onHide={this.hideModal}>
<Modal.Header closeButton>
<Modal.Title>{ modalTitle }</Modal.Title>
</Modal.Header>
<Modal.Body>
Please make a note of the new secret access key.
This is the last time you will be able to view it.
<br/>(It might take a few minutes for the access key to show up in table after page refresh.)
<div className="row mt-15">
<div className="col-4 text-600 text-right no-user-select">
Access Key ID
</div>
<div className="col-8">
<code>{ access_key_id }</code>
</div>
</div>
<div className="row mt-05">
<div className="col-4 text-600 text-right no-user-select">
Secret Access Key
</div>
<div className="col-8">
<code>{ secret_access_key }</code>
</div>
</div>
</Modal.Body>
</Modal>
) });
}
/**** Methods which are CALLED BY ITEMSTORE VIA DISPATCH(); TODO: Refactor, more Reactful ****/
handleResetSecret(id) {
ajax.load(id + 'reset-secret', (resp)=>{
this.showNewSecret(resp, true);
}, 'POST', (err)=>{
Alerts.queue({
'title' : "Resetting access key failed",
"message" : "Check your internet connection or if you have been logged out due to expired session.",
"style" : 'danger'
});
});
}
handleDelete(item) {
const dispatch_body = { 'status': 'deleted' };
if (item.accession){
dispatch_body.accession = item.accession;
}
if (item.uuid){
dispatch_body.uuid = item.uuid;
}
ajax.load(item['@id'] + '?render=false', (resp)=>{
this.setState(({ access_keys : prevKeys }) => {
const foundItemIdx = _.findIndex(prevKeys, function(sItem){
return sItem['@id'] === item['@id'];
});
if (typeof foundItemIdx !== 'number' || foundItemIdx === -1){
logger.error('Couldn\'t find deleted key - ' + sItem['@id']);
throw new Error('Couldn\'t find deleted key - ' + sItem['@id']);
}
const foundItem = prevKeys[foundItemIdx];
const nextKeys = prevKeys.slice(0);
nextKeys.splice(foundItemIdx, 1);
return {
'access_keys' : nextKeys,
'modal' : (
<Modal show onHide={this.hideModal}>
<Modal.Header closeButton>
<Modal.Title className="text-400">Access key <span className="text-monospace">{ foundItem.access_key_id }</span> has been deleted.</Modal.Title>
</Modal.Header>
</Modal>
)
};
});
}, "PATCH", ()=>{
Alerts.queue({
'title' : "Deleting access key failed",
"message" : "Check your internet connection or if you have been logged out due to expired session.",
"style" : 'danger'
});
}, JSON.stringify(dispatch_body));
}
hideModal() {
this.setState({ 'modal' : null });
}
render() {
const { access_keys, loadingStatus, modal } = this.state;
if (!Array.isArray(access_keys) || !this.store){
if (loadingStatus === 'loading'){
return (
<AccessKeyTableContainer>
<div className="text-center pt-3 pb-3">
<i className="icon icon-2x icon-fw icon-circle-notch icon-spin fas" style={{ 'color' : '#999' }}/>
</div>
</AccessKeyTableContainer>
);
} else if (loadingStatus === 'failed'){
return (
<AccessKeyTableContainer>
<div className="text-center pt-3 pb-3">
<i className="icon icon-2x icon-fw icon-times fas" style={{ 'color' : 'maroon' }}/>
<h4 className="text-400">Failed to load Access Keys</h4>
</div>
</AccessKeyTableContainer>
);
} else if (loadingStatus === 'loaded'){
return (
<AccessKeyTableContainer>
<div className="text-center pt-3 pb-3">
<i className="icon icon-2x icon-fw icon-times fas" style={{ 'color' : 'maroon' }}/>
<h4 className="text-400">Unknown Error</h4>
</div>
</AccessKeyTableContainer>
);
}
}
return (
<AccessKeyTableContainer>
<AccessKeyTable accessKeys={access_keys} onResetSecret={this.handleResetSecret} onDelete={this.handleDelete} />
<button type="button" id="add-access-key" className="btn btn-success mb-2" onClick={this.handleCreate}>Add Access Key</button>
{ modal }
</AccessKeyTableContainer>
);
}
}
function AccessKeyTableContainer({ children }){
return (
<div className="access-keys-container">
<h3 className="text-300">Access Keys</h3>
<div className="access-keys-table-container clearfix">{ children }</div>
</div>
);
}
const AccessKeyTable = React.memo(function AccessKeyTable({ accessKeys, onDelete, onResetSecret }){
if (typeof accessKeys === 'undefined' || !accessKeys.length){
return (
<div className="no-access-keys">
<hr/><span>No access keys set.</span>
</div>
);
}
return (
<table className="table access-keys-table">
<thead>
<tr>
<th>Access Key ID</th>
<th>Created</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
{ _.map(accessKeys, function(accessKey, idx){
const { access_key_id : id, date_created, description, uuid } = accessKey;
const atId = accessKey['@id'];
function resetKey(e){ onResetSecret(atId); }
function deleteKey(e){ onDelete({ '@id' : atId, uuid }); }
return (
<tr key={id || idx}>
<td className="access-key-id">{ id }</td>
<td>{ date_created ? <LocalizedTime timestamp={date_created} formatType="date-time-md" dateTimeSeparator=" - " /> : 'N/A' }</td>
<td>{ description }</td>
<td className="access-key-buttons">
<button type="button" className="btn btn-xs btn-success" onClick={resetKey}>Reset</button>
<button type="button" className="btn btn-xs btn-danger" onClick={deleteKey}>Delete</button>
</td>
</tr>
);
}) }
</tbody>
</table>
);
});
/**
* Draws a User Profile page.
*
* @public
* @type {Component}
* @prop {Object} context - Context value for user, e.g. from Redux store. AKA user object.
* @prop {Object} schemas - Object of schemas, e.g. passed from app state.
* @memberof module:item-pages/user
*/
export default class UserView extends React.Component {
static onEditableFieldSave(nextContext){
store.dispatch({
type: { 'context': nextContext }
});
}
static propTypes = {
'context' : PropTypes.shape({
'@id' : PropTypes.string.isRequired,
'access_keys' : PropTypes.array,
'email' : PropTypes.string,
'first_name' : PropTypes.string,
'last_name' : PropTypes.string,
'title' : PropTypes.string,
'groups' : PropTypes.array,
'lab' : PropTypes.object,
'status' : PropTypes.string,
'timezone' : PropTypes.string,
'job_title' : PropTypes.string
}),
'href' : PropTypes.string.isRequired,
'schemas' : PropTypes.shape({
'User' : PropTypes.shape({
'required' : PropTypes.array,
'properties' : PropTypes.shape({
'first_name' : PropTypes.object,
'last_name' : PropTypes.object,
'email' : PropTypes.object,
'phone1' : PropTypes.object,
'fax' : PropTypes.object,
'skype' : PropTypes.object,
// etc.
})
})
})
};
mayEdit(){
const { context } = this.props;
return _.any((context && context.actions) || [], function(action){
return action.name && action.name === 'edit';
});
}
render() {
const { context : user, schemas, href, windowWidth } = this.props;
const { email, lab, submits_for, access_keys } = user;
const mayEdit = this.mayEdit();
// Todo: remove
const ifCurrentlyEditingClass = this.state && this.state.currentlyEditing ? ' editing editable-fields-container' : '';
return (
<div className="user-profile-page container" id="content">
<header className="row">
<div className="col-sm-12">
</div>
</header>
<div className={"page-container data-display" + ifCurrentlyEditingClass}>
<div className="row mt-5 mb-12">
<div className="col-12 col-lg-6 col-xl-7">
<div className="panel user-info shadow-border">
<div className="user-title-row-container">
<div className="row title-row">
<div className="col-md-3 gravatar-container">
{ object.itemUtil.User.gravatar(email, 70) }
<a className="edit-button-remote text-center" target="_blank" rel="noopener noreferrer" href="https://gravatar.com">
<i className="icon icon-pencil fas"/>
</a>
</div>
<div className="col-md-9 user-title-col">
<h1 className="user-title">
<FieldSet context={user} parent={this}
inputSize="lg" absoluteBox={false} objectType="User" onSave={UserView.onEditableFieldSave}
schemas={schemas} disabled={!mayEdit} href={href} windowWidth={windowWidth}>
<EditableField labelID="first_name" fallbackText="No first name set"
placeholder="First name" style="inline" />
{' '}
<EditableField labelID="last_name" fallbackText="No last name set"
placeholder="Last name" style="inline" />
</FieldSet>
</h1>
</div>
</div>
</div>
<ProfileContactFields user={user} parent={this} mayEdit={mayEdit} href={href} />
</div>
</div>
<div className="col-12 col-lg-6 col-xl-5">
<ProfileWorkFields user={user} parent={this} href={href} />
</div>
</div>
<SyncedAccessKeyTable user={user} access_keys={access_keys} />
</div>
</div>
);
}
}
/**
* Renders out the contact fields for user, which are editable.
* Shows Gravatar and User's first and last name at top.
*
* @private
* @type {Component}
*/
function ProfileContactFields(props){
const { user, windowWidth, parent, mayEdit, href, schemas } = props;
const { email, phone1, fax, skype } = user;
return (
<FieldSet context={user} onSave={UserView.onEditableFieldSave}
parent={parent} className="profile-contact-fields"
disabled={!mayEdit} objectType="User" windowWidth={windowWidth}
schemas={schemas} href={href}>
<EditableField label="Email" labelID="email" placeholder="[email protected]" fallbackText="No email address" fieldType="email" disabled={true}>
<ProfileContactFieldsIcon icon="envelope fas" /> <a href={'mailto:' + email}>{ email }</a>
</EditableField>
<EditableField label="Phone" labelID="phone1" placeholder="17775551234 x47" fallbackText="No phone number" fieldType="phone">
<ProfileContactFieldsIcon icon="phone fas" /> { phone1 }
</EditableField>
<EditableField label="Fax" labelID="fax" placeholder="17775554321" fallbackText="No fax number" fieldType="phone">
<ProfileContactFieldsIcon icon="fax fas" /> { fax }
</EditableField>
<EditableField label="Skype" labelID="skype" fallbackText="No skype ID" fieldType="username">
<ProfileContactFieldsIcon icon="skype fas" /> { skype }
</EditableField>
</FieldSet>
);
}
function ProfileContactFieldsIcon({ icon }){
return <i className={"visible-lg-inline icon icon-fw icon-" + icon }/>;
}
/**
* Renders out the lab and awards fields for user, which are not editable.
* Uses AJAX to fetch details for fields which are not embedded.
*
* @private
* @type {Component}
*/
class ProfileWorkFields extends React.PureComponent {
/**
* Get list of all awards (unique) from list of labs.
* ToDo : Migrate somewhere more static-cy.
*
* @param {Item[]} labDetails - Array of lab objects with embedded award details.
* @return {Item[]} List of all unique awards in labs.
*/
static getAwardsList(labDetails){
if (!labDetails || !Array.isArray(labDetails) || labDetails.length === 0){
return [];
}
// Awards are embedded within labs, so we get full details.
var awardsList = [];
function addAwardToList(award){
if (!award || typeof award['@id'] !== 'string' || _.pluck(awardsList, '@id').indexOf(award['@id']) > -1) return;
awardsList.push(award);
}
_.forEach(labDetails, function(lab){
if (!lab || !lab.awards || !Array.isArray(lab.awards) || lab.awards.length === 0) return;
_.forEach(lab.awards, addAwardToList);
});
return awardsList;
}
static defaultProps = {
containerClassName : 'panel user-work-info shadow-border'
}
constructor(props){
super(props);
this.updateAwardsList = this.updateAwardsList.bind(this);
this.render = this.render.bind(this);
this.state = {
'awards_list' : []
};
if (props.user && props.user.lab && props.user.lab.awards){
this.state.awards_list = props.user.lab.awards.slice(0);
}
}
/**
* Update state.awards_list with award details from list of lab details.
*
* @param {Item[]} labDetails - Array of lab objects with embedded award details.
* @returns {void} Nothing.
*/
updateAwardsList(labDetails){
if (!labDetails || !Array.isArray(labDetails) || labDetails.length === 0){
return;
}
this.setState(function({ awards_list = [] }){
// As of React 16 we can return null in setState func to cancel out of state update.
const nextAwardsList = awards_list.slice(0);
const nextAwardsListIDs = new Set(_.map(nextAwardsList, object.atIdFromObject));
const newAwards = ProfileWorkFields.getAwardsList(labDetails);
for (var i = 0; i < newAwards.length; i++){
const award = newAwards[i];
const awardID = award && object.atIdFromObject(award);
if (!awardID) continue; // Error ?
if (!nextAwardsListIDs.has(awardID)) nextAwardsList.push(award);
}
if (nextAwardsList.length > (awards_list || []).length){
return { 'awards_list' : nextAwardsList };
} else {
return null;
}
});
}
render(){
const { user, containerClassName } = this.props;
const { submits_for = [], lab, pending_lab, job_title } = user;
const { awards_list: awards } = this.state;
let labTitle = <span className="not-set">No Labs</span>;
const pendingLabText = "Will be verified in the next few business days"; // Default
if (lab){
labTitle = object.itemUtil.generateLink(lab);
} else if (pending_lab && object.itemUtil.isAnItem(pending_lab)){
// Might occur later... currently not embedded.
labTitle = <span>{ object.itemUtil.generateLink(pending_lab) } <em data-tip={pendingLabText}>(pending)</em></span>;
} else if (pending_lab && typeof pending_lab === 'string'){
labTitle = <span className="text-400">{ pendingLabText }</span>;
}
// THESE FIELDS ARE NOT EDITABLE.
// To be modified by admins, potentially w/ exception of 'Primary Lab' (e.g. select from submits_for list).
return (
<div className={containerClassName}>
<h3 className="text-300 block-title">
<i className="icon icon-users icon-fw fas"/> Organizations
</h3>
<div className="row field-entry lab">
<div className="col-md-3 text-right text-left-xs">
<label htmlFor="lab">Primary Lab</label>
</div>
<div id="lab" className="col-md-9 value text-500">
{ labTitle }
</div>
</div>
<div className="row field-entry job_title">
<div className="col-md-3 text-right text-left-xs">
<label htmlFor="job_title">Role</label>
</div>
<div id="job_title" className="col-md-9 value">
{ job_title || <span className="not-set">No Job Title</span> }
</div>
</div>
<div className="row field-entry submits_for">
<div className="col-md-3 text-right text-left-xs">
<label htmlFor="submits_for">Submits For</label>
</div>
<div className="col-md-9 value text-500">
<FormattedInfoBlock.List
renderItem={object.itemUtil.generateLink}
endpoints={_.filter(_.map(submits_for, object.itemUtil.atId))}
propertyName="submits_for"
fallbackMsg="Not submitting for any organizations"
ajaxCallback={this.updateAwardsList}
/>
</div>
</div>
<div className="row field-entry awards">
<div className="col-md-3 text-right text-left-xs">
<label htmlFor="awards">Awards</label>
</div>
<div className="col-md-9 value text-500">
<FormattedInfoBlock.List
details={awards}
renderItem={object.linkFromItem}
propertyName="awards"
fallbackMsg="No awards"
loading={false}
/>
</div>
</div>
</div>
);
}
}
/**
* @private
* @type {Component}
*/
class BasicForm extends React.PureComponent {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
'value' : ''
};
}
handleChange(e) {
this.setState({ 'value': e.target.value });
}
handleSubmit(e){
e.preventDefault();
const { onSubmit } = this.props, { value } = this.state;
if (value.length === 0){
return;
}
onSubmit(value);
this.setState({ 'value': '' });
}
render() {
const { value } = this.state;
return(
<form onSubmit={this.handleSubmit}>
<FormControl className="mt-08" type="text" placeholder="Enter an email to impersonate..."
onChange={this.handleChange} value={value}/>
<button type="submit" className="btn btn-primary btn-md mt-15">
<i className="icon icon-fw icon-user fas"/> Impersonate
</button>
</form>
);
}
}
/**
* @private
* @type {Component}
*/
export class ImpersonateUserForm extends React.PureComponent {
static propTypes = {
'updateAppSessionState': PropTypes.func.isRequired
};
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
/**
* Handler for Impersonate User submit button/action.
* Performs AJAX request to '/impersonate-user' endpoint then saves returned JWT
* as own and in order to pretend to be impersonated user.
*
* @instance
* @param {Object} data - User ID or email address.
*/
handleSubmit(data) {
const { updateAppSessionState } = this.props;
const url = "/impersonate-user";
const postData = { 'userid' : data };
const callbackFxn = (resp) => {
//if(typeof(Storage) !== 'undefined'){ // check if localStorage supported
// localStorage.setItem("user_info", JSON.stringify(payload));
//}
JWT.saveUserInfoLocalStorage(resp);
updateAppSessionState();
let navTarget = "/";
const profileAction = resp.user_actions && _.find(resp.user_actions, { 'id' : 'profile' });
if (profileAction && profileAction.href){
navTarget = profileAction.href;
}
navigate(navTarget, { 'inPlace' : true });
alert('Success! ' + data + ' is being impersonated.');
};
const fallbackFxn = function() {
alert('Impersonation unsuccessful.\nPlease check to make sure the provided email is correct.');
};
//var userInfo = localStorage.getItem('user_info') || null;
//var idToken = userInfo ? JSON.parse(userInfo).id_token : null;
//var reqHeaders = {'Accept': 'application/json'};
//if(userInfo){
// reqHeaders['Authorization'] = 'Bearer '+idToken;
//}
ajax.load(url, callbackFxn, 'POST', fallbackFxn, JSON.stringify(postData));
}
render() {
return (
<div className="mt-3 container" id="content">
<hr />
<h2 className="text-400 mt-5">Impersonate a User</h2>
<div className="row">
<div className="col-12 col-lg-6">
<BasicForm onSubmit={this.handleSubmit} />
</div>
</div>
</div>
);
}
}
const UserPageTitle = React.memo(function UserPageTitle(props) {
const { alerts, context, session, href, schemas } = props;
const myDetails = JWT.getUserDetails();
const myEmail = myDetails && myDetails.email;
if (myEmail && context && context.email && myEmail === context.email) {
return (
<PageTitleContainer alerts={alerts}>
<StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" />
<TitleAndSubtitleUnder>
My Profile
</TitleAndSubtitleUnder>
</PageTitleContainer>
);
}
return (
<PageTitleContainer alerts={alerts}>
<StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" />
<OnlyTitle>User</OnlyTitle>
</PageTitleContainer>
);
});
pageTitleViews.register(UserPageTitle, "User");
|
app/javascript/mastodon/features/report/components/status_check_box.js | yukimochi/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
import noop from 'lodash/noop';
import StatusContent from '../../../components/status_content';
import { MediaGallery, Video } from '../../ui/util/async-components';
import Bundle from '../../ui/components/bundle';
export default class StatusCheckBox extends React.PureComponent {
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
checked: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
disabled: PropTypes.bool,
};
render () {
const { status, checked, onToggle, disabled } = this.props;
let media = null;
if (status.get('reblog')) {
return null;
}
if (status.get('media_attachments').size > 0) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
media = (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
blurhash={video.get('blurhash')}
src={video.get('url')}
alt={video.get('description')}
width={239}
height={110}
inline
sensitive={status.get('sensitive')}
onOpenVideo={noop}
/>
)}
</Bundle>
);
} else {
media = (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />}
</Bundle>
);
}
}
return (
<div className='status-check-box'>
<div className='status-check-box__status'>
<StatusContent status={status} />
{media}
</div>
<div className='status-check-box-toggle'>
<Toggle checked={checked} onChange={onToggle} disabled={disabled} />
</div>
</div>
);
}
}
|
src/datepicker/Month.js | prometheusresearch/react-datetimepicker | /**
* @copyright 2016-present Prometheus Research, LLC
*/
import noop from 'lodash/noop';
import React from 'react';
import moment from 'moment';
import {Button} from '../ui';
const MONTHS_SHORT = moment.monthsShort();
export default class Month extends React.Component {
static propTypes = {
month: React.PropTypes.number,
active: React.PropTypes.bool,
onClick: React.PropTypes.func,
};
static defaultProps = {
onClick: noop,
};
render() {
let {active, month, ...props} = this.props;
return (
<Button
{...props}
width={7 / 3}
active={active}
tabIndex={0}
onClick={this.onClick}>
{MONTHS_SHORT[month]}
</Button>
);
}
onClick = () => {
this.props.onClick(this.props.month);
};
}
|
stories/color-picker.js | CommonActionForum/liqen-face | import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import ColorPicker from '../client/components/annotators/color-picker'
storiesOf('ColorPicker', module)
.add('8 colors', () => {
const list = [
{
code: '#FFAB40',
title: 'Orange A200',
selected: true
},
{
code: '#E91E63',
title: 'Pink 500'
},
{
code: '#E040FB',
title: 'Purple A200'
},
{
code: '#AA00FF',
title: 'Purple A700',
selected: true
},
{
code: '#9FA8DA',
title: 'Indigo 200'
},
{
code: '#2962FF',
title: 'Blue A700',
selected: true
},
{
code: '#18FFFF',
title: 'Cyan A200'
},
{
code: '#B2FF59',
title: 'Light Green A200'
},
{
code: '#EEFF41',
title: 'Lime A200'
},
{
code: '#FFFFFF',
title: 'white'
}
]
return (
<ColorPicker
list={list}
onSelect={action('select color')}
position={{top: 0, left: 100, width: 0, height: 0}}
/>
)
})
|
src/component/knight/KnightPage.js | NJU-itxia/front-end | import React, { Component } from 'react';
import { Navbar, Nav, NavItem, Glyphicon } from "react-bootstrap";
import { LinkContainer, IndexLinkContainer } from "react-router-bootstrap";
const style = {
"marginBottom": 0,
};
export default class App extends Component {
state = {
adminLoggedIn: true
};
render() {
const navbarAdmin = (
<LinkContainer to="/knight/setting">
<NavItem><Glyphicon glyph="glyphicon glyphicon-cog" /> 设置</NavItem>
</LinkContainer>
);
return (
<div>
<Navbar style={ style }>
<Navbar.Header className='navbar-header'>
<Navbar.Brand>
<IndexLinkContainer to='/login'>
<a>南京大学 IT 侠预约处理系统</a>
</IndexLinkContainer>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<LinkContainer to="/knight/orders">
<NavItem><Glyphicon glyph="list-alt" /> 处理请求</NavItem>
</LinkContainer>
<LinkContainer to="/knight/message">
<NavItem><Glyphicon glyph="comment" /> 最近回复</NavItem>
</LinkContainer>
{this.state.adminLoggedIn ? navbarAdmin : null}
</Nav>
<Nav pullRight>
<LinkContainer to="/logout" onClick={this.handleLogout.bind(this)}>
<NavItem><Glyphicon glyph="log-out" /> 登出</NavItem>
</LinkContainer>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className="container">
{this.props.children}
</div>
<footer className="page-footer">
<div className="container">
<hr className="colorgraph" />
<p className="text-center">Designed and built by LC & 南京大学 IT 侠工作室</p>
</div>
</footer>
</div>
);
}
handleLogout() {
}
}
|
src/utils/childUtils.js | lawrence-yu/material-ui | import React from 'react';
import createFragment from 'react-addons-create-fragment';
export function createChildFragment(fragments) {
const newFragments = {};
let validChildrenCount = 0;
let firstKey;
// Only create non-empty key fragments
for (const key in fragments) {
const currentChild = fragments[key];
if (currentChild) {
if (validChildrenCount === 0) firstKey = key;
newFragments[key] = currentChild;
validChildrenCount++;
}
}
if (validChildrenCount === 0) return undefined;
if (validChildrenCount === 1) return newFragments[firstKey];
return createFragment(newFragments);
}
export function extendChildren(children, extendedProps, extendedChildren) {
return React.Children.map(children, (child) => {
if (!React.isValidElement(child)) {
return child;
}
const newProps = typeof extendedProps === 'function' ?
extendedProps(child) : extendedProps;
const newChildren = typeof extendedChildren === 'function' ?
extendedChildren(child) : extendedChildren ?
extendedChildren : child.props.children;
return React.cloneElement(child, newProps, newChildren);
});
}
|
app/javascript/mastodon/components/avatar_composite.js | lynlynlynx/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class AvatarComposite extends React.PureComponent {
static propTypes = {
accounts: ImmutablePropTypes.list.isRequired,
animate: PropTypes.bool,
size: PropTypes.number.isRequired,
};
static defaultProps = {
animate: autoPlayGif,
};
renderItem (account, size, index) {
const { animate } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '1px';
} else {
left = '1px';
}
} else if (size === 3) {
if (index === 0) {
right = '1px';
} else if (index > 0) {
left = '1px';
}
if (index === 1) {
bottom = '1px';
} else if (index > 1) {
top = '1px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '1px';
}
if (index === 1 || index === 3) {
left = '1px';
}
if (index < 2) {
bottom = '1px';
} else {
top = '1px';
}
}
const style = {
left: left,
top: top,
right: right,
bottom: bottom,
width: `${width}%`,
height: `${height}%`,
backgroundSize: 'cover',
backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`,
};
return (
<div key={account.get('id')} style={style} />
);
}
render() {
const { accounts, size } = this.props;
return (
<div className='account__avatar-composite' style={{ width: `${size}px`, height: `${size}px` }}>
{accounts.take(4).map((account, i) => this.renderItem(account, Math.min(accounts.size, 4), i))}
{accounts.size > 4 && (
<span className='account__avatar-composite__label'>
+{accounts.size - 4}
</span>
)}
</div>
);
}
}
|
app/javascript/mastodon/components/icon_button.js | robotstart/mastodon | import React from 'react';
import { Motion, spring } from 'react-motion';
import PropTypes from 'prop-types';
class IconButton extends React.PureComponent {
constructor (props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
handleClick (e) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onClick(e);
}
}
render () {
let style = {
fontSize: `${this.props.size}px`,
width: `${this.props.size * 1.28571429}px`,
height: `${this.props.size * 1.28571429}px`,
lineHeight: `${this.props.size}px`,
...this.props.style
};
if (this.props.active) {
style = { ...style, ...this.props.activeStyle };
}
const classes = ['icon-button'];
if (this.props.active) {
classes.push('active');
}
if (this.props.disabled) {
classes.push('disabled');
}
if (this.props.inverted) {
classes.push('inverted');
}
if (this.props.overlay) {
classes.push('overlayed');
}
if (this.props.className) {
classes.push(this.props.className)
}
return (
<Motion defaultStyle={{ rotate: this.props.active ? -360 : 0 }} style={{ rotate: this.props.animate ? spring(this.props.active ? -360 : 0, { stiffness: 120, damping: 7 }) : 0 }}>
{({ rotate }) =>
<button
aria-label={this.props.title}
title={this.props.title}
className={classes.join(' ')}
onClick={this.handleClick}
style={style}>
<i style={{ transform: `rotate(${rotate}deg)` }} className={`fa fa-fw fa-${this.props.icon}`} aria-hidden='true' />
</button>
}
</Motion>
);
}
}
IconButton.propTypes = {
className: PropTypes.string,
title: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
onClick: PropTypes.func,
size: PropTypes.number,
active: PropTypes.bool,
style: PropTypes.object,
activeStyle: PropTypes.object,
disabled: PropTypes.bool,
inverted: PropTypes.bool,
animate: PropTypes.bool,
overlay: PropTypes.bool
};
IconButton.defaultProps = {
size: 18,
active: false,
disabled: false,
animate: false,
overlay: false
};
export default IconButton;
|
src/Root.js | deguchi/mastobone | /**
* @flow
*/
import React, { Component } from 'react';
import { createStore, applyMiddleware, compose } from 'redux';
import { AsyncStorage } from 'react-native';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import reducers from './reducers';
import App from './App';
var isDebuggingInChrome = __DEV__ && !!window.navigator.userAgent;
// create store...
const store = compose(
applyMiddleware(thunk)
)(createStore)(reducers);
if (isDebuggingInChrome) {
window.store = store;
}
console.disableYellowBox = true;
export default class Root extends Component {
render () {
return (
<Provider store={store}>
<App />
</Provider>
)
}
} |
wp-content/themes/adaycurated/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | SarahJune/wp-adc | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
src/utils/createContextWrapper.js | Azerothian/react-bootstrap | import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function (contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, ...props} = this.props; // eslint-disable-line object-shorthand
delete props.context;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
src/app/components/Examples.js | arraqib/react-weather | import React from 'react';
export default class Examples extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<h4>Examples Component</h4>
</div>
);
}
} |
frontend/routes.js | anabiozz/blog | import React from 'react';
import IndexRoute from 'react-router/lib/IndexRoute';
// import IndexRedirect from 'react-router/lib/IndexRedirect';
import Route from 'react-router/lib/Route';
//Layouts
import Layout from './containers/Layout';
//containers
import Login from './containers/Login';
import LocalAuth from './containers/LocalAuth';
//components
export default (user) => {
function requireAuth(nextState, replace) {
if (!user) {
replace({
pathname: '/'
});
}
}
function hasLogin(nextState, replace) {
if (user && user.name != 'Unknown') {
replace({
pathname: '/dashboard'
});
}
}
const core_url = process.env.CORE_URL ? process.env.CORE_URL : '/';
return (
<Route path={core_url} component={Layout} mode={'full'}>
<IndexRoute component={Login} onEnter={hasLogin} />
<Route path="signin" component={LocalAuth} onEnter={hasLogin} />
<Route path="dashboard" onEnter={requireAuth}/>
</Route>
);
}; |
src/pages/404.js | scimusmn/app-template | import React from 'react';
import NoMatch from '@components/NoMatch';
function NotFoundPage() {
return <NoMatch />;
}
export default NotFoundPage;
|
src/containers/Asians/BreaksCalculator/BreakingTeamPointsDistribution/index.js | westoncolemanl/tabbr-web | import React from 'react'
import Card, {
CardContent
} from 'material-ui/Card'
import SureBreakPoints from './SureBreakPoints'
import BreakPointsTable from './BreakPointsTable'
export default ({
result,
numberOfBreakingTeams,
numberOfRounds
}) => {
return (
<Card
className={'overflow-x-scroll'}
>
<CardContent>
<SureBreakPoints
breakPoint={Number(result.sureBreak)}
/>
<BreakPointsTable
result={result}
numberOfBreakingTeams={numberOfBreakingTeams}
numberOfRounds={numberOfRounds}
/>
</CardContent>
</Card>
)
}
|
src/containers/PetitionInfo.js | iris-dni/iris-frontend | import React from 'react';
import { connect } from 'react-redux';
import PetitionInfo from 'components/PetitionInfo';
import getPetitionInfo from 'selectors/petitionInfo';
const PetitionInfoContainer = (props) => (
<PetitionInfo {...props} />
);
const mapStateToProps = ({ petition }) => getPetitionInfo(petition);
PetitionInfoContainer.propTypes = {
owner: React.PropTypes.string,
city: React.PropTypes.object,
ending: React.PropTypes.string
};
export default connect(
mapStateToProps
)(PetitionInfoContainer);
|
src/Input.js | bbc/react-bootstrap | import React from 'react';
import InputBase from './InputBase';
import * as FormControls from './FormControls';
import deprecationWarning from './utils/deprecationWarning';
class Input extends InputBase {
render() {
if (this.props.type === 'static') {
deprecationWarning('Input type=static', 'FormControls.Static');
return <FormControls.Static {...this.props} />;
}
return super.render();
}
}
Input.propTypes = {
type: React.PropTypes.string
};
export default Input;
|
ditto/static/tidy/js/lib/state.js | Kvoti/ditto | // Wrap React.addons.update for common operations
//
// Use as follows
//
// <input onChange={state.set.bind(this, ['some', 'part', 'of', 'state'])}
//
//
import React from 'react';
export const Arg = '__arg__';
export function set(...args) {
let [path, e] = getChangePath(args);
let value;
if (!e.target) {
value = e;
} else if (e.target.type === 'checkbox' || e.target.type === 'radio') {
value = e.target.checked;
} else {
value = e.target.value;
}
const change = getChangeSpec(path, '$set', value);
console.log('change', change);
this.setState((state) => {
return React.addons.update(state, change);
});
}
export function add(...args) {
let [path, value] = getChangePath(args);
const change = getChangeSpec(path, '$push', [value]);
const newState = React.addons.update(this.state, change);
this.setState(newState);
}
export function remove(...args) {
let [path, index] = getChangePath(args);
const change = getChangeSpec(path, '$splice', [[index, 1]]);
const newState = React.addons.update(this.state, change);
this.setState(newState);
}
function getChangePath(args) {
console.log('path', args);
let path = args[0];
const last = args.pop();
const params = args.slice(1);
console.log(path, params, last);
path = replaceParamsInPath(path, params);
return [path, last];
}
function replaceParamsInPath(path, params) {
console.log('replacing', path, params);
let replaced = path.map(part => {
if (part === Arg) {
let replacement = params[0];
params = params.slice(1);
return replacement;
}
return part;
});
console.log('replaced', replaced, 'remaining', params);
return replaced.concat(params);
}
function getChangeSpec(path, operation, value) {
const change = {};
let tmp = change;
path.forEach(key => {
tmp[key] = {};
tmp = tmp[key];
});
tmp[operation] = value;
console.log('change', change);
return change;
}
|
client/modules/App/components/DevTools.js | Amigos466/GITTER-REACT | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
imports/ui/dataTable/helpers.js | ctagroup/home-app | import '/imports/ui/dataTable/dataTableEditButton';
import '/imports/ui/dataTable/dataTableDeleteButton';
import '/imports/ui/dataTable/dataTableTextButton';
import '/imports/ui/dataTable/createButton';
import { fullName } from '/imports/api/utils';
import { formatDate } from '/imports/both/helpers';
import BlazeTemplate from '/imports/ui/components/BlazeComponent';
import React from 'react';
import Users from '/imports/api/users/users';
export const TableDom = '<"box"<"box-header"<"box-toolbar"<"clearfix"ri><"pull-left"<lf>><"pull-right"p>>><"box-body table-responsive"t>>'; // eslint-disable-line max-len
// eslint-disable-next-line react/react-in-jsx-scope
export const blazeData = (name, data, classes) =>
(<BlazeTemplate name={name} data={data} classes={classes} />);
export function editButton(path, options) {
return Object.assign({
data: '_id',
title: 'Edit',
filterable: false,
render() {
return '';
},
createdCell(node, _id) {
const data = {
path,
_id,
};
Blaze.renderWithData(Template.DataTableEditButton, data, node);
},
reactCreatedCell(node, _id, row) {
const data = {
path,
_id,
row,
};
return blazeData('DataTableEditButton', data);
},
width: '45px',
orderable: false,
}, options);
}
export function deleteHouseholdButton() {
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id) {
const templateData = {
_id,
message: `Are you sure you want to delete household ${_id}?`,
method: 'deleteHousehold',
args: [_id],
onSuccess() {
Meteor.setTimeout(() => location.reload(), 1500);
},
};
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id) {
const templateData = {
_id,
message: `Are you sure you want to delete household ${_id}?`,
method: 'deleteHousehold',
args: [_id],
onSuccess() {
Meteor.setTimeout(() => location.reload(), 1500);
},
};
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteHousingUnitButton() {
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id, rowData) {
const name = rowData.aliasName || _id;
const templateData = {
_id,
message: `Are you sure you want to delete housing unit ${name} (${_id})?`,
method: 'housingUnits.delete',
args: [_id],
onSuccess() {
// Meteor.setTimeout(() => location.reload(), 1500);
},
};
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id, rowData) {
const name = rowData.aliasName || _id;
const templateData = {
_id,
message: `Are you sure you want to delete housing unit ${name} (${_id})?`,
method: 'housingUnits.delete',
args: [_id],
onSuccess() {
// Meteor.setTimeout(() => location.reload(), 1500);
},
};
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteSurveyButton(onSuccessCallback) {
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id, rowData) {
const title = rowData.title || _id;
const templateData = {
_id,
message: `Are you sure you want to delete Survey ${title} (${_id})?`,
method: 'surveys.delete',
args: [_id],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
};
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id, rowData) {
const title = rowData.title || _id;
const templateData = {
_id,
message: `Are you sure you want to delete Survey ${title} (${_id})?`,
method: 'surveys.delete',
args: [_id],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
};
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteQuestionButton(onSuccessCallback) {
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id, rowData) {
const title = rowData.displayText || _id;
const templateData = {
_id,
message: `Are you sure you want to delete Question ${title} (${_id})?`,
method: 'questions.delete',
args: [rowData.questionGroupId, _id],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
};
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id, rowData) {
const title = rowData.displayText || _id;
const templateData = {
_id,
message: `Are you sure you want to delete Question ${title} (${_id})?`,
method: 'questions.delete',
args: [rowData.questionGroupId, _id],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
};
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteUserButton() {
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id) {
const user = Users.findOne(_id);
const name = fullName(user.services.HMIS || {}) || _id;
const templateData = {
_id,
message: `Are you sure you want to delete user ${name}?`,
method: 'users.delete',
args: [_id],
onSuccess() {
// Meteor.setTimeout(() => location.reload(), 1500);
},
};
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id) {
const user = Users.findOne(_id);
const name = fullName(user.services.HMIS || {}) || _id;
const templateData = {
_id,
message: `Are you sure you want to delete user ${name}?`,
method: 'users.delete',
args: [_id],
onSuccess() {
// Meteor.setTimeout(() => location.reload(), 1500);
},
};
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteFileButton() {
const composeData = (_id) => ({
_id,
message: 'Are you sure you want to delete this file?',
method: 'files.delete',
args: [_id],
});
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id) {
const templateData = composeData(_id);
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id) {
const templateData = composeData(_id);
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteResponseButton(onSuccessCallback) {
const composeData = (_id, rowData) => {
const name = fullName(rowData.clientDetails) || rowData.clientId;
return {
_id,
message: `Are you sure you want to delete the response of ${name}?`,
method: 'responses.delete',
args: [_id],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
};
};
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function deleteProjectButton(onSuccessCallback) {
const composeData = (_id, rowData) => (
{
_id,
message: `Are you sure you want to delete the project ${rowData.projectName}?`,
method: 'projects.delete',
args: [_id, rowData.schema],
onSuccess() {
if (onSuccessCallback) {
onSuccessCallback(rowData);
}
},
}
);
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
createdCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
Blaze.renderWithData(Template.DataTableDeleteButton, templateData, node);
},
reactCreatedCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
return blazeData('DataTableDeleteButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function removeClientTagButton(onSuccessCallback) {
const composeData = (_id, rowData) => {
const removed = rowData.operation;
const inverseOperation = rowData.operation ? 0 : 1;
return {
_id,
operation: rowData.operation,
operationText: removed ? 'Remove' : 'Add',
title: `Confirm ${removed ? 'removal' : 'addition'}`,
message: `Are you sure you want to ${removed ? 'remove' : 'add'
} client tag #${rowData.id} (${rowData.tag.name}) as of ${formatDate(rowData.date)}?`,
method: 'tagApi',
args: ['createClientTag',
{ ...rowData, operation: inverseOperation, appliedOn: rowData.date }],
onSuccess(result) {
if (onSuccessCallback) onSuccessCallback(result);
},
};
};
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
reactCreatedCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
return blazeData('DataTableTextButton', templateData);
},
width: '45px',
orderable: false,
};
}
export function removeReferralButton(onSuccessCallback) {
const composeData = (_id, rowData) => {
return {
_id,
operation: 0,
operationText: 'Remove',
title: 'Confirm removal',
message: `Are you sure you want to remove Referral #${rowData.id}?`,
method: 'tagApi',
args: ['removeReferral', rowData],
onSuccess(result) {
if (onSuccessCallback) onSuccessCallback(result);
},
};
};
return {
data: '_id',
title: 'Delete',
filterable: false,
render() { return ''; },
reactCreatedCell(node, _id, rowData) {
const templateData = composeData(_id, rowData);
return blazeData('DataTableTextButton', templateData);
},
width: '45px',
orderable: false,
};
}
|
app/components/Base.js | appbaseio-apps/gitxplore | import React, { Component } from 'react';
import {
ReactiveBase,
CategorySearch,
ResultCard,
MultiDropdownList,
RangeSlider,
SingleDropdownRange
} from '@appbaseio/reactivesearch';
import './Base.styl';
class Base extends Component {
constructor() {
super();
this.state = {
topics: [],
showNav: false
};
this.toggleTopic = this.toggleTopic.bind(this);
this.resetTopic = this.resetTopic.bind(this);
this.handleToggleFilters = this.handleToggleFilters.bind(this);
}
handleToggleFilters() {
const showNav = !this.state.showNav;
this.setState({
showNav
});
}
toggleTopic(topic) {
const topics = [ ...this.state.topics ];
const index = topics.indexOf(topic);
let nextTopics = [];
if (index === -1) {
nextTopics = [ ...topics, topic ];
} else {
nextTopics = topics.slice(0, index).concat(topics.slice(index + 1));
}
this.setState({
topics: nextTopics
});
}
resetTopic(topics) {
const nextTopics = topics || [];
this.setState({
topics: nextTopics
});
}
onData(res, toggleTopic) {
const result = {
desc: (
<div className="card-layout">
<div className="card-top">
<div className="card-details">
<div className="card-title">
<img src={res.avatar} className="card-image" />
<a href={res.url} target="_blank">
{res.owner}/{res.owner.length + res.name.length > 27 ? <br /> : ''}{res.name}
</a>
</div>
<div className="card-description">
{res.description}
</div>
{
res.topics.length > 0 ?
<div className="card-tags">
{res.topics.slice(0, 7).map(topic => <span className="card-tag" key={`${res.name}-${topic}`} onClick={() => toggleTopic(topic)}>#{topic}</span>)}
</div> :
null
}
</div>
</div>
<div className="card-bottom">
<a href={res.url} target="_blank">
<div className="card-stars">
<i className="fa fa-star" aria-hidden="true" />{res.stars}
</div>
</a>
<a href={res.url} target="_blank">
<div className="card-stars">
<i className="fa fa-code-fork" aria-hidden="true" />{res.forks}
</div>
</a>
<a href={res.url} target="_blank">
<div className="card-stars">
<i className="fa fa-eye" aria-hidden="true" />{res.watchers}
</div>
</a>
</div>
</div>
)
};
return result;
}
render() {
return (
<ReactiveBase
app="gitxplore-latest"
type="gitxplore-latest"
credentials="W7ZomvYgQ:df994896-a25d-4d4e-8724-e26659b93001"
theme="rbc-green"
>
<div className={`${this.state.showNav ? 'full-header' : ''}`}>
<header>
<div className="search-params">
<div className="title">
<a href="https://appbaseio-apps.github.io/gitxplore/">
<h3>GitXplore</h3>
</a>
</div>
<div className="toggle-button" onClick={this.handleToggleFilters}>
<i className="fa fa-search-plus" aria-hidden="true" />
Toggle Filters
</div>
<div className="search-filters">
<MultiDropdownList
componentId="language"
dataField="language.raw"
title="Language"
size={100}
URLParams
/>
<MultiDropdownList
componentId="topics"
dataField="topics.raw"
title="Repo Topics"
defaultSelected={this.state.topics}
size={1000}
queryFormat="and"
onValueChange={value => this.resetTopic(value)}
URLParams
/>
<SingleDropdownRange
componentId="pushed"
dataField="pushed"
title="Last Active"
data={[
{"start": "now-1M", "end": "now", "label": "Last 30 days"},
{"start": "now-6M", "end": "now", "label": "Last 6 months"},
{"start": "now-1y", "end": "now", "label": "Last year"}
]}
URLParams
/>
<SingleDropdownRange
componentId="created"
dataField="created"
title="Created"
data={[
{"start": "2017-01-01T00:00:00Z", "end": "2017-12-31T23:59:59Z", "label": "2017"},
{"start": "2016-01-01T00:00:00Z", "end": "2016-12-31T23:59:59Z", "label": "2016"},
{"start": "2015-01-01T00:00:00Z", "end": "2015-12-31T23:59:59Z", "label": "2015"},
{"start": "2014-01-01T00:00:00Z", "end": "2014-12-31T23:59:59Z", "label": "2014"},
{"start": "2013-01-01T00:00:00Z", "end": "2013-12-31T23:59:59Z", "label": "2013"},
{"start": "2012-01-01T00:00:00Z", "end": "2012-12-31T23:59:59Z", "label": "2012"},
{"start": "2011-01-01T00:00:00Z", "end": "2011-12-31T23:59:59Z", "label": "2011"},
{"start": "2010-01-01T00:00:00Z", "end": "2010-12-31T23:59:59Z", "label": "2010"},
{"start": "2009-01-01T00:00:00Z", "end": "2009-12-31T23:59:59Z", "label": "2009"},
{"start": "2008-01-01T00:00:00Z", "end": "2008-12-31T23:59:59Z", "label": "2008"},
{"start": "2007-01-01T00:00:00Z", "end": "2007-12-31T23:59:59Z", "label": "2007"}
]}
URLParams
/>
<RangeSlider
componentId="stars"
dataField="stars"
title="Repo Stars"
showHistogram={false}
range={{
"start": 0,
"end": 300000
}}
defaultSelected={{
"start": 0,
"end": 300000
}}
rangeLabels={{
"start": "0 Stars",
"end": "300K Stars"
}}
stepValue={1}
/>
<RangeSlider
componentId="forks"
dataField="forks"
title="Repo Forks"
showHistogram={false}
range={{
"start": 0,
"end": 180000
}}
defaultSelected={{
"start": 0,
"end": 180000
}}
rangeLabels={{
"start": "0 Forks",
"end": "180K Forks"
}}
stepValue={1}
/>
</div>
</div>
</header>
</div>
<div className="content">
<CategorySearch
componentId="repo"
dataField={["name", "description", "name.raw", "fullname", "owner", "topics"]}
categoryField="language.raw"
queryFormat="and"
placeholder="Search Repos"
URLParams={true}
/>
<ResultCard
componentId="SearchResult"
dataField="name"
noResults="No results were found, try clearing all the filters."
pagination={true}
size={6}
onData={(res) => this.onData(res, this.toggleTopic)}
react={{
and: ["repo", "topics", "stars", "forks", "pushed", "created", "language"]
}}
sortOptions={[
{
label: "Best Match",
dataField: "_score",
sortBy: "desc"
},
{
label: "Most Stars",
dataField: "stars",
sortBy: "desc"
},
{
label: "Fewest Stars",
dataField: "stars",
sortBy: "asc"
},
{
label: "Most Forks",
dataField: "forks",
sortBy: "desc"
},
{
label: "Fewest Forks",
dataField: "forks",
sortBy: "asc"
},
{
label: "A to Z",
dataField: "owner.raw",
sortBy: "asc"
},
{
label: "Z to A",
dataField: "owner.raw",
sortBy: "desc"
},
{
label: "Recently Updated",
dataField: "pushed",
sortBy: "desc"
},
{
label: "Least Recently Updated",
dataField: "pushed",
sortBy: "asc"
}
]}
/>
<div
className="blog-container"
onClick={() => window.open('https://medium.appbase.io/how-to-build-a-github-search-ui-in-60-minutes-295109211c70')}
>
<a
className="blog"
href="https://medium.appbase.io/how-to-build-a-github-search-ui-in-60-minutes-295109211c70"
target="_blank"
>
<i className="fa fa-newspaper-o" /> Read How We Built It!
</a>
</div>
</div>
</ReactiveBase>
);
}
}
export default Base;
|
src/button-content.js | anthonyjgrove/react-google-login | import React from 'react'
const ButtonContent = ({ children, icon }) => (
<span style={{ paddingRight: 10, fontWeight: 500, paddingLeft: icon ? 0 : 10, paddingTop: 10, paddingBottom: 10 }}>{children}</span>
)
export default ButtonContent
|
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Wallet/js/components/passwordprompt.js | patel344/Mr.Miner | import PropTypes from 'prop-types'
import React from 'react'
const PasswordPrompt = ({password, error, unlocking, actions}) => {
const onPasswordChange = (e) => actions.handlePasswordChange(e.target.value)
const onUnlockClick = () => actions.unlockWallet(password)
if (unlocking) {
return (
<span className="unlock-status"> Unlocking your wallet, this may take a while (up to several minutes)... </span>
)
}
return (
<div className="password-prompt">
<h2> Wallet Locked </h2>
<span> Enter your wallet password to unlock the wallet. </span>
<i className="fa fa-lock fa-4x" />
<input type="password" value={password} className="password-input" onChange={onPasswordChange} />
<button className="unlock-button" onClick={onUnlockClick}>Unlock</button>
<div className="password-prompt-error">{error}</div>
</div>
)
}
PasswordPrompt.propTypes = {
password: PropTypes.string.isRequired,
error: PropTypes.string,
}
export default PasswordPrompt
|
app/javascript/mastodon/components/status_content.js | esetomo/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { isRtl } from '../rtl';
import { FormattedMessage } from 'react-intl';
import Permalink from './permalink';
import classnames from 'classnames';
export default class StatusContent extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
expanded: PropTypes.bool,
onExpandedToggle: PropTypes.func,
onClick: PropTypes.func,
};
state = {
hidden: true,
};
_updateStatusLinks () {
const node = this.node;
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
let mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
link.setAttribute('title', link.href);
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener');
}
}
componentDidMount () {
this._updateStatusLinks();
}
componentDidUpdate () {
this._updateStatusLinks();
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '').toLowerCase();
if (this.context.router && e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/timelines/tag/${hashtag}`);
}
}
handleMouseDown = (e) => {
this.startXY = [e.clientX, e.clientY];
}
handleMouseUp = (e) => {
if (!this.startXY) {
return;
}
const [ startX, startY ] = this.startXY;
const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) {
return;
}
if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) {
this.props.onClick();
}
this.startXY = null;
}
handleSpoilerClick = (e) => {
e.preventDefault();
if (this.props.onExpandedToggle) {
// The parent manages the state
this.props.onExpandedToggle();
} else {
this.setState({ hidden: !this.state.hidden });
}
}
setRef = (c) => {
this.node = c;
}
render () {
const { status } = this.props;
const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
const content = { __html: status.get('contentHtml') };
const spoilerContent = { __html: status.get('spoilerHtml') };
const directionStyle = { direction: 'ltr' };
const classNames = classnames('status__content', {
'status__content--with-action': this.props.onClick && this.context.router,
'status__content--with-spoiler': status.get('spoiler_text').length > 0,
});
if (isRtl(status.get('search_index'))) {
directionStyle.direction = 'rtl';
}
if (status.get('spoiler_text').length > 0) {
let mentionsPlaceholder = '';
const mentionLinks = status.get('mentions').map(item => (
<Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'>
@<span>{item.get('username')}</span>
</Permalink>
)).reduce((aggregate, item) => [...aggregate, item, ' '], []);
const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />;
if (hidden) {
mentionsPlaceholder = <div>{mentionLinks}</div>;
}
return (
<div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
<p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
<span dangerouslySetInnerHTML={spoilerContent} />
{' '}
<button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button>
</p>
{mentionsPlaceholder}
<div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} />
</div>
);
} else if (this.props.onClick) {
return (
<div
ref={this.setRef}
tabIndex='0'
className={classNames}
style={directionStyle}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
dangerouslySetInnerHTML={content}
/>
);
} else {
return (
<div
tabIndex='0'
ref={this.setRef}
className='status__content'
style={directionStyle}
dangerouslySetInnerHTML={content}
/>
);
}
}
}
|
src/items/components/show.js | rek/grammar-notes | import React from 'react'
import {connect} from 'react-redux'
import {v4} from 'node-uuid';
import {
FormGroup,
ControlLabel,
FormControl,
Button,
ButtonToolbar
} from 'react-bootstrap'
import {ajax} from '../../utils'
import Actions from '../actions'
const Show = ({state, handleChange, handleEdit, handleSave}) =>
<div className='container-fluid' key={state.key}>
<form>
<div className='row'>
<div className='col-md-6'>
<FormGroup controlId='formControlsTextarea'>
<ControlLabel>Content:</ControlLabel>
<FormControl
rows='20'
value={state.content}
onChange={handleChange}
componentClass='textarea'
placeholder='...'
/>
</FormGroup>
</div>
</div>
<ButtonToolbar>
{/*
<Button type='submit' bsSize='small' onClick={handleEdit}>Edit Item</Button>
*/}
<Button type='submit' bsStyle='primary' onClick={handleSave}>Save</Button>
</ButtonToolbar>
</form>
</div>
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
key: v4(),
item: {
title: 'No Title',
content: 'Default Content'
}
}
}
componentDidMount() {
// console.log('Show mounted', this);
// console.log('Page:', this.props.routeParams.itemId);
ajax().get('/api/item/' + this.props.routeParams.itemId)
.then((data) => {
// console.log('GOT DATA in show:', data);
let item = data.data
console.log('Item:', item);
this.setState({
content: item.content
})
}).catch((error) => {
console.log('error', error);
})
}
// save the content of the item
handleSave(event) {
event.preventDefault()
this.props.save({
item_id: this.props.routeParams.itemId,
content: this.state.content
})
}
// edit the item title
handleEdit(event) {
event.preventDefault()
console.log('Editing:', this.props.routeParams.itemId);
this.props.edit(this.props.routeParams.itemId)
}
handleChange(event) {
event.preventDefault()
this.setState({content: event.target.value});
}
render() {
// console.log('this', this);
// console.log('state', this.state);
return (
<div>
<Show
state={this.state}
handleChange={this.handleChange}
handleEdit={this.handleEdit}
handleSave={this.handleSave}
/>
</div>
)
}
}
// to actions we need to add the things we wanna pass in
// Actions
// eg: handleChange
export default connect((state) => state.ItemsReducer, Actions)(App)
|
thinking-in-react/step-4.js | hackerrdave/nodeschool | import React from 'react';
export const ProductCategoryRow = React.createClass({
render() {
return (
<tr>
<th colSpan={2}>{this.props.category}</th>
</tr>
);
}
});
export const ProductRow = React.createClass({
render() {
const product = this.props.product;
const style = {
color: product.stocked ? null : 'red'
};
return (
<tr>
<td style={style}>{product.name}</td>
<td>{product.price}</td>
</tr>
);
}
});
export const ProductTable = React.createClass({
render() {
const products = this.props.products;
const rows = [];
let currentCategory;
products.forEach((product) => {
if (product.category !== currentCategory) {
currentCategory = product.category;
rows.push((
<ProductCategoryRow key={currentCategory} category={currentCategory}/>
));
}
rows.push((
<ProductRow key={product.name} product={product}/>
));
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
export const SearchBar = React.createClass({
render() {
return (
<form>
<input type="search" placeholder="Search..."/>
<label>
<input type="checkbox"/>
Only show products in stock
</label>
</form>
);
}
});
export const FilterableProductTable = React.createClass({
getInitialState() {
return {
filterText: '',
inStockOnly: false,
};
},
render() {
const products = this.props.products;
return (
<div>
<SearchBar/>
<ProductTable products={products}/>
</div>
);
}
});
|
frontend/src/repo-folder-trash.js | miurahr/seahub | import React from 'react';
import ReactDOM from 'react-dom';
import { navigate } from '@reach/router';
import moment from 'moment';
import { Utils } from './utils/utils';
import { gettext, siteRoot, mediaUrl, logoPath, logoWidth, logoHeight, siteTitle } from './utils/constants';
import { seafileAPI } from './utils/seafile-api';
import Loading from './components/loading';
import ModalPortal from './components/modal-portal';
import toaster from './components/toast';
import CommonToolbar from './components/toolbar/common-toolbar';
import CleanTrash from './components/dialog/clean-trash';
import './css/toolbar.css';
import './css/search.css';
import './css/repo-folder-trash.css';
const {
repoID,
repoFolderName,
path,
enableClean
} = window.app.pageOptions;
class RepoFolderTrash extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
errorMsg: '',
items: [],
scanStat: null,
more: false,
isCleanTrashDialogOpen: false
};
}
componentDidMount() {
this.getItems();
}
getItems = (scanStat) => {
seafileAPI.getRepoFolderTrash(repoID, path, scanStat).then((res) => {
const { data, more, scan_stat } = res.data;
if (!data.length && more) {
this.getItems(scan_stat);
} else {
this.setState({
isLoading: false,
items: this.state.items.concat(data),
more: more,
scanStat: scan_stat
});
}
}).catch((error) => {
this.setState({
isLoading: false,
errorMsg: Utils.getErrorMsg(error, true) // true: show login tip if 403
});
});
}
getMore = () => {
this.setState({
isLoading: true
});
this.getItems(this.state.scanStat);
}
onSearchedClick = (selectedItem) => {
if (selectedItem.is_dir === true) {
let url = siteRoot + 'library/' + selectedItem.repo_id + '/' + selectedItem.repo_name + selectedItem.path;
navigate(url, {repalce: true});
} else {
let url = siteRoot + 'lib/' + selectedItem.repo_id + '/file' + Utils.encodePath(selectedItem.path);
let newWindow = window.open('about:blank');
newWindow.location.href = url;
}
}
goBack = (e) => {
e.preventDefault();
window.history.back();
}
cleanTrash = () => {
this.toggleCleanTrashDialog();
}
toggleCleanTrashDialog = () => {
this.setState({
isCleanTrashDialogOpen: !this.state.isCleanTrashDialogOpen
});
}
refreshTrash = () => {
this.setState({
isLoading: true,
errorMsg: '',
items: [],
scanStat: null,
more: false,
showFolder: false
});
this.getItems();
}
renderFolder = (commitID, baseDir, folderPath) => {
this.setState({
showFolder: true,
commitID: commitID,
baseDir: baseDir,
folderPath: folderPath,
folderItems: [],
isLoading: true
});
seafileAPI.listCommitDir(repoID, commitID, `${baseDir.substr(0, baseDir.length - 1)}${folderPath}`).then((res) => {
this.setState({
isLoading: false,
folderItems: res.data.dirent_list
});
}).catch((error) => {
if (error.response) {
if (error.response.status == 403) {
this.setState({
isLoading: false,
errorMsg: gettext('Permission denied')
});
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Error')
});
}
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Please check the network.')
});
}
});
}
clickRoot = (e) => {
e.preventDefault();
this.refreshTrash();
}
clickFolderPath = (folderPath, e) => {
e.preventDefault();
const { commitID, baseDir } = this.state;
this.renderFolder(commitID, baseDir, folderPath);
}
renderFolderPath = () => {
const pathList = this.state.folderPath.split('/');
return (
<React.Fragment>
<a href="#" onClick={this.clickRoot}>{repoFolderName}</a>
<span> / </span>
{pathList.map((item, index) => {
if (index > 0 && index != pathList.length - 1) {
return (
<React.Fragment key={index}>
<a href="#" onClick={this.clickFolderPath.bind(this, pathList.slice(0, index+1).join('/'))}>{pathList[index]}</a>
<span> / </span>
</React.Fragment>
);
}
}
)}
{pathList[pathList.length - 1]}
</React.Fragment>
);
}
render() {
const { isCleanTrashDialogOpen, showFolder } = this.state;
return (
<React.Fragment>
<div className="h-100 d-flex flex-column">
<div className="top-header d-flex justify-content-between">
<a href={siteRoot}>
<img src={mediaUrl + logoPath} height={logoHeight} width={logoWidth} title={siteTitle} alt="logo" />
</a>
<CommonToolbar onSearchedClick={this.onSearchedClick} />
</div>
<div className="flex-auto container-fluid pt-4 pb-6 o-auto">
<div className="row">
<div className="col-md-10 offset-md-1">
<h2 dangerouslySetInnerHTML={{__html: Utils.generateDialogTitle(gettext('{placeholder} Trash'), repoFolderName)}}></h2>
<a href="#" className="go-back" title={gettext('Back')} onClick={this.goBack}>
<span className="fas fa-chevron-left"></span>
</a>
<div className="d-flex justify-content-between align-items-center op-bar">
<p className="m-0">{gettext('Current path: ')}{showFolder ? this.renderFolderPath() : repoFolderName}</p>
{(path == '/' && enableClean && !showFolder) &&
<button className="btn btn-secondary clean" onClick={this.cleanTrash}>{gettext('Clean')}</button>
}
</div>
<Content
data={this.state}
getMore={this.getMore}
renderFolder={this.renderFolder}
/>
</div>
</div>
</div>
</div>
{isCleanTrashDialogOpen &&
<ModalPortal>
<CleanTrash
repoID={repoID}
refreshTrash={this.refreshTrash}
toggleDialog={this.toggleCleanTrashDialog}
/>
</ModalPortal>
}
</React.Fragment>
);
}
}
class Content extends React.Component {
constructor(props) {
super(props);
this.theadData = [
{width: '5%', text: ''},
{width: '45%', text: gettext('Name')},
{width: '20%', text: gettext('Delete Time')},
{width: '15%', text: gettext('Size')},
{width: '15%', text: ''}
];
}
render() {
const { isLoading, errorMsg, items, more, showFolder, commitID, baseDir, folderPath, folderItems } = this.props.data;
return (
<React.Fragment>
<table className="table-hover">
<thead>
<tr>
{this.theadData.map((item, index) => {
return <th key={index} width={item.width}>{item.text}</th>;
})}
</tr>
</thead>
<tbody>
{showFolder ?
folderItems.map((item, index) => {
return <FolderItem
key={index}
item={item}
commitID={commitID}
baseDir={baseDir}
folderPath={folderPath}
renderFolder={this.props.renderFolder}
/>;
}) :
items.map((item, index) => {
return <Item
key={index}
item={item}
renderFolder={this.props.renderFolder}
/>;
})}
</tbody>
</table>
{isLoading && <Loading />}
{errorMsg && <p className="error mt-6 text-center">{errorMsg}</p>}
{(more && !isLoading && !showFolder) && (
<button className="btn btn-block more mt-6" onClick={this.props.getMore}>{gettext('More')}</button>
)}
</React.Fragment>
);
}
}
class Item extends React.Component {
constructor(props) {
super(props);
this.state = {
restored: false,
isIconShown: false
};
}
handleMouseOver = () => {
this.setState({isIconShown: true});
}
handleMouseOut = () => {
this.setState({isIconShown: false});
}
restoreItem = (e) => {
e.preventDefault();
const item = this.props.item;
const { commit_id, parent_dir, obj_name } = item;
const path = parent_dir + obj_name;
const request = item.is_dir ?
seafileAPI.restoreFolder(repoID, commit_id, path) :
seafileAPI.restoreFile(repoID, commit_id, path);
request.then((res) => {
this.setState({
restored: true
});
toaster.success(gettext('Successfully restored 1 item.'));
}).catch((error) => {
let errorMsg = '';
if (error.response) {
errorMsg = error.response.data.error_msg || gettext('Error');
} else {
errorMsg = gettext('Please check the network.');
}
toaster.danger(errorMsg);
});
}
renderFolder = (e) => {
e.preventDefault();
const item = this.props.item;
this.props.renderFolder(item.commit_id, item.parent_dir, Utils.joinPath('/', item.obj_name));
}
render() {
const item = this.props.item;
const { restored, isIconShown } = this.state;
if (restored) {
return null;
}
return item.is_dir ? (
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFolderIconUrl()} alt={gettext('Directory')} width="24" /></td>
<td><a href="#" onClick={this.renderFolder}>{item.obj_name}</a></td>
<td title={moment(item.deleted_time).format('LLLL')}>{moment(item.deleted_time).format('YYYY-MM-DD')}</td>
<td></td>
<td>
<a href="#" className={isIconShown ? '': 'invisible'} onClick={this.restoreItem}>{gettext('Restore')}</a>
</td>
</tr>
) : (
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFileIconUrl(item.obj_name)} alt={gettext('File')} width="24" /></td>
<td><a href={`${siteRoot}repo/${repoID}/trash/files/?obj_id=${item.obj_id}&commit_id=${item.commit_id}&base=${encodeURIComponent(item.parent_dir)}&p=${encodeURIComponent('/' + item.obj_name)}`} target="_blank">{item.obj_name}</a></td>
<td title={moment(item.deleted_time).format('LLLL')}>{moment(item.deleted_time).format('YYYY-MM-DD')}</td>
<td>{Utils.bytesToSize(item.size)}</td>
<td>
<a href="#" className={isIconShown ? '': 'invisible'} onClick={this.restoreItem}>{gettext('Restore')}</a>
</td>
</tr>
);
}
}
class FolderItem extends React.Component {
constructor(props) {
super(props);
this.state = {
isIconShown: false
};
}
handleMouseOver = () => {
this.setState({isIconShown: true});
}
handleMouseOut = () => {
this.setState({isIconShown: false});
}
renderFolder = (e) => {
e.preventDefault();
const item = this.props.item;
const { commitID, baseDir, folderPath } = this.props;
this.props.renderFolder(commitID, baseDir, Utils.joinPath(folderPath, item.name));
}
render() {
const item = this.props.item;
const { isIconShown } = this.state;
const { commitID, baseDir, folderPath } = this.props;
return item.type == 'dir' ? (
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFolderIconUrl()} alt={gettext('Directory')} width="24" /></td>
<td><a href="#" onClick={this.renderFolder}>{item.name}</a></td>
<td></td>
<td></td>
<td></td>
</tr>
) : (
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFileIconUrl(item.name)} alt={gettext('File')} width="24" /></td>
<td><a href={`${siteRoot}repo/${repoID}/trash/files/?obj_id=${item.obj_id}&commit_id=${commitID}&base=${encodeURIComponent(baseDir)}&p=${encodeURIComponent(Utils.joinPath(folderPath, item.name))}`} target="_blank">{item.name}</a></td>
<td></td>
<td>{Utils.bytesToSize(item.size)}</td>
<td></td>
</tr>
);
}
}
ReactDOM.render(
<RepoFolderTrash />,
document.getElementById('wrapper')
);
|
app/scripts/CloseTrackMenu.js | hms-dbmi/4DN_matrix-viewer | import PropTypes from 'prop-types';
import React from 'react';
import ContextMenuItem from './ContextMenuItem';
import { getSeriesItems } from './SeriesListItems';
// Styles
import '../styles/ContextMenu.module.scss';
const CloseTrackMenu = (props) => (
<div>
{getSeriesItems(props.tracks, null, null, props.onCloseTrack)}
<hr styleName="context-menu-hr" />
<ContextMenuItem onClick={() => props.onCloseTrack(props.tracks[0].uid)}>
{'Close all series'}
</ContextMenuItem>
</div>
);
CloseTrackMenu.propTypes = {
onCloseTrack: PropTypes.func.isRequired,
tracks: PropTypes.array.isRequired,
};
export default CloseTrackMenu;
|
entry_types/scrolled/package/src/contentElements/inlineImage/InlineImage.js | tf/pageflow | import React from 'react';
import {
Image,
Figure,
FitViewport,
useContentElementLifecycle,
useFile,
usePortraitOrientation
} from 'pageflow-scrolled/frontend';
export function InlineImage({configuration}) {
const imageFile = useFile({
collectionName: 'imageFiles', permaId: configuration.id
});
const portraitImageFile = useFile({
collectionName: 'imageFiles', permaId: configuration.portraitId
});
// Only render OrientationAwareInlineImage if a portrait image has
// been selected. This prevents having the component rerender on
// orientation changes even if it does not depend on orientation at
// all.
if (portraitImageFile) {
return (
<OrientationAwareInlineImage landscapeImageFile={imageFile}
portraitImageFile={portraitImageFile}
configuration={configuration} />
);
}
else {
return (
<ImageWithCaption imageFile={imageFile}
configuration={configuration} />
)
}
}
function OrientationAwareInlineImage({landscapeImageFile, portraitImageFile, configuration}) {
const portraitOrientation = usePortraitOrientation();
const imageFile = portraitOrientation && portraitImageFile ?
portraitImageFile : landscapeImageFile;
return (
<ImageWithCaption imageFile={imageFile}
configuration={configuration} />
);
}
function ImageWithCaption({imageFile, configuration}) {
const {shouldLoad} = useContentElementLifecycle();
return (
<FitViewport file={imageFile}
aspectRatio={imageFile ? undefined : 0.75}>
<Figure caption={configuration.caption}>
<FitViewport.Content>
<Image imageFile={imageFile}
load={shouldLoad}
structuredData={true}
variant={configuration.position === 'full' ? 'large' : 'medium'} />
</FitViewport.Content>
</Figure>
</FitViewport>
);
}
|
src/components/antd/calendar/index.js | hyd378008136/olymComponents | import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import FullCalendar from 'rc-calendar/lib/FullCalendar';
import { PREFIX_CLS } from './Constants';
import Header from './Header';
import { getComponentLocale, getLocaleCode } from '../_util/getLocale';
function noop() { return null; }
function zerofixed(v) {
if (v < 10) {
return `0${v}`;
}
return `${v}`;
}
export default class Calendar extends React.Component {
constructor(props, context) {
super(props, context);
this.monthCellRender = (value) => {
const { prefixCls, monthCellRender = noop } = this.props;
return (React.createElement("div", { className: `${prefixCls}-month` },
React.createElement("div", { className: `${prefixCls}-value` }, value.localeData().monthsShort(value)),
React.createElement("div", { className: `${prefixCls}-content` }, monthCellRender(value))));
};
this.dateCellRender = (value) => {
const { prefixCls, dateCellRender = noop } = this.props;
return (React.createElement("div", { className: `${prefixCls}-date` },
React.createElement("div", { className: `${prefixCls}-value` }, zerofixed(value.date())),
React.createElement("div", { className: `${prefixCls}-content` }, dateCellRender(value))));
};
this.setValue = (value, way) => {
if (!('value' in this.props)) {
this.setState({ value });
}
if (way === 'select') {
if (this.props.onSelect) {
this.props.onSelect(value);
}
}
else if (way === 'changePanel') {
this.onPanelChange(value, this.state.mode);
}
};
this.setType = (type) => {
const mode = (type === 'date') ? 'month' : 'year';
if (this.state.mode !== mode) {
this.setState({ mode });
this.onPanelChange(this.state.value, mode);
}
};
this.onHeaderValueChange = (value) => {
this.setValue(value, 'changePanel');
};
this.onHeaderTypeChange = (type) => {
this.setType(type);
};
this.onSelect = (value) => {
this.setValue(value, 'select');
};
// Make sure that moment locale had be set correctly.
getComponentLocale(props, context, 'Calendar', () => require('./locale/zh_CN'));
const value = props.value || props.defaultValue || moment();
if (!moment.isMoment(value)) {
throw new Error('The value/defaultValue of Calendar must be a moment object after `[email protected]`, ' +
'see: https://u.ant.design/calendar-value');
}
this.state = {
value,
mode: props.mode,
};
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.setState({
value: nextProps.value,
});
}
}
onPanelChange(value, mode) {
const { onPanelChange } = this.props;
if (onPanelChange) {
onPanelChange(value, mode);
}
}
render() {
const { state, props, context } = this;
const { value, mode } = state;
const localeCode = getLocaleCode(context);
if (value && localeCode) {
value.locale(localeCode);
}
const { prefixCls, style, className, fullscreen, dateFullCellRender, monthFullCellRender } = props;
const type = (mode === 'year') ? 'month' : 'date';
const locale = getComponentLocale(props, context, 'Calendar', () => require('./locale/zh_CN'));
let cls = className || '';
if (fullscreen) {
cls += (` ${prefixCls}-fullscreen`);
}
const monthCellRender = monthFullCellRender || this.monthCellRender;
const dateCellRender = dateFullCellRender || this.dateCellRender;
return (React.createElement("div", { className: cls, style: style },
React.createElement(Header, { fullscreen: fullscreen, type: type, value: value, locale: locale.lang, prefixCls: prefixCls, onTypeChange: this.onHeaderTypeChange, onValueChange: this.onHeaderValueChange }),
React.createElement(FullCalendar, Object.assign({}, props, { Select: noop, locale: locale.lang, type: type, prefixCls: prefixCls, showHeader: false, value: value, monthCellRender: monthCellRender, dateCellRender: dateCellRender, onSelect: this.onSelect }))));
}
}
Calendar.defaultProps = {
locale: {},
fullscreen: true,
prefixCls: PREFIX_CLS,
mode: 'month',
onSelect: noop,
onPanelChange: noop,
};
Calendar.propTypes = {
monthCellRender: PropTypes.func,
dateCellRender: PropTypes.func,
monthFullCellRender: PropTypes.func,
dateFullCellRender: PropTypes.func,
fullscreen: PropTypes.bool,
locale: PropTypes.object,
prefixCls: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
onPanelChange: PropTypes.func,
value: PropTypes.object,
onSelect: PropTypes.func,
};
Calendar.contextTypes = {
antLocale: PropTypes.object,
};
|
frontend-web-v2/src/components/Header.js | ClubCedille/jardiniot | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import HamburgerMenu from 'react-hamburger-menu';
import Sidebar from 'react-sidebar';
import SidebarContent from './Sidebar';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
isMenuOpen: false
};
}
render() {
return (
<Sidebar
sidebar={<SidebarContent onHamburgerClick={this.onHamburgerClick} parent={this} />}
open={this.state.isMenuOpen}
onSetOpen={this.onHamburgerClick.bind(this)}
styles={{ sidebar: { background: "black" } }}
pullRight={true}
>
<header>
<div className="custom-container">
<Link to="/">
<img className="logo" src="/img/cedille-logo.png" />
</Link>
<div className="title">Jardiniot</div>
<div className="menu">
<HamburgerMenu
isOpen={this.state.isMenuOpen}
menuClicked={this.onHamburgerClick.bind(this)}
width={25}
height={22}
strokeWidth={1}
rotate={1}
color="black"
borderRadius={0}
animationDuration={0.5}
/>
</div>
</div>
</header>
</Sidebar>
);
}
onHamburgerClick(e) {
this.setState({
isMenuOpen: !this.state.isMenuOpen
});
console.log('oui allo');
}
}
export default Header; |
client/components/Form/FormGroup.js | alex-ta/Chat-Server | import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
function setType(key) {
let type = 'text';
if (key.indexOf('email') > -1) {
type = 'email';
}
if (key.indexOf('password') > -1) {
type = 'password';
}
return type;
}
const FormGroup = ({
name,
value,
label,
type,
error,
onChange,
onBlur
}) => {
if (!label) {
label = name;
}
if (!type) {
type = setType(name);
}
return (
<div className={classnames('form-group', {'has-error': error})}>
<label className='control-label'>{name.toUpperCase()}</label>
<input onChange={onChange} onBlur={onBlur} value={value} type={type} name={name} className='form-control'/> {error && <span className='help-block'>{error}</span>}
</div>
);
}
FormGroup.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
label: PropTypes.string,
type: PropTypes.string,
error: PropTypes.string,
onChange: PropTypes.func,
onBlur: PropTypes.func
}
export default FormGroup;
|
js/components/signup/index.js | phamngoclinh/PetOnline_vs2 |
import React, { Component } from 'react';
import { Image, Alert, AsyncStorage } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Content, Text, Button, View, Icon, InputGroup, Input, List, ListItem, CheckBox, Spinner } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import template from '../../themes/style-template';
import styles from './styles';
import GLOBAL from '../../storage/global';
const {
popRoute,
replaceAt,
} = actions;
import feathers from 'feathers/client'
import hooks from 'feathers-hooks';
import socketio from 'feathers-socketio/client'
import authentication from 'feathers-authentication/client';
var io = require('../../packages/socket.io-client/socket.io');
const PLACEHOLDER = '../../../images/avatarThumbnail.png';
const background = require('../../../images/background-signup.jpg');
class Signup extends Component {
static propTypes = {
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
replaceAt: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
username: React.PropTypes.string,
phone: React.PropTypes.number,
password: React.PropTypes.string
}
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
phone: '',
firstName: '',
lastName: '',
password: '',
is_loading: true,
data : null,
registerMessage: ''
};
const options = {transports: ['websocket'], forceNew: true};
const socket = io('192.168.56.1:3030', options);
this.featherAPI = feathers()
.configure(socketio(socket, {timeout: 50000}))
.configure(hooks())
// Use AsyncStorage to store our login toke
.configure(authentication({
storage: AsyncStorage
}));
}
componentDidMount() {
let _this = this;
_this.setState({
is_loading: false
});
}
replaceRoute(route) {
this.props.replaceAt('signup', { key: route }, this.props.navigation.key);
}
_saveUserInfo(user) {
try {
AsyncStorage.multiSet([
[GLOBAL.USER_FULL_NAME, user.userEntity.firstName + user.userEntity.lastName],
[GLOBAL.USER_FIRST_NAME, user.userEntity.firstName],
[GLOBAL.USER_LAST_NAME, user.userEntity.lastName],
[GLOBAL.USER_EMAIL, user.userEntity.email],
[GLOBAL.USER_LOCATION, user.userEntity.nationality]
], (error) => {
console.log("Error: ", error);
});
} catch (error) {
console.log("Error: ", error);
}
}
signup() {
let _this = this;
if(this.state.email == '' || this.state.phone == '' || this.state.password == '' || this.state.firstName == '' || this.state.lastName == '') {
_this.setState({
registerMessage: 'Vui lòng nhập đầy đủ thông tin đăng ký'
})
} else {
_this.setState({
is_loading: true
});
// ...
fetch('http://210.211.118.178/PetsAPI/api/userauthinfos', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"email": this.state.email,
"phone": this.state.phone,
"firstName": this.state.firstName,
"lastName": this.state.lastName,
"passwordHash": this.state.password
})
})
.then((response) => response.json())
.then((responseJson) => {
// Store the results in the state variable results and set loading to
console.log(responseJson);
if(responseJson.errorCode) {
console.log("Code: "+ responseJson.errorMsg);
_this.setState({
is_loading: false,
registerMessage: responseJson.errorMsg
});
} else {
_this.setState({
data: responseJson,
is_loading: false
});
_this.featherAPI.service('users').create({
email: this.state.email,
password: this.state.password
}).then((result) => {
if(result.length > 0) {
console.log("Tạo tài khoản thành công. ", result);
}
}).catch((error) => {
console.log("Lỗi. Không thể tạo tài khoản Chát. ", error);
});
_this._saveUserInfo(responseJson);
Alert.alert(
"Đăng ký thành công",
"Tôi hoàn toàn đồng ý với mọi quy định của ứng dụng",
[
{text: 'Đồng ý', onPress: () => this.replaceRoute('login')},
]
);
}
})
.catch((error) => {
_this.setState({
is_loading: false
});
Alert.alert(
"Lỗi",
"Lỗi phát sinh trong quá trình đăng ký. Vui lòng thử lại!",
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
]
);
console.error(error);
});
}
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
const { props: { name, index, list } } = this;
return (
<Container>
<View style={styles.container}>
<Content>
<Image source={background} style={styles.shadow}>
<View style={styles.top}>
<Image style={styles.logo} source={require('../../../images/logo-5.png')}/>
</View>
<View style={styles.main}>
<InputGroup style={styles.input}>
<Icon name="ios-mail-outline" style={{marginTop: -10, marginRight: 20, color: "#5b71ff"}}/>
<Input placeholder="Email" onChangeText={email => this.setState({ email })} style={{color: '#333333'}}/>
</InputGroup>
<InputGroup style={styles.input}>
<Icon name="ios-call-outline" style={{marginTop: -10, marginRight: 20, color: "#5b71ff"}} />
<Input placeholder="Số điện thoại" keyboardType="numeric"
onChangeText={phone => this.setState({ phone })} />
</InputGroup>
<InputGroup style={styles.input}>
<Icon name="ios-person-outline" style={{marginTop: -10, marginRight: 20, color: "#5b71ff"}} />
<Input placeholder="Tên"
onChangeText={firstName => this.setState({ firstName })} />
</InputGroup>
<InputGroup style={styles.input}>
<Icon name="ios-person-outline" style={{marginTop: -10, marginRight: 20, color: "#5b71ff"}} />
<Input placeholder="Họ"
onChangeText={lastName => this.setState({ lastName })} />
</InputGroup>
<InputGroup style={styles.input}>
<Icon name="ios-unlock-outline" style={{marginTop: -10, marginRight: 20, color: "#5b71ff"}}/>
<Input
placeholder="Mật khẩu"
secureTextEntry
onChangeText={password => this.setState({ password })}
/>
</InputGroup>
{this.state.registerMessage ? <Text style={{ color: template.danger, alignSelf: 'center' }}>{this.state.registerMessage}</Text> : null}
<Button rounded style={{width: 250, height: 50, alignSelf: 'center', marginBottom: 20, marginTop: 30}} onPress={() => this.signup()}>
<Text style={{color:'#FFFFFF'}}>ĐĂNG KÝ</Text>
</Button>
<Button rounded bordered danger style={{width: 250, height: 50, alignSelf: 'center', marginBottom: 30}}
onPress={() => this.replaceRoute('login')}>
QUAY VỀ
</Button>
{this.state.is_loading ? <Spinner color='blue' visible={this.state.is_loading} /> : null}
</View>
</Image>
</Content>
</View>
</Container>
);
}
}
function bindAction(dispatch) {
return {
replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)),
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
});
export default connect(mapStateToProps, bindAction)(Signup);
|
static/src/components/islands/IslandTrees.js | Mathboy19/airhornbot | // @flow
// jscs:disable maximumLineLength
import React from 'react';
type Props = {
paused: boolean
};
export default ({paused}: Props): React.Element => (
<svg className={`island trees ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259px" height="276px" viewBox="0 0 259 276">
<g fill="none" fill-rule="evenodd">
<path fill="#FFE6A7" d="M1.5012 148.2279v57.903l118.413 68.367 136.734-78.942v-57.903l-255.147 10.575z"/>
<path fill="#EDD194" d="M118.8135 143.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 137.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C7E082" d="M1.5012 148.2279v20.403l118.413 68.37 136.734-78.945v-20.403l-255.147 10.575z"/>
<path fill="#B0CC64" d="M119.8134 143.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 140.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#B7D86F" d="M1.5012 148.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/>
<path stroke="#5E4634" strokeWidth="3" d="M119.9151 216.5949l-118.416-68.367 136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906" strokeLinecap="round" strokeLinejoin="round"/>
<g className="leaves">
<path fill="#C3F270" d="M143.9334 29.8173l-.003-.003v-.006c.69-6.153 7.671-9.375 12.801-5.907l.003.003v.006c-.69 6.156-7.671 9.375-12.801 5.907"/>
<path stroke="#5E4634" strokeWidth="3" d="M143.9334 29.8173l-.003-.003v-.006c.69-6.153 7.671-9.375 12.801-5.907l.003.003v.006c-.69 6.156-7.671 9.375-12.801 5.907z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C3F270" d="M164.8071 3.9903v-.006l.003-.003c4.515-4.236 11.916-2.163 13.575 3.804v.003l-.003.006c-4.515 4.236-11.916 2.163-13.575-3.804"/>
<path stroke="#5E4634" strokeWidth="3" d="M164.8071 3.9903v-.006l.003-.003c4.515-4.236 11.916-2.163 13.575 3.804v.003l-.003.006c-4.515 4.236-11.916 2.163-13.575-3.804z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C3F270" d="M230.3529 109.9143l-.006-.003v-.006c-.099-6.192 6.414-10.275 11.943-7.491l.006.003v.006c.099 6.192-6.411 10.275-11.943 7.491"/>
<path stroke="#5E4634" strokeWidth="3" d="M230.3529 109.9143l-.006-.003v-.006c-.099-6.192 6.414-10.275 11.943-7.491l.006.003v.006c.099 6.192-6.411 10.275-11.943 7.491z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#FFE6A7" d="M91.9257 130.8846v26.625c0 2.691 5.289 4.875 11.814 4.875 6.522 0 11.811-2.184 11.811-4.875v-26.625h-23.625z"/>
<path fill="#EDD194" d="M103.8012 130.8846v31.497c6.495-.015 11.751-2.19 11.751-4.872v-26.625h-11.751z"/>
<path stroke="#5E4634" strokeWidth="3" d="M91.9257 130.8846v26.625c0 2.691 5.289 4.875 11.814 4.875 6.522 0 11.811-2.184 11.811-4.875v-26.625h-23.625z" strokeLinecap="round" strokeLinejoin="round"/>
<path stroke="#5E4634" strokeWidth="3" d="M178.3866 112.875zm13.0602 5.5353v3.249M40.1967 137.6514v3.249m75.354 57.9306v3.249m7.5582-9.0015v3.249m0-43.9992v3.249m-38.412-6.4989v3.249m-5.5002.0009v3.249m-51-28.8738v5.523m-4.875-2.3982v5.523m173.3751-16.023v3.75" strokeLinecap="round" strokeLinejoin="round"/>
<g className="stretch">
<path fill="#C3F270" d="M109.3728 25.3635l36.129 98.73c1.719 4.695.099 10.05-4.092 12.777-6.051 3.939-17.328 8.265-37.671 8.265s-31.62-4.326-37.671-8.265c-4.191-2.727-5.814-8.082-4.095-12.777l36.132-98.73c1.92-5.25 9.348-5.25 11.268 0"/>
<path fill="#B7D86F" d="M145.5027 124.0935l-36.129-98.73c-1.923-5.25-9.348-5.25-11.271 0l-2.88 7.875 31.239 85.365c1.719 4.695.099 10.05-4.095 12.777-6.051 3.939-17.328 8.265-37.671 8.265-5.913 0-11.043-.375-15.519-.99 6.552 3.354 17.274 6.48 34.56 6.48 20.343 0 31.62-4.326 37.671-8.265 4.194-2.727 5.814-8.082 4.095-12.777"/>
<path stroke="#5E4634" strokeWidth="3" d="M109.3728 25.3635l36.129 98.73c1.719 4.695.099 10.05-4.092 12.777-6.051 3.939-17.328 8.265-37.671 8.265s-31.62-4.326-37.671-8.265c-4.191-2.727-5.814-8.082-4.095-12.777l36.132-98.73c1.92-5.25 9.348-5.25 11.268 0z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#FFE6A7" d="M172.7298 96.9837v29.784c0 1.29 2.532 2.334 5.658 2.334 3.123 0 5.655-1.044 5.655-2.334v-29.784h-11.313z"/>
<path fill="#EDD194" d="M178.8012 96.9837v32.103c2.928-.09 5.241-1.089 5.241-2.319v-29.784h-5.241z"/>
<path stroke="#5E4634" strokeWidth="3" d="M172.7298 96.9837v29.784c0 1.29 2.532 2.334 5.658 2.334 3.123 0 5.655-1.044 5.655-2.334v-29.784h-11.313z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="stretch">
<path fill="#C3F270" d="M178.3866 117.543c-14.232 0-25.875-11.643-25.875-25.875v-9.327c0-14.232 11.643-25.875 25.875-25.875s25.875 11.643 25.875 25.875v9.327c0 14.232-11.643 25.875-25.875 25.875"/>
<path fill="#B7D86F" d="M179.9904 56.5479c5.655 4.755 9.27 11.871 9.27 19.794v9.327c0 14.232-11.643 25.875-25.875 25.875-.54 0-1.068-.048-1.602-.081 4.503 3.786 10.296 6.081 16.602 6.081 14.232 0 25.875-11.643 25.875-25.875v-9.327c0-13.692-10.782-24.954-24.27-25.794"/>
<path stroke="#5E4634" strokeWidth="3" d="M178.3866 117.543c-14.232 0-25.875-11.643-25.875-25.875v-9.327c0-14.232 11.643-25.875 25.875-25.875s25.875 11.643 25.875 25.875v9.327c0 14.232-11.643 25.875-25.875 25.875z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#EBEBEB" d="M157.9878 164.9463h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M157.9878 164.9463h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="lines">
<path stroke="#5E4634" strokeWidth="3" d="M132.5016 45.2829c7.356 2.253 15.573 1.536 22.428-1.953s12.267-9.714 14.775-16.983m-66.4152 13.3812c-5.976-4.326-13.56-5.736-20.913-6.324-8.142-.651-16.479-.417-24.258 2.064-7.782 2.481-15.003 7.404-19.056 14.493-4.056 7.089-4.488 16.443-.036 23.289 5.172 7.95 15.288 10.953 24.678 12.303" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="6 12"/>
</g>
</g>
</svg>
);
|
app/containers/Overview.js | 7kfpun/AudienceNetworkReactNative | import React, { Component } from 'react';
import {
BackHandler,
FlatList,
Platform,
RefreshControl,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import moment from 'moment-timezone';
import { AccessToken } from 'react-native-fbsdk';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { IndicatorViewPager, PagerDotIndicator } from 'rn-viewpager';
import { NativeAdsManager } from 'react-native-fbads';
import Icon from 'react-native-vector-icons/MaterialIcons';
import * as dateRangeActions from '../actions/dateRange';
import * as insightActions from '../actions/insights';
import AdBanner from '../components/fbadbanner';
import FbAds from '../components/fbads';
import InsightItem from '../components/InsightBoxItem';
import LineChart from '../components/LineChart';
import OverviewSummary from '../components/OverviewSummary';
import RangePicker from '../components/RangePicker';
import VictoryChart from '../components/VictoryChart';
import tracker from '../utils/tracker';
import { config } from '../config';
const adsManager = new NativeAdsManager(config.fbads[Platform.OS].native);
moment.tz.setDefault('America/Los_Angeles');
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ECEFF1',
},
headerNav: {
flex: 1,
justifyContent: 'center',
padding: 6,
},
headerLeftText: {
fontSize: 16,
color: '#0076FF',
},
body: {
paddingVertical: 6,
},
navigatorBar: {
borderBottomWidth: StyleSheet.hairlineWidth * 2,
borderBottomColor: '#E0E0E0',
},
row: {
padding: 15,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'white',
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: '#E0E0E0',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#E0E0E0',
},
datePicker: {
backgroundColor: 'white',
},
overviewBlock: {
height: 80,
padding: 15,
marginBottom: 5,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'stretch',
backgroundColor: 'white',
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: '#E0E0E0',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#E0E0E0',
},
overviewCell: {
justifyContent: 'space-between',
alignItems: 'center',
},
chartBlock: {
paddingHorizontal: 15,
paddingVertical: 10,
marginTop: 5,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: '#E0E0E0',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#E0E0E0',
},
insightsBlock: {
marginTop: 5,
width: 960,
},
text: {
fontSize: 15,
lineHeight: 24,
},
sumTitleCellText: {
fontSize: 12,
},
sumCellText: {
fontSize: 12,
fontWeight: '200',
},
cellText: {
fontSize: 13,
},
});
class OverviewView extends Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.appName} (${navigation.state.params.appId})`,
headerLeft: <TouchableOpacity
style={styles.headerNav}
underlayColor="white"
onPress={() => {
navigation.goBack();
}}
>
{Platform.OS === 'ios' ? <Text style={styles.headerLeftText}>{'Back'}</Text> : <Icon style={styles.headerLeftIcon} name="arrow-back" size={30} color="#0076FF" />}
</TouchableOpacity>,
headerStyle: {
backgroundColor: 'white',
},
headerTitleStyle: {
fontSize: 12,
},
});
state = {
refreshing: false,
isChanged: false,
};
componentDidMount() {
const { appId } = this.props.navigation.state.params;
const { startDate, endDate, rangeType, isCompareTo } = this.props;
this.checkPermissions();
this.onRequest(appId, startDate, endDate, rangeType, isCompareTo);
this.sub = BackHandler.addEventListener('backPress', () => this.props.navigation.goBack());
}
componentWillReceiveProps(nextProps) {
const { appId } = this.props.navigation.state.params;
if (nextProps.startDate !== this.props.startDate || nextProps.endDate !== this.props.endDate) {
this.onRequest(appId, nextProps.startDate, nextProps.endDate, nextProps.rangeType, nextProps.isCompareTo);
}
}
componentWillUnmount() {
this.sub.remove();
}
onRequest(appId, startDate, endDate, rangeType, isCompareTo) {
if (startDate && endDate) {
const { fetchRequests, fetchFilledRequests, fetchImpressions, fetchClicks, fetchRevenue } = this.props;
fetchRequests(appId, startDate, endDate, rangeType, isCompareTo);
fetchFilledRequests(appId, startDate, endDate, rangeType, isCompareTo);
fetchImpressions(appId, startDate, endDate, rangeType, isCompareTo);
fetchClicks(appId, startDate, endDate, rangeType, isCompareTo);
fetchRevenue(appId, startDate, endDate, rangeType, isCompareTo);
}
}
checkPermissions() {
const { dispatch, navigate } = this.props.navigation;
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log('getCurrentAccessToken', data);
if (!data || !data.permissions) {
dispatch({ type: 'Logout' });
navigate('Login');
}
// if (data && data.permissions && data.permissions.indexOf('read_audience_network_insights') === -1) {
// LoginManager.logInWithReadPermissions(['read_audience_network_insights']).then(
// (result) => {
// if (result.isCancelled) {
// alert('You cannot use this app without read_audience_network_insights permissions.');
// tracker.logEvent('cancel-read-audience-network-insights-permission', { category: 'auth-event', view: 'overview' });
// } else {
// this.onRequest(appId, nextProps.startDate, nextProps.endDate, nextProps.rangeType, nextProps.isCompareTo);
// tracker.logEvent('give-read-audience-network-insights-permission', { category: 'auth-event', view: 'overview' });
// }
// },
// (error) => {
// alert(`Login fail with error: ${error}`);
// tracker.logEvent('login-failed', { category: 'auth-event', view: 'overview' });
// },
// );
// }
},
);
}
renderInsights() {
const { requests, impressions, clicks, revenue, all } = this.props;
const { startDate, endDate } = this.props;
return (
<View>
<OverviewSummary />
<FbAds adsManager={adsManager} />
{startDate && endDate && moment(startDate).format('L') !== moment(endDate).format('L') && <IndicatorViewPager
style={{ height: 280, marginBottom: 5 }}
indicator={<PagerDotIndicator selectedDotStyle={{ backgroundColor: '#F4F4F4' }} pageCount={4} />}
>
<View style={styles.chartBlock}>
{Platform.OS === 'ios' ? <VictoryChart data={requests} /> : <LineChart data={requests} />}
<Text style={styles.cellText}>{'Requests'}</Text>
</View>
<View style={styles.chartBlock}>
{Platform.OS === 'ios' ? <VictoryChart data={impressions} /> : <LineChart data={impressions} />}
<Text style={styles.cellText}>{'Impressions'}</Text>
</View>
<View style={styles.chartBlock}>
{Platform.OS === 'ios' ? <VictoryChart data={clicks} /> : <LineChart data={clicks} />}
<Text style={styles.cellText}>{'Clicks'}</Text>
</View>
<View style={styles.chartBlock}>
{Platform.OS === 'ios' ? <VictoryChart data={revenue} /> : <LineChart data={revenue} />}
<Text style={styles.cellText}>{'Estimated Revenue'}</Text>
</View>
</IndicatorViewPager>}
{/* <ScrollView contentContainerStyle={styles.insightsBlock} horizontal showsHorizontalScrollIndicator={false}>
<FlatList
style={{ marginBottom: 10 }}
enableEmptySections={true}
scrollEnabled={false}
data={all}
ListHeaderComponent={() => <InsightHeader />}
renderItem={({ item }) => <InsightItem item={item} />}
/>
</ScrollView> */}
<ScrollView contentContainerStyle={{ flex: 1, marginTop: 6 }}>
<FlatList
style={{ marginBottom: 10 }}
enableEmptySections={true}
scrollEnabled={false}
data={all}
renderItem={({ item }) => <InsightItem item={item} />}
/>
</ScrollView>
</View>
);
}
render() {
const { startDate, endDate, rangeType, isCompareTo, isLoading, all, navigation } = this.props;
const { appId } = this.props.navigation.state.params;
if (!isLoading && all.length === 0) {
return (<View style={styles.container}>
<RangePicker navigation={navigation} />
<View style={{ padding: 30 }}>
<Text style={[styles.text, { textAlign: 'center', fontSize: 12 }]}>No performance data available. Please check if the ads are running and get some requests.</Text>
</View>
</View>);
}
return (
<View style={styles.container}>
<RangePicker navigation={navigation} />
<ScrollView
style={styles.body}
refreshControl={
<RefreshControl
refreshing={isLoading}
onRefresh={() => {
this.onRequest(appId, startDate, endDate, rangeType, isCompareTo);
tracker.logEvent('refresh-overview', { category: 'user-event', view: 'overview' });
}}
/>
}
>
{this.renderInsights()}
</ScrollView>
<AdBanner withPopUp={false} />
</View>
);
}
}
OverviewView.defaultProps = {
startDate: null,
endDate: null,
rangeType: 'days',
isCompareTo: false,
};
OverviewView.propTypes = {
navigation: React.PropTypes.object.isRequired,
startDate: React.PropTypes.object,
endDate: React.PropTypes.object,
rangeType: React.PropTypes.string,
isCompareTo: React.PropTypes.bool,
isLoading: React.PropTypes.bool.isRequired,
all: React.PropTypes.array.isRequired,
requests: React.PropTypes.arrayOf(React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
time: React.PropTypes.string.isRequired,
}).isRequired).isRequired,
// filledRequests: React.PropTypes.arrayOf(React.PropTypes.shape({
// value: React.PropTypes.string.isRequired,
// time: React.PropTypes.string.isRequired,
// }).isRequired).isRequired,
impressions: React.PropTypes.arrayOf(React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
time: React.PropTypes.string.isRequired,
}).isRequired).isRequired,
clicks: React.PropTypes.arrayOf(React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
time: React.PropTypes.string.isRequired,
}).isRequired).isRequired,
revenue: React.PropTypes.arrayOf(React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
time: React.PropTypes.string.isRequired,
}).isRequired).isRequired,
fetchRequests: React.PropTypes.func.isRequired,
fetchFilledRequests: React.PropTypes.func.isRequired,
fetchImpressions: React.PropTypes.func.isRequired,
fetchClicks: React.PropTypes.func.isRequired,
fetchRevenue: React.PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
startDate: state.dateRange.startDate,
endDate: state.dateRange.endDate,
rangeType: state.dateRange.rangeType,
isCompareTo: state.dateRange.isCompareTo,
isLoading: state.insights.isLoading,
all: state.insights.all,
requests: state.insights.requests,
filledRequests: state.insights.filledRequests,
impressions: state.insights.impressions,
clicks: state.insights.clicks,
revenue: state.insights.revenue,
requestsSum: state.insights.requestsSum,
filledRequestsSum: state.insights.filledRequestsSum,
impressionsSum: state.insights.impressionsSum,
clicksSum: state.insights.clicksSum,
revenueSum: state.insights.revenueSum,
});
export default connect(
mapStateToProps,
dispatch => bindActionCreators({ ...dateRangeActions, ...insightActions }, dispatch),
)(OverviewView);
|
src/components/panes.js | jorgerobles/LaserWeb4 | /**
* Panes module.
* - Handle panes.
* @module
*/
// React/Redux
import React from 'react'
import { connect } from 'react-redux'
/**
* Pane component.
*
* @extends module:react~React~Component
* @param {Object} props Component properties.
*/
class Pane extends React.Component {
/**
* @type {Object}
* @member module:components/pane~Pane.prototype#props
* @property {String} key Pane key.
* @property {String} title Pane title.
* @property {String} icon Pane icon name (font-awesome).
* @property {Boolean} active True if active button.
* @property {module:react~React~Component|module:react~React~Component[]} children Component children.
*/
/**
* Render the component.
* @return {String}
*/
render() {
return (
<div className={ "pane" + (this.props.active ? " active" : "") + " pane-"+this.props.id}>
<div className="pane-content">{ this.props.children }</div>
</div>
)
}
}
/**
* Panes component.
* - Handle panes.
*
* @extends module:react~React~Component
* @param {Object} props Component properties.
*/
class Panes extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps.selected !== this.props.selected || nextProps.style.width !== this.props.style.width;
}
render() {
return (
<div className={"panes full-height"} style={this.props.style}>
{
this.props.children
.filter(item => item.props.id === this.props.selected)
.map(item => (
<Pane
{...item.props}
key={item.props.id}
id={item.props.id}
active={item.props.id === this.props.selected}
>
{item}
</Pane>))
}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
selected: state.panes.selected,
}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
// Exports
export { Panes, Pane }
export default connect(mapStateToProps, mapDispatchToProps)(Panes)
|
webpack-test2/src/components/Main.js | cooliean/react-study | require('normalize.css/normalize.css');
require('styles/App.css');
import React from 'react';
let yeomanImage = require('../images/yeoman.png');
class AppComponent extends React.Component {
render() {
return (
<div className="index">
<img src={yeomanImage} alt="Yeoman Generator" />
<div className="notice">111Please edit <code>src/components/Main111122.js</code> to get started!</div>
</div>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
static/src/containers/Dashboard.js | detailyang/cas-server | /**
* @Author: BingWu Yang <detailyang>
* @Date: 2016-04-20T23:43:35+08:00
* @Email: [email protected]
* @Last modified by: detailyang
* @Last modified time: 2016-04-21T00:34:05+08:00
* @License: The MIT License (MIT)
*/
import React from 'react';
import { Nav, Header } from '../components';
import { connect } from 'react-redux';
import { logout } from '../actions';
function Dashboard({ children, auth, location, logout }) {
return (
<div>
<Header handleLogout={logout} />
<Nav isAdmin={ auth.isAdmin } currentPath={ location.pathname } />
<div className="dashboard-container">{children}</div>
</div>
);
}
export default connect(
({ auth }) => ({ auth }),
{ logout }
)(Dashboard);
|
webpack/components/TemplateSyncResult/components/SyncedTemplate/InfoItem.js | theforeman/foreman_templates | import React from 'react';
import { ListView, OverlayTrigger, Tooltip } from 'patternfly-react';
import PropTypes from 'prop-types';
const InfoItem = ({ itemId, children, tooltipText }) => {
const overlay = (
<OverlayTrigger
overlay={tooltipText ? <Tooltip id={itemId}>{tooltipText}</Tooltip> : ''}
placement="top"
trigger={['hover', 'focus']}
rootClose={false}
>
{children}
</OverlayTrigger>
);
return (
<ListView.InfoItem key={itemId} className="additional-info-wide">
{tooltipText ? overlay : children}
</ListView.InfoItem>
);
};
InfoItem.propTypes = {
itemId: PropTypes.string.isRequired,
children: PropTypes.node,
tooltipText: PropTypes.string,
};
InfoItem.defaultProps = {
tooltipText: '',
children: undefined,
};
export default InfoItem;
|
assets/javascripts/kitten/components/information/tag/stories.js | KissKissBankBank/kitten | import React from 'react'
import { Tag } from './index'
import { DocsPage } from 'storybook/docs-page'
import { FlashIconNext } from 'kitten'
export default {
title: 'Information/Tag',
component: Tag,
parameters: {
docs: { page: () => <DocsPage filepath={__filename} importString="Tag" /> },
},
decorators: [
story => <div className="story-Container story-Grid">{story()}</div>,
],
args: {
type: 'info',
size: 'medium',
variant: 'light',
children: '5 contributors',
},
argTypes: {
type: {
name: 'type',
options: ['info', 'warning', 'success', 'error', 'disabled'],
control: 'radio',
},
size: {
name: 'size',
options: ['small', 'medium'],
control: 'radio',
},
variant: {
name: 'variant',
options: ['light', 'status', 'dark'],
control: 'radio',
},
},
}
export const Default = args => {
return <Tag {...args} />
}
export const WithIcon = args => {
return (
<Tag {...args} flex>
<FlashIconNext width="10" />
Abonnement
</Tag>
)
}
export const AllVariants = () => {
return (
<>
<div>
<Tag variant="status" type="info" size="medium">
Abonnement
</Tag>
</div>
<div>
<Tag variant="light" type="info" size="medium">
Abonnement
</Tag>
</div>
<div>
<Tag variant="dark" type="info" size="medium">
Abonnement
</Tag>
</div>
<div>
<Tag variant="status" type="success" size="medium">
Validée
</Tag>
</div>
<div>
<Tag variant="light" type="success" size="medium">
Validée
</Tag>
</div>
<div>
<Tag variant="dark" type="success" size="medium">
Validée
</Tag>
</div>
<div>
<Tag variant="status" type="error" size="medium">
Échoué
</Tag>
</div>
<div>
<Tag variant="light" type="error" size="medium">
Échoué
</Tag>
</div>
<div>
<Tag variant="dark" type="error" size="medium">
Échoué
</Tag>
</div>
<div>
<Tag variant="status" type="warning" size="medium">
En pause
</Tag>
</div>
<div>
<Tag variant="light" type="warning" size="medium">
En pause
</Tag>
</div>
<div>
<Tag variant="dark" type="warning" size="medium">
En pause
</Tag>
</div>
<div>
<Tag variant="status" type="disabled" size="medium">
Don libre
</Tag>
</div>
<div>
<Tag variant="light" type="disabled" size="medium">
Don libre
</Tag>
</div>
<div>
<Tag variant="dark" type="disabled" size="medium">
Don libre
</Tag>
</div>
<div>
<Tag variant="status" type="info" size="small">
Abonnement
</Tag>
</div>
<div>
<Tag variant="light" type="info" size="small">
Abonnement
</Tag>
</div>
<div>
<Tag variant="dark" type="info" size="small">
Abonnement
</Tag>
</div>
<div>
<Tag variant="status" type="success" size="small">
Validée
</Tag>
</div>
<div>
<Tag variant="light" type="success" size="small">
Validée
</Tag>
</div>
<div>
<Tag variant="dark" type="success" size="small">
Validée
</Tag>
</div>
<div>
<Tag variant="status" type="error" size="small">
Échoué
</Tag>
</div>
<div>
<Tag variant="light" type="error" size="small">
Échoué
</Tag>
</div>
<div>
<Tag variant="dark" type="error" size="small">
Échoué
</Tag>
</div>
<div>
<Tag variant="status" type="warning" size="small">
En pause
</Tag>
</div>
<div>
<Tag variant="light" type="warning" size="small">
En pause
</Tag>
</div>
<div>
<Tag variant="dark" type="warning" size="small">
En pause
</Tag>
</div>
<div>
<Tag variant="status" type="disabled" size="small">
Don libre
</Tag>
</div>
<div>
<Tag variant="light" type="disabled" size="small">
Don libre
</Tag>
</div>
<div>
<Tag variant="dark" type="disabled" size="small">
Don libre
</Tag>
</div>
</>
)
}
|
src/components/screens/Network.js | whphhg/vcash-ui | import React from 'react'
import { translate } from 'react-i18next'
import { Route } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
/** Components */
import DailyRewardChart from '../charts/DailyRewardChart.js'
import DifficultyChart from '../charts/DifficultyChart.js'
import Footer from '../Footer.js'
import HashRateChart from '../charts/HashRateChart.js'
import Header from '../Header.js'
import IncentiveInfo from '../wallet/IncentiveInfo.js'
import NetworkInfo from '../wallet/NetworkInfo.js'
import NetworkMenu from '../menus/NetworkMenu.js'
import Peers from '../wallet/Peers.js'
import RecentBlockList from '../lists/RecentBlockList.js'
import RewardSpreadChart from '../charts/RewardSpreadChart.js'
@translate(['common'])
@inject('connections')
@observer
class Network extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.connections = props.connections
}
render() {
const key = '/' + this.connections.viewingId + '/network/'
return (
<div id="AppListContent">
<div className="list grid-tb">
<div>
<NetworkMenu />
</div>
<div>
<IncentiveInfo />
</div>
</div>
<div id="AppHeaderFooter">
<Header />
<Route
path={key + 'info'}
render={() => (
<div className="grid-tb">
<div id="InfoBlocks">
<NetworkInfo />
<RecentBlockList />
</div>
<Peers />
</div>
)}
/>
<Route
path={key + 'rewards'}
render={() => (
<div className="grid-tb">
<div style={{ minWidth: '100%' }}>
<div className="flex" style={{ margin: '0 0 10px 0' }}>
<i className="material-icons md-16">timeline</i>
<p>{this.t('rewardSpread')}</p>
</div>
<RewardSpreadChart />
</div>
<div style={{ minWidth: '100%' }}>
<div className="flex" style={{ margin: '0 0 10px 0' }}>
<i className="material-icons md-16">view_week</i>
<p>{this.t('rewardsPerDay')}</p>
</div>
<DailyRewardChart />
</div>
</div>
)}
/>
<Route
path={key + 'rates'}
render={() => (
<div className="grid-tb">
<div style={{ minWidth: '100%' }}>
<div className="flex" style={{ margin: '0 0 10px 0' }}>
<i className="material-icons md-16">trending_up</i>
<p>{this.t('difficulties')}</p>
</div>
<DifficultyChart />
</div>
<div style={{ minWidth: '100%' }}>
<div className="flex" style={{ margin: '0 0 10px 0' }}>
<i className="material-icons md-16">network_check</i>
<p>{this.t('hashRate')}</p>
</div>
<HashRateChart />
</div>
</div>
)}
/>
<Footer />
</div>
</div>
)
}
}
export default Network
|
ReactJS/app/components/CommentList.js | aitch0083/extjs-and-more | import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {Comment} from 'app/components/Comment';
import _ from 'underscore';
export class CommentList extends React.Component{
constructor(props){
super(props);
this._onEditClickHandler = this._onEditClickHandler.bind(this);
this._onRemoveClickHandler = this._onRemoveClickHandler.bind(this);
}
render(){
var nodes = this.props.data.map( (record, idx) => {
return <Comment author={record.author}
content={record.content}
date={record.date}
key={idx}
eleIdx={idx}
onEditClickHandler={this._onEditClickHandler}
onRemoveClickHandler={this._onRemoveClickHandler}>
</Comment>
});
return (<div className="ui comments">{nodes}</div>);
}
_onEditClickHandler(idx, evt){
evt.preventDefault();
if(!_.isUndefined(this.props.editComment)){
this.props.editComment(idx);
}
}
_onRemoveClickHandler(idx, evt){
evt.preventDefault();
if(!_.isUndefined(this.props.removeComment)){
this.props.removeComment(idx);
}
}
}
CommentList.propTypes = {
editComment: React.PropTypes.func.isRequired,
removeComment: React.PropTypes.func.isRequired
}; |
docs/examples/like-button/src/scripts/main.js | alarner/au-flux | // import React from 'react';
// import ReactDOM from 'react-dom';
// import Button from './components/Button';
import { globals } from 'au-flux';
// import stores from './stores';
console.log(globals);
// globals.set('stores', stores);
{/*ReactDOM.render(<Button />, document.getElementById('main'));*/}
|
src/server.js | PtitNoony/abretonworkshop | /* eslint no-console: "off"*/
/* global __dirname */
import path from 'path';
import { Server } from 'http';
import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter as Router } from 'react-router-dom';
import { App } from './components/App';
import cors from 'cors';
var compression = require('compression');
var data = require('./server/data.js');
const app = new Express();
const server = new Server(app);
// use ejs templates
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(compression());
app.use(cors());
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
app.get('/api/bowling/games', (req, res) => {
data.bowlingGames(result => {
res.json(result);
});
});
app.get('/api/bowling/players', (req, res) => {
data.bowlingPlayers(result => {
res.json(result);
});
});
app.get('/api/bowling/player/:playerID', (req, res) => {
data.bowlingPlayer(req.params.playerID, result => {
res.json(result);
});
});
app.get('/api/bowling/playerStats/:playerID', (req, res) => {
data.bowlingPlayerStats(req.params.playerID, result => {
res.json(result);
});
});
app.get('/api/bowling/playerData/:playerID', (req, res) => {
data.bowlingPlayerFullData(req.params.playerID, result => {
res.json(result);
});
});
//
app.get('/api/foe/era', (req, res) => {
data.foeEra(result => {
res.json(result);
});
});
//
app.get('/api/foe/buildingTypes', (req, res) => {
data.foeBuildingTypes(result => {
res.json(result);
});
});
//
app.get('/api/foe/buildings', (req, res) => {
data.foeBuildings(result => {
res.json(result);
});
});
//
app.get('/api/research/publications', (req, res) => {
data.publications(result => {
res.json(result);
});
});
// universal routing and rendering
app.get('*', (req, res) => {
let markup = '';
let status = 200;
if (process.env.UNIVERSAL) {
const context = {};
markup = renderToString(
<Router location={req.url} context={context}>
<App />
</Router>,
);
// context.url will contain the URL to redirect to if a <Redirect> was used
if (context.url) {
return res.redirect(302, context.url);
}
if (context.is404) {
status = 404;
}
}
return res.status(status).render('index', { markup });
});
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.info(
`
Server running on http://localhost:${port} [${env}]
Universal rendering: ${process.env.UNIVERSAL ? 'enabled' : 'disabled'}
`);
});
|
src/parser/druid/feral/modules/azeritetraits/IronJaws.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { calculateAzeriteEffects } from 'common/stats';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateBonusAzeriteDamage from 'parser/core/calculateBonusAzeriteDamage';
import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox';
import ItemDamageDone from 'interface/ItemDamageDone';
import Abilities from '../Abilities';
const debug = false;
const BUFFER_TIME = 100;
const PROC_CHANCE_PER_COMBO = 0.08;
/**
* Iron Jaws
* Ferocious Bite has a 8% chance per combo point to increase the damage of your next Maim by X per combo point.
*
* Example log: /report/7ZjPwhdHXFb8r6ky/6-Normal+Grong+the+Revenant+-+Kill+(3:30)/17-Ashurabisha
*
* Using Ferocious Bite has a chance to give the player the Iron Jaws buff, which lasts 30 seconds or until they next use Maim.
* When Maim is used with the buff active the removebuff event appears before the cast event for Maim in the log.
*/
class IronJaws extends Analyzer {
static dependencies = {
abilities: Abilities,
};
traitBonus = 0; // trait bonus damage is per combo point on
coefficient = 0; // per combo point spent on Maim
damage = 0;
// updated when Maim is cast, used when Maim damage is detected
attackPower = 0;
comboPoints = 0;
ironJawsProcCount = 0;
expectedProcCount = 0;
unbuffedMaimCount = 0;
buffedMaimCount = 0;
missingComboMaimCount = 0;
constructor(...args) {
super(...args);
if (!this.selectedCombatant.hasTrait(SPELLS.IRON_JAWS_TRAIT.id)) {
this.active = false;
return;
}
this.traitBonus = this.selectedCombatant.traitsBySpellId[SPELLS.IRON_JAWS_TRAIT.id]
.reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.IRON_JAWS_TRAIT.id, rank)[0], 0);
this.coefficient = this.abilities.getAbility(SPELLS.MAIM.id).primaryCoefficient;
debug && this.log(`Iron Jaws bonus: ${this.traitBonus} from ${this.selectedCombatant.traitsBySpellId[SPELLS.IRON_JAWS_TRAIT.id].length} traits.`);
debug && this.log(`Maim's coefficient: ${this.coefficient}`);
this.addEventListener(Events.applybuff.to(SELECTED_PLAYER).spell(SPELLS.IRON_JAWS_BUFF), this._gainIronJaws);
this.addEventListener(Events.refreshbuff.to(SELECTED_PLAYER).spell(SPELLS.IRON_JAWS_BUFF), this._gainIronJaws);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.MAIM), this._castMaim);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.MAIM), this._damageMaim);
// there is also a damage event in the log from SPELLS.MAIM_DEBUFF but that's the stun attempting to be applied and never causes damage.
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FEROCIOUS_BITE), this._castBite);
}
getComboPoints(event) {
const resource = event.classResources.find(item => item.type === RESOURCE_TYPES.COMBO_POINTS.id);
if (!resource) {
debug && this.log('Unable to find combo points.');
return null;
}
return resource.amount;
}
_gainIronJaws(event) {
this.ironJawsProcCount += 1;
}
_castMaim(event) {
if (!this.selectedCombatant.hasBuff(SPELLS.IRON_JAWS_BUFF.id, null, BUFFER_TIME)) {
this.unbuffedMaimCount += 1;
debug && this.log('Unbuffed Maim');
return;
}
this.buffedMaimCount += 1;
debug && this.log('Buffed Maim');
this.comboPoints = this.getComboPoints(event);
debug && this.log(`Maim used with ${this.comboPoints} combo points.`);
if (this.comboPoints && this.comboPoints < 5) {
this.missingComboMaimCount += 1;
}
this.attackPower = event.attackPower;
}
_damageMaim(event) {
if (!this.comboPoints || !this.attackPower) {
debug && this.warn(`Unable to find attackPower (${this.attackPower}) or combo points (${this.comboPoints}) of Maim cast.`);
return;
}
const [ traitDamageContribution ] = calculateBonusAzeriteDamage(event, [this.traitBonus * this.comboPoints], this.attackPower, this.coefficient * this.comboPoints);
this.damage += traitDamageContribution;
debug && this.log(`Iron Jaws contributed ${traitDamageContribution.toFixed(0)} bonus damage of Maim's total ${event.amount + event.absorbed}`);
}
_castBite(event) {
// whenever the player casts Ferocious Bite there's a chance it'll activate Iron Jaws. Keep track of that chance and see how it matches up with reality.
const comboPoints = this.getComboPoints(event);
if (!comboPoints) return;
this.expectedProcCount += PROC_CHANCE_PER_COMBO * comboPoints;
}
statistic() {
return (
<TraitStatisticBox
position={STATISTIC_ORDER.OPTIONAL()}
trait={SPELLS.IRON_JAWS_TRAIT.id}
value={(
<ItemDamageDone amount={this.damage} />
)}
tooltip={(
<>
Increased your Maim damage by a total of <b>{formatNumber(this.damage)}</b>.<br />
From your use of Ferocious Bite you would expect on average to get <b>{this.expectedProcCount.toFixed(1)}</b> Iron Jaws procs. You actually got <b>{this.ironJawsProcCount}</b>.<br />
Of those <b>{this.ironJawsProcCount}</b> procs you made use of <b>{this.buffedMaimCount}</b> to buff Maim's damage.<br />
You cast Maim <b>{this.unbuffedMaimCount}</b> time{this.unbuffedMaimCount === 1 ? '' : 's'} without the Iron Jaws buff.
</>
)}
/>
);
}
get traitCountThreshold() {
return { // 1 trait is basically worthless, 2+ is fine
actual: this.selectedCombatant.traitsBySpellId[SPELLS.IRON_JAWS_TRAIT.id].length,
isLessThan: {
minor: 2,
average: 2,
major: 2,
},
style: 'number',
};
}
get wastedProcsThreshold() {
return { // percentage of procs that were not used
actual: (this.ironJawsProcCount - this.buffedMaimCount) / this.ironJawsProcCount,
isGreaterThan: {
minor: 0.10,
average: 0.15,
major: 0.25,
},
style: 'percentage',
};
}
get unbuffedMaimThreshold() {
return { // unbuffed Maims per minute
actual: this.unbuffedMaimCount / (this.owner.fightDuration / (60000)),
isGreaterThan: {
minor: 0.3,
average: 0.9,
major: 1.2,
},
style: 'number',
};
}
get missingComboMaimThreshold() {
return { // percentage of Maim casts made without full combo points
actual: this.missingComboMaimCount / (this.unbuffedMaimCount + this.buffedMaimCount),
isGreaterThan: {
minor: 0.0,
average: 0.0,
major: 0.2,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.traitCountThreshold).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
Using just 1 <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> Azerite trait is usually a waste. The reduction in your damage output from using <SpellLink id={SPELLS.MAIM.id} /> is only just made up for by the trait's bonus damage, so you would be better off with almost any other Feral trait.
</>,
)
.icon(SPELLS.IRON_JAWS_TRAIT.icon)
.actual(`${actual} Iron Jaws traits.`)
.recommended(`2, 3 or none is recommended.`);
});
when(this.wastedProcsThreshold).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
You're not making full use of your <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> Azerite trait. When <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> procs you should replace your next finisher with <SpellLink id={SPELLS.MAIM.id} /> to make use of the significant bonus damage.
</>,
)
.icon(SPELLS.IRON_JAWS_TRAIT.icon)
.actual(`${(actual * 100).toFixed(0)}% of Iron Jaws procs wasted.`)
.recommended(`<${(recommended * 100).toFixed(0)}% recommended.`);
});
when(this.unbuffedMaimThreshold).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
You're using <SpellLink id={SPELLS.MAIM.id} /> when it's not buffed by your <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> Azerite trait. Because of the cooldown on <SpellLink id={SPELLS.MAIM.id} /> this risks the ability not being available when <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> is active. If a fight requires you to regularly use <SpellLink id={SPELLS.MAIM.id} /> outside of your damage rotation, switching to different Azerite traits is likely to be beneficial.
</>,
)
.icon(SPELLS.IRON_JAWS_TRAIT.icon)
.actual(`${actual.toFixed(1)} unbuffed Maims per minute.`)
.recommended(`<${recommended.toFixed(1)} recommended.`);
});
when(this.missingComboMaimThreshold).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
You're using <SpellLink id={SPELLS.MAIM.id} /> without full combo points. With your <SpellLink id={SPELLS.IRON_JAWS_TRAIT.id} /> Azerite trait <SpellLink id={SPELLS.MAIM.id} /> becomes an important damage source, and using it without full combo points significantly reduces its damage.
</>,
)
.icon(SPELLS.IRON_JAWS_TRAIT.icon)
.actual(`${(actual * 100).toFixed(0)}% of Maims used without full combo points.`)
.recommended(`${(recommended * 100).toFixed(0)}% recommended.`);
});
}
}
export default IronJaws;
|
components/Header.js | sunday-school/sundayschool.rocks | import React from 'react'
import Nav from './Nav'
import Church from './Church'
const Header = ({children}) =>
<header className='bb cf mb3'>
<div className='fl w-10'>
<Church />
</div>
<div className='fl w-60'>
<h1 className='pa0 ma0'>{children}</h1>
</div>
<div className='fl w-30'>
<Nav />
</div>
</header>
export default Header
|
src/routes/about/index.js | quyetvv/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-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 Page from '../../components/Page';
import ImageList from '../../components/ImageList';
export default {
path: '/about',
async action() {
const data = await require.ensure([], require => require('./about.md'), 'about');
return {
title: data.title,
chunk: 'about',
component: <Layout><Page {...data} />
<ImageList />
</Layout>,
};
},
};
|
src/components/fields/PasswordStrengthIndicator.js | streamr-app/streamr-web | import React from 'react'
import cx from 'classnames'
import waitForZxcvbn from 'bundle-loader!zxcvbn'
export default class PasswordStrengthIndicator extends React.Component {
constructor (props) {
super(props)
this.state = {
zxcvbn: () => ({ score: 0 })
}
}
componentDidMount () {
waitForZxcvbn((zxcvbn) => {
this.setState({ zxcvbn })
})
}
render () {
const score = this.state.zxcvbn(this.props.password).score
return (
<div className={`password-strength-indicator score-${score}`}>
<div className={cx('strength-bar', { filled: this.props.password })} />
<div className={cx('strength-bar', { filled: score >= 1 })} />
<div className={cx('strength-bar', { filled: score >= 2 })} />
<div className={cx('strength-bar', { filled: score >= 3 })} />
<div className={cx('strength-bar', { filled: score >= 4 })} />
</div>
)
}
}
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/antd/es/timeline/Timeline.js | bhathiya/test | import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
import TimelineItem from './TimelineItem';
var Timeline = function (_React$Component) {
_inherits(Timeline, _React$Component);
function Timeline() {
_classCallCheck(this, Timeline);
return _possibleConstructorReturn(this, (Timeline.__proto__ || Object.getPrototypeOf(Timeline)).apply(this, arguments));
}
_createClass(Timeline, [{
key: 'render',
value: function render() {
var _a = this.props,
prefixCls = _a.prefixCls,
children = _a.children,
pending = _a.pending,
className = _a.className,
restProps = __rest(_a, ["prefixCls", "children", "pending", "className"]);
var pendingNode = typeof pending === 'boolean' ? null : pending;
var classString = classNames(prefixCls, _defineProperty({}, prefixCls + '-pending', !!pending), className);
var items = React.Children.map(children, function (ele, idx) {
return React.cloneElement(ele, {
last: idx === children.length - 1
});
});
var pendingItem = !!pending ? React.createElement(
TimelineItem,
{ pending: !!pending },
pendingNode
) : null;
return React.createElement(
'ul',
_extends({}, restProps, { className: classString }),
items,
pendingItem
);
}
}]);
return Timeline;
}(React.Component);
export default Timeline;
Timeline.Item = TimelineItem;
Timeline.defaultProps = {
prefixCls: 'ant-timeline'
}; |
src/components/SignUpForm/index.js | khankuan/asset-library-demo | import React from 'react';
import Button from '../Button';
import TextField from '../TextField';
import Text from '../Text';
export default class SignUpForm extends React.Component {
static propTypes = {
onSignUp: React.PropTypes.func.isRequired,
}
_handleSignUp = () => {
if (this.props.onSignUp) {
this.props.onSignUp(this.refs.email.getValue(), this.refs.password.getValue(),
this.refs.name.getValue());
}
}
render() {
return (
<div className="signup-form">
<Text block bold size="large">Welcome onboard!</Text>
<TextField ref="name" type="text" placeholder="Your Name"/>
<br/>
<TextField ref="email" type="text" placeholder="Your Email"/>
<br/>
<TextField ref="password" type="password" placeholder="Your Password"/>
<br/>
<Button onClick={ this._handleSignUp } >Sign Up</Button>
</div>
);
}
}
|
react/features/mobile/audio-mode/components/AudioRoutePickerDialog.js | gpolitis/jitsi-meet | // @flow
import _ from 'lodash';
import React, { Component } from 'react';
import { NativeModules, Text, TouchableHighlight, View } from 'react-native';
import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { hideDialog, BottomSheet } from '../../../base/dialog';
import { translate } from '../../../base/i18n';
import {
Icon,
IconCar,
IconDeviceBluetooth,
IconDeviceEarpiece,
IconDeviceHeadphone,
IconDeviceSpeaker
} from '../../../base/icons';
import { connect } from '../../../base/redux';
import { ColorPalette, type StyleType } from '../../../base/styles';
import styles from './styles';
const { AudioMode } = NativeModules;
/**
* Type definition for a single entry in the device list.
*/
type Device = {
/**
* Name of the icon which will be rendered on the right.
*/
icon: Object,
/**
* True if the element is selected (will be highlighted in blue),
* false otherwise.
*/
selected: boolean,
/**
* Text which will be rendered in the row.
*/
text: string,
/**
* Device type.
*/
type: string,
/**
* Unique device ID.
*/
uid: ?string
};
/**
* "Raw" device, as returned by native.
*/
type RawDevice = {
/**
* Display name for the device.
*/
name: ?string,
/**
* Is this device selected?
*/
selected: boolean,
/**
* Device type.
*/
type: string,
/**
* Unique device ID.
*/
uid: ?string
};
/**
* {@code AudioRoutePickerDialog}'s React {@code Component} prop types.
*/
type Props = {
/**
* Style of the bottom sheet feature.
*/
_bottomSheetStyles: StyleType,
/**
* Object describing available devices.
*/
_devices: Array<RawDevice>,
/**
* Used for hiding the dialog when the selection was completed.
*/
dispatch: Function,
/**
* Invoked to obtain translated strings.
*/
t: Function
};
/**
* {@code AudioRoutePickerDialog}'s React {@code Component} state types.
*/
type State = {
/**
* Array of available devices.
*/
devices: Array<Device>
};
/**
* Maps each device type to a display name and icon.
*/
const deviceInfoMap = {
BLUETOOTH: {
icon: IconDeviceBluetooth,
text: 'audioDevices.bluetooth',
type: 'BLUETOOTH'
},
CAR: {
icon: IconCar,
text: 'audioDevices.car',
type: 'CAR'
},
EARPIECE: {
icon: IconDeviceEarpiece,
text: 'audioDevices.phone',
type: 'EARPIECE'
},
HEADPHONES: {
icon: IconDeviceHeadphone,
text: 'audioDevices.headphones',
type: 'HEADPHONES'
},
SPEAKER: {
icon: IconDeviceSpeaker,
text: 'audioDevices.speaker',
type: 'SPEAKER'
}
};
/**
* The exported React {@code Component}.
*/
let AudioRoutePickerDialog_; // eslint-disable-line prefer-const
/**
* Implements a React {@code Component} which prompts the user when a password
* is required to join a conference.
*/
class AudioRoutePickerDialog extends Component<Props, State> {
state = {
/**
* Available audio devices, it will be set in
* {@link #getDerivedStateFromProps()}.
*/
devices: []
};
/**
* Implements React's {@link Component#getDerivedStateFromProps()}.
*
* @inheritdoc
*/
static getDerivedStateFromProps(props: Props) {
const { _devices: devices, t } = props;
if (!devices) {
return null;
}
const audioDevices = [];
for (const device of devices) {
const infoMap = deviceInfoMap[device.type];
// Skip devices with unknown type.
if (!infoMap) {
// eslint-disable-next-line no-continue
continue;
}
let text = t(infoMap.text);
// iOS provides descriptive names for these, use it.
if ((device.type === 'BLUETOOTH' || device.type === 'CAR') && device.name) {
text = device.name;
}
if (infoMap) {
const info = {
...infoMap,
selected: Boolean(device.selected),
text,
uid: device.uid
};
audioDevices.push(info);
}
}
// Make sure devices is alphabetically sorted.
return {
devices: _.sortBy(audioDevices, 'text')
};
}
/**
* Initializes a new {@code PasswordRequiredPrompt} instance.
*
* @param {Props} props - The read-only React {@code Component} props with
* which the new instance is to be initialized.
*/
constructor(props: Props) {
super(props);
// Bind event handlers so they are only bound once per instance.
this._onCancel = this._onCancel.bind(this);
// Trigger an initial update.
AudioMode.updateDeviceList && AudioMode.updateDeviceList();
}
/**
* Dispatches a redux action to hide this sheet.
*
* @returns {void}
*/
_hide() {
this.props.dispatch(hideDialog(AudioRoutePickerDialog_));
}
_onCancel: () => void;
/**
* Cancels the dialog by hiding it.
*
* @private
* @returns {void}
*/
_onCancel() {
this._hide();
}
_onSelectDeviceFn: (Device) => Function;
/**
* Builds and returns a function which handles the selection of a device
* on the sheet. The selected device will be used by {@code AudioMode}.
*
* @param {Device} device - Object representing the selected device.
* @private
* @returns {Function}
*/
_onSelectDeviceFn(device: Device) {
return () => {
this._hide();
AudioMode.setAudioDevice(device.uid || device.type);
};
}
/**
* Renders a single device.
*
* @param {Device} device - Object representing a single device.
* @private
* @returns {ReactElement}
*/
_renderDevice(device: Device) {
const { _bottomSheetStyles } = this.props;
const { icon, selected, text } = device;
const selectedStyle = selected ? styles.selectedText : {};
return (
<TouchableHighlight
key = { device.type }
onPress = { this._onSelectDeviceFn(device) }
underlayColor = { ColorPalette.overflowMenuItemUnderlay } >
<View style = { styles.deviceRow } >
<Icon
src = { icon }
style = { [ styles.deviceIcon, _bottomSheetStyles.buttons.iconStyle, selectedStyle ] } />
<Text style = { [ styles.deviceText, _bottomSheetStyles.buttons.labelStyle, selectedStyle ] } >
{ text }
</Text>
</View>
</TouchableHighlight>
);
}
/**
* Renders a "fake" device row indicating there are no devices.
*
* @private
* @returns {ReactElement}
*/
_renderNoDevices() {
const { _bottomSheetStyles, t } = this.props;
return (
<View style = { styles.deviceRow } >
<Icon
src = { deviceInfoMap.SPEAKER.icon }
style = { [ styles.deviceIcon, _bottomSheetStyles.buttons.iconStyle ] } />
<Text style = { [ styles.deviceText, _bottomSheetStyles.buttons.labelStyle ] } >
{ t('audioDevices.none') }
</Text>
</View>
);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { devices } = this.state;
let content;
if (devices.length === 0) {
content = this._renderNoDevices();
} else {
content = this.state.devices.map(this._renderDevice, this);
}
return (
<BottomSheet onCancel = { this._onCancel }>
{ content }
</BottomSheet>
);
}
}
/**
* Maps part of the Redux state to the props of this component.
*
* @param {Object} state - The Redux state.
* @returns {Object}
*/
function _mapStateToProps(state) {
return {
_bottomSheetStyles: ColorSchemeRegistry.get(state, 'BottomSheet'),
_devices: state['features/mobile/audio-mode'].devices
};
}
AudioRoutePickerDialog_ = translate(connect(_mapStateToProps)(AudioRoutePickerDialog));
export default AudioRoutePickerDialog_;
|
app/components/LoadingIndicator/index.js | pacog/recoreco | import React from 'react';
import RefreshIndicator from 'material-ui/RefreshIndicator';
const style = {
container: {
position: 'relative',
textAlign: 'center',
marginTop: 50,
paddingTop: 50,
paddingBottom: 50
},
refresh: {
display: 'inline-block',
position: 'relative',
},
};
const LoadingIndicator = () => (
<div style={style.container}>
<RefreshIndicator
size={50}
left={0}
top={0}
status="loading"
style={style.refresh}
/>
</div>
);
export default LoadingIndicator;
|
client/routes/error/ErrorPage.js | kriasoft/FSharp-Server-Template | /**
* ASP.NET Core Starter Kit
*
* 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 { Layout } from '../../components';
function ErrorPage() {
return (
<Layout>
<h1 className="mdl-typography--title">Page Not Found</h1>
<p className="mdl-typography--body-1">
Sorry, this page does not exist.
</p>
</Layout>
);
}
export default ErrorPage;
|
src/svg-icons/file/attachment.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileAttachment = (props) => (
<SvgIcon {...props}>
<path d="M2 12.5C2 9.46 4.46 7 7.5 7H18c2.21 0 4 1.79 4 4s-1.79 4-4 4H9.5C8.12 15 7 13.88 7 12.5S8.12 10 9.5 10H17v2H9.41c-.55 0-.55 1 0 1H18c1.1 0 2-.9 2-2s-.9-2-2-2H7.5C5.57 9 4 10.57 4 12.5S5.57 16 7.5 16H17v2H7.5C4.46 18 2 15.54 2 12.5z"/>
</SvgIcon>
);
FileAttachment = pure(FileAttachment);
FileAttachment.displayName = 'FileAttachment';
FileAttachment.muiName = 'SvgIcon';
export default FileAttachment;
|
index.ios.js | fakerabbit/SenalesDelFinRNA | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class SenalesDelFinRNA2 extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('SenalesDelFinRNA2', () => SenalesDelFinRNA2);
|
examples/universal/server/server.js | julen/redux | /* eslint-disable no-console, no-use-before-define */
import path from 'path';
import Express from 'express';
import qs from 'qs';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../common/store/configureStore';
import App from '../common/containers/App';
import { fetchCounter } from '../common/api/counter';
const app = new Express();
const port = 3000;
// Use this middleware to server up static files built into dist
app.use(require('serve-static')(path.join(__dirname, '../dist')));
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
// Query our mock API asynchronously
fetchCounter(apiResult => {
// Read the counter from the request, if provided
const params = qs.parse(req.query);
const counter = parseInt(params.counter, 10) || apiResult || 0;
// Compile an initial state
const initialState = { counter };
// Create a new Redux store instance
const store = configureStore(initialState);
// Render the component to a string
const html = React.renderToString(
<Provider store={store}>
{ () => <App/> }
</Provider>);
// Grab the initial state from our Redux store
const finalState = store.getState();
// Send the rendered page back to the client
res.send(renderFullPage(html, finalState));
});
}
function renderFullPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<script src="/bundle.js"></script>
</body>
</html>
`;
}
app.listen(port, (error) => {
if (error) {
console.error(error);
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
}
});
|
src/svg-icons/action/supervisor-account.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSupervisorAccount = (props) => (
<SvgIcon {...props}>
<path d="M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7C15.12 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5zM9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5C7.34 5 6 6.34 6 8s1.34 3 3 3zm7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75zM9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13z"/>
</SvgIcon>
);
ActionSupervisorAccount = pure(ActionSupervisorAccount);
ActionSupervisorAccount.displayName = 'ActionSupervisorAccount';
export default ActionSupervisorAccount;
|
stories/Badge/DefaultBadge.js | skyiea/wix-style-react | import React from 'react';
import {Badge} from 'wix-style-react';
export default () => (
<div>
<Badge>Default</Badge>
<Badge type="primary">Primary</Badge>
<Badge type="success">Success</Badge>
<Badge type="info">Info</Badge>
<Badge type="warning">Warning</Badge>
<Badge type="danger">Danger</Badge>
<Badge type="businessManagerCounter">1</Badge>
<Badge type="businessManagerCounter">3</Badge>
<Badge type="businessManagerCounter">44</Badge>
<Badge type="businessManagerCounter">666</Badge>
</div>
);
|
app/static/src/diagnostic/TestTypeResultForm_modules/NewPcbTestForm.js | SnowBeaver/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Button from 'react-bootstrap/lib/Button';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
const TextField = React.createClass({
render: function() {
var label = (this.props.label != null) ? this.props.label: "";
var name = (this.props.name != null) ? this.props.name: "";
var value = (this.props.value != null) ? this.props.value: "";
return (
<FormGroup validationState={this.props.errors[name] ? 'error' : null}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
value={value}
data-type={this.props["data-type"]}
/>
<HelpBlock className="warning">{this.props.errors[name]}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
);
}
});
const CheckBox = React.createClass({
render: function () {
var name = (this.props.name != null) ? this.props.name: "";
var checked = (this.props.value != null) ? this.props.value: false;
var is_checked = (checked) ? 'checked': '';
return (
<Checkbox checked={is_checked} name={name}>
<span className="glyphicon glyphicon-menu-left">
</span>
</Checkbox>
);
}
});
var NewPcbTestForm = React.createClass({
getInitialState: function () {
return {
loading: false,
errors: {},
fields: [
'aroclor_1242', 'aroclor_1254', 'aroclor_1260',
'aroclor_1242_flag', 'aroclor_1254_flag', 'aroclor_1260_flag',
'pcb_total', 'total_flag'
]
}
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId;
this.serverRequest = $.authorizedGet(source, function (result) {
var res = (result['result']);
if (res.length > 0) {
var fields = this.state.fields;
fields.push('id');
var data = res[0];
var state = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
if (data.hasOwnProperty(key)) {
state[key] = data[key];
}
}
this.setState(state);
}
}.bind(this), 'json');
},
_create: function () {
var fields = this.state.fields;
var data = {test_result_id: this.props.testResultId};
var url = '/api/v1.0/' + this.props.tableName + '/';
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
data[key] = this.state[key];
}
if ('id' in this.state) {
url += this.state['id'];
delete data.id;
}
return $.authorizedAjax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
})
},
_onSubmit: function (e) {
e.preventDefault();
// Do not propagate the submit event of the main form
e.stopPropagation();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
e.stopPropagation();
return false;
}
var xhr = this._create();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
// this.setState(this.getInitialState());
NotificationManager.success('Test values have been saved successfully.');
if ($.isNumeric(data.result)) {
this.setState({id: data.result});
}
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
_onChange: function (e) {
var state = {};
if (e.target.type == 'checkbox') {
state[e.target.name] = e.target.checked;
}
else if (e.target.type == 'radio') {
state[e.target.name] = e.target.value;
}
else if (e.target.type == 'select-one') {
state[e.target.name] = e.target.value;
}
else {
state[e.target.name] = $.trim(e.target.value);
}
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
render: function () {
return (
<div className="form-container">
<form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="row">
<div className="col-md-1 ">
<CheckBox name="aroclor_1242_flag" value={this.state.aroclor_1242_flag}/>
</div>
<div className="col-md-3">
<TextField label="Aroclor-1242" name="aroclor_1242" value={this.state.aroclor_1242}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-1 ">
<CheckBox name="aroclor_1254_flag" value={this.state.aroclor_1254_flag}/>
</div>
<div className="col-md-3">
<TextField label="Aroclor-1254" name="aroclor_1254" value={this.state.aroclor_1254}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-1 ">
<CheckBox name="aroclor_1260_flag" value={this.state.aroclor_1260_flag}/>
</div>
<div className="col-md-3">
<TextField label="Aroclor-1260" name="aroclor_1260" value={this.state.aroclor_1260}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-3 pull-right">
<TextField label="PCB-Total" name="pcb_total" value={this.state.pcb_total}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-1 pull-right">
<CheckBox name="total_flag" value={this.state.total_flag}/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Button bsStyle="success"
className="pull-right"
type="submit">Save</Button>
<Button bsStyle="danger"
className="pull-right margin-right-xs"
onClick={this.props.handleClose}
>Cancel</Button>
</div>
</div>
</form>
</div>
);
}
});
export default NewPcbTestForm;
|
examples/huge-apps/routes/Messages/components/Messages.js | rubengrill/react-router | import React from 'react'
class Messages extends React.Component {
render() {
return (
<div>
<h2>Messages</h2>
</div>
)
}
}
export default Messages
|
app/src/components/Common/Title.js | nickdecooman/template-react-frontend | // @flow
import React from 'react';
import { StyleSheet, css } from 'aphrodite/no-important';
import { type SheetDefinition, getStyle } from '../../utils/aphrodite';
type Props = {
children: string,
styleSheet?: {
title?: SheetDefinition,
},
};
const styles = StyleSheet.create({
title: {
fontSize: '24pt',
},
});
const Title = ({ children, styleSheet }: Props) => {
const textStyle = getStyle('title', styles, styleSheet);
return <span className={css(textStyle)}>{children}</span>;
};
Title.defaultProps = {
styleSheet: {
title: null,
},
};
export default Title;
|
webservice/src/main/resources/app/scripts/utils/TopologyUtils.js | hmcl/Streams | /**
* Copyright 2017 Hortonworks.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import React from 'react';
import _ from 'lodash';
import {Components, toastOpt} from './Constants';
import d3 from 'd3';
import TopologyREST from '../rest/TopologyREST';
import FSReactToastr from '../components/FSReactToastr';
//Sources
import SourceNodeForm from '../containers/Streams/TopologyEditor/SourceNodeForm';
//Processors
import ProcessorNodeForm from '../containers/Streams/TopologyEditor/ProcessorNodeForm';
import RulesNodeForm from '../containers/Streams/TopologyEditor/RulesNodeForm';
import SplitNodeForm from '../containers/Streams/TopologyEditor/SplitNodeForm';
import StageNodeForm from '../containers/Streams/TopologyEditor/StageNodeForm';
import JoinNodeForm from '../containers/Streams/TopologyEditor/JoinNodeForm';
import CustomNodeForm from '../containers/Streams/TopologyEditor/CustomNodeForm';
import NormalizationNodeForm from '../containers/Streams/TopologyEditor/NormalizationNodeForm';
import WindowingAggregateNodeForm from '../containers/Streams/TopologyEditor/WindowingAggregateNodeForm';
import BranchNodeForm from '../containers/Streams/TopologyEditor/BranchNodeForm';
import ModelNodeForm from '../containers/Streams/TopologyEditor/ModelNodeForm';
import ProjectionProcessorContainer from '../containers/Streams/TopologyEditor/ProjectionProcessorContainer';
// import RealTimeJoinNodeProcessor from '../containers/Streams/TopologyEditor/RealTimeJoinNodeProcessor';
//Sinks
import SinkNodeForm from '../containers/Streams/TopologyEditor/SinkNodeForm';
import CommonNotification from './CommonNotification';
import {deleteNodeIdArr} from '../utils/Constants';
const defineMarkers = function(svg) {
// define arrow markers for graph links
let defs = svg.append('svg:defs');
defs.append('svg:marker').attr('id', 'end-arrow').attr('viewBox', '0 -5 10 10').attr('refX', "14").attr('markerWidth', 6.5).attr('markerHeight', 7.5).attr('orient', 'auto').append('svg:path').attr('d', 'M0 -5 L10 0 L0 5');
// define arrow markers for leading arrow
defs.append('svg:marker').attr('id', 'mark-end-arrow').attr('viewBox', '0 -5 10 10').attr('refX', 7).attr('markerWidth', 6.5).attr('markerHeight', 7.5).attr('orient', 'auto').append('svg:path').attr('d', 'M0 -5 L10 0 L0 5');
// define filter for gray(unconfigured) icons
defs.append('svg:filter').attr('id', 'grayscale').append('feColorMatrix').attr('type', 'saturate').attr('values', '0');
// define filter for node shadow
var filter = defs.append('svg:filter').attr('id', 'dropshadow').attr('x', 0).attr('y', 0).attr('width', '200%').attr('height', '200%');
filter.append('feOffset').attr('result', 'offOut').attr('in', 'SourceAlpha').attr('dx', -4).attr('dy', -4);
filter.append('feGaussianBlur').attr('result', 'blurOut').attr('in', 'offOut').attr('stdDeviation', 6);
filter.append('feBlend').attr('in', 'SourceGraphic').attr('in2', 'blurOut').attr('mode', 'normal');
};
const isValidConnection = function(sourceNode, targetNode) {
let validConnection = true;
// if((sourceNode.currentType.toLowerCase() !== 'split' && targetNode.currentType.toLowerCase() === 'stage') ||
// (sourceNode.currentType.toLowerCase() === 'stage' && targetNode.currentType.toLowerCase() !== 'join')
// ){
// validConnection = false;
// }
return validConnection;
};
const createNode = function(topologyId, versionId, data, callback, metaInfo, paths, edges, internalFlags, uinamesList, setLastChange) {
let promiseArr = [];
data.map((o) => {
let nodeType = this.getNodeType(o.parentType);
let customName = o.uiname;
//Dynamic Names of nodes
while (uinamesList.indexOf(o.uiname) !== -1) {
let arr = o.uiname.split('-');
let count = 1;
if (arr.length > 1) {
count = parseInt(arr[1], 10) + 1;
}
o.uiname = arr[0] + '-' + count;
}
uinamesList.push(o.uiname);
//
//
if (o.currentType.toLowerCase() === 'custom') {
if (metaInfo.customNames) {
metaInfo.customNames.push({uiname: o.uiname, customProcessorName: customName});
} else {
metaInfo.customNames = [
{
uiname: o.uiname,
customProcessorName: customName
}
];
}
}
let obj = {
name: o.uiname,
config: {},
topologyComponentBundleId: o.topologyComponentBundleId
};
if (o.parentType === 'PROCESSOR') {
obj["outputStreamIds"] = [];
}
promiseArr.push(TopologyREST.createNode(topologyId, versionId, nodeType, {body: JSON.stringify(obj)}));
if (callback) {
//call the callback to update the graph
callback();
}
});
//Make calls to create node or nodes
Promise.all(promiseArr).then((results) => {
results.map((o, i) => {
if (o.responseMessage !== undefined) {
FSReactToastr.error(
<CommonNotification flag="error" content={o.responseMessage}/>, '', toastOpt);
} else {
data[i].nodeId = o.id;
}
if (i > 0) {
//Creating edge link
this.createEdge(data[i - 1], data[i], paths, edges, internalFlags, callback, topologyId, versionId);
}
});
setLastChange(results[0].timestamp);
this.saveMetaInfo(topologyId, versionId, data, metaInfo, callback);
});
};
const saveMetaInfo = function(topologyId, versionId, nodes, metaInfo, callback) {
if (nodes) {
nodes.map((o) => {
let obj = {
x: o.x,
y: o.y,
id: o.nodeId
};
metaInfo[this.getNodeType(o.parentType)].push(obj);
});
}
let data = {
topologyId: topologyId,
data: JSON.stringify(metaInfo)
};
TopologyREST.putMetaInfo(topologyId, versionId, {body: JSON.stringify(data)}).then(() => {
if (callback) {
//call the callback to update the graph
callback();
}
});
};
const updateMetaInfo = function(topologyId, versionId, node, metaInfo) {
let metaArr = metaInfo[this.getNodeType(node.parentType)];
let oldMetaObj = metaArr.filter((o) => {
return o.id === node.nodeId;
});
if (oldMetaObj.length !== 0) {
oldMetaObj = oldMetaObj[0];
oldMetaObj.x = node.x;
oldMetaObj.y = node.y;
if (node.streamId === 'failedTuplesStream') {
oldMetaObj.streamId = node.streamId;
} else {
delete oldMetaObj.streamId;
}
} else {
metaArr.push({x: node.x, y: node.y, id: node.nodeId});
}
let data = {
topologyId: topologyId,
data: JSON.stringify(metaInfo)
};
TopologyREST.putMetaInfo(topologyId, versionId, {body: JSON.stringify(data)});
};
const removeNodeFromMeta = function(metaInfo, currentNode) {
let currentType = this.getNodeType(currentNode.parentType);
let arr = metaInfo[currentType];
let nodeMeta = arr.filter((o) => {
return o.id === currentNode.nodeId;
});
let customNameArr = metaInfo.customNames;
nodeMeta.map((o) => {
arr.splice(arr.indexOf(o), 1);
});
if (customNameArr) {
let customMeta = customNameArr.filter((o) => {
return o.uiname === currentNode.uiname;
});
customMeta.map((o) => {
customNameArr.splice(customNameArr.indexOf(o), 1);
});
}
return metaInfo;
};
const createEdge = function(mouseDownNode, d, paths, edges, internalFlags, callback, topologyId, versionId, getEdgeConfigModal, setLastChange, drawLine) {
if (this.isValidConnection(mouseDownNode, d)) {
let newEdge = {
source: mouseDownNode,
target: d
};
let filtRes = paths.filter(function(d) {
if (d.source === newEdge.target && d.target === newEdge.source) {
edges.splice(edges.indexOf(d), 1);
}
return d.source === newEdge.source && d.target === newEdge.target;
});
if (d.currentType.toLowerCase() === 'rule' || d.currentType.toLowerCase() === 'window' || d.currentType.toLowerCase() === 'projection' || d.currentType.toLowerCase() === 'pmml' || d.currentType.toLowerCase() === 'branch' || d.currentType.toLowerCase() === 'custom') {
let filtEdges = paths.filter(function(d) {
return newEdge.target === d.target;
});
if (filtEdges[0].length > 0) {
drawLine.classed("hidden", true);
FSReactToastr.info(
<CommonNotification flag="error" content={"Cannot connect more than one edge to " + d.uiname}/>, '', toastOpt);
return;
}
}
if (!filtRes[0].length) {
TopologyREST.getNode(topologyId, versionId, this.getNodeType(newEdge.source.parentType), newEdge.source.nodeId).then((result) => {
setLastChange(result.timestamp);
let nodeData = result;
if (newEdge.source.currentType.toLowerCase() === 'window' || newEdge.source.currentType.toLowerCase() === 'rule' || newEdge.source.currentType.toLowerCase() === 'projection') {
nodeData.type = newEdge.source.currentType.toUpperCase();
}
drawLine.classed('hidden', true);
if (getEdgeConfigModal) {
getEdgeConfigModal(topologyId, versionId, newEdge, edges, callback, nodeData);
} else {
console.error("Cannot find getEdgeConfigModal: from createEdge:TopologyUtils");
}
});
}
} else {
FSReactToastr.error(
<CommonNotification flag="error" content={mouseDownNode.currentType + " cannot be connected to " + d.currentType}/>, '', toastOpt);
}
};
const getNodeType = function(parentType) {
switch (parentType) {
case 'SOURCE':
return 'sources';
break;
case 'PROCESSOR':
return 'processors';
break;
case 'SINK':
return 'sinks';
break;
}
};
const spliceDeleteNodeArr = function(nodeId) {
const index = deleteNodeIdArr.findIndex((x) => {
return Number(x) === nodeId;
});
if (index !== -1) {
deleteNodeIdArr.splice(index, 1);
}
};
const deleteNode = function(topologyId, versionId, currentNode, nodes, edges, internalFlags, updateGraphMethod, metaInfo, uinamesList, setLastChange, topologyConfigMessageCB) {
let promiseArr = [],
nodePromiseArr = [],
callback = null,
currentType = currentNode.currentType;
deleteNodeIdArr.push(currentNode.nodeId);
//Get data of current node
nodePromiseArr.push(TopologyREST.getNode(topologyId, versionId, this.getNodeType(currentNode.parentType), currentNode.nodeId));
//Find out if the source of the current node is rules/windows
//then update those processor by removing actions from it.
let connectingNodes = edges.filter((obj) => {
return obj.target == currentNode;
});
let actionsPromiseArr = [];
let currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction";
let streamId = [];
connectingNodes.map((o, i) => {
if (o.source.currentType.toLowerCase() === 'rule' || o.source.currentType.toLowerCase() === 'window' ||
o.source.currentType.toLowerCase() === 'branch' || o.source.currentType.toLowerCase() === 'projection') {
let t = o.source.currentType.toLowerCase();
let type = (t === 'rule' || t === "projection")
? 'rules'
: t === 'branch'
? 'branchrules'
: 'windows';
streamId[i] = o.streamGrouping.streamId;
let currentNodeEdges = edges.filter((obj) => {
return obj.source === o.source && streamId[i] === obj.streamGrouping.streamId;
});
if (currentNode.currentType.toLowerCase() === 'notification') {
currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.NotifierAction";
} else {
currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction";
}
let rulesPromiseArr = [
TopologyREST.getAllNodes(topologyId, versionId, 'streams'),
TopologyREST.getAllNodes(topologyId, versionId, type)
];
Promise.all(rulesPromiseArr).then((results) => {
results[1].entities.map((nodeObj) => {
let actionsArr = nodeObj.actions,
actions = [],
hasAction = false;
let ruleStream = results[0].entities.find((s) => {
return s.id === streamId[i];
});
actionsArr.map((a) => {
if (a.outputStreams[0] === ruleStream.streamId && a.__type === currentActionType) {
hasAction = true;
if (currentNodeEdges.length > 0) {
if (currentActionType === 'com.hortonworks.streamline.streams.layout.component.rule.action.NotifierAction') {
let notifierActionsArr = currentNodeEdges.filter((obj) => {
return obj.target !== currentNode && obj.target.currentType.toLowerCase() === 'notification';
});
if (notifierActionsArr.length > 0) {
let targetNode = notifierActionsArr[0].target;
let stream = results[0].entities.find((s) => {
return s.id === notifierActionsArr[0].streamGrouping.streamId;
});
actions.push({
__type: currentActionType,
name: 'notifierAction',
outputStreams: [stream.streamId],
outputFieldsAndDefaults: {},
notifierName: ''
});
}
} else if (currentActionType === 'com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction') {
let transformActionsArr = currentNodeEdges.filter((obj) => {
return obj.target !== currentNode && obj.target.currentType.toLowerCase() !== 'notification';
});
if (transformActionsArr.length > 0) {
let targetNode = transformActionsArr[0].target;
let stream = results[0].entities.find((s) => {
return s.id === transformActionsArr[0].streamGrouping.streamId;
});
actions.push({
__type: currentActionType,
name: 'transformAction',
outputStreams: [stream.streamId],
transforms: []
});
}
}
}
} else {
actions.push(a);
}
});
if (hasAction) {
nodeObj.actions = actions;
actionsPromiseArr.push(TopologyREST.updateNode(topologyId, versionId, type, nodeObj.id, {body: JSON.stringify(nodeObj)}));
}
});
});
}
});
Promise.all(actionsPromiseArr).then((results) => {
for (let i = 0; i < results.length; i++) {
if (results[i].responseMessage !== undefined) {
FSReactToastr.error(
<CommonNotification flag="error" content={results[i].responseMessage}/>, '', toastOpt);
}
}
});
Promise.all(nodePromiseArr).then(results => {
let nodeData = results[0];
nodeData.type = currentNode.currentType;
setLastChange(results[0].timestamp);
callback = function() {
// Graph related Operations
uinamesList.splice(uinamesList.indexOf(currentNode.uiname), 1);
nodes.splice(nodes.indexOf(currentNode), 1);
this.spliceLinksForNode(currentNode, edges);
internalFlags.selectedNode = null;
this.spliceDeleteNodeArr(currentNode.nodeId);
updateGraphMethod();
if (topologyConfigMessageCB) {
topologyConfigMessageCB(currentNode.nodeId);
}
}.bind(this);
//Delete data from metadata
metaInfo = this.removeNodeFromMeta(metaInfo, currentNode);
let metaData = {
topologyId: topologyId,
data: JSON.stringify(metaInfo)
};
promiseArr.push(TopologyREST.putMetaInfo(topologyId, versionId, {body: JSON.stringify(metaData)}));
//Delete Links
// let edgeArr = this.getEdges(edges, currentNode);
//
// edgeArr.map((o)=>{
// promiseArr.push(TopologyREST.deleteNode(topologyId, 'edges', o.edgeId));
// });
Promise.all(promiseArr).then((edgeResults) => {
let edgeAPISuccess = true;
edgeResults.map((edge) => {
if (edge.responseMessage !== undefined) {
edgeAPISuccess = false;
FSReactToastr.error(
<CommonNotification flag="error" content={edge.responseMessage}/>, '', toastOpt);
}
});
if (edgeAPISuccess) {
let processorsPromiseArr = [];
//Delete Rules incase of Rule Processor or Projection Processor
if (nodeData.type.toLowerCase() === 'rule' || nodeData.type.toLowerCase() === 'projection') {
if (nodeData.config.properties.rules) {
nodeData.config.properties.rules.map(ruleId => {
processorsPromiseArr.push(TopologyREST.deleteNode(topologyId, 'rules', ruleId));
});
}
}
//Delete Window incase of Window Processor
if (nodeData.type.toLowerCase() === 'window') {
if (nodeData.config.properties.rules) {
nodeData.config.properties.rules.map(ruleId => {
processorsPromiseArr.push(TopologyREST.deleteNode(topologyId, 'windows', ruleId));
});
}
}
//Delete Branch incase of Branch Processor
if (nodeData.type.toLowerCase() === 'branch') {
if (nodeData.config.properties.rules) {
nodeData.config.properties.rules.map(ruleId => {
processorsPromiseArr.push(TopologyREST.deleteNode(topologyId, 'branchrules', ruleId));
});
}
}
//Delete current node
processorsPromiseArr.push(TopologyREST.deleteNode(topologyId, this.getNodeType(currentNode.parentType), currentNode.nodeId));
Promise.all(processorsPromiseArr).then((processorResult) => {
let processorAPISuccess = true;
processorResult.map((processor) => {
if (processor.responseMessage !== undefined) {
processorAPISuccess = false;
FSReactToastr.error(
<CommonNotification flag="error" content={processor.responseMessage}/>, '', toastOpt);
}
});
if (processorAPISuccess) {
let streamsPromiseArr = [];
//Delete streams of all nodes
results.map(result => {
let node = result;
if (node.outputStreams) {
node.outputStreams.map(stream => {
if (stream.id) {
streamsPromiseArr.push(TopologyREST.deleteNode(topologyId, 'streams', stream.id));
}
});
}
});
Promise.all(streamsPromiseArr).then((streamsResult) => {
streamsResult.map((stream) => {
if (stream.responseMessage !== undefined) {
FSReactToastr.error(
<CommonNotification flag="error" content={stream.responseMessage}/>, '', toastOpt);
}
});
//call the callback
callback();
});
}
});
}
});
});
};
const getEdges = function(allEdges, currentNode) {
return allEdges.filter((l) => {
return (l.source.nodeId === currentNode.nodeId || l.target.nodeId === currentNode.nodeId);
});
};
const deleteEdge = function(selectedEdge, topologyId, versionId, internalFlags, edges, nodes, updateGraphMethod, setLastChange) {
let targetNodeType = selectedEdge.target.parentType === 'PROCESSOR'
? 'processors'
: 'sinks';
let promiseArr = [
TopologyREST.deleteNode(topologyId, 'edges', selectedEdge.edgeId),
TopologyREST.getNode(topologyId, versionId, targetNodeType, selectedEdge.target.nodeId),
TopologyREST.getAllNodes(topologyId, versionId, 'streams')
];
if (selectedEdge.source.currentType.toLowerCase() === 'rule' || selectedEdge.source.currentType.toLowerCase() === 'window'
|| selectedEdge.source.currentType.toLowerCase() === 'branch' || selectedEdge.source.currentType.toLowerCase() === 'projection') {
promiseArr.push(TopologyREST.getNode(topologyId, versionId, 'processors', selectedEdge.source.nodeId));
}
Promise.all(promiseArr).then((results) => {
setLastChange(results[0].timestamp);
if (selectedEdge.target.currentType.toLowerCase() === 'join') {
let joinProcessorNode = results[1];
if (_.keys(joinProcessorNode.config.properties).length > 0) {
joinProcessorNode.config.properties.joins = [];
joinProcessorNode.config.properties.from = {};
TopologyREST.updateNode(topologyId, versionId, 'processors', joinProcessorNode.id, {body: JSON.stringify(joinProcessorNode)});
}
}
if (results.length === 4) {
//Find the connected source rule/window
let rulePromises = [];
let ruleProcessorNode = results[3];
let ruleStream = results[2].entities.find((s) => {
return s.id === selectedEdge.streamGrouping.streamId;
});
let currentNodeEdges = edges.filter((obj) => {
return obj.source === selectedEdge.source && obj.streamGrouping.streamId === selectedEdge.streamGrouping.streamId;
});
let currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction";
let t = selectedEdge.source.currentType.toLowerCase();
let type = t === 'window'
? 'windows'
: (t === 'rule' || t === 'projection'
? 'rules'
: 'branchrules');
if (ruleProcessorNode.config.properties.rules) {
ruleProcessorNode.config.properties.rules.map(ruleId => {
rulePromises.push(TopologyREST.getNode(topologyId, versionId, type, ruleId));
});
}
if (selectedEdge.target.currentType.toLowerCase() === 'notification') {
currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.NotifierAction";
} else {
currentActionType = "com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction";
}
Promise.all(rulePromises).then(rulesResults => {
rulesResults.map(ruleEntity => {
let rule = ruleEntity;
if (rule.actions) {
//If source rule has target notification inside rule action,
//then remove and update the rules/window.
let index = null;
let actionObj = null;
rule.actions.map((a, i) => {
if (a.outputStreams[0] === ruleStream.streamId && a.__type === currentActionType) {
index = i;
if (currentNodeEdges.length > 0) {
if (currentActionType === 'com.hortonworks.streamline.streams.layout.component.rule.action.NotifierAction') {
let notifierActionsArr = currentNodeEdges.filter((obj) => {
return obj.target !== selectedEdge.target && obj.target.currentType.toLowerCase() === 'notification';
});
if (notifierActionsArr.length > 0) {
let targetNode = notifierActionsArr[0].target;
let stream = results[2].entities.find((s) => {
return s.id === notifierActionsArr[0].streamGrouping.streamId;
});
actionObj = {
__type: currentActionType,
name: 'notifierAction',
outputStreams: [stream.streamId],
notifierName: '',
outputFieldsAndDefaults: {}
};
}
} else if (currentActionType === 'com.hortonworks.streamline.streams.layout.component.rule.action.TransformAction') {
let transformActionsArr = currentNodeEdges.filter((obj) => {
return obj.target !== selectedEdge.target && obj.target.currentType.toLowerCase() !== 'notification';
});
if (transformActionsArr.length > 0) {
let targetNode = transformActionsArr[0].target;
let stream = results[2].entities.find((s) => {
return s.id === transformActionsArr[0].streamGrouping.streamId;
});
actionObj = {
__type: currentActionType,
name: 'transformAction',
outputStreams: [stream.streamId],
transforms: []
};
}
}
}
}
});
if (index !== null) {
if (actionObj !== null) {
rule.actions[index] = actionObj;
} else {
rule.actions.splice(index, 1);
}
TopologyREST.updateNode(topologyId, versionId, type, rule.id, {body: JSON.stringify(rule)});
}
}
});
});
}
edges.splice(edges.indexOf(selectedEdge), 1);
internalFlags.selectedEdge = null;
updateGraphMethod();
});
};
// remove edges associated with a node
const spliceLinksForNode = function(node, edges) {
let toSplice = this.getEdges(edges, node);
toSplice.map(function(l) {
edges.splice(edges.indexOf(l), 1);
});
};
const replaceSelectNode = function(d3Node, nodeData, constants, internalFlags, rectangles) {
d3Node.classed(constants.selectedClass, true);
if (internalFlags.selectedNode) {
this.removeSelectFromNode(rectangles, constants, internalFlags);
}
internalFlags.selectedNode = nodeData;
};
const removeSelectFromNode = function(rectangles, constants, internalFlags) {
rectangles.filter(function(cd) {
return cd.nodeId === internalFlags.selectedNode.nodeId;
}).classed(constants.selectedClass, false);
internalFlags.selectedNode = null;
};
const replaceSelectEdge = function(d3, d3Path, edgeData, constants, internalFlags, paths) {
d3Path.classed(constants.selectedClass, true);
if (internalFlags.selectedEdge) {
this.removeSelectFromEdge(d3, paths, constants, internalFlags);
}
internalFlags.selectedEdge = edgeData;
};
const removeSelectFromEdge = function(d3, paths, constants, internalFlags) {
let path = paths.filter(function(cd) {
return cd === internalFlags.selectedEdge;
});
let selectedPath = path[0][0];
d3.select(selectedPath.previousSibling).classed(constants.selectedClass, false);
internalFlags.selectedEdge = null;
};
const defineLinePath = function(p1, p2, flag) {
let segments = [],
sourceX = p1.x,
sourceY = p1.y,
targetX = p2.x,
targetY = p2.y;
segments.push("M" + sourceX + ',' + sourceY);
if (!flag) {
if (sourceX < targetX && sourceY === targetY) {
segments.push("H" + targetX);
} else if (sourceX > targetX) {
segments.push("H" + (sourceX + 20));
segments.push("V" + ((sourceY + targetY) / 2));
segments.push("H" + (targetX - 20));
segments.push("V" + (targetY));
segments.push("H" + (targetX));
} else {
segments.push("H" + ((sourceX + targetX) / 2));
segments.push("V" + (targetY));
segments.push("H" + (targetX));
}
} else {
segments.push("V" + (targetY));
segments.push("H" + (targetX));
}
return segments.join(' ');
};
const showNodeModal = function(ModalScope, setModalContent, node, updateGraphMethod, allNodes, edges, linkShuffleOptions) {
let currentEdges = this.getEdges(edges, node);
let scope = ModalScope(node);
setModalContent(node, updateGraphMethod, this.getConfigContainer(node, scope.configData, scope.editMode, scope.topologyId, scope.versionId, scope.namespaceId, currentEdges, allNodes, linkShuffleOptions, edges, updateGraphMethod,scope.testRunActivated),currentEdges);
};
const getConfigContainer = function(node, configData, editMode, topologyId, versionId, namespaceId, currentEdges, allNodes, linkShuffleOptions, edges, updateGraphMethod,testRunActivated) {
let nodeType = this.getNodeType(node.parentType);
let sourceNodes = [],
targetNodes = [];
currentEdges.map((e) => {
if (e.target.nodeId === node.nodeId) {
//find source node of parser
sourceNodes.push(e.source);
} else if (e.source.nodeId === node.nodeId) {
//find target node of parser
targetNodes.push(e.target);
}
});
if (node.parentType === 'SOURCE') {
return () => {
return <SourceNodeForm ref="ConfigModal" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} namespaceId={namespaceId} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions}/>;
};
} else if (node.parentType === 'SINK') {
return () => {
return <SinkNodeForm ref="ConfigModal" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} namespaceId={namespaceId} sourceNodes={sourceNodes}/>;
};
} else if (node.parentType === 'PROCESSOR') {
let childElement = null;
switch (node.currentType.toUpperCase()) {
case 'RULE': //Rule
childElement = () => {
return <RulesNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} graphEdges={edges} updateGraphMethod={updateGraphMethod}/>;
};
break;
case 'CUSTOM': //Custom
childElement = () => {
return <CustomNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes[0]} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions}/>;
};
break;
case 'NORMALIZATION': //Normalization
childElement = () => {
return <NormalizationNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges}/>;
};
break;
case 'SPLIT': //Split
childElement = () => {
return <SplitNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes[0]} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions}/>;
};
break;
case 'STAGE': //Stage
childElement = () => {
return <StageNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges}/>;
};
break;
case 'JOIN': //Join
childElement = () => {
return <JoinNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges} graphEdges={edges}/>;
};
break;
case 'WINDOW': //Windowing
childElement = () => {
return <WindowingAggregateNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes[0]} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges}/>;
};
break;
case 'BRANCH': //Branch
childElement = () => {
return <BranchNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} graphEdges={edges} updateGraphMethod={updateGraphMethod}/>;
};
break;
case 'PMML': //Pmml
childElement = () => {
return <ModelNodeForm ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId}/>;
};
break;
case 'PROJECTION': //Projection
childElement = () => {
return <ProjectionProcessorContainer ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes[0]} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges}/>;
};
break;
// case 'RT-JOIN': //RT-JOIN
// childElement = () => {
// return <RealTimeJoinNodeProcessor ref="ProcessorChildElement" nodeData={node} configData={configData} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNode={sourceNodes[0]} targetNodes={targetNodes} linkShuffleOptions={linkShuffleOptions} currentEdges={currentEdges}/>;
// };
// break;
}
return () => {
return <ProcessorNodeForm ref="ConfigModal" nodeData={node} editMode={editMode} testRunActivated={testRunActivated} nodeType={nodeType} topologyId={topologyId} versionId={versionId} sourceNodes={sourceNodes} getChildElement={childElement}/>;
};
}
};
const MouseUpAction = function(topologyId, versionId, d3node, d, metaInfo, internalFlags, constants, dragLine, paths, allNodes, edges, linkShuffleOptions, updateGraphMethod, elementType, getModalScope, setModalContent, rectangles, getEdgeConfigModal, setLastChange) {
// reset the internalFlags
internalFlags.shiftNodeDrag = false;
d3node.classed(constants.connectClass, false);
var mouseDownNode = internalFlags.mouseDownNode;
var hasSource = edges.filter((e) => {
return e.target.nodeId === d.nodeId;
});
//cannot connect from unconfigured node
if (!internalFlags.addEdgeFromNode) {
internalFlags.addEdgeFromNode = true;
return;
}
// if (!mouseDownNode) return;
// dragLine.classed("hidden", true);
if (mouseDownNode && mouseDownNode !== d) {
// we're in a different node: create new edge for mousedown edge and add to graph
if (hasSource.length && d.currentType.toLowerCase() === 'branch') {
dragLine.classed("hidden", true);
FSReactToastr.warning(
<strong>Edge cannot be connected to Branch.</strong>
);
} else {
this.createEdge(mouseDownNode, d, paths, edges, internalFlags, updateGraphMethod, topologyId, versionId, getEdgeConfigModal, setLastChange, dragLine);
}
this.updateMetaInfo(topologyId, versionId, d, metaInfo);
} else {
if (elementType === 'rectangle') {
// we're in the same node
if (internalFlags.justDragged) {
// dragged, not clicked
internalFlags.justDragged = false;
} else {
// clicked, not dragged
if (d3.event && d3.event.type === 'dblclick') {
let hasSource = edges.filter((e) => {
return e.target.nodeId === d.nodeId;
});
if (d.parentType === 'SOURCE' || hasSource.length) {
this.showNodeModal(getModalScope, setModalContent, d, updateGraphMethod, allNodes, edges, linkShuffleOptions);
} else {
FSReactToastr.warning(
<strong>Connect and configure a source component</strong>
);
}
} else {
// we're in the same node
if (internalFlags.selectedEdge) {
this.removeSelectFromEdge(d3, paths, constants, internalFlags);
}
var prevNode = internalFlags.selectedNode;
if (!prevNode || prevNode.nodeId !== d.nodeId) {
this.replaceSelectNode(d3node, d, constants, internalFlags, rectangles);
} else {
this.removeSelectFromNode(rectangles, constants, internalFlags);
}
}
}
} else if (elementType === 'circle') {
// we're in the same node
if (internalFlags.selectedEdge) {
this.removeSelectFromEdge(d3, paths, constants, internalFlags);
}
var prevNode = internalFlags.selectedNode;
if (!prevNode || prevNode.nodeId !== d.nodeId) {
this.replaceSelectNode(d3node, d, constants, internalFlags, rectangles);
} else {
this.removeSelectFromNode(rectangles, constants, internalFlags);
}
}
}
internalFlags.failedTupleDrag = false;
internalFlags.mouseDownNode = null;
return;
};
const KeyDownAction = function(d, internalFlags, allNodes, edges, linkShuffleOptions, updateGraphMethod, getModalScope, setModalContent, rectangles, constants) {
var keyDownNode = internalFlags.keyDownNode;
var hasSource = edges.filter((e) => {
return e.target.nodeId === d.nodeId;
});
if (d.parentType === 'SOURCE' || hasSource.length) {
this.showNodeModal(getModalScope, setModalContent, d, updateGraphMethod, allNodes, edges, linkShuffleOptions);
if (internalFlags.selectedNode) {
this.removeSelectFromNode(rectangles, constants, internalFlags);
}
} else {
FSReactToastr.warning(
<strong>Connect and configure a source component</strong>
);
}
internalFlags.keyDownNode = null;
internalFlags.lastKeyDown = -1;
return;
};
const setShuffleOptions = function(linkConfigArr) {
let options = [];
linkConfigArr.map((o) => {
options.push({label: o.subType, value: o.subType});
});
return options;
};
const syncNodeData = function(sources, processors, sinks, metadata, sourcesBundle, processorsBundle, sinksBundle) {
let nodeArr = [];
this.generateNodeData(sources, sourcesBundle, metadata.sources, nodeArr);
this.generateNodeData(processors, processorsBundle, metadata.processors, nodeArr);
this.generateNodeData(sinks, sinksBundle, metadata.sinks, nodeArr);
return nodeArr;
};
const capitalizeFirstLetter = function(string) {
string = string.toLowerCase();
return string.charAt(0).toUpperCase() + string.slice(1);
};
const generateNodeData = function(nodes, componentBundle, metadata, resultArr) {
for (let i = 0; i < nodes.length; i++) {
let componentObj = componentBundle.filter(c => {
return c.id === nodes[i].topologyComponentBundleId;
})[0];
let currentType = this.capitalizeFirstLetter(componentObj.subType);
let configuredFlag = _.keys(nodes[i].config.properties).length > 0
? true
: false;
if (currentType === 'Window' && _.keys(nodes[i].config.properties).length === 1) {
configuredFlag = false;
}
let currentMetaObj = metadata.filter((o) => {
return o.id === nodes[i].id;
});
if (currentMetaObj.length === 0) {
console.error("Failed to get meta data");
} else {
currentMetaObj = currentMetaObj[0];
}
let nodeLabel = componentObj.name;
if (componentObj.subType.toLowerCase() === 'custom') {
let config = componentObj.topologyComponentUISpecification.fields,
name = _.find(config, {fieldName: "name"});
nodeLabel = name.defaultValue || 'Custom';
}
let obj = {
x: currentMetaObj.x,
y: currentMetaObj.y,
nodeId: nodes[i].id,
parentType: componentObj.type,
currentType: currentType,
uiname: nodes[i].name,
imageURL: 'styles/img/icon-' + componentObj.subType.toLowerCase() + '.png',
isConfigured: configuredFlag,
parallelismCount: nodes[i].config.properties.parallelism || 1,
nodeLabel: nodeLabel,
topologyComponentBundleId: componentObj.id
};
if (currentMetaObj.streamId) {
obj.streamId = currentMetaObj.streamId;
}
resultArr.push(obj);
}
};
const syncEdgeData = function(edges, nodes) {
let edgesArr = [];
edges.map((edge) => {
//Find source node
let fromNode = nodes.filter((o) => {
return o.nodeId === edge.fromId;
});
if (fromNode.length !== 0) {
fromNode = fromNode[0];
} else {
console.error("From node is missing");
}
//Find target node
let toNode = nodes.filter((o) => {
return o.nodeId === edge.toId;
});
if (toNode.length !== 0) {
toNode = toNode[0];
} else {
console.error("To node is missing");
}
edgesArr.push({source: fromNode, target: toNode, edgeId: edge.id, streamGrouping: edge.streamGroupings[0]});
});
return edgesArr;
};
const createLineOnUI = function(edge, constants) {
let arr = [],
isFailedTupleflag = false;
if (edge.target.streamId === "failedTuplesStream") {
arr.push({
x: (edge.source.x + constants.rectangleWidth / 2),
y: (edge.source.y + constants.rectangleHeight)
}, {
x: edge.target.x,
y: (edge.target.y + constants.rectangleHeight / 2)
});
isFailedTupleflag = true;
} else {
arr.push({
x: (edge.source.x + constants.rectangleWidth),
y: (edge.source.y + constants.rectangleHeight / 2)
}, {
x: edge.target.x,
y: (edge.target.y + constants.rectangleHeight / 2)
});
}
return this.defineLinePath(arr[0], arr[1], isFailedTupleflag);
};
const getNodeRectClass = function(data) {
if (data.parentType === 'SOURCE') {
return 'source';
} else if (data.parentType === 'PROCESSOR') {
return 'processor';
} else if (data.parentType === 'SINK') {
return 'datasink';
}
};
const getNodeImgRectClass = function(data) {
if (data.parentType === 'SOURCE') {
return 'source-img';
} else if (data.parentType === 'PROCESSOR') {
return 'processor-img';
} else if (data.parentType === 'SINK') {
return 'datasink-img';
}
};
const updateParallelismCount = function(topologyId, versionId, nodeData, setLastChange) {
let currentType = this.getNodeType(nodeData.parentType);
TopologyREST.getNode(topologyId, versionId, currentType, nodeData.nodeId).then((result) => {
let data = result;
data.config.properties.parallelism = nodeData.parallelismCount;
TopologyREST.updateNode(topologyId, versionId, currentType, nodeData.nodeId, {body: JSON.stringify(data)}).then((newNodeData) => {
setLastChange(newNodeData.timestamp);
});
});
};
const topologyFilter = function(entities, filterValue,entity) {
let matchFilter = new RegExp(filterValue, 'i');
return entities.filter(filteredList => !filterValue || matchFilter.test(filteredList[entity].name));
};
const getEdgeData = function(data, topologyId, versionId, callback) {
TopologyREST.getNode(topologyId, versionId, 'streams', data.streamGrouping.streamId).then((result) => {
let obj = {
streamName: result.streamId,
grouping: data.streamGrouping.grouping,
groupingFields: data.streamGrouping.fields,
edgeData: data
};
callback(obj);
});
};
const getNodeStreams = function(topologyId, versionId, nodeId, parentType, edges, callback) {
let streamData = {
inputSchema: [],
outputSchema: []
};
let nodeType = this.getNodeType(parentType);
let promiseArr = [TopologyREST.getNode(topologyId, versionId, nodeType, nodeId)];
let connectingEdges = edges.filter((obj) => {
return obj.target.nodeId == nodeId;
});
connectingEdges.map((e) => {
promiseArr.push(TopologyREST.getNode(topologyId, versionId, 'streams', e.streamGrouping.streamId));
});
Promise.all(promiseArr).then(results => {
results.map((s, i) => {
if (i === 0 && parentType !== 'SINK') {
if (s.outputStreams.length) {
streamData.outputSchema = s.outputStreams[0].fields;
}
} else if (i > 0) {
streamData.inputSchema = [
...streamData.inputSchema,
...s.fields
];
}
});
streamData.inputSchema = _.uniqWith(streamData.inputSchema, _.isEqual);
callback(streamData);
});
};
const updateGraphEdges = function(graphEdges, newEdges) {
newEdges.map((edge) => {
let currentEdge = graphEdges.find((e) => {
return e.edgeId === edge.id;
});
currentEdge.streamGrouping = edge.streamGroupings[0];
});
};
export default {
defineMarkers,
isValidConnection,
createNode,
saveMetaInfo,
updateMetaInfo,
removeNodeFromMeta,
createEdge,
getNodeType,
deleteNode,
deleteEdge,
getEdges,
spliceLinksForNode,
replaceSelectNode,
removeSelectFromNode,
replaceSelectEdge,
removeSelectFromEdge,
defineLinePath,
showNodeModal,
getConfigContainer,
MouseUpAction,
KeyDownAction,
setShuffleOptions,
syncNodeData,
capitalizeFirstLetter,
generateNodeData,
syncEdgeData,
createLineOnUI,
getNodeRectClass,
getNodeImgRectClass,
updateParallelismCount,
topologyFilter,
getEdgeData,
getNodeStreams,
updateGraphEdges,
spliceDeleteNodeArr
};
|
imports/ui/components/DocumentEditor.js | GreatFallz/base | /* eslint-disable max-len, no-return-assign */
import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
import documentEditor from '../../modules/document-editor.js';
export default class DocumentEditor extends React.Component {
componentDidMount() {
documentEditor({ component: this });
setTimeout(() => { document.querySelector('[name="title"]').focus(); }, 0);
}
render() {
const { doc } = this.props;
return (<form
ref={ form => (this.documentEditorForm = form) }
onSubmit={ event => event.preventDefault() }
>
<FormGroup>
<ControlLabel>Title</ControlLabel>
<FormControl
type="text"
name="title"
defaultValue={ doc && doc.title }
placeholder="Oh, The Places You'll Go!"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Body</ControlLabel>
<FormControl
componentClass="textarea"
name="body"
defaultValue={ doc && doc.body }
placeholder="Congratulations! Today is your day. You're off to Great Places! You're off and away!"
/>
</FormGroup>
<Button type="submit" bsStyle="success">
{ doc && doc._id ? 'Save Changes' : 'Add Document' }
</Button>
</form>);
}
}
DocumentEditor.propTypes = {
doc: PropTypes.object,
};
|
stories/LanguagePicker/index.js | skyiea/wix-style-react | import React from 'react';
import {storiesOf} from '@storybook/react';
import Markdown from '../utils/Components/Markdown';
import AutoDocs from '../utils/Components/AutoDocs';
import CodeExample from '../utils/Components/CodeExample';
import ReadmeTestkit from '../../src/LanguagePicker/README.TESTKIT.md';
import LanguagePickerSource from '!raw-loader!wix-style-react/LanguagePicker/LanguagePicker';
import TabbedView from '../utils/Components/TabbedView';
import Example from './Example';
import ExampleRaw from '!raw-loader!./Example';
storiesOf('Core', module)
.add('LanguagePicker', () => (
<TabbedView tabs={['API', 'Testkit']}>
<div>
<AutoDocs source={LanguagePickerSource}/>
<h1>Usage examples</h1>
<CodeExample title="Example" code={ExampleRaw}>
<Example/>
</CodeExample>
</div>
<Markdown source={ReadmeTestkit}/>
</TabbedView>
));
|
src/js/mixins/form/form_error_handler_mixin.js | rafaelfbs/realizejs | import React from 'react';
import _ from 'lodash';
import i18n from '../../i18n/i18n';
import PropTypes from '../../prop_types';
import { FormActions } from '../../actions';
import Flash from '../../components/flash/flash';
export default {
propTypes: {
errorMessage: PropTypes.string,
baseErrorParam: PropTypes.string,
onError: PropTypes.func,
mapping: PropTypes.bool,
},
getDefaultProps() {
return {
errorMessage: i18n.t('errors.formErrorMessage'),
baseErrorParam: 'base',
onError() { return true; },
mapping: true,
};
},
getInitialState() {
return {
errors: {},
};
},
clearErrors() {
this.setState({ errors: {} });
},
handleValidationError(xhr) {
this.setState({ errors: this.getParsedErrors(xhr.responseText) });
},
getParsedErrors(errors) {
const parsedErrors = JSON.parse(errors);
if (this.props.mapping) {
return this.mapParsedErrors(parsedErrors);
} else {
return parsedErrors;
}
},
mapParsedErrors(parsedErrors) {
return Object.keys(parsedErrors)
.reduce((acc, k) => Object.assign({}, acc, { [k.split('.').pop()]: parsedErrors[k] }), {});
},
handleError(xhr, status, error) {
this.setState({ isLoading: false });
FormActions.error(this.props.id, xhr, status, error);
if (this.props.onError(xhr, status, error) && (xhr.status === 422)) {
this.handleValidationError(xhr);
}
},
renderBaseErrorsListItems(baseErrors) {
return baseErrors.map((baseError) => (
<li key={baseError}>{baseError}</li>
));
},
renderBaseErrorsList() {
const baseErrors = this.state.errors[this.props.baseErrorParam];
if (!baseErrors) return <span />;
return (
<ul>
{this.renderBaseErrorsListItems(baseErrors)}
</ul>
);
},
renderFlashErrorMessage() {
return (
<div>
{this.props.errorMessage}
{this.renderBaseErrorsList()}
</div>
);
},
renderFlashErrors() {
if (_.isEmpty(this.state.errors)) return <span />;
return (
<Flash
type="error"
message={this.renderFlashErrorMessage()}
dismissed={false}
/>
);
},
};
|
web/src/components/SearchBar.js | blacktop/scifgif | import React from 'react';
class SearchBar extends React.Component {
state = { term: '' };
onFormSubmit = event => {
event.preventDefault();
this.props.onSubmit(this.state.term);
};
render() {
return (
<div className="ui segment search-bar">
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<input
className={"form-control mr-sm-2"}
type="text"
placeholder={"Search"}
aria-label={"Search"}
value={this.state.term}
onChange={e => this.setState({ term: e.target.value })}
/>
</div>
</form>
</div>
);
}
}
export default SearchBar;
|
app/components/Footer/index.js | jdm85kor/sentbe | import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from 'components/A';
import LocaleToggle from 'containers/LocaleToggle';
import Wrapper from './Wrapper';
import messages from './messages';
function Footer() {
return (
<Wrapper>
<section>
<FormattedMessage {...messages.licenseMessage} />
</section>
<section>
<LocaleToggle />
</section>
<section>
<FormattedMessage
{...messages.authorMessage}
values={{
author: <A href="https://twitter.com/mxstbr">Max Stoiber</A>,
}}
/>
</section>
</Wrapper>
);
}
export default Footer;
|
assets/javascripts/kitten/components/form/field/components/checkbox.js | KissKissBankBank/kitten | import React from 'react'
import { Checkbox } from '../../../form/checkbox'
export const FieldCheckbox = props => <Checkbox {...props} />
|
src/app.js | townmi/ReactExamples | /**
* @Created by Administrator
* @Date 2015/12/14.
* @author [[email protected]]
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import App from './root';
const MOUNT_NODE = document.getElementById('reactApp');
let render = () => {
const routes = require('./routes/index').default();
ReactDOM.render(
<App routes={routes}/>,
MOUNT_NODE
)
};
render(); |
src/js/CreateStepper/Content/BasicDataForm/TagList.js | ludonow/ludo-beta-react | import React from 'react';
import styled from 'styled-components';
import DeleteIcon from 'material-ui/svg-icons/action/delete-forever';
import { grey200 } from 'material-ui/styles/colors';
import { CustomScrollBarCSS } from '../../../baseStyle';
// styled components
const DeleteIconWrapper = styled.div`
align-items: center;
display: flex;
`;
const TagListWrapper = styled.div`
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 0 auto;
max-height: 70px;
overflow: auto;
width: 50%;
${CustomScrollBarCSS}
`;
const TagWrapper = styled.div`
background-color: rgba(0, 0, 0, 0.6);
display: inline-flex;
margin: 5px;
`;
const TagText = styled.div`
display: inline-flex;
color: white;
overflow: auto;
padding: 5px;
${CustomScrollBarCSS}
`;
// override material-ui
const deleteIconStyle = {
height: '20px',
width: '20px',
};
const Tag = ({
handleTagDelete,
id,
text,
}) => (
<TagWrapper>
<TagText>
#{text}
</TagText>
<DeleteIconWrapper>
<DeleteIcon
color={grey200}
data-id={id}
onTouchTap={handleTagDelete}
style={deleteIconStyle}
/>
</DeleteIconWrapper>
</TagWrapper>
);
const TagList = ({
handleTagDelete,
tagList,
}) => {
return (
<TagListWrapper>
{
tagList ?
tagList.map((tag, index) => (
<Tag
handleTagDelete={handleTagDelete}
id={index}
key={`create-card-tag-${index}`}
text={tag}
/>
))
: null
}
</TagListWrapper>
);
}
export default TagList; |
client/sidebar/Item/skeletons/CondensedSkeleton.js | VoiSmart/Rocket.Chat | import { Box, Skeleton } from '@rocket.chat/fuselage';
import React from 'react';
import Condensed from '../Condensed';
const CondensedSkeleton = ({ showAvatar }) => (
<Box height='x28'>
<Condensed
title={<Skeleton width='100%' />}
titleIcon={<Box mi='x4'>{<Skeleton width={12} />}</Box>}
avatar={showAvatar && <Skeleton variant='rect' width={16} height={16} />}
/>
</Box>
);
export default CondensedSkeleton;
|
src/svg-icons/image/palette.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePalette = (props) => (
<SvgIcon {...props}>
<path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
ImagePalette = pure(ImagePalette);
ImagePalette.displayName = 'ImagePalette';
export default ImagePalette;
|
src/home/Table.js | zhangxin840/mobile-env | import React, { Component } from 'react';
import _ from 'lodash';
import { Case } from './Case';
import { CaseCount } from './CaseCount';
var Browsers = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
},
render: function() {
var browsers = [];
for(var key in this.props.data){
browsers.push(
<span key={key} className="cell browser">
{this.props.data[key].name}
</span>
);
}
return (
<div className="row">
<span className="spacer"> </span>
<div className="wrapper browsers">
{browsers}
</div>
</div>
);
}
});
var Row = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
},
render: function() {
var cases = [];
// console.log("rendering row:", this.props.data);
for(var key in this.props.browsers){
if(this.props.type === 'issues'){
cases.push(
<Case key={this.props.device + "-" + key} browser={key} device={this.props.device} data={this.props.rowCases[key]} />
);
}else{
cases.push(
<CaseCount key={this.props.device + "-" + key} browser={key} device={this.props.device} data={this.props.rowCases[key]} />
);
}
}
return (
<div className="row">
<span className="spacer name">{this.props.name}</span>
<div className="wrapper cases">
{cases}
</div>
</div>
);
}
});
var Rows = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
},
render: function() {
var rows = [];
for(var key in this.props.devices){
rows.push(
<Row key={key} device={key} type={this.props.type} browsers={this.props.browsers} name={this.props.devices[key].name} rowCases={this.props.cases[key]}/>
);
}
rows.sort((a, b) => {
return this.props.devices[b.props.device].ratio - this.props.devices[a.props.device].ratio;
});
return (
<div className="rows">
{rows}
</div>
);
}
});
var Table = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
},
render: function() {
return (
<div className="table">
<Browsers data={this.props.browsers} />
<Rows {...this.props} />
</div>
);
}
});
export { Table };
|
docs/src/app/components/pages/components/Paper/ExampleSimple.js | igorbt/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleSimple = () => (
<div>
<Paper style={style} zDepth={1} />
<Paper style={style} zDepth={2} />
<Paper style={style} zDepth={3} />
<Paper style={style} zDepth={4} />
<Paper style={style} zDepth={5} />
</div>
);
export default PaperExampleSimple;
|
githubApp/js/Boy.js | anchoretics/ztf-work-app | /**
* Created by lingfengliang on 2017/3/13.
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity
} from 'react-native';
import Girl from './Girl';
import NavigationBar from './Components/NavigationBar';
export default class Boy extends Component{
constructor(props){
super(props)
this.state = {
word: ''
}
}
render(){
let word = this.state.word;
return(
<View style={styles.container}>
<NavigationBar title={"Boy"} statusBar={{
backgroundColor: 'green'
}} style={{backgroundColor: 'green'}}></NavigationBar>
<Text style={styles.text}>I am a Boy</Text>
<Text style={styles.text} onPress={()=>{
this.props.navigator.push({
component: Girl,
params: {
word: '一只玫瑰',
onCallBack: (word)=>{
this.setState({
word: word
})
}
}
});
}}>送女孩一只玫瑰</Text>
<Text style={styles.text}>{word}</Text>
</View>)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'gray',
},
text: {
fontSize: 20,
}
}) |
public/src/routes/routes.js | white87332/react-redux-sample | import React from 'react';
import { Router, Route } from 'react-router';
import * as postsActions from '../actions/postsActions';
// async load component
const async = bundle => (location, callback) =>
{
bundle((component) =>
{
callback(null, component.default);
});
};
const postsListInit = (store, dispatch) =>
{
return (nextState, replace, next) =>
{
// dispatch(postsActions.postsList()).then((data) =>
dispatch(postsActions.postsList()).then(() =>
{
next();
});
};
};
export default function createRoutes(history, store, dispatch)
{
return (
<Router history={history}>
<Route component={require('../components/main/main').default}>
<Route path="/" getComponent={async(require('bundle?name=counter&lazy!../containers/counter/counter'))} />
<Route getComponent={async(require('bundle?name=layout&lazy!../components/layout/layout'))}>
<Route path="/selectItems" getComponent={async(require('bundle?name=selectItems&lazy!../containers/selectItems/selectItems'))} />
<Route path="/drag" getComponent={async(require('bundle?name=drag&lazy!../containers/drag/drag'))} />
<Route path="/dnd" getComponent={async(require('bundle?name=dnd&lazy!../containers/dnd/dnd'))} />
<Route path="/transMotion" getComponent={async(require('bundle?name=transMotion&lazy!../containers/transMotion/transMotion'))} />
<Route path="/sortable" getComponent={async(require('bundle?name=sortable&lazy!../containers/sortable/sortable'))} />
<Route path="/draggableBalls" getComponent={async(require('bundle?name=draggableBalls&lazy!../containers/draggableBalls/draggableBalls'))} />
<Route path="/posts" getComponent={async(require('bundle?name=posts&lazy!../containers/posts/posts'))} onEnter={postsListInit(store, dispatch)} />
<Route path="/donut" getComponent={async(require('bundle?name=donut&lazy!../containers/donut/donut'))} />
<Route path="/slider" getComponent={async(require('bundle?name=slider&lazy!../containers/slider/slider'))} />
<Route path="/areaChart" getComponent={async(require('bundle?name=areaChart&lazy!../containers/areaChart/areaChart'))} />
<Route path="/calendar" getComponent={async(require('bundle?name=calendar&lazy!../containers/calendar/calendar'))} />
</Route>
</Route>
</Router>
);
}
|
public/components/DevTools.js | datpham23/tinder-wingman | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
defaultIsVisible={false}
toggleVisibilityKey='ctrl-e'
changePositionKey='ctrl-q'>
<LogMonitor />
</DockMonitor>
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.