path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
12_ReactJS Fundamentals/03_events_and_forms/src/index.js
akkirilov/SoftUniProject
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
frontend/src/components/common/hoc/withConditionalDisplay.js
unicef/un-partner-portal
// eslint-disable-next-line import React from 'react'; import R from 'ramda'; import { connect } from 'react-redux'; const mapStateToProps = conditions => (state) => { const displayComponent = R.reduce((acc, next) => { if (typeof next === 'function') return acc && next(state); return acc && next; }, true, conditions); return { displayComponent, }; }; export default (conditions = [true]) => WrappedComponent => connect(mapStateToProps(conditions))( (props) => { const { displayComponent, ...other } = props; if (!displayComponent) return null; return ( <WrappedComponent {...other} />); }, );
react/dashboard_example/src/server.js
webmaster444/webmaster444.github.io
import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; // import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import React from 'react'; import ReactDOM from 'react-dom/server'; import UniversalRouter from 'universal-router'; import PrettyError from 'pretty-error'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import passport from './core/passport'; // import models from './data/models'; // import schema from './data/schema'; import routes from './routes'; import assets from './assets'; // eslint-disable-line import/no-unresolved import { port, auth } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, })); app.use(passport.initialize()); app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }) ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); } ); // // Register API middleware // ----------------------------------------------------------------------------- // app.use('/graphql', expressGraphQL(req => ({ // schema, // graphiql: true, // rootValue: { request: req }, // pretty: process.env.NODE_ENV !== 'production', // }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { let css = new Set(); let statusCode = 200; const data = { title: '', description: '', style: '', script: assets.main.js, children: '' }; await UniversalRouter.resolve(routes, { path: req.path, query: req.query, context: { insertCss: (...styles) => { styles.forEach(style => css.add(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len }, setTitle: value => (data.title = value), setMeta: (key, value) => (data[key] = value), }, render(component, status = 200) { // console.log('inside render of UniversalRouter', component); css = new Set(); statusCode = status; data.children = ReactDOM.renderToString(component); data.style = [...css].join(''); return true; }, }); // console.log('outside render func of UniversalRouter with statusCode', statusCode); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode); res.send(`<!doctype html>${html}`); } catch (err) { // console.log('some error occured', err); next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const statusCode = err.status || 500; const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html> ); res.status(statusCode); res.send(`<!doctype html>${html}`); }); app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ // models.sync().catch(err => console.error(err.stack)).then(() => { // app.listen(port, () => { // console.log(`The server is running at http://localhost:${port}/`); // }); // }); /* eslint-enable no-console */
node_modules/antd/es/table/SelectionCheckboxAll.js
ZSMingNB/react-news
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import Checkbox from '../checkbox'; import Dropdown from '../dropdown'; import Menu from '../menu'; import Icon from '../icon'; import classNames from 'classnames'; var SelectionCheckboxAll = function (_React$Component) { _inherits(SelectionCheckboxAll, _React$Component); function SelectionCheckboxAll(props) { _classCallCheck(this, SelectionCheckboxAll); var _this = _possibleConstructorReturn(this, (SelectionCheckboxAll.__proto__ || Object.getPrototypeOf(SelectionCheckboxAll)).call(this, props)); _this.handleSelectAllChagne = function (e) { var checked = e.target.checked; _this.props.onSelect(checked ? 'all' : 'removeAll', 0, null); }; _this.defaultSelections = [{ key: 'all', text: props.locale.selectAll, onSelect: function onSelect() {} }, { key: 'invert', text: props.locale.selectInvert, onSelect: function onSelect() {} }]; _this.state = { checked: _this.getCheckState(props), indeterminate: _this.getIndeterminateState(props) }; return _this; } _createClass(SelectionCheckboxAll, [{ key: 'componentDidMount', value: function componentDidMount() { this.subscribe(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.setCheckState(nextProps); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); } } }, { key: 'subscribe', value: function subscribe() { var _this2 = this; var store = this.props.store; this.unsubscribe = store.subscribe(function () { _this2.setCheckState(_this2.props); }); } }, { key: 'checkSelection', value: function checkSelection(data, type, byDefaultChecked) { var _props = this.props, store = _props.store, getCheckboxPropsByItem = _props.getCheckboxPropsByItem, getRecordKey = _props.getRecordKey; // type should be 'every' | 'some' if (type === 'every' || type === 'some') { return byDefaultChecked ? data[type](function (item, i) { return getCheckboxPropsByItem(item, i).defaultChecked; }) : data[type](function (item, i) { return store.getState().selectedRowKeys.indexOf(getRecordKey(item, i)) >= 0; }); } return false; } }, { key: 'setCheckState', value: function setCheckState(props) { var checked = this.getCheckState(props); var indeterminate = this.getIndeterminateState(props); if (checked !== this.state.checked) { this.setState({ checked: checked }); } if (indeterminate !== this.state.indeterminate) { this.setState({ indeterminate: indeterminate }); } } }, { key: 'getCheckState', value: function getCheckState(props) { var store = props.store, data = props.data; var checked = void 0; if (!data.length) { checked = false; } else { checked = store.getState().selectionDirty ? this.checkSelection(data, 'every', false) : this.checkSelection(data, 'every', false) || this.checkSelection(data, 'every', true); } return checked; } }, { key: 'getIndeterminateState', value: function getIndeterminateState(props) { var store = props.store, data = props.data; var indeterminate = void 0; if (!data.length) { indeterminate = false; } else { indeterminate = store.getState().selectionDirty ? this.checkSelection(data, 'some', false) && !this.checkSelection(data, 'every', false) : this.checkSelection(data, 'some', false) && !this.checkSelection(data, 'every', false) || this.checkSelection(data, 'some', true) && !this.checkSelection(data, 'every', true); } return indeterminate; } }, { key: 'renderMenus', value: function renderMenus(selections) { var _this3 = this; return selections.map(function (selection, index) { return React.createElement( Menu.Item, { key: selection.key || index }, React.createElement( 'div', { onClick: function onClick() { _this3.props.onSelect(selection.key, index, selection.onSelect); } }, selection.text ) ); }); } }, { key: 'render', value: function render() { var _props2 = this.props, disabled = _props2.disabled, prefixCls = _props2.prefixCls, selections = _props2.selections, getPopupContainer = _props2.getPopupContainer; var _state = this.state, checked = _state.checked, indeterminate = _state.indeterminate; var selectionPrefixCls = prefixCls + '-selection'; var customSelections = null; if (selections) { var newSelections = Array.isArray(selections) ? this.defaultSelections.concat(selections) : this.defaultSelections; var menu = React.createElement( Menu, { className: selectionPrefixCls + '-menu', selectedKeys: [] }, this.renderMenus(newSelections) ); customSelections = React.createElement( Dropdown, { overlay: menu, getPopupContainer: getPopupContainer }, React.createElement( 'div', { className: selectionPrefixCls + '-down' }, React.createElement(Icon, { type: 'down' }) ) ); } return React.createElement( 'div', { className: selectionPrefixCls }, React.createElement(Checkbox, { className: classNames(_defineProperty({}, selectionPrefixCls + '-select-all-custom', customSelections)), checked: checked, indeterminate: indeterminate, disabled: disabled, onChange: this.handleSelectAllChagne }), customSelections ); } }]); return SelectionCheckboxAll; }(React.Component); export default SelectionCheckboxAll;
webapp/app/components/CreateUser/Form/Buttons/index.js
EIP-SAM/SAM-Solution-Node-js
// // Component email form in create user page // import React from 'react'; import { browserHistory } from 'react-router'; import { ButtonToolbar } from 'react-bootstrap'; import LinkContainerButton from 'components/Button'; import styles from 'components/CreateUser/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class CreateUserFormButtons extends React.Component { static handleCancelClick() { browserHistory.goBack(); } handleCreateClick(event) { event.preventDefault(); if (this.props.username !== '' && this.props.email !== '' && this.props.password !== '' && this.props.passwordConfirmation !== '') { this.props.createUserRequest(this.props.username, this.props.email, this.props.password, this.props.passwordConfirmation, this.props.selectedGroup); } if (this.props.username === '') { this.props.usernameErrorMsg('A user must have a name'); } if (this.props.email === '') { this.props.emailErrorMsg('A user must have an email'); } if (this.props.password === '') { this.props.passwordErrorMsg('A user must have a password'); } if (this.props.passwordConfirmation === '') { this.props.passwordConfirmationErrorMsg('Please confirmation your password'); } } render() { return ( <ButtonToolbar className={styles.toolbar}> <LinkContainerButton buttonType="submit" buttonBsStyle="info" buttonText="Create" onClick={event => this.handleCreateClick(event)} /> <LinkContainerButton buttonBsStyle="default" buttonText="Cancel" onClick={() => CreateUserFormButtons.handleCancelClick()} /> </ButtonToolbar> ); } } CreateUserFormButtons.propTypes = { username: React.PropTypes.string, email: React.PropTypes.string, password: React.PropTypes.string, passwordConfirmation: React.PropTypes.string, selectedGroup: React.PropTypes.arrayOf(React.PropTypes.string), createUserRequest: React.PropTypes.func, usernameErrorMsg: React.PropTypes.func, emailErrorMsg: React.PropTypes.func, passwordErrorMsg: React.PropTypes.func, passwordConfirmationErrorMsg: React.PropTypes.func, };
src/icons/FaceIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FaceIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M18 23.5c-1.38 0-2.5 1.12-2.5 2.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5-1.12-2.5-2.5-2.5zm12 0c-1.38 0-2.5 1.12-2.5 2.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5-1.12-2.5-2.5-2.5zM24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16 0-.58.04-1.15.1-1.71 4.71-2.09 8.47-5.95 10.42-10.74 3.62 5.1 9.57 8.45 16.31 8.45 1.55 0 3.06-.19 4.5-.53.43 1.44.67 2.96.67 4.53 0 8.82-7.18 16-16 16z"/></svg>;} };
blueocean-material-icons/src/js/components/svg-icons/image/vignette.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageVignette = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 15c-4.42 0-8-2.69-8-6s3.58-6 8-6 8 2.69 8 6-3.58 6-8 6z"/> </SvgIcon> ); ImageVignette.displayName = 'ImageVignette'; ImageVignette.muiName = 'SvgIcon'; export default ImageVignette;
client/scripts/src/app.js
lina/tictactoe
import React from 'react'; import ReactDOM from 'react-dom'; // Import components import Board from './board.jsx'; // import css stylesheet import './stylesheets/main.scss'; // render the loading screen ReactDOM.render( <Board/>, document.getElementById('tic-tac-toe-view-placeholder'));
src/components/drupal/original/DrupalOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DrupalOriginal.svg' /** DrupalOriginal */ function DrupalOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'DrupalOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DrupalOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DrupalOriginal
src/components/footer/index.js
Tsarpf/babel-webpack-react-router-eslint-boilerplate
import React from 'react'; export default class Footer extends React.Component { render() { return ( <div> <hr/> <p> Footer that shows in every page </p> </div> ) } }
app/javascript/mastodon/features/standalone/community_timeline/index.js
honpya/taketodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { refreshCommunityTimeline, expandCommunityTimeline, } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { defineMessages, injectIntl } from 'react-intl'; import { connectCommunityStream } from '../../../actions/streaming'; const messages = defineMessages({ title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' }, }); @connect() @injectIntl export default class CommunityTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch } = this.props; dispatch(refreshCommunityTimeline()); this.disconnect = dispatch(connectCommunityStream()); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = () => { this.props.dispatch(expandCommunityTimeline()); } render () { const { intl } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='users' title={intl.formatMessage(messages.title)} onClick={this.handleHeaderClick} /> <StatusListContainer timelineId='community' loadMore={this.handleLoadMore} scrollKey='standalone_public_timeline' trackScroll={false} /> </Column> ); } }
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsUninitialized.js
samwgoldman/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps: DefaultProps; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps: DefaultProps; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
app/components/UserProfile.js
jmpressman/REACTO-platform
import React from 'react'; import { Jumbotron, Button, Card, CardImg, CardText, CardBlock, CardTitle, CardSubtitle } from 'reactstrap'; import {connect} from 'react-redux'; const UserProfile = (props) => { return ( <div className="col-lg-10"> <Jumbotron> <h3 className="display-3">Welcome, {props.user && props.user.name}</h3> <Card> <CardImg top width="25%" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap" /> <CardBlock> <CardTitle>User email</CardTitle> <CardSubtitle>User stuff</CardSubtitle> <CardText>More user info goes here</CardText> </CardBlock> </Card> </Jumbotron> </div> ); }; const mapStateToProps = (state) => { return { user: state.auth }; }; export default connect(mapStateToProps, null)(UserProfile);
client/src/app/components/forms/inputs/Clockpicker.js
zraees/sms-project
import React from 'react' import 'script-loader!clockpicker/dist/bootstrap-clockpicker.min.js' export default class Clockpicker extends React.Component { componentDidMount() { const element = $(this.refs.input); const options = { placement: 'top', donetext: 'Done' }; element.clockpicker(options); } render() { return ( <input type="text" {...this.props} ref="input"/> ) } }
src/components/common/Operations/OperationLog.js
ndxm/NDReactBoilerplate
import React from 'react'; import Styles from './OperationLogs.css'; import _ from 'underscore'; import DateUtils from '../../../utils/DateUtils'; import OptionsDomain from '../../../constants/OptionsDomain' import OptionsStore from '../../../stores/OptionsStore' var OperationLog = React.createClass({ propTypes: { item: React.PropTypes.object }, _matchValue(_value){ if(!_value){ return '空'; } if(typeof _value == 'number' && _value>10000000000){ return DateUtils.returnDateString(_value); } if(_value===true){ return '是'; } if(_value===false){ return '否'; } let result ; Object.keys(OptionsDomain).forEach( (key)=> { OptionsStore.getOptions(OptionsDomain[key]).forEach((option)=>{ if(option.value ===_value ){ result = option.display; } }); }); return (!result) ? _value : result; }, _getLogContent(log){ let auditUser = !!log['created_by']['name'] ? log['created_by']['name'] : log['created_by']['id']; let option = log['op']; let optionTime = DateUtils.returnTimeString(log['created_date']); let logContent; switch (option) { case 'ADD': logContent = `${auditUser} 创建了该记录 ${optionTime}`; break; case 'UPDATE': let filedName = log['entity_field']['filed_name']; let oldValue = log['entity_field']['old_value']; let newValue = log['entity_field']['new_value']; if(_.isArray(newValue)){ if (!oldValue || newValue.length > oldValue.length) { logContent = `${auditUser} 修改了该记录字段(${filedName}):新增一条记录 ${optionTime}`; } else if (oldValue.length > newValue.length) { logContent = `${auditUser} 修改了该记录字段(${filedName}):减少一条记录 ${optionTime}`; } break; } let oldValueDisplay = this._matchValue(oldValue); let newValueDisplay = this._matchValue(newValue); logContent = `${auditUser} 修改了该记录字段(${filedName}):'${oldValueDisplay}' -> '${newValueDisplay}' ${optionTime}`; break; case 'DELETE': logContent = `${auditUser} 删除了该记录 ${optionTime}`; break; default : logContent = log['log_ontent']; break; } return logContent; }, _getIcon(log){ let icon; switch (log['op']) { case 'ADD': icon = <i className={'icon-plus '+Styles['icon'] }/>; break; case 'UPDATE': icon = <i className={'icon-pencil '+Styles['icon'] }/>; break; default : icon = <i className={'icon-pencil '+Styles['icon'] }/>; break; } return icon; }, render() { return ( <div className={Styles['log']}> {this._getIcon(this.props.item)} {this._getLogContent(this.props.item)} </div> ) } }); export default OperationLog;
src/svg-icons/notification/sim-card-alert.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSimCardAlert = (props) => ( <SvgIcon {...props}> <path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 15h-2v-2h2v2zm0-4h-2V8h2v5z"/> </SvgIcon> ); NotificationSimCardAlert = pure(NotificationSimCardAlert); NotificationSimCardAlert.displayName = 'NotificationSimCardAlert'; NotificationSimCardAlert.muiName = 'SvgIcon'; export default NotificationSimCardAlert;
frontend/src/index.js
tdv-casts/website
// @flow import injectTapEventPlugin from 'react-tap-event-plugin'; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom' import App from './App'; import './index.css'; injectTapEventPlugin(); ReactDOM.render( ( <BrowserRouter> <App /> </BrowserRouter> ), document.getElementById('root') );
src/index.js
worms618/React-Component-Generator
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root'));
src/routes.js
aries-auto/ariesautomotive
import React from 'react'; import ga from 'react-ga'; import Router from 'react-routing/src/Router'; import App from './components/App'; import BecomeDealer from './components/BecomeDealer'; import Product from './components/Product'; import Category from './components/Category'; import CategoryTree from './components/CategoryTree'; import Contact from './components/Contact'; import CustomContent from './components/CustomContent'; import Home from './components/Home'; import SearchResults from './components/SearchResults'; import VehicleResults from './components/VehicleResults'; import LuverneResults from './components/LuverneResults'; // import WhereToBuy from './components/WhereToBuy'; import About from './components/About'; import AppGuides from './components/AppGuides'; import AppGuide from './components/AppGuides/AppGuide'; import Terms from './components/Terms'; import Warranties from './components/Warranties'; import LatestNews from './components/LatestNews'; import LatestNewsItem from './components/LatestNewsItem'; import LandingPage from './components/LandingPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; import { siteMenu, googleAnalyticsId, brand } from './config'; import VehicleStore from './stores/VehicleStore'; import LuverneStore from './stores/LuverneStore'; import ContactStore from './stores/ContactStore'; import ProductStore from './stores/ProductStore'; import AppGuideStore from './stores/AppGuideStore'; import GeographyStore from './stores/GeographyStore'; import CategoryStore from './stores/CategoryStore'; import SiteStore from './stores/SiteStore'; import SearchStore from './stores/SearchStore'; import cookie from 'react-cookie'; const isBrowser = typeof window !== 'undefined'; const gaOptions = { debug: true }; const MyWindowDependentLibrary = isBrowser ? ga.initialize(googleAnalyticsId, gaOptions) : undefined; const router = new Router(on => { on('*', async (state, next) => { if (!state.context) { state.context = {}; } state.context.params = state.params; state.context.siteMenu = siteMenu; const slug = state.params[0].replace(/\//g, ''); const cookieVehicle = cookie.load('vehicle'); const cookieVehicleLuverne = cookie.load('vehicleluverne'); if (slug === '_ahhealth' || slug.indexOf('health') >= 0) { return null; } if (state.path.indexOf('/vehicle') === -1) { // don't want to request this here, since we'll be doing it in the route if (brand.id === 4) { await Promise.all([ cookieVehicleLuverne ? LuverneStore.fetchVehicle(cookieVehicleLuverne.base_vehicle.year, cookieVehicleLuverne.base_vehicle.make, cookieVehicleLuverne.base_vehicle.model) : LuverneStore.fetchVehicle(), ]); } else { await Promise.all([ cookieVehicle ? VehicleStore.fetchVehicle(cookieVehicle.base.year, cookieVehicle.base.make, cookieVehicle.base.model) : VehicleStore.fetchVehicle(), ]); } } await Promise.all([ SiteStore.fetchPageData(slug), CategoryStore.fetchCategories(), SiteStore.fetchContentMenus(), ]); if (MyWindowDependentLibrary !== undefined) { ga.initialize(googleAnalyticsId, gaOptions); } ga.pageview('aries:' + state.path); const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/part/:id', async (state) => { await Promise.all([ ProductStore.fetchFeatured(), ProductStore.fetchProduct(state.params.id), ]); return <Product {...state} />; }); on('/category', async (state) => { return <CategoryTree context={state.context} />; }); on('/category/:id', async (state) => { await CategoryStore.fetchCategory(state.params.id); const cat = CategoryStore.getCategory(state.params.id); let prods = []; if (!cat.vehicle_specific) { await CategoryStore.fetchProducts(state.params.id); prods = CategoryStore.getProducts(); } state.context.canonical = encodeURI(`https://www.${brand.domain}/category/${state.params.id}/${cat.title}`); return <Category context={state.context} category={cat} categoryProducts={prods} />; }); on('/category/:id/:title', async (state) => { await CategoryStore.fetchCategory(state.params.id); const cat = CategoryStore.getCategory(state.params.id); let prods = {}; if (!cat.vehicle_specific) { await CategoryStore.fetchProducts(state.params.id); prods = CategoryStore.getProducts(); } state.context.canonical = encodeURI(`https://www.${brand.domain}/category/${state.params.id}/${cat.title}`); return <Category context={state.context} category={cat} categoryProducts={prods} />; }); on('/category/:id/:title/:sub', async (state) => { await CategoryStore.fetchCategory(state.params.id); const cat = CategoryStore.getCategory(state.params.id); let prods = []; if (!cat.vehicle_specific) { await CategoryStore.fetchProducts(state.params.id); prods = CategoryStore.getProducts(); } return <Category context={state.context} category={cat} categoryProducts={prods} />; }); on('/search/:term', async (state) => { await SearchStore.fetchSearchResults(state.params.term); return <SearchResults context={state.context} />; }); on('/search', async (state) => { await SearchStore.fetchSearchResults(state.query.term); return <SearchResults context={state.context} />; }); on('/vehicle', async (state) => { state.context.params = state.params; if (brand.id === 4) { return <LuverneResults context={state.context} />; } return <VehicleResults context={state.context} />; }); on('/vehicle/:year', async (state) => { state.context.params = state.params; if (brand.id === 4) { return <LuverneResults context={state.context} />; } return <VehicleResults context={state.context} />; }); on('/vehicle/:year/:make', async (state) => { state.context.params = state.params; if (brand.id === 4) { return <LuverneResults context={state.context} />; } return <VehicleResults context={state.context} />; }); on('/vehicle/:year/:make/:model', async (state) => { state.context.params = state.params; const tmp = { base: { year: state.params.year, make: state.params.make, model: state.params.model, }, }; if (brand.id === 4) { tmp.base_vehicle = tmp.base; tmp.base = []; cookie.save('vehicleluverne', JSON.stringify(tmp), { path: '/' }); await LuverneStore.fetchVehicle(state.params.year, state.params.make, state.params.model); return <LuverneResults context={state.context} win={state.win} />; } cookie.save('vehicle', JSON.stringify(tmp), { path: '/' }); await Promise.all([ VehicleStore.fetchVehicle(state.params.year, state.params.make, state.params.model), VehicleStore.fetchEnvision(state.params.year, state.params.make, state.params.model), ]); return <VehicleResults context={state.context} window={state.win} />; }); on('/about', async (state) => { return <About context={state.context} />; }); on('/appguides', async (state) => { await AppGuideStore.fetchAppGuides(); return <AppGuides context={state.context} />; }); on('/appguides/:guide/:page', async (state) => { const collection = state.params.guide; const page = state.params.page; await AppGuideStore.fetchAppGuide(collection, page); return <AppGuide context={state.context} />; }); on('/becomedealer', async (state) => { await GeographyStore.fetchCountries(); return <BecomeDealer context={state.context} />; }); on('/contact', async (state) => { await Promise.all([ ContactStore.fetchTypes(), GeographyStore.fetchCountries(), ]); return <Contact context={state.context} />; }); on('/terms', async (state) => { return <Terms context={state.context} />; }); on('/news', async (state) => { return <LatestNews context={state.context} />; }); on('/news/:id', async (state) => { await SiteStore.fetchNewsItem(state.params.id); return <LatestNewsItem context={state.context} />; }); on('/buy', async (state, next) => { // redirect for now since its broken. state.redirect = '/'; next(); // state.context.id = state.params.id; // return <WhereToBuy context={state.context} google={state.google} navigator={state.navigator} />; }); on('/warranties', async (state) => { state.context.id = state.params.id; await GeographyStore.fetchCountries(); return <Warranties context={state.context} />; }); on('/styleguard', (state, next) => { state.redirect = '/category/321/Interior/StyleGuard%20Floor%20Liners'; next(); }); on('/page/:id', async (state) => { const siteMenus = SiteStore.getContentMenus(); state.context.id = state.params.id; const id = parseInt(state.context.id, 10) > 0 ? parseInt(state.context.id, 10) : 0; if (siteMenus.length > 0) { const temp = siteMenus.filter((c) => c.id === id); if (temp.length > 0) { state.context.customContent = temp[0]; } } if (state.context.siteContents && state.context.siteContents.length > 0) { const temp = state.context.siteContents.filter((c) => c.id.toString() === state.params.id); if (temp.length > 0) { state.context.customContent = temp[0]; } } return <CustomContent context={state.context} />; }); on('/lp/:id', async (state) => { await SiteStore.fetchLandingPage(state.params.id); return <LandingPage context={state.context} />; }); on('/', async (state) => { await Promise.all([ ProductStore.fetchFeatured(), SiteStore.fetchTestimonials(), ]); return <Home context={state.context} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
frontend/navigation/AppContainer.js
datoszs/czech-lawyers
import React from 'react'; import PropTypes from 'prop-types'; import Navigation from './Navigation'; import Sidebar from './Sidebar'; import Footer from './Footer'; import Redirect from './Redirect'; const AppContainer = ({children}) => ( <div> <Navigation /> <div className="container"> {children} </div> <Sidebar /> <Redirect /> <Footer /> </div> ); AppContainer.propTypes = { children: PropTypes.node, }; AppContainer.defaultProps = { children: null, }; export default AppContainer;
packages/components/src/Actions/ActionDropdown/Dropdown.stories.js
Talend/ui
import React from 'react'; import Immutable from 'immutable'; import { action } from '@storybook/addon-actions'; import ActionDropdown from './ActionDropdown.component'; import FilterBar from '../../FilterBar'; import Action from '../Action'; const myAction = { id: 'context-dropdown-related-items', label: 'related items', icon: 'talend-file-xls-o', items: [ { id: 'context-dropdown-item-document-1', icon: 'talend-file-json-o', label: 'document 1', 'data-feature': 'actiondropdown.items', onClick: action('document 1 click'), }, { divider: true, }, { id: 'context-dropdown-item-document-2', label: 'document 2', 'data-feature': 'actiondropdown.items', onClick: action('document 2 click'), }, ], }; const loadingAdditionalContent = { id: 'context-dropdown-related-items', label: 'related items', loading: true, icon: 'talend-file-xls-o', items: [], }; const contentAndLoadingAdditionalContent = { ...loadingAdditionalContent, items: [ { id: 'context-dropdown-item-document-1', icon: 'talend-file-json-o', label: 'document 1', 'data-feature': 'actiondropdown.items', onClick: action('document 1 click'), }, { divider: true, }, ], }; const withImmutable = { id: 'context-dropdown-related-items', label: 'related immutable items', items: Immutable.fromJS([ { id: 'context-dropdown-item-document-1', icon: 'talend-file-json-o', label: 'document 1', 'data-feature': 'actiondropdown.items', onClick: action('document 1 click'), }, { divider: true, }, { id: 'context-dropdown-item-document-2', label: 'document 2', 'data-feature': 'actiondropdown.items', onClick: action('document 2 click'), }, ]), }; const openWithImmutable = { ...withImmutable, open: true }; const withComponents = { id: 'context-dropdown-custom-items', label: 'custom items', icon: 'talend-file-xls-o', getComponent: key => { if (key === 'Action') { return Action; } else if (key === 'FilterBar') { return FilterBar; } throw new Error('Component not found'); }, components: { itemsDropdown: [ { component: 'Action', label: 'First item', 'data-feature': 'actiondropdown.items', }, { divider: true, }, { component: 'FilterBar', label: 'Second item', 'data-feature': 'actiondropdown.items', onFilter: action('onFilter'), }, ], }, }; const mixItemsComponents = { id: 'context-dropdown-mix-items', label: 'mix items', getComponent: key => { if (key === 'Action') { return Action; } throw new Error('Component not found'); }, items: [ { id: 'context-dropdown-item-document-1', icon: 'talend-file-json-o', label: 'document 1', 'data-feature': 'actiondropdown.items', onClick: action('document 1 click'), }, { divider: true, }, { id: 'context-dropdown-item-document-2', label: 'document 2', 'data-feature': 'actiondropdown.items', onClick: action('document 2 click'), }, ], components: { itemsDropdown: [ { component: 'Action', label: 'Third item', 'data-feature': 'actiondropdown.items', }, { divider: true, }, { component: 'Action', label: 'Fourth item', 'data-feature': 'actiondropdown.items', }, ], }, }; const propsTooltip = { id: 'context-dropdown-tooltip-items', tooltipLabel: 'my tooltip', label: 'Tooltip', items: [ { id: 'context-dropdown-item-document-1', icon: 'talend-file-json-o', label: 'document 1', 'data-feature': 'actiondropdown.items', onClick: action('document 1 click'), }, { divider: true, }, { id: 'context-dropdown-item-document-2', label: 'document 2', 'data-feature': 'actiondropdown.items', onClick: action('document 2 click'), }, ], }; const oneEventAction = { id: 'context-dropdown-events', label: 'Dropdown', items: [ { id: 'item-1', label: 'Item 1', 'data-feature': 'actiondropdown.items' }, { id: 'item-2', label: 'Item 2', 'data-feature': 'actiondropdown.items', }, ], onSelect: action('onItemSelect'), }; export default { title: 'Buttons/Dropdown', }; export const Default = () => ( <div> <h3>By default :</h3> <div id="default"> <ActionDropdown {...myAction} /> </div> <h3>With one event handler:</h3> <div id="oneEvent"> <ActionDropdown {...oneEventAction} /> </div> <h3>With hideLabel option</h3> <div id="hidelabel"> <ActionDropdown {...myAction} hideLabel /> </div> <h3>With ellipsis option</h3> <div id="ellipsis"> <ActionDropdown {...myAction} ellipsis /> </div> <h3>Empty option</h3> <div id="empty"> <ActionDropdown {...myAction} items={[]} hideLabel /> </div> <h3>Dropup</h3> <div id="dropup"> <ActionDropdown {...myAction} dropup /> </div> <h3>Automatic Dropup : this is contained in a restricted ".tc-dropdown-container" element.</h3> <div id="auto-dropup" className="tc-dropdown-container" style={{ border: '1px solid black', overflow: 'scroll', height: '300px' }} > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <br /> ut labore et dolore magna aliqua. <br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco la <br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <br /> ut labore et dolore magna aliqua. <br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco la <br /> <br /> <br /> <br /> <p>Scroll me to set overflow on top or down of the container, then open the dropdown.</p> <ActionDropdown {...myAction} /> <br /> <br /> <br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <br /> ut labore et dolore magna aliqua. <br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco la Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <br /> ut labore et dolore magna aliqua. <br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco la </div> <h3>Type link</h3> <div id="typeLink"> <ActionDropdown {...myAction} link /> </div> <h3>Components Items</h3> <div id="withComponents"> <ActionDropdown {...withComponents} /> </div> <h3>Mix Items</h3> <div id="mixComponents"> <ActionDropdown {...mixItemsComponents} /> </div> <h3>Tool tip</h3> <div id="toolTip"> <ActionDropdown {...propsTooltip} /> </div> <h3>With immutable items :</h3> <div id="default"> <ActionDropdown {...withImmutable} /> </div> <h3>Loading additional content</h3> <div id="loadingAdditionalContent"> <ActionDropdown {...loadingAdditionalContent} /> </div> <h3>Content and loading additional content</h3> <div id="contentAndLoadingAdditionalContent"> <ActionDropdown {...contentAndLoadingAdditionalContent} /> </div> <h3>Opened and with immutable items :</h3> <div id="openImmutable"> <ActionDropdown {...openWithImmutable} /> </div> </div> );
src/components/typography/H3/index.js
apedyashev/react-universal-jobs-aggregator
// libs import React from 'react'; import {PropTypes} from 'prop-types'; import cn from 'classnames'; // other import styles from './index.less'; export default function H3({children, className}) { return ( <h3 className={cn(styles.root, className)}> {children} </h3> ); } H3.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, }; H3.defaultProps = { className: '', };
src/index.js
SaKKo/react-redux-todo-boilerplate
import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import './styles/styles.scss'; //Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. const store = configureStore(); window.store = store; render( <Provider store={store}> <App /> </Provider> , document.getElementById('app') );
src/components/input/rich-text/index.js
KleeGroup/focus-components
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import RichTextEditor from 'react-rte'; // FIX ME cannot import RichTextEditor from 'react-rte/lib/RichTextEditor'; // Due to use of CSS modules /** * Rich text editor, for both edition and consult mode. * See https://github.com/sstur/react-rte for more details and options. * * @class RichTextField * @extends {Component} */ class RichTextField extends Component { static propTypes = { onChange: PropTypes.func.isRequired, value: PropTypes.string.isRequired, language: PropTypes.oneOf('html', 'markdown'), isEdit: PropTypes.bool.isRequired }; static defaultProps = { language: 'markdown' }; /** * Creates an instance of RichTextField. * @param {any} props props from parent * @memberof RichTextField */ constructor(props) { super(props); const { value, language } = this.props; this.state = { value: this.buildValue(value, language) }; this.onChange = this.onChange.bind(this); this.forceChange = this.forceChange.bind(this); } /** @inheritdoc */ componentWillReceiveProps({ value, language }) { // We are only listening to first value, else we have cursor issue in edit mode if (value && !this.props.value) { this.forceChange(value, language); } } /** * Build Value for the editor from a string value and the markup type. * * @param {string} strValue the value * @param {string} language the markup * @returns {object} a value for the editor * @memberof RichTextField */ buildValue(strValue, language) { return strValue ? RichTextEditor.createValueFromString(strValue, language) : RichTextEditor.createEmptyValue() } /** * Method to forcibly change content of editor, if it already have value. * * @param {string} value new value for editor content * @param {string} language the markuo to use (html, markdown) * @memberof RichTextField */ forceChange(value, language) { this.setState({ value: this.buildValue(value, language) }) } /** * Inner onchange on the component, to avoid cursor issue for this component and to return string value. * * @param {object} value Value returned by the RTE component * @memberof RichTextField */ onChange(value) { this.setState({ value }); if (this.props.onChange) { this.props.onChange(value.toString(this.props.language)); } } /** @inheritdoc */ render() { return ( <div> <RichTextEditor {...this.props} value={this.state.value} onChange={this.onChange} readOnly={!this.props.isEdit} /> </div> ); } } export default RichTextField;
client/android/app/src/pages/Email.js
blusclips/zonaster
import React, { Component } from 'react'; import {Image, StyleSheet} from 'react-native'; import { StackNavigator } from 'react-navigation'; import { Container, Content, Text, H1, H3, Button, Item, Input, Grid, Col} from 'native-base'; import general from '../styles/general'; import Icon from 'react-native-vector-icons/FontAwesome'; import SplashScreen from 'react-native-splash-screen'; import { SocialIcon } from 'react-native-elements'; export default class Login extends Component { static navigationOptions = { header:null }; constructor(props) { super(props); this.state = {}; this.props.navigation; } componentDidMount(){ SplashScreen.hide(); } render(){ const { navigate } = this.props.navigation; return( <Container style={{backgroundColor:'#fff'}}> <Content style={{padding:30}}> <H3 style={{textAlign:'center', marginTop:25, marginBottom:80, fontWeight:'bold', fontSize:18}}>Enter Email or Phone to continue</H3> <Item style={general.pad, {marginBottom:60}}> <Icon active name='user-circle' size={20} /> <Input placeholder='Email or Phone'/> </Item> <Button full rounded style={general.pad, general.primaryColorDark} onPress={()=>navigate('signUp')}> <Text>Next</Text> </Button> <Grid style={{marginTop:35, marginBottom:50}}> </Grid> </Content> </Container> ) } }
ReactNativeApp/react-native-starter-app/src/components/general/Placeholder.js
jjhyu/hackthe6ix2017
/** * Placeholder Scene * <Placeholder text={"Hello World"} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Text } from '@ui/'; /* Component ==================================================================== */ const Placeholder = ({ text }) => ( <View style={[AppStyles.container, AppStyles.containerCentered]}> <Text>{text}</Text> </View> ); Placeholder.propTypes = { text: PropTypes.string }; Placeholder.defaultProps = { text: 'Coming soon...' }; Placeholder.componentName = 'Placeholder'; /* Export Component ==================================================================== */ export default Placeholder;
blueocean-material-icons/src/js/components/svg-icons/image/add-to-photos.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageAddToPhotos = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/> </SvgIcon> ); ImageAddToPhotos.displayName = 'ImageAddToPhotos'; ImageAddToPhotos.muiName = 'SvgIcon'; export default ImageAddToPhotos;
src/components/Badge/Badge.js
GetAmbassador/react-ions
import React from 'react' import PropTypes from 'prop-types' import style from './style.scss' import classNames from 'classnames/bind' import Icon from '../Icon' const Badge = props => { const cx = classNames.bind(style) const iconPlusText = (props.icon && props.text) ? 'padded' : null const iconSize = props.size === 'heavy' ? '30' : '16' const badgeClasses = cx(style.badge, props.theme, props.size, props.optClass, iconPlusText) return ( <div className={badgeClasses}> {props.icon ? <Icon name={props.icon} height={iconSize} width={iconSize} /> : null}{props.text ? <span>{props.text}</span> : null} </div> ) } Badge.propTypes = { /** * Background color of the badge. */ theme: PropTypes.string, /** * Icon value to display in the badge. */ icon: PropTypes.string, /** * Text value to display in the badge (number or string). */ text: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]), /** * The size of the badge. */ size: PropTypes.string, /** * Optional CSS class to pass to the badge. */ optClass: PropTypes.string } export default Badge
frontend/containers/board.js
mgi166/usi-front
import React from 'react'; import { connect } from 'react-redux'; import board from '../components/board'; const mapStateToProps = (state) => { return { board: state.shogi.board.board, open: state.promoteModal.open }; }; const Board = connect( mapStateToProps )(board); export default Board;
src/pages/amissima.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Amissima' /> )
src/Loader/Loader.driver.js
nirhart/wix-style-react
import React from 'react'; import ReactDOM from 'react-dom'; import Loader from '../Loader'; const loaderDriverFactory = ({element, wrapper}) => { const isClassExists = (element, className) => !!element && element.className.indexOf(className) !== -1; const text = element.childNodes[1]; return { exists: () => !!element, isSmall: () => isClassExists(element, 'small'), isMedium: () => isClassExists(element, 'medium'), isLarge: () => isClassExists(element, 'large'), hasText: () => isClassExists(text, 'text'), getText: () => text.textContent, setProps: props => { ReactDOM.render(<div ref={r => element = r}><Loader {...props}/></div>, wrapper); }, component: () => element }; }; export default loaderDriverFactory;
test/test_helper.js
RegOpz/RegOpzWebApp
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/HLayout.js
dazhifu/react-touch-ui
import React from 'react'; import { View } from "./View.js" import './Layout.scss' import classnames from 'classnames'; export class HLayout extends View { static propTypes = { /* * 如果一条轴线排不下,如何换行 * wrap 换行,第一行在上方 * nowrap 不换行 * wrap-reverse 换行,第一行在下方 * */ flexWrap: React.PropTypes.string, /* * 水平对其 相当于 Flex 布局的 justify-content * start 起点对齐 * center 中点对齐 * end 终点对齐 * space-between 间隔平均分布 * space-around 每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍 * stretch 轴线占满整个交叉轴 */ ah: React.PropTypes.string, /* * 垂直对其 相当于 Flex 布局的 align-items * start 起点对齐 * center 中点对齐 * end 终点对齐 * space-between 间隔平均分布 * space-around 每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍 * stretch 轴线占满整个交叉轴 */ av: React.PropTypes.string, /* * 自身对其方式 单个项目有与其他项目不一样的对齐方式 相当于 Flex 布局的 align-self * start 起点对齐 * center 中点对齐 * end 终点对齐 * baseline 项目的第一行文字的基线对齐 * stretch 轴线占满整个交叉轴 */ as: React.PropTypes.string }; constructor(props) { super(props); } ; render() { var { flexWrap, ah, av, as, className, ...props } = this.props; var alignjustify; if (ah == "start") { alignjustify = "aui-layout-justify-content-flex-start"; } else if (ah == "center") { alignjustify = "aui-layout-justify-content-center"; } else if (ah == "end") { alignjustify = "aui-layout-justify-content-flex-end"; } else { alignjustify = "aui-layout-justify-content-" + ah; } var alignItemsContent; if (av == "start") { alignItemsContent = "aui-layout-align-items-flex-start"; } else if (av == "center") { alignItemsContent = "aui-layout-align-items-center"; } else if (av == "end") { alignItemsContent = "aui-layout-align-items-flex-end"; } else { alignItemsContent = "aui-layout-align-items-" + av; } var alignSelfContent; if (as == "start") { alignSelfContent = "aui-layout-align-self-flex-start"; } else if (as == "center") { alignSelfContent = "aui-layout-align-self-center"; } else if (as == "end") { alignSelfContent = "aui-layout-align-self-flex-end"; } else { alignSelfContent = "aui-layout-align-self-" + as; } var classname = classnames(className, "aui-layout-flexbox", "aui-layout-row", "aui-layout-" + flexWrap, alignjustify, alignItemsContent, alignSelfContent); //console.log("Layout->render",classname,argType) return ( <View className={classname} // className={ super.classNames("flexbox","column")} {...props} /> ); } }
cmd/manabu-server/ui/app/Components/Multiply.js
nii236/manabu
import React, { Component } from 'react'; import axios from 'axios'; export default class Operands extends Component { constructor(props) { super(props); this.state = { left: 0, right: 0, answer: 'Something' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit() { console.log('Clicked'); const left = this.state.left; const right = this.state.right; axios.get('http://localhost:8080/multiply/' + left + '/' + right) .then((response) => { console.log(response); this.setState({answer: response.data}) }) .catch( (response) => { console.log(response); this.setState({answer: response.data}) }); } handleChange(position, event) { if (position === 'left') { this.setState({left: event.target.value}) } else if (position === 'right') { this.setState({right: event.target.value}) } else { console.error('Invalid position'); } } render() { return ( <div> Please enter your operands <br/> <input className='btn btn-default' onChange={this.handleChange.bind(this, 'left')}/> <br/> x <br/> <input className='btn btn-default' onChange={this.handleChange.bind(this, 'right')}/> <br/> <div className='h1'> = {this.state.answer} </div> <br/> <button className='btn btn-default' onClick={this.handleSubmit}> Submit </button> </div> ); } }
client/app/scripts/components/node-details/node-details-generic-table.js
kinvolk/scope
import React from 'react'; import sortBy from 'lodash/sortBy'; import { Map as makeMap } from 'immutable'; import { NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT } from '../../constants/limits'; import { isNumeric, getTableColumnsStyles, genericTableEntryKey } from '../../utils/node-details-utils'; import NodeDetailsTableHeaders from './node-details-table-headers'; import MatchedText from '../matched-text'; import ShowMore from '../show-more'; function sortedRows(rows, columns, sortedBy, sortedDesc) { const column = columns.find(c => c.id === sortedBy); const sorted = sortBy(rows, (row) => { let value = row.entries[sortedBy]; if (isNumeric(column)) { value = parseFloat(value); } return value; }); if (sortedDesc) { sorted.reverse(); } return sorted; } export default class NodeDetailsGenericTable extends React.Component { constructor(props, context) { super(props, context); this.state = { limit: NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT, sortedBy: props.columns && props.columns[0].id, sortedDesc: true }; this.handleLimitClick = this.handleLimitClick.bind(this); this.updateSorted = this.updateSorted.bind(this); } updateSorted(sortedBy, sortedDesc) { this.setState({ sortedBy, sortedDesc }); } handleLimitClick() { this.setState({ limit: this.state.limit ? 0 : NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT }); } render() { const { sortedBy, sortedDesc } = this.state; const { columns, matches = makeMap() } = this.props; const expanded = this.state.limit === 0; let rows = this.props.rows || []; let notShown = 0; // If there are rows that would be hidden behind 'show more', keep them // expanded if any of them match the search query; otherwise hide them. if (this.state.limit > 0 && rows.length > this.state.limit) { const hasHiddenMatch = rows.slice(this.state.limit).some(row => columns.some(column => matches.has(genericTableEntryKey(row, column)))); if (!hasHiddenMatch) { notShown = rows.length - NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT; rows = rows.slice(0, this.state.limit); } } const styles = getTableColumnsStyles(columns); return ( <div className="node-details-generic-table"> <table> <thead> <NodeDetailsTableHeaders headers={columns} sortedBy={sortedBy} sortedDesc={sortedDesc} onClick={this.updateSorted} /> </thead> <tbody> {sortedRows(rows, columns, sortedBy, sortedDesc).map(row => ( <tr className="node-details-generic-table-row" key={row.id}> {columns.map((column, index) => { const match = matches.get(genericTableEntryKey(row, column)); const value = row.entries[column.id]; return ( <td className="node-details-generic-table-value truncate" title={value} key={column.id} style={styles[index]}> {column.dataType === 'link' ? <a rel="noopener noreferrer" target="_blank" className="node-details-table-node-link" href={value}> {value} </a> : <MatchedText text={value} match={match} /> } </td> ); })} </tr> ))} </tbody> </table> <ShowMore handleClick={this.handleLimitClick} collection={this.props.rows} expanded={expanded} notShown={notShown} /> </div> ); } }
src/components/Store.js
dogsGhost/storefronts
import React from 'react'; const Store = (props) => { let classes = 'store'; if (props.isOccupied) classes += ' isOccupied'; return ( <div className={classes} onClick={(e) => { let tar = e.target; if (tar.classList.length) { tar.classList.toggle('active'); } else { tar.parentNode.classList.toggle('active'); } }}> {props.address} <div className="store-details"> <h4>{props.address} {props.street.name}</h4> <p>{props.isOccupied ? null : 'Vacant'}</p> <p>{props.occupantName ? `Occupant: ${props.occupantName}` : null}</p> <p>{ props.category ? props.category.name : null }</p> <p>{ props.notes ? props.notes : null }</p> </div> </div> ); }; Store.propTypes = { address: React.PropTypes.number.isRequired, isOccupied: React.PropTypes.bool, occupantName: React.PropTypes.string, street: React.PropTypes.object, category: React.PropTypes.object, notes: React.PropTypes.string }; export default Store;
src/App.js
muhammadghazali/mpok-doro-timer
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
src/modules/Talk/routes.js
prjctrft/mantenuto
import React from 'react'; import { Route } from 'react-router'; import ConnectTalkController from './TalkController'; export default ( <Route path='talk' component={ConnectTalkController} /> );
5.ParentChildCommunication/app.js
vishaljadav94/ReactBasic
import React from 'react'; import ReactDom from 'react-dom'; import Welcome from './src/welcome'; import Header from './src/header'; class App extends React.Component { constructor(props) { super(props); this.state = { headerTitle: "Welcome to React" } } render() { return <div> <Header message={this.state.headerTitle}/> <Welcome message={this.showAlert} changeNewHeader={this.changeHeader}/> </div> } showAlert = () => { alert("Welcome to react") }; changeHeader = (newHeaderTitle) => { this.setState({ headerTitle: newHeaderTitle }); } } ReactDom.render( <App/>, document.getElementById("app") ) ;
pages/example-css-modules/css-modules.js
conversataal/conversataal.github.io
import React from 'react' import styles from './example.module.css' import Helmet from 'react-helmet' import { config } from 'config' export default class PostCSS extends React.Component { render () { return ( <div className="container"> <Helmet title={`${config.siteTitle} | Hi PostCSSy friends`} /> <h1 className={styles['the-css-module-class']}> Hi CSS Modules friends </h1> <p>You can use CSS Modules in Gatsby with Postcss, Less, and Sass. They are enabled for any file in the format *.module.* </p> <div className={styles['css-modules-nav-example']}> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
src/components/hello-world/index.js
christiannaths/webpack-react-boilerplate
import React from 'react'; import styles from './index.scss'; export default class HelloWorld extends React.Component { constructor(props){ super(props) } render(){ return ( <div className='hello-world'> <p>Hello world!</p> </div> ); } }
src/Label.js
esbenp/react-native-clean-form
import React from 'react' import { Text, View, Platform } from 'react-native' import PropTypes from 'prop-types' import styled from 'styled-components/native' import defaultTheme from './Theme' const LabelWrapper = styled.View` flex: ${props => props.inlineLabel ? 0.5 : 1}; flex-direction: ${props => props.inlineLabel ? 'row' : 'column'}; flex-direction: column; justify-content: center; padding-left: ${Platform.OS === 'android' ? 5 : 0}; marginTop: ${props => props.inlineLabel ? 0 : 5}; ` const LabelText = styled.Text` color: ${props => props.theme.Label.color}; font-size: ${props => props.theme.Label.fontSize}; ` LabelText.defaultProps = { theme: defaultTheme, componentName: 'Label', } const Label = props => { const { children, inlineLabel, theme } = props return ( <LabelWrapper inlineLabel={inlineLabel} theme={theme}> <LabelText inlineLabel={inlineLabel} theme={theme} >{ children }</LabelText> </LabelWrapper> ) } Label.propTypes = { children: PropTypes.string.isRequired } export default Label
src/App.js
brookslyrette/reactit
import React from 'react'; import logo from './logo.svg'; import './App.css'; import { BrowserRouter, Route, Link } from 'react-router-dom'; import FrontPageContainer from './containers/FrontPageContainer.js'; import SubredditPageContainer from './containers/SubredditPageContainer.js'; import DefaultRedditsContainer from './containers/DefaultRedditsContainer.js' const App = (props) => ( <BrowserRouter> <div className="App container-fluid"> <div className="App-reddit-selector"> <Link to="/">Front</Link> - <Link to="/r/all">All</Link> | <DefaultRedditsContainer /> </div> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <strong>Reactit!</strong> An Example ReactJs Reddit front-end </div> <Route exact path="/" component={FrontPageContainer}/> <Route path="/r/:name" component={SubredditPageContainer} /> </div> </BrowserRouter> ); export default App;
src/containers/flightgenerator/Entity.js
dataloom/gallery
import React from 'react'; import PropTypes from 'prop-types'; import Select from 'react-select'; import { Button } from 'react-bootstrap'; import InlineEditableControl from '../../components/controls/InlineEditableControl'; import styles from './styles.module.css'; const timeZonesMap = { 'UTC (Universal Coordinated Time)': '0', 'EST (New York)': '-5', 'CST (Chicago)': '-6', 'MST (Denver)': '-7', 'PST (Los Angeles)': '-8' }; export default class Entity extends React.Component { static propTypes = { entity: PropTypes.shape({ entitySetId: PropTypes.string.isRequired, alias: PropTypes.string.isRequired, useCurrentSync: PropTypes.bool.isRequired, properties: PropTypes.object.isRequired, dateFormats: PropTypes.object, timeZones: PropTypes.object }).isRequired, index: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, allEntitySetsAsMap: PropTypes.object.isRequired, allEntityTypesAsMap: PropTypes.object.isRequired, allPropertyTypesAsMap: PropTypes.object.isRequired, usedAliases: PropTypes.array.isRequired } removeEntity = () => { this.props.onDelete(this.props.index); } handleEntitySetChange = (event) => { const { index, allEntityTypesAsMap, allPropertyTypesAsMap, allEntitySetsAsMap, onChange, usedAliases } = this.props; const entitySetId = event.value; const properties = {}; const dateFormats = {}; const timeZones = {}; allEntityTypesAsMap[allEntitySetsAsMap[entitySetId].entityTypeId].properties.forEach((id) => { properties[id] = ''; if (allPropertyTypesAsMap[id].datatype === 'Date') { dateFormats[id] = ''; timeZones[id] = '0'; } }); const baseAlias = allEntitySetsAsMap[entitySetId].title.concat(' Entity'); let alias = baseAlias; let counter = 1; while (usedAliases.includes(alias)) { alias = baseAlias.concat(` (${counter})`); counter += 1; } const entity = Object.assign({}, this.props.entity, { entitySetId, alias, properties, dateFormats, timeZones }); onChange(entity, index); } handleAliasChange = (alias) => { const { entity, index, onChange, usedAliases } = this.props; if (usedAliases.includes(alias)) return Promise.resolve(false); const newEntity = Object.assign({}, entity, { alias }); onChange(newEntity, index); return Promise.resolve(true); } handleCurrentSyncChange = () => { const { entity, index, onChange } = this.props; const newEntity = Object.assign({}, entity, { useCurrentSync: !entity.useCurrentSync }); onChange(newEntity, index); } handlePropertyChange = (event, propertyTypeId) => { const { entity, index, onChange } = this.props; const newValue = event.target.value; const properties = Object.assign({}, entity.properties, { [propertyTypeId]: newValue }); const newEntity = Object.assign({}, entity, { properties }); onChange(newEntity, index); } handleDateFormatChange = (newFormat, propertyTypeId) => { const { entity, index, onChange } = this.props; const format = { [propertyTypeId]: newFormat }; const dateFormats = (entity.dateFormats) ? Object.assign({}, entity.dateFormats, format) : format; const newEntity = Object.assign({}, entity, { dateFormats }); onChange(newEntity, index); } handleTimeZoneChange = (newTimeZone, propertyTypeId) => { const { entity, index, onChange } = this.props; const timeZone = { [propertyTypeId]: newTimeZone }; const timeZones = (entity.timeZones) ? Object.assign({}, entity.timeZones, timeZone) : timeZone; const newEntity = Object.assign({}, entity, { timeZones }); onChange(newEntity, index); } renderDeleteButton = () => { return ( <div className={styles.deleteButton}> <Button bsStyle="danger" onClick={this.removeEntity}> Remove </Button> </div> ); } renderEntitySetSelection = () => { const options = []; Object.values(this.props.allEntitySetsAsMap).forEach((entitySet) => { if (this.props.allEntityTypesAsMap[entitySet.entityTypeId]) { options.push({ label: entitySet.title, value: entitySet.id }); } }); return ( <Select value={this.props.entity.entitySetId} onChange={this.handleEntitySetChange} options={options} /> ); } renderAlias = () => { const alias = this.props.entity.alias; if (!alias.length) return null; return ( <div className={styles.alias}> <InlineEditableControl type="text" size="medium" placeholder="Entity alias" value={alias} onChangeConfirm={this.handleAliasChange} /> </div> ); } renderCurrentSync = () => { if (!this.props.entity.alias.length) return null; const useCurrentSync = this.props.entity.useCurrentSync; const name = `${this.props.entity.alias}-sync`; return ( <div className={styles.currentSync}> <input name={name} type="checkbox" checked={!useCurrentSync} onChange={this.handleCurrentSyncChange} /> <label className={styles.currentSyncLabel} htmlFor={name}>Overwrite existing data for entity set?</label> </div> ); } renderDateFormatInput = (property) => { if (property.datatype !== 'Date') return null; let formatValue = ''; let timeZoneValue = ''; if (this.props.entity.dateFormats && this.props.entity.dateFormats[property.id]) { formatValue = this.props.entity.dateFormats[property.id]; } if (this.props.entity.timeZones && this.props.entity.timeZones[property.id]) { timeZoneValue = this.props.entity.timeZones[property.id]; } const timeZoneOptions = Object.keys(timeZonesMap).map((timeZone) => { const offset = timeZonesMap[timeZone]; return { label: timeZone, value: offset }; }); return ( <div> <td className={styles.tableCell}> <input type="text" placeholder="Date format" value={formatValue} onChange={(event) => { this.handleDateFormatChange(event.target.value, property.id); }} /> </td> <td className={styles.tableCell} style={{ width: '500px' }}> <Select value={timeZoneValue} options={timeZoneOptions} clearable={false} backspaceRemoves={false} deleteRemoves={false} onChange={(event) => { this.handleTimeZoneChange(event.value, property.id); }} /> </td> </div> ); } renderProperties = () => { const properties = Object.keys(this.props.entity.properties).map((propertyTypeId) => { const property = this.props.allPropertyTypesAsMap[propertyTypeId]; const title = property.title; const fqn = `${property.type.namespace}.${property.type.name}`; return ( <tr key={propertyTypeId} className={styles.propertyName}> <td className={styles.tableCell}> <span className={styles.propertyName}>{title} <i>({fqn})</i></span> </td> <td className={styles.tableCell}> <input type="text" placeholder="CSV Header Name" value={this.props.entity.properties[propertyTypeId]} onChange={(e) => { this.handlePropertyChange(e, propertyTypeId); }} /> </td> {this.renderDateFormatInput(property)} </tr> ); }); return ( <table> <tbody> {properties} </tbody> </table> ); } render() { return ( <div> {this.renderDeleteButton()} {this.renderEntitySetSelection()} {this.renderAlias()} {this.renderCurrentSync()} {this.renderProperties()} </div> ); } }
src/PageItem.js
aparticka/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import SafeAnchor from './SafeAnchor'; const PageItem = React.createClass({ propTypes: { href: React.PropTypes.string, target: React.PropTypes.string, title: React.PropTypes.string, disabled: React.PropTypes.bool, previous: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }, getDefaultProps() { return { disabled: false, previous: false, next: false }; }, render() { let classes = { 'disabled': this.props.disabled, 'previous': this.props.previous, 'next': this.props.next }; return ( <li {...this.props} className={classNames(this.props.className, classes)}> <SafeAnchor href={this.props.href} title={this.props.title} target={this.props.target} onClick={this.handleSelect}> {this.props.children} </SafeAnchor> </li> ); }, handleSelect(e) { if (this.props.onSelect || this.props.disabled) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); export default PageItem;
src/TPA/TextLink/TextLink.js
skyiea/wix-style-react
import React from 'react'; import {string} from 'prop-types'; import classNames from 'classnames'; import WixComponent from '../../BaseComponents/WixComponent'; import tpaStyleInjector from '../TpaStyleInjector'; import omit from 'omit'; let styles = {locals: {}}; try { styles = require('!css-loader?modules&camelCase&localIdentName="[path][name]__[local]__[hash:base64:5]"!sass-loader!./TextLink.scss'); } catch (e) {} class TextLink extends WixComponent { static propTypes = { link: string.isRequired, id: string, children: string }; static defaultProps = { disabled: false, rel: null, target: null }; render() { const {children, className, link} = this.props; const {locals} = styles; const classes = (classNames([locals['wix-style-react-text-link']], className)).trim(); const propsToOmit = ['children', 'className', 'link', 'href', 'dataHook', 'injectedStyles']; return ( <a className={classes} href={link} {...omit(propsToOmit, this.props)}> {children} </a> ); } } TextLink.displayName = 'TextLink'; export default tpaStyleInjector(TextLink, styles);
src/parser/shared/modules/spells/bfa/essences/BloodOfTheEnemy.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import SpellLink from 'common/SpellLink'; import { formatNumber } from 'common/format'; import HIT_TYPES from 'game/HIT_TYPES'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import StatisticGroup from 'interface/statistics/StatisticGroup'; import HasteIcon from 'interface/icons/Haste'; import CritIcon from 'interface/icons/CriticalStrike'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events, { EventType } from 'parser/core/Events'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import Abilities from 'parser/core/modules/Abilities'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import StatTracker from 'parser/shared/modules/StatTracker'; import ItemDamageDone from 'interface/ItemDamageDone'; import { calculatePrimaryStat } from 'common/stats'; const BOTE_DAMAGE_BONUS = 0.25; const MINOR_SPELL_IDS = { 1: SPELLS.BLOOD_OF_THE_ENEMY_MINOR.id, 2: SPELLS.BLOOD_OF_THE_ENEMY_MINOR_RANK_TWO_CRIT_BUFF.id, 3: SPELLS.BLOOD_OF_THE_ENEMY_MINOR_RANK_THREE_PARTIAL_STACK_LOSS.id, 4: SPELLS.BLOOD_OF_THE_ENEMY_MINOR_RANK_THREE_PARTIAL_STACK_LOSS.id, }; const MAJOR_SPELL_IDS = { 1: SPELLS.BLOOD_OF_THE_ENEMY.id, 2: SPELLS.BLOOD_OF_THE_ENEMY_MAJOR_RANK_TWO_REDUCED_CD.id, 3: SPELLS.BLOOD_OF_THE_ENEMY_MAJOR_RANK_THREE_CRIT_DAMAGE_BUFF.id, 4: SPELLS.BLOOD_OF_THE_ENEMY_MAJOR_RANK_THREE_CRIT_DAMAGE_BUFF.id, }; /** * Major: The Heart of Azeroth erupts violently, dealing 19,408 Shadow damage to enemies within 12 yds. You gain 25% critical strike chance against the targets for 10 sec. * Minor: Your critical strikes with spells and abilities grant a stack of Blood-Soaked. Upon reaching 40 stacks, you gain 548 Haste for 8 sec. * R2: 30 second CD reduction / Each stack of Blood-Soaked grants 8 Critical Strike * R3: increases your critical hit damage by 25% for 5 sec / Blood-Soaked has a 25% chance of only consuming 30 stacks. */ class BloodOfTheEnemy extends Analyzer { static dependencies = { abilities: Abilities, statTracker: StatTracker, enemies: EnemyInstances, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasEssence(SPELLS.BLOOD_OF_THE_ENEMY.traitId); if (!this.active) { return; } const rank = this.selectedCombatant.essenceRank(SPELLS.BLOOD_OF_THE_ENEMY.traitId); this.haste = calculatePrimaryStat(505, 726, this.selectedCombatant.neck.itemLevel); this.statTracker.add(SPELLS.BLOOD_SOAKED_HASTE_BUFF.id, { haste: this.haste, }); this.hasMajor = this.selectedCombatant.hasMajor(SPELLS.BLOOD_OF_THE_ENEMY.traitId); if (this.hasMajor) { this.abilities.add({ spell: SPELLS.BLOOD_OF_THE_ENEMY, category: Abilities.SPELL_CATEGORIES.ITEMS, cooldown: (rank === 1) ? 120 : 90, gcd: { base: 1500, }, castEfficiency: { suggestion: true, recommendedEfficiency: 0.80, }, }); } this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.BLOOD_OF_THE_ENEMY), this.onMajorCastDamage); if (rank > 1) { this.crit = calculatePrimaryStat(455, 7, this.selectedCombatant.neck.itemLevel); this.statTracker.add(SPELLS.BLOOD_SOAKED_STACKING_BUFF.id, { crit: this.crit, }); this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.BLOOD_SOAKED_STACKING_BUFF), this.handleStacks); this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.BLOOD_SOAKED_STACKING_BUFF), this.handleStacks); this.addEventListener(Events.applybuffstack.by(SELECTED_PLAYER).spell(SPELLS.BLOOD_SOAKED_STACKING_BUFF), this.handleStacks); } if (rank > 2 && this.hasMajor) { this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage); } } majorCastDamage = 0; currentStacks = 0; lastStackTimestamp = 0; totalCrit = 0; bonusDamage = 0; crit = 0; haste = 0; onMajorCastDamage(event) { this.majorCastDamage += event.amount + (event.absorbed || 0); } onDamage(event) { const enemy = this.enemies.getEntity(event); if (!enemy) { return; } const playerHasBuff = this.selectedCombatant.hasBuff(SPELLS.SEETHING_RAGE.id); if (!playerHasBuff) { return; } const isCrit = event.hitType === HIT_TYPES.CRIT || event.hitType === HIT_TYPES.BLOCKED_CRIT; if (!isCrit) { return; } this.bonusDamage += calculateEffectiveDamage(event, BOTE_DAMAGE_BONUS); } handleStacks(event) { const uptimeOnStack = event.timestamp - this.lastStackTimestamp; this.totalCrit += this.currentStacks * this.crit * uptimeOnStack; if (event.type === EventType.ApplyBuff) { // when the R3 minor procs and only 30 stacks are consumed, an applybuff granting 10 stacks goes out after the removebuff but has the same timestamp as the removebuff event this.currentStacks = (uptimeOnStack === 0 ? 10 : 1); } else if (event.type === EventType.RemoveBuff) { this.currentStacks = 0; } else { this.currentStacks = event.stack; } this.lastStackTimestamp = event.timestamp; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BLOOD_SOAKED_HASTE_BUFF.id) / this.owner.fightDuration; } get averageHaste() { return (this.haste * this.uptime); } get averageCrit() { return (this.totalCrit / this.owner.fightDuration).toFixed(0); } statistic() { const rank = this.selectedCombatant.essenceRank(SPELLS.BLOOD_OF_THE_ENEMY.traitId); const rankThreeTooltip = (rank > 2) ? <><br />Damage done from increased critical hit damage: {formatNumber(this.bonusDamage)}</> : <> </>; return ( <StatisticGroup category={STATISTIC_CATEGORY.ITEMS}> <ItemStatistic ultrawide> <div className="pad"> <label><SpellLink id={MINOR_SPELL_IDS[rank]} /> - Minor Rank {rank}</label> <div className="value"> <HasteIcon /> {formatNumber(this.averageHaste)} <small>average Haste gained</small><br /> <CritIcon /> {formatNumber(this.averageCrit)} <small>average Crit gained</small> </div> </div> </ItemStatistic> {this.hasMajor && ( <ItemStatistic ultrawide tooltip={( <> Damage done by AoE hit: {formatNumber(this.majorCastDamage)} {rankThreeTooltip} </> )} > <div className="pad"> <label><SpellLink id={MAJOR_SPELL_IDS[rank]} /> - Major Rank {rank}</label> <div className="value"> <ItemDamageDone amount={this.bonusDamage + this.majorCastDamage} /> </div> </div> </ItemStatistic> )} </StatisticGroup> ); } } export default BloodOfTheEnemy;
docs/app/components/Logo/Logo.js
react-fabric/react-fabric
/* eslint-disable max-len */ import React from 'react' import cssm from 'react-css-modules' import paths from './paths.js' import style from './Logo.scss' const Logo = ({ fill, ...props }) => ( <svg {...props} styleName="logo" viewBox="0 0 256 233"> <g stroke="none" fill={fill} fillRule="evenodd"> <path d={paths.react} id="react"></path> <path d={paths.office} id="office"></path> </g> </svg> ) Logo.propTypes = { fill: React.PropTypes.string } Logo.defaultProps = { fill: '#D83B01' } export default cssm(Logo, style)
frontend/src/Settings/DownloadClients/DownloadClients/EditDownloadClientModalContentConnector.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { saveDownloadClient, setDownloadClientFieldValue, setDownloadClientValue, testDownloadClient } from 'Store/Actions/settingsActions'; import createProviderSettingsSelector from 'Store/Selectors/createProviderSettingsSelector'; import EditDownloadClientModalContent from './EditDownloadClientModalContent'; function createMapStateToProps() { return createSelector( (state) => state.settings.advancedSettings, createProviderSettingsSelector('downloadClients'), (advancedSettings, downloadClient) => { return { advancedSettings, ...downloadClient }; } ); } const mapDispatchToProps = { setDownloadClientValue, setDownloadClientFieldValue, saveDownloadClient, testDownloadClient }; class EditDownloadClientModalContentConnector extends Component { // // Lifecycle componentDidUpdate(prevProps, prevState) { if (prevProps.isSaving && !this.props.isSaving && !this.props.saveError) { this.props.onModalClose(); } } // // Listeners onInputChange = ({ name, value }) => { this.props.setDownloadClientValue({ name, value }); } onFieldChange = ({ name, value }) => { this.props.setDownloadClientFieldValue({ name, value }); } onSavePress = () => { this.props.saveDownloadClient({ id: this.props.id }); } onTestPress = () => { this.props.testDownloadClient({ id: this.props.id }); } // // Render render() { return ( <EditDownloadClientModalContent {...this.props} onSavePress={this.onSavePress} onTestPress={this.onTestPress} onInputChange={this.onInputChange} onFieldChange={this.onFieldChange} /> ); } } EditDownloadClientModalContentConnector.propTypes = { id: PropTypes.number, isFetching: PropTypes.bool.isRequired, isSaving: PropTypes.bool.isRequired, saveError: PropTypes.object, item: PropTypes.object.isRequired, setDownloadClientValue: PropTypes.func.isRequired, setDownloadClientFieldValue: PropTypes.func.isRequired, saveDownloadClient: PropTypes.func.isRequired, testDownloadClient: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(EditDownloadClientModalContentConnector);
frontend/component/Signup.js
plusse7en/practice-node-project
import React from 'react'; import jQuery from 'jquery'; import {signup} from '../lib/client'; import {redirectURL} from '../lib/utils'; export default class Signup extends React.Component { constructor(props) { super(props); this.state = {}; } handleChange(name, e) { this.state[name] = e.target.value; } handleLogin(e) { const $btn = jQuery(e.target); $btn.button('loading'); signup(this.state.name, this.state.email, this.state.password, this.state.nickname) .then(ret => { $btn.button('reset'); alert('注册成功!'); redirectURL('/login'); }) .catch(err => { $btn.button('reset'); alert(err); }); } render() { return ( <div style={{width: 400, margin: 'auto'}}> <div className="panel panel-primary"> <div className="panel-heading">注册</div> <div className="panel-body"> <form> <div className="form-group"> <label htmlFor="ipt-name">用户名</label> <input type="text" className="form-control" id="ipt-name" onChange={this.handleChange.bind(this, 'name')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="ipt-email">邮箱</label> <input type="email" className="form-control" id="ipt-email" onChange={this.handleChange.bind(this, 'email')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="ipt-nickname">昵称</label> <input type="text" className="form-control" id="ipt-nickname" onChange={this.handleChange.bind(this, 'nickname')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="password">密码</label> <input type="password" className="form-control" id="password" onChange={this.handleChange.bind(this, 'password')} placeholder="" /> </div> <button type="button" className="btn btn-primary" onClick={this.handleLogin.bind(this)}>注册</button> </form> </div> </div> </div> ) } }
fluxible-router/components/Nav.js
jeffreywescott/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import {NavLink} from 'fluxible-router'; class Nav extends React.Component { render() { return ( <ul className="pure-menu pure-menu-open pure-menu-horizontal"> <li><NavLink routeName="home" activeStyle={{backgroundColor: '#ccc'}}>Home</NavLink></li> <li><NavLink routeName="about" activeStyle={{backgroundColor: '#ccc'}}>About</NavLink></li> </ul> ); } } export default Nav;
packages/benchmarks/src/app/Benchmark/index.js
css-components/styled-components
/** * The MIT License (MIT) * Copyright (c) 2017 Paul Armstrong * https://github.com/paularmstrong/react-component-benchmark */ /* global $Values */ /** * @flow */ import * as Timing from './timing'; import React, { Component } from 'react'; import { getMean, getMedian, getStdDev } from './math'; import type { BenchResultsType, FullSampleTimingType, SampleTimingType } from './types'; export const BenchmarkType = { MOUNT: 'mount', UPDATE: 'update', UNMOUNT: 'unmount' }; const shouldRender = (cycle: number, type: $Values<typeof BenchmarkType>): boolean => { switch (type) { // Render every odd iteration (first, third, etc) // Mounts and unmounts the component case BenchmarkType.MOUNT: case BenchmarkType.UNMOUNT: return !((cycle + 1) % 2); // Render every iteration (updates previously rendered module) case BenchmarkType.UPDATE: return true; default: return false; } }; const shouldRecord = (cycle: number, type: $Values<typeof BenchmarkType>): boolean => { switch (type) { // Record every odd iteration (when mounted: first, third, etc) case BenchmarkType.MOUNT: return !((cycle + 1) % 2); // Record every iteration case BenchmarkType.UPDATE: return true; // Record every even iteration (when unmounted) case BenchmarkType.UNMOUNT: return !(cycle % 2); default: return false; } }; const isDone = ( cycle: number, sampleCount: number, type: $Values<typeof BenchmarkType> ): boolean => { switch (type) { case BenchmarkType.MOUNT: return cycle >= sampleCount * 2 - 1; case BenchmarkType.UPDATE: return cycle >= sampleCount - 1; case BenchmarkType.UNMOUNT: return cycle >= sampleCount * 2; default: return true; } }; const sortNumbers = (a: number, b: number): number => a - b; type BenchmarkPropsType = { component: typeof React.Component, forceLayout?: boolean, getComponentProps: Function, onComplete: (x: BenchResultsType) => void, sampleCount: number, timeout: number, type: $Values<typeof BenchmarkType> }; type BenchmarkStateType = { componentProps: Object, cycle: number, running: boolean }; /** * Benchmark * TODO: documentation */ export default class Benchmark extends Component<BenchmarkPropsType, BenchmarkStateType> { _raf: ?Function; _startTime: number; _samples: Array<SampleTimingType>; static displayName = 'Benchmark'; static defaultProps = { sampleCount: 50, timeout: 10000, // 10 seconds type: BenchmarkType.MOUNT }; static Type = BenchmarkType; constructor(props: BenchmarkPropsType, context?: {}) { super(props, context); const cycle = 0; const componentProps = props.getComponentProps({ cycle }); this.state = { componentProps, cycle, running: false }; this._startTime = 0; this._samples = []; } componentWillReceiveProps(nextProps: BenchmarkPropsType) { if (nextProps) { this.setState(state => ({ componentProps: nextProps.getComponentProps(state.cycle) })); } } componentWillUpdate(nextProps: BenchmarkPropsType, nextState: BenchmarkStateType) { if (nextState.running && !this.state.running) { this._startTime = Timing.now(); } } componentDidUpdate() { const { forceLayout, sampleCount, timeout, type } = this.props; const { cycle, running } = this.state; if (running && shouldRecord(cycle, type)) { this._samples[cycle].scriptingEnd = Timing.now(); // force style recalc that would otherwise happen before the next frame if (forceLayout) { this._samples[cycle].layoutStart = Timing.now(); if (document.body) { document.body.offsetWidth; } this._samples[cycle].layoutEnd = Timing.now(); } } if (running) { const now = Timing.now(); if (!isDone(cycle, sampleCount, type) && now - this._startTime < timeout) { this._handleCycleComplete(); } else { this._handleComplete(now); } } } componentWillUnmount() { if (this._raf) { window.cancelAnimationFrame(this._raf); } } render() { const { component: Component, type } = this.props; const { componentProps, cycle, running } = this.state; if (running && shouldRecord(cycle, type)) { this._samples[cycle] = { scriptingStart: Timing.now() }; } return running && shouldRender(cycle, type) ? <Component {...componentProps} /> : null; } start() { this._samples = []; this.setState(() => ({ running: true, cycle: 0 })); } _handleCycleComplete() { const { getComponentProps, type } = this.props; const { cycle } = this.state; let componentProps; if (getComponentProps) { // Calculate the component props outside of the time recording (render) // so that it doesn't skew results componentProps = getComponentProps({ cycle }); // make sure props always change for update tests if (type === BenchmarkType.UPDATE) { componentProps['data-test'] = cycle; } } this._raf = window.requestAnimationFrame(() => { this.setState((state: BenchmarkStateType) => ({ cycle: state.cycle + 1, componentProps })); }); } getSamples(): Array<FullSampleTimingType> { return this._samples.reduce( ( memo: Array<FullSampleTimingType>, { scriptingStart, scriptingEnd, layoutStart, layoutEnd }: SampleTimingType ): Array<FullSampleTimingType> => { memo.push({ start: scriptingStart, end: layoutEnd || scriptingEnd || 0, scriptingStart, scriptingEnd: scriptingEnd || 0, layoutStart, layoutEnd }); return memo; }, [] ); } _handleComplete(endTime: number) { const { onComplete } = this.props; const samples = this.getSamples(); this.setState(() => ({ running: false, cycle: 0 })); const runTime = endTime - this._startTime; const sortedElapsedTimes = samples.map(({ start, end }) => end - start).sort(sortNumbers); const sortedScriptingElapsedTimes = samples .map(({ scriptingStart, scriptingEnd }) => scriptingEnd - scriptingStart) .sort(sortNumbers); const sortedLayoutElapsedTimes = samples .map(({ layoutStart, layoutEnd }) => (layoutEnd || 0) - (layoutStart || 0)) .sort(sortNumbers); onComplete({ startTime: this._startTime, endTime, runTime, sampleCount: samples.length, samples: samples, max: sortedElapsedTimes[sortedElapsedTimes.length - 1], min: sortedElapsedTimes[0], median: getMedian(sortedElapsedTimes), mean: getMean(sortedElapsedTimes), stdDev: getStdDev(sortedElapsedTimes), meanLayout: getMean(sortedLayoutElapsedTimes), meanScripting: getMean(sortedScriptingElapsedTimes) }); } }
turismo_client/src/containers/userBoardContainer.js
leiverandres/turismo-risaralda
import React, { Component } from 'react'; import { Grid, Message, Card, Label, Header, Icon, Dropdown } from 'semantic-ui-react'; import requests from '../utils/requests'; import ListItemsWithPagination from '../components/listItemsWithPagination'; import EventInfoModal from '../components/eventInfoModal'; const itemsPerPage = 10; const EventCard = ({ event, onSeeMore }) => { return ( <Card> <Card.Content> <Card.Header>{event.name}</Card.Header> <Card.Meta onClick={onSeeMore}> <a> Ver información completa </a> </Card.Meta> <Card.Description content={event.description.slice(0, 140)} /> </Card.Content> <Card.Content extra> <Label tag>{event.channel.activity}</Label> <Label tag>{event.channel.municipality}</Label> </Card.Content> </Card> ); }; const FilterToolkit = ({ options, name, iconName, handleChange }) => { return ( <Dropdown placeholder={name} fluid multiple search selection options={options} name={name} onChange={handleChange} /> ); }; class UserBoardContainer extends Component { state = { showModal: false, modalEvent: {}, loading: false, pageSelected: 1, pageNumbers: [], events: [], activityOpts: [], municipalityOpts: [], filterActivity: [], filterMunicipality: [], allEvents: [] }; componentDidMount() { this.fetchEvents(); } generateOpts = events => { const activityOpts = []; const municipalityOpts = []; for (let e of events) { if (activityOpts.indexOf(e.channel.activity) === -1) { activityOpts.push(e.channel.activity); } if (municipalityOpts.indexOf(e.channel.municipality) === -1) { municipalityOpts.push(e.channel.municipality); } } this.setState({ activityOpts: activityOpts.map(act => { return { key: act, text: act, value: act }; }), municipalityOpts: municipalityOpts.map(mun => { return { key: mun, text: mun, value: mun }; }) }); }; fetchEvents = () => { this.setState({ loading: true }); requests .getUserEvents() .then(res => { const events = res.data; this.setState({ loading: false, allEvents: events, events }); this.generateOpts(events); this.calculatePages(); }) .catch(err => { this.setState({ loading: false }); }); }; calculatePages = () => { const elements = this.state.events; const pages = Math.ceil(elements.length / itemsPerPage); const pageNumbers = []; for (let i = 1; i <= pages; i++) { pageNumbers.push(i); } this.setState({ pageNumbers }); }; handlePageChange = page => { this.setState({ pageSelected: page }); }; showModal = eventObj => { this.setState({ showModal: true, modalEvent: eventObj }); }; closeModal = () => { this.setState({ showModal: false, modalEvent: {} }); }; onFilterChange = (ev, { name, value }) => { if (name === 'Municipios') { this.setState({ filterMunicipality: value }); } else { this.setState({ filterActivity: value }); } console.log('filtering'); this.setState(prevState => { const { filterActivity, filterMunicipality } = prevState; console.log(filterActivity, filterMunicipality); console.log(prevState.events); let filteredEvents = prevState.allEvents.filter(ev => { const curActivity = ev.channel.activity; const curMunicipality = ev.channel.municipality; if (filterActivity.length > 0) { return filterActivity.indexOf(curActivity) !== -1; } if (filterMunicipality.length > 0) { return filterMunicipality.indexOf(curMunicipality) !== -1; } return false; }); if ( filteredEvents.length === 0 && filterActivity.length === 0 && filterMunicipality.length === 0 ) { console.log('no filter'); filteredEvents = prevState.allEvents; } return (prevState.events = filteredEvents); }); }; render() { const { loading, pageNumbers, pageSelected, showModal, modalEvent, activityOpts, municipalityOpts } = this.state; const startList = (pageSelected - 1) * itemsPerPage; const endList = startList + itemsPerPage; let events = this.state.events || this.state.allEvents; return ( <div> <EventInfoModal open={showModal} event={modalEvent} handleClose={this.closeModal} /> <Header size="huge"> <Icon name="world" /> <Header.Content> Explorar </Header.Content> <Header.Subheader> Te presentamos las mejores actividades según tus intereses </Header.Subheader> </Header> <Grid columns={3} padded stackable> <Grid.Column width={4}> <FilterToolkit name="Municipios" options={municipalityOpts} handleChange={this.onFilterChange} /> <br /> <FilterToolkit name="Actividades" options={activityOpts} handleChange={this.onFilterChange} /> </Grid.Column> <Grid.Column width={12}> <ListItemsWithPagination title="Explorar" loading={loading} pageNumbers={pageNumbers} pageSelected={pageSelected} onPageUpdate={this.handlePageChange} width="16" > {events && events.length > 0 ? <Card.Group> {events.slice(startList, endList).map(event => { return ( <EventCard key={event._id} event={event} onSeeMore={this.showModal.bind(null, event)} /> ); })} </Card.Group> : <Message color="orange" size="massive" icon="hand victory" header="No eventos para ti" content={`No hemos encontrado eventos dentro de tus intereses`} />} </ListItemsWithPagination> </Grid.Column> </Grid> </div> ); } } export default UserBoardContainer;
src/app2.js
vlasn/mets
/** * Created by clstrfvck on 19/04/2017. */ import React from 'react' import ReactDOM from 'react-dom' import { createStore, combineReducers } from 'redux' import { Provider } from 'react-redux' import { Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore, routerReducer } from 'react-router-redux' import reducers from './reducers' // Add the reducer to your store on the `routing` key const store = createStore( combineReducers({ ...reducers, routing: routerReducer }) ) import Login from "./components/Login" // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store) ReactDOM.render( <Provider store={store}> { /* Tell the Router to use our enhanced history */ } <Router history={history}> <Route path="/" component={App}> <Route path="login" component={Login}/> </Route> </Router> </Provider>, document.getElementById('root') )
node_modules/native-base/Components/Widgets/Icon.js
mk007sg/threeSeaShells
/* @flow */ 'use strict'; import React from 'react'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import variables from '../Themes/light'; import Ionicons from 'react-native-vector-icons/Ionicons'; import Entypo from 'react-native-vector-icons/Entypo'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import Octicons from 'react-native-vector-icons/Octicons'; import Zocial from 'react-native-vector-icons/Zocial'; var Icon; switch(variables.iconFamily) { case 'Ionicons': Icon = Ionicons; break; case 'Entypo': Icon = Entypo; break; case 'FontAwesome': Icon = FontAwesome; break; case 'Foundation': Icon = Foundation; break; case 'MaterialIcons': Icon = MaterialIcons; break; case 'Octicons': Icon = Octicons; break; case 'Zocial': Icon = Zocial; break; default: Icon = Ionicons; } export default class IconNB extends NativeBaseComponent { propTypes: { style : React.PropTypes.object } getInitialStyle() { return { icon: { fontSize: this.getTheme().iconFontSize, color: this.getContextForegroundColor() } } } prepareRootProps() { var defaultProps = { style: this.getInitialStyle().icon }; return computeProps(this.props, defaultProps); } render() { return( <Icon {...this.prepareRootProps()}/> ); } }
src/routes/admin/index.js
ziedAb/PVMourakiboun
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; const title = 'Admin Page'; const isAdmin = false; export default { path: '/admin', async action() { if (!isAdmin) { return { redirect: '/login' }; } const Admin = await require.ensure([], require => require('./Admin').default, 'admin'); return { title, chunk: 'admin', component: <Layout><Admin title={title} /></Layout>, }; }, };
src/MenuItem.js
yuche/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import SafeAnchor from './SafeAnchor'; const MenuItem = React.createClass({ propTypes: { header: React.PropTypes.bool, divider: React.PropTypes.bool, href: React.PropTypes.string, title: React.PropTypes.string, target: React.PropTypes.string, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any, active: React.PropTypes.bool, disabled: React.PropTypes.bool }, getDefaultProps() { return { active: false }; }, handleClick(e) { if (this.props.disabled) { e.preventDefault(); return; } if (this.props.onSelect) { e.preventDefault(); this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } }, renderAnchor() { return ( <SafeAnchor onClick={this.handleClick} href={this.props.href} target={this.props.target} title={this.props.title} tabIndex="-1"> {this.props.children} </SafeAnchor> ); }, render() { let classes = { 'dropdown-header': this.props.header, 'divider': this.props.divider, 'active': this.props.active, 'disabled': this.props.disabled }; let children = null; if (this.props.header) { children = this.props.children; } else if (!this.props.divider) { children = this.renderAnchor(); } return ( <li {...this.props} role="presentation" title={null} href={null} className={classNames(this.props.className, classes)}> {children} </li> ); } }); export default MenuItem;
src/component/searchTab/SearchTab.js
BristolPound/cyclos-mobile-3-TownPound
import React from 'react' import { View, Dimensions } from 'react-native' import _ from 'lodash' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import BackgroundMap from './BackgroundMap' import ComponentList from './ComponentList' import BusinessListItem, { SelectedBusiness } from './BusinessListItem' import DraggableList from './DraggableList' import styles, { SEARCH_BAR_HEIGHT, SEARCH_BAR_MARGIN, maxExpandedHeight } from './SearchTabStyle' import { ROW_HEIGHT, BUSINESS_LIST_SELECTED_GAP} from './BusinessListStyle' import { selectBusiness, updateTabMode, openTraderModal, moveMap, addFilter, removeFilter, tabModes } from '../../store/reducer/business' import { Overlay } from '../common/Overlay' import Search from './Search' import calculatePanelHeight from '../../util/calculatePanelHeight' const BUSINESS_LIST_GAP_PLACEHOLDER = { pressable: false } const EXPANDED_LIST_TOP_OFFSET = SEARCH_BAR_HEIGHT + SEARCH_BAR_MARGIN const listCroppedLength = Math.ceil(Dimensions.get('window').height / ROW_HEIGHT) const ComponentForItem = (item, deselect) => { if (item === BUSINESS_LIST_GAP_PLACEHOLDER) { return <View style={{ height: 10 }}/> } if (item.isSelected) { return <SelectedBusiness business={item} deselect={deselect}/> } return <BusinessListItem business={item} /> } class SearchTab extends React.Component { constructor(props) { super() this.state = { componentListArray: this.createComponentListArray(props).slice(0, listCroppedLength) } this.listPosition = 1 } createComponentListArray(props = this.props) { const makePressable = (itemProps) => { itemProps.pressable = true return itemProps } if (props.selectedBusiness) { return [ _.extend({isSelected: true}, makePressable(props.selectedBusiness)), BUSINESS_LIST_GAP_PLACEHOLDER, ...props.closestBusinesses.map(makePressable) ] } else { return props.closestBusinesses.map(makePressable) } } calculateOffset(heights) { return heights.map(height => EXPANDED_LIST_TOP_OFFSET + maxExpandedHeight - height) } componentWillReceiveProps(nextProps) { let mapMoved = false nextProps.closestBusinesses.forEach((b, index) => { if (!this.props.closestBusinesses[index] || b.id !== this.props.closestBusinesses[index].id) { mapMoved = true } }) if (nextProps.selectedBusiness !== this.props.selectedBusiness || mapMoved) { const componentListArray = this.createComponentListArray(nextProps) componentListArray = this.listPosition ? componentListArray.slice(0, listCroppedLength) : componentListArray this.setState({ componentListArray: componentListArray}) } } onPositionChange(position) { if (position === 0 && this.listPosition !== 0) { this.setState({ componentListArray: this.createComponentListArray() }) } this.listPosition = position } render() { const { closestBusinesses, openTraderModal, selectedBusiness, tabMode, updateTabMode } = this.props const { componentList } = this.refs const noOfCloseBusinesses = closestBusinesses.length, childrenHeight = selectedBusiness ? (noOfCloseBusinesses + 1) * ROW_HEIGHT + BUSINESS_LIST_SELECTED_GAP : noOfCloseBusinesses * ROW_HEIGHT const { collapsedHeight, expandedHeight, closedHeight } = calculatePanelHeight( this.props.closestBusinesses.length, this.props.selectedBusiness ) return ( <View style={{flex: 1}}> <BackgroundMap /> {tabMode === tabModes.default && <DraggableList ref={this.props.registerBusinessList} style={styles.searchTab.expandPanel} topOffset={this.calculateOffset([ expandedHeight, collapsedHeight, closedHeight ])} expandedHeight={expandedHeight} onTouchEnd={(event, hasMoved) => componentList && componentList.handleRelease(hasMoved, event)} onTouchStart={location => componentList && componentList.highlightItem(location)} onMove={() => componentList && componentList.handleRelease(true)} childrenHeight={childrenHeight + BUSINESS_LIST_SELECTED_GAP} startPosition={1} onPositionChange={(position) => this.onPositionChange(position)}> <ComponentList ref='componentList' items={this.state.componentListArray} refreshTabMode={() => updateTabMode(tabMode)} componentForItem={ComponentForItem} deselect={() => this.props.selectBusiness(undefined)} onPressItem={index => this.state.componentListArray[index].id && openTraderModal(this.state.componentListArray[index].id)} /> </DraggableList>} {tabMode!==tabModes.default && <Overlay overlayVisible={true} onPress={() => updateTabMode(tabModes.default)} />} <Search {...this.props} /> </View> ) } } const mapStateToProps = (state) => ({ closestBusinesses: state.business.closestBusinesses.filter(b => b.id !== state.business.selectedBusinessId), allFilters: state.business.categories, activeFilters: state.business.activeFilters, selectedBusiness: state.business.selectedBusinessId ? state.business.businessList[state.business.selectedBusinessId] : undefined, allBusinesses: state.business.businessList, tabMode: state.business.tabMode, mapViewport: state.business.mapViewport, geolocationStatus: state.business.geolocationStatus }) const mapDispatchToProps = (dispatch) => bindActionCreators({ moveMap, addFilter, removeFilter, selectBusiness, updateTabMode, openTraderModal }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(SearchTab)
app/javascript/mastodon/features/ui/components/modal_root.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { getScrollbarWidth } from 'mastodon/utils/scrollbar'; import Base from 'mastodon/components/modal_root'; import BundleContainer from '../containers/bundle_container'; import BundleModalError from './bundle_modal_error'; import ModalLoading from './modal_loading'; import ActionsModal from './actions_modal'; import MediaModal from './media_modal'; import VideoModal from './video_modal'; import BoostModal from './boost_modal'; import AudioModal from './audio_modal'; import ConfirmationModal from './confirmation_modal'; import FocalPointModal from './focal_point_modal'; import { MuteModal, BlockModal, ReportModal, EmbedModal, ListEditor, ListAdder, CompareHistoryModal, } from 'mastodon/features/ui/util/async-components'; const MODAL_COMPONENTS = { 'MEDIA': () => Promise.resolve({ default: MediaModal }), 'VIDEO': () => Promise.resolve({ default: VideoModal }), 'AUDIO': () => Promise.resolve({ default: AudioModal }), 'BOOST': () => Promise.resolve({ default: BoostModal }), 'CONFIRM': () => Promise.resolve({ default: ConfirmationModal }), 'MUTE': MuteModal, 'BLOCK': BlockModal, 'REPORT': ReportModal, 'ACTIONS': () => Promise.resolve({ default: ActionsModal }), 'EMBED': EmbedModal, 'LIST_EDITOR': ListEditor, 'FOCAL_POINT': () => Promise.resolve({ default: FocalPointModal }), 'LIST_ADDER': ListAdder, 'COMPARE_HISTORY': CompareHistoryModal, }; export default class ModalRoot extends React.PureComponent { static propTypes = { type: PropTypes.string, props: PropTypes.object, onClose: PropTypes.func.isRequired, ignoreFocus: PropTypes.bool, }; state = { backgroundColor: null, }; getSnapshotBeforeUpdate () { return { visible: !!this.props.type }; } componentDidUpdate (prevProps, prevState, { visible }) { if (visible) { document.body.classList.add('with-modals--active'); document.documentElement.style.marginRight = `${getScrollbarWidth()}px`; } else { document.body.classList.remove('with-modals--active'); document.documentElement.style.marginRight = 0; } } setBackgroundColor = color => { this.setState({ backgroundColor: color }); } renderLoading = modalId => () => { return ['MEDIA', 'VIDEO', 'BOOST', 'CONFIRM', 'ACTIONS'].indexOf(modalId) === -1 ? <ModalLoading /> : null; } renderError = (props) => { const { onClose } = this.props; return <BundleModalError {...props} onClose={onClose} />; } handleClose = (ignoreFocus = false) => { const { onClose } = this.props; let message = null; try { message = this._modal?.getWrappedInstance?.().getCloseConfirmationMessage?.(); } catch (_) { // injectIntl defines `getWrappedInstance` but errors out if `withRef` // isn't set. // This would be much smoother with react-intl 3+ and `forwardRef`. } onClose(message, ignoreFocus); } setModalRef = (c) => { this._modal = c; } render () { const { type, props, ignoreFocus } = this.props; const { backgroundColor } = this.state; const visible = !!type; return ( <Base backgroundColor={backgroundColor} onClose={this.handleClose} ignoreFocus={ignoreFocus}> {visible && ( <BundleContainer fetchComponent={MODAL_COMPONENTS[type]} loading={this.renderLoading(type)} error={this.renderError} renderDelay={200}> {(SpecificComponent) => <SpecificComponent {...props} onChangeBackgroundColor={this.setBackgroundColor} onClose={this.handleClose} ref={this.setModalRef} />} </BundleContainer> )} </Base> ); } }
app/javascript/mastodon/components/animated_number.js
cobodo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
js/jqwidgets/demos/react/app/docking/keyboardnavigation/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDocking from '../../../jqwidgets-react/react_jqxdocking.js'; class App extends React.Component { componentDidMount() { this.refs.myDocking.showAllCollapseButtons(); this.refs.myDocking.focus(); } render() { return ( <div> <JqxDocking ref='myDocking' width={650} orientation={'horizontal'} mode={'default'} keyboardNavigation={true} > <div> <div id="window0" style={{ height: 150 }}> <div>CISC</div> <div> Before the RISC philosophy became prominent, many computer architects tried to bridge the so called semantic gap, i.e. to design instruction sets that directly supported high-level programming constructs such as procedure calls, loop control, and complex... </div> </div> <div id="window1" style={{ height: 150 }}> <div>Database management system</div> <div> A database management system (DBMS) is a software package with computer programs that control the creation, maintenance, and the use of a database. It allows organizations to conveniently develop databases... </div> </div> </div> <div> <div id="window2" style={{ height: 150 }}> <div>RISC</div> <div> Some aspects attributed to the first RISC-labeled designs around 1975 include the observations that the memory-restricted compilers of the time were often unable to take advantage... </div> </div> </div> </JqxDocking> <ul> <li><b>Tab</b> - Once the focus is received, users will be able to use the keyboard to change the focused Docking Panel.</li> <li><b>Shift+Tab</b> - reverses the direction of the tab order. Once in the widget, a Shift+Tab will take the user to the previous Docking Panel.</li> <li><b>Esc</b> - closes the focused Docking Panel.</li> <li><b>Enter</b> - collapses/expands the focused Docking Panel.</li> </ul> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/containers/AdminRelaisCommandes/components/ListeAcheteursItem.js
Proxiweb/react-boilerplate
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { ListItem } from 'material-ui/List'; import round from 'lodash/round'; import PastilleIcon from 'material-ui/svg-icons/image/brightness-1'; import DoneIcon from 'material-ui/svg-icons/action/done'; import DoneAllIcon from 'material-ui/svg-icons/action/done-all'; import WalletIcon from 'material-ui/svg-icons/action/account-balance-wallet'; import capitalize from 'lodash/capitalize'; import api from 'utils/stellarApi'; class ListeAcheteursItem extends Component { static propTypes = { utilisateur: PropTypes.object.isRequired, value: PropTypes.string.isRequired, commandeUtilisateur: PropTypes.object.isRequired, depots: PropTypes.array.isRequired, key: PropTypes.number.isRequired, totaux: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, }; state = { color: 'silver', paiements: null, error: false, }; componentDidMount() { if (this.props.utilisateur.stellarKeys && !this.props.commandeUtilisateur.dateLivraison) { api .loadAccount(this.props.utilisateur.stellarKeys.adresse) .then(res => { const bal = res.balances.find(b => b.asset_code === 'PROXI'); this.setState({ ...this.state, paiements: bal, }); }) .catch(() => { this.setState({ ...this.state, error: true }); }); } } computeDatas = () => { const { utilisateur: { id }, depots, totaux, commandeUtilisateur } = this.props; const { paiements } = this.state; const dep = depots.find(d => d.utilisateurId === id && !d.transfertEffectue && d.type === 'depot_relais'); // si un dépot a été fait, en tenir compte const depot = dep && dep.montant ? parseFloat(dep.montant) : 0; let iconColor = 'silver'; if (this.state.paiements) { const total = round(parseFloat(totaux.prix + totaux.recolteFond), 2); const totalAvecDepot = round(depot + parseFloat(paiements.balance), 2); iconColor = total <= totalAvecDepot ? 'green' : 'orange'; } return { dep, iconColor, }; }; handleClick = dep => { const { utilisateur, totaux } = this.props; const totalCommande = round(totaux.prix + totaux.recolteFond, 2); this.props.onClick(utilisateur.id, dep, totalCommande, this.state.paiements); }; render() { const { key, utilisateur, commandeUtilisateur, onClick } = this.props; const datas = this.computeDatas(); const { dep, iconColor } = datas; return ( <ListItem key={key} primaryText={`${utilisateur.nom.toUpperCase()} ${capitalize(utilisateur.prenom)}`} value={this.props.value} onClick={() => this.handleClick(dep)} leftIcon={ commandeUtilisateur.dateLivraison ? commandeUtilisateur.datePaiement ? <DoneAllIcon color="green" /> : <DoneIcon color="green" /> : <PastilleIcon color={iconColor} /> } rightIcon={dep && <WalletIcon />} /> ); } } export default connect()(ListeAcheteursItem);
src/applications/static-pages/health-care-manage-benefits/schedule-view-va-appointments-page/components/AuthContent/index.js
department-of-veterans-affairs/vets-website
// Node modules. import React from 'react'; import PropTypes from 'prop-types'; // Relative imports. import CernerCallToAction from '../../../components/CernerCallToAction'; import MoreInfoAboutBenefits from '../../../components/MoreInfoAboutBenefits'; import { appointmentsToolLink, getCernerURL } from 'platform/utilities/cerner'; import ServiceProvidersList from 'platform/user/authentication/components/ServiceProvidersList'; export const AuthContent = ({ cernerFacilities, otherFacilities }) => ( <> <CernerCallToAction cernerFacilities={cernerFacilities} otherFacilities={otherFacilities} linksHeaderText="Manage appointments at:" myHealtheVetLink={appointmentsToolLink} myVAHealthLink={getCernerURL('/pages/scheduling/upcoming')} /> <p data-testid="cerner-content"> <strong>Note:</strong> If you can’t keep an existing appointment, please contact the facility as soon as you can to reschedule or cancel. <br /> <a href="/find-locations/">Find your health facility’s phone number</a> </p> <h2>How can these appointment tools help me manage my care?</h2> <p> These tools offer a secure, online way to schedule, view, and organize your VA and community care appointments. The appointments you can schedule online depend on your facility, the type of health service, and other factors. </p> <p> <strong>You can use these tools to:</strong> </p> <ul> <li>Schedule some of your VA health appointments online</li> <li>Request approved community care appointments online</li> <li>Cancel appointments made online</li> <li>View appointments on your health calendar</li> <li> Find the location of the VA or community care facility for your appointments </li> <li>Print a list of your future appointments</li> </ul> <h2>Am I eligible to use these tools?</h2> <p> You can use these tools if you meet all of the requirements listed below. </p> <p> <strong>All of these must be true. You’re:</strong> </p> <ul> <li> Enrolled in VA health care, <strong>and</strong> </li> <li> Scheduling your appointment with a VA health facility that uses online scheduling, <strong>and</strong> </li> <li>Registered or you’ve had an appointment at that facility before</li> </ul> <p> <a href="/health-care/how-to-apply"> Find out how to apply for VA health care </a> </p> <p> <strong>And, you must have one of these free accounts:</strong> </p> <ServiceProvidersList /> <h2>How do I know if my VA health facility uses online scheduling?</h2> <p> Online scheduling is available at all VA facilities except those in these 2 locations: </p> <ul> <li>Indianapolis, IN</li> <li>Manila, Philippines</li> </ul> <p> <strong>Note:</strong> Online scheduling is available for some types of health services. We hope to expand the types of appointments and health services available through online scheduling in the future. </p> <h2>Can I use these tools to schedule community (non-VA) appointments?</h2> <p> Yes. If you’re eligible to receive care from a community provider outside of VA, you can use these tools to submit appointment requests. You must receive prior approval from us before getting care from a community provider. </p> <p> <a href="/communitycare/programs/veterans/index.asp" rel="noreferrer noopener" > Learn more about community care </a> </p> <p> <a href="/find-locations">Find a community provider in the VA network</a> </p> <h2>Can I schedule appointments through VA secure messaging?</h2> <p> If you use secure messaging with your VA health care team, you may be able to use this service to schedule and cancel appointments. </p> <p> <a href="/health-care/secure-messaging/"> Learn more about secure messaging </a> </p> <p> <strong>Please note:</strong> The fastest way to schedule appointments is usually to call the health facility where you get care. To reschedule or cancel an existing appointment, please contact your facility as soon as possible. </p> <p> <a href="/find-locations">Find your health facility’s phone number</a> </p> <h2>Will my personal health information be protected?</h2> <p> Yes. Our health management portals are secure websites. We follow strict security policies and practices to protect your personal health information. And only you and your VA health care team will have access to your secure messages. </p> <p> If you print or download any messages, you’ll need to take responsibility for protecting that information. </p> <p> <a href="https://www.myhealth.va.gov/mhv-portal-web/web/myhealthevet/protecting-your-personal-health-information" rel="noreferrer noopener" > Get tips for protecting your personal health information </a> </p> <h2>What if I have more questions?</h2> <h3>For questions about scheduling an appointment</h3> <p>Please call your VA or community care health facility.</p> <p> <a href="/find-locations/">Find your health facility’s phone number</a> </p> <h3>For questions about the VA appointments tool</h3> <p> Please call{' '} <a href="tel: 18774705947" aria-label="8 7 7. 4 7 0. 5 9 4 7."> 877-470-5947 </a>{' '} ( <a href="tel:711" aria-label="TTY. 7 1 1."> TTY: 711 </a> ). We’re here Monday through Friday, 8:00 a.m. to 8:00 p.m. ET. </p> <h3>For questions about My VA Health</h3> <p> Call My VA Health support anytime at{' '} <a href="tel:18009621024" aria-label="8 0 0. 9 6 2. 1 0 2 4."> 800-962-1024 </a> . </p> <h3>For questions about joining a VA Video Connect appointment</h3> <p> Please call{' '} <a href="tel: 18666513180" aria-label="8 6 6. 6 5 1. 3 1 8 0."> 866-651-3180 </a>{' '} ( <a href="tel:711" aria-label="TTY. 7 1 1."> TTY: 711 </a> ). We’re here 24/7. </p> <MoreInfoAboutBenefits /> </> ); AuthContent.propTypes = { cernerfacilities: PropTypes.arrayOf( PropTypes.shape({ facilityId: PropTypes.string.isRequired, isCerner: PropTypes.bool.isRequired, usesCernerAppointments: PropTypes.string, usesCernerMedicalRecords: PropTypes.string, usesCernerMessaging: PropTypes.string, usesCernerRx: PropTypes.string, usesCernerTestResults: PropTypes.string, }).isRequired, ), otherfacilities: PropTypes.arrayOf( PropTypes.shape({ facilityId: PropTypes.string.isRequired, isCerner: PropTypes.bool.isRequired, usesCernerAppointments: PropTypes.string, usesCernerMedicalRecords: PropTypes.string, usesCernerMessaging: PropTypes.string, usesCernerRx: PropTypes.string, usesCernerTestResults: PropTypes.string, }).isRequired, ), }; export default AuthContent;
src/packages/@ncigdc/components/TabbedLinks.js
NCI-GDC/portal-ui
import React from 'react'; import { get } from 'lodash'; import LocationSubscriber from '@ncigdc/components/LocationSubscriber'; import Tabs from '@ncigdc/uikit/Tabs'; import Link from '@ncigdc/components/Links/Link'; type TTabbedLinksProps = { defaultIndex?: number, links: Array<Object>, queryParam: string, tabToolbar?: React.Element<>, hideTabs?: boolean, style?: Object, side?: Boolean, linkStyle?: Object, defaultContent?: React.Element<{}>, }; type TTabbedLinks = (props: TTabbedLinksProps) => React.Element<{}>; const TabbedLinks: TTabbedLinks = ({ links, queryParam, defaultIndex = 0, tabToolbar, hideTabs, style, side, linkStyle = {}, defaultContent, } = {}) => ( <LocationSubscriber> {(ctx: { pathname: string, query: IRawQuery }) => { const foundIndex = links.findIndex( x => x.id === (ctx.query || {})[queryParam], ); const activeIndex = defaultContent ? foundIndex : foundIndex < 0 ? defaultIndex : foundIndex; return ( <Tabs activeIndex={activeIndex} className="test-tabbed-links" side={side} style={style} tabs={ hideTabs ? [] : links.map(({ filters = null, id, merge, text, }) => ( <Link className={`test-${id}`} key={id} merge={merge || true} query={{ filters, [queryParam]: id, }} style={{ display: 'inline-block', padding: '1.2rem 1.8rem', textDecoration: 'none', ...linkStyle, }} > {text} </Link> )) } tabStyle={{ padding: 0 }} tabToolbar={tabToolbar} > {get(links, [activeIndex, 'component'], defaultContent)} </Tabs> ); }} </LocationSubscriber> ); export default TabbedLinks;
app/javascript/mastodon/features/direct_timeline/components/conversation.js
TheInventrix/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContainer from '../../../containers/status_container'; export default class Conversation extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { conversationId: PropTypes.string.isRequired, accounts: ImmutablePropTypes.list.isRequired, lastStatusId: PropTypes.string, unread:PropTypes.bool.isRequired, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, markRead: PropTypes.func.isRequired, }; handleClick = () => { if (!this.context.router) { return; } const { lastStatusId, unread, markRead } = this.props; if (unread) { markRead(); } this.context.router.history.push(`/statuses/${lastStatusId}`); } handleHotkeyMoveUp = () => { this.props.onMoveUp(this.props.conversationId); } handleHotkeyMoveDown = () => { this.props.onMoveDown(this.props.conversationId); } render () { const { accounts, lastStatusId, unread } = this.props; if (lastStatusId === null) { return null; } return ( <StatusContainer id={lastStatusId} unread={unread} otherAccounts={accounts} onMoveUp={this.handleHotkeyMoveUp} onMoveDown={this.handleHotkeyMoveDown} onClick={this.handleClick} /> ); } }
examples/todos/src/containers/AddTodo.js
bvasko/redux
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
_deprecated/src/components/About.js
paigekehoe/paigekehoe.github.io
import React from 'react'; import Interactive from 'react-interactive'; import { Switch, Route, Link } from 'react-router-dom'; import ExampleTwoDeepComponent from './ExampleTwoDeepComponent'; import PageNotFound from './PageNotFound'; import s from '../styles/exampleComponent.style'; const ExamplePageText = () => ( <p style={s.p}> This is an example page. Refresh the page or copy/paste the url to test out the redirect functionality (this same page should load after the redirect). </p> ); export default function ExampleComponent() { return ( <Switch> <Route exact path="/example/two-deep" render={({ location }) => ( <div> <ExamplePageText /> <ExampleTwoDeepComponent location={location} /> </div> )} /> <Route exact path="/example" render={() => ( <div> <ExamplePageText /> <div style={s.pageLinkContainer}> <Interactive as={Link} {...s.link} to="/example/two-deep?field1=foo&field2=bar#boom!" >Example two deep with query and hash</Interactive> </div> </div> )} /> <Route component={PageNotFound} /> </Switch> ); }
03-mybooks/src/index.js
iproduct/course-node-express-react
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
client/admin/info/InformationPage.stories.js
iiet/iiet-chat
import { action } from '@storybook/addon-actions'; import { boolean, object } from '@storybook/addon-knobs/react'; import React from 'react'; import { dummyDate } from '../../../.storybook/helpers'; import { InformationPage } from './InformationPage'; export default { title: 'admin/info/InformationPage', component: InformationPage, decorators: [ (fn) => <div className='rc-old'>{fn()}</div>, ], }; const info = { marketplaceApiVersion: 'info.marketplaceApiVersion', commit: { hash: 'info.commit.hash', date: 'info.commit.date', branch: 'info.commit.branch', tag: 'info.commit.tag', author: 'info.commit.author', subject: 'info.commit.subject', }, compile: { platform: 'info.compile.platform', arch: 'info.compile.arch', osRelease: 'info.compile.osRelease', nodeVersion: 'info.compile.nodeVersion', date: dummyDate, }, }; const statistics = { version: 'statistics.version', migration: { version: 'statistics.migration.version', lockedAt: dummyDate, }, installedAt: dummyDate, process: { nodeVersion: 'statistics.process.nodeVersion', uptime: 10 * 24 * 60 * 60, pid: 'statistics.process.pid', }, uniqueId: 'statistics.uniqueId', instanceCount: 1, oplogEnabled: true, os: { type: 'statistics.os.type', platform: 'statistics.os.platform', arch: 'statistics.os.arch', release: 'statistics.os.release', uptime: 10 * 24 * 60 * 60, loadavg: [1.1, 1.5, 1.15], totalmem: 1024, freemem: 1024, cpus: [{}], }, mongoVersion: 'statistics.mongoVersion', mongoStorageEngine: 'statistics.mongoStorageEngine', totalUsers: 'statistics.totalUsers', nonActiveUsers: 'nonActiveUsers', activeUsers: 'statistics.activeUsers', totalConnectedUsers: 'statistics.totalConnectedUsers', onlineUsers: 'statistics.onlineUsers', awayUsers: 'statistics.awayUsers', offlineUsers: 'statistics.offlineUsers', totalRooms: 'statistics.totalRooms', totalChannels: 'statistics.totalChannels', totalPrivateGroups: 'statistics.totalPrivateGroups', totalDirect: 'statistics.totalDirect', totalLivechat: 'statistics.totalLivechat', totalDiscussions: 'statistics.totalDiscussions', totalThreads: 'statistics.totalThreads', totalMessages: 'statistics.totalMessages', totalChannelMessages: 'statistics.totalChannelMessages', totalPrivateGroupMessages: 'statistics.totalPrivateGroupMessages', totalDirectMessages: 'statistics.totalDirectMessages', totalLivechatMessages: 'statistics.totalLivechatMessages', uploadsTotal: 'statistics.uploadsTotal', uploadsTotalSize: 1024, integrations: { totalIntegrations: 'statistics.integrations.totalIntegrations', totalIncoming: 'statistics.integrations.totalIncoming', totalIncomingActive: 'statistics.integrations.totalIncomingActive', totalOutgoing: 'statistics.integrations.totalOutgoing', totalOutgoingActive: 'statistics.integrations.totalOutgoingActive', totalWithScriptEnabled: 'statistics.integrations.totalWithScriptEnabled', }, }; const exampleInstance = { address: 'instances[].address', broadcastAuth: 'instances[].broadcastAuth', currentStatus: { connected: 'instances[].currentStatus.connected', retryCount: 'instances[].currentStatus.retryCount', status: 'instances[].currentStatus.status', }, instanceRecord: { _id: 'instances[].instanceRecord._id', pid: 'instances[].instanceRecord.pid', _createdAt: dummyDate, _updatedAt: dummyDate, }, }; export const _default = () => <InformationPage canViewStatistics={boolean('canViewStatistics', true)} isLoading={boolean('isLoading', false)} info={object('info', info)} statistics={object('statistics', statistics)} instances={object('instances', exampleInstance)} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const withoutCanViewStatisticsPermission = () => <InformationPage info={info} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const loading = () => <InformationPage canViewStatistics isLoading info={info} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const withStatistics = () => <InformationPage canViewStatistics info={info} statistics={statistics} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const withOneInstance = () => <InformationPage canViewStatistics info={info} statistics={statistics} instances={[exampleInstance]} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const withTwoInstances = () => <InformationPage canViewStatistics info={info} statistics={statistics} instances={[exampleInstance, exampleInstance]} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />; export const withTwoInstancesAndDisabledOplog = () => <InformationPage canViewStatistics info={info} statistics={{ ...statistics, instanceCount: 2, oplogEnabled: false }} instances={[exampleInstance, exampleInstance]} onClickRefreshButton={action('clickRefreshButton')} onClickDownloadInfo={action('clickDownloadInfo')} />;
examples/official-storybook/stories/addon-toolbars.stories.js
storybooks/storybook
import React from 'react'; import { styled } from '@storybook/theming'; export default { title: 'Addons/Toolbars', parameters: { layout: 'centered', }, }; const getCaptionForLocale = (locale) => { switch (locale) { case 'es': return 'Hola!'; case 'fr': return 'Bonjour!'; case 'zh': return '你好!'; case 'kr': return '안녕하세요!'; case 'en': default: return 'Hello'; } }; export const Locale = (_args, { globals: { locale } }) => { return ( <Themed> <div style={{ fontSize: 30 }}>Your locale is '{locale}', so I say:</div> <div style={{ fontSize: 14 }}>note: cycle backwards and forwards with "K" & "L"</div> <div style={{ fontSize: 60, fontWeight: 'bold' }}>{getCaptionForLocale(locale)}</div> </Themed> ); }; const Themed = styled.div(({ theme }) => ({ color: theme.color.defaultText, }));
node_modules/react-icons/fa/jsfiddle.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const FaJsfiddle = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m34.9 17.6q2.2 0.9 3.5 2.8t1.4 4.3q0 3.2-2.3 5.5t-5.6 2.2q0 0-0.2 0t-0.2 0h-23.6q-3.3-0.2-5.6-2.4t-2.3-5.5q0-2.1 1.1-3.9t2.8-2.9q-0.2-0.7-0.2-1.6 0-2.2 1.6-3.8t3.8-1.5q1.9 0 3.4 1.1 1.4-3 4.3-4.8t6.3-1.8q3.3 0 6 1.5t4.3 4.3 1.6 5.8q0 0.1-0.1 0.3t0 0.4z m-25.8 5.2q0 2.3 1.6 3.7t4.1 1.4q2.6 0 4.6-1.9-0.3-0.4-0.9-1.1t-0.9-1q-1.3 1.2-2.8 1.2-1 0-1.8-0.6t-0.7-1.7q0-1 0.7-1.7t1.8-0.7q0.9 0 1.6 0.5t1.5 1 1.2 1.5 1.4 1.6 1.5 1.4 1.8 1.1 2.4 0.4q2.4 0 4-1.4t1.6-3.7q0-2.3-1.6-3.7t-4.1-1.4q-2.7 0-4.6 1.9 0.2 0.3 0.5 0.7t0.7 0.7 0.6 0.7q1.3-1.3 2.7-1.3 1 0 1.8 0.7t0.8 1.6q0 1.1-0.7 1.8t-1.9 0.7q-0.8 0-1.6-0.4t-1.4-1.1-1.2-1.5-1.4-1.6-1.5-1.4-1.8-1.1-2.3-0.4q-2.4 0-4.1 1.4t-1.6 3.7z"/></g> </Icon> ) export default FaJsfiddle
frontend/src/components/select-editor/select-editor.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { gettext } from '../../utils/constants'; import Select from 'react-select'; import '../../css/select-editor.css'; const propTypes = { isTextMode: PropTypes.bool.isRequired, // there will be two mode. first: text and select. second: just select isEditIconShow: PropTypes.bool.isRequired, options: PropTypes.array.isRequired, currentOption: PropTypes.string.isRequired, translateOption: PropTypes.func.isRequired, translateExplanation: PropTypes.func, onOptionChanged: PropTypes.func.isRequired, toggleItemFreezed: PropTypes.func, }; class SelectEditor extends React.Component { constructor(props) { super(props); this.state = { isEditing: false, options: [] }; this.options = []; } componentDidMount() { document.addEventListener('click', this.onHideSelect); this.setOptions(); } setOptions = () => { this.options = []; const options = this.props.options; for (let i = 0, length = options.length; i < length; i++) { let option = {}; option.value = options[i]; if (!options[i].length) { // it's ''. for example, intitution option in 'system admin - users' page can be ''. option.label = <div style={{minHeight: '1em'}}></div>; } else { option.label = <div>{this.props.translateOption(options[i])}{ this.props.translateExplanation && <div className="permission-editor-explanation">{this.props.translateExplanation(options[i])}</div>}</div>; } this.options.push(option); } this.setState({ options: this.options }); } componentWillReceiveProps() { this.setOptions(); } componentWillUnmount() { document.removeEventListener('click', this.onHideSelect); } onEditPermission = (e) => { e.nativeEvent.stopImmediatePropagation(); this.setState({isEditing: true}); this.props.toggleItemFreezed && this.props.toggleItemFreezed(true); } onOptionChanged = (e) => { let permission = e.value; if (permission !== this.props.currentOption) { this.props.onOptionChanged(permission); } this.setState({isEditing: false}); this.props.toggleItemFreezed && this.props.toggleItemFreezed(false); } onSelectHandler = (e) => { e.nativeEvent.stopImmediatePropagation(); } onHideSelect = () => { this.setState({isEditing: false}); this.props.toggleItemFreezed && this.props.toggleItemFreezed(false); } render() { let { currentOption, isTextMode } = this.props; // scence1: isTextMode (text)editor-icon --> select // scence2: !isTextMode select return ( <div className="permission-editor" onClick={this.onSelectHandler}> {(!isTextMode || this.state.isEditing) && <Select options={this.state.options} className="permission-editor-select" classNamePrefix="permission-editor" placeholder={this.props.translateOption(currentOption)} value={currentOption} onChange={this.onOptionChanged} captureMenuScroll={false} /> } {(isTextMode && !this.state.isEditing) && <div> {this.props.translateOption(currentOption)} {this.props.isEditIconShow && ( <span title={gettext('Edit')} className="fa fa-pencil-alt attr-action-icon" onClick={this.onEditPermission}> </span> )} </div> } </div> ); } } SelectEditor.propTypes = propTypes; export default SelectEditor;
app/javascript/mastodon/features/community_timeline/index.js
yukimochi/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandCommunityTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectCommunityStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.community', defaultMessage: 'Local timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'community', 'other', 'onlyMedia']); const timelineState = state.getIn(['timelines', `community${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, }; }; export default @connect(mapStateToProps) @injectIntl class CommunityTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, columnId: PropTypes.string, intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, onlyMedia: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('COMMUNITY', { other: { onlyMedia } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia } = this.props; dispatch(expandCommunityTimeline({ onlyMedia })); this.disconnect = dispatch(connectCommunityStream({ onlyMedia })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia) { const { dispatch, onlyMedia } = this.props; this.disconnect(); dispatch(expandCommunityTimeline({ onlyMedia })); this.disconnect = dispatch(connectCommunityStream({ onlyMedia })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia } = this.props; dispatch(expandCommunityTimeline({ maxId, onlyMedia })); } render () { const { intl, hasUnread, columnId, multiColumn, onlyMedia } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='users' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`community_timeline-${columnId}`} timelineId={`community${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />} bindToDocument={!multiColumn} /> </Column> ); } }
UI/Buttons/ButtonCheck.js
Datasilk/Dedicate
import React from 'react'; import { View, TouchableOpacity} from 'react-native'; import {Path} from 'react-native-svg'; import SvgIcon from 'ui/SvgIcon'; import AppStyles from 'dedicate/AppStyles'; export default class ButtonCheck extends React.Component { constructor(props){ super(props); } render() { const color = this.props.color || AppStyles.color; return ( <TouchableOpacity onPress={this.props.onPress}> <View style={[this.props.style]}> <SvgIcon {...this.props}> <Path fill={color} d="M 64 6 L 54 0 26 46 8 28 0 36 28 64 64 6 Z"/> </SvgIcon> </View> </TouchableOpacity> ); } }
src/components/AlertContainer.js
ravasthi/yaras
import PropTypes from 'prop-types'; import React from 'react'; /** * A container for one or more `Alert` components. * * @param {any} props */ function AlertContainer({ children, className }) { const classNames = `alerts ${className}`; return ( <ul className={classNames}> {children} </ul> ); } AlertContainer.propTypes = { /** Any number of alerts */ children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), /** Any custom class names */ className: PropTypes.string, }; AlertContainer.defaultProps = { className: '', }; export default AlertContainer;
packages/material-ui-styles/src/withTheme/withTheme.js
lgollut/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { chainPropTypes, getDisplayName } from '@material-ui/utils'; import useTheme from '../useTheme'; export function withThemeCreator(options = {}) { const { defaultTheme } = options; const withTheme = (Component) => { if (process.env.NODE_ENV !== 'production') { if (Component === undefined) { throw new Error( [ 'You are calling withTheme(Component) with an undefined component.', 'You may have forgotten to import it.', ].join('\n'), ); } } const WithTheme = React.forwardRef(function WithTheme(props, ref) { const { innerRef, ...other } = props; const theme = useTheme() || defaultTheme; return <Component theme={theme} ref={innerRef || ref} {...other} />; }); WithTheme.propTypes = { /** * Use that prop to pass a ref to the decorated component. * @deprecated */ innerRef: chainPropTypes(PropTypes.oneOfType([PropTypes.func, PropTypes.object]), (props) => { if (props.innerRef == null) { return null; } return new Error( 'Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' + 'Refs are now automatically forwarded to the inner component.', ); }), }; if (process.env.NODE_ENV !== 'production') { WithTheme.displayName = `WithTheme(${getDisplayName(Component)})`; } hoistNonReactStatics(WithTheme, Component); if (process.env.NODE_ENV !== 'production') { // Exposed for test purposes. WithTheme.Naked = Component; } return WithTheme; }; return withTheme; } // Provide the theme object as a prop to the input component. // It's an alternative API to useTheme(). // We encourage the usage of useTheme() where possible. const withTheme = withThemeCreator(); export default withTheme;
src/components/comment-list.js
josebigio/PodCast
import React from 'react'; import Comment from './comment' const CommentList = ({comments, isLoading})=>{ console.log('COMMENT LIST. IS LOADING',isLoading); return( <ul className="list-group comment-list"> {comments && comments.map((comment,i)=>{ return <Comment key={i} comment={comment}/> })} {isLoading && <div className="comment-list-loader-parent"><div className="loader"/></div>} </ul> ); } export default CommentList;
src/components/SponsorsItem/SponsorsItem.js
ksevezich/DayOfBlueprint
import React from 'react' import classes from './SponsorsItem.scss' const determineSize = (size) => { switch (size) { case 3: return {'maxWidth': '225px', 'maxHeight': '150px'} case 2: return {'maxWidth': '150px'} case 1: return {'maxWidth': '100px'} default: return {'maxWidth': '100px'} } } export const SponsorsItem = (props) => ( <div> <div className={classes.imageBox}> <a href={props.sponsorUrl}> <img className={classes.image} style={determineSize(props.size)} src={props.imageUrl} /> </a> </div> </div> ) SponsorsItem.propTypes = { imageUrl: React.PropTypes.string.isRequired, sponsorUrl: React.PropTypes.string.isRequired, size: React.PropTypes.number.isRequired } export default SponsorsItem
src/student/components/postovi/popuni.js
zeljkoX/e-learning
import React from 'react'; import CardHeader from 'material-ui/lib/card/card-header'; import CardText from 'material-ui/lib/card/card-text'; import CardActions from 'material-ui/lib/card/card-actions'; import Card from 'material-ui/lib/card/card'; import Avatar from 'material-ui/lib/avatar'; import FlatButton from 'material-ui/lib/flat-button'; class Popuni extends React.Component { constructor(props) { super(props); } render() { return ( <Card initiallyExpanded={true} style={{ width: '70%', margin: '10 auto' }}> <CardHeader title={this.props.title} subtitle="Subtitle" avatar={<Avatar style={{color:'red'}}>A</Avatar>} actAsExpander={true} showExpandableButton={true}> </CardHeader> <CardText expandable={true}> {this.props.sadrzaj} </CardText> <CardActions expandable={true}> <FlatButton label="Action1"/> <FlatButton label="Action2"/> </CardActions> </Card> ); } } export default Popuni;
src/components/Tabset/ButtonIcon.js
xander-salesforce/lcc-react-quickstart-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; // require("../../../node_modules/@salesforce-ux/design-system/assets/icons/standard-sprite/svg/symbols.svg"); require("../../../node_modules/@salesforce-ux/design-system/assets/icons/utility-sprite/svg/symbols.svg"); class ButtonIcon extends Component { static propTypes = { name: PropTypes.string.isRequired, stateful: PropTypes.string.isRequired, position: PropTypes.string.isRequired, size: PropTypes.string.isRequired, hint: PropTypes.string.isRequired } render() { let useTag = '<use xlink:href="symbols.svg#' + this.props.name + '" />'; let className = "slds-button__icon"; if (this.props.stateful) { className += "--stateful"; } if (this.props.position) { className = className + " slds-button__icon--" + this.props.position; } if (this.props.size) { className = className + " slds-button__icon--" + this.props.size; } if (this.props.hint) { className = className + " slds-button__icon--hint"; } return <svg aria-hidden="true" className={className} dangerouslySetInnerHTML={{__html: useTag }} />; } } export default ButtonIcon;
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/PageHeader.js
JamieMason/npm-cache-benchmark
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var PageHeader = function (_React$Component) { _inherits(PageHeader, _React$Component); function PageHeader() { _classCallCheck(this, PageHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } PageHeader.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement( 'div', _extends({}, elementProps, { className: classNames(className, classes) }), React.createElement( 'h1', null, children ) ); }; return PageHeader; }(React.Component); export default bsClass('page-header', PageHeader);
demo01/src/App.js
lxlneo/reactdemo
import React, { Component } from 'react'; import './App.css'; import Header from './components/header'; import Body from './components/body'; class App extends Component { render() { return ( <div className="App"> <Header/> <Body/> </div> ); } } export default App;
modules/gui/src/widget/confirm.js
openforis/sepal
import {Panel} from 'widget/panel/panel' import {msg} from 'translate' import PropTypes from 'prop-types' import React from 'react' import styles from './confirm.module.css' export default class Confirm extends React.Component { render() { const {title, message, label, onConfirm, onCancel, children} = this.props const confirm = () => onConfirm() const cancel = () => onCancel() return ( <Panel className={styles.panel} type='modal'> <Panel.Header icon='exclamation-triangle' title={title || msg('widget.confirm.title')}/> <Panel.Content> <div className={styles.message}> {message || children} </div> </Panel.Content> <Panel.Buttons onEnter={confirm} onEscape={cancel}> <Panel.Buttons.Main> <Panel.Buttons.Confirm label={label || msg('widget.confirm.label')} onClick={confirm}/> </Panel.Buttons.Main> <Panel.Buttons.Extra> <Panel.Buttons.Cancel onClick={cancel}/> </Panel.Buttons.Extra> </Panel.Buttons> </Panel> ) } } Confirm.propTypes = { onCancel: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, children: PropTypes.any, label: PropTypes.string, message: PropTypes.string, title: PropTypes.string }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestParameters.js
IamJoseph/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id = 0, ...rest }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load({ id: 0, user: { id: 42, name: '42' } }); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-parameters"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
examples/js/selection/click-to-select-table.js
AllenFang/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', clickToSelect: true // enable click to select }; export default class ClickToSelectTable 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> ); } }
node_modules/@material-ui/core/esm/Button/Button.js
pcclarke/civ-techs
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/extends"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import { fade } from '../styles/colorManipulator'; import ButtonBase from '../ButtonBase'; import { capitalize } from '../utils/helpers'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: _extends({ lineHeight: 1.75 }, theme.typography.button, { boxSizing: 'border-box', minWidth: 64, padding: '6px 16px', borderRadius: theme.shape.borderRadius, color: theme.palette.text.primary, transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], { duration: theme.transitions.duration.short }), '&:hover': { textDecoration: 'none', backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' }, '&$disabled': { backgroundColor: 'transparent' } }, '&$disabled': { color: theme.palette.action.disabled } }), /* Styles applied to the span element that wraps the children. */ label: { width: '100%', // Ensure the correct width for iOS Safari display: 'inherit', alignItems: 'inherit', justifyContent: 'inherit' }, /* Styles applied to the root element if `variant="text"`. */ text: { padding: '6px 8px' }, /* Styles applied to the root element if `variant="text"` and `color="primary"`. */ textPrimary: { color: theme.palette.primary.main, '&:hover': { backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="text"` and `color="secondary"`. */ textSecondary: { color: theme.palette.secondary.main, '&:hover': { backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"`. */ outlined: { padding: '5px 16px', border: "1px solid ".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'), '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabled) } }, /* Styles applied to the root element if `variant="outlined"` and `color="primary"`. */ outlinedPrimary: { color: theme.palette.primary.main, border: "1px solid ".concat(fade(theme.palette.primary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.primary.main), backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"` and `color="secondary"`. */ outlinedSecondary: { color: theme.palette.secondary.main, border: "1px solid ".concat(fade(theme.palette.secondary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.secondary.main), backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } }, '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabled) } }, /* Styles applied to the root element if `variant="contained"`. */ contained: { color: theme.palette.getContrastText(theme.palette.grey[300]), backgroundColor: theme.palette.grey[300], boxShadow: theme.shadows[2], '&$focusVisible': { boxShadow: theme.shadows[6] }, '&:active': { boxShadow: theme.shadows[8] }, '&$disabled': { color: theme.palette.action.disabled, boxShadow: theme.shadows[0], backgroundColor: theme.palette.action.disabledBackground }, '&:hover': { backgroundColor: theme.palette.grey.A100, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.grey[300] }, '&$disabled': { backgroundColor: theme.palette.action.disabledBackground } } }, /* Styles applied to the root element if `variant="contained"` and `color="primary"`. */ containedPrimary: { color: theme.palette.primary.contrastText, backgroundColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.primary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.primary.main } } }, /* Styles applied to the root element if `variant="contained"` and `color="secondary"`. */ containedSecondary: { color: theme.palette.secondary.contrastText, backgroundColor: theme.palette.secondary.main, '&:hover': { backgroundColor: theme.palette.secondary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.secondary.main } } }, /* Styles applied to the ButtonBase root element if the button is keyboard focused. */ focusVisible: {}, /* Styles applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `color="inherit"`. */ colorInherit: { color: 'inherit', borderColor: 'currentColor' }, /* Styles applied to the root element if `size="small"`. */ sizeSmall: { padding: '4px 8px', minWidth: 64, fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"`. */ sizeLarge: { padding: '8px 24px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' } }; }; var Button = React.forwardRef(function Button(props, ref) { var children = props.children, classes = props.classes, classNameProp = props.className, _props$color = props.color, color = _props$color === void 0 ? 'default' : _props$color, _props$component = props.component, component = _props$component === void 0 ? 'button' : _props$component, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$disableFocusRi = props.disableFocusRipple, disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi, focusVisibleClassName = props.focusVisibleClassName, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$size = props.size, size = _props$size === void 0 ? 'medium' : _props$size, _props$type = props.type, type = _props$type === void 0 ? 'button' : _props$type, _props$variant = props.variant, variant = _props$variant === void 0 ? 'text' : _props$variant, other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "disabled", "disableFocusRipple", "focusVisibleClassName", "fullWidth", "size", "type", "variant"]); var contained = variant === 'contained'; var text = variant === 'text'; var className = clsx(classes.root, classNameProp, variant === 'outlined' && [classes.outlined, color === 'primary' && classes.outlinedPrimary, color === 'secondary' && classes.outlinedSecondary], color === 'secondary' && [text && classes.textSecondary, contained && classes.containedSecondary], color === 'primary' && [text && classes.textPrimary, contained && classes.containedPrimary], text && classes.text, contained && classes.contained, size !== 'medium' && classes["size".concat(capitalize(size))], disabled && classes.disabled, fullWidth && classes.fullWidth, color === 'inherit' && classes.colorInherit); return React.createElement(ButtonBase, _extends({ className: className, component: component, disabled: disabled, focusRipple: !disableFocusRipple, focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName), ref: ref, type: type }, other), React.createElement("span", { className: classes.label }, children)); }); process.env.NODE_ENV !== "production" ? Button.propTypes = { /** * The content of the button. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the button will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the keyboard focus ripple will be disabled. * `disableRipple` must also be true. */ disableFocusRipple: PropTypes.bool, /** * If `true`, the ripple effect will be disabled. * * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure * to highlight the element by applying separate styles with the `focusVisibleClassName`. */ disableRipple: PropTypes.bool, /** * @ignore */ focusVisibleClassName: PropTypes.string, /** * If `true`, the button will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The URL to link to when the button is clicked. * If defined, an `a` element will be used as the root node. */ href: PropTypes.string, /** * The size of the button. * `small` is equivalent to the dense button styling. */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** * @ignore */ type: PropTypes.string, /** * The variant to use. */ variant: PropTypes.oneOf(['text', 'outlined', 'contained']) } : void 0; export default withStyles(styles, { name: 'MuiButton' })(Button);
src/views/AppContext.js
physiii/home-gateway
import React from 'react'; import PropTypes from 'prop-types'; import PureComponent from './components/PureComponent.js'; const Context = React.createContext(), NavigationScreenContext = React.createContext(), navigationScreenActions = new Map(), navigationScreenBackActions = new Map(); class AppContext extends React.Component { constructor (props) { super(props); this.setScreenActions = this.setScreenActions.bind(this); this.clearScreenActions = this.clearScreenActions.bind(this); this.setScreenBackActions = this.setScreenBackActions.bind(this); this.clearScreenBackActions = this.clearScreenBackActions.bind(this); this.contextValue = { screenActions: navigationScreenActions, setScreenActions: this.setScreenActions, clearScreenActions: this.clearScreenActions, screenBackActions: navigationScreenBackActions, setScreenBackActions: this.setScreenBackActions, clearScreenBackActions: this.clearScreenBackActions }; } setScreenActions (path, content) { navigationScreenActions.set(path, content); this.forceUpdate(); } clearScreenActions (path) { navigationScreenActions.delete(path); this.forceUpdate(); } setScreenBackActions (path, content) { navigationScreenBackActions.set(path, content); this.forceUpdate(); } clearScreenBackActions (path) { navigationScreenBackActions.delete(path); this.forceUpdate(); } render () { return ( <Context.Provider value={this.contextValue}> <NavigationScreenContext.Provider value={{ navigationScreenActions: Array.from(navigationScreenActions.values()).pop(), navigationScreenBackAction: Array.from(navigationScreenBackActions.values()).pop() }}> <PureComponent> {this.props.children} </PureComponent> </NavigationScreenContext.Provider> </Context.Provider> ); } } AppContext.propTypes = { children: PropTypes.node }; export const withAppContext = ({includeScreenActions} = {}) => (Component) => (_props) => ( <Context.Consumer> {(context) => { if (includeScreenActions) { return ( <NavigationScreenContext.Consumer> {(screenContext) => <Component {...context} {...screenContext} {..._props} />} </NavigationScreenContext.Consumer> ); } return <Component {...context} {..._props} />; }} </Context.Consumer> ); export default AppContext;
src/app/components/Overlay/index.js
nhardy/web-scaffold
// @flow import React, { Component } from 'react'; import cx from 'classnames'; import styles from './styles.styl'; type Props = { className?: string, }; const dismissEvents = ['click', 'touchstart']; export default class Overlay extends Component<Props, void> { static defaultProps = { className: undefined, }; componentDidMount() { dismissEvents.forEach(type => this._node && this._node.addEventListener(type, this.handleDismiss)); } componentWillUnmount() { dismissEvents.forEach(type => this._node && this._node.removeEventListener(type, this.handleDismiss)); } _node: ?HTMLDivElement; listeners: Array<() => void> = []; addListener(listener: () => void) { this.listeners.push(listener); return () => { this.listeners = this.listeners.filter(l => l !== listener); }; } handleDismiss = () => { this.listeners.forEach(l => l()); }; render() { // FIXME: Remove when better flow recognition in eslint-plugin-react is merged // @see: https://github.com/yannickcr/eslint-plugin-react/issues/1138 /* eslint-disable react/prop-types */ return ( <div className={cx(styles.root, this.props.className)} ref={ref => (this._node = ref)} /> ); } }
src/icons/Umbrella.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Umbrella extends React.Component { render() { if(this.props.bare) { return <g> <g> <g> <path d="M376.2,288c0,0.1,0,0.2,0,0.4C376.2,288.2,376.2,288.1,376.2,288L376.2,288z"></path> <path d="M136.2,288c0,0.1,0,0.2,0,0.4C136.2,288.2,136.2,288.1,136.2,288L136.2,288z"></path> </g> <path d="M272,48.8c0-0.3,0-0.5,0-0.8c0-8.8-7.2-16-16-16c-8.8,0-16,7.2-16,16c0,0.2,0,0.5,0,0.7c-116.3,8-208,103.1-208,221.4 c0,3.6,0.2,14.2,0.4,17.8c2.7-26.3,24.7-51.7,51.7-51.7c28.7,0,51.9,23.1,52.1,51.7h0c0.2-28.6,23.4-51.7,52.1-51.7 c26.5,0,50.9,21.1,51.7,45.5V416c0,17.9-14.1,32-32,32c-17.1,0-31-14.4-31-32c0-8.8-7.2-16-16-16s-16,7.2-16,16 c0,35.3,28.3,64,63,64c17.3,0,33.5-6.7,45.5-18.8c11.9-12,18.5-28.1,18.5-45.2l0-135.3c3.3-32.7,23.4-44.4,52.1-44.4 c28.7,0,51.9,23.1,52.1,51.7h0c0.2-28.6,23.4-51.7,52.1-51.7c26.1,0,47.6,26.7,51.4,51.7c0.1-2.8,0.2-9.1,0.2-11.8 C480,157.8,388.2,57.3,272,48.8z"></path> </g> </g>; } return <IconBase> <g> <g> <path d="M376.2,288c0,0.1,0,0.2,0,0.4C376.2,288.2,376.2,288.1,376.2,288L376.2,288z"></path> <path d="M136.2,288c0,0.1,0,0.2,0,0.4C136.2,288.2,136.2,288.1,136.2,288L136.2,288z"></path> </g> <path d="M272,48.8c0-0.3,0-0.5,0-0.8c0-8.8-7.2-16-16-16c-8.8,0-16,7.2-16,16c0,0.2,0,0.5,0,0.7c-116.3,8-208,103.1-208,221.4 c0,3.6,0.2,14.2,0.4,17.8c2.7-26.3,24.7-51.7,51.7-51.7c28.7,0,51.9,23.1,52.1,51.7h0c0.2-28.6,23.4-51.7,52.1-51.7 c26.5,0,50.9,21.1,51.7,45.5V416c0,17.9-14.1,32-32,32c-17.1,0-31-14.4-31-32c0-8.8-7.2-16-16-16s-16,7.2-16,16 c0,35.3,28.3,64,63,64c17.3,0,33.5-6.7,45.5-18.8c11.9-12,18.5-28.1,18.5-45.2l0-135.3c3.3-32.7,23.4-44.4,52.1-44.4 c28.7,0,51.9,23.1,52.1,51.7h0c0.2-28.6,23.4-51.7,52.1-51.7c26.1,0,47.6,26.7,51.4,51.7c0.1-2.8,0.2-9.1,0.2-11.8 C480,157.8,388.2,57.3,272,48.8z"></path> </g> </IconBase>; } };Umbrella.defaultProps = {bare: false}
src/Label.js
apisandipas/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Label = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render() { let classes = this.getBsClassSet(); return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Label;
src/svg-icons/image/control-point-duplicate.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageControlPointDuplicate = (props) => ( <SvgIcon {...props}> <path d="M16 8h-2v3h-3v2h3v3h2v-3h3v-2h-3zM2 12c0-2.79 1.64-5.2 4.01-6.32V3.52C2.52 4.76 0 8.09 0 12s2.52 7.24 6.01 8.48v-2.16C3.64 17.2 2 14.79 2 12zm13-9c-4.96 0-9 4.04-9 9s4.04 9 9 9 9-4.04 9-9-4.04-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z"/> </SvgIcon> ); ImageControlPointDuplicate = pure(ImageControlPointDuplicate); ImageControlPointDuplicate.displayName = 'ImageControlPointDuplicate'; ImageControlPointDuplicate.muiName = 'SvgIcon'; export default ImageControlPointDuplicate;
src/components/Controls.js
tobice/flux-lumines
import React from 'react'; import PureComponent from './PureComponent.js'; export default class Controls extends PureComponent { render() { return ( <g className="lumines-controls"> <text x={-2} className="lumines-control-legend">Pause/Resume</text> <text x={2} className="lumines-control-key">Esc</text> <text x={-2} y={5} className="lumines-control-legend">Restart</text> <text x={2} y={5} className="lumines-control-key">R</text> <text x={-2} y={10} className="lumines-control-legend">Move left/right</text> <text x={2} y={10} className="lumines-control-key">Arrow left/right</text> <text x={-2} y={15} className="lumines-control-legend">Rotate left</text> <text x={2} y={15} className="lumines-control-key">A</text> <text x={-2} y={20} className="lumines-control-legend">Rotate right</text> <text x={2} y={20} className="lumines-control-key">D, Arrow up</text> <text x={-2} y={25} className="lumines-control-legend">Drop</text> <text x={2} y={25} className="lumines-control-key">Arrow down</text> </g>); } }
src1/layouts/CoreLayout.js
Cron-J/CSV-RE
import React from 'react'; import 'styles/core.scss'; import Navigation from 'containers/Navigation'; import Message from '../common/messageComponent/view/Message.react'; export default class CoreLayout extends React.Component { static propTypes = { children : React.PropTypes.element } constructor () { super(); } render () { return ( <div className='page-container'> <Message /> <div> <Navigation routedto={this.props.children}/> </div> <div className='view-container'> {this.props.children} </div> </div> ); } }
example/App.js
backgroundColor/ag-grid-addons
import React from 'react' // import TopChangePage from '../lib/TopPageChange.js' import AgTable from '../lib/AgTable.js' // import ColDefs from '../lib/ColDefs.js' export default class App extends React.Component { render () { const colDefs = [{ headerName: '序号', width: 40, cellRenderer: function (params) { return params.node.id + 1 }}, { headerName: 'test1', field: 'test1' }, { headerName: 'test2', field: 'test2' } ] const gridOptions = { rowSelection: 'single' // rowModelType: 'pagination', // rowStyle: {'font-size': '12px'}, // localeText: { // page: '', // more: '...', // to: '', // of: '/', // next: '>', // last: '>>', // first: '<<', // previous: '<', // loadingOoo: '数据加载中...', // noRowsToShow: '暂无数据' // } } const rowdata = [{ test1: '123', test2: '456' }, { test1: '789', test2: '098' }] return ( <div style={{ height: '600px', width: '800px' }}> <AgTable gridOptions={gridOptions} columnDefs={colDefs} rowData={rowdata} enableColResize='true' enableSorting='true' rowHeight='34' headerHeight='28' rowBuffer='50' debug='false' /> </div> ) } }
fields/components/DateInput.js
michaelerobertsjr/keystone
import moment from 'moment'; import DayPicker from 'react-day-picker'; import React from 'react'; import { findDOMNode } from 'react-dom'; import Popout from '../../admin/client/App/shared/Popout'; import { FormInput } from 'elemental'; let lastId = 0; module.exports = React.createClass({ displayName: 'DateInput', propTypes: { format: React.PropTypes.string, name: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, path: React.PropTypes.string, value: React.PropTypes.string.isRequired, }, getDefaultProps () { return { format: 'YYYY-MM-DD', }; }, getInitialState () { const id = ++lastId; let month = new Date(); const { format, value } = this.props; if (moment(value, format, true).isValid()) { month = moment(value, format).toDate(); } return { id: `_DateInput_${id}`, month: month, pickerIsOpen: false, inputValue: value, }; }, componentDidMount () { this.showCurrentMonth(); }, componentWillReceiveProps: function (newProps) { if (newProps.value === this.props.value) return; this.setState({ month: moment(newProps.value, this.props.format).toDate(), inputValue: newProps.value, }, this.showCurrentMonth); }, focus () { if (!this.refs.input) return; findDOMNode(this.refs.input).focus(); }, handleInputChange (e) { const { value } = e.target; this.setState({ inputValue: value }, this.showCurrentMonth); }, handleKeyPress (e) { if (e.key === 'Enter') { e.preventDefault(); // If the date is strictly equal to the format string, dispatch onChange if (moment(this.state.inputValue, this.props.format, true).isValid()) { this.props.onChange({ value: this.state.inputValue }); // If the date is not strictly equal, only change the tab that is displayed } else if (moment(this.state.inputValue, this.props.format).isValid()) { this.setState({ month: moment(this.state.inputValue, this.props.format).toDate(), }, this.showCurrentMonth); } } }, handleDaySelect (e, date, modifiers) { if (modifiers && modifiers.disabled) return; var value = moment(date).format(this.props.format); this.props.onChange({ value }); this.setState({ pickerIsOpen: false, month: date, inputValue: value, }); }, showPicker () { this.setState({ pickerIsOpen: true }, this.showCurrentMonth); }, showCurrentMonth () { if (!this.refs.picker) return; this.refs.picker.showMonth(this.state.month); }, handleFocus (e) { if (this.state.pickerIsOpen) return; this.showPicker(); }, handleCancel () { this.setState({ pickerIsOpen: false }); }, handleBlur (e) { let rt = e.relatedTarget || e.nativeEvent.explicitOriginalTarget; const popout = this.refs.popout.getPortalDOMNode(); while (rt) { if (rt === popout) return; rt = rt.parentNode; } this.setState({ pickerIsOpen: false, }); }, render () { const selectedDay = this.props.value; // react-day-picker adds a class to the selected day based on this const modifiers = { selected: (day) => moment(day).format(this.props.format) === selectedDay, }; return ( <div> <FormInput autoComplete="off" id={this.state.id} name={this.props.name} onBlur={this.handleBlur} onChange={this.handleInputChange} onFocus={this.handleFocus} onKeyPress={this.handleKeyPress} placeholder={this.props.format} ref="input" value={this.state.inputValue} /> <Popout isOpen={this.state.pickerIsOpen} onCancel={this.handleCancel} ref="popout" relativeToID={this.state.id} width={260} > <DayPicker modifiers={modifiers} onDayClick={this.handleDaySelect} ref="picker" tabIndex={-1} /> </Popout> </div> ); }, });
client/Slides/FlappyDemoSlide.js
Dean177/jumpy-bird-react-demo
import '!style!css!less!../resources/styles/JumpyBird.less'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import FlappyBirdGame from '../FlappyBird/FlappyBirdGame'; import GameDetails from '../FlappyBird/GameDetails'; @connect(state => state) class FlappyDemoSlide extends Component { render() { const { flappy, gameDetails, dispatch } = this.props; return ( <div className="flappy-slide"> <FlappyBirdGame gameState={flappy} dispatch={dispatch} /> <GameDetails gameDetails={gameDetails} dispatch={dispatch} /> </div> ); } } export default FlappyDemoSlide
webapp/app/components/DashboardByUser/HeaderPage/Button/index.js
EIP-SAM/SAM-Solution-Server
// // Button header page in dashboard by user page // import React from 'react'; import { ButtonToolbar } from 'react-bootstrap'; import LinkContainerButton from 'components/Button'; import RebootButtonModal from 'containers/DashboardByUser/HeaderPage/Button/ModalRebootUser'; import styles from './styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class DashboardByUserHeaderPageButton extends React.Component { handleRebootClick() { this.props.showInstantRebootModal(); } render() { return ( <div className={styles.buttonHandle}> <ButtonToolbar className={styles.toolbar}> <LinkContainerButton buttonBsStyle="info" buttonText="Reboot" onClick={() => this.handleRebootClick()} /> <LinkContainerButton buttonBsStyle="info" buttonText="Send notification" link="/notifications" /> </ButtonToolbar> <RebootButtonModal /> </div> ); } } DashboardByUserHeaderPageButton.propTypes = { showInstantRebootModal: React.PropTypes.func, };
src/client/components/error/error.js
adeperio/base
'use strict'; import './error.less'; import React from 'react'; export default React.createClass({ propTypes: { }, render: function() { var homeUrl = '/'; return ( <div className={'error'}> <div className="error-box"> <h1>These arent the droids you are looking for</h1> <a href={homeUrl}>Sign in with your email</a> </div> </div> ); } });
src/Parser/Paladin/Holy/Modules/Talents/AuraOfMercy.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatNumber } from 'common/format'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Combatants from 'Parser/Core/Modules/Combatants'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class AuraOfMercy extends Analyzer { static dependencies = { combatants: Combatants, abilityTracker: AbilityTracker, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.AURA_OF_MERCY_TALENT.id); } get healing() { const abilityTracker = this.abilityTracker; const getAbility = spellId => abilityTracker.getAbility(spellId); return (getAbility(SPELLS.AURA_OF_MERCY_HEAL.id).healingEffective + getAbility(SPELLS.AURA_OF_MERCY_HEAL.id).healingAbsorbed); } get hps() { return this.healing / this.owner.fightDuration * 1000; } get suggestionThresholds() { return { actual: this.hps, isLessThan: { minor: 30000, average: 25000, major: 20000, }, }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> The healing done by your <SpellLink id={SPELLS.AURA_OF_MERCY_TALENT.id} /> is low. Try to find a better moment to cast it or consider changing to <SpellLink id={SPELLS.AURA_OF_SACRIFICE_TALENT.id} /> or <SpellLink id={SPELLS.DEVOTION_AURA_TALENT.id} /> which can be more reliable. </Wrapper> ) .icon(SPELLS.AURA_OF_MERCY_TALENT.icon) .actual(`${formatNumber(actual)} HPS`) .recommended(`>${formatNumber(recommended)} HPS is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.AURA_OF_MERCY_TALENT.id} />} value={`${formatNumber(this.hps)} HPS`} label="Healing done" /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(60); } export default AuraOfMercy;
packages/react-instantsearch-dom/src/widgets/RatingMenu.js
algolia/react-instantsearch
import React from 'react'; import { connectRange } from 'react-instantsearch-core'; import PanelCallbackHandler from '../components/PanelCallbackHandler'; import RatingMenu from '../components/RatingMenu'; /** * RatingMenu lets the user refine search results by clicking on stars. * * The stars are based on the selected `attribute`. * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @name RatingMenu * @kind widget * @requirements The attribute passed to the `attribute` prop must be present in “attributes for faceting” * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * The values inside the attribute must be JavaScript numbers (not strings). * @propType {string} attribute - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-RatingMenu - the root div of the widget * @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RatingMenu-list - the list of ratings * @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement * @themeKey ais-RatingMenu-item - the rating list item * @themeKey ais-RatingMenu-item--selected - the selected rating list item * @themeKey ais-RatingMenu-item--disabled - the disabled rating list item * @themeKey ais-RatingMenu-link - the rating clickable item * @themeKey ais-RatingMenu-starIcon - the star icon * @themeKey ais-RatingMenu-starIcon--full - the filled star icon * @themeKey ais-RatingMenu-starIcon--empty - the empty star icon * @themeKey ais-RatingMenu-label - the label used after the stars * @themeKey ais-RatingMenu-count - the count of ratings for a specific item * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RatingMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); */ const RatingMenuWidget = (props) => ( <PanelCallbackHandler {...props}> <RatingMenu {...props} /> </PanelCallbackHandler> ); export default connectRange(RatingMenuWidget);