path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
react_version/src/AppHeader/AppHeader.js | maju435/drozdz | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './AppHeader.css';
import { Link } from 'react-router-dom';
class AppHeader extends Component {
render() {
return (
<header className="App-header">
<nav className="main-nav">
<div className="main-nav-left">
<ul>
<li><Link to="/"><span>Główna</span></Link></li>
<li><Link to="/galery"><span>Galeria</span></Link></li>
<li><Link to="/contact"><span>Kontakt</span></Link></li>
</ul>
</div>
<div className="main-nav-right">
<ul>
<li style={{ float: "right" }} ><a href="#0"><span>Zarejestruj</span></a></li>
<li style={{ float: "right" }} ><a href="#0"><span>Zaloguj</span></a></li>
</ul>
</div>
</nav>
</header>
);
}
}
AppHeader.propTypes = {
};
export default AppHeader; |
src/components/metadata/MetaArray.js | ashmaroli/jekyll-admin | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Sortable from 'sortablejs';
import _ from 'underscore';
import MetaArrayItem from './MetaArrayItem';
export class MetaArray extends Component {
sortableGroupDecorator(component) {
const { moveArrayItem, namePrefix } = this.props;
if (component) {
const options = {
draggable: '.array-item-wrap',
group: { name: 'meta-array-items', pull: false, put: false },
handle: '.move',
animation: 0,
onEnd: (e) => {
let srcInd = e.item.getAttribute('data-id');
moveArrayItem(namePrefix, srcInd, e.newIndex);
}
};
Sortable.create(component, options);
}
}
render() {
const { fieldKey, fieldValue, namePrefix, addField,
removeField, updateFieldKey, updateFieldValue, moveArrayItem,
convertField, key_prefix, appMeta} = this.props;
const items = _.map(fieldValue, (item, i) => {
let type = 'simple';
if (_.isObject(item)) type = 'object';
if (_.isArray(item)) type = 'array';
return (
<MetaArrayItem
key={`${key_prefix}-${i}`}
key_prefix={key_prefix}
index={i}
fieldKey={fieldKey}
fieldValue={item}
type={type}
addField={addField}
removeField={removeField}
updateFieldKey={updateFieldKey}
updateFieldValue={updateFieldValue}
moveArrayItem={moveArrayItem}
convertField={convertField}
nameAttr={`${namePrefix}[${i}]`}
namePrefix={namePrefix}
appMeta={appMeta} />
);
});
return (
<div className="meta-value-array" ref={this.sortableGroupDecorator.bind(this)}>
{items}
<a onClick={() => addField(namePrefix)}
className="add-field-array" title="Add new list item">
<i className="fa fa-plus" />
</a>
</div>
);
}
}
MetaArray.propTypes = {
fieldKey: PropTypes.string.isRequired,
fieldValue: PropTypes.any.isRequired,
nameAttr: PropTypes.string.isRequired,
namePrefix: PropTypes.string.isRequired,
addField: PropTypes.func.isRequired,
removeField: PropTypes.func.isRequired,
updateFieldKey: PropTypes.func.isRequired,
updateFieldValue: PropTypes.func.isRequired,
convertField: PropTypes.func.isRequired,
moveArrayItem: PropTypes.func.isRequired,
key_prefix: PropTypes.string.isRequired,
appMeta: PropTypes.object
};
export default MetaArray;
|
components/list/ListItemActions.js | KerenChandran/react-toolbox | import React from 'react';
import style from './style';
import ListItemAction from './ListItemAction';
const ListItemActions = ({type, children}) => {
const validChildren = React.Children.toArray(children).filter(c => (
React.isValidElement(c)
));
return (
<span className={style[type]}>
{validChildren.map((action, i) => <ListItemAction key={i} action={action} />)}
</span>
);
};
ListItemActions.propTypes = {
children: React.PropTypes.any,
type: React.PropTypes.oneOf(['left', 'right'])
};
export default ListItemActions;
|
src/js/components/PasswordInput.js | kylebyerly-hp/grommet | // (C) Copyright 2014 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../utils/CSSClassnames';
import Button from './Button';
import ViewIcon from './icons/base/View';
import Intl from '../utils/Intl';
const CLASS_ROOT = CSSClassnames.PASSWORD_INPUT;
const INPUT = CSSClassnames.INPUT;
export default class PasswordInput extends Component {
constructor() {
super();
this.state = {
showPassword: false
};
}
render () {
const { className, ...rest } = this.props;
const { showPassword } = this.state;
const { intl } = this.context;
let classes = classnames(
CLASS_ROOT,
className
);
return (
<div className={classes}>
<input {...rest} ref={ref => this.inputRef = ref}
type={showPassword ? 'text' : 'password'}
className={`${INPUT} ${CLASS_ROOT}__input`} />
<Button className={`${CLASS_ROOT}__control`}
a11yTitle={Intl.getMessage(intl, 'Show Password')}
icon={
<ViewIcon colorIndex={showPassword ? 'brand' : undefined} />
}
onClick={() => this.setState({
showPassword: !this.state.showPassword })
} />
</div>
);
}
}
PasswordInput.propTypes = {
className: PropTypes.string
};
PasswordInput.contextTypes = {
intl: PropTypes.object
};
|
react-fundamental/src/components/LifeCycle.js | zhangfaliang/learnReact | import React, { Component } from 'react';
class LifeCycle extends Component {
static defaultProps = {
value: '开始渲染'
}
componentWillReceiveProps(nextProps){
console.log('componentWillReceiveProps');
this.setState({
value: nextProps.value
});
}
/**
* diff 数据对比
* 对比完成,如果数据没有差异,不更新
* return false
* @param {[type]} nextProps [description]
* @param {[type]} nextState [description]
* @return {[type]} [description]
*/
shouldComponentUpdate(nextProps,nextState){
console.log('shouldComponentUpdate');
return true;
}
componentWillUpdate(nextProps,nextState){
console.log('componentWillUpdate');
}
componentWillMount(){
console.log('componentWillMount');
}
render() {
console.log('render');
return <span>{this.props.value}</span>
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate(prevProps,prevState) {
console.log('componentDidUpdate');
}
componentWillUnmount(prevProps,prevState) {
console.log('componentWillUnmount');
}
}
export default LifeCycle;
|
index.ios.js | t4sk/react-native-todo | /**
* 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 Todo 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('Todo', () => Todo);
|
template/src/Component.js | nkbt/cf-react-component-template | import React from 'react';
export const {{package.global}} = () =>
<div>{{package.name}}</div>;
|
docs/src/app/components/pages/customization/Styles.js | IsenrichO/mui-with-arrows | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../CodeExample';
import MarkdownElement from '../../MarkdownElement';
import stylesText from './styles.md';
import stylesOverridingInlineText from './styles-overriding-inline.md';
import StylesOverridingInlineExample from './StylesOverridingInlineExample';
import stylesOverridingInlineExampleCode from '!raw!./StylesOverridingInlineExample';
import stylesOvveridingCssText from './styles-overriding-css.md';
import StylesOverridingCssExample from './StylesOverridingCssExample';
import stylesOvveridingCssExampleCode from '!raw!./StylesOverridingCssExample';
const stylesOvveridingCssExampleCodeWithCss = `${stylesOvveridingCssExampleCode}
/*
With the following css style:
.styles-overriding-css-example {
width: 50% !important;
margin: 0 auto !important;
border: 2px solid #FF9800 !important;
background-color: #ffd699 !important;
}
*/
`;
const Styles = () => (
<div>
<Title render={(previousTitle) => `Styles - ${previousTitle}`} />
<MarkdownElement text={stylesText} />
<MarkdownElement text={stylesOverridingInlineText} />
<CodeExample
title="Inline Style example"
code={stylesOverridingInlineExampleCode}
component={false}
>
<StylesOverridingInlineExample />
</CodeExample>
<MarkdownElement text={stylesOvveridingCssText} />
<CodeExample
title="CSS Style example"
code={stylesOvveridingCssExampleCodeWithCss}
component={false}
>
<StylesOverridingCssExample />
</CodeExample>
</div>
);
export default Styles;
|
src/layouts/Header/containers/HeaderContainer.js | dkanas/timelog | import React from 'react'
import { connect } from 'react-redux'
import pick from 'lodash/pick'
import { logout } from 'store/sessionModule'
import Header from '../components/Header'
const Connect = connect(
state => pick(state.session, ['user', 'isAuthenticated']),
{ logout }
)
const HeaderContainer = ({ isAuthenticated, user, logout }) => (
<Header
logout={logout}
isAuthenticated={isAuthenticated}
user={user} />
)
export default Connect(HeaderContainer)
|
example-swift/ReactNativeEventBridgeSwift/ReactNative/index.ios.js | maicki/react-native-event-bridge | /**
* @flow
*/
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
Alert,
EmitterSubscription,
} from 'react-native';
import EventBridge from 'react-native-event-bridge';
export default class ReactNativeEventBridgeSwift extends React.Component {
_eventSubscription: ?EmitterSubscription;
static contextTypes = {
rootTag: React.PropTypes.number,
};
componentDidMount() {
this._eventSubscription = EventBridge.addEventListener(
this,
// eslint-disable-next-line no-unused-vars
(name, info) => {
Alert.alert('Native Event', 'Received Event from Native');
}
);
}
componentWillUnmount() {
if (this._eventSubscription) {
this._eventSubscription.remove();
}
}
buttonClicked = () => {
// Emit an event from within a React component
EventBridge.emitEvent(this, 'Event');
};
buttonClickedCallback = () => {
// Emit an event with callback from within a React component
EventBridge.emitEventCallback(this, 'EventWithCallback', () => {
Alert.alert('Callback Response', 'Some Callback Response');
});
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native Event Bridge!
</Text>
<Button onPress={this.buttonClicked} title="Send RN Event" />
<Button
onPress={this.buttonClickedCallback}
title="Send RN Event With Callback"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent(
'ReactNativeEventBridgeSwift',
() => ReactNativeEventBridgeSwift
);
|
app/components/Header/index.js | juanda99/arasaac-frontend | /**
*
* Header
*
*/
import React from 'react'
import PropTypes from 'prop-types'
import AppBar from 'material-ui/AppBar'
import styles from './styles'
import Title from './Title'
import UserMenu from './UserMenu'
import GuestMenu from './GuestMenu'
const Header = (props) => {
const handleTouchTapLeftIconButton = () => {
props.touchTapLeftIconButton()
}
const {
isAuthenticated,
showMenuIconButton,
title,
isTranslating,
changeLocale,
signout,
isMobile,
role
} = props
return (
<div style={{ position: 'relative' }}>
<AppBar
onLeftIconButtonTouchTap={handleTouchTapLeftIconButton}
title={<Title docked={props.docked}>{title}</Title>}
zDepth={0}
id='header'
style={styles.appBar}
showMenuIconButton={showMenuIconButton}
iconElementRight={
isAuthenticated ? (
<UserMenu
isTranslating={isTranslating}
changeLocale={changeLocale}
signout={signout}
role={role}
/>
) : (
<GuestMenu isMobile={isMobile} />
)
}
/>
{/* <div style={{ position: 'absolute', margin: 10, left: '50px', color: 'white', top: 0, zIndex: 14000 }}>
<h1 style={{ display: 'inline' }}>ARASAAC</h1>
</div> */}
</div>
)
}
Header.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
// we use it both for menu icon and for
showMenuIconButton: PropTypes.bool.isRequired,
// será un string
title: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.object.isRequired
]),
docked: PropTypes.bool.isRequired,
changeLocale: PropTypes.func.isRequired,
signout: PropTypes.func.isRequired,
touchTapLeftIconButton: PropTypes.func.isRequired,
isTranslating: PropTypes.bool.isRequired,
isMobile: PropTypes.bool.isRequired,
role: PropTypes.string
}
export default Header
|
src/server.js | GustavPersson/tvattstuga | import path from 'path';
import morgan from 'morgan';
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createMemoryHistory, match, RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import chalk from 'chalk';
import createRoutes from './routes';
import configureStore from './redux/store';
import { createSelectLocationState } from './util/helpers';
import renderHtmlPage from './util/renderHtmlPage';
import config from './config';
const app = express();
// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());
// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(favicon(path.join(process.cwd(), './public/favicon.ico')));
app.use(express.static(path.join(process.cwd(), './public')));
// Run express as webpack dev server
if (__DEV__) {
const webpack = require('webpack');
const webpackConfig = require('../tools/webpack/config.babel');
const compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
noInfo: true,
stats: { colors: true },
}));
app.use(require('webpack-hot-middleware')(compiler));
}
// Register server-side rendering middleware
app.get('*', (req, res) => {
if (__DEV__) webpackIsomorphicTools.refresh();
const store = configureStore();
// If __DISABLE_SSR__ = true, disable server side rendering
if (__DISABLE_SSR__) {
res.send(renderHtmlPage(store));
return;
}
const memoryHistory = createMemoryHistory(req.url);
const routes = createRoutes(store);
const history = syncHistoryWithStore(memoryHistory, store, {
selectLocationState: createSelectLocationState('routing'),
});
// eslint-disable-next-line max-len
match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (!renderProps) {
res.sendStatus(404);
} else {
// Dispatch the initial action of each container first
const promises = renderProps.components
.filter(component => component.fetchData)
.map(component => component.fetchData(store.dispatch, renderProps.params));
// Then render the routes
Promise.all(promises)
.then(() => {
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>,
);
res.status(200).send(renderHtmlPage(store, content));
})
.catch((err) => {
console.error(`==> 😭 Rendering routes error: ${err}`);
})
.catch((err) => {
console.error(`==> 😭 Rendering routes error: ${err}`);
});
}
});
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) console.error(`==> 😭 OMG!!! ${err}`);
console.info(chalk.green(`==> 🌎 Listening at http://${config.host}:${config.port}`));
console.info(chalk.green(`==> 🌎 Server info ${config.host}:${config.port} ${process.env.NODE_ENV}`));
});
} else {
console.error(chalk.red('==> 😭 OMG!!! No PORT environment variable has been specified'));
}
|
src/Row.js | omerts/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Row = React.createClass({
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'row')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Row;
|
src/svg-icons/hardware/laptop-mac.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopMac = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
HardwareLaptopMac = pure(HardwareLaptopMac);
HardwareLaptopMac.displayName = 'HardwareLaptopMac';
HardwareLaptopMac.muiName = 'SvgIcon';
export default HardwareLaptopMac;
|
src/public/js/logs.js | TooAngel/democratic-collaboration | import React from 'react';
/**
* Logs class
**/
export class Logs extends React.Component { // eslint-disable-line no-unused-vars
/**
* contructor - The constructor
*
* @param {object} props - The properties
* @return {void}
**/
constructor(props) {
super(props);
this.state = {
dataFromServer: [],
};
this.initWS = this.initWS.bind(this);
}
/**
* componentDidUpdate - When the component updated
*
* @return {void}
**/
componentDidUpdate() {
this.node.scrollTop = this.node.scrollHeight;
}
/**
* initWS - Initializes the websocket connection
*
* @return {void}
**/
initWS() {
let protocol = 'wss';
if (window.location.protocol === 'http:') {
protocol = 'ws';
}
const url = `${protocol}://${window.location.hostname}:${window.location.port}/admin/logs`;
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log('connected');
};
this.ws.onmessage = (event) => {
const dataFromServer = this.state.dataFromServer;
dataFromServer.push(event.data);
if (dataFromServer.length > 100) {
dataFromServer.shift();
}
this.setState({dataFromServer: dataFromServer});
};
this.ws.onclose = () => {
console.log('disconnected');
this.initWS();
};
}
/**
* componentDidMount - on build of the component
*
* @return {void}
**/
componentDidMount() {
this.initWS();
}
/**
* render - renders
* @return {object} - The element to be renderd
**/
render() {
const lines = [];
for (let i=0; i<this.state.dataFromServer.length; i++) {
lines.push(<li key={i}>{this.state.dataFromServer[i]}</li>);
}
const ulStyle = {
listStyleType: 'none',
paddingLeft: '0px',
};
return <div className="log" ref={(node) => {
this.node = node;
}}><ul style={ulStyle}>{ lines }</ul></div>;
}
}
|
src/components/file/upload.js | abbr/ShowPreper | import React from 'react'
import ReactDOM from 'react-dom'
module.exports = class Importer extends React.Component {
click = () => {
let domEle = ReactDOM.findDOMNode(this)
domEle.value = null
domEle.click()
}
onChange = e => {
let file = e.target.files[0]
// TODO validate file mime type
if (file != null) {
let reader = new FileReader()
reader.onload = function(e) {
// TODO parse files
this.props.onNewDeck(file.name, JSON.parse(e.target.result))
}.bind(this)
reader.readAsText(file)
}
}
render() {
return (
<input
type="file"
style={{ display: 'none' }}
accept=".spj"
onChange={this.onChange}
/>
)
}
}
|
react-dixie-memory-considerate-loading/src/components/SwitchWithLabel/index.js | GoogleChromeLabs/adaptive-loading | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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 Toggle from 'react-toggle'; // TODO: update -> deprecated lifecyle usage detected
import 'react-toggle/style.css';
import './switch-with-label.css';
const SwitchWithLabel = ({ label, ...rest }) => (
<div className='switch-with-label'>
<Toggle {...rest}/>
<label>
{label}
</label>
</div>
);
export default SwitchWithLabel;
|
src/svg-icons/image/wb-sunny.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbSunny = (props) => (
<SvgIcon {...props}>
<path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
</SvgIcon>
);
ImageWbSunny = pure(ImageWbSunny);
ImageWbSunny.displayName = 'ImageWbSunny';
ImageWbSunny.muiName = 'SvgIcon';
export default ImageWbSunny;
|
app/features/notifications/Notify/index.js | Kaniwani/KW-Frontend | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createPortal } from 'react-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { POSITIONS } from '../constants';
import actions from '../actions';
import Notification from '../Notification';
import { Container, Wrapper } from './styles';
export class Notify extends React.PureComponent {
static propTypes = {
notifications: PropTypes.array.isRequired,
remove: PropTypes.func.isRequired,
transitionDurations: PropTypes.shape({
enter: PropTypes.number,
exit: PropTypes.number,
}),
position: PropTypes.string,
node: PropTypes.any,
};
static defaultProps = {
transitionDurations: {
enter: 160,
exit: 240,
},
position: POSITIONS.TOP_RIGHT,
};
componentWillUnmount() {
if (this.defaultNode) {
document.body.removeChild(this.defaultNode);
}
this.defaultNode = null;
}
handleDismiss = (id) => {
this.props.remove(id);
};
renderNotification() {
const { notifications, transitionDurations, position, ...props } = this.props;
return (
<TransitionGroup component={Container} position={position}>
{notifications.map((notification, index) => (
// eslint-disable-next-line react/no-array-index-key
<CSSTransition classNames="slide" key={index} timeout={transitionDurations}>
<Wrapper>
<Notification
key={notification.id}
{...props}
{...notification}
handleDismiss={this.handleDismiss}
/>
</Wrapper>
</CSSTransition>
))}
</TransitionGroup>
);
}
render() {
if (!this.props.node && !this.defaultNode) {
/* eslint-disable no-undef */
this.defaultNode = document.createElement('div');
document.body.appendChild(this.defaultNode);
}
return createPortal(this.renderNotification(), this.props.node || this.defaultNode);
}
}
const mapStateToProps = (state) => ({
notifications: state.notifications,
});
const mapDispatchToProps = {
remove: actions.remove,
};
export default connect(mapStateToProps, mapDispatchToProps)(Notify);
|
app/components/LoadingIndicator/index.js | chaintng/react-boilerplate | import React from 'react';
import Circle from './Circle';
import Wrapper from './Wrapper';
const LoadingIndicator = () => (
<Wrapper>
<Circle />
<Circle rotate={30} delay={-1.1} />
<Circle rotate={60} delay={-1} />
<Circle rotate={90} delay={-0.9} />
<Circle rotate={120} delay={-0.8} />
<Circle rotate={150} delay={-0.7} />
<Circle rotate={180} delay={-0.6} />
<Circle rotate={210} delay={-0.5} />
<Circle rotate={240} delay={-0.4} />
<Circle rotate={270} delay={-0.3} />
<Circle rotate={300} delay={-0.2} />
<Circle rotate={330} delay={-0.1} />
</Wrapper>
);
export default LoadingIndicator;
|
src/components/Account/OAuthLogin/OAuthLogin.container.js | shayc/cboard | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FormattedMessage, injectIntl, intlShape } from 'react-intl';
import { login } from '../Login/Login.actions';
import messages from './OAuthLogin.messages';
import { getUser } from '../../App/App.selectors';
import './OAuthLogin.css';
class OAuthLoginContainer extends React.Component {
static propTypes = {
intl: intlShape.isRequired,
user: PropTypes.object,
login: PropTypes.func
};
constructor(props) {
super(props);
const {
match: {
params: { type }
},
location: { search: query },
history
} = this.props;
this.type = type;
this.query = query;
this.hasErrors = query.indexOf('error=') >= 0;
if (this.hasErrors) {
setTimeout(() => {
history.replace('/');
}, 3000);
}
}
componentDidMount() {
if (!this.checkUser()) {
this.props.login({ email: this.type, password: this.query }, this.type);
}
}
componentDidUpdate() {
this.checkUser();
}
checkUser() {
const { history, user } = this.props;
if (user.email) {
history.replace('/');
}
return !!user.email;
}
render() {
return (
<div className="OAuthContainer">
{!this.hasErrors && <FormattedMessage {...messages.loading} />}
{this.hasErrors && <FormattedMessage {...messages.errorMessage} />}
</div>
);
}
}
const mapStateToProps = state => ({
user: getUser(state)
});
const mapDispatchToProps = {
login
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(injectIntl(OAuthLoginContainer));
|
src/components/Buttons/Switch.js | instacart/Snacks | import React from 'react'
import PropTypes from 'prop-types'
import RadioCheckboxBase from '../../base/RadioCheckboxBase'
import colors from '../../styles/colors'
import ZeroSvg from '../../assets/zero.svg'
import OneSvg from '../../assets/one.svg'
const SWITCH_WIDTH = 36
const STYLES = {
background: {
borderRadius: '11px',
position: 'relative',
transition: 'background-color 200ms ease-in-out',
},
toggle: {
default: {
height: '18px',
width: '18px',
backgroundColor: colors.WHITE,
borderRadius: '50%',
display: 'block',
position: 'absolute',
top: '2px',
left: '2px',
transition: 'left 200ms ease-in-out',
},
selected: {
left: '16px',
},
},
zero: {
position: 'absolute',
right: '5px',
top: '7px',
},
one: {
position: 'absolute',
left: '8px',
top: '7px',
},
}
const renderInputButton = (isSelected, style, displayOnOffLabel) => {
return (
<div style={[style, { backgroundColor: style.fill }, STYLES.background]}>
{displayOnOffLabel && isSelected && <OneSvg style={STYLES.one} />}
{displayOnOffLabel && !isSelected && <ZeroSvg style={STYLES.zero} />}
<div style={[STYLES.toggle.default, isSelected && STYLES.toggle.selected]} />
</div>
)
}
const Switch = props => {
return (
<RadioCheckboxBase
btnType="checkbox"
width={SWITCH_WIDTH}
renderInputButton={(isSelected, style) =>
renderInputButton(isSelected, style, props.displayOnOffLabel)
}
{...props}
/>
)
}
Switch.propTypes = {
aria: PropTypes.shape({
label: PropTypes.string,
}),
children: PropTypes.node,
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
isDisabled: PropTypes.bool,
isSelected: PropTypes.bool,
name: PropTypes.string,
onChange: PropTypes.func,
style: PropTypes.shape({
button: PropTypes.object,
label: PropTypes.object,
wrapEl: PropTypes.object,
}),
value: PropTypes.string,
wrapEl: PropTypes.string,
displayOnOffLabel: PropTypes.bool,
}
export default Switch
|
src/components/Ingredients.js | MichaelLSmith/recipeBox | import React from 'react';
import { ListGroup, ListGroupItem } from 'react-bootstrap';
function Ingredients(props) {
// console.log(props);
if(props.ingredients == undefined){
return <div>Ingredients here</div>
}
const ingredientsList = props.ingredients.map(
(ingredient, key) => {
return (
<ListGroupItem key={key}>{ingredient}</ListGroupItem>
)}
)
return (
<ListGroup>
<h3 className="text-center">Ingredients</h3>
<hr/>
{ingredientsList}
</ListGroup>
);
}
export default Ingredients;
|
ui/src/components/event/EventExecs.js | d3sw/conductor | import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import { Breadcrumb, BreadcrumbItem, Input, Well, Button, Panel, DropdownButton, MenuItem, Popover, OverlayTrigger, ButtonGroup, Table, Grid, Row, Col } from 'react-bootstrap';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import { connect } from 'react-redux';
import { getEvents, getEventHandlers } from '../../actions/WorkflowActions';
import Typeahead from 'react-bootstrap-typeahead';
const EventExecs = React.createClass({
getInitialState() {
return {
events: [],
executions: [],
eventTypes: []
}
},
componentWillMount(){
this.props.dispatch(getEventHandlers());
//this.props.dispatch(getEvents());
},
componentWillReceiveProps(nextProps) {
this.state.executions = nextProps.executions;
this.state.events = nextProps.events;
},
render() {
let executions = this.state.executions;
let events = this.state.events;
let eventTypes = [];
events.forEach(event => {
eventTypes.push(event.event);
});
return (
<div className="ui-content">
<h1>Event Executions</h1>
<h4>Search for Event Executions</h4>
<Grid fluid={true}>
<Row className="show-grid">
<Col md={8}>
<Typeahead ref="eventTypes" options={eventTypes} placeholder="Filter by Event" multiple={true} selected={this.state.eventTypes}/>
</Col>
<Col md={4}>
<Input type="text" ref="q" placeholder="search..."></Input>
</Col>
</Row>
</Grid>
<br/>
<Table responsive={true} striped={true} hover={true} condensed={false} bordered={true}>
<thead>
<tr>
<th>Something here</th>
</tr>
</thead>
</Table>
</div>
);
}
});
export default connect(state => state.workflow)(EventExecs);
|
src/Accordion.js | leozdgao/react-bootstrap | import React from 'react';
import PanelGroup from './PanelGroup';
const Accordion = React.createClass({
render() {
return (
<PanelGroup {...this.props} accordion={true}>
{this.props.children}
</PanelGroup>
);
}
});
export default Accordion;
|
src/interface/report/Results/Timeline/Buffs.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { Trans } from '@lingui/macro';
import { formatDuration } from 'common/format';
import Icon from 'common/Icon';
import SpellLink from 'common/SpellLink';
import BuffsModule from 'parser/core/modules/Buffs';
import Tooltip from 'common/Tooltip';
import './Buffs.scss';
class Buffs extends React.PureComponent {
static propTypes = {
start: PropTypes.number.isRequired,
secondWidth: PropTypes.number.isRequired,
parser: PropTypes.shape({
eventHistory: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.string.isRequired,
})).isRequired,
}).isRequired,
buffs: PropTypes.instanceOf(BuffsModule).isRequired,
};
constructor() {
super();
this.renderEvent = this.renderEvent.bind(this);
}
getOffsetLeft(timestamp) {
return (timestamp - this.props.start) / 1000 * this.props.secondWidth;
}
// TODO: Fabricate removebuff events for buffs that expired after the fight
isApplicableBuffEvent(event) {
const parser = this.props.parser;
if (!parser.toPlayer(event)) {
// Ignore pet/boss buffs
return false;
}
const spellId = event.ability.guid;
const buff = this.props.buffs.getBuff(spellId);
if (!buff || !buff.timelineHightlight) {
return false;
}
return true;
}
renderEvent(event) {
switch (event.type) {
case 'applybuff':
if (this.isApplicableBuffEvent(event)) {
return this.renderApplyBuff(event);
} else {
return null;
}
case 'removebuff':
if (this.isApplicableBuffEvent(event)) {
return this.renderRemoveBuff(event);
} else {
return null;
}
case 'fightend':
return this.renderLeftOverBuffs(event);
default:
return null;
}
}
_applied = {};
_levels = [];
_maxLevel = 0;
_getLevel() {
// Look for the first available level, reusing levels that are no longer used
let level = 0;
while (this._levels[level] !== undefined) {
level += 1;
}
return level;
}
renderApplyBuff(event) {
const spellId = event.ability.guid;
// Avoid overlapping icons
const level = this._getLevel();
this._applied[spellId] = event;
this._levels[level] = spellId;
this._maxLevel = Math.max(this._maxLevel, level);
return this.renderIcon(event, {
className: 'hoist',
style: {
'--level': level,
},
children: <div className="time-indicator" />,
});
}
renderRemoveBuff(event) {
const applied = this._applied[event.ability.guid];
if (!applied) {
// This may occur for broken logs with missing events due to range/logger issues
return null;
}
const left = this.getOffsetLeft(applied.timestamp);
const duration = event.timestamp - applied.timestamp;
const fightDuration = (applied.timestamp - this.props.start) / 1000;
const level = this._levels.indexOf(event.ability.guid);
this._levels[level] = undefined;
delete this._applied[event.ability.guid];
// TODO: tooltip renders at completely wrong places
return (
<Tooltip
key={`buff-${left}-${event.ability.guid}`}
content={(
<Trans>
{formatDuration(fightDuration, 3)}: gained {event.ability.name} for {(duration / 1000).toFixed(2)}s
</Trans>
)}
>
<div
className="buff hoist"
style={{
left,
width: (event.timestamp - applied.timestamp) / 1000 * this.props.secondWidth,
'--level': level,
}}
data-effect="float"
/>
</Tooltip>
);
}
renderLeftOverBuffs(event) {
// We don't have a removebuff event for buffs that end *after* the fight, so instead we go through all remaining active buffs and manually trigger the removebuff render.
const elems = [];
Object.keys(this._applied).forEach(spellId => {
const applied = this._applied[spellId];
elems.push(this.renderRemoveBuff({
...applied,
timestamp: event.timestamp,
}));
});
return elems;
}
renderIcon(event, { className = '', style = {}, children } = {}) {
const left = this.getOffsetLeft(event.timestamp);
return (
<SpellLink
key={`cast-${left}-${event.ability.guid}`}
id={event.ability.guid}
icon={false}
className={`cast ${className}`}
style={{
left,
...style,
}}
>
<Icon
icon={event.ability.abilityIcon.replace('.jpg', '')}
alt={event.ability.name}
/>
{children}
</SpellLink>
);
}
render() {
const { parser } = this.props;
const buffs = parser.eventHistory.map(this.renderEvent);
return (
<div className="buffs" style={{ '--levels': this._maxLevel + 1 }}>
{buffs}
</div>
);
}
}
export default Buffs;
|
src/components/Footer/Footer.js | YumboRumbo/FlashCard | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import s from './Footer.scss';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
@withStyles(s)
class Footer extends Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<a className={s.link} href="/" onClick={Link.handleClick}>Home</a>
<span className={s.spacer}>·</span>
<a className={s.link} href="/privacy" onClick={Link.handleClick}>Privacy</a>
<span className={s.spacer}>·</span>
<a className={s.link} href="/not-found" onClick={Link.handleClick}>Not Found</a>
</div>
</div>
);
}
}
export default Footer;
|
mla_game/front-end/javascript/components/partials/corrections.js | WGBH/FixIt | import React from 'react'
import classNames from 'classnames'
class Corrections extends React.Component {
render(){
return(
<div className="vote-option corrected">
{this.props.text}
</div>
)
}
}
export default Corrections; |
src/scenes/imports/view.js | bobinette/papernet-front | import PropTypes from 'prop-types';
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import classNames from 'classnames';
import { paperPropType } from 'utils/constants';
import FileLoader from './components/file-loader';
import ImportViewRow from './components/row';
import './view.scss';
const ImportView = ({ loading, imported, onImport, papers }) => {
const btnClassName = classNames(
'btn',
{ 'btn-primary': !loading, disabled: loading || imported },
);
let btnText = 'Import all papers';
if (loading) btnText = 'Importing...';
else if (imported) btnText = 'Done';
let btnIcon = null;
if (loading) btnIcon = (<i className="ImportView__ButtonIcon fa fa-circle-o-notch fa-spin fa-3x fa-fw" />);
else if (imported) btnIcon = (<i className="ImportView__ButtonIcon fa fa-check" />);
return (
<div className="ImportView">
<div className="ImportView__Input">
<div className="ImportView__Input__Help">
Import your Google Chrome Bookmarks as Papers
<br /><small className="text-sm">(Help:
<a
href="http://www.wikihow.com/Export-Bookmarks-from-Chrome"
target="_blank"
rel="noopener noreferrer"
>
Export Chrome bookmarks to file
</a>)</small>
</div>
<FileLoader />
</div>
{papers && papers.size > 0 &&
<div className="ImportView__List">
<div className="ImportView__ImportButton">
<button className={btnClassName} onClick={loading ? null : onImport}>
{btnText}
{btnIcon}
</button>
</div>
<ul>{
papers.map(paper => (
<li key={paper.get('title')}>
<ImportViewRow paper={paper} />
</li>
))
}</ul>
</div>
}
</div>
);
};
ImportView.propTypes = {
loading: PropTypes.bool.isRequired,
imported: PropTypes.bool.isRequired,
onImport: PropTypes.func.isRequired,
papers: ImmutablePropTypes.listOf(paperPropType).isRequired,
};
export default ImportView;
|
app.js | melnik88/rusty-hammers | /* global document */
import './node_modules/milligram/dist/milligram.min.css';
import './style.css';
import Main from './components/Main.jsx';
import Results from './components/Results.jsx';
import Contacts from './components/Contacts.jsx';
import Walks from './components/Walks.jsx';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link } from 'react-router';
ReactDOM.render(
<Router>
<Route path="/" component={Main} />
<Route path="/results" component={Results} />
<Route path="/walks" component={Walks} />
<Route path="/contacts" component={Contacts} />
</Router>
, document.getElementById('app'));
|
src/client/app.js | JBostelaar/Digital-Dash | import getRoutes from 'client/utils/getRoutes';
import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import * as reducers from 'client/reducers';
const reducer = combineReducers(reducers);
const store = createStore(reducer);
render((
<Provider store={store}>
<Router history={browserHistory} children={getRoutes()} />
</Provider>
), document.getElementById('app'));
|
src/components/AnimalPage.js | KingCountySAR/database-frontend | import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Card, CardHeader, CardText } from 'material-ui/Card';
import MissionsTable from './MissionsTable';
import { missionProp, animalProp } from '../propTypes';
import Page from './Page';
const AnimalPage = ({ animal, missions }) => (
<Page>
<Card>
<CardHeader
title={animal.name}
/>
<CardText>
<p>Type: {animal.type}</p>
<p>Name: {animal.name}</p>
<p>Status: {animal.status}</p>
<p>Owner: <Link to={`/members/${animal.owner.id}`}>{animal.owner.name}</Link></p>
</CardText>
</Card>
<Card>
<CardHeader title="Missions" subtitle={`Missions ${animal.name} has responded to`} />
<MissionsTable missions={missions} />
</Card>
</Page>
);
AnimalPage.propTypes = {
animal: animalProp.isRequired,
missions: PropTypes.arrayOf(missionProp).isRequired,
};
export default AnimalPage;
|
react-frontend/src/LoginPanel.js | aabmass/print-web | import React, { Component } from 'react';
import { Card, Button } from 'semantic-ui-react'
import LoginForm from './LoginForm';
// a react function component
class LoginPanel extends Component {
render() {
let body = undefined;
let isLoggedIn = this.props.user.isLoggedIn;
if (isLoggedIn) {
let { username, email } = this.props.user;
body = (
<Card>
<Card.Content>
<Card.Header>{username}</Card.Header>
<Card.Meta>{email}</Card.Meta>
</Card.Content>
<Button primary onClick={this.props.handleLogout}>Logout</Button>
</Card>
);
}
else {
body = (
<LoginForm
handleLogin={this.props.handleLogin}
isLoggedIn={isLoggedIn}
/>
);
}
return body;
}
}
export default LoginPanel;
|
stories/toast.stories.js | sovrin/spectres | import React from 'react';
import {storiesOf} from '@storybook/react';
import Toast from '../src/components/Toast';
import Button from '../src/components/Button';
import Toasts from '../src/managers/Toasts';
import {text} from '../.storybook/addons';
const manager = Toasts.getManager();
storiesOf('Toast', module)
.add('Plain', () =>
<Toast title={text('Language', 'HTML')} timed>{text('Body', '<div>hello world</div>')}</Toast>,
)
.add('Manager', () => {
return <div>
<Toasts manager={manager}/>
<Button onClick={() => manager.dispatch(<Toast timed>{Math.random(20) * 10}</Toast>)}>Add toast</Button>
</div>
},
)
;
|
examples/03 Nesting/Drop Targets/Container.js | arnif/react-dnd | import React from 'react';
import Dustbin from './Dustbin';
import Box from './Box';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
@DragDropContext(HTML5Backend)
export default class Container {
render() {
return (
<div>
<div style={{ overflow: 'hidden', clear: 'both', margin: '-1rem' }}>
<Dustbin greedy>
<Dustbin greedy>
<Dustbin greedy />
</Dustbin>
</Dustbin>
<Dustbin>
<Dustbin>
<Dustbin />
</Dustbin>
</Dustbin>
</div>
<div style={{ overflow: 'hidden', clear: 'both', marginTop: '1.5rem' }}>
<Box />
</div>
</div>
);
}
} |
app/scripts/main.js | kroupaTomass/Piknik-In-The-City | import React from 'react';
import Router from 'react-router';
import routes from './routes';
Router.run(routes, Handler => React.render(<Handler />, document.body));
|
frontend/app/common/conf/pagesIndex.js | First-Peoples-Cultural-Council/fv-web-ui | /*
Copyright 2016 First People's Cultural Council
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'
const ExploreLanguages = React.lazy(() => import('components/ExploreLanguages/ExploreLanguagesContainer'))
const PageExploreDialect = React.lazy(() => import('components/ExploreDialect'))
const PageDialectLearn = React.lazy(() => import('components/DialectLearn'))
const PageDialectMedia = React.lazy(() => import('components/Media'))
const PageDialectPlay = React.lazy(() => import('components/Games'))
const PageJigsawGame = React.lazy(() => import('components/Games/jigsaw'))
const PageWordSearch = React.lazy(() => import('components/Games/wordsearch'))
const PageParachute = React.lazy(() => import('components/Games/parachute'))
const PageWordscramble = React.lazy(() => import('components/Games/wordscramble'))
const PageQuiz = React.lazy(() => import('components/Games/quiz'))
const PageConcentration = React.lazy(() => import('components/Games/concentration'))
const PageDialectGalleries = React.lazy(() => import('components/Gallery'))
const PageDialectGalleryView = React.lazy(() => import('components/Gallery/view'))
const Reports = React.lazy(() => import('components/Reports/ReportsContainer'))
const PageDialectLearnWords = React.lazy(() => import('components/Words/WordsContainer'))
const PageDialectLearnPhrases = React.lazy(() => import('components/Phrases/PhrasesContainer'))
const PageDialectLearnStoriesAndSongs = React.lazy(() => import('components/SongsStories'))
const PageDialectViewMedia = React.lazy(() => import('components/Media/view'))
const PageDialectViewWord = React.lazy(() => import('components/Word/WordContainer'))
const PageDialectViewPhrase = React.lazy(() => import('components/Phrase/PhraseContainer'))
const PageDialectViewBook = React.lazy(() => import('components/SongStory/SongStoryContainer'))
const PageDialectViewAlphabet = React.lazy(() => import('components/Alphabet/AlphabetPage'))
const PageDialectViewCharacter = React.lazy(() => import('components/AlphabetDetail/AlphabetDetailContainer'))
const PageDialectLearnWordsCategories = React.lazy(() => import('components/Categories/WordCategories'))
const PhraseBooksGridContainer = React.lazy(() => import('components/PhraseBooksGrid/PhraseBooksGridContainer'))
const WordsCategoriesGridContainer = React.lazy(() =>
import('components/WordsCategoriesGrid/WordsCategoriesGridContainer')
)
const PageDialectImmersionList = React.lazy(() => import('components/Immersion'))
const PageDebugTypography = React.lazy(() => import('components/DebugTypography'))
const PageError = React.lazy(() => import('components/PageError'))
const PageHome = React.lazy(() => import('components/HomeLayout'))
const PageContent = React.lazy(() => import('components/PageContent'))
const PagePlay = React.lazy(() => import('components/Games'))
const PageSearch = React.lazy(() => import('components/SearchDictionary/SearchDictionaryContainer'))
const Join = React.lazy(() => import('components/Join/JoinContainer'))
const Register = React.lazy(() => import('components/Register/RegisterContainer'))
const PageUsersForgotPassword = React.lazy(() => import('components/Users/forgotpassword'))
// KIDS
const KidsHome = React.lazy(() => import('components/KidsHome'))
const KidsPhrasesByPhrasebook = React.lazy(() =>
import('components/KidsPhrasesByPhrasebook/KidsPhrasesByPhrasebookContainer')
)
const KidsWordsByCategory = React.lazy(() => import('components/KidsWordsByCategory/KidsWordsByCategoryContainer'))
// EDIT
const PageExploreDialectEdit = React.lazy(() => import('components/ExploreDialectEdit'))
const PageDialectGalleryEdit = React.lazy(() => import('components/Gallery/edit'))
const PageDialectEditMedia = React.lazy(() => import('components/Media/edit'))
const PageDialectWordEdit = React.lazy(() => import('components/WordsCreateEdit/Edit'))
const PageDialectPhraseEdit = React.lazy(() => import('components/PhrasesCreateEdit/Edit'))
const PageDialectBookEdit = React.lazy(() => import('components/SongsStories/edit'))
const PageDialectBookEntryEdit = React.lazy(() => import('components/SongsStories/entry/edit'))
const PageDialectAlphabetCharacterEdit = React.lazy(() => import('components/Alphabet/edit'))
// CREATE
const PageDialectWordsCreate = React.lazy(() => import('components/WordsCreateEdit/Create'))
const CreateV2 = React.lazy(() => import('components/WordsCreateEdit/CreateV2'))
const CreateAudio = React.lazy(() => import('components/Audio'))
const PageDialectPhrasesCreate = React.lazy(() => import('components/PhrasesCreateEdit/Create'))
const PageDialectStoriesAndSongsCreate = React.lazy(() => import('components/SongsStories/create'))
const PageDialectStoriesAndSongsBookEntryCreate = React.lazy(() => import('components/SongsStories/entry/create'))
const PageDialectGalleryCreate = React.lazy(() => import('components/Gallery/create'))
// CATEGORY
// ----------------------
const CategoryBrowse = React.lazy(() => import('components/Categories')) // Browse
const CategoryDetail = React.lazy(() => import('components/Category/detail')) // Detail
const PageDialectCategoryCreate = React.lazy(() => import('components/Category/createV1')) // Create V1 for modal
const CategoryCreate = React.lazy(() => import('components/Category/create')) // Create
const CategoryEdit = React.lazy(() => import('components/Category/edit')) // Edit
// CONTRIBUTOR
// ----------------------
const ContributorBrowse = React.lazy(() => import('components/Contributors')) // Browse
const ContributorDetail = React.lazy(() => import('components/Contributor/detail')) // Detail
const ContributorCreateV1 = React.lazy(() => import('components/Contributor/createV1')) // Create V1
const ContributorCreate = React.lazy(() => import('components/Contributor/create')) // Create V2
const ContributorEdit = React.lazy(() => import('components/Contributor/edit')) // Edit
// PHRASEBOOK
// ----------------------
const PhrasebookBrowse = React.lazy(() => import('components/Phrasebooks')) // Browse
const PhrasebookDetail = React.lazy(() => import('components/Phrasebook/detail')) // Detail
const PageDialectPhraseBooksCreate = React.lazy(() => import('components/Phrasebook/createV1')) // Create V1
const PhrasebookCreate = React.lazy(() => import('components/Phrasebook/create')) // Create V2
const PhrasebookEdit = React.lazy(() => import('components/Phrasebook/edit')) // Edit
// RECORDER
// ----------------------
const RecorderBrowse = React.lazy(() => import('components/Recorders')) // Browse
const RecorderDetail = React.lazy(() => import('components/Recorder/detail')) // Detail
const RecorderCreate = React.lazy(() => import('components/Recorder/create')) // Create
const RecorderEdit = React.lazy(() => import('components/Recorder/edit')) // Edit
// DASHBOARD
// ----------------------
const DashboardContainer = React.lazy(() => import('components/Dashboard/DashboardContainer'))
const Membership = React.lazy(() => import('components/Membership/MembershipContainer'))
// MENTOR-APPRENTICE PHOTO PROJECT
// ----------------------
const PageMAPPhotoProject = React.lazy(() => import('components/PhotoProject'))
export {
PageMAPPhotoProject,
PageDebugTypography,
PageError,
PageHome,
PageContent,
ExploreLanguages,
PageExploreDialect,
PageDialectLearn,
PageDialectMedia,
PageDialectLearnWords,
PageDialectLearnWordsCategories,
PageDialectLearnPhrases,
PhraseBooksGridContainer,
WordsCategoriesGridContainer,
PageDialectLearnStoriesAndSongs,
PageDialectViewWord,
PageDialectViewMedia,
PageDialectViewPhrase,
PageDialectViewBook,
PageDialectViewAlphabet,
PageDialectViewCharacter,
PageDialectPlay,
PageDialectGalleries,
PageDialectGalleryView,
Reports,
PagePlay,
PageSearch,
Join,
Register,
PageUsersForgotPassword,
PageDialectImmersionList,
//GAMES
PageJigsawGame,
PageWordSearch,
PageConcentration,
PageParachute,
PageWordscramble,
PageQuiz,
// KIDS
KidsHome,
KidsPhrasesByPhrasebook,
KidsWordsByCategory,
// EDITS
PageExploreDialectEdit,
PageDialectWordEdit,
PageDialectEditMedia,
PageDialectPhraseEdit,
PageDialectBookEdit,
PageDialectBookEntryEdit,
PageDialectAlphabetCharacterEdit,
PageDialectGalleryEdit,
//CREATE
PageDialectWordsCreate,
CreateV2,
CreateAudio,
PageDialectPhrasesCreate,
PageDialectStoriesAndSongsCreate,
PageDialectStoriesAndSongsBookEntryCreate,
PageDialectGalleryCreate,
// CATEGORY
CategoryBrowse,
CategoryDetail,
PageDialectCategoryCreate,
CategoryCreate,
CategoryEdit,
// PHRASEBOOK
PhrasebookBrowse,
PhrasebookDetail,
PageDialectPhraseBooksCreate,
PhrasebookCreate,
PhrasebookEdit,
// CONTRIBUTOR
ContributorBrowse,
ContributorDetail,
ContributorCreateV1,
ContributorCreate,
ContributorEdit,
// RECORDER
RecorderBrowse,
RecorderCreate,
RecorderDetail,
RecorderEdit,
// DASHBOARD
DashboardContainer,
Membership,
}
|
src/components/common/Button.js | jaggerwang/zqc-app-demo | /**
* 在球场
* zaiqiuchang.com
*/
import React from 'react'
import {StyleSheet, Text, TouchableOpacity} from 'react-native'
import flattenStyle from 'flattenStyle'
import {COLOR} from '../../config'
export default ({text, onPress, containerStyle, textStyle}) => {
let {fontSize} = flattenStyle(textStyle || styles.text)
return (
<TouchableOpacity
onPress={onPress}
style={[styles.container, {padding: Math.round(fontSize / 2)},
containerStyle]}
>
<Text style={[styles.text, textStyle]}>{text}</Text>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
container: {
margin: 10,
padding: 10,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderColor: COLOR.theme,
borderRadius: 5
},
text: {
color: COLOR.theme,
fontSize: 14
}
})
|
interface/components/SendTx/index.js | ethereum/mist | import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import ExecutionContext from './ExecutionContext';
import FeeSelector from './FeeSelector';
import Footer from './Footer';
import TxParties from './TxParties';
import {
confirmTx,
determineIfContract,
estimateGasUsage,
getGasPrice,
getPriceConversion,
lookupSignature,
setWindowSize,
togglePriority
} from '../../actions.js';
class SendTx extends Component {
constructor(props) {
super(props);
this.state = {
hasSignature: false
};
}
componentDidMount() {
this.getGasPrice();
this.determineIfContract();
this.lookupSignature();
this.estimateGasUsage();
this.getPriceConversion();
setTimeout(this.adjustWindowHeight, 500);
}
componentDidUpdate() {
this.adjustWindowHeight();
}
componentWillUnmount() {
clearInterval(this.interval);
}
getGasPrice = () => {
this.props.dispatch(getGasPrice());
};
determineIfContract = () => {
this.props.dispatch(determineIfContract(this.props.newTx.to));
};
lookupSignature = () => {
const { data } = this.props.newTx;
this.props.dispatch(lookupSignature(data));
};
estimateGasUsage = () => {
this.props.dispatch(estimateGasUsage());
};
getPriceConversion = () => {
this.props.dispatch(getPriceConversion());
};
adjustWindowHeight = () => {
const height = this.divElement.clientHeight;
this.props.dispatch(setWindowSize(height));
};
togglePriority = () => {
this.props.dispatch(togglePriority());
};
handleSubmit = formData => {
const {
data,
to,
from,
gas,
gasPriceGweiStandard,
gasPriceGweiPriority,
estimatedGas,
priority,
value
} = this.props.newTx;
const chosenPriceGwei = priority
? gasPriceGweiPriority
: gasPriceGweiStandard;
const chosenPriceWei = web3.utils.toWei(chosenPriceGwei.toString(), 'gwei');
let txData = {
data,
from,
gas: gas || estimatedGas,
gasPrice: chosenPriceWei,
pw: formData.pw,
value
};
if (to) {
txData.to = to;
}
this.props.dispatch(confirmTx(txData));
};
render() {
return (
<div className="popup-windows tx-info">
<div ref={divElement => (this.divElement = divElement)}>
<ExecutionContext
adjustWindowHeight={this.adjustWindowHeight}
estimatedGas={this.props.newTx.estimatedGas}
executionFunction={this.props.newTx.executionFunction}
gasPriceGweiStandard={this.props.newTx.gasPriceGweiStandard}
gasPriceGweiPriority={this.props.newTx.gasPriceGweiPriority}
gasError={this.props.newTx.gasError}
isNewContract={this.props.newTx.isNewContract}
params={this.props.newTx.params}
toIsContract={this.props.newTx.toIsContract}
value={this.props.newTx.value}
token={this.props.newTx.token}
/>
<TxParties
fromIsContract={this.state.fromIsContract}
from={this.props.newTx.from}
isNewContract={this.props.newTx.isNewContract}
to={this.props.newTx.to}
toIsContract={this.props.newTx.toIsContract}
executionFunction={this.props.newTx.executionFunction}
params={this.props.newTx.params}
hasSignature={this.state.hasSignature}
value={this.props.newTx.value}
/>
<FeeSelector
estimatedGas={this.props.newTx.estimatedGas}
gasLoading={this.props.newTx.gasLoading}
gasPriceGweiStandard={this.props.newTx.gasPriceGweiStandard}
gasPriceGweiPriority={this.props.newTx.gasPriceGweiPriority}
getGasPrice={this.getGasPrice}
getGasUsage={this.estimateGasUsage}
etherPriceUSD={this.props.etherPriceUSD}
network={this.props.network}
priority={this.props.newTx.priority}
togglePriority={this.togglePriority}
/>
<Footer
unlocking={this.props.newTx.unlocking}
estimatedGas={this.props.newTx.estimatedGas}
gasPrice={this.props.newTx.gasPriceGweiStandard}
gasError={this.props.newTx.gasError}
handleSubmit={this.handleSubmit}
/>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
etherPriceUSD: state.settings.etherPriceUSD,
network: state.nodes.network,
newTx: state.newTx
};
}
export default connect(mapStateToProps)(SendTx);
|
lib/client/app/components/grid-rows.js | andrei-cacio/perl-prerender | /* jshint esnext: true */
import React from 'react';
import ReactDOM from 'react-dom';
import Griddle from 'griddle-react';
import {fakeData} from '../fixtures/grid';
/* jshint ignore:start */
export const GriddleRows = React.createClass({
componentWillMount() {
this.setState({
rows: this.props.params.rows
})
},
render() {
return <Griddle results={fakeData} resultsPerPage={this.state.rows}></Griddle>;
}
})
/* jshint ignore:end */ |
react/features/base/react/components/native/NavigateSectionListItem.js | jitsi/jitsi-meet | // @flow
import React, { Component } from 'react';
import type { Item } from '../../Types';
import AvatarListItem from './AvatarListItem';
import Container from './Container';
import Text from './Text';
import styles from './styles';
type Props = {
/**
* Item containing data to be rendered.
*/
item: Item,
/**
* Function to be invoked when an item is long pressed. The item is passed.
*/
onLongPress: ?Function,
/**
* Function to be invoked when an Item is pressed. The Item's URL is passed.
*/
onPress: ?Function,
/**
* Function to be invoked when secondary action was performed on an Item.
*/
secondaryAction: ?Function
}
/**
* Implements a React/Native {@link Component} that renders the Navigate Section
* List Item.
*
* @augments Component
*/
export default class NavigateSectionListItem extends Component<Props> {
/**
* Constructor of the NavigateSectionList component.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this._renderItemLine = this._renderItemLine.bind(this);
this._renderItemLines = this._renderItemLines.bind(this);
}
_renderItemLine: (string, number) => React$Node;
/**
* Renders a single line from the additional lines.
*
* @param {string} line - The line text.
* @param {number} index - The index of the line.
* @private
* @returns {React$Node}
*/
_renderItemLine(line, index) {
if (!line) {
return null;
}
return (
<Text
key = { index }
numberOfLines = { 1 }
style = { styles.listItemText }>
{line}
</Text>
);
}
_renderItemLines: Array<string> => Array<React$Node>;
/**
* Renders the additional item lines, if any.
*
* @param {Array<string>} lines - The lines to render.
* @private
* @returns {Array<React$Node>}
*/
_renderItemLines(lines) {
return lines && lines.length ? lines.map(this._renderItemLine) : null;
}
/**
* Renders the secondary action label.
*
* @private
* @returns {React$Node}
*/
_renderSecondaryAction() {
const { secondaryAction } = this.props;
return (
<Container
onClick = { secondaryAction }
style = { styles.secondaryActionContainer }>
<Text style = { styles.secondaryActionLabel }>+</Text>
</Container>
);
}
/**
* Renders the content of this component.
*
* @returns {ReactElement}
*/
render() {
const { item, onLongPress, onPress, secondaryAction } = this.props;
return (
<AvatarListItem
item = { item }
onLongPress = { onLongPress }
onPress = { onPress } >
{ secondaryAction && this._renderSecondaryAction() }
</AvatarListItem>
);
}
}
|
src/svg-icons/editor/multiline-chart.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMultilineChart = (props) => (
<SvgIcon {...props}>
<path d="M22 6.92l-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z"/>
</SvgIcon>
);
EditorMultilineChart = pure(EditorMultilineChart);
EditorMultilineChart.displayName = 'EditorMultilineChart';
EditorMultilineChart.muiName = 'SvgIcon';
export default EditorMultilineChart;
|
src/parser/monk/brewmaster/modules/features/StaggerPoolGraph.js | FaideWW/WoWAnalyzer | import React from 'react';
import { Line as LineChart } from 'react-chartjs-2';
import 'common/chartjs-plugin-vertical';
import { formatDuration, formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Analyzer from 'parser/core/Analyzer';
import Tab from 'interface/others/Tab';
import StaggerFabricator from '../core/StaggerFabricator';
/**
* A graph of staggered damage (and related quantities) over time.
*
* The idea of this is to help people identify the root cause of:
* - overly high dtps (purifying well after a peak instead of at the peak)
* - death (stagger ticking too high? one-shot? health trickling away without heals?)
*
* As well as just giving a generally interesting look into when damage
* actually hit your health bar on a fight.
*/
class StaggerPoolGraph extends Analyzer {
static dependencies = {
fab: StaggerFabricator,
};
_hpEvents = [];
_staggerEvents = [];
_deathEvents = [];
_purifyTimestamps = [];
on_addstagger(event) {
this._staggerEvents.push(event);
}
on_removestagger(event) {
if (event.trigger.ability && event.trigger.ability.guid === SPELLS.PURIFYING_BREW.id) {
// record the *previous* timestamp for purification. this will
// make the purifies line up with peaks in the plot, instead of
// showing up *after* peaks
this._purifyTimestamps.push(this._staggerEvents[this._staggerEvents.length-1].timestamp);
}
this._staggerEvents.push(event);
}
on_toPlayer_death(event) {
this._deathEvents.push(event);
}
on_toPlayer_damage(event) {
this._hpEvents.push(event);
}
on_toPlayer_heal(event) {
this._hpEvents.push(event);
}
plot() {
// x indices
const labels = Array.from({ length: Math.ceil(this.owner.fightDuration / 500) }, (x, i) => i);
// somethingByLabels are all objects mapping from label ->
// something, where if a value is unknown for that timestamp it is
// undefined (the key is still present).
const poolByLabels = labels.reduce((obj, sec) => {
obj[sec] = undefined;
return obj;
}, {});
const hpByLabels = Object.assign({}, poolByLabels);
const purifies = this._purifyTimestamps.map(timestamp => Math.floor((timestamp - this.owner.fight.start_time) / 500));
const deaths = this._deathEvents.map(({ timestamp, killingAbility }) => {
return {
label: Math.floor((timestamp - this.owner.fight.start_time) / 500),
ability: killingAbility,
};
});
this._staggerEvents.forEach(({ timestamp, newPooledDamage }) => {
const label = Math.floor((timestamp - this.owner.fight.start_time) / 500);
// show the peak rather than left or right edge of the bin. this
// can cause display issues if there is a rapid sequence of
// hit->purify->hit but has the upside of making purifies after
// big hits (aka good purifies) very visible.
//
// note for future me: upping resolution from 1s -> 500ms
// eliminated the issue mentioned above
poolByLabels[label] = (poolByLabels[label] > newPooledDamage) ? poolByLabels[label] : newPooledDamage;
});
this._hpEvents.forEach(({ timestamp, hitPoints, maxHitPoints }) => {
const label = Math.floor((timestamp - this.owner.fight.start_time) / 500);
// we fill in the blanks later if hitPoints is not defined
if (!!hitPoints) {
hpByLabels[label] = { hitPoints, maxHitPoints };
}
});
// fill in blanks. after deaths hp and stagger should be set to
// zero. in periods of no activity, the same hp/stagger should be
// preserved.
//
// you might wonder "but i thought stagger ticked twice a second? so
// either you're dead or damage is incoming!" Friendo, let me
// introduce you to the joy of stagger pausing: BoC + ISB pauses the
// dot for 3 seconds so we may have gaps where we are *not* dead and
// also not taking damage
let lastPoolContents = 0;
let lastHpContents = { hitPoints: 0, maxHitPoints: 0 };
for (const label in labels) {
if (poolByLabels[label] === undefined) {
poolByLabels[label] = lastPoolContents;
} else {
lastPoolContents = poolByLabels[label];
}
if (hpByLabels[label] === undefined) {
hpByLabels[label] = lastHpContents;
} else {
lastHpContents = hpByLabels[label];
}
if (!!deaths.find(event => event.label === Number(label))) {
lastPoolContents = 0;
lastHpContents = { hitPoints: 0, maxHitPoints: lastHpContents.maxHitPoints };
}
}
const deathsByLabels = Object.keys(hpByLabels).map(label => {
const deathEvent = deaths.find(event => event.label === Number(label));
if (!!deathEvent) {
return { hp: hpByLabels[label].maxHitPoints, ...deathEvent };
} else {
return undefined;
}
});
const labelIndices = Object.keys(poolByLabels).reduce ((obj, label, index) => { obj[label] = index; return obj; }, {});
// some labels are referred to later for drawing tooltips
const DEATH_LABEL = 'Player Death';
const PURIFY_LABEL = 'Purifying Brew Cast';
const HP_LABEL = 'Health';
const STAGGER_LABEL = 'Stagger Pool Size';
const chartData = {
labels,
datasets: [
{
label: DEATH_LABEL,
borderColor: '#ff2222',
borderWidth: 2,
data: deathsByLabels.map(obj => !!obj ? obj.hp : undefined),
pointStyle: 'line',
verticalLine: true,
},
{
label: 'Max Health',
data: Object.values(hpByLabels).map(({ maxHitPoints }) => maxHitPoints),
backgroundColor: 'rgba(255, 139, 45, 0.0)',
borderColor: 'rgb(183, 76, 75)',
borderWidth: 2,
pointStyle: 'line',
},
{
label: HP_LABEL,
data: Object.values(hpByLabels).map(({ hitPoints }) => hitPoints),
backgroundColor: 'rgba(255, 139, 45, 0.2)',
borderColor: 'rgb(255, 139, 45)',
borderWidth: 2,
pointStyle: 'rect',
},
{
label: PURIFY_LABEL,
backgroundColor: '#00ff96',
data: purifies.map(label => { return { x: labelIndices[String(label)], y: poolByLabels[String(label)] }; }),
type: 'scatter',
pointRadius: 4,
showLine: false,
},
{
label: STAGGER_LABEL,
data: Object.values(poolByLabels),
backgroundColor: 'rgba(240, 234, 214, 0.2)',
borderColor: 'rgb(240, 234, 214)',
borderWidth: 2,
pointStyle: 'rect',
},
],
};
function safeAbilityName(ability) {
if (ability === undefined || ability.name === undefined) {
return 'an Unknown Ability';
} else {
return ability.name;
}
}
// labels an item in the tooltip
function labelItem(tooltipItem, data) {
const { index } = tooltipItem;
const dataset = data.datasets[tooltipItem.datasetIndex];
switch (dataset.label) {
case DEATH_LABEL:
return `Player died when hit by ${safeAbilityName(deathsByLabels[index].ability)} at ${formatNumber(deathsByLabels[index].hp)} HP.`;
case PURIFY_LABEL:
return `Purifying Brew cast with ${formatNumber(tooltipItem.yLabel)} damage staggered.`;
default:
return `${dataset.label}: ${formatNumber(tooltipItem.yLabel)}`;
}
}
return (
<div className="graph-container">
<LineChart
data={chartData}
height={100}
width={300}
options={{
tooltips: {
callbacks: {
label: labelItem.bind(this),
},
},
legend: {
labels: {
usePointStyle: true,
fontColor: '#ccc',
},
},
animation: {
duration: 0,
},
elements: {
line: {
tension: 0,
},
point: {
radius: 0,
hitRadius: 4,
hoverRadius: 4,
},
},
scales: {
xAxes: [{
labelString: 'Time',
ticks: {
fontColor: '#ccc',
callback: function (x) {
const label = formatDuration(Math.floor(x/2), 1); // formatDuration got changed -- need precision=1 or it blows up, but that adds a .0 to it
return label.substring(0, label.length - 2);
},
},
}],
yAxes: [{
labelString: 'Damage',
ticks: {
fontColor: '#ccc',
callback: formatNumber,
},
}],
},
}}
/>
</div>
);
}
tab() {
return {
title: 'Stagger Pool',
url: 'stagger-pool',
render: () => (
<Tab>
{this.plot()}
<div style={{ paddingLeft: '1em' }}>
Damage you take is placed into a <em>pool</em> by <SpellLink id={SPELLS.STAGGER.id} />. This damage is then removed by the damage-over-time component of <SpellLink id={SPELLS.STAGGER.id} /> or by <SpellLink id={SPELLS.PURIFYING_BREW.id} /> (or other sources of purification). This plot shows the amount of damage pooled over the course of the fight.
</div>
</Tab>
),
};
}
}
export default StaggerPoolGraph;
|
imports/react/containers/AppContainer.js | leocavalcante/mars | import React from 'react'
import App from '../components/App'
import { connect } from 'react-redux'
import { queryMessages } from '/imports/redux/actions/query-messages'
import { addMessage } from '/imports/redux/actions/add-message'
const props = state => ({
label: state.label,
messages: state.messages,
})
const actions = dispatch => ({
onSubmit: event => {
event.preventDefault()
const body = event.currentTarget.body.value.trim()
dispatch(addMessage(body))
}
})
export default connect(props, actions)(App)
|
src/components/structures/RightPanel.js | martindale/vector | /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd
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 PropTypes from 'prop-types';
import classNames from 'classnames';
import { _t } from 'matrix-react-sdk/lib/languageHandler';
import sdk from 'matrix-react-sdk';
import dis from 'matrix-react-sdk/lib/dispatcher';
import { MatrixClient } from 'matrix-js-sdk';
import Analytics from 'matrix-react-sdk/lib/Analytics';
import rate_limited_func from 'matrix-react-sdk/lib/ratelimitedfunc';
import AccessibleButton from 'matrix-react-sdk/lib/components/views/elements/AccessibleButton';
import { showGroupInviteDialog, showGroupAddRoomDialog } from 'matrix-react-sdk/lib/GroupAddressPicker';
import GroupStoreCache from 'matrix-react-sdk/lib/stores/GroupStoreCache';
class HeaderButton extends React.Component {
constructor() {
super();
this.onClick = this.onClick.bind(this);
}
onClick(ev) {
Analytics.trackEvent(...this.props.analytics);
dis.dispatch({
action: 'view_right_panel_phase',
phase: this.props.clickPhase,
});
}
render() {
const TintableSvg = sdk.getComponent("elements.TintableSvg");
const AccessibleButton = sdk.getComponent("elements.AccessibleButton");
return <AccessibleButton className="mx_RightPanel_headerButton" onClick={this.onClick} >
<div className="mx_RightPanel_headerButton_badge">
{ this.props.badge ? this.props.badge : <span> </span> }
</div>
<TintableSvg src={this.props.iconSrc} width="25" height="25"/>
{ this.props.isHighlighted ? <div className="mx_RightPanel_headerButton_highlight"></div> : <div/> }
</AccessibleButton>;
}
}
HeaderButton.propTypes = {
// Whether this button is highlighted
isHighlighted: PropTypes.bool.isRequired,
// The phase to swap to when the button is clicked
clickPhase: PropTypes.string.isRequired,
// The source file of the icon to display
iconSrc: PropTypes.string.isRequired,
// The badge to display above the icon
badge: PropTypes.node,
// The parameters to track the click event
analytics: PropTypes.arrayOf(PropTypes.string).isRequired,
};
module.exports = React.createClass({
displayName: 'RightPanel',
propTypes: {
// TODO: We're trying to move away from these being props, but we need to know
// whether we should be displaying a room or group member list
roomId: React.PropTypes.string, // if showing panels for a given room, this is set
groupId: React.PropTypes.string, // if showing panels for a given group, this is set
collapsed: React.PropTypes.bool, // currently unused property to request for a minimized view of the panel
},
contextTypes: {
matrixClient: PropTypes.instanceOf(MatrixClient),
},
Phase: {
RoomMemberList: 'RoomMemberList',
GroupMemberList: 'GroupMemberList',
GroupRoomList: 'GroupRoomList',
GroupRoomInfo: 'GroupRoomInfo',
FilePanel: 'FilePanel',
NotificationPanel: 'NotificationPanel',
RoomMemberInfo: 'RoomMemberInfo',
GroupMemberInfo: 'GroupMemberInfo',
},
componentWillMount: function() {
this.dispatcherRef = dis.register(this.onAction);
const cli = this.context.matrixClient;
cli.on("RoomState.members", this.onRoomStateMember);
this._initGroupStore(this.props.groupId);
},
componentWillUnmount: function() {
dis.unregister(this.dispatcherRef);
if (this.context.matrixClient) {
this.context.matrixClient.removeListener("RoomState.members", this.onRoomStateMember);
}
this._unregisterGroupStore();
},
getInitialState: function() {
return {
phase: this.props.groupId ? this.Phase.GroupMemberList : this.Phase.RoomMemberList,
isUserPrivilegedInGroup: null,
}
},
componentWillReceiveProps(newProps) {
if (newProps.groupId !== this.props.groupId) {
this._unregisterGroupStore();
this._initGroupStore(newProps.groupId);
}
},
_initGroupStore(groupId) {
if (!groupId) return;
this._groupStore = GroupStoreCache.getGroupStore(
this.context.matrixClient, groupId,
);
this._groupStore.registerListener(this.onGroupStoreUpdated);
},
_unregisterGroupStore() {
if (this._groupStore) {
this._groupStore.unregisterListener(this.onGroupStoreUpdated);
}
},
onGroupStoreUpdated: function(){
this.setState({
isUserPrivilegedInGroup: this._groupStore.isUserPrivileged(),
});
},
onCollapseClick: function() {
dis.dispatch({
action: 'hide_right_panel',
});
},
onInviteButtonClick: function() {
if (this.context.matrixClient.isGuest()) {
dis.dispatch({action: 'view_set_mxid'});
return;
}
if (this.state.phase === this.Phase.GroupMemberList) {
showGroupInviteDialog(this.props.groupId);
} else if (this.state.phase === this.Phase.GroupRoomList) {
showGroupAddRoomDialog(this.props.groupId).then(() => {
this.forceUpdate();
});
} else {
// call AddressPickerDialog
dis.dispatch({
action: 'view_invite',
roomId: this.props.roomId,
});
}
},
onRoomStateMember: function(ev, state, member) {
// redraw the badge on the membership list
if (this.state.phase == this.Phase.RoomMemberList && member.roomId === this.props.roomId) {
this._delayedUpdate();
}
else if (this.state.phase === this.Phase.RoomMemberInfo && member.roomId === this.props.roomId &&
member.userId === this.state.member.userId) {
// refresh the member info (e.g. new power level)
this._delayedUpdate();
}
},
_delayedUpdate: new rate_limited_func(function() {
this.forceUpdate();
}, 500),
onAction: function(payload) {
if (payload.action === "view_user") {
dis.dispatch({
action: 'show_right_panel',
});
if (payload.member) {
this.setState({
phase: this.Phase.RoomMemberInfo,
member: payload.member,
});
} else {
if (this.props.roomId) {
this.setState({
phase: this.Phase.RoomMemberList,
});
} else if (this.props.groupId) {
this.setState({
phase: this.Phase.GroupMemberList,
member: payload.member,
});
}
}
} else if (payload.action === "view_group") {
this.setState({
phase: this.Phase.GroupMemberList,
member: null,
});
} else if (payload.action === "view_group_room") {
this.setState({
phase: this.Phase.GroupRoomInfo,
groupRoomId: payload.groupRoomId,
});
} else if (payload.action === "view_group_room_list") {
this.setState({
phase: this.Phase.GroupRoomList,
});
} else if (payload.action === "view_group_user") {
this.setState({
phase: this.Phase.GroupMemberInfo,
member: payload.member,
});
} else if (payload.action === "view_room") {
this.setState({
phase: this.Phase.RoomMemberList,
});
} else if (payload.action === "view_right_panel_phase") {
this.setState({
phase: payload.phase,
});
}
},
render: function() {
const MemberList = sdk.getComponent('rooms.MemberList');
const MemberInfo = sdk.getComponent('rooms.MemberInfo');
const NotificationPanel = sdk.getComponent('structures.NotificationPanel');
const FilePanel = sdk.getComponent('structures.FilePanel');
const GroupMemberList = sdk.getComponent('groups.GroupMemberList');
const GroupMemberInfo = sdk.getComponent('groups.GroupMemberInfo');
const GroupRoomList = sdk.getComponent('groups.GroupRoomList');
const GroupRoomInfo = sdk.getComponent('groups.GroupRoomInfo');
const TintableSvg = sdk.getComponent("elements.TintableSvg");
let inviteGroup;
let membersBadge;
if ((this.state.phase == this.Phase.RoomMemberList || this.state.phase === this.Phase.RoomMemberInfo)
&& this.props.roomId
) {
const cli = this.context.matrixClient;
const room = cli.getRoom(this.props.roomId);
let userIsInRoom;
if (room) {
membersBadge = room.getJoinedMembers().length;
userIsInRoom = room.hasMembershipState(
this.context.matrixClient.credentials.userId, 'join',
);
}
if (userIsInRoom) {
inviteGroup =
<AccessibleButton className="mx_RightPanel_invite" onClick={ this.onInviteButtonClick } >
<div className="mx_RightPanel_icon" >
<TintableSvg src="img/icon-invite-people.svg" width="35" height="35" />
</div>
<div className="mx_RightPanel_message">{ _t('Invite to this room') }</div>
</AccessibleButton>;
}
}
const isPhaseGroup = [
this.Phase.GroupMemberInfo,
this.Phase.GroupMemberList
].includes(this.state.phase);
let headerButtons = [];
if (this.props.roomId) {
headerButtons = [
<HeaderButton key="_membersButton" title={_t('Members')} iconSrc="img/icons-people.svg"
isHighlighted={[this.Phase.RoomMemberList, this.Phase.RoomMemberInfo].includes(this.state.phase)}
clickPhase={this.Phase.RoomMemberList}
badge={membersBadge}
analytics={['Right Panel', 'Member List Button', 'click']}
/>,
<HeaderButton key="_filesButton" title={_t('Files')} iconSrc="img/icons-files.svg"
isHighlighted={this.state.phase === this.Phase.FilePanel}
clickPhase={this.Phase.FilePanel}
analytics={['Right Panel', 'File List Button', 'click']}
/>,
<HeaderButton key="_notifsButton" title={_t('Notifications')} iconSrc="img/icons-notifications.svg"
isHighlighted={this.state.phase === this.Phase.NotificationPanel}
clickPhase={this.Phase.NotificationPanel}
analytics={['Right Panel', 'Notification List Button', 'click']}
/>,
];
} else if (this.props.groupId) {
headerButtons = [
<HeaderButton key="_groupMembersButton" title={_t('Members')} iconSrc="img/icons-people.svg"
isHighlighted={isPhaseGroup}
clickPhase={this.Phase.GroupMemberList}
analytics={['Right Panel', 'Group Member List Button', 'click']}
/>,
<HeaderButton key="_roomsButton" title={_t('Rooms')} iconSrc="img/icons-room.svg"
isHighlighted={[this.Phase.GroupRoomList, this.Phase.GroupRoomInfo].includes(this.state.phase)}
clickPhase={this.Phase.GroupRoomList}
analytics={['Right Panel', 'Group Room List Button', 'click']}
/>,
];
}
if (this.props.roomId || this.props.groupId) {
// Hiding the right panel hides it completely and relies on an 'expand' button
// being put in the RoomHeader or GroupView header, so only show the minimise
// button on these 2 screens or you won't be able to re-expand the panel.
headerButtons.push(
<div className="mx_RightPanel_headerButton mx_RightPanel_collapsebutton" key="_minimizeButton"
title={ _t("Hide panel") } onClick={ this.onCollapseClick }
>
<TintableSvg src="img/minimise.svg" width="10" height="16"/>
</div>,
);
}
let panel = <div />;
if (!this.props.collapsed) {
if (this.props.roomId && this.state.phase == this.Phase.RoomMemberList) {
panel = <MemberList roomId={this.props.roomId} key={this.props.roomId} />;
} else if (this.props.groupId && this.state.phase == this.Phase.GroupMemberList) {
panel = <GroupMemberList groupId={this.props.groupId} key={this.props.groupId} />;
} else if (this.state.phase === this.Phase.GroupRoomList) {
panel = <GroupRoomList groupId={this.props.groupId} key={this.props.groupId} />;
} else if (this.state.phase == this.Phase.RoomMemberInfo) {
panel = <MemberInfo member={this.state.member} key={this.props.roomId || this.state.member.userId} />;
} else if (this.state.phase == this.Phase.GroupMemberInfo) {
panel = <GroupMemberInfo
groupMember={this.state.member}
groupId={this.props.groupId}
key={this.state.member.user_id} />;
} else if (this.state.phase == this.Phase.GroupRoomInfo) {
panel = <GroupRoomInfo
groupRoomId={this.state.groupRoomId}
groupId={this.props.groupId}
key={this.state.groupRoomId} />;
} else if (this.state.phase == this.Phase.NotificationPanel) {
panel = <NotificationPanel />;
} else if (this.state.phase == this.Phase.FilePanel) {
panel = <FilePanel roomId={this.props.roomId} />;
}
}
if (!panel) {
panel = <div className="mx_RightPanel_blank"></div>;
}
if (this.props.groupId && this.state.isUserPrivilegedInGroup) {
inviteGroup = isPhaseGroup ? (
<AccessibleButton className="mx_RightPanel_invite" onClick={ this.onInviteButtonClick } >
<div className="mx_RightPanel_icon" >
<TintableSvg src="img/icon-invite-people.svg" width="35" height="35" />
</div>
<div className="mx_RightPanel_message">{ _t('Invite to this community') }</div>
</AccessibleButton>
) : (
<AccessibleButton className="mx_RightPanel_invite" onClick={ this.onInviteButtonClick } >
<div className="mx_RightPanel_icon" >
<TintableSvg src="img/icons-room-add.svg" width="35" height="35" />
</div>
<div className="mx_RightPanel_message">{ _t('Add rooms to this community') }</div>
</AccessibleButton>
);
}
let classes = classNames(
"mx_RightPanel", "mx_fadable",
{
"collapsed": this.props.collapsed,
"mx_fadable_faded": this.props.disabled,
}
);
return (
<aside className={classes}>
<div className="mx_RightPanel_header">
<div className="mx_RightPanel_headerButtonGroup">
{headerButtons}
</div>
</div>
{ panel }
<div className="mx_RightPanel_footer">
{ inviteGroup }
</div>
</aside>
);
},
});
|
src/app.js | telpalbrox/EliteTime | 'use strict';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Route } from 'react-router-dom';
import MainPage from './components/MainPage.js';
import TorrentPage from './components/TorrentPage';
import SearchPage from './components/SearchPage';
import SettingsPage from './components/SettingsPage';
import Footer from './components/Footer';
// set default provider
if (!localStorage.getItem('provider')) {
localStorage.setItem('provider', 'EliteTorrent');
}
ReactDOM.render(
<div>
<Router>
<div className="row">
<Route exact path="/" component={MainPage} />
<Route path="/torrent/:id" component={TorrentPage} />
<Route path="/search/:query?" component={SearchPage} />
<Route path="/settings" component={SettingsPage} />
</div>
</Router>
<Footer />
</div>, document.querySelector('#elite-time')
);
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DestructuringAndAwait.js | RobzDoom/frame_trap | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
async function load() {
return {
users: [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
],
};
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const { users } = await load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-destructuring-and-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
src/components/ExperienceDetail/Heading/index.js | goodjoblife/GoodJobShare | import React from 'react';
import PropTypes from 'prop-types';
import { Heading, P } from 'common/base';
import cn from 'classnames';
import styles from './Heading.module.css';
import { companyNameSelector, jobTitleSelector } from '../experienceSelector';
const formatType = type => {
switch (type) {
case 'work':
return '工作心得';
case 'interview':
return '面試經驗';
case 'intern':
return '實習心得';
default:
return '工作心得';
}
};
const ExperienceHeading = ({ experience, className }) => (
<div className={cn(styles.heading, className)}>
<P Tag="h2" size="l" className={styles.badge}>
{experience && formatType(experience.type)}
</P>
<Heading size="l">
{experience &&
`${companyNameSelector(experience)} ${jobTitleSelector(experience)}`}
</Heading>
</div>
);
ExperienceHeading.propTypes = {
experience: PropTypes.object,
className: PropTypes.string,
};
export default ExperienceHeading;
|
packages/stockflux-launcher/src/search-results/SearchResults.js | owennw/OpenFinD3FC | import React from 'react';
import classNames from 'classnames';
import SearchResult from './SearchResult';
export default ({ results, paddingNeeded }) =>
results &&
results.length > 0 && (
<div className={classNames('cards', { 'padding-top': paddingNeeded })}>
{results.map(result => (
<SearchResult
key={result.symbol}
symbol={result.symbol}
name={result.name}
/>
))}
</div>
);
|
packages/mineral-ui-icons/src/IconCode.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconCode(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"/>
</g>
</Icon>
);
}
IconCode.displayName = 'IconCode';
IconCode.category = 'action';
|
dva/wind-tunnel/src/routes/P3.js | imuntil/React | import React from 'react'
import MainLayout from '../components/MainLayout/MainLayout'
import FadeInOut from '../components/Animation/FadeInOut'
import Form from '../components/End/Form'
import { connect } from 'dva'
function P3({current, dispatch, location, history, match}) {
function handleSubmit() {
dispatch({
type: 'page/next',
payload: current + 1
})
}
return (
<FadeInOut>
<MainLayout>
<FadeInOut>
<Form onSubmit={handleSubmit} />
</FadeInOut>
</MainLayout>
</FadeInOut>
)
}
function mapStateToProps(state) {
const { current } = state.page
return { current }
}
export default connect(mapStateToProps)(P3)
|
client/my-sites/importer/dispatcher-converter.js | tinkertinker/wp-calypso | import Dispatcher from 'dispatcher';
import React from 'react';
import find from 'lodash/find';
import identity from 'lodash/identity';
import isFunction from 'lodash/isFunction';
const firstCallable = ( ...args ) => find( args, isFunction );
const mergeProps = ( ...args ) => Object.assign( {}, ...args );
const dispatchObject = action => Dispatcher.handleViewAction( action );
const dispatchThunk = thunk => thunk( dispatchObject );
const dispatch = action => isFunction( action )
? dispatchThunk( action )
: dispatchObject( action );
export const connectDispatcher = ( fromState, fromDispatch ) => Component => props => (
React.createElement(
Component,
mergeProps(
props,
firstCallable( fromState, identity )( {} ),
firstCallable( fromDispatch, identity )( dispatch )
),
props.children
)
);
|
src/Form/Field/FieldBody.js | boldr/boldr-ui | // @flow
import React from 'react';
import classNames from 'classnames';
import { createWrappedComponent } from '../../util/boldrui';
export type Props = {
tag?: string,
className?: string,
};
export function FieldBody({ tag = 'div', ...props }: Props) {
const className = classNames('boldrui-form__field-body', props.className);
return React.createElement(tag, { ...props, className });
}
export default createWrappedComponent(FieldBody);
|
internals/templates/containers/LanguageProvider/index.js | iPhaeton/Selectors-study | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
app/pages/ProductPage.js | Byte-Code/lm-digitalstore | import React from 'react';
import PropTypes from 'prop-types';
import Page from '../components/Page';
import Product from '../containers/Product';
import Footer from '../components/Footer';
import SideMenu from '../components/SideMenu';
export default function ProductPage(props) {
return (
<Page padding="0 0 140px">
<SideMenu />
<Product params={props.params} />
<Footer />
</Page>
);
}
ProductPage.propTypes = {
params: PropTypes.shape({ productCode: PropTypes.string.isRequired }).isRequired
};
|
src/svg-icons/action/search.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSearch = (props) => (
<SvgIcon {...props}>
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
</SvgIcon>
);
ActionSearch = pure(ActionSearch);
ActionSearch.displayName = 'ActionSearch';
ActionSearch.muiName = 'SvgIcon';
export default ActionSearch;
|
packages/example-phone/src/scripts/components/auth-status.js | udaysrinath/spark-js-sdk | import React from 'react';
export default function AuthStatus({authenticated, authenticating}) {
let message;
if (authenticated) {
message = `authenticated`;
}
else if (authenticating) {
message = `authenticating`;
}
else {
message = `not authenticated`;
}
return <span className="authentication-status">{message}</span>;
}
AuthStatus.propTypes = {
authenticated: React.PropTypes.bool.isRequired,
authenticating: React.PropTypes.bool.isRequired
};
|
src/routes/request/index.js | mapengze/Antd-Backstage | import React from 'react'
import styles from './index.less'
import Mock from 'mockjs'
import { request, config } from '../../utils'
import {
Row,
Col,
Card,
Select,
Input,
Button,
} from 'antd'
const { api, baseURL } = config
const { dashboard, users, userLogin, user } = api
const requestOptions = [
{
url: baseURL + user.replace('/:id', ''),
desc: 'intercept request by mock.js',
},
{
url: baseURL + dashboard,
desc: 'intercept request by mock.js',
},
{
url: baseURL + userLogin,
method: 'post',
data: {
username: 'guest',
password: 'guest',
},
desc: 'intercept request by mock.js',
},
{
url: baseURL + users,
desc: 'intercept request by mock.js',
},
{
url: baseURL + user,
desc: 'intercept request by mock.js',
data: Mock.mock({
id: '@id',
}),
},
{
url: baseURL + user.replace('/:id', ''),
desc: 'intercept request by mock.js',
method: 'post',
data: Mock.mock({
name: '@cname',
nickName: '@last',
phone: /^1[34578]\d{9}$/,
'age|11-99': 1,
address: '@county(true)',
isMale: '@boolean',
email: '@email',
avatar () {
return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
},
}),
},
{
url: baseURL + user,
desc: 'intercept request by mock.js',
method: 'patch',
data: Mock.mock({
id: '@id',
name: '@cname',
}),
},
{
url: baseURL + user,
desc: 'intercept request by mock.js',
method: 'delete',
data: Mock.mock({
id: '@id',
}),
},
{
url: `${baseURL}/test`,
desc: 'intercept request by mock.js',
method: 'get',
},
{
url: 'http://api.asilu.com/weather/',
desc: 'cross-domain request, but match config.baseURL(./src/utils/config.js)',
},
{
url: 'http://www.zuimeitianqi.com/zuimei/queryWeather',
data: {
cityCode: '01010101',
},
desc: 'cross-domain request by yahoo\'s yql',
}]
export default class RequestPage extends React.Component {
constructor (props) {
super(props)
this.state = {
currntRequest: requestOptions[0],
method: 'get',
result: '',
}
}
componentDidMount () {
this.handleRequest()
}
handleRequest = () => {
const { currntRequest } = this.state
const { desc, ...requestParams } = currntRequest
this.setState({
...this.state,
result: <div key="sending">
请求中<br />
url:{currntRequest.url}<br />
method:{currntRequest.method}<br />
params:{currntRequest.data ? JSON.stringify(currntRequest.data) : 'null'}<br />
</div>,
})
request({ ...requestParams }).then((data) => {
const state = this.state
state.result = [this.state.result, <div key="complete"><div>请求完成</div>{JSON.stringify(data)}</div>]
this.setState(state)
})
}
handeleURLChange = (value) => {
const state = this.state
const curretUrl = value.split('?')[0]
const curretMethod = value.split('?')[1]
const currntItem = requestOptions.filter(item => {
const { method = 'get' } = item
return curretUrl === item.url && curretMethod === method
})
state.currntRequest = currntItem[0]
this.setState(state)
}
render () {
const colProps = {
lg: 12,
md: 24,
}
const { result, currntRequest } = this.state
const { method = 'get' } = currntRequest
return (
<div className="content-inner">
<Row gutter={32}>
<Col {...colProps}>
<Card title="Request" style={{
overflow: 'visible',
}}>
<div className={styles.option}>
<Select style={{
width: '100%',
flex: 1,
}} defaultValue={`${method.toLocaleUpperCase()} ${requestOptions[0].url}`}
size="large"
onChange={this.handeleURLChange}
>
{requestOptions.map((item, index) => {
const m = item.method || 'get'
return (<Select.Option key={index} value={`${item.url}?${m}`}>
{`${m.toLocaleUpperCase()} `}{item.url}
</Select.Option>)
})}
</Select>
<Button type="primary" style={{ width: 100, marginLeft: 16 }} onClick={this.handleRequest}>发送</Button>
</div>
<div className={styles.params}>
<div className={styles.label}>Params:</div>
<Input disabled value={currntRequest.data ? JSON.stringify(currntRequest.data) : 'null'} size="large" style={{ width: 200 }} placeholder="null" />
<div style={{ flex: 1, marginLeft: 16 }}>{currntRequest.desc}</div>
</div>
<div className={styles.result}>
{result}
</div>
</Card>
</Col>
</Row>
</div>
)
}
}
|
client/components/user/user_profile.js | xxnatc/waste-not | import React, { Component } from 'react';
import InventoryList from './inventory_list';
import Map from '../map/map';
export default class OrganizationProfile extends Component {
render() {
return (
<div>
<InventoryList />
<Map />
</div>
);
}
}
|
src/elements/List/ListIcon.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
createShorthandFactory,
getUnhandledProps,
META,
SUI,
useVerticalAlignProp,
} from '../../lib'
import Icon from '../Icon/Icon'
/**
* A list item can contain an icon.
*/
function ListIcon(props) {
const { className, verticalAlign } = props
const classes = cx(
useVerticalAlignProp(verticalAlign),
className,
)
const rest = getUnhandledProps(ListIcon, props)
return <Icon {...rest} className={classes} />
}
ListIcon._meta = {
name: 'ListIcon',
parent: 'List',
type: META.TYPES.ELEMENT,
}
ListIcon.propTypes = {
/** Additional classes. */
className: PropTypes.string,
/** An element inside a list can be vertically aligned. */
verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS),
}
ListIcon.create = createShorthandFactory(ListIcon, name => ({ name }))
export default ListIcon
|
src/component/List.js | CompileYouth/SmallFish | import React, { Component } from 'react';
import {
ListView
} from 'react-native';
import Item from './Item';
export default class List extends Component {
constructor() {
super();
this._renderTodo = this._renderTodo.bind(this);
}
componentWillMount() {
this.todos = [
{ text: '吃饭', date: '2017-02-07 10:08', prior: 0, index: 0 },
{ text: '睡觉', date: '2017-02-07 10:08', prior: 1, index: 1 },
{ text: '打豆豆', date: '2017-02-07 10:08', prior: 2, index: 2 },
{ text: '吃饭', prior: 3, index: 3 },
{ text: '睡觉', date: '2017-02-07 10:08', prior: 4, index: 4 },
{ text: '打豆豆', date: '2017-02-07 10:08', prior: 5, index: 5 },
{ text: '吃饭', prior: 6, index: 6 },
{ text: '睡觉', date: '2017-02-07 10:08', prior: 7, index: 7 },
{ text: '打豆豆', date: '2017-02-07 10:08', prior: 8, index: 8 },
];
this.ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state = {
allTodos: this.ds.cloneWithRows(this.todos)
};
}
_renderTodo() {
return <Item />;
}
render() {
return (
<ListView
dataSource={this.state.allTodos}
renderRow={this._renderTodo}
/>
);
}
}
|
src/svg-icons/action/visibility.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionVisibility = (props) => (
<SvgIcon {...props}>
<path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
</SvgIcon>
);
ActionVisibility = pure(ActionVisibility);
ActionVisibility.displayName = 'ActionVisibility';
ActionVisibility.muiName = 'SvgIcon';
export default ActionVisibility;
|
public/js/left.js | MelanistOnca/Pers | import React from 'react';
import { render } from 'react-dom';
import $ from 'jquery';
import Foot from './foot';
import LayoutSelector from './subComponents/layoutSelector'
import site_left_switch from './helpers/site_left_switch'
export default class Left extends React.Component {
render(){
// console.log(this.props, 'was this.props in left.js');
let hotSwap = <div></div>
if(this.props.selectedLayout === 'twitterMimic'){
hotSwap =
<div>
<LayoutSelector {...this.props} />
<Foot {...this.props} />
</div>
}
return(
<div id="leftContainer"
style={site_left_switch(this.props)}
>
{hotSwap}
</div>
)
}
}
|
templates/frontOffice/modern/components/React/SubTitle/index.js | lopes-vincent/thelia | import React from 'react';
export default function SubTitle({ subTitle, className }) {
return (
<div
className={`text-3xl font-bold text-left outline-none mb-8 leading-none ${className}`}
>
{subTitle}
</div>
);
}
|
src/containers/ProductsContainer.js | ihenvyr/react-parse | import React from 'react';
import Products from '../components/Products';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { brandsLoad } from '../actions';
import { withRouter } from 'react-router';
const ProductsContainer = (props) => {
return (
<Products {...props} />
);
};
ProductsContainer.propTypes = {/*
React.PropTypes.array
React.PropTypes.bool
React.PropTypes.func
React.PropTypes.number
React.PropTypes.object
React.PropTypes.string
React.PropTypes.node // anything that can be rendered
React.PropTypes.element
React.PropTypes.instanceOf(MyClass)
React.PropTypes.oneOf(['Thing 1', 'Thing 2'])
React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.string
])
React.PropTypes.arrayOf(React.PropTypes.string)
React.PropTypes.objectOf(React.PropTypes.string)
React.PropTypes.shape({
age: React.PropTypes.number,
name: React.PropTypes.string
})
React.PropTypes.any */
};
ProductsContainer.defaultProps = {};
const mapStateToProps = (state) => {
return {
brands: state.brands,
products: state.products,
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ brandsLoad }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ProductsContainer));
|
src/scripts/routes.js | jie/microgate | import cookie from './utils/cookie'
import React from 'react'
import { Router, Route } from 'react-router'
import AccountLoginApp from './containers/account'
import { MainApp } from './containers/admin'
import { DashboardApp } from './containers/admin'
import { ApiCreateApp, ApisListApp } from './containers/admin'
import { ApplicationsApp, ApplicationsCreateApp } from './containers/admin'
import { ServicesApp, ServicesCreateApp } from './containers/admin'
import { UsersApp, UsersCreateApp } from './containers/admin'
// account
AccountLoginApp.title = 'AccountLoginApp';
AccountLoginApp.path = '/portal/account/login';
// admin
MainApp.title = 'MainApp';
MainApp.path = '/portal/admin';
// api
ApiCreateApp.title = 'ApiCreateApp';
ApiCreateApp.path = '/portal/admin/apis/create';
ApisListApp.title = 'ApisListApp';
ApisListApp.path = '/portal/admin/apis';
// service
ServicesApp.title = 'ServicesApp';
ServicesApp.path = '/portal/admin/services';
ServicesCreateApp.title = 'ServicesCreateApp';
ServicesCreateApp.path = '/portal/admin/services/create';
// dashboard
DashboardApp.title = 'DashboardApp';
DashboardApp.path = '/portal/admin/dashboard';
// application
ApplicationsApp.title = 'ApplicationsApp';
ApplicationsApp.path = '/portal/admin/applications';
ApplicationsCreateApp.title = 'ApplicationsCreateApp';
ApplicationsCreateApp.path = '/portal/admin/applications/create';
// user
UsersApp.title = 'UsersApp';
UsersApp.path = '/portal/admin/users';
UsersCreateApp.title = 'UsersCreateApp';
UsersCreateApp.path = '/portal/admin/users/create';
const authenticate = function(next, replace, callback) {
const authenticated = !!cookie.get('microgate')
if (!authenticated && next.location.pathname != '/portal/account/login') {
replace('/portal/account/login')
}
callback()
}
export default (
<Router>
<Route path={ MainApp.path } component={ MainApp }>
<Route path={ DashboardApp.path } component={ DashboardApp } />
<Route path={ ApiCreateApp.path } component={ ApiCreateApp } />
<Route path={ ApisListApp.path } component={ ApisListApp } />
<Route path={ ServicesApp.path } component={ ServicesApp } />
<Route path={ ServicesCreateApp.path } component={ ServicesCreateApp } />
<Route path={ ApplicationsApp.path } component={ ApplicationsApp } />
<Route path={ ApplicationsCreateApp.path } component={ ApplicationsCreateApp } />
<Route path={ UsersApp.path } component={ UsersApp } />
<Route path={ UsersCreateApp.path } component={ UsersCreateApp } />
</Route>
<Route>
<Route path={ AccountLoginApp.path } component={ AccountLoginApp } />
</Route>
</Router>
)
|
fields/types/file/FileField.js | xyzteam2016/keystone | import Field from '../Field';
import React from 'react';
import { Button, FormField, FormInput, FormNote } from 'elemental';
module.exports = Field.create({
displayName: 'FileField',
statics: {
type: 'File',
},
shouldCollapse () {
return this.props.collapse && !this.hasExisting();
},
fileFieldNode () {
return this.refs.fileField;
},
changeFile () {
this.fileFieldNode().click();
},
getFileSource () {
if (this.hasLocal()) {
return this.state.localSource;
} else if (this.hasExisting()) {
return this.props.value.url;
} else {
return null;
}
},
getFileURL () {
if (!this.hasLocal() && this.hasExisting()) {
return this.props.value.url;
}
},
undoRemove () {
this.fileFieldNode().value = '';
this.setState({
removeExisting: false,
localSource: null,
origin: false,
action: null,
});
},
fileChanged (event) { // eslint-disable-line no-unused-vars
this.setState({
origin: 'local',
});
},
removeFile (e) {
var state = {
localSource: null,
origin: false,
};
if (this.hasLocal()) {
this.fileFieldNode().value = '';
} else if (this.hasExisting()) {
state.removeExisting = true;
if (this.props.autoCleanup) {
if (e.altKey) {
state.action = 'reset';
} else {
state.action = 'delete';
}
} else {
if (e.altKey) {
state.action = 'delete';
} else {
state.action = 'reset';
}
}
}
this.setState(state);
},
hasLocal () {
return this.state.origin === 'local';
},
hasExisting () {
return this.props.value && !!this.props.value.filename;
},
hasFile () {
return this.hasExisting() || this.hasLocal();
},
getFilename () {
if (this.hasLocal()) {
return this.fileFieldNode().value.split('\\').pop();
} else {
return this.props.value.filename;
}
},
renderFileDetails (add) {
var details = null;
var href = this.getFileURL();
if (this.hasFile() && !this.state.removeExisting) {
details = (
<div className="file-values">
<FormInput noedit>{href ? (
<a href={href}>{this.getFilename()}</a>
) : this.getFilename()}</FormInput>
</div>
);
}
return (
<div key={this.props.path + '_details'} className="file-details">
{details}
{add}
</div>
);
},
renderAlert () {
if (this.hasLocal()) {
return (
<div className="file-values upload-queued">
<FormInput noedit>File selected - save to upload</FormInput>
</div>
);
} else if (this.state.origin === 'cloudinary') {
return (
<div className="file-values select-queued">
<FormInput noedit>File selected from Cloudinary</FormInput>
</div>
);
} else if (this.state.removeExisting) {
return (
<div className="file-values delete-queued">
<FormInput noedit>File {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</FormInput>
</div>
);
} else {
return null;
}
},
renderClearButton () {
if (this.state.removeExisting) {
return (
<Button type="link" onClick={this.undoRemove}>
Undo Remove
</Button>
);
} else {
var clearText;
if (this.hasLocal()) {
clearText = 'Cancel Upload';
} else {
clearText = (this.props.autoCleanup ? 'Delete File' : 'Remove File');
}
return (
<Button type="link-cancel" onClick={this.removeFile}>
{clearText}
</Button>
);
}
},
renderFileField () {
if (!this.shouldRenderField()) return null;
return <input ref="fileField" type="file" name={this.props.paths.upload} className="field-upload" onChange={this.fileChanged} tabIndex="-1" />;
},
renderFileAction () {
if (!this.shouldRenderField()) return null;
return <input type="hidden" name={this.props.paths.action} className="field-action" value={this.state.action} />;
},
renderFileToolbar () {
return (
<div key={this.props.path + '_toolbar'} className="file-toolbar">
<div className="u-float-left">
<Button onClick={this.changeFile}>
{this.hasFile() ? 'Change' : 'Upload'} File
</Button>
{this.hasFile() && this.renderClearButton()}
</div>
</div>
);
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
var container = [];
var body = [];
var hasFile = this.hasFile();
if (this.shouldRenderField()) {
if (hasFile) {
container.push(this.renderFileDetails(this.renderAlert()));
}
body.push(this.renderFileToolbar());
} else {
if (hasFile) {
container.push(this.renderFileDetails());
} else {
container.push(<FormInput noedit>no file</FormInput>);
}
}
return (
<FormField label={this.props.label} className="field-type-localfile" htmlFor={this.props.path}>
{this.renderFileField()}
{this.renderFileAction()}
<div className="file-container">{container}</div>
{body}
{this.renderNote()}
</FormField>
);
},
});
|
app/components/Editor/index.js | rohitRev/React | /**
*
* Editor
*
*/
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const customContentStyle = {
width: '60%',
maxWidth: 'none',
};
class Editor extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
open: false,
previewImage: '',
};
}
componentWillReceiveProps(nextProps) {
this.setState({open: nextProps.popState});
}
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
disabled={true}
onTouchTap={this.handleClose}
/>,
];
return (
<MuiThemeProvider>
<div>
<Dialog contentStyle={customContentStyle} actions={actions} modal={true} open={this.state.open}>
<div className="attachment-pop-up" id="attachment-pop-up1" tabIndex={-1}>
<div className="modal-dialog modal-lg" role="document">
<div className="modal-content">
<div className="modal-body">
<div className="row">
<div className="col-md-12">
<div className="top-fil-list">
<h4>Add Images & Markup</h4>
<ul className="disabled">
<a href="#" className="ok-btn-a" data-dismiss="modal" aria-label="Close"><i className="fa fa-check"/></a>
<li className="hide-s">
<div className="filter-markup">
<i className="fa fa-arrow-left" aria-hidden="true"/>
</div>
</li>
<li className="hide-s">
<div className="filter-markup">
<i className="fa fa-arrow-right" aria-hidden="true"/>
</div>
</li>
<li>
<div className="filter-markup">
<i className="fa fa-crop" aria-hidden="true"/>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-undo" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color rotate-sec">
<div className="common-div-s no-hover">
<a href="#">Rotate 90o<i className="fa fa-undo" aria-hidden="true"/></a>
<a href="#"><span>Straighten</span><input type="range" name="straighten" className="active"/><span className="thumb active"><span className="value">62</span></span></a>
</div>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-red-circle" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color">
<div className="common-div-s active">
<a href="#" className="pink-color"/>
</div>
<div className="common-div-s">
<a href="#" className="yellow-color"/>
</div>
<div className="common-div-s">
<a href="#" className="black-color"/>
</div>
<div className="common-div-s">
<a href="#" className="blue-color"/>
</div>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-line-box" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color">
<div className="common-div-s no-hover">
<input type="range"/><span className="thumb"><span className="value"/></span>
</div>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-left-bottom" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color crop-tools">
<div className="common-div-s active">
<a href="#"><img src="/public/img/line-left.png"/></a>
</div>
<div className="common-div-s">
<a href="#"><img src="/public/img/box-line.png"/></a>
</div>
<div className="common-div-s">
<a href="#"><img src="/public/img/rectangle.png"/></a>
</div>
<div className="common-div-s">
<a href="#"><img src="/public/img/circle.png"/></a>
</div>
<div className="common-div-s">
<a href="#"><img src="/public/img/line-icon.png"/></a>
</div>
<div className="common-div-s">
<a href="#"><img src="/public/img/pen-icon.png"/></a>
</div>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-text" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color rotate-sec">
<div className="common-div-s no-hover">
<a href="#"><i className="fa fa-list-ol" aria-hidden="true"/> Text Numbering</a>
<a href="#"><i className="fa fa-text-width" aria-hidden="true"/> A | Free Hand text</a>
</div>
</div>
</li>
<li className="drop-down">
<div className="filter-markup">
<i className="fa fa-attach" aria-hidden="true"/>
<span> </span>
</div>
<div className="pop-hover-color crop-tools attach-f">
<div className="common-div-s active">
<a href="#">Main cover</a>
</div>
<div className="common-div-s">
<a href="#">Reference</a>
</div>
<div className="common-div-s">
<a href="#">Other</a>
</div>
</div>
</li>
{/*
<li><i class="fa fa-search-plus" aria-hidden="true"></i><a href="#"><i class="fa fa-plus-square" aria-hidden="true"></i></a><a href="#"><i class="fa fa-minus-square" aria-hidden="true"></i></a></li> */}
</ul>
<div className="dropdown cust-dd-height">
{/*Trigger*/}
<button className="btn btn-primary dropdown-toggle waves-effect waves-light mbl-h-btns" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i className="fa fa-arrows" aria-hidden="true"/></button>
{/*Menu*/}
<div className="dropdown-menu dropdown-primary" aria-labelledby="dropdownMenu1" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
<li className>
<form className="form-inline-fields">
<button className="btn btn-primary mbl-h-btns-desktop hide-tabs"><i className="fa fa-search-plus" aria-hidden="true"/></button>
<button className="btn btn-primary mbl-h-btns-desktop hide-tabs"><i className="fa fa-search-minus" aria-hidden="true"/></button>
<div className="md-form">
<span className="label-fixed"><span className="badge-round">W</span></span>
<input type="text" className="form-control" placeholder="3.25"/>
</div>
<div className="md-form">
<span className="label-fixed"><span className="badge-round">H</span></span>
<input type="text" className="form-control" placeholder="3.25"/>
</div>
<button className="btn btn-primary mbl-h-btns-desktop"><i className="fa fa-lock" aria-hidden="true"/></button>
<div className="md-form">
<select className="browser-default">
<option value={1}>In</option>
<option value={2}>cm</option>
<option value={3}>mm</option>
</select>
</div>
<button className="btn btn-primary mbl-h-btns-desktop"><i className="fa fa-check" aria-hidden="true"/></button>
<button className="btn btn-primary mbl-h-btns-desktop hide-tabs"><i className="fa fa-trash" aria-hidden="true"/></button>
</form>
</li>
</div>
</div>
<div className="clearfix"/>
<p className="zoom-icons"><i className="fa fa-search-plus" aria-hidden="true"/></p>
<p className="zoom-icons"><i className="fa fa-search-minus" aria-hidden="true"/></p>
</div>
<div className="app-bottom-section">
<div className="col-md-10 text-xs-center">
<div className="row">
<div className="white-board-dev">
{
(this.props.previewImage != "")
?
<img src={this.props.previewImage} alt='editImage'/>
:
<canvas></canvas>
}
</div>
</div>
</div>
<div className="mbl-tools-del text-xs-center">
<ul>
<li>
<a href="#"><i className="fa fa-reply" aria-hidden="true"/></a>
<a href="#"><i className="fa fa-trash" aria-hidden="true"/></a>
<a href="#"><i className="fa fa-reply f-flip" aria-hidden="true"/></a>
</li>
</ul>
</div>
<div className="col-md-2 right-side-section">
<div className="upload-lib upload-attachment-side-link ">
<div className="upload-new-sec">
<i className="fa fa-cloud-upload" aria-hidden="true"/><br />
<a className="nav-link dropdown-toggle waves-effect waves-light" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Attach New</a>
<div className="dropdown-menu dropdown-default for-dropdown-attachment" aria-labelledby="dropdownMenu2" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
<ul>
<li>
<a href="#"><i className="fa fa-desktop" aria-hidden="true"/> Computer</a>
</li>
<li>
<a href="#"><i className="fa fa-dropbox" aria-hidden="true"/> Dropbox</a>
</li>
<li>
<a href="#"><i className="fa fa-drive" aria-hidden="true"/> Google Drive</a>
</li>
<li>
<a href="#"><i className="fa fa-cloud-download" aria-hidden="true"/> One drive</a>
</li>
<li>
<a href="#"><i className="fa fa-box" aria-hidden="true"/> Box</a>
</li>
<li>
<a href="#"><i className="fa fa-facebook-square" aria-hidden="true"/> Facebook</a>
</li>
<li>
<a href="#"><i className="fa fa-flickr" aria-hidden="true"/> Flickr</a>
</li>
</ul>
<div className="modal-footer">
<div className="md-form">
<i className="fa fa-link prefix active" aria-hidden="true"/>
<input type="email" id="form9" className="form-control validate" placeholder="Paste url to capture from web..."/>
</div>
<button type="button" className="btn btn-amber waves-effect waves-light">Capture</button>
</div>
</div>
</div>
<div className="upload-new-sec" data-click-tab=".library-block" data-click-hide=".dropzone">
{/* <input type="file" name="library-new"> */}
<i className="fa fa-hdd-o" aria-hidden="true"/><br /> Library
</div>
</div>
<div className="white-board-sec">
<a href="#">Add a Whiteboard</a>
</div>
<div className="img-repeat-sec">
<ul>
<li>
<a href="#"><img src="/public/img/kim.jpg"/></a>
</li>
<li>
<a href="#"><img src="/public/img/second-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/third-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
<li>
<a href="#"><img src="/public/img/fifth-image.png"/></a>
</li>
</ul>
<div className="bottom-arrow-fun">
<a href="#"><i className="fa fa-caret-down" aria-hidden="true"/></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Dialog>
</div>
</MuiThemeProvider>
);
}
}
export default Editor;
|
js/components/tabMenu/index.js | gectorat/react-native-app |
import React, { Component } from 'react';
import {
TouchableOpacity,
Image,
Alert
} from 'react-native';
import { View as RawView } from 'react-native';
import { connect } from 'react-redux';
import {
Container,
Content,
Header,
Title,
Tabs,
Text,
Card,
CardItem,
Grid,
Col,
Row,
Button,
View,
InputGroup,
Input,
Icon } from 'native-base';
import TabCard from '../common/cards/TabCard';
import TabCardComplex from '../common/cards/TabCardComplex';
import NoItems from '../common/NoItemContentMsg';
import { setIndex } from '../../actions/list';
import { syncPosts, fetchPosts } from '../../actions/post';
import { popRoute } from '../../actions/route';
import myTheme from '../../themes/base-theme';
import styles from './styles';
class Home extends Component {
static propTypes = {
setIndex: React.PropTypes.func,
name: React.PropTypes.string,
list: React.PropTypes.arrayOf(React.PropTypes.string),
}
constructor() {
super();
this.state = { description: '' }
}
componentDidMount() {
// this.props.fetchPosts();
}
render() {
const { posts, isEditing } = this.props.posts;
const mockText = 'NativeBase is a free and open source framework that enables developers to build high-quality mobile apps using React Native iOS and Android apps with a fusion of ES6.';
return (
<Container theme={myTheme} style={styles.container}>
<Header>
<Button transparent onPress={() => this.props.popRoute()}>
<Icon name="ios-arrow-back" />
</Button>
<Title>Tab Menu</Title>
</Header>
<Content style={{backgroundColor:'#000'}}>
<Tabs>
<View tabLabel='Home'>
<RawView style={{backgroundColor:'#000'}}>
<TabCard>
{mockText}
</TabCard>
<TabCard>
{mockText}
</TabCard>
<TabCard>
{mockText}
</TabCard>
<TabCard>
{mockText}
</TabCard>
</RawView>
</View>
<View tabLabel="Menu">
<RawView style={{backgroundColor:'#000'}}>
<Card>
<CardItem cardBody>
<Text>
NativeBase is a free and open source framework that enables
developers to build high-quality mobile apps using React Native
iOS and Android apps with a fusion of ES6.
</Text>
</CardItem>
<CardItem header>
<Icon name='ios-eye'></Icon>
<Text>315</Text>
<Icon name='ios-heart'></Icon>
<Text>315</Text>
</CardItem>
</Card>
</RawView>
<RawView style={{backgroundColor:'#000'}}>
<TabCardComplex
header={{
iconName: "ios-people",
title:"Tab Header"
}}
actionMenu={true}>
{mockText}
</TabCardComplex>
</RawView>
</View>
</Tabs>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
fetchPosts: () => dispatch(fetchPosts()),
syncPosts: () => dispatch(syncPosts()),
popRoute: () => dispatch(popRoute()),
setIndex: index => dispatch(setIndex(index)),
};
}
function mapStateToProps(state) {
return {
name: state.user.name,
posts: state.posts,
list: state.list.list,
};
}
export default connect(mapStateToProps, bindAction)(Home);
|
src/svg-icons/maps/local-convenience-store.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalConvenienceStore = (props) => (
<SvgIcon {...props}>
<path d="M19 7V4H5v3H2v13h8v-4h4v4h8V7h-3zm-8 3H9v1h2v1H8V9h2V8H8V7h3v3zm5 2h-1v-2h-2V7h1v2h1V7h1v5z"/>
</SvgIcon>
);
MapsLocalConvenienceStore = pure(MapsLocalConvenienceStore);
MapsLocalConvenienceStore.displayName = 'MapsLocalConvenienceStore';
MapsLocalConvenienceStore.muiName = 'SvgIcon';
export default MapsLocalConvenienceStore;
|
app/utils/icons.js | wilomgfx/AnyWeatherReactRedux | import React from 'react';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export default function getWeatherIconByIconName(darkSkyIconName, iconSize =30, color='white', styles= {}){
switch (darkSkyIconName){
case 'clear-day':
return <Icon name="weather-sunny" size={iconSize} color={color} style={styles} />
case 'rain':
return <Icon name="weather-rainy" size={iconSize} color={color} style={styles} />
case 'snow':
return <Icon name="weather-snowy" size={iconSize} color={color} style={styles} />
case 'sleet':
return <Icon name="weather-snowy-rainy" size={iconSize} color={color} style={styles} />
case 'wind':
return <Icon name="weather-windy" size={iconSize} color={color} style={styles} />
case 'fog':
return <Icon name="weather-fog" size={iconSize} color={color} style={styles} />
case 'cloudy':
return <Icon name="weather-cloudy" size={iconSize} color={color} style={styles} />
case 'partly-cloudy-night':
case 'clear-night':
return <Icon name="weather-night" size={iconSize} color={color} style={styles} />
case 'partly-cloudy-day':
return <Icon name="weather-partlycloudy" size={iconSize} color={color} style={styles} />
default:
return <Icon name="weather-cloudy" size={iconSize} color={color} style={styles} />
}
}
|
react/features/welcome/components/AbstractWelcomePage.js | bickelj/jitsi-meet | import React, { Component } from 'react';
import { appNavigate } from '../../app';
import { isRoomValid } from '../../base/conference';
import { VideoTrack } from '../../base/media';
import { getLocalVideoTrack } from '../../base/tracks';
/**
* Base (abstract) class for container component rendering the welcome page.
*
* @abstract
*/
export class AbstractWelcomePage extends Component {
/**
* Initializes a new AbstractWelcomePage instance, including the initial
* state of the room name input.
*
* @param {Object} props - Component properties.
*/
constructor(props) {
super(props);
/**
* Save room name into component's local state.
*
* @type {{room: string}}
*/
this.state = {
room: ''
};
// Bind event handlers so they are only bound once for every instance.
this._onJoinClick = this._onJoinClick.bind(this);
this._onRoomChange = this._onRoomChange.bind(this);
}
/**
* This method is executed when component receives new properties.
*
* @inheritdoc
* @param {Object} nextProps - New props component will receive.
*/
componentWillReceiveProps(nextProps) {
this.setState({ room: nextProps.room });
}
/**
* Determines whether the 'Join' button is (to be) disabled i.e. there's no
* valid room name typed into the respective text input field.
*
* @protected
* @returns {boolean} If the 'Join' button is (to be) disabled, true;
* otherwise, false.
*/
_isJoinDisabled() {
return !isRoomValid(this.state.room);
}
/**
* Handles click on 'Join' button.
*
* @protected
* @returns {void}
*/
_onJoinClick() {
this.props.dispatch(appNavigate(this.state.room));
}
/**
* Handles 'change' event for the room name text input field.
*
* @param {string} value - The text typed into the respective text input
* field.
* @protected
* @returns {void}
*/
_onRoomChange(value) {
this.setState({ room: value });
}
/**
* Renders a local video if any.
*
* @protected
* @returns {(ReactElement|null)}
*/
_renderLocalVideo() {
return (
<VideoTrack videoTrack = { this.props.localVideoTrack } />
);
}
}
/**
* AbstractWelcomePage component's property types.
*
* @static
*/
AbstractWelcomePage.propTypes = {
dispatch: React.PropTypes.func,
localVideoTrack: React.PropTypes.object,
room: React.PropTypes.string
};
/**
* Selects local video track from tracks in state, local participant and room
* and maps them to component props. It seems it's not possible to 'connect'
* base component and then extend from it. So we export this function in order
* to be used in child classes for 'connect'.
*
* @param {Object} state - Redux state.
* @returns {{
* localVideoTrack: (Track|undefined),
* room: string
* }}
*/
export function mapStateToProps(state) {
const conference = state['features/base/conference'];
const tracks = state['features/base/tracks'];
return {
localVideoTrack: getLocalVideoTrack(tracks),
room: conference.room
};
}
|
src/svg-icons/notification/power.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPower = (props) => (
<SvgIcon {...props}>
<path d="M16.01 7L16 3h-2v4h-4V3H8v4h-.01C7 6.99 6 7.99 6 8.99v5.49L9.5 18v3h5v-3l3.5-3.51v-5.5c0-1-1-2-1.99-1.99z"/>
</SvgIcon>
);
NotificationPower = pure(NotificationPower);
NotificationPower.displayName = 'NotificationPower';
NotificationPower.muiName = 'SvgIcon';
export default NotificationPower;
|
examples/js/manipulation/del-row-custom-confirm.js | rolandsusans/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-console: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
function customConfirm(next, dropRowKeys) {
const dropRowKeysStr = dropRowKeys.join(',');
if (confirm(`(It's a custom confirm)Are you sure you want to delete ${dropRowKeysStr}?`)) {
// If the confirmation is true, call the function that
// continues the deletion of the record.
next();
}
}
const options = {
handleConfirmDeleteRow: customConfirm
};
// If you want to enable deleteRow, you must enable row selection also.
const selectRowProp = {
mode: 'checkbox'
};
export default class DeleteRowCustomComfirmTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } deleteRow={ true } selectRow={ selectRowProp } options={ options }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/app/DevTools.js | eordano/sherlock | 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-g'
changePositionKey='ctrl-q' >
<LogMonitor />
</DockMonitor>
)
|
src/components/Account/components/Reservations/components/PastReservations/components/PastReservation/index.js | galsen0/hair-dv-front | /**
* Created by diop on 11/05/2017.
*/
import React from 'react';
import { Item, Label, Button, Grid, Icon } from 'semantic-ui-react';
const PastReservation = () => {
return(
<Item>
<Item.Image src='../../../img/front-image-one.jpeg' size="medium" />
<Item.Content>
<Item.Header as='a'>Name</Item.Header>
<Item.Meta>
<span>Adress CP Ville</span><br/>
<span>0785360476</span>
</Item.Meta>
<Item.Description>
<Grid columns={2} textAlign={"center"}>
<Grid.Column>
<h4>Client: Ndeye Fatou Diop</h4>
</Grid.Column>
<Grid.Column>
<h4>vendredi 19 mai 2017 à 17h40</h4>
<Label color="grey" size="big">Tarif : 15 €</Label>
</Grid.Column>
<Grid.Row></Grid.Row>
</Grid>
</Item.Description>
<Item.Extra>
<Item.Extra>
<Button floated='left' color="blue">
REFAIRE UNE RESERVATION
<Icon name='right chevron' />
</Button>
</Item.Extra>
</Item.Extra>
</Item.Content>
</Item>
);
};
export default PastReservation; |
packages/core/stories/tokens/icons/Icon.stories.js | massgov/mayflower | import React from 'react';
import { assets } from './Icon.knob.options';
import IconDisplay from './IconDisplay';
import generateTitle from '../../util/generateTitle';
export const Icons = (args) => (
<ul className="sg-icons">
{
Object.keys(assets).map((icon) => (
<IconDisplay {...args} name={icon} key={`icon_${icon}`} />
))
}
</ul>
);
Icons.args = {
width: 40,
height: 50,
title: 'Icon Title Here',
classes: [''],
ariaHidden: false,
fill: '#000'
};
Icons.argTypes = {
fill: {
control: {
type: 'color'
}
}
};
export default {
title: generateTitle('Icon'),
component: Icons
};
|
app/javascript/mastodon/features/favourited_statuses/index.js | Kirishima21/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites';
import Column from '../ui/components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { debounce } from 'lodash';
const messages = defineMessages({
heading: { id: 'column.favourites', defaultMessage: 'Favourites' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'favourites', 'items']),
isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true),
hasMore: !!state.getIn(['status_lists', 'favourites', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Favourites extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFavouritedStatuses());
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('FAVOURITES', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFavouritedStatuses());
}, 300, { leading: true })
render () {
const { intl, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props;
const pinned = !!columnId;
const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite toots yet. When you favourite one, it will show up here." />;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}>
<ColumnHeader
icon='star'
title={intl.formatMessage(messages.heading)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusList
trackScroll={!pinned}
statusIds={statusIds}
scrollKey={`favourited_statuses-${columnId}`}
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
server/dashboard/js/components/Bench.react.js | MrAlone/mzbench | import React from 'react';
import BenchStore from '../stores/BenchStore';
import BenchNav from './BenchNav.react';
import BenchOverview from './BenchOverview.react';
import BenchGraphs from './BenchGraphs.react';
import BenchReports from './BenchReports.react';
import BenchScenario from './BenchScenario.react';
import NewBench from './NewBench.react';
import BenchLog from './BenchLog.react';
import LoadingSpinner from './LoadingSpinner.react';
import Highlight from './Highlight.react';
class Bench extends React.Component {
constructor(props) {
super(props);
this.state = this._resolveState();
this._onChange = this._onChange.bind(this);
}
componentDidMount() {
BenchStore.onChange(this._onChange);
}
componentWillUnmount() {
BenchStore.off(this._onChange);
}
renderActiveTab() {
let component;
switch (this.state.tab) {
case "graphs":
component = <BenchGraphs bench = {this.state.bench} activeGraph = {this.state.activeGraph}/>;
break;
case "reports":
component = <BenchReports bench = {this.state.bench } />;
break;
case "scenario":
component = <BenchScenario bench = {this.state.bench} />;
break;
case "logs":
component = <BenchLog bench = {this.state.bench} isBenchActive = {this.state.bench.isRunning()}/>;
break;
default:
component = <BenchOverview bench = {this.state.bench} activeGraph = {this.state.activeGraph}/>;
break;
}
return component;
}
renderLoadingSpinner() {
return (<LoadingSpinner>Loading...</LoadingSpinner>);
}
renderUnknownBench() {
return (
<div className="alert alert-warning" role="alert">
<strong>Oh snap!</strong>
Cant find benchmark
</div>
);
}
render() {
if (!this.state.isLoaded) {
return this.renderLoadingSpinner();
}
if (this.state.isNewSelected) {
return <NewBench bench={BenchStore.getNew()} clouds={BenchStore.getClouds()}/>;
}
if (!this.state.bench) {
return this.renderUnknownBench();
}
return (
<div key={this.state.bench.id}>
<BenchNav bench={this.state.bench} selectedTab={this.state.tab} />
{ this.renderActiveTab() }
</div>
);
}
_resolveState() {
if (!BenchStore.isLoaded()) {
return { isLoaded: false };
}
if (BenchStore.isNewSelected()) {
return { isLoaded: true, isNewSelected: true };
}
return {
isLoaded: true,
isNewSelected: false,
bench: BenchStore.getSelected(),
tab: BenchStore.getActiveTab(),
activeGraph: BenchStore.getSelectedGraph()
};
}
_onChange() {
this.setState(this._resolveState());
}
}
export default Bench;
|
react/private/GlobalFooter/GlobalFooter.js | seekinternational/seek-asia-style-guide | import React, { Component } from 'react';
import styles from './GlobalFooter.less';
import PropTypes from 'prop-types';
import FooterLinks from './components/FooterLinks/FooterLinks';
import UpperFooter from './components/UpperFooter/UpperFooter';
import { Hidden, Text, PageBlock, ListItem, Icon } from 'seek-asia-style-guide/react';
import classnames from 'classnames';
import smoothScroll from 'seek-asia-style-guide/react/private/smoothScroll';
import _get from 'lodash/get';
export const makeDefaultLinkRenderer = () => {
const DefaultLinkRenderer = ({ href, children, ...props }) => (
<a className={styles.link} href={href} {...props}>
{React.Children.map(children, child => {
return (child.type === ListItem) ?
React.cloneElement(child, { noShadow: true }) : child;
})}
</a>
);
DefaultLinkRenderer.propTypes = {
children: PropTypes.array,
href: PropTypes.string
};
return DefaultLinkRenderer;
};
const currentLocale = ({ title, ItemIcon } = {}) => {
return title ? <div className={styles.currentLocale}>
{ItemIcon && <ItemIcon className={styles.localeIcon} />}
<Text whispering className={styles.currentLocaleLabel}>{title}</Text>
</div> : null;
};
currentLocale.propTypes = {
title: PropTypes.string,
ItemIcon: PropTypes.func
};
const pageBottom = 'pageBottom';
export default class GlobalFooter extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
handleClick() {
const shouldOpen = !this.state.isOpen;
this.setState({
isOpen: shouldOpen
});
if (shouldOpen) {
smoothScroll(pageBottom);
}
}
render() {
const { linkRenderer, isExpandedVersion, showHeaderActionTrayOffset, footerMessages, showCountryLanguage, locales } = this.props;
const { isOpen } = this.state;
const year = new Date().getFullYear();
const shouldShowCountryLanguage = showCountryLanguage && locales[0];
return (
<footer className={classnames(styles.container, { [styles.headerActionTrayOffset]: showHeaderActionTrayOffset })}>
<PageBlock>
<div className={classnames(styles.upperWrapper, { [styles.hidden]: isExpandedVersion ? false : !isOpen })}>
<UpperFooter footerMessages={footerMessages} linkRenderer={linkRenderer} />
<Hidden aboveMobile>
<FooterLinks footerMessages={footerMessages} linkRenderer={linkRenderer} />
</Hidden>
</div>
<div className={styles.lowerWrapper} >
{
shouldShowCountryLanguage && currentLocale(locales[0])
}
<div className={classnames(styles.meta)}>
<Hidden mobile>
<FooterLinks footerMessages={footerMessages} linkRenderer={linkRenderer} className={classnames(styles.bottomMeta)} />
</Hidden>
<Text whispering secondary semiStrong className={styles.copyright}>
{_get(footerMessages, 'copyright').replace('{year}', year)}
</Text>
</div>
{ !isExpandedVersion &&
<div className={styles.chevronIcon} onClick={e => this.handleClick(e)}>
<Icon type="chevron" id={pageBottom} smoothRotate rotation={isOpen ? 'reset' : '-180deg'} />
</div>
}
</div>
</PageBlock>
</footer>
);
}
}
GlobalFooter.defaultProps = {
linkRenderer: makeDefaultLinkRenderer()
};
GlobalFooter.propTypes = {
linkRenderer: PropTypes.func,
isExpandedVersion: PropTypes.bool,
showHeaderActionTrayOffset: PropTypes.bool,
showCountryLanguage: PropTypes.bool,
footerMessages: PropTypes.object.isRequired,
locales: PropTypes.array.isRequired
};
|
docs/tutorial/DO_NOT_TOUCH/01/src/index.js | FWeinb/cerebral | import React from 'react'
import {render} from 'react-dom'
import {Controller} from 'cerebral'
import {Container} from 'cerebral/react'
import Devtools from 'cerebral/devtools'
import App from './components/App'
const controller = Controller({
devtools: Devtools()
})
render((
<Container controller={controller}>
<App />
</Container>
), document.querySelector('#root'))
|
src/routes/register/index.js | jwhchambers/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Register from './Register';
const title = 'New User Registration';
export default {
path: '/register',
action() {
return {
title,
component: <Register title={title} />,
};
},
};
|
client/modules/core/components/main_layout.js | wmzhai/mantra-demo | import React from 'react';
import Header from './header';
const Layout = ({content = () => null }) => (
<div>
<Header />
<main className="app-layout">
{content()}
</main>
<footer className="site-footer">
<small>基于<a href='https://github.com/kadirahq/mantra'>Mantra</a> & Meteor构建.</small>
</footer>
</div>
);
export default Layout;
|
src/BootstrapMixin.js | natlownes/react-bootstrap | import React from 'react';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const BootstrapMixin = {
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES),
/**
* Style variants
* @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")}
*/
bsStyle: React.PropTypes.oneOf(styleMaps.STYLES),
/**
* Size variants
* @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")}
*/
bsSize: CustomPropTypes.keyOf(styleMaps.SIZES)
},
getBsClassSet() {
let classes = {};
let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass];
if (bsClass) {
classes[bsClass] = true;
let prefix = bsClass + '-';
let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize];
if (bsSize) {
classes[prefix + bsSize] = true;
}
if (this.props.bsStyle) {
if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) {
classes[prefix + this.props.bsStyle] = true;
} else {
classes[this.props.bsStyle] = true;
}
}
}
return classes;
},
prefixClass(subClass) {
return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass;
}
};
export default BootstrapMixin;
|
src/app/containers/App.js | skratchdot/js-playground | import React, { Component } from 'react';
import { Grid } from 'react-bootstrap';
import pathGet from 'object-path-get';
import GithubCorner from 'react-github-corner';
import Header from '../components/Header';
import Footer from '../components/Footer';
import stringToCssName from '../helpers/stringToCssName';
class App extends Component {
render() {
const path = pathGet(this, 'this.children.props.route.path', '');
const pageParams = pathGet(this, 'props.params', {});
const githubUrl = 'https://github.com/skratchdot/js-playground';
return (
<div className={`page-${stringToCssName(path)}`}>
<Grid>
<Header pageParams={pageParams} />
{this.props.children}
<Footer />
<GithubCorner href={githubUrl} />
</Grid>
</div>
);
}
}
export default App;
|
hw8/frontend/src/index.js | yusong-shen/comp531-web-development | /*
High level logic for entire front-end applicaiton
*/
require('expose?$!expose?jQuery!jquery')
require("bootstrap-webpack")
require('./styles.css')
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import { createStore, compose, applyMiddleware } from 'redux'
import reduxThunk from 'redux-thunk'
import App from './components/app'
import rootReducer from './reducers/reducers'
const logger = createLogger()
const store = createStore(rootReducer,
compose(
applyMiddleware(logger),
applyMiddleware(reduxThunk)
))
class MyComponent extends React.Component {
render() {
return <Provider store={store}>
<App />
</Provider>
}
}
ReactDOM.render(<MyComponent />,
document.getElementById('app')
)
|
assets/jqwidgets/demos/react/app/grid/bindingtoobservablearray/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
class App extends React.Component {
constructor() {
super();
this.state = {
observableArray: new $.jqx.observableArray(generatedata(2), (changed) => {
this.updateLog(this.state.observableArray);
})
};
}
componentDidMount() {
this.updateLog(this.state.observableArray);
this.refs.addItem.on('click', () => {
let row = generatedata(1)[0];
let temp = this.state.observableArray;
temp.push(row);
this.setState({
observableArray: temp
});
});
this.refs.deleteItem.on('click', () => {
if (this.state.observableArray.length > 0) {
let temp = this.state.observableArray;
temp.splice(0, 1);
this.setState({
observableArray: temp
});
}
});
this.refs.updatePath.on('click', () => {
if (this.state.observableArray.length > 0) {
let row = generatedata(1)[0];
let temp = this.state.observableArray;
temp.set('0.firstname', row.firstname);
temp.set('0.lastname', row.lastname);
this.setState({
observableArray: temp
});
}
});
this.refs.updateItem.on('click', () => {
if (this.state.observableArray.length > 0) {
let row = generatedata(1)[0];
let temp = this.state.observableArray;
temp.set(0, row);
this.setState({
observableArray: temp
});
}
});
}
updateLog(observableArray) {
let rows = '';
for (let i = 0; i < observableArray.length; i++) {
rows += observableArray.toJSON(['firstname', 'lastname', 'productname', 'quantity', 'price', 'total'], observableArray[i]);
rows += '<br/>';
}
let container = document.getElementById('log');
container.innerHTML = rows;
}
render() {
let source =
{
localdata: this.state.observableArray,
datatype: 'obserableArray',
datafields:
[
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' },
{ name: 'productname', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'total', type: 'number' }
]
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'Name', datafield: 'firstname', width: 120 },
{ text: 'Last Name', datafield: 'lastname', width: 120 },
{ text: 'Product', datafield: 'productname', width: 180 },
{ text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
{ text: 'Unit Price', datafield: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' },
{ text: 'Total', datafield: 'total', cellsalign: 'right', cellsformat: 'c2' }
];
return (
<div>
<JqxGrid
width={850} height={150} source={dataAdapter}
sortable={true} columnsresize={true} editable={true}
columns={columns} selectionmode={'multiplecellsadvanced'}
/>
<br /><br />
<JqxButton ref='addItem' value='Add Item' style={{ float: 'left' }}/>
<JqxButton ref='deleteItem' value='Delete Item' style={{ float: 'left' }}/>
<JqxButton ref='updateItem' value='Update Item' style={{ float: 'left' }}/>
<JqxButton ref='updatePath' value='Update Path' style={{ float: 'left' }}/>
<br />
<div id='log' style={{ clear: 'both' }} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/action/label.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLabel = (props) => (
<SvgIcon {...props}>
<path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12l-4.37-6.16z"/>
</SvgIcon>
);
ActionLabel = pure(ActionLabel);
ActionLabel.displayName = 'ActionLabel';
export default ActionLabel;
|
src/basic/Textarea.js | sampsasaarela/NativeBase | import React, { Component } from 'react';
import { TextInput } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import variables from '../theme/variables/platform';
import computeProps from '../Utils/computeProps';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
class Textarea extends Component {
getStyle() {
return {
textarea: {
height: (this.props.rowSpan) ? this.props.rowSpan * 25 : 60,
},
};
}
prepareRootProps() {
const defaultProps = {
style: this.getStyle().textarea,
};
return computeProps(this.props, defaultProps);
}
render() {
return (
<TextInput
ref={(c) => { this._textInput = c; this._root = c; }} {...this.prepareRootProps()}
multiline
placeholderTextColor={this.props.placeholderTextColor ? this.props.placeholderTextColor : variables.inputColorPlaceholder} underlineColorAndroid="rgba(0,0,0,0)"
/>
);
}
}
Textarea.propTypes = {
...TextInput.propTypes,
style: React.PropTypes.object,
rowSpan: React.PropTypes.number,
bordered: React.PropTypes.bool,
underline: React.PropTypes.bool,
};
const StyledTextarea = connectStyle('NativeBase.Textarea', {}, mapPropsToStyleNames)(Textarea);
export {
StyledTextarea as Textarea,
};
|
src/svg-icons/av/not-interested.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvNotInterested = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/>
</SvgIcon>
);
AvNotInterested = pure(AvNotInterested);
AvNotInterested.displayName = 'AvNotInterested';
AvNotInterested.muiName = 'SvgIcon';
export default AvNotInterested;
|
src/svg-icons/image/center-focus-strong.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCenterFocusStrong = (props) => (
<SvgIcon {...props}>
<path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-7 7H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z"/>
</SvgIcon>
);
ImageCenterFocusStrong = pure(ImageCenterFocusStrong);
ImageCenterFocusStrong.displayName = 'ImageCenterFocusStrong';
export default ImageCenterFocusStrong;
|
examples/js/selection/select-bgcolor-table.js | dana2208/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
bgColor: 'pink'
};
export default class SelectBgColorTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/scenes/ProductView/index.native.js | Manuelandro/Universal-Commerce | import React from 'react'
import { graphql, compose } from 'react-apollo'
import { ProductViewQuery } from '../../../server/graphql/queries/product'
import ProductView from './component.native'
import { ScrollView } from '../../components/native'
const ProductViewWithData = (props) =>
(
<ScrollView>
<ProductView {...props} />
</ScrollView>
)
const ProductViewQueryOptions = {
options: ({ product: { id } }) => ({
variables: {
product: parseInt(id, 10)
}
}),
props: ({ ownProps, data: { loading, error, product } }) => ({
...ownProps, loading, error, product
})
}
export default compose(
graphql(ProductViewQuery, ProductViewQueryOptions)
)(ProductViewWithData) |
packages/bonde-admin-canary/src/components/Tutorial/Provider.js | ourcities/rebu-client | // Provider is responsible to union Dialog components
import React from 'react'
import PropTypes from 'prop-types'
import Context, { defaultContext } from './Context'
import Dialog from './Dialog'
const initializeCondition = initialize => (
typeof initialize === 'function'
? initialize()
: initialize
)
class Provider extends React.Component {
static Dialog = Dialog
state = {
...defaultContext,
initialize: this.props.initialize
}
//
// Class attribute that stores all childrens keys
// in rendering runtime, to update Provider state with it.
//
registeredStepKeys = []
componentDidMount () {
if (initializeCondition(this.props.initialize)) {
this.setState({ currentStep: 1 })
}
}
static getDerivedStateFromProps (props, state) {
if (props.initialize !== state.initialize) {
const stateChanged = {}
if (initializeCondition(props.initialize)) {
stateChanged.currentStep = 1
}
else if (!initializeCondition(props.initialize) && state.currentStep !== 0) {
stateChanged.currentStep = 0
}
return { initialize: props.initialize, ...stateChanged }
}
return null
}
registerStep (key) {
if (!this.registeredStepKeys.includes(key)) {
this.registeredStepKeys.push(key)
this.setState({ steps: this.registeredStepKeys })
}
}
onNext () {
const { steps, currentStep } = this.state
this.setState({
currentStep: steps.length === currentStep ? 1 : currentStep + 1
})
}
onClose () {
this.setState({ currentStep: 0 })
this.props.onClose && this.props.onClose()
}
render () {
const context = {
registerStep: this.registerStep.bind(this),
onNext: this.onNext.bind(this),
onClose: this.onClose.bind(this),
currentStep: this.state.currentStep,
total: this.state.steps.length
}
return (
<Context.Provider value={context}>
{this.props.children}
</Context.Provider>
)
}
}
Provider.defaultProps = {
initialize: false
}
Provider.propTypes = {
initialize: PropTypes.oneOfType([
PropTypes.func,
PropTypes.bool
]),
onClose: PropTypes.func
}
export default Provider
|
app/components/SoundPlayer/ShowSoundPlayer.js | juanda99/arasaac-frontend | import React from 'react'
import SoundPlayer from './index';
import GetAppIcon from 'material-ui/svg-icons/action/get-app'
import IconButton from 'material-ui/IconButton'
import {
LOCUTIONS_URL,
} from 'services/config'
import {downloadLocution } from 'services'
const ShowSoundPlayer = ({hasLocution, locale, keyword, download, onDownloadLocution}) => {
// split('/').join("\\\\") for pictos like 1/3, rewrote to 1\\3 for file system restrictions
const streamUrl = hasLocution ? `${LOCUTIONS_URL}/${locale}/${encodeURIComponent(keyword.toLowerCase().split('/').join('\\\\'))}.mp3` : null
return (
<div style={{ display: 'flex' }}>
{!download &&
<SoundPlayer
crossOrigin='anonymous'
streamUrl={streamUrl}
keyword={keyword}
preloadType='metadata'
showProgress={false}
showTimer={false}
/>
}
{download && hasLocution && (
<IconButton
touch={true}
onClick={
()=> (window.location = downloadLocution(locale, keyword))
}
>
<GetAppIcon />
</IconButton>
)}
</div>
)
}
export default ShowSoundPlayer
|
src/components/Charts/Bar/index.js | ascrutae/sky-walking-ui | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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, { Component } from 'react';
import { Chart, Axis, Tooltip, Geom } from 'bizcharts';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import autoHeight from '../autoHeight';
import styles from '../index.less';
@autoHeight()
class Bar extends Component {
state = {
autoHideXLabels: false,
};
componentDidMount() {
window.addEventListener('resize', this.resize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
@Bind()
@Debounce(400)
resize() {
if (!this.node) {
return;
}
const canvasWidth = this.node.parentNode.clientWidth;
const { data = [], autoLabel = true } = this.props;
if (!autoLabel) {
return;
}
const minWidth = data.length * 30;
const { autoHideXLabels } = this.state;
if (canvasWidth <= minWidth) {
if (!autoHideXLabels) {
this.setState({
autoHideXLabels: true,
});
}
} else if (autoHideXLabels) {
this.setState({
autoHideXLabels: false,
});
}
}
handleRoot = (n) => {
this.root = n;
};
handleRef = (n) => {
this.node = n;
};
render() {
const {
height,
title,
forceFit = true,
data,
color = 'rgba(24, 144, 255, 0.85)',
padding,
} = this.props;
const { autoHideXLabels } = this.state;
const scale = {
x: {
type: 'cat',
},
y: {
min: 0,
},
};
const tooltip = [
'x*y',
(x, y) => ({
name: x,
value: y,
}),
];
return (
<div className={styles.chart} style={{ height }} ref={this.handleRoot}>
<div ref={this.handleRef}>
{title && <h4 style={{ marginBottom: 20 }}>{title}</h4>}
<Chart
scale={scale}
height={title ? height - 41 : height}
forceFit={forceFit}
data={data}
padding={padding || 'auto'}
>
<Axis
name="x"
title={false}
label={autoHideXLabels ? false : {}}
tickLine={autoHideXLabels ? false : {}}
/>
<Axis name="y" min={0} />
<Tooltip showTitle={false} crosshairs={false} />
<Geom type="interval" position="x*y" color={color} tooltip={tooltip} />
</Chart>
</div>
</div>
);
}
}
export default Bar;
|
fields/types/boolean/BooleanFilter.js | stosorio/keystone | import React from 'react';
import { SegmentedControl } from 'elemental';
const TOGGLE_OPTIONS = [
{ label: 'Is Checked', value: true },
{ label: 'Is NOT Checked', value: false }
];
var BooleanFilter = React.createClass({
getInitialState () {
return {
checked: this.props.value || TOGGLE_OPTIONS[0].value
};
},
toggleChecked (checked) {
this.setState({
checked: checked
});
},
render () {
return <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.checked} onChange={this.toggleChecked} />;
}
});
module.exports = BooleanFilter;
|
client/components/ui/tabs.js | bnjbvr/kresus | import React from 'react';
import { Route, Switch, Redirect, NavLink } from 'react-router-dom';
import PropTypes from 'prop-types';
class TabsContainer extends React.Component {
handleSelectorChange = event => {
let newPath = event.target.value;
// Only modify current path if necessary
if (this.props.location.pathname !== newPath) {
this.props.history.push(newPath);
}
};
render() {
let routes = [];
let tabsLinks = [];
let tabsOptions = [];
for (let [path, tab] of this.props.tabs) {
routes.push(<Route key={path} path={path} component={tab.component} />);
tabsLinks.push(
<li key={path}>
<NavLink activeClassName="active" to={path}>
{tab.name}
</NavLink>
</li>
);
tabsOptions.push(
<option key={path} value={path}>
{tab.name}
</option>
);
}
return (
<React.Fragment>
<div className="tabs-container-selector">
<ul>{tabsLinks}</ul>
<select
className="form-element-block"
value={this.props.selectedTab}
onChange={this.handleSelectorChange}>
{tabsOptions}
</select>
</div>
<div className="tab-content">
<Switch>
{routes}
<Redirect to={this.props.defaultTab} push={false} />
</Switch>
</div>
</React.Fragment>
);
}
}
TabsContainer.propTypes = {
// A map of tabs to display where the key is the tab identifier and the value
// is the tab's name and component.
tabs: PropTypes.instanceOf(Map).isRequired,
// The default tab.
defaultTab: PropTypes.string.isRequired,
// The selected tab.
selectedTab: (props, propName, componentName) => {
if (
typeof props.selectedTab !== 'undefined' &&
typeof props.selectedTab !== 'string' &&
!props.tabs.has(props.selectedTab)
) {
return new Error(
`Invalid prop 'selectedTab' of ${componentName} should be a key in 'tabs' prop if defined`
);
}
},
// The history object, providing access to the history API.
history: PropTypes.object.isRequired,
// Location object (contains the current path).
location: PropTypes.object.isRequired
};
export default TabsContainer;
|
app/javascript/mastodon/features/ui/components/column_link.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const ColumnLink = ({ icon, text, to, href, method, badge }) => {
const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null;
if (href) {
return (
<a href={href} className='column-link' data-method={method}>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</a>
);
} else {
return (
<Link to={to} className='column-link'>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</Link>
);
}
};
ColumnLink.propTypes = {
icon: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
to: PropTypes.string,
href: PropTypes.string,
method: PropTypes.string,
badge: PropTypes.node,
};
export default ColumnLink;
|
src/components/molecules/Feature/index.js | DimensionLab/narc | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { ifProp } from 'styled-tools'
import { Icon, Link, Paragraph, Heading, Badge, PreformattedText } from 'components'
const Wrapper = styled.div`
position: relative;
display: flex;
padding: 1rem;
box-sizing: border-box;
opacity: ${ifProp('soon', 0.4, 1)};
@media screen and (max-width: 640px) {
padding: 0.5rem;
}
`
const StyledIcon = styled(Icon)`
flex: none;
@media screen and (max-width: 640px) {
width: 32px;
}
`
const Text = styled.div`
margin-left: 1rem;
overflow: auto;
> :first-child {
margin: 0;
}
`
const StyledBadge = styled(Badge)`
position: absolute;
top: 1rem;
right: 1rem;
@media screen and (max-width: 640px) {
top: 0.5rem;
right: 0.5rem;
}
`
const Feature = ({
icon, title, link, code, children, ...props
}) => {
return (
<Wrapper {...props}>
{icon && <StyledIcon icon={icon} width={64} />}
<Text>
<Heading level={2}>
{link ? <Link href={link}>{title}</Link> : title}
</Heading>
<Paragraph>{children}</Paragraph>
{code && <PreformattedText block>{code}</PreformattedText>}
</Text>
{props.soon && <StyledBadge palette="grayscale">soon</StyledBadge>}
</Wrapper>
)
}
Feature.propTypes = {
title: PropTypes.string.isRequired,
icon: PropTypes.string,
link: PropTypes.string,
soon: PropTypes.bool,
children: PropTypes.any,
code: PropTypes.node,
}
export default Feature
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.