path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
.storybook/components/FooterStory.js
hellobrian/carbon-components-react
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import Footer from '../../components/Footer'; import Checkbox from '../../components/Checkbox'; const additionalProps = { onClick: action('onClick'), className: 'some-class', labelOne: 'Need Help?', linkTextOne: 'Contact Bluemix Sales', linkHrefOne: 'www.google.com', labelTwo: 'Estimate Monthly Cost', linkTextTwo: 'Cost Calculator', linkHrefTwo: 'www.google.com', buttonText: 'Create', }; storiesOf('Footer', module) .addWithInfo( 'Default', ` Footer is used on configuration screens. `, () => <Footer {...additionalProps} />, ) .addWithInfo( 'Custom', ` This footer allows custom elements to be placed inside. `, () => ( <Footer className="some-class"> This is a test Footer. </Footer> ), );
src/applications/static-pages/health-care-manage-benefits/refill-track-prescriptions-page/index.js
department-of-veterans-affairs/vets-website
// Node modules. import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; export default (store, widgetType) => { const root = document.querySelector(`[data-widget-type="${widgetType}"]`); if (root) { import(/* webpackChunkName: "refill-track-prescriptions-page" */ './components/App').then(module => { const App = module.default; ReactDOM.render( <Provider store={store}> <App /> </Provider>, root, ); }); } };
app/index.js
ivtpz/brancher
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import { resetTree } from './actions/verticalTreeActions'; // import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); history.listen(location => { if (location.pathname === '/') { store.dispatch(resetTree()); } }); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
src/common/form/fields/TextAreaField.js
fastmonkeys/respa-ui
import React from 'react'; import PropTypes from 'prop-types'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import FormControl from 'react-bootstrap/lib/FormControl'; const TextAreaField = ({ onChange, onKeyPress, label, placeholder, value, id, rows, }) => ( <FormGroup controlId={`textAreaField-${id}`}> {label && <ControlLabel className="app-TextAreaField__label">{label}</ControlLabel>} <FormControl className="app-TextAreaField__textarea" componentClass="textarea" onChange={onChange} onKeyPress={onKeyPress} placeholder={placeholder} rows={rows} value={value} /> </FormGroup> ); TextAreaField.propTypes = { id: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onKeyPress: PropTypes.func, label: PropTypes.string, placeholder: PropTypes.string, rows: PropTypes.number, value: PropTypes.string.isRequired, }; export default TextAreaField;
packages/icons/src/md/maps/LocalAtm.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLocalAtm(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M22 34h4v-2h2c1.1 0 2-.9 2-2v-6c0-1.1-.9-2-2-2h-6v-2h8v-4h-4v-2h-4v2h-2c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h6v2h-8v4h4v2zM40 8c2.21 0 4 1.79 4 4v24c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4l.02-24c0-2.21 1.77-4 3.98-4h32zm0 28V12H8v24h32z" /> </IconBase> ); } export default MdLocalAtm;
src/svg-icons/device/bluetooth-disabled.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothDisabled = (props) => ( <SvgIcon {...props}> <path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/> </SvgIcon> ); DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled); DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled'; DeviceBluetoothDisabled.muiName = 'SvgIcon'; export default DeviceBluetoothDisabled;
src/containers/Header.js
ashmaroli/jekyll-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; export class Header extends Component { render() { const { config, admin } = this.props; return ( <div className="header"> <h3 className="title"> <Link target="_blank" to={config.url || '/'}> <i className="fa fa-home" /> <span>{config.title || 'You have no title!'}</span> </Link> </h3> <span className="version">{admin.version}</span> </div> ); } } Header.propTypes = { admin: PropTypes.object.isRequired, config: PropTypes.object.isRequired, }; export default Header;
src/main.js
guileen/react-forum
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import makeRoutes from './routes' import Root from './containers/Root' import configureStore from './redux/configureStore' import injectTapEventPlugin from 'react-tap-event-plugin' // Needed for onTouchTap // Can go away when react 1.0 release // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin() // Configure history for react-router const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__ const store = configureStore(initialState, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store) // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={history} routes={routes} store={store} />, document.getElementById('root') )
consoles/my-joy-instances/src/containers/instances/user-script.js
yldio/joyent-portal
import React from 'react'; import { compose, graphql } from 'react-apollo'; import { Margin } from 'styled-components-spacing'; import get from 'lodash.get'; import { ViewContainer, Message, MessageTitle, MessageDescription, StatusLoader } from 'joyent-ui-toolkit'; import Editor from 'joyent-ui-toolkit/dist/es/editor'; import Description from '@components/instances/description'; import Empty from 'joyent-ui-resource-step'; import GetMetadata from '@graphql/list-metadata.gql'; export const UserScript = ({ metadata, loading = false, error = null }) => ( <ViewContainer main> <Margin bottom="3"> <Description href="https://docs.joyent.com/private-cloud/instances/using-mdata#UsingtheMetadataAPI-ListofMetadataKeys"> User script can be used to inject a custom boot script. </Description> </Margin> {loading ? <StatusLoader /> : null} {!loading && error ? ( <Margin bottom="5"> <Message error> <MessageTitle>Ooops!</MessageTitle> <MessageDescription> An error occurred while loading the instance user-script </MessageDescription> </Message> </Margin> ) : null} {!loading && metadata ? ( <Editor defaultValue={metadata.value} readOnly /> ) : null} {!loading && !error && !metadata ? ( <Empty borderTop>No User Script defined</Empty> ) : null} </ViewContainer> ); export default compose( graphql(GetMetadata, { options: ({ match }) => ({ ssr: false, variables: { fetchPolicy: 'network-only', id: get(match, 'params.instance') } }), props: ({ data }) => { const { loading, error, machine } = data; const metadata = get(machine, 'metadata', []) .filter(({ name = '' }) => name === 'user-script') .shift(); return { metadata, instance: machine, loading, error }; } }) )(UserScript);
modules/react-move/src/components/Move.js
JunisphereSystemsAG/react-color
'use strict'; import React from 'react'; import ReactCSS from 'reactcss'; export class Move extends ReactCSS.Component { classes() { return { 'default': { outer: { opacity: this.props.inStartOpacity, transform: this.props.inStartTransform, transition: this.props.inStartTransition, }, }, }; } componentDidMount() { var animate = this.refs.outer; setTimeout((function() { animate.style.opacity = this.props.inEndOpacity; animate.style.transform = this.props.inEndTransform; animate.style.transition = this.props.inEndTransition; }).bind(this), this.props.inDelay); } render() { return ( <div is="outer" ref="outer" className="foobarbaz">{ this.props.children }</div> ); } } Move.defaultProps = { inStartOpacity: '0', inStartTransform: '', inStartTransition: 'all 400ms cubic-bezier(.55,0,.1,1)', inEndOpacity: '1', inEndTransform: '', inEndTransition: 'all 400ms cubic-bezier(.55,0,.1,1)', inDelay: 0, }; export default Move;
src/svg-icons/av/closed-caption.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvClosedCaption = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 7H9.5v-.5h-2v3h2V13H11v1c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H18v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1z"/> </SvgIcon> ); AvClosedCaption = pure(AvClosedCaption); AvClosedCaption.displayName = 'AvClosedCaption'; AvClosedCaption.muiName = 'SvgIcon'; export default AvClosedCaption;
actor-apps/app-web/src/app/components/common/AvatarItem.react.js
jamesbond12/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import React from 'react'; import classNames from 'classnames'; class AvatarItem extends React.Component { static propTypes = { className: React.PropTypes.string, image: React.PropTypes.string, placeholder: React.PropTypes.string.isRequired, size: React.PropTypes.string, title: React.PropTypes.string.isRequired }; constructor(props) { super(props); } render() { const { title, className, image, size, placeholder } = this.props; const placeholderClassName = classNames('avatar__placeholder', `avatar__placeholder--${placeholder}`); const avatarClassName = classNames('avatar', { 'avatar--tiny': size === 'tiny', 'avatar--small': size === 'small', 'avatar--medium': size === 'medium', 'avatar--large': size === 'large', 'avatar--big': size === 'big', 'avatar--huge': size === 'huge' }, className); const avatar = image ? <img alt={title} className="avatar__image" src={image}/> : null; return ( <div className={avatarClassName}> {avatar} <span className={placeholderClassName}>{title[0]}</span> </div> ); } } export default AvatarItem;
src/js/index.js
thomas-lack/patchwork-planner
import React from 'react'; import ReactDom from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import patchworkPatternApp from './reducers'; import PatchworkPlannerApp from './components/PatchworkPlannerApp'; // import index.html to import webpack bundling import 'file-loader?name=[name].[ext]!../index.html'; let store = createStore(patchworkPatternApp); ReactDom.render( <Provider store={store}> <PatchworkPlannerApp /> </Provider>, document.getElementById('root') ); window.store = store;
src/components/widgets/A_H/index.js
humaniq/humaniq-pwa-website
import React from 'react'; import * as T from "prop-types"; import './styles.scss'; import {cssClassName} from 'utils' const cn = cssClassName('A_H') const A_H = ({type, icon, children, center , mix}) =>{ let tagType switch(type){ case 'animated-hero': case 'video-hero': tagType = 'h1' break; case 'hero': tagType = 'h1' break; case 'section': tagType = 'h2' break; case 'android-white': tagType = 'h2' break; case 'android-black': tagType = 'h2' break; case 'timeline': tagType = 'h2' break; case 'search': tagType = 'h3' break; case 'section-sub': tagType = 'h4' break; case 'bs': case 'tooltip': case 'hmq-e': case 's': tagType = 'h5' break; case 'tooltip-sub': case 'b-xs': case 'xs': tagType = 'h6' break; case 'xxl': tagType = 'h6' break; case 'openitem': tagType = 'h6' break; default: tagType = 'h3' } center = center && 'center' return ( React.createElement( tagType, {className: cn({type}, [center, mix])}, (icon ? <span className={cn('iconed', {icon}, [center])}>{children}</span> : children ) ) ) } A_H.propTypes = { type: T.oneOf([ 'animated-hero', 'video-hero', 'hmq-e', 'hmq', // black icon title for hmq explorer 16/25 /600, mob -margin left 16px 'hero', //black bold 25 'search', // white bold 25 used on wiki search 'timeline', // black title uses at component O_Timeline, 16/24 'bs', // blue title uses at hero home page, 16/24 'wiki-result', // blue title 16/24/600/ marign-bottom 8 'window', // black bold title 16/24 used on subscribe/personal/join/partners tooltip pages 'tooltip', // black bold title 16/24 used on tooltip marign bottom 2px 'tooltip-sub', //blue subtitle 15/26 used on tooltip marign bottom 8px 'xs', // black title uses at hero home page, 13/20 bold 'section', //black title used for sections 23/32 padding-bottom 10 'section-sub', //black title used for sections 23/32 padding-bottom 10 'section-c', //black title used for sections 23/32 padding-bottom 30, always text-align center 'xxl', //black title used at error page 60 'openitem', //light black used in open source page 'hmq-title', // 'android-white', // white bold 30 used on mobile-app 'android-black', // white bold 30 used on mobile-app ]), icon: T.oneOf([ 'placeholder', // placeholder icon ]), children: T.any.isRequired }; A_H.defaultProps = { } export default A_H
examples/counter/containers/Root.js
Gazler/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import CounterApp from './CounterApp'; import configureStore from '../store/configureStore'; const store = configureStore(); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <CounterApp />} </Provider> ); } }
src/pages/my.js
ChrisMichaelPerezSantiago/CodetrotterFinalProject
// npm packages import _ from 'lodash'; import React from 'react'; import {Observable} from 'rxjs'; // my packages import db from '../db'; import {Crunchyroll} from '../api'; // my components import Navbar from '../components/navbar'; import Series from '../components/series'; export default class MyStuff extends React.Component { constructor() { super(); this.state = { series: [], }; // trigger list update Crunchyroll.getMySeries(); } componentDidMount() { this.sub = Observable.fromEvent( db.series.changes({ since: 0, live: true, include_docs: true, }), 'change' ) .filter(change => !change.deleted) .map(change => change.doc) .filter(doc => doc.bookmarked) .scan((acc, doc) => acc.concat([doc]), []) .debounceTime(1000) .subscribe(series => this.setState({series})); } componentWillUnmount() { this.sub.unsubscribe(); } render() { const {series} = this.state; return ( <div> <Navbar /> {_.chunk(series, 4).map((chunk, i) => ( <div key={`chunk_${i}`} className="tile is-ancestor"> {chunk.map(s => <Series key={s._id} series={s} />)} </div> ))} <footer className="footer" id="video-footer"> <div className="container"> <div className="content has-text-centered"> <p> <strong>Japanistic Anime</strong> by <a>Chris M. Perez</a>. The source code is licensed <a> MIT.</a> </p> <p> <a className="icon"> <i className="fa fa-github"></i> </a> </p> </div> </div> </footer> </div> ); } }
app/javascript/mastodon/features/notifications/components/filter_bar.js
masto-donte-com-br/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; const tooltips = defineMessages({ mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' }, favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favourites' }, boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' }, polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' }, follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' }, statuses: { id: 'notifications.filter.statuses', defaultMessage: 'Updates from people you follow' }, }); export default @injectIntl class FilterBar extends React.PureComponent { static propTypes = { selectFilter: PropTypes.func.isRequired, selectedFilter: PropTypes.string.isRequired, advancedMode: PropTypes.bool.isRequired, intl: PropTypes.object.isRequired, }; onClick (notificationType) { return () => this.props.selectFilter(notificationType); } render () { const { selectedFilter, advancedMode, intl } = this.props; const renderedElement = !advancedMode ? ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} > <FormattedMessage id='notifications.filter.mentions' defaultMessage='Mentions' /> </button> </div> ) : ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} title={intl.formatMessage(tooltips.mentions)} > <Icon id='reply-all' fixedWidth /> </button> <button className={selectedFilter === 'favourite' ? 'active' : ''} onClick={this.onClick('favourite')} title={intl.formatMessage(tooltips.favourites)} > <Icon id='star' fixedWidth /> </button> <button className={selectedFilter === 'reblog' ? 'active' : ''} onClick={this.onClick('reblog')} title={intl.formatMessage(tooltips.boosts)} > <Icon id='retweet' fixedWidth /> </button> <button className={selectedFilter === 'poll' ? 'active' : ''} onClick={this.onClick('poll')} title={intl.formatMessage(tooltips.polls)} > <Icon id='tasks' fixedWidth /> </button> <button className={selectedFilter === 'status' ? 'active' : ''} onClick={this.onClick('status')} title={intl.formatMessage(tooltips.statuses)} > <Icon id='home' fixedWidth /> </button> <button className={selectedFilter === 'follow' ? 'active' : ''} onClick={this.onClick('follow')} title={intl.formatMessage(tooltips.follows)} > <Icon id='user-plus' fixedWidth /> </button> </div> ); return renderedElement; } }
src/SafeAnchor.js
wjb12/react-bootstrap
import React from 'react'; import createChainedFunction from './utils/createChainedFunction'; /** * Note: This is intended as a stop-gap for accessibility concerns that the * Bootstrap CSS does not address as they have styled anchors and not buttons * in many cases. */ export default class SafeAnchor extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(event) { if (this.props.href === undefined) { event.preventDefault(); } } render() { return ( <a role={this.props.href ? undefined : 'button'} {...this.props} onClick={createChainedFunction(this.props.onClick, this.handleClick)} href={this.props.href || ''}/> ); } } SafeAnchor.propTypes = { href: React.PropTypes.string, onClick: React.PropTypes.func };
src/svg-icons/av/sort-by-alpha.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSortByAlpha = (props) => ( <SvgIcon {...props}> <path d="M14.94 4.66h-4.72l2.36-2.36zm-4.69 14.71h4.66l-2.33 2.33zM6.1 6.27L1.6 17.73h1.84l.92-2.45h5.11l.92 2.45h1.84L7.74 6.27H6.1zm-1.13 7.37l1.94-5.18 1.94 5.18H4.97zm10.76 2.5h6.12v1.59h-8.53v-1.29l5.92-8.56h-5.88v-1.6h8.3v1.26l-5.93 8.6z"/> </SvgIcon> ); AvSortByAlpha = pure(AvSortByAlpha); AvSortByAlpha.displayName = 'AvSortByAlpha'; AvSortByAlpha.muiName = 'SvgIcon'; export default AvSortByAlpha;
packages/material-ui/src/Form/FormGroup.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = { root: { display: 'flex', flexDirection: 'column', flexWrap: 'wrap', }, row: { flexDirection: 'row', }, }; /** * `FormGroup` wraps controls such as `Checkbox` and `Switch`. * It provides compact row layout. * For the `Radio`, you should be using the `RadioGroup` component instead of this one. */ function FormGroup(props) { const { classes, className, children, row, ...other } = props; return ( <div className={classNames( classes.root, { [classes.row]: row, }, className, )} {...other} > {children} </div> ); } FormGroup.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Display group of elements in a compact row. */ row: PropTypes.bool, }; FormGroup.defaultProps = { row: false, }; export default withStyles(styles, { name: 'MuiFormGroup' })(FormGroup);
packages/docs/pages/plugin/static-toolbar/index.js
draft-js-plugins/draft-js-plugins
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import customExampleCode from '!!raw-loader!../../../components/Examples/static-toolbar/CustomToolbarEditor'; // eslint-disable-next-line import/no-unresolved import customExampleEditorStylesCode from '!!raw-loader!../../../components/Examples/static-toolbar/CustomToolbarEditor/editorStyles.module.css'; // eslint-disable-next-line import/no-unresolved import gettingStarted from '!!raw-loader!../../../components/Examples/static-toolbar/gettingStarted'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import simpleExampleCode from '!!raw-loader!../../../components/Examples/static-toolbar/SimpleToolbarEditor'; // eslint-disable-next-line import/no-unresolved import simpleExampleEditorStylesCode from '!!raw-loader!../../../components/Examples/static-toolbar/SimpleToolbarEditor/editorStyles.module.css'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import themedExampleCode from '!!raw-loader!../../../components/Examples/static-toolbar/ThemedToolbarEditor'; // eslint-disable-next-line import/no-unresolved import themedExampleButtonStylesCode from '!!raw-loader!../../../components/Examples/static-toolbar/ThemedToolbarEditor/buttonStyles.module.css'; // eslint-disable-next-line import/no-unresolved import themedExampleEditorStylesCode from '!!raw-loader!../../../components/Examples/static-toolbar/ThemedToolbarEditor/editorStyles.module.css'; // eslint-disable-next-line import/no-unresolved import themedExampleToolbarStylesCode from '!!raw-loader!../../../components/Examples/static-toolbar/ThemedToolbarEditor/toolbarStyles.module.css'; // eslint-disable-next-line import/no-unresolved import webpackConfig from '!!raw-loader!../../../components/Examples/static-toolbar/webpackConfig'; import React, { Component } from 'react'; import AlternateContainer from '../../../components/AlternateContainer/AlternateContainer'; import Code from '../../../components/Code/Code'; import Container from '../../../components/Container/Container'; // eslint-disable-next-line import/no-duplicates import CustomToolbarEditor from '../../../components/Examples/static-toolbar/CustomToolbarEditor'; // eslint-disable-next-line import/no-duplicates import SimpleToolbarEditor from '../../../components/Examples/static-toolbar/SimpleToolbarEditor'; // eslint-disable-next-line import/no-duplicates import ThemedToolbarEditor from '../../../components/Examples/static-toolbar/ThemedToolbarEditor'; import Heading from '../../../components/Heading/Heading'; import InlineCode from '../../../components/InlineCode/InlineCode'; import PluginPageFrame from '../../../components/PluginPageFrame/PluginPageFrame'; import styles from './styles.module.css'; export default class App extends Component { render() { return ( <PluginPageFrame filePath={'packages/docs/pages/plugin/static-toolbar/index.js'} > <Container> <Heading level={2}>Toolbar</Heading> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}>Desktop: Yes</li> <li className={styles.listEntry}>Mobile: No</li> <li className={styles.listEntry}>Screen-reader: No</li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install @draft-js-plugins/editor" /> <Code code="npm install @draft-js-plugins/static-toolbar" /> <Code code={gettingStarted} name="gettingStarted.js" /> <Heading level={3}>Importing the default styles</Heading> <p> The plugin ships with a default styling available at this location in the installed package: &nbsp; <InlineCode code={ 'node_modules/@draft-js-plugins/static-toolbar/lib/plugin.css' } /> </p> <Heading level={4}>Webpack Usage</Heading> <ul className={styles.list}> <li className={styles.listEntry}> 1. Install Webpack loaders: &nbsp; <InlineCode code={'npm i style-loader css-loader --save-dev'} /> </li> <li className={styles.listEntry}> 2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list. <Code code={webpackConfig} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 3. Add the below import line to your component to tell Webpack to inject the style to your component. <Code code={ "import '@draft-js-plugins/static-toolbar/lib/plugin.css';" } className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}>4. Restart Webpack.</li> </ul> </AlternateContainer> <Container> <Heading level={2}>Simple Static Toolbar Example</Heading> <SimpleToolbarEditor /> <Code code={simpleExampleCode} name="SimpleToolbarEditor.js" /> <Code code={simpleExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Custom Static Toolbar Example</Heading> <CustomToolbarEditor /> <Code code={customExampleCode} name="CustomToolbarEditor.js" /> <Code code={customExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Themed Static Toolbar Example</Heading> <ThemedToolbarEditor /> <Code code={themedExampleCode} name="ThemedToolbarEditor.js" /> <Code code={themedExampleEditorStylesCode} name="editorStyles.css" /> <Code code={themedExampleButtonStylesCode} name="buttonStyles.css" /> <Code code={themedExampleToolbarStylesCode} name="toolbarStyles.css" /> </Container> </PluginPageFrame> ); } }
app/imports/client/Pages/Article/Components/Informations.js
FractalFlows/Emergence
import React from 'react' import { pure } from 'recompose' import { RaisedButton, } from 'material-ui' // Components import { Panel, PanelHeader, PanelBody, PanelHeaderButton, } from '/imports/client/Components/Panel' import KnowledgeBit from '/imports/client/Components/KnowledgeBit' // Helpers import requireLoginAndGoTo from '/imports/client/Utils/requireLoginAndGoTo' function ArticleInformations({ articleSlug, informations, }){ return ( <Panel> <PanelHeader title="Knowledge bits"> <PanelHeaderButton data-name="add-knowledge-btn" onClick={() => requireLoginAndGoTo({ pathname: `/article/information-upsert/${articleSlug}`, state: { modal: true }, })} > Add knowledge product </PanelHeaderButton> </PanelHeader> <PanelBody> {informations.length > 0 ? informations.map((knowledgeBit, i) => <KnowledgeBit key={knowledgeBit.link} knowledgeBit={knowledgeBit} articleSlug={articleSlug} /> ) : <div style={{ textAlign: 'center', }} > <RaisedButton label="Create a new knowledge bit" onClick={() => requireLoginAndGoTo({ pathname: `/article/information-upsert/${articleSlug}`, state: { modal: true }, })} primary /> </div> } </PanelBody> </Panel> ) } export default pure(ArticleInformations)
example/index.android.js
q6112345/react-native-google-place-picker
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import WelcomeScreen from './WelcomeScreen'; AppRegistry.registerComponent('example', () => WelcomeScreen);
modules/IndexRedirect.js
mattkrick/react-router
import React from 'react' import warning from './warning' import invariant from 'invariant' import Redirect from './Redirect' import { falsy } from './PropTypes' const { string, object } = React.PropTypes /** * An <IndexRedirect> is used to redirect from an indexRoute. */ const IndexRedirect = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element) } else { warning( false, 'An <IndexRedirect> does not make sense at the root of your route config' ) } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<IndexRedirect> elements are for router configuration only and should not be rendered' ) } }) export default IndexRedirect
frontend/app_v2/src/components/Alphabet/AlphabetPresentation.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' // FPCC import AlphabetPresentationSelected from 'components/Alphabet/AlphabetPresentationSelected' import SectionTitle from 'components/SectionTitle' function AlphabetPresentation({ characters, selectedData, kids, links, onVideoClick, sitename, videoIsOpen }) { return ( <section className="pt-2 md:pt-4 lg:pt-8 bg-white" data-testid="AlphabetPresentation"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <SectionTitle.Presentation title={'ALPHABET'} accentColor={'primary'} /> {links && ( <div className="flex font-bold items-center justify-center text-center text-primary mb-5"> <ul className="flex text-center"> {links.map(({ url, title }, index) => { return ( <li key={index} className="m-3 inline-flex"> <Link to={url}>{title}</Link> </li> ) })} </ul> </div> )} <div className="mb-5 grid grid-cols-6 sm:grid-cols-8 xl:grid-cols-12 gap-2 max-w-screen-lg mx-auto items-center"> {characters && characters.map(({ title, id }) => { return ( <Link data-testid={selectedData?.title === title ? 'AlphabetPresentation__selectedCharacter' : undefined} className={`border col-span-1 font-medium inline-flex justify-center p-3 sm:p-5 xl:p-3 rounded shadow text-2xl ${ selectedData?.title === title ? 'bg-primary text-white' : '' } `} key={id} to={`/${sitename}/${kids ? 'kids/' : ''}alphabet?char=${title}`} > {title} </Link> ) })} </div> <div className="p-2 pb-4 lg:pb-10"> {selectedData?.title === undefined && ( <div data-testid="AlphabetPresentation__noCharacter" className="text-center font-bold sm:text-3xl text-2xl text-primary m-10" > Please select a character </div> )} {selectedData?.id && ( <AlphabetPresentationSelected selectedData={selectedData} onVideoClick={onVideoClick} videoIsOpen={videoIsOpen} kids={kids} /> )} </div> </div> </section> ) } // PROPTYPES const { bool, array, func, string, shape, arrayOf, object } = PropTypes AlphabetPresentation.propTypes = { characters: arrayOf( shape({ title: string, id: string, relatedAudio: array, relatedLinks: array, relatedPictures: array, relatedVideo: array, relatedWords: array, }) ), selectedData: object, links: array, onVideoClick: func, videoIsOpen: bool, } AlphabetPresentation.defaultProps = { onVideoClick: () => {}, } export default AlphabetPresentation
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
xiaotaijun/actor-platform
import _ from 'lodash'; import Immutable from 'immutable'; import keymirror from 'keymirror'; import React from 'react'; import { Styles, TextField, FlatButton } from 'material-ui'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import ContactStore from 'stores/ContactStore'; import ContactItem from './ContactItem.react'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); const STEPS = keymirror({ NAME_INPUT: null, CONTACTS_SELECTION: null }); class CreateGroupForm extends React.Component { static displayName = 'CreateGroupForm' static childContextTypes = { muiTheme: React.PropTypes.object }; state = { step: STEPS.NAME_INPUT, selectedUserIds: new Immutable.Set() } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7' } }); } render() { let stepForm; switch (this.state.step) { case STEPS.NAME_INPUT: stepForm = ( <form className="group-name" onSubmit={this.onNameSubmit}> <div className="modal-new__body"> <TextField className="login__form__input" floatingLabelText="Group name" fullWidth onChange={this.onNameChange} value={this.state.name}/> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Add members" secondary={true} type="submit"/> </footer> </form> ); break; case STEPS.CONTACTS_SELECTION: let contactList = _.map(ContactStore.getContacts(), (contact, i) => { return ( <ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/> ); }); stepForm = ( <form className="group-members" onSubmit={this.onMembersSubmit}> <div className="count">{this.state.selectedUserIds.size} Members</div> <div className="modal-new__body"> <ul className="contacts__list"> {contactList} </ul> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Create group" secondary={true} type="submit"/> </footer> </form> ); break; } return stepForm; } onContactToggle = (contact, isSelected) => { if (isSelected) { this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)}); } else { this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)}); } } onNameChange = event => { event.preventDefault(); this.setState({name: event.target.value}); } onNameSubmit = event => { event.preventDefault(); if (this.state.name) { let name = this.state.name.trim(); if (name.length > 0) { this.setState({step: STEPS.CONTACTS_SELECTION}); } } } onMembersSubmit =event => { event.preventDefault(); CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS()); } } export default CreateGroupForm;
.storybook/stories/LoadingOverlay.js
derrickpelletier/react-loading-overlay
import React from 'react' import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import styled from 'styled-components' import LoadingOverlay from '../../src/LoadingOverlay.js' const wrapped = ( <div style={{padding: '20px', background: '#FFF'}}> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Justo eget magna fermentum iaculis eu non diam phasellus vestibulum. Eget nunc scelerisque viverra mauris. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Proin sagittis nisl rhoncus mattis rhoncus urna neque viverra. Tincidunt eget nullam non nisi est sit amet facilisis magna. Pharetra vel turpis nunc eget lorem dolor sed viverra. Condimentum mattis pellentesque id nibh tortor id aliquet. Mi sit amet mauris commodo. Vehicula ipsum a arcu cursus. Tortor id aliquet lectus proin nibh nisl. Iaculis eu non diam phasellus vestibulum lorem. Urna et pharetra pharetra massa massa ultricies mi quis. Egestas dui id ornare arcu odio. Morbi quis commodo odio aenean sed adipiscing.</p> <p>In hac habitasse platea dictumst quisque sagittis purus sit amet. Amet mattis vulputate enim nulla aliquet porttitor lacus luctus. Tristique et egestas quis ipsum. Risus pretium quam vulputate dignissim suspendisse in. Eget est lorem ipsum dolor. Cum sociis natoque penatibus et magnis dis. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Elementum pulvinar etiam non quam lacus suspendisse faucibus interdum posuere. Lorem mollis aliquam ut porttitor leo a diam sollicitudin. Porta lorem mollis aliquam ut porttitor leo a diam.</p> </div>) class FadeWrapper extends React.Component { constructor (props) { super(props) this.state = { active: true } } toggleActive = () => { this.setState((prevState) => ({ active: !prevState.active })) } render () { const { active } = this.state return ( <> <button type='button' onClick={this.toggleActive} > turn loader {active ? 'off' : 'on'} </button> <br /> <br /> <LoadingOverlay {...this.props} onClick={action('overlay-click')} active={this.state.active} /> </> ) } } storiesOf('LoadingOverlay', module) .add('no props', () => ( <LoadingOverlay> {wrapped} </LoadingOverlay> )) .add('active with text', () => ( <div> Don't overlay this <LoadingOverlay active text='Loading your fake content...' > {wrapped} </LoadingOverlay> </div> )) .add('with spinner', () => ( <FadeWrapper active spinner > {wrapped} </FadeWrapper> )) .add('No fade', () => ( <div> <FadeWrapper text='No fade when toggled' fadeSpeed={0} > {wrapped} </FadeWrapper> </div> )) .add('with spinner and text', () => ( <FadeWrapper active spinner text='Loading stuff...' > {wrapped} </FadeWrapper> )) .add('with custom spinner', () => ( <FadeWrapper active spinner={<p>FAKE SPINNER</p>} text='Loading stuff...' > {wrapped} </FadeWrapper> )) .add('styles prop', () => ( <FadeWrapper active spinner styles={{ wrapper: (base, props) => ({ ...base, width: 300, height: 200, overflow: props.active ? 'hidden' : 'scroll' }), overlay: (base) => ({ ...base, background: 'rgba(0, 0, 255, 0.5)' }), spinner: (base) => ({ ...base, width: '100px', '& svg circle': { stroke: '#FF0000' } }) }} > {wrapped} </FadeWrapper> )) .add('styled-components (or with classes)', () => { const StyledLoader = styled(FadeWrapper)` width: 250px; height: 400px; overflow: scroll; .myOverlay_overlay { background: rgba(255, 0, 0, 0.5); } &.myOverlay_wrapper--active { overflow: hidden; } ` return ( <StyledLoader classNamePrefix='myOverlay_' active spinner > {wrapped} </StyledLoader> ) })
src/components/Header/Header.js
jhines2k7/react-starter-one
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
ui/src/components/common/Header.js
d3sw/conductor
import React, { Component } from 'react'; import { Link } from 'react-router' import { Navbar, Nav, NavItem, NavDropdown, MenuItem, Input, Button, Tabs, Tab } from 'react-bootstrap'; import http from '../../core/HttpClient'; import d3 from 'd3'; import update from 'react-addons-update'; import { connect } from 'react-redux'; const Header = React.createClass({ getInitialState: function () { return {}; }, render: function () { return ( <div> <header style={{marginLeft: '180px', top: '10px', position: 'fixed'}}> <input type="search" style={{height: '30px', border: 'none'}} placeholder="search"></input> </header> </div> ); } }); export default connect(state => state.workflow)(Header);
client/src/app-components/topic-viewer.js
ivandiazwm/opensupports
import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'lodash'; import classNames from 'classnames'; import {Link} from 'react-router'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import ModalContainer from 'app-components/modal-container'; import TopicEditModal from 'app-components/topic-edit-modal'; import AreYouSure from 'app-components/are-you-sure'; import ArticleAddModal from 'app-components/article-add-modal'; import Icon from 'core-components/icon'; import Button from 'core-components/button'; class TopicViewer extends React.Component { static propTypes = { id: React.PropTypes.number.isRequired, name: React.PropTypes.string.isRequired, icon: React.PropTypes.string.isRequired, iconColor: React.PropTypes.string.isRequired, articles: React.PropTypes.array.isRequired, articlePath: React.PropTypes.string, editable: React.PropTypes.bool, private: React.PropTypes.bool }; static defaultProps = { articlePath: '/admin/panel/articles/view-article/', editable: true }; state = { articles: this.props.articles.sort((a, b) => { return (a.position*1) - (b.position*1); }), currentDraggedId: 0 }; componentWillReceiveProps(nextProps) { this.setState({ articles: nextProps.articles.sort((a, b) => { return (a.position*1) - (b.position*1); }) }); } render() { return ( <div className="topic-viewer"> <div className="topic-viewer__header"> <Icon className="topic-viewer__icon" name={this.props.icon} color={this.props.iconColor}/> <span className="topic-viewer__title">{this.props.name}</span> {(this.props.editable) ? this.renderEditButton() : null} {(this.props.editable) ? this.renderDeleteButton() : null} {this.props.private*1 ? <Icon className="topic-viewer__private" name='user-secret' color='grey'/> : null} </div> <ul className="topic-viewer__list"> {this.state.articles.map(this.renderArticleItem.bind(this))} {(this.props.editable) ? this.renderAddNewArticle() : null} </ul> </div> ); } renderEditButton() { return ( <span onClick={() => {ModalContainer.openModal(this.renderEditModal());}}> <Icon className="topic-viewer__edit-icon" name="pencil" /> </span> ); } renderDeleteButton() { return ( <span onClick={() => AreYouSure.openModal(i18n('DELETE_TOPIC_DESCRIPTION'), this.onDeleteClick.bind(this))}> <Icon className="topic-viewer__edit-icon" name="trash" /> </span> ); } renderArticleItem(article, index) { let props = { className: 'topic-viewer__list-item', key: index, draggable: true }; if(this.props.editable) { _.extend(props, { onDragOver: (this.state.currentDraggedId) ? this.onItemDragOver.bind(this, article, index) : null, onDrop: (this.state.currentDraggedId) ? this.onItemDrop.bind(this, article, index) : null, onDragStart: () => { this.setState({currentDraggedId: article.id}) }, onDragEnd: () => { if(this.state.currentDraggedId) { this.setState({articles: this.props.articles, currentDraggedId: 0}); } } }); } return ( <li {...props}> <Link {...this.getArticleLinkProps(article, index)}> {article.title} </Link> {(this.props.editable) ? <Icon className="topic-viewer__grab-icon" name="arrows" ref={'grab-' + index}/> : null} </li> ); } renderAddNewArticle() { return ( <li className="topic-viewer__list-item"> <Button type="link" className="topic-viewer__add-item" onClick={() => ModalContainer.openModal(this.renderAddNewArticleModal())}> {i18n('ADD_NEW_ARTICLE')} </Button> </li> ); } renderEditModal() { let props = { topicId: this.props.id, onChange: this.props.onChange, defaultValues: { title: this.props.name, icon: this.props.icon, iconColor: this.props.iconColor, private: this.props.private * 1 } }; return ( <TopicEditModal {...props} /> ); } renderAddNewArticleModal() { let props = { topicId: this.props.id, position: this.props.articles.length, onChange: this.props.onChange, topicName: this.props.name }; return ( <ArticleAddModal {...props}/> ); } getArticleLinkProps(article) { let classes = { 'topic-viewer__list-item-button': true, 'topic-viewer__list-item-hidden': article.hidden }; return { className: classNames(classes), to: this.props.articlePath + article.id }; } onDeleteClick() { API.call({ path: '/article/delete-topic', data: { topicId: this.props.id } }).then(this.onChange.bind(this)); } onItemDragOver(article, index, event) { event.preventDefault(); if(!article.hidden) { let articles = []; let draggedId = this.state.currentDraggedId; let draggedIndex = _.findIndex(this.props.articles, {id: draggedId}); _.forEach(this.props.articles, (current, currentIndex) => { if(draggedIndex < index) { if(current.id !== draggedId) { articles.push(current); } if(index === currentIndex) { articles.push({ id: article.id, title: 'X', hidden: true }); } } else { if(index === currentIndex) { articles.push({ id: article.id, title: 'X', hidden: true }); } if(current.id !== draggedId) { articles.push(current); } } }); this.setState({articles}); } } onItemDrop(article, index, event) { event.stopPropagation(); event.preventDefault(); let articles = []; let draggedId = this.state.currentDraggedId; let dragged = _.find(this.props.articles, {id: draggedId}); let draggedIndex = _.findIndex(this.props.articles, {id: draggedId}); _.forEach(this.props.articles, (current) => { if(current.id !== draggedId) { if(draggedIndex < index) { articles.push(current); if(current.id === article.id) { articles.push(dragged); } } else { if(current.id === article.id) { articles.push(dragged); } articles.push(current); } } }); if(draggedIndex === index) { this.setState({articles: this.props.articles, currentDraggedId: 0}); } else { this.updatePositions(articles.map((article) => article.id)); this.setState({articles, currentDraggedId: 0}, this.onChange.bind(this)); } } updatePositions(positions) { _.forEach(positions, (id, index) => { if(this.props.articles[index].id !== id) { API.call({ path: '/article/edit', data: { articleId: id, position: index + 1 } }); } }); } onChange() { if(this.props.onChange) { this.props.onChange(); } } } export default TopicViewer;
src/parser/paladin/holy/modules/beacons/DirectBeaconHealing.js
sMteX/WoWAnalyzer
import React from 'react'; import { Trans } from '@lingui/macro'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import Statistic from 'interface/statistics/Statistic'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import UpArrowIcon from 'interface/icons/UpArrow'; import PlusIcon from 'interface/icons/Plus'; import Analyzer from 'parser/core/Analyzer'; import Abilities from '../Abilities'; import PaladinAbilityTracker from '../core/PaladinAbilityTracker'; import { BEACON_TRANSFERING_ABILITIES } from '../../constants'; class DirectBeaconHealing extends Analyzer { static dependencies = { abilityTracker: PaladinAbilityTracker, abilities: Abilities, }; get beaconTransferingAbilities() { return this.abilities.activeAbilities .filter(ability => BEACON_TRANSFERING_ABILITIES[ability.spell.id] !== undefined); } get totalFoLHLOnBeaconPercentage() { const abilityTracker = this.abilityTracker; const getCastCount = spellId => abilityTracker.getAbility(spellId); let casts = 0; let castsOnBeacon = 0; this.beaconTransferingAbilities .filter(ability => [SPELLS.FLASH_OF_LIGHT.id, SPELLS.HOLY_LIGHT.id].includes(ability.spell.id)) .forEach(ability => { const castCount = getCastCount(ability.spell.id); casts += castCount.healingHits || 0; castsOnBeacon += castCount.healingBeaconHits || 0; }); return castsOnBeacon / casts; } get totalOtherSpellsOnBeaconPercentage() { const abilityTracker = this.abilityTracker; const getCastCount = spellId => abilityTracker.getAbility(spellId); let casts = 0; let castsOnBeacon = 0; this.beaconTransferingAbilities .filter(ability => ![SPELLS.FLASH_OF_LIGHT.id, SPELLS.HOLY_LIGHT.id].includes(ability.spell.id)) .forEach(ability => { const castCount = getCastCount(ability.spell.id); casts += castCount.healingHits || 0; castsOnBeacon += castCount.healingBeaconHits || 0; }); return castsOnBeacon / casts; } get totalHealsOnBeaconPercentage() { const abilityTracker = this.abilityTracker; const getCastCount = spellId => abilityTracker.getAbility(spellId); let casts = 0; let castsOnBeacon = 0; this.beaconTransferingAbilities.forEach(ability => { const castCount = getCastCount(ability.spell.id); casts += castCount.healingHits || 0; castsOnBeacon += castCount.healingBeaconHits || 0; }); return castsOnBeacon / casts; } get suggestionThresholds() { return { actual: this.totalHealsOnBeaconPercentage, isGreaterThan: { minor: 0.2, average: 0.25, major: 0.35, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds.actual).isGreaterThan(this.suggestionThresholds.isGreaterThan.minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<Trans>You cast a lot of direct heals on beacon targets. Direct healing beacon targets is inefficient. Try to only cast on beacon targets when they would otherwise die.</Trans>) .icon('ability_paladin_beaconoflight') .actual(<Trans>{formatPercentage(actual)}% of all your healing spell casts were on a beacon target</Trans>) .recommended(<Trans>&lt;{formatPercentage(recommended)}% is recommended</Trans>) .regular(this.suggestionThresholds.isGreaterThan.average).major(this.suggestionThresholds.isGreaterThan.major); }); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(50)} size="small" > <div className="pad"> <div className="pull-right"> <PlusIcon />{' '} <UpArrowIcon style={{ transform: 'rotate(90deg)' }} />{' '} <SpellIcon id={SPELLS.BEACON_OF_LIGHT_CAST_AND_BUFF.id} /> </div> <label><Trans>Direct beacon healing</Trans></label> <div className="flex" style={{ marginTop: -10 }}> <div className="flex-main value" style={{ marginRight: 15 }}> {formatPercentage(this.totalHealsOnBeaconPercentage, 0)}% </div> <div className="flex-main"> <div className="flex pull-right text-center" style={{ whiteSpace: 'nowrap' }}> <div className="flex-main" style={{ marginRight: 15 }}> <small><Trans>HL/FoL</Trans></small> <div className="value" style={{ fontSize: '1em' }}>{formatPercentage(this.totalFoLHLOnBeaconPercentage, 0)}%</div> </div> <div className="flex-main"> <small><Trans>Other spells</Trans></small> <div className="value" style={{ fontSize: '1em' }}>{formatPercentage(this.totalOtherSpellsOnBeaconPercentage, 0)}%</div> </div> </div> </div> </div> </div> </Statistic> ); } } export default DirectBeaconHealing;
src/js/component/Clickable.js
drexelieee/dragonhacks
import 'css/Clickable.css'; import React, { Component } from 'react'; import classNames from 'classnames'; export default class Clickable extends Component { render() { let rootClasses = classNames('clickable', { 'clickable--border': this.props.border, 'clickable--link': this.props.link, 'clickable--nav-link': this.props.navLink, }); return ( <a className={rootClasses} href={this.props.href} onClick={this.props.onClick}> {this.props.children} </a> ); } }
packages/lore-react-forms-material-ui/src/fields/custom.js
lore/lore-forms
import React from 'react'; import _ from 'lodash'; import { Field } from 'lore-react-forms'; export default function(form, props, name) { return ( <Field name={name}> {(field) => { return props.render(field, props); }} </Field> ); }
pootle/static/js/shared/components/FormSelectInput.js
evernote/zing
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import Select from 'react-select'; const FormSelectInput = React.createClass({ propTypes: { handleChange: React.PropTypes.func.isRequired, multiple: React.PropTypes.bool, name: React.PropTypes.string.isRequired, options: React.PropTypes.array.isRequired, value: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.number, React.PropTypes.string, React.PropTypes.array, ]).isRequired, }, handleChange(value) { const newValue = this.props.multiple ? value.split(',') : value; this.props.handleChange(this.props.name, newValue); }, render() { const { value } = this.props; /* FIXME: react-select#25 prevents using non-string values */ const selectValue = this.props.multiple ? value : value.toString(); return ( <Select clearAllText={gettext('Clear all')} clearValueText={gettext('Clear value')} noResultsText={gettext('No results found')} onChange={this.handleChange} placeholder={gettext('Select...')} searchPromptText={gettext('Type to search')} {...this.props} multi={this.props.multiple} value={selectValue} /> ); }, }); export default FormSelectInput;
web/src/SuggestTweets.js
remeh/smartwitter
import React, { Component } from 'react'; import { Button, Container, Divider, Tab, } from 'semantic-ui-react' import XHR from './xhr.js'; import TweetCard from './TweetCard.js'; import './App.css'; class SuggestTweets extends Component { constructor(props) { super(props); this.refreshTimeout = null; this.state = { tabs: [], } this.fetchKeywords(); } fetchKeywords() { XHR.getJson( XHR.domain + '/api/1.0/keywords', ).then((json) => { let tabs = []; for (let i = 0; i < json.length; i++) { tabs.push({ menuItem: json[i].label, render: () => <Tweets p={i} /> }); } tabs.push(this.addTab()); this.setState({tabs: tabs}); }).catch((response) => { // TODO(remy): error? }); } addTab() { return { menuItem: { key: 'Add', icon: 'add', content: '' }, render: <div />, }; } render() { return ( <Container style={{marginTop: '1em'}}> <Tab panes={this.state.tabs} /> </Container> ); } } class Tweets extends Component { constructor(props) { super(props); this.refreshTimeout = null; this.state = { tweets: [], p: this.props.p, loading: false, reloadDisabled: true, } setTimeout(() => { this.setState({ reloadDisabled: false, }); }, 5000); this.fetch(); } reload = () => { this.setState({ reloadDisabled: true, }); this.fetch(); } fetch = () => { var params = { p: this.state.p, }; setTimeout(() => { this.setState({ reloadDisabled: false, }); }, 5000); XHR.getJson( XHR.domain + '/api/1.0/suggest', params, ).then((json) => { this.setState({ tweets: json, loading: false, }); }).catch((response) => { this.setState({ reloadDisabled: false, loading: false, }); }); } render() { return ( <Tab.Pane> <Button disabled={this.state.reloadDisabled} onClick={this.reload} icon='refresh' primary content='Reload' /> <Button icon='edit' content='Configure keywords' /> <Divider /> <Container> {this.state.tweets.map( (tweet) => <div key={tweet.uid}> <TweetCard reload={this.fetch} name={tweet.name} screen_name={tweet.screen_name} avatar={tweet.avatar} time={tweet.time} tweet_id={tweet.tweet_id} text={tweet.text} entities={tweet.entities} link={tweet.link} retweeted={tweet.retweeted} liked={tweet.liked} like_count={tweet.like_count} retweet_count={tweet.retweet_count} /> <Divider /> </div> )} </Container> </Tab.Pane> ); } }; export default SuggestTweets;
examples/HighstockPlotBands/index.js
AlexMayants/react-jsx-highcharts
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.getElementById('root') );
examples/01 Dustbin/Restaurant Host/index.js
tylercollier/react-dnd-demo
import React, { Component } from 'react'; import Container from './Container'; export default class RestaurantHost extends Component { render() { return ( <div> <p> <b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/01%20Dustbin/Multiple%20Targets'>Browse the Source</a></b> </p> <p> Custom example for Tyler's presentation </p> <p> It shows off an async drop process. </p> <Container /> </div> ); } }
src/pages/SettingPage.js
LinDing/two-life
import React, { Component } from 'react'; import { StyleSheet, Navigator, Dimensions, TouchableOpacity, AlertIOS, Alert, AsyncStorage, Modal, TextInput, TouchableHighlight } from 'react-native'; import { createAnimatableComponent, View, Text } from 'react-native-animatable'; import CommonNav from '../common/CommonNav'; import RightButtonNav from '../common/RightButtonNav'; import TextPingFang from '../common/TextPingFang'; import {HOST, QINIU_UPHOST} from '../util/config'; import HttpUtils from '../util/HttpUtils'; import Platform from 'Platform'; import AlertBox from '../common/AlertBox'; import InputBox from '../common/InputBox'; import ImageCropPicker from 'react-native-image-crop-picker'; import ImagePicker from 'react-native-image-picker'; import ImageResizer from 'react-native-image-resizer'; import Image from 'react-native-image-progress'; import * as Progress from 'react-native-progress'; const WIDTH = Dimensions.get("window").width; const INNERWIDTH = WIDTH - 16; const HEIGHT = Dimensions.get("window").height; const URL1 = HOST + 'users/update'; const URL2 = HOST + 'users/close_connect'; const URL_TOKEN = HOST + "util/qiniu_token";//qiniu_token export default class SettingPage extends Component { static defaultProps = {} constructor(props) { super(props); this.state = { user_sex: this.props.user.user_sex, user_name: this.props.user.user_name, user_state: this.props.user.user_other_id, isDialogVisible: false, isInputVisible: false, data: {}, file:{}, upload: 0, user_face: this.props.user.user_face }; } showInput(){ this.setState({isInputVisible:true}); } hideInput(){ this.setState({isInputVisible:false}); } onPost() { var user_face = this.state.user_face if (this.state.upload !== 0) { user_face = 'https://airing.ursb.me/' + this.state.file.name + '-avatar.jpg' } console.log('user_face:' + user_face) HttpUtils.post(URL1, { uid: this.props.user.uid, timestamp: this.props.user.timestamp, token: this.props.user.token, user_name: this.state.user_name, user_sex: this.state.user_sex, user_face: user_face, }).then((res)=> { if (res.status == 0) { this.showDialog() this.setState({ data: { user_name: this.state.user_name, user_sex: this.state.user_sex, user_other_id: this.state.user_state, user_face: user_face } }) } }).catch((error)=> { console.log(error); }) } resizeFile(file, complete) { if(!file.name) { Alert.alert("小提示","图片没有名称哦~"); return ; } if(!file.uri) { Alert.alert("小提示","图片没有内容哦~"); return ; } ImageResizer.createResizedImage(file.uri, file.width, file.height, 'JPEG', 80) .then((resizedImageUri) => { file.resizedUri = resizedImageUri; complete(file); }).catch((err) => { Alert.alert("小提示","压缩图片失败哦~"); return ; }); } uploadFile(file, complete) { if(!file.name) { Alert.alert("小提示","图片没有名称哦~"); return ; } if(!file.uri) { Alert.alert("小提示","图片没有内容哦~"); return ; } HttpUtils.post(URL_TOKEN,{ token: this.props.user.token, uid: this.props.user.uid, timestamp: this.props.timestamp, filename: file.name//"image/twolife/" + this.state.file.name, }).then((response)=>{ if(response.status== 0) { file.token = response.qiniu_token; var formData = new FormData(); formData.append('file', {uri: file.resizedUri, type:'application/octet-stream', name: file.name}); formData.append('key', file.name); formData.append('token', file.token); return fetch(QINIU_UPHOST, { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/octet-stream' }, body: formData }).then((response) => { this.state.upload = 1; complete(); }).catch((error) => { Alert.alert("小提示", '网络故障:('); }); } }).catch((error)=>{ Alert.alert("小提示", '网络故障:('); }) } changeName() { if(Platform.OS === 'ios'){ AlertIOS.prompt('请输入新的昵称','',[ {text:'取消', onPress:this.userCanceled}, {text:'确定', onPress:(name)=>{this.setState({user_name: name})}} ]); // this.showInput() } else { Alert.alert('小提醒', '对不起,安卓用户暂时不支持更改昵称。。'); } } showDialog(){ this.setState({isDialogVisible:true}); } hideDialog(){ this.setState({isDialogVisible:false}); } changeSex() { Alert.alert('是否更改性别?','',[ {text:'取消', onPress:this.userCanceled}, {text:'确定', onPress:(sex)=>{ this.state.user_sex == 1? this.setState({user_sex: 0}):this.setState({user_sex: 1}) }}]) } changeConnectState() { Alert.alert('是否关闭匹配功能?如果关闭,任何人都将无法再匹配到您,并会断绝现有契约。','',[ {text:'取消', onPress:this.userCanceled}, {text:'确定', onPress:(user_state)=>{ if(this.state.user_state !== -404) { HttpUtils.post(URL2, { uid: this.props.user.uid, token: this.props.user.token, timestamp: this.props.user.timestamp, user_other_id: this.state.user_state }).then((res)=>{ if (res.status == 0) { this.setState({user_state: -404}); Alert.alert('小提醒', '您已成功关闭了匹配功能'); let data = { user_name: this.state.user_name, user_sex: this.state.user_sex, user_other_id: this.state.user_state } this.props.onCallBack(data); } else { Alert.alert('小提醒', '网络故障QAQ'); } }) } else { Alert.alert('小提醒', '您已成功开启了匹配功能,快去寻找另一半吧!'); this.setState({user_state: -1}) let data = { user_name: this.state.user_name, user_sex: this.state.user_sex, user_other_id: this.state.user_state } this.props.onCallBack(data); } }}]) } render() { var options = { title: '选择头像', customButtons: [ ], storageOptions: { skipBackup: true, path: 'images' } }; var avatar = null; if (this.state.file.uri) { avatar = <Image style={styles.avatar} source={{uri:this.state.file.uri}} indicator={Progress.Circle} indicatorProps={{indeterminate:true, progress:0.5}}/> } else { avatar = <Image style={styles.avatar} source={{uri:this.props.user.user_face}} indicator={Progress.Circle}/> } return ( <View style={styles.container}> <AlertBox _dialogVisible={this.state.isDialogVisible} _dialogRightBtnAction={()=> { this.props.onCallBack(this.state.data); this.props.navigator.pop(); }} _dialogContent={'个人信息更改成功'} /> <Image style={styles.bg} source={this.state.user_sex==0?require("../../res/images/about_bg.png"):require("../../res/images/about_bg1.png")}> <RightButtonNav title={"设置"} navigator={this.props.navigator} rightOnPress={()=>{ this.onPost(); }} /> <TouchableOpacity onPress={()=>{ ImageCropPicker.openPicker({ width: 400, height: 400, cropping: true }).then(response => { console.log(response) let file = { uri: response.path, height:response.height, width:response.width, name: 'image/twolife/' + this.props.user.uid + '/' + response.path.substr(response.path.length-12) }; console.log(file) this.setState({ file: file }) if (this.state.file.uri) { this.resizeFile(this.state.file, ()=>{ this.uploadFile(this.state.file, ()=>{ console.log('uploadFile success'); }) }); } }); }}> <Image style={styles.avatar_round} source={require("../../res/images/avatar_round.png")}> {avatar} </Image> </TouchableOpacity> <TextPingFang style={styles.avatar_font}>{this.props.user.user_code}</TextPingFang> </Image> <TouchableOpacity onPress={()=>{ this.changeName(); }}> <View style={styles.online_name} delay={100} animation="bounceInRight"> <Text style={styles.online_font}> {this.state.user_name} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={()=>{ this.changeSex(); }}> <View style={styles.online_sex} delay={150} animation="bounceInRight"> <Text style={styles.online_font}> {this.state.user_sex==0?'男':'女'} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={()=>{ this.changeConnectState(); }}> <View style={styles.online_state} delay={200} animation="bounceInRight"> <Text style={styles.online_font}> {this.state.user_state==-404?'拒绝任何匹配':'开放匹配'} </Text> </View> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { height: HEIGHT, width: WIDTH, alignItems: 'center', backgroundColor: "rgb(242,246,250)" }, bg: { width: WIDTH, alignItems: 'center', }, opacity0:{ backgroundColor: "rgba(0,0,0,0)" }, avatar_round: { justifyContent: 'center', alignItems: 'center', marginTop: 48 }, avatar: { width: 55 / 375 * WIDTH, height: 55 / 667 * HEIGHT, borderRadius: 27.5 / 667 * HEIGHT }, avatar_font: { color:"#666666", fontSize:17, backgroundColor:"rgba(0,0,0,0)", marginTop:15, fontWeight:"600" }, online_name: { marginTop: 52, backgroundColor: "white", alignItems: "center", justifyContent: "center", width: 150 / 375 * WIDTH, height: 44 / 667 * HEIGHT, borderRadius: 22 / 667 * HEIGHT }, online_sex:{ marginTop: 20, backgroundColor: "white", alignItems: "center", justifyContent: "center", width: 150 / 375 * WIDTH, height: 44 / 667 * HEIGHT, borderRadius: 22 / 667 * HEIGHT }, online_state:{ marginTop: 20, backgroundColor: "white", alignItems: "center", justifyContent: "center", width: 150 / 375 * WIDTH, height: 44 / 667 * HEIGHT, borderRadius: 22 / 667 * HEIGHT }, online_font: { fontSize: 14, fontWeight: "600", color: "#666666", } });
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
ebihara99999/mastodon
import React from 'react'; import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' }, emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' }, people: { id: 'emoji_button.people', defaultMessage: 'People' }, nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' }, food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' }, activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' }, travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' }, objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' }, symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' }, flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' }, }); const settings = { imageType: 'png', sprites: false, imagePathPNG: '/emoji/', }; let EmojiPicker; // load asynchronously class EmojiPickerDropdown extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, onPickEmoji: PropTypes.func.isRequired, }; state = { active: false, loading: false, }; setRef = (c) => { this.dropdown = c; } handleChange = (data) => { this.dropdown.hide(); this.props.onPickEmoji(data); } onShowDropdown = () => { this.setState({active: true}); if (!EmojiPicker) { this.setState({loading: true}); import(/* webpackChunkName: "emojione_picker" */ 'emojione-picker').then(TheEmojiPicker => { EmojiPicker = TheEmojiPicker.default; this.setState({loading: false}); }).catch(err => { // TODO: show the user an error? this.setState({loading: false}); }); } } onHideDropdown = () => { this.setState({active: false}); } render () { const { intl } = this.props; const categories = { people: { title: intl.formatMessage(messages.people), emoji: 'smile', }, nature: { title: intl.formatMessage(messages.nature), emoji: 'hamster', }, food: { title: intl.formatMessage(messages.food), emoji: 'pizza', }, activity: { title: intl.formatMessage(messages.activity), emoji: 'soccer', }, travel: { title: intl.formatMessage(messages.travel), emoji: 'earth_americas', }, objects: { title: intl.formatMessage(messages.objects), emoji: 'bulb', }, symbols: { title: intl.formatMessage(messages.symbols), emoji: 'clock9', }, flags: { title: intl.formatMessage(messages.flags), emoji: 'flag_gb', }, }; const { active, loading } = this.state; return ( <Dropdown ref={this.setRef} className='emoji-picker__dropdown' onShow={this.onShowDropdown} onHide={this.onHideDropdown}> <DropdownTrigger className='emoji-button' title={intl.formatMessage(messages.emoji)}> <img draggable="false" className={`emojione ${active && loading ? "pulse-loading" : ''}`} alt="🙂" src="/emoji/1f602.svg" /> </DropdownTrigger> <DropdownContent className='dropdown__left'> { this.state.active && !this.state.loading && (<EmojiPicker emojione={settings} onChange={this.handleChange} searchPlaceholder={intl.formatMessage(messages.emoji_search)} categories={categories} search={true} />) } </DropdownContent> </Dropdown> ); } } export default injectIntl(EmojiPickerDropdown);
app/javascript/mastodon/components/column_back_button.js
MastodonCloud/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class ColumnBackButton extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } render () { return ( <button onClick={this.handleClick} className='column-back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); } }
App/Components/ListItem.js
bretth18/bison
import { View, Text, TouchableHighlight, StyleSheet} from 'react-native'; import React, { Component } from 'react'; import moment from 'moment'; import { Icon } from 'native-base'; import { Card, CardImage, CardTitle, CardContent, CardAction } from 'react-native-card-view'; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'flex-start', backgroundColor: '#F5FCFF', margin: 5 }, card: { backgroundColor: "#fff", borderRadius: 2, shadowColor: "#000000", shadowOpacity: 0.3, shadowRadius: 1, shadowOffset: { height: 1, width: 0.3, } }, cardImage: { flex: 1 }, cardTitle: { flex: 1, flexDirection: 'row', paddingTop: 1, paddingBottom: 1, }, cardContent: { paddingRight: 16, paddingLeft: 16, paddingTop: 1, paddingBottom: 1, }, cardAction: { margin: 8, flexDirection: 'row', alignItems: 'center', }, separator: { flex: 1, height: 1, backgroundColor: '#E9E9E9' } }); class ListItem extends Component { setNativeProps (nativeProps) { this._root.setNativeProps(nativeProps); } render(){ var displayTime = moment(this.props.item.time).format('dddd, MMMM Do YYYY, h:mm:ss a'); // console.log('ListItem props:'); // console.log(this.props); return( <TouchableHighlight onPress={this.props.onPress}> <View style={[styles.container, styles.card,]}> <CardTitle> <Text >{this.props.item.title}</Text> </CardTitle> <CardContent> <Text >{displayTime}</Text> <Text >{this.props.item.score}pts</Text> </CardContent> <CardContent style={{flexDirection:'flex-end'}}> <Icon name='ios-more' style={{alignItems:'flex-end', color:'black'}} /> </CardContent> </View> </TouchableHighlight> ); } } module.exports = ListItem;
client/login.js
BillZito/greenfield
import React from 'react'; import { StyleSheet, Text, View, Image, AlertIOS, AsyncStorage } from 'react-native'; import { Font } from 'exponent'; import { Container, Header, Title, Content, Footer, Button, List, ListItem, Input, InputGroup } from 'native-base'; import { Ionicons } from '@exponent/vector-icons'; var STORAGE_KEY = 'id_token'; export default class Login extends React.Component { constructor(props) { super(props); this.state = { fontLoaded: false, username: '', password: '' } } async componentDidMount() { await Font.loadAsync({ 'pacifico': require('./assets/fonts/Pacifico.ttf'), 'montserrat': require('./assets/fonts/Montserrat-Regular.ttf') }); this.setState({ fontLoaded: true }); } _navigate(username) { this.props.navigator.push({ name: 'Homescreen', passProps: { 'username': username } }) } async _onValueChange(item, selectedValue) { try { await AsyncStorage.setItem(item, selectedValue); console.log('token saved!'); } catch (error) { console.log('AsyncStorage error: ' + error.message); } } login() { var context = this; if (this.state.username && this.state.password) { fetch('https://invalid-memories-greenfield.herokuapp.com/api/users/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.username, password: this.state.password }) }) .then(function(response) { var username = context.state.username; context.clearInput(); if (response.status === 201) { var token = JSON.parse(response._bodyText).id_token; return context._onValueChange(STORAGE_KEY, token) .then(function() { context._navigate(username); }); } else { AlertIOS.alert('Invalid username/password.'); } }); } else { AlertIOS.alert('Username and password required.'); } } signup() { var context = this; if (this.state.username && this.state.password) { fetch('https://invalid-memories-greenfield.herokuapp.com/api/users/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.username, password: this.state.password }) }) .then(function(response) { var username = context.state.username; context.clearInput(); if (response.status === 201) { var token = JSON.parse(response._bodyText).id_token; return context._onValueChange(STORAGE_KEY, token) .then(function() { context._navigate(username); }); } else { AlertIOS.alert('Username already exists.'); } }); } else { AlertIOS.alert('Username and password required.'); } } clearInput() { this.setState({username: '', password: ''}); } render() { return ( <Container> <View style={styles.backgroundImageWrapper}> <Image source={require('./assets/images/london.jpg')} style={styles.backgroundImage} /> </View> <View style={styles.container}> { this.state.fontLoaded ? ( <View> <View style={styles.title}> <Text style={styles.titleText}>TagMe</Text> </View> <View style={styles.subtitle}> <Text style={styles.subtitleText}>photo</Text> <Text style={styles.subtitleText}>tagging</Text> <Text style={styles.subtitleText}>power</Text> </View> </View> ) : null } <List style={{marginRight:20}}> <ListItem> <InputGroup> <Input placeholder='USERNAME' placeholderTextColor='#444' onChangeText={(text) => this.setState({username: text})} value={this.state.username} style={styles.formText} /> </InputGroup> </ListItem> <ListItem> <InputGroup> <Input placeholder='PASSWORD' placeholderTextColor='#444' secureTextEntry={true} onChangeText={(text) => this.setState({password: text})} value={this.state.password} style={styles.formText} /> </InputGroup> </ListItem> </List> { this.state.fontLoaded ? ( <View style={styles.buttonsContainer}> <Button primary style={styles.button} onPress={this.login.bind(this)}> <Text style={styles.buttonText}> Login <Ionicons name="ios-log-in" size={23} color="white" /> </Text> </Button> <Button primary style={styles.button} onPress={this.signup.bind(this)}> <Text style={styles.buttonText}> Signup <Ionicons name="ios-person-add-outline" size={25} color="white" /> </Text> </Button> </View> ) : null } </View> </Container> ); } } const styles = StyleSheet.create({ backgroundImageWrapper: { position: 'absolute', alignItems: 'center' }, backgroundImage: { flex: 1, resizeMode: 'stretch' }, container: { flex: 1, }, buttonsContainer: { flexDirection: 'row', marginTop: 50, justifyContent: 'center', alignItems: 'center' }, title: { marginTop: 100, marginBottom: 10, alignItems: 'center' }, titleText: { ...Font.style('pacifico'), color: '#f6755e', fontSize: 80 }, subtitle: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 40 }, subtitleText: { color: '#25a2c3', fontSize: 16, textAlign: 'center', height: 30, borderColor: '#aaa', borderRadius: 15, borderWidth: 1, paddingTop: 5, paddingRight: 8, paddingLeft: 8, marginRight: 3, marginLeft: 3 }, formText: { fontSize: 17, color: '#333' }, button: { backgroundColor: '#f6755e', height: 45, width: 100, marginRight: 10, marginLeft: 10 }, buttonText: { ...Font.style('montserrat'), color: '#fff', fontSize: 18, marginBottom: 5 } });
examples/js/custom/csv-button/fully-custom-csv-button.js
echaouchna/react-bootstrap-tab
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn, InsertButton } 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); export default class FullyCustomInsertButtonTable extends React.Component { createCustomExportCSVButton = (onClick) => { return ( <button style={ { color: 'red' } } onClick={ onClick }>Custom Export CSV Btn</button> ); } render() { const options = { exportCSVBtn: this.createCustomExportCSVButton }; return ( <BootstrapTable data={ products } options={ options } exportCSV> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
examples/js/pagination/custom-pagination-table.js
pvoznyuk/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(100); export default class CustomPaginationTable extends React.Component { render() { const options = { page: 2, // which page you want to show as default sizePerPageList: [ 5, 10 ], // you can change the dropdown list for size per page sizePerPage: 5, // which size per page you want to locate as default paginationSize: 3, // the pagination bar size. prePage: 'Prev', // Previous page button text nextPage: 'Next', // Next page button text firstPage: 'First', // First page button text lastPage: 'Last' // Last page button text }; return ( <BootstrapTable data={ products } pagination={ true } options={ options }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
classic/src/scenes/mailboxes/src/Components/Backed/ServiceAvatar.js
wavebox/waveboxapp
import React from 'react' import PropTypes from 'prop-types' import { accountStore } from 'stores/account' import shallowCompare from 'react-addons-shallow-compare' import Resolver from 'Runtime/Resolver' import ACAvatarCircle2 from 'wbui/ACAvatarCircle2' export default class ServiceAvatar extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { serviceId: PropTypes.string.isRequired } /* **************************************************************************/ // Component Lifecycle /* **************************************************************************/ componentDidMount () { accountStore.listen(this.accountChanged) } componentWillUnmount () { accountStore.unlisten(this.accountChanged) } componentWillReceiveProps (nextProps) { if (this.props.serviceId !== nextProps.serviceId) { this.setState({ avatar: accountStore.getState().getServiceAvatarConfig(nextProps.serviceId) }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { return { avatar: accountStore.getState().getServiceAvatarConfig(this.props.serviceId) } })() accountChanged = (accountState) => { this.setState({ avatar: accountState.getServiceAvatarConfig(this.props.serviceId) }) } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { serviceId, ...passProps } = this.props const { avatar } = this.state return ( <ACAvatarCircle2 avatar={avatar} resolver={(i) => Resolver.image(i)} {...passProps} /> ) } }
packages/react-art/src/ReactART.js
VioletLife/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactVersion from 'shared/ReactVersion'; import {LegacyRoot} from 'shared/ReactRootTags'; import { createContainer, updateContainer, injectIntoDevTools, } from 'react-reconciler/inline.art'; import Transform from 'art/core/transform'; import Mode from 'art/modes/current'; import FastNoSideEffects from 'art/modes/fast-noSideEffects'; import {TYPES, childrenAsString} from './ReactARTInternals'; Mode.setCurrent( // Change to 'art/modes/dom' for easier debugging via SVG FastNoSideEffects, ); /** Declarative fill-type objects; API design not finalized */ const slice = Array.prototype.slice; class LinearGradient { constructor(stops, x1, y1, x2, y2) { this._args = slice.call(arguments); } applyFill(node) { node.fillLinear.apply(node, this._args); } } class RadialGradient { constructor(stops, fx, fy, rx, ry, cx, cy) { this._args = slice.call(arguments); } applyFill(node) { node.fillRadial.apply(node, this._args); } } class Pattern { constructor(url, width, height, left, top) { this._args = slice.call(arguments); } applyFill(node) { node.fillImage.apply(node, this._args); } } /** React Components */ class Surface extends React.Component { componentDidMount() { const {height, width} = this.props; this._surface = Mode.Surface(+width, +height, this._tagRef); this._mountNode = createContainer(this._surface, LegacyRoot, false); updateContainer(this.props.children, this._mountNode, this); } componentDidUpdate(prevProps, prevState) { const props = this.props; if (props.height !== prevProps.height || props.width !== prevProps.width) { this._surface.resize(+props.width, +props.height); } updateContainer(this.props.children, this._mountNode, this); if (this._surface.render) { this._surface.render(); } } componentWillUnmount() { updateContainer(null, this._mountNode, this); } render() { // This is going to be a placeholder because we don't know what it will // actually resolve to because ART may render canvas, vml or svg tags here. // We only allow a subset of properties since others might conflict with // ART's properties. const props = this.props; // TODO: ART's Canvas Mode overrides surface title and cursor const Tag = Mode.Surface.tagName; return ( <Tag ref={ref => (this._tagRef = ref)} accessKey={props.accessKey} className={props.className} draggable={props.draggable} role={props.role} style={props.style} tabIndex={props.tabIndex} title={props.title} /> ); } } class Text extends React.Component { constructor(props) { super(props); // We allow reading these props. Ideally we could expose the Text node as // ref directly. ['height', 'width', 'x', 'y'].forEach(key => { Object.defineProperty(this, key, { get: function() { return this._text ? this._text[key] : undefined; }, }); }); } render() { // This means you can't have children that render into strings... const T = TYPES.TEXT; return ( <T {...this.props} ref={t => (this._text = t)}> {childrenAsString(this.props.children)} </T> ); } } injectIntoDevTools({ findFiberByHostInstance: () => null, bundleType: __DEV__ ? 1 : 0, version: ReactVersion, rendererPackageName: 'react-art', }); /** API */ export const ClippingRectangle = TYPES.CLIPPING_RECTANGLE; export const Group = TYPES.GROUP; export const Shape = TYPES.SHAPE; export const Path = Mode.Path; export {LinearGradient, Pattern, RadialGradient, Surface, Text, Transform};
src/svg-icons/action/settings-input-component.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputComponent = (props) => ( <SvgIcon {...props}> <path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/> </SvgIcon> ); ActionSettingsInputComponent = pure(ActionSettingsInputComponent); ActionSettingsInputComponent.displayName = 'ActionSettingsInputComponent'; ActionSettingsInputComponent.muiName = 'SvgIcon'; export default ActionSettingsInputComponent;
src/components/Header.js
ecovirtual/dclv-calculator
import React from 'react'; import { Link } from 'react-router'; import { Menu } from 'semantic-ui-react'; const Header = () => { return ( <Menu> <Menu.Item as={Link} to="/" name="inicio" content="Inicio" /> <Menu.Item as={Link} to="/about" name="about" content="Descripción del Proyecto" /> </Menu> ); }; export default Header;
docs/src/Root.js
laran/react-bootstrap
import React from 'react'; import Router from 'react-router'; const Root = React.createClass({ statics: { /** * Get the list of pages that are renderable * * @returns {Array} */ getPages() { return [ 'index.html', 'introduction.html', 'getting-started.html', 'components.html', 'support.html' ]; } }, getDefaultProps() { return { assetBaseUrl: '' }; }, childContextTypes: { metadata: React.PropTypes.object }, getChildContext() { return { metadata: this.props.propData }; }, render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. let browserInitScriptObj = { __html: `window.INITIAL_PROPS = ${JSON.stringify(this.props)}; // console noop shim for IE8/9 (function (w) { var noop = function () {}; if (!w.console) { w.console = {}; ['log', 'info', 'warn', 'error'].forEach(function (method) { w.console[method] = noop; }); } }(window));` }; let head = { __html: `<title>React-Bootstrap</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet"> <link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> <Router.RouteHandler propData={this.props.propData} /> <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={`${this.props.assetBaseUrl}/assets/bundle.js`} /> </body> </html> ); } }); export default Root;
application/components/calendar/Calendar.js
buildreactnative/assemblies-tutorial
import moment from 'moment'; import Icon from 'react-native-vector-icons/Ionicons'; import NavigationBar from 'react-native-navbar'; import React, { Component } from 'react'; import { View, Text, ListView, TouchableOpacity } from 'react-native'; import { uniq, flatten, find } from 'underscore'; import { getSectionData, getRowData, sectionHeaderHasChanged, rowHasChanged } from '../../utilities'; import Loading from '../shared/Loading'; import { globals, calendarStyles } from '../../styles'; const styles = calendarStyles; const EmptyList = ({ ready }) => { if (! ready ) { return <Loading /> } return ( <View style={[globals.textContainer, calendarStyles.emptyText]}> <Text style={styles.h2}> No events scheduled. Explore groups in the groups tab or create your own to start an event. </Text> </View> ); }; class EventList extends Component{ constructor(props){ super(props); this.renderRow = this.renderRow.bind(this); this.renderSectionHeader = this.renderSectionHeader.bind(this); this.visitEvent = this.visitEvent.bind(this); this.state = { dataSource: this._loadData(props.events) }; } _loadData(events){ let dataBlob = {}; let dates = uniq(events.map(evt => new Date(evt.start).toLocaleDateString())); /* Get all unique dates */ let sections = dates.map((date, id) => ({ date : new Date(date), events : events.filter(event => new Date(event.start).toLocaleDateString() === date), id : id, })); let sectionIDs = sections.map((section, id) => id); let rowIDs = sectionIDs.map(sectionID => sections[sectionID].events.map((e, id) => id)); sections.forEach(section => { dataBlob[section.id] = section.date; section.events.forEach((event, rowID) => { dataBlob[`${section.id}:${rowID}`] = event; }); }); return new ListView.DataSource({ getSectionData: getSectionData, getRowData: getRowData, rowHasChanged: rowHasChanged, sectionHeaderHasChanged: sectionHeaderHasChanged }) .cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs); } visitEvent(event){ this.props.navigator.push({ name: 'Event', event }) } renderRow(event, sectionID, rowID){ let isGoing = find(event.going, (id) => id === this.props.currentUser.id) != 'undefined'; return ( <TouchableOpacity style={styles.row} onPress={() => this.visitEvent(event)}> <View style={globals.flex}> <View style={styles.textContainer}> <Text style={styles.h4}>{event.name}</Text> <Text style={styles.h5}> {event.going.length} going</Text> { isGoing && <Text style={[globals.primaryText, styles.h5]}><Icon name="ios-checkmark" color={Colors.brandSuccess}/> Yes</Text> } </View> </View> <View style={styles.textContainer}> <Text style={[styles.dateText, globals.mh1]}>{moment(event.start).format('h:mm a')}</Text> <Icon style={styles.arrow} name="ios-arrow-forward" size={25} color={Colors.bodyTextLight}/> </View> </TouchableOpacity> ) } renderSectionHeader(sectionData, sectionID){ return ( <View style={styles.sectionHeader}> <Text style={styles.sectionHeaderText}>{moment(sectionData).format('dddd MMM Do')}</Text> </View> ) } render(){ return ( <ListView enableEmptySectionHeaders={true} style={globals.flex} contentInset={{ bottom: 49 }} automaticallyAdjustContentInsets={false} dataSource={this.state.dataSource} renderRow={this.renderRow} renderSectionHeader={this.renderSectionHeader} /> ) } } class Calendar extends Component{ render(){ let { events, ready } = this.props; return ( <View style={globals.flexContainer}> <NavigationBar tintColor={Colors.brandPrimary} title={{ title: 'Calendar ', tintColor: 'white' }} /> { events && events.length ? <EventList {...this.props}/> : <EmptyList ready={ready} /> } </View> ) } }; export default Calendar;
src/components/navbar/index.js
jamjar919/bork
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { toggleMenuAction } from '../../actions'; const NavbarItem = props => ( <li className="list-group-item list-group-item-action"> { props.children } </li> ); NavbarItem.propTypes = { children: PropTypes.element, }; // eslint-disable-next-line react/prefer-stateless-function class Navbar extends React.Component { render() { return ( <div className={`column-left ${this.props.menuMinimised ? 'column-left-minimised' : ''}`}> <nav> <ul className="list-group"> <NavbarItem><Link to="/"><i className="fa fa-home" aria-hidden="true" />{this.props.menuMinimised ? '' : 'Home'}</Link></NavbarItem> <NavbarItem><Link to="/about"><i className="fa fa-question-circle" aria-hidden="true" />{this.props.menuMinimised ? '' : 'About'}</Link></NavbarItem> <li className="nav-item"> <a className="nav-link active" onClick={() => { this.props.toggleMenu(); }}>{`${this.props.menuMinimised ? '>' : 'Minimise'}`}</a> </li> </ul> </nav> </div> ); } } Navbar.propTypes = { menuMinimised: PropTypes.bool, toggleMenu: PropTypes.func.isRequired, }; function mapStateToProps(state) { return { menuMinimised: state.menuMinimised, }; } function mapDispatchToProps(dispatch) { return { toggleMenu: toggleMenuAction(dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
modules/RouteUtils.js
MattSPalmer/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
modules/Link.js
okcoker/react-router
import React from 'react' import warning from 'warning' const { bool, object, string, func } = React.PropTypes function isLeftClickEvent(event) { return event.button === 0 } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) } function isEmptyObject(object) { for (const p in object) if (object.hasOwnProperty(p)) return false return true } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name * (or the value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ const Link = React.createClass({ contextTypes: { history: object }, propTypes: { activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, to: string.isRequired, query: object, state: object, onClick: func }, getDefaultProps() { return { onlyActiveOnIndex: false, className: '', style: {} } }, handleClick(event) { let allowTransition = true, clickResult if (this.props.onClick) clickResult = this.props.onClick(event) if (isModifiedEvent(event) || !isLeftClickEvent(event)) return if (clickResult === false || event.defaultPrevented === true) allowTransition = false event.preventDefault() if (allowTransition) this.context.history.pushState(this.props.state, this.props.to, this.props.query) }, componentWillMount() { warning( this.context.history, 'A <Link> should not be rendered outside the context of history ' + 'some features including real hrefs, active styling, and navigation ' + 'will not function correctly' ) }, render() { const { history } = this.context const { activeClassName, activeStyle, onlyActiveOnIndex, to, query, state, onClick, ...props } = this.props props.onClick = this.handleClick // Ignore if rendered outside the context // of history, simplifies unit testing. if (history) { props.href = history.createHref(to, query) if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) { if (history.isActive(to, query, onlyActiveOnIndex)) { if (activeClassName) props.className += props.className === '' ? activeClassName : ` ${activeClassName}` if (activeStyle) props.style = { ...props.style, ...activeStyle } } } } return React.createElement('a', props) } }) export default Link
src/components/componentWithPopup.js
markup-app/markup
'use strict'; import React from 'react'; import {generatePid} from '../utilities/general'; const propTypes = { children: React.PropTypes.node.isRequired, message: React.PropTypes.node, style: React.PropTypes.object, forceHide: React.PropTypes.bool }; const defaultProps = { message: '', forceHide: false }; class ComponentWithPopup extends React.Component { constructor (props) { super(props); this.dismissPopup = this.dismissPopup.bind(this); // PID used for identifying this instance of popup component, so we can exclude // this particular component with the window's click event this._internalPID = generatePid(); this.state = { showMessage: false }; } componentDidMount () { window && window.addEventListener('click', this.dismissPopup); } componentWillReceiveProps (nextProps) { if (nextProps.forceHide && !!this.state.showMessage) { this.setState({ showMessage: false }); } } componentWillUnmount () { window && window.removeEventListener('click', this.dismissPopup); } dismissPopup (event) { // Only remove pop up if user clicks on something other than our popup item if (event.target.getAttribute('data-popup-pid') !== this._internalPID) { this.setState({ showMessage: false }); } } render () { var childrenWithProps = React.Children.map(this.props.children, (child) => React.cloneElement(child, { 'data-popup-pid': this._internalPID }) ); return ( <div className="popup-message-container" style={this.props.style} onClick={() => { this.setState({ showMessage: true }); }} > {childrenWithProps} {this.state.showMessage && <PopUp message={this.props.message} pid={this._internalPID} /> } </div> ); } }; function PopUp ({message, pid}) { return ( <div className="popup-message" data-popup-pid={pid}> <div className="popup-arrow" /> {message} </div> ); }; ComponentWithPopup.propTypes = propTypes; ComponentWithPopup.defaultProps = defaultProps; export default ComponentWithPopup;
.history/src/components/InstaCelebs/index_20171001004543.js
oded-soffrin/gkm_viewer
import React from 'react'; import { connect } from 'react-redux' import _ from 'lodash' const InstaCelebs = ({instaCeleb}) => { console.log('instaCeleb', instaCeleb) const stats = _.map(instaCeleb.stats, (x,y) => <div>{y} - {x.like}</div>) return ( <div className="stats"> <h1>Stats</h1> {stats} </div> ) } const mapStateToProps = (state) => ({ instaCeleb: state.instaCeleb }) const InstaCelebsConnected = connect( mapStateToProps, { } )(InstaCelebs) export default InstaCelebsConnected
src/apps/dynamicUI/component/grid/sequenceColumn.js
ziaochina/reactMonkey
import React from 'react' import {Table, Column, Cell} from 'fixed-data-table' export function appendSequenceColumn(columns, gridProps){ columns.splice(0,0,( <Column key= "sequence" width = {40} fixed = {true} cell = {props => ( <Cell> {props.rowIndex + ''} </Cell> )} header = { <Cell>序号</Cell> } footer = { <Cell>合计</Cell> } /> )) return columns }
src/main/viz/FeatureTrack.js
snaheth/pileup.js
/** * Visualization of features, including exons and coding regions. * @flow */ 'use strict'; import type {Feature, FeatureDataSource} from '../sources/FeatureDataSource'; import type {DataCanvasRenderingContext2D} from 'data-canvas'; import type {VizProps} from '../VisualizationWrapper'; import type {Scale} from './d3utils'; import React from 'react'; import shallowEquals from 'shallow-equals'; import _ from 'underscore'; import d3utils from './d3utils'; import RemoteRequest from '../RemoteRequest'; import ContigInterval from '../ContigInterval'; import canvasUtils from './canvas-utils'; import TiledCanvas from './TiledCanvas'; import dataCanvas from 'data-canvas'; import style from '../style'; import utils from '../utils'; import type {State, NetworkStatus} from './pileuputils'; class FeatureTiledCanvas extends TiledCanvas { options: Object; source: FeatureDataSource; constructor(source: FeatureDataSource, options: Object) { super(); this.source = source; this.options = options; } update(newOptions: Object) { this.options = newOptions; } // TODO: can update to handle overlapping features heightForRef(ref: string): number { return style.VARIANT_HEIGHT; } render(ctx: DataCanvasRenderingContext2D, scale: (x: number)=>number, range: ContigInterval<string>, originalRange: ?ContigInterval<string>, resolution: ?number) { var relaxedRange = new ContigInterval(range.contig, range.start() - 1, range.stop() + 1); var vFeatures = this.source.getFeaturesInRange(relaxedRange, resolution); renderFeatures(ctx, scale, relaxedRange, vFeatures); } } // Draw features function renderFeatures(ctx: DataCanvasRenderingContext2D, scale: (num: number) => number, range: ContigInterval<string>, features: Feature[]) { ctx.font = `${style.GENE_FONT_SIZE}px ${style.GENE_FONT}`; ctx.textAlign = 'center'; features.forEach(feature => { var position = new ContigInterval(feature.contig, feature.start, feature.stop); if (!position.chrIntersects(range)) return; ctx.pushObject(feature); ctx.lineWidth = 1; // Create transparency value based on score. Score of <= 200 is the same transparency. var alphaScore = Math.max(feature.score / 1000.0, 0.2); ctx.fillStyle = 'rgba(0, 0, 0, ' + alphaScore + ')'; var x = Math.round(scale(feature.start)); var width = Math.ceil(scale(feature.stop) - scale(feature.start)); ctx.fillRect(x - 0.5, 0, width, style.VARIANT_HEIGHT); ctx.popObject(); }); } class FeatureTrack extends React.Component { props: VizProps & { source: FeatureDataSource }; state: State; tiles: FeatureTiledCanvas; constructor(props: VizProps) { super(props); this.state = { networkStatus: null }; } render(): any { var statusEl = null, networkStatus = this.state.networkStatus; if (networkStatus) { statusEl = ( <div ref='status' className='network-status-small'> <div className='network-status-message-small'> Loading features… </div> </div> ); } var rangeLength = this.props.range.stop - this.props.range.start; // If range is too large, do not render 'canvas' if (rangeLength > RemoteRequest.MONSTER_REQUEST) { return ( <div> <div className='center'> Zoom in to see features </div> <canvas onClick={this.handleClick.bind(this)} /> </div> ); } else { return ( <div> {statusEl} <div ref='container'> <canvas ref='canvas' onClick={this.handleClick.bind(this)} /> </div> </div> ); } } componentDidMount() { this.tiles = new FeatureTiledCanvas(this.props.source, this.props.options); // Visualize new reference data as it comes in from the network. this.props.source.on('newdata', (range) => { this.tiles.invalidateRange(range); this.updateVisualization(); }); this.props.source.on('networkprogress', e => { this.setState({networkStatus: e}); }); this.props.source.on('networkdone', e => { this.setState({networkStatus: null}); }); this.updateVisualization(); } getScale(): Scale { return d3utils.getTrackScale(this.props.range, this.props.width); } componentDidUpdate(prevProps: any, prevState: any) { if (!shallowEquals(this.props, prevProps) || !shallowEquals(this.state, prevState)) { this.tiles.update(this.props.options); this.tiles.invalidateAll(); this.updateVisualization(); } } updateVisualization() { var canvas = (this.refs.canvas : HTMLCanvasElement), {width, height} = this.props, genomeRange = this.props.range; var range = new ContigInterval(genomeRange.contig, genomeRange.start, genomeRange.stop); // Hold off until height & width are known. if (width === 0 || typeof canvas == 'undefined') return; d3utils.sizeCanvas(canvas, width, height); var ctx = dataCanvas.getDataContext(canvasUtils.getContext(canvas)); ctx.reset(); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); this.tiles.renderToScreen(ctx, range, this.getScale()); ctx.restore(); } handleClick(reactEvent: any) { var ev = reactEvent.nativeEvent, x = ev.offsetX; var genomeRange = this.props.range, // allow some buffering so click isn't so sensitive range = new ContigInterval(genomeRange.contig, genomeRange.start-1, genomeRange.stop+1), scale = this.getScale(), // leave padding of 2px to reduce click specificity clickStart = Math.floor(scale.invert(x)) - 2, clickEnd = clickStart + 2, // If click-tracking gets slow, this range could be narrowed to one // closer to the click coordinate, rather than the whole visible range. vFeatures = this.props.source.getFeaturesInRange(range); var feature = _.find(vFeatures, f => utils.tupleRangeOverlaps([[f.start], [f.stop]], [[clickStart], [clickEnd]])); var alert = window.alert || console.log; if (feature) { // Construct a JSON object to show the user. var messageObject = _.extend( { 'id': feature.id, 'range': `${feature.contig}:${feature.start}-${feature.stop}`, 'score': feature.score }); alert(JSON.stringify(messageObject, null, ' ')); } } } FeatureTrack.displayName = 'features'; module.exports = FeatureTrack;
client/modules/Post/components/PostListItem/PostListItem.js
Hashnode/mern-starter
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './PostListItem.css'; function PostListItem(props) { return ( <div className={styles['single-post']}> <h3 className={styles['post-title']}> <Link to={`/posts/${props.post.slug}-${props.post.cuid}`} > {props.post.title} </Link> </h3> <p className={styles['author-name']}><FormattedMessage id="by" /> {props.post.name}</p> <p className={styles['post-desc']}>{props.post.content}</p> <p className={styles['post-action']}><a href="#" onClick={props.onDelete}><FormattedMessage id="deletePost" /></a></p> <hr className={styles.divider} /> </div> ); } PostListItem.propTypes = { post: PropTypes.shape({ name: PropTypes.string.isRequired, title: PropTypes.string.isRequired, content: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, cuid: PropTypes.string.isRequired, }).isRequired, onDelete: PropTypes.func.isRequired, }; export default PostListItem;
src/svg-icons/communication/call.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCall = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); CommunicationCall = pure(CommunicationCall); CommunicationCall.displayName = 'CommunicationCall'; CommunicationCall.muiName = 'SvgIcon'; export default CommunicationCall;
app/src/components/common/KortCoin.js
kort/kort-native
import React, { Component } from 'react'; import { Text } from 'react-native'; import * as Animatable from 'react-native-animatable'; class KortCoin extends Component { renderKoin() { let animationEffect = ''; if (this.props.animationStyle === 'normal') { animationEffect = 'pulse'; } else if (this.props.animationStyle === 'win') { animationEffect = 'flipInY'; } return ( <Animatable.Image animation={animationEffect} easing="ease-out" iterationCount="infinite" style={[styles.koinStyle]} source={{ uri: 'koin' }} defaultSource={{ uri: 'placeholder_badge' }} > <Text style={styles.amountStyle}>{this.props.children}</Text> </Animatable.Image> ); } render() { return ( this.renderKoin() ); } } const styles = { amountStyle: { backgroundColor: 'transparent', color: '#C89E1E', textAlign: 'center', fontSize: 25, marginLeft: 0, marginRight: 0, fontFamily: 'Britannic-BoldT.', }, koinStyle: { justifyContent: 'center', height: 60, width: 60, alignSelf: 'center', }, }; export { KortCoin };
frontend/src/components/frame/components/Progress.js
jf248/scrape-the-plate
import React from 'react'; import { Loading } from 'controllers/loading'; import ProgressPres from './ProgressPres'; function Progress() { return ( <Loading render={({ isLoading }) => <ProgressPres {...{ isLoading }} />} /> ); } export default Progress;
bunbunbakeshop/src/Products.js
jzheng13/SSUI-Homework-4
import React, { Component } from 'react'; import './styles/index.css'; import './styles/font-awesome.min.css'; import Item from './Item'; import Menu from './Menu'; class Products extends Component { constructor(props) { super(props); this.state = { item: -1, } this.changeView = this.changeView.bind(this); } changeView(id) { this.setState({ item: id, }); } render() { return ( <div> {this.state.item < 0 ? <Menu changeView={this.changeView} changeState={this.props.changeState} /> : <Item data={this.state.item} changeView={this.changeView} updateCart={this.props.updateCart} changeState={this.props.changeState}/>} </div> ); } } export default Products;
actor-apps/app-web/src/app/components/common/MessageItem.react.js
bunnyblue/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import memoize from 'memoizee'; import classNames from 'classnames'; import emojify from 'emojify.js'; import hljs from 'highlight.js'; import marked from 'marked'; import emojiCharacters from 'emoji-named-characters'; import Lightbox from 'jsonlylightbox'; import VisibilitySensor from 'react-visibility-sensor'; import AvatarItem from 'components/common/AvatarItem.react'; import DialogActionCreators from 'actions/DialogActionCreators'; import { MessageContentTypes } from 'constants/ActorAppConstants'; let lastMessageSenderId, lastMessageContentType; var MessageItem = React.createClass({ displayName: 'MessageItem', propTypes: { message: React.PropTypes.object.isRequired, newDay: React.PropTypes.bool, onVisibilityChange: React.PropTypes.func }, mixins: [PureRenderMixin], onClick() { DialogActionCreators.selectDialogPeerUser(this.props.message.sender.peer.id); }, onVisibilityChange(isVisible) { this.props.onVisibilityChange(this.props.message, isVisible); }, render() { const message = this.props.message; const newDay = this.props.newDay; let header, visibilitySensor, leftBlock; let isSameSender = message.sender.peer.id === lastMessageSenderId && lastMessageContentType !== MessageContentTypes.SERVICE && message.content.content !== MessageContentTypes.SERVICE && !newDay; let messageClassName = classNames({ 'message': true, 'row': true, 'message--same-sender': isSameSender }); if (isSameSender) { leftBlock = ( <div className="message__info text-right"> <time className="message__timestamp">{message.date}</time> <MessageItem.State message={message}/> </div> ); } else { leftBlock = ( <div className="message__info message__info--avatar"> <a onClick={this.onClick}> <AvatarItem image={message.sender.avatar} placeholder={message.sender.placeholder} title={message.sender.title}/> </a> </div> ); header = ( <header className="message__header"> <h3 className="message__sender"> <a onClick={this.onClick}>{message.sender.title}</a> </h3> <time className="message__timestamp">{message.date}</time> <MessageItem.State message={message}/> </header> ); } if (message.content.content === MessageContentTypes.SERVICE) { leftBlock = null; header = null; } if (this.props.onVisibilityChange) { visibilitySensor = <VisibilitySensor onChange={this.onVisibilityChange}/>; } lastMessageSenderId = message.sender.peer.id; lastMessageContentType = message.content.content; return ( <li className={messageClassName}> {leftBlock} <div className="message__body col-xs"> {header} <MessageItem.Content content={message.content}/> {visibilitySensor} </div> </li> ); } }); emojify.setConfig({ mode: 'img', img_dir: 'assets/img/emoji' // eslint-disable-line }); const mdRenderer = new marked.Renderer(); // target _blank for links mdRenderer.link = function(href, title, text) { let external, newWindow, out; external = /^https?:\/\/.+$/.test(href); newWindow = external || title === 'newWindow'; out = '<a href=\"' + href + '\"'; if (newWindow) { out += ' target="_blank"'; } if (title && title !== 'newWindow') { out += ' title=\"' + title + '\"'; } return (out + '>' + text + '</a>'); }; const markedOptions = { sanitize: true, breaks: true, highlight: function (code) { return hljs.highlightAuto(code).value; }, renderer: mdRenderer }; const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character)); const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) { return name.replace(/\+/g, '\\+'); }); const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi'); const processText = function(text) { let markedText = marked(text, markedOptions); // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127 const noPTag = markedText.replace(/<p>/g, '<p> '); let emojifiedText = emojify .replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':')); return emojifiedText; }; const memoizedProcessText = memoize(processText, { length: 1000, maxAge: 60 * 60 * 1000, max: 10000 }); // lightbox init const lightbox = new Lightbox(); const lightboxOptions = { animation: false, controlClose: '<i class="material-icons">close</i>' }; lightbox.load(lightboxOptions); MessageItem.Content = React.createClass({ propTypes: { content: React.PropTypes.object.isRequired }, mixins: [PureRenderMixin], getInitialState() { return { isImageLoaded: false }; }, render() { const content = this.props.content; const isImageLoaded = this.state.isImageLoaded; let contentClassName = classNames('message__content', { 'message__content--service': content.content === MessageContentTypes.SERVICE, 'message__content--text': content.content === MessageContentTypes.TEXT, 'message__content--photo': content.content === MessageContentTypes.PHOTO, 'message__content--photo--loaded': isImageLoaded, 'message__content--document': content.content === MessageContentTypes.DOCUMENT, 'message__content--unsupported': content.content === MessageContentTypes.UNSUPPORTED }); switch (content.content) { case 'service': return ( <div className={contentClassName}> {content.text} </div> ); case 'text': return ( <div className={contentClassName} dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}> </div> ); case 'photo': const preview = <img className="photo photo--preview" src={content.preview}/>; const k = content.w / 300; const photoMessageStyes = { width: Math.round(content.w / k), height: Math.round(content.h / k) }; let original, preloader; if (content.fileUrl) { original = ( <img className="photo photo--original" height={content.h} onClick={this.openLightBox} onLoad={this.imageLoaded} src={content.fileUrl} width={content.w}/> ); } if (content.isUploading === true || isImageLoaded === false) { preloader = <div className="preloader"><div/><div/><div/><div/><div/></div>; } return ( <div className={contentClassName} style={photoMessageStyes}> {preview} {original} {preloader} <svg dangerouslySetInnerHTML={{__html: '<filter id="blur-effect"><feGaussianBlur stdDeviation="3"/></filter>'}}></svg> </div> ); case 'document': contentClassName = classNames(contentClassName, 'row'); let availableActions; if (content.isUploading === true) { availableActions = <span>Loading...</span>; } else { availableActions = <a href={content.fileUrl}>Open</a>; } return ( <div className={contentClassName}> <div className="document row"> <div className="document__icon"> <i className="material-icons">attach_file</i> </div> <div className="col-xs"> <span className="document__filename">{content.fileName}</span> <div className="document__meta"> <span className="document__meta__size">{content.fileSize}</span> <span className="document__meta__ext">{content.fileExtension}</span> </div> <div className="document__actions"> {availableActions} </div> </div> </div> <div className="col-xs"></div> </div> ); default: } }, imageLoaded() { this.setState({isImageLoaded: true}); }, openLightBox() { lightbox.open(this.props.content.fileUrl); } }); MessageItem.State = React.createClass({ propTypes: { message: React.PropTypes.object.isRequired }, render() { const message = this.props.message; if (message.content.content === MessageContentTypes.SERVICE) { return null; } else { let icon = null; switch(message.state) { case 'pending': icon = <i className="status status--penging material-icons">access_time</i>; break; case 'sent': icon = <i className="status status--sent material-icons">done</i>; break; case 'received': icon = <i className="status status--received material-icons">done_all</i>; break; case 'read': icon = <i className="status status--read material-icons">done_all</i>; break; case 'error': icon = <i className="status status--error material-icons">report_problem</i>; break; default: } return ( <div className="message__status">{icon}</div> ); } } }); export default MessageItem;
app/containers/RepoListItem/index.js
w01fgang/react-boilerplate
/** * RepoListItem * * Lists the name and the issue count of a repository */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { FormattedNumber } from 'react-intl'; import { selectCurrentUser } from 'containers/App/selectors'; import ListItem from 'components/ListItem'; import IssueIcon from 'components/IssueIcon'; import A from 'components/A'; import styles from './styles.css'; export class RepoListItem extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; let nameprefix = ''; // If the repository is owned by a different person than we got the data for // it's a fork and we should show the name of the owner if (item.owner.login !== this.props.currentUser) { nameprefix = `${item.owner.login}/`; } // Put together the content of the repository const content = ( <div className={styles.linkWrapper}> <A className={styles.linkRepo} href={item.html_url} target="_blank" > {nameprefix + item.name} </A> <A className={styles.linkIssues} href={`${item.html_url}/issues`} target="_blank" > <IssueIcon className={styles.issueIcon} /> <FormattedNumber value={item.open_issues_count} /> </A> </div> ); // Render the content into a list item return ( <ListItem key={`repo-list-item-${item.full_name}`} item={content} /> ); } } RepoListItem.propTypes = { item: React.PropTypes.object, currentUser: React.PropTypes.string, }; export default connect(createSelector( selectCurrentUser(), (currentUser) => ({ currentUser }) ))(RepoListItem);
entry_types/scrolled/package/src/frontend/layouts/TwoColumn.js
codevise/pageflow
import React from 'react'; import classNames from 'classnames'; import {ContentElements} from '../ContentElements'; import {useNarrowViewport} from '../useNarrowViewport'; import styles from './TwoColumn.module.css'; function availablePositions(narrow) { if (narrow) { return ['inline', 'wide', 'full']; } else { return ['inline', 'sticky', 'wide', 'full']; } } export function TwoColumn(props) { const narrow = useNarrowViewport(); return ( <div className={classNames(styles.root, styles[props.align], narrow ? styles.narrowViewport : styles.wideViewport)}> <div className={classNames(styles.group)} key={props.align}> <div className={styles.inline} ref={props.contentAreaRef} /> </div> {renderItems(props, narrow)} {renderPlaceholder(props.placeholder)} </div> ); } TwoColumn.defaultProps = { align: 'left' } function renderItems(props, narrow) { return groupItemsByPosition(props.items, availablePositions(narrow)).map((group, index) => <div key={index} className={classNames(styles.group, styles[`group-${group.position}`])}> {renderItemGroup(props, group, 'sticky')} {renderItemGroup(props, group, 'inline')} {renderItemGroup(props, group, 'wide')} {renderItemGroup(props, group, 'full')} </div> ); } function renderItemGroup(props, group, position) { if (group[position].length) { return ( <div className={styles[position]}> {props.children( <ContentElements sectionProps={props.sectionProps} items={group[position]} />, { position, openStart: position === 'inline' && group.openStart, openEnd: position === 'inline' && group.openEnd } )} </div> ); } } function groupItemsByPosition(items, availablePositions) { let groups = []; let currentGroup; items.reduce((previousItemPosition, item, index) => { const position = availablePositions.indexOf(item.position) >= 0 ? item.position : 'inline'; if (!previousItemPosition || (previousItemPosition !== position && !(previousItemPosition === 'sticky' && position === 'inline'))) { currentGroup = { position, sticky: [], inline: [], wide: [], full: [] }; groups = [...groups, currentGroup]; } currentGroup[position].push(item); return position; }, null); groups.forEach((group, index) => { const previous = groups[index - 1]; const next = groups[index + 1]; group.openStart = previous && !(previous.full.length || previous.wide.length); group.openEnd = next && next.inline.length > 0; }) return groups; } function renderPlaceholder(placeholder) { if (!placeholder) { return null; } return ( <div className={classNames(styles.group)}> <div className={styles.inline}> {placeholder} </div> </div> ) }
app/src/components/ProductList.js
jluangphasy/shop
import React, { Component } from 'react'; import Product from './Product'; class ProductList extends Component { /** * Render <Product /> * * @param: {id} * - id (string): product id * @return: {JSX} */ renderProduct(id) { const quantity = this.props.order[id] || 0; return ( <Product addProductOrder={this.props.addProductOrder} key={id} quantity={quantity} product={this.props.products[id]} /> ); } /** * Render <ProductList /> * * @return: {JSX} */ render() { const products = Object.keys(this.props.products); const productsCount = products.length; return ( <section> <h2>Lapel Pins</h2> {productsCount < 1 && <p>No lapel pins available. Check back soon!</p>} {productsCount > 0 && products.map((id) => this.renderProduct(id))} </section> ); } } export default ProductList;
app/javascript/src/components/UserProfileCard.js
michelson/chaskiq
import React from 'react' import { withRouter, Link } from 'react-router-dom' import { connect } from 'react-redux' import Moment from 'react-moment' import Accordeon from './Accordeon' import Badge from './Badge' import { compact } from 'lodash' function UserProfileCard ({ app, app_user }) { function getPropertiesItems () { if (!app.customFields) return [] const fields = app.customFields.map((field) => field.name) const items = fields.map((f) => { const val = app_user.properties[f] if (!val) return null return { label: `${f}:`, value: val } }) return compact(items) } return ( <div className="divide-y divide-gray-200"> <div className="pb-6"> <div className="bg-yellow-200 h-24 sm:h-20 lg:h-28" /> <div className="-mt-12 flow-root px-4 space-y-6 sm:-mt-8 sm:flex sm:items-end sm:px-6 sm:space-x-6 lg:-mt-15"> <div> <div className="-m-1 flex"> <div className="inline-flex rounded-lg overflow-hidden border-4 border-white"> <img className="flex-shrink-0 h-24 w-24 sm:h-40 sm:w-40 lg:w-48 lg:h-48" src={app_user.avatarUrl} /> </div> </div> </div> <div className="ml-3 sm:flex-1"> <div> <div className="flex items-center space-x-2.5"> <h3 className="font-bold text-xl leading-7 text-gray-900 dark:text-gray-100 sm:text-2xl sm:leading-8"> {app_user.properties.name} </h3> { app_user.online && <span aria-label="Online" className="ml-2 bg-green-400 flex-shrink-0 inline-block h-2 w-2 rounded-full" /> } </div> <p className="text-sm leading-5 text-gray-500"> {app_user.email} </p> </div> <div className="mt-3 flex flex-wrap"> <span className="flex-shrink-0 w-full inline-flex rounded-md shadow-sm sm:flex-1"> <Link className="w-full inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:border-pink-700 focus:shadow-outline-indigo active:bg-pink-700 transition ease-in-out duration-150" to={`/apps/${app.key}/users/${app_user.id}`}> show profile </Link> </span> {/* <span className="mt-3 flex-1 w-full inline-flex rounded-md shadow-sm sm:mt-0 sm:ml-3"> <button type="button" className="w-full inline-flex items-center justify-center px-4 py-2 border border-gray-300 text-sm leading-5 font-medium rounded-md text-gray-700 bg-white hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:text-gray-800 active:bg-gray-50 transition ease-in-out duration-150"> Call </button> </span> */} </div> </div> </div> </div> <div className="px-4 py-5 sm:px-0 sm:py-0"> <dl className="space-y-8 sm:space-y-0"> <div className="sm:flex sm:space-x-6 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Last seen </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> <p> <Moment fromNow ago> {Date.parse(app_user.lastVisitedAt)} </Moment> </p> </dd> </div> <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Location </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> {[app_user.city, app_user.region, app_user.country].filter((o) => o).join(', ')} </dd> </div> <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Web Sessions </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> {app_user.webSessions} </dd> </div> { app_user.timezone && <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Timezone </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> {app_user.timezone} </dd> </div> } { app_user.browser && <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Browser </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> {[app_user.browser, app_user.browserVersion].join(', ')} </dd> </div> } { app_user.os && <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Operating System </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> {[app_user.os, app_user.osVersion].join(', ')} </dd> </div> } { app_user.tagList && <div className="sm:flex sm:space-x-6 sm:border-t sm:border-gray-200 dark:sm:border-gray-800 sm:px-6 sm:py-5"> <dt className="text-sm leading-5 font-medium text-gray-500 dark:text-gray-300 sm:w-40 sm:flex-shrink-0 lg:w-48"> Tags </dt> <dd className="mt-1 text-sm leading-5 text-gray-900 dark:text-gray-100 sm:mt-0 sm:col-span-2"> { app_user.tagList.map((tag, i) => (<Badge size="sm" key={`tag-${i}`}> {tag} </Badge>))} </dd> </div> } </dl> </div> <Accordeon items={[ { name: 'Properties', component: null, items: getPropertiesItems() }, { name: 'External Profiles', component: ( <div> <ul dense> {app_user.externalProfiles && app_user.externalProfiles.map((o) => { return ( <div m={2} key={`app-user-profile-${app_user.id}-${o.id}`} > <div className="flex flex-col" > <div className="flex flex-col"> <p className="font-bold"> {o.provider} </p> <p variant="h6">{o.profileId}</p> </div> {/* <Button size="small" variant={'outlined'} className="w-24" onClick={() => this.syncExternalProfile(o)} > sync </Button> */} </div> <div style={{ display: 'flex', flexDirection: 'column', textAlign: 'left' }} > {o.data && Object.keys(o.data).map((a, i) => { if ( !o.data[a] || typeof o.data[a] === 'object' ) { return null } return ( <p variant={'caption'} key={`app-user-${o.provider}-${app_user.id}-${i}`} > {<b>{a}:</b>} {` ${o.data[a]}`} </p> ) })} </div> </div> ) })} </ul> </div> ) } ]} /> </div> ) } function mapStateToProps (state) { const { app_user, app } = state return { app_user, app } } export default withRouter(connect(mapStateToProps)(UserProfileCard))
src/render-react.js
abramz/gulp-render-react
/*! Gulp Render React | MIT License */ import gutil from 'gulp-util'; import through from 'through2'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; /** * Requires a file containing a React component and create an instance of it * @param {String} filePath file path to the React component to render * @param {Object} props properties to apply to the element * @return {Element} the created React element */ function createElement(filePath, props) { if (!filePath || typeof filePath !== 'string' || filePath.length === 0) { throw new Error('Expected filePath to be a string'); } // clear the require cache if we have already imported the file (if we are watching it) if (require.cache[filePath]) { delete require.cache[filePath]; } const component = require(filePath); // eslint-disable-line global-require, import/no-dynamic-require const element = React.createElement(component.default || component, props || {}); return element; } /** * Uses ReactDOMServer.renderToString on a component at filePath. Will apply optional pro * https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring * * @param {String} filePath react component to render * @param {Object} props properties to apply to the React component * @return {Buffer} buffer of the component rendered to a string */ function renderToString(filePath, props) { const element = createElement(filePath, props); const elementString = ReactDOMServer.renderToString(element); return new Buffer(elementString); } /** * Uses ReactDOMServer.renderToStatic on a component at filePath. Will apply optional props * https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup * * @param {String} filePath react component to render * @param {Object} props properties to apply to the React component * @return {Buffer} buffer of the component rendered to a string */ function renderToStaticMarkup(filePath, props) { const element = createElement(filePath, props); const elementMarkup = ReactDOMServer.renderToStaticMarkup(element); return new Buffer(elementMarkup); } module.exports = (options) => { const opts = options || {}; if (!opts.type || (opts.type !== 'string' && opts.type !== 'markup')) { throw new gutil.PluginError('gulp-render-react', '`type` required (`string` or `markup`)'); } return through.obj(function process(file, enc, callback) { try { const newFile = file; // temporary before we allow src extension in options if (opts.type === 'string') { newFile.contents = renderToString(file.path, opts.props ? opts.props : {}); } else if (opts.type === 'markup') { newFile.contents = renderToStaticMarkup(file.path, opts.props ? opts.props : {}); } // temporary before we allow dest extension in options newFile.path = gutil.replaceExtension(file.path, '.html'); this.push(newFile); } catch (err) { this.emit('error', new gutil.PluginError('gulp-render-react', err, { fileName: file.path })); } callback(); }); };
examples/counter/index.js
omnidan/redux-devtools
import React from 'react'; import App from './containers/App'; React.render( <App />, document.getElementById('root') );
app/components/checkbox.js
garth/material-components
import React from 'react'; import { connect } from '@cerebral/react'; import Example from './example'; import { Checkbox } from '../../lib'; import { state, signal } from 'cerebral/tags'; const CheckboxDemo = ({ checkbox, checkboxChanged }) => ( <div> <Example code={` import { Checkbox } from 'material-components'; `} /> <Example code={` <Checkbox label="Checkbox" value={checked} onChange={setChecked}/> `} /> <div> <Checkbox label="Checkbox" value={checkbox.checked} onChange={e => checkboxChanged({ value: e.target.value })} /> </div> <div> <Checkbox label="Opposite" value={!checkbox.checked} onChange={e => checkboxChanged({ value: !e.target.value })} /> </div> </div> ); export default connect( { checkbox: state`demos.checkbox`, checkboxChanged: signal`checkboxChanged` }, CheckboxDemo );
src/Glyphicon.js
mmartche/boilerplate-shop
import React from 'react'; import classNames from 'classnames'; const Glyphicon = React.createClass({ propTypes: { /** * bootstrap className * @private */ bsClass: React.PropTypes.string, /** * An icon name. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: React.PropTypes.string.isRequired, /** * Adds 'form-control-feedback' class * @private */ formControlFeedback: React.PropTypes.bool }, getDefaultProps() { return { bsClass: 'glyphicon', formControlFeedback: false }; }, render() { let className = classNames(this.props.className, { [this.props.bsClass]: true, ['glyphicon-' + this.props.glyph]: true, ['form-control-feedback']: this.props.formControlFeedback }); return ( <span {...this.props} className={className}> {this.props.children} </span> ); } }); export default Glyphicon;
tests/react/createElementRequiredProp_string.js
mroch/flow
// @flow import React from 'react'; class Bar extends React.Component<{test: number}> { render() { return ( <div> {this.props.test} </div> ) } } class Foo extends React.Component<{}> { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }
src/components/icons/close.js
ipfs-shipyard/peerpad
import React from 'react' export default ({ className, style }) => ( <svg width='16' height='16' viewBox='0 0 149 146.7' xmlns='http://www.w3.org/2000/svg' className={className} style={style}> <path d='M74.5 11a62.3 62.3 0 1 0 62.3 62.3A62.37 62.37 0 0 0 74.5 11zm55 62.39a55 55 0 1 1-55-55 55.11 55.11 0 0 1 55.04 55.05z' /> <path d='M104 45.34a3.34 3.34 0 0 0-4.72 0L75 69.67 50.67 45.34A3.34 3.34 0 0 0 46 50.06l24.28 24.33L46 98.71a3.34 3.34 0 0 0 4.72 4.72L75 79.11l24.33 24.33a3.34 3.34 0 1 0 4.67-4.73L79.72 74.39 104 50.06a3.34 3.34 0 0 0 0-4.72z' /> </svg> )
src/components/Feedback/Feedback.js
amit242/antyka
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.less'; import withStyles from '../../decorators/withStyles'; import withViewport from '../../decorators/withViewport'; @withViewport @withStyles(styles) class Feedback { render() { let { width, height } = this.props.viewport; let feedbackClassName = "feedback"; if(width < 340) { feedbackClassName += " bottom"; } return ( <div className={feedbackClassName}> <div className="feedback-container"> <a className="feedback-link" href="https://github.com/amit242/antyka/issues/new">Ask a question</a> <span className="feedback-spacer">|</span> <a className="feedback-link" href="https://github.com/amit242/antyka/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
packages/cf-component-dropdown/example/basic/component.js
koddsson/cf-ui
import React from 'react'; import { Dropdown, DropdownLink, DropdownSeparator } from 'cf-component-dropdown'; import { Button, ButtonGroup } from 'cf-component-button'; class DropdownComponent extends React.Component { constructor(props) { super(props); this.state = { dropdown1Open: false, dropdown2Open: false }; } render() { return ( <ButtonGroup> <Button type="primary" onClick={() => this.setState({ dropdown1Open: true })} > Open Dropdown 1 </Button> {this.state.dropdown1Open && <Dropdown onClose={() => this.setState({ dropdown1Open: false })}> <DropdownLink to="/foo">Link to /foo</DropdownLink> <DropdownLink to="/bar">Link to /bar</DropdownLink> <DropdownSeparator /> <DropdownLink to="/baz">Link to /baz</DropdownLink> <DropdownLink to="/bat">Link to /bat</DropdownLink> </Dropdown>} <Button type="success" onClick={() => this.setState({ dropdown2Open: true })} > Open Dropdown 2 </Button> {this.state.dropdown2Open && <Dropdown align="right" onClose={() => this.setState({ dropdown2Open: false })} > <DropdownLink to="/foo">Link to /foo</DropdownLink> <DropdownLink to="/bar">Link to /bar</DropdownLink> <DropdownSeparator /> <DropdownLink to="/baz">Link to /baz</DropdownLink> <DropdownLink to="/bat">Link to /bat</DropdownLink> </Dropdown>} </ButtonGroup> ); } } export default DropdownComponent;
example_components/RadioInput.react.js
blueberryapps/react-bluekit
import Component from '../src/app/PureRenderComponent.react'; import Radium from 'radium'; import React from 'react'; import RPT from 'prop-types'; import ToolTip from '../src/app/atoms/ToolTip.react'; @Radium export default class RadioInput extends Component { static propTypes = { horizontal: RPT.bool, name: RPT.string.isRequired, onChange: RPT.func.isRequired, selected: RPT.bool.isRequired, text: RPT.string, tooltip: RPT.string, value: RPT.string.isRequired } render() { const {name, onChange, selected, value, tooltip, horizontal, text} = this.props; const focused = Radium.getState(this.state, 'input', ':focus'); const optionText = text && text || value; return ( <label style={[styles.wrapper, horizontal && styles.horizontal]}> <div style={[ styles.base, selected && styles.baseChecked, focused && styles.baseFocused ]}> <div style={[styles.unchecked, selected && styles.checked]} /> </div> <input checked={selected} key='input' name={name} onChange={onChange} style={styles.input} type='radio' value={value} /> <div style={styles.text}>{optionText}</div> {tooltip && <ToolTip inheritedStyles={styles.tooltip}> {tooltip} </ToolTip> } </label> ); } } const styles = { wrapper: { position: 'relative', padding: '0 30px 0 25px', userSelect: 'none', cursor: 'pointer', fontWeight: 'normal', '@media (max-width: 991px)': { display: 'block', margin: '10px 0' } }, horizontal: { display: 'block' }, input: { position: 'absolute', left: '-9999px', ':focus': {} }, text: { padding: '4px 12px', display: 'inline-block' }, base: { width: '24px', height: '24px', borderWidth: '1px', borderStyle: 'solid', borderColor: 'hsl(0, 0%, 80%)', borderRadius: '100%', position: 'absolute', top: 0, left: 0, transition: 'border-color .2s ease-in-out' }, baseFocused: { borderColor: 'hsl(0, 0%, 50%)', backgroundColor: 'hsl(0, 0%, 95%)' }, baseChecked: { borderColor: 'hsl(0, 0%, 50%)' }, unchecked: { backgroundColor: '#6dad0d', backgroundImage: 'linear-gradient(bottom, #6dad0d 0%, #81d10b 100%)', width: '14px', height: '14px', borderRadius: '100%', position: 'absolute', top: '5px', left: '5px', transform: 'scale(0, 0)' }, tooltip: { bottom: 'calc(100% + 10px)', top: 'auto' }, checked: { transform: 'scale(1, 1)', transition: 'transform .2s' } };
src/components/NotAuthenticated.js
react-auth/react-auth
import React from 'react'; import utils from '../utils'; export default class NotAuthenticated extends React.Component { static contextTypes = { user: React.PropTypes.object }; render() { var user = this.context.user; var authenticated = user !== undefined; if (this.props.inGroup) { if (authenticated) { if (user.groups) { authenticated = utils.groupsMatchExpression(user.groups, this.props.inGroup); } else { utils.logWarning('<NotAuthenticated> In order to use the inGroup option, you must expand the groups resource for the /me endpoint.'); } } else { return null; } } return !authenticated ? utils.enforceRootElement(this.props.children) : null; } }
src/Enigma/UI/Component/WiredWheel/Reflector.js
minkiele/EnigmaUI
import React from 'react'; import EventEmitter from 'events'; import FormControl from 'react-bootstrap/lib/FormControl'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; export const INITIAL_REFLECTOR_TYPE = ''; export default class Reflector extends React.Component { updateType (type) { this.props.eventManager.emit('change.reflector', type); } render () { return ( <div className="enigmaReflector"> <div className="enigmaReflectorType"> <ControlLabel>Type</ControlLabel> <FormControl componentClass="select" value={this.props.type} onChange={(evt) => { this.updateType(evt.target.value); }}> <option value="">Choose a reflector</option> {this.props.children} </FormControl> </div> </div> ); } } Reflector.propTypes = { type: React.PropTypes.string.isRequired, eventManager: React.PropTypes.instanceOf(EventEmitter).isRequired }; Reflector.defaultProps = { type: INITIAL_REFLECTOR_TYPE };
src/svg-icons/places/child-friendly.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesChildFriendly = (props) => ( <SvgIcon {...props}> <path d="M13 2v8h8c0-4.42-3.58-8-8-8zm6.32 13.89C20.37 14.54 21 12.84 21 11H6.44l-.95-2H2v2h2.22s1.89 4.07 2.12 4.42c-1.1.59-1.84 1.75-1.84 3.08C4.5 20.43 6.07 22 8 22c1.76 0 3.22-1.3 3.46-3h2.08c.24 1.7 1.7 3 3.46 3 1.93 0 3.5-1.57 3.5-3.5 0-1.04-.46-1.97-1.18-2.61zM8 20c-.83 0-1.5-.67-1.5-1.5S7.17 17 8 17s1.5.67 1.5 1.5S8.83 20 8 20zm9 0c-.83 0-1.5-.67-1.5-1.5S16.17 17 17 17s1.5.67 1.5 1.5S17.83 20 17 20z"/> </SvgIcon> ); PlacesChildFriendly = pure(PlacesChildFriendly); PlacesChildFriendly.displayName = 'PlacesChildFriendly'; PlacesChildFriendly.muiName = 'SvgIcon'; export default PlacesChildFriendly;
src/components/MapState.js
neontribe/gbptm
import React from 'react'; import config from '../config'; const MapStateContext = React.createContext(); const reducer = (state, newState) => { return { ...state, ...newState, }; }; export const MapStateProvider = ({ children }) => { const [state, setState] = React.useReducer(reducer, { center: config.fallbackLocation, zoom: 16, radius: 1000, geolocation: null, }); return ( <MapStateContext.Provider value={[state, setState]}> {children} </MapStateContext.Provider> ); }; export const useMapState = () => React.useContext(MapStateContext);
src/SpringFitnessRedux.js
mrbjoern/SpringFitnessMobile
import React from 'react'; import { Provider, connect } from 'react-redux' import { AppRegistry, Text } from 'react-native'; import StartPage from './components/page/StartPage'; import LoginPage from './components/page/LoginPage'; import HomePage from './components/page/HomePage'; import WorkoutPage from './components/page/WorkoutPage'; import RegistrationPage from './components/page/RegistrationPage'; import AboutPage from './components/page/AboutPage'; import store from './store'; const pages = { 'LoginPage': LoginPage, 'HomePage': HomePage, 'WorkoutPage': WorkoutPage, 'StartPage': StartPage, 'RegistrationPage': RegistrationPage, 'AboutPage': AboutPage, }; const Page = (props) => { const DisplayPage = pages[props.pageName]; return <DisplayPage /> } const ConnectedPage = connect( (state) => ({ pageName: state.routing.pageStack[state.routing.pageStack.length - 1], }), )(Page); const SpringFitnessRedux = () => ( <Provider store={store}> <ConnectedPage /> </Provider> ); export const registerApp = () => { AppRegistry.registerComponent('SpringFitnessMobile', () => SpringFitnessRedux); };
src/interface/icons/ScrollFilled.js
yajinni/WoWAnalyzer
import React from 'react'; // https://thenounproject.com/jngll2/uploads/?i=1219368 // Created by jngll from the Noun Project const Icon = ({ ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="icon" {...other}> <path d="M80.64,10.87l-.52,0-.26,0H30.64A11.24,11.24,0,0,0,19.42,21.94s0,.05,0,.08V66.66h-.64a3,3,0,0,0-.63.07,11.23,11.23,0,0,0,0,22.33,3,3,0,0,0,.63.07h45.4A11.25,11.25,0,0,0,75.41,77.9V33.34h5.23a11.23,11.23,0,1,0,0-22.47Zm-66.52,67a5.24,5.24,0,0,1,5.23-5.23H54.24a11.17,11.17,0,0,0,0,10.47H19.36A5.24,5.24,0,0,1,14.12,77.9Zm55.28,0a5.23,5.23,0,1,1-5.23-5.23,3,3,0,0,0,0-6H25.41V22.1a5.24,5.24,0,0,1,5.23-5.23H70.71a11.16,11.16,0,0,0-1.29,5.07s0,.05,0,.08ZM80.64,27.34H75.41V22.1a5.23,5.23,0,1,1,5.23,5.23Z" /> <rect x="29.33" y="52.67" width="8" height="6" /> <rect x="42.33" y="52.67" width="22" height="6" /> <rect x="29.33" y="40.67" width="8" height="6" /> <rect x="42.33" y="40.67" width="22" height="6" /> <rect x="29.33" y="28.67" width="8" height="6" /> <rect x="42.33" y="28.67" width="22" height="6" /> </svg> ); export default Icon;
react/features/mobile/navigation/screenOptions.js
gpolitis/jitsi-meet
// @flow import { TransitionPresets } from '@react-navigation/stack'; import React from 'react'; import { useTranslation } from 'react-i18next'; import { Platform } from 'react-native'; import { Icon, IconClose, IconHelp, IconHome, IconInfo, IconSettings } from '../../base/icons'; import BaseTheme from '../../base/ui/components/BaseTheme.native'; import HeaderNavigationButton from './components/HeaderNavigationButton'; import { goBack } from './components/conference/ConferenceNavigationContainerRef'; /** * Navigation container theme. */ export const navigationContainerTheme = { colors: { background: BaseTheme.palette.ui12 } }; /** * Default modal transition for the current platform. */ export const conferenceModalPresentation = Platform.select({ ios: TransitionPresets.ModalPresentationIOS, default: TransitionPresets.DefaultTransition }); /** * Screen options and transition types. */ export const fullScreenOptions = { ...TransitionPresets.ModalTransition, gestureEnabled: false, headerShown: false }; /** * Dial-IN Info screen options and transition types. */ export const dialInSummaryScreenOptions = { ...TransitionPresets.ModalTransition, gestureEnabled: true, headerShown: true, headerStyle: { backgroundColor: BaseTheme.palette.screen01Header }, headerTitleStyle: { color: BaseTheme.palette.text01 } }; /** * Drawer navigator screens options and transition types. */ export const drawerNavigatorScreenOptions = { ...TransitionPresets.ModalTransition, gestureEnabled: true, headerShown: false }; /** * Drawer screen options and transition types. */ export const drawerScreenOptions = { ...TransitionPresets.ModalTransition, gestureEnabled: true, headerShown: true, headerStyle: { backgroundColor: BaseTheme.palette.screen01Header } }; /** * Drawer content options. */ export const drawerContentOptions = { drawerActiveBackgroundColor: BaseTheme.palette.uiBackground, drawerActiveTintColor: BaseTheme.palette.screen01Header, drawerInactiveTintColor: BaseTheme.palette.text02, drawerLabelStyle: { marginLeft: BaseTheme.spacing[2] }, drawerStyle: { backgroundColor: BaseTheme.palette.uiBackground, maxWidth: 400, width: '75%' } }; /** * Screen options for welcome page. */ export const welcomeScreenOptions = { ...drawerScreenOptions, drawerIcon: ({ focused }) => ( <Icon color = { focused ? BaseTheme.palette.screen01Header : BaseTheme.palette.icon02 } size = { 20 } src = { IconHome } /> ), headerTitleStyle: { color: BaseTheme.palette.screen01Header } }; /** * Screen options for settings screen. */ export const settingsScreenOptions = { ...drawerScreenOptions, drawerIcon: ({ focused }) => ( <Icon color = { focused ? BaseTheme.palette.screen01Header : BaseTheme.palette.icon02 } size = { 20 } src = { IconSettings } /> ), headerTitleStyle: { color: BaseTheme.palette.text01 } }; /** * Screen options for terms/privacy screens. */ export const termsAndPrivacyScreenOptions = { ...drawerScreenOptions, drawerIcon: ({ focused }) => ( <Icon color = { focused ? BaseTheme.palette.screen01Header : BaseTheme.palette.icon02 } size = { 20 } src = { IconInfo } /> ), headerTitleStyle: { color: BaseTheme.palette.text01 } }; /** * Screen options for help screen. */ export const helpScreenOptions = { ...drawerScreenOptions, drawerIcon: ({ focused }) => ( <Icon color = { focused ? BaseTheme.palette.screen01Header : BaseTheme.palette.icon02 } size = { 20 } src = { IconHelp } /> ), headerTitleStyle: { color: BaseTheme.palette.text01 } }; /** * Screen options for conference. */ export const conferenceScreenOptions = { ...fullScreenOptions }; /** * Screen options for lobby modal. */ export const lobbyScreenOptions = { ...fullScreenOptions }; /** * Tab bar options for chat screen. */ export const chatTabBarOptions = { tabBarActiveTintColor: BaseTheme.palette.screen01Header, tabBarLabelStyle: { fontSize: BaseTheme.typography.labelRegular.fontSize }, tabBarInactiveTintColor: BaseTheme.palette.text01, tabBarIndicatorStyle: { backgroundColor: BaseTheme.palette.screen01Header } }; /** * Screen options for presentation type modals. */ export const presentationScreenOptions = { ...conferenceModalPresentation, headerBackTitleVisible: false, headerLeft: () => { const { t } = useTranslation(); if (Platform.OS === 'ios') { return ( <HeaderNavigationButton label = { t('dialog.close') } onPress = { goBack } /> ); } return ( <HeaderNavigationButton onPress = { goBack } src = { IconClose } /> ); }, headerStatusBarHeight: 0, headerStyle: { backgroundColor: BaseTheme.palette.screen01Header }, headerTitleStyle: { color: BaseTheme.palette.text01 } }; /** * Screen options for chat. */ export const chatScreenOptions = { ...presentationScreenOptions }; /** * Screen options for invite modal. */ export const inviteScreenOptions = { ...presentationScreenOptions }; /** * Screen options for participants modal. */ export const participantsScreenOptions = { ...presentationScreenOptions }; /** * Screen options for speaker stats modal. */ export const speakerStatsScreenOptions = { ...presentationScreenOptions }; /** * Screen options for security options modal. */ export const securityScreenOptions = { ...presentationScreenOptions }; /** * Screen options for recording modal. */ export const recordingScreenOptions = { ...presentationScreenOptions }; /** * Screen options for live stream modal. */ export const liveStreamScreenOptions = { ...presentationScreenOptions }; /** * Screen options for salesforce link modal. */ export const salesforceScreenOptions = presentationScreenOptions; /** * Screen options for GIPHY integration modal. */ export const gifsMenuOptions = presentationScreenOptions; /** * Screen options for shared document. */ export const sharedDocumentScreenOptions = { ...TransitionPresets.DefaultTransition, headerBackTitleVisible: false, headerShown: true, headerStyle: { backgroundColor: BaseTheme.palette.screen01Header }, headerTitleStyle: { color: BaseTheme.palette.text01 } };
app/jsx/account_course_user_search/NewCourseModal.js
venturehive/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import React from 'react' import {arrayOf} from 'prop-types' import I18n from 'i18n!account_course_user_search' import Modal from 'jsx/shared/modal' import ModalContent from '../shared/modal-content' import ModalButtons from '../shared/modal-buttons' import CoursesStore from './CoursesStore' import TermsStore from './TermsStore' import AccountsTreeStore from './AccountsTreeStore' import IcInput from './IcInput' import IcSelect from './IcSelect' import 'compiled/jquery.rails_flash_notifications' export default class NewCourseModal extends React.Component { static propTypes = { terms: arrayOf(TermsStore.PropType), accounts: arrayOf(AccountsTreeStore.PropType) } constructor () { super() this.state = { isOpen: false, data: {}, errors: {} } } openModal() { this.setState({ isOpen: true }) } closeModal = () => { this.setState({ isOpen: false, data: {}, errors: {} }) } onChange(field, value) { this.setState({ data: { ...this.state.data, [field]: value }, errors: {} }) } onSubmit = () => { const { data } = this.state const errors = {} if (!data.name) errors.name = I18n.t('Course name is required') if (!data.course_code) errors.course_code = I18n.t('Reference code is required') if (Object.keys(errors).length) { this.setState({ errors }) return } // TODO: error handling const promise = $.Deferred() CoursesStore.create({ course: data }).then(() => { this.closeModal() $.flashMessage( I18n.t('%{course_name} successfully added!', { course_name: data.name }) ) promise.resolve() }) return promise } renderAccountOptions(accounts=this.props.accounts, depth=0) { return accounts.map(account => [ <option key={account.id} value={account.id}> {Array(2 * depth + 1).join('\u00a0') + account.name} </option> ].concat( this.renderAccountOptions(account.subAccounts || [], depth + 1) ) ) } renderTermOptions() { return (this.props.terms || []).map(term => <option key={term.id} value={term.id}> {term.name} </option> ) } render() { const { data, isOpen, errors } = this.state const onChange = field => e => this.onChange(field, e.target.value) return ( <Modal className="ReactModal__Content--canvas ReactModal__Content--mini-modal" isOpen={isOpen} title={I18n.t('Add a New Course')} onRequestClose={this.closeModal} onSubmit={this.onSubmit} contentLabel={I18n.t('Add a New Course')} > <ModalContent> <IcInput className="name" label={I18n.t('Course Name')} value={data.name} error={errors.name} onChange={onChange('name')} /> <IcInput className="course_code" label={I18n.t('Reference Code')} value={data.course_code} error={errors.course_code} onChange={onChange('course_code')} /> <IcSelect className="account_id" label={I18n.t('Subaccount')} value={data.account_id} onChange={onChange('account_id')} > {this.renderAccountOptions()} </IcSelect> <IcSelect className="enrollment_term_id" label={I18n.t('Enrollment Term')} value={data.enrollment_term_id} onChange={onChange('enrollment_term_id')} > {this.renderTermOptions()} </IcSelect> </ModalContent> <ModalButtons> <button type="button" className="Button" onClick={this.closeModal}> {I18n.t('Cancel')} </button> <button type="submit" className="Button Button--primary"> {I18n.t('Add Course')} </button> </ModalButtons> </Modal> ) } }
docs/src/app/components/pages/components/FloatingActionButton/Page.js
mmrtnz/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import floatingButtonReadmeText from './README'; import floatingButtonExampleSimpleCode from '!raw!./ExampleSimple'; import FloatingButtonExampleSimple from './ExampleSimple'; import floatingButtonCode from '!raw!material-ui/FloatingActionButton/FloatingActionButton'; const FloatingActionButtonPage = () => ( <div> <Title render={(previousTitle) => `Floating Action Button - ${previousTitle}`} /> <MarkdownElement text={floatingButtonReadmeText} /> <CodeExample code={floatingButtonExampleSimpleCode}> <FloatingButtonExampleSimple /> </CodeExample> <PropTypeDescription code={floatingButtonCode} /> </div> ); export default FloatingActionButtonPage;
ignite/Examples/Containers/ignite-ir-boilerplate/RowExample.js
Ezeebube5/Nairasense
import React from 'react' import { View, Text, ListView } from 'react-native' import { connect } from 'react-redux' // Styles import styles from './Styles/RowExampleStyle' class RowExample extends React.Component { constructor (props) { super(props) // If you need scroll to bottom, consider http://bit.ly/2bMQ2BZ /* *********************************************************** * STEP 1 * This is an array of objects with the properties you desire * Usually this should come from Redux mapStateToProps *************************************************************/ const dataObjects = [ {title: 'First Title', description: 'First Description'}, {title: 'Second Title', description: 'Second Description'}, {title: 'Third Title', description: 'Third Description'}, {title: 'Fourth Title', description: 'Fourth Description'}, {title: 'Fifth Title', description: 'Fifth Description'}, {title: 'Sixth Title', description: 'Sixth Description'}, {title: 'Seventh Title', description: 'Seventh Description'} ] /* *********************************************************** * STEP 2 * Teach datasource how to detect if rows are different * Make this function fast! Perhaps something like: * (r1, r2) => r1.id !== r2.id} *************************************************************/ const rowHasChanged = (r1, r2) => r1 !== r2 // DataSource configured const ds = new ListView.DataSource({rowHasChanged}) // Datasource is always in state this.state = { dataSource: ds.cloneWithRows(dataObjects) } } /* *********************************************************** * STEP 3 * `_renderRow` function -How each cell/row should be rendered * It's our best practice to place a single component here: * * e.g. return <MyCustomCell title={rowData.title} description={rowData.description} /> *************************************************************/ _renderRow (rowData) { return ( <View style={styles.row}> <Text style={styles.boldLabel}>{rowData.title}</Text> <Text style={styles.label}>{rowData.description}</Text> </View> ) } /* *********************************************************** * STEP 4 * If your datasource is driven by Redux, you'll need to * reset it when new data arrives. * DO NOT! place `cloneWithRows` inside of render, since render * is called very often, and should remain fast! Just replace * state's datasource on newProps. * * e.g. componentWillReceiveProps (newProps) { if (newProps.someData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(newProps.someData) }) } } *************************************************************/ // Used for friendly AlertMessage // returns true if the dataSource is empty _noRowData () { return this.state.dataSource.getRowCount() === 0 } // Render a footer. _renderFooter = () => { return ( <Text> - Footer - </Text> ) } render () { return ( <View style={styles.container}> <ListView contentContainerStyle={styles.listContent} dataSource={this.state.dataSource} renderRow={this._renderRow} renderFooter={this._renderFooter} enableEmptySections pageSize={15} /> </View> ) } } const mapStateToProps = (state) => { return { // ...redux state to props here } } const mapDispatchToProps = (dispatch) => { return { } } export default connect(mapStateToProps, mapDispatchToProps)(RowExample)
js/App/Components/SensorDetails/SubViews/CalendarModalComponent.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { TouchableOpacity, ScrollView } from 'react-native'; import { Calendar } from 'react-native-calendars'; import Modal from 'react-native-modal'; let dayjs = require('dayjs'); let utc = require('dayjs/plugin/utc'); let timezone = require('dayjs/plugin/timezone'); dayjs.extend(utc); dayjs.extend(timezone); const isEqual = require('react-fast-compare'); import DeviceInfo from 'react-native-device-info'; import { View, Poster, Text, FormattedDate, } from '../../../../BaseComponents'; import CalendarDay from './CalendarDay'; import { withTheme, PropsThemedComponent, } from '../../HOC/withTheme'; import i18n from '../../../Translations/common'; import Theme from '../../../Theme'; type Props = PropsThemedComponent & { isVisible: boolean, current: any, onPressPositive: (any) => void, onPressNegative: () => void, appLayout: Object, intl: Object, maxDate: string, propToUpdate: 1 | 2, timestamp: Object, gatewayTimezone: string, }; type DefaultProps = { isVisible: boolean, }; class CalendarModalComponent extends View<Props, null> { props: Props; static defaultProps: DefaultProps = { isVisible: false, }; isTablet: boolean; static getDerivedStateFromProps(props: Object, state: Object): null | Object { const { isVisible, current } = props; if (isVisible !== state.isVisible) { return { isVisible, current, }; } if ((current !== state.current) && !state.isVisible) { return { current, isVisible, }; } return null; } onPressPositive: () => void; onPressNegative: () => void; onDayPress: (Object) => void; renderDay: (Object) => void; constructor(props: Props) { super(props); this.state = { current: props.current, isVisible: props.isVisible, }; this.isTablet = DeviceInfo.isTablet(); this.onPressPositive = this.onPressPositive.bind(this); this.onPressNegative = this.onPressNegative.bind(this); this.onDayPress = this.onDayPress.bind(this); this.renderDay = this.renderDay.bind(this); const { formatMessage } = props.intl; this.ok = formatMessage(i18n.defaultPositiveText); this.cancel = formatMessage(i18n.defaultNegativeText); } onPressPositive() { const { onPressPositive } = this.props; const { current } = this.state; if (onPressPositive) { onPressPositive(current); } } onPressNegative() { const { onPressNegative } = this.props; if (onPressNegative) { onPressNegative(); } } shouldComponentUpdate(nextProps: Object, nextState: Object): boolean { const isStateEqual = isEqual(this.state, nextState); const isLayoutEqual = isEqual(this.props.appLayout, nextProps.appLayout); const isMaxDateEqual = nextProps.maxDate === this.props.maxDate; return (nextState.isVisible || this.state.isVisible) && (!isStateEqual || !isLayoutEqual || isMaxDateEqual); } onDayPress(day: Object) { const { propToUpdate, gatewayTimezone } = this.props; if (gatewayTimezone) { dayjs.tz.setDefault(gatewayTimezone); } // The received timestamp is in GMT also start of the day timestamp in milliseconds let { timestamp } = day; timestamp = timestamp / 1000; // Converting UTC start of the day[SOD] timestap to user's locale SOD let selectedTimestamp = dayjs.unix(timestamp).startOf('day').unix(); // While choosing 'to' date if (propToUpdate === 2) { const todayDate = dayjs().format('YYYY-MM-DD'); const timestampAsDate = dayjs.unix(timestamp).format('YYYY-MM-DD'); // Use end of the day[EOD] timestamp, also dayjs converts UTC to user's locale selectedTimestamp = dayjs.unix(timestamp).endOf('day').unix(); // If 'to' date is today then use 'now/current time' timestamp if (timestampAsDate === todayDate) { selectedTimestamp = parseInt(dayjs().format('X'), 10); } } dayjs.tz.setDefault(); this.setState({ current: selectedTimestamp, }); } renderDay({date, state, marking}: Object): Object { const props = { date, state, marking, onDayPress: this.onDayPress, appLayout: this.props.appLayout, }; return ( <CalendarDay {...props} /> ); } getMarkedDatesAndPosterDate(current: number, gatewayTimezone: string): Object { if (gatewayTimezone) { dayjs.tz.setDefault(gatewayTimezone); } const posterDate = dayjs.unix(current); let currentMark = dayjs.unix(current).format('YYYY-MM-DD'); let { timestamp, propToUpdate } = this.props, markedDates = {}; let { fromTimestamp, toTimestamp } = timestamp; let startDate = dayjs.unix(fromTimestamp).format('YYYY-MM-DD'), endDate = dayjs.unix(toTimestamp).format('YYYY-MM-DD'); if (propToUpdate === 1) { startDate = dayjs.unix(current).format('YYYY-MM-DD'); } else { endDate = dayjs.unix(current).format('YYYY-MM-DD'); } markedDates[startDate] = {marked: true, startingDay: true, selected: currentMark === startDate}; const diff = dayjs(endDate).diff(dayjs(startDate), 'day'); if (diff <= 0) { if (dayjs(currentMark).isBefore(startDate)) { markedDates[currentMark] = {marked: true, selected: true, endingDay: true}; } if (startDate === currentMark) { markedDates[startDate] = {marked: true, startingDay: true, selected: true, endingDay: true}; } dayjs.tz.setDefault(); return { markedDates, posterDate, }; } let temp = startDate; for (let i = 0; i < diff; i++) { temp = dayjs(temp).add(1, 'd').format('YYYY-MM-DD'); markedDates[temp] = {marked: true, endingDay: i === (diff - 1), selected: temp === currentMark}; } dayjs.tz.setDefault(); return { markedDates, posterDate, }; } render(): Object { const { current, isVisible } = this.state; const { appLayout, maxDate, gatewayTimezone, } = this.props; const { containerStyle, posterWidth, posterHeight, posterItemsStyle, posterTextOneStyle, posterTextTwoStyle, calendarTheme, footerStyle, positiveLabelStyle, negativeLabelStyle, } = this.getStyle(appLayout); const { markedDates, posterDate, } = this.getMarkedDatesAndPosterDate(current, gatewayTimezone); return ( <Modal isVisible={isVisible} hideModalContentWhileAnimating={true} supportedOrientations={['portrait', 'landscape']} onRequestClose={this.onPressNegative}> <ScrollView style={{flex: 1}} contentContainerStyle={containerStyle}> <Poster posterWidth={posterWidth} posterHeight={posterHeight}> <View style={posterItemsStyle}> <FormattedDate value={posterDate} year="numeric" style={posterTextOneStyle} level={33}/> <FormattedDate value={posterDate} day="numeric" month="short" weekday="short" style={posterTextTwoStyle} level={33}/> </View> </Poster> <Calendar markedDates={{ ...markedDates, }} maxDate={maxDate} dayComponent={this.renderDay} theme={calendarTheme} firstDay={1}/> <View style={footerStyle}> <TouchableOpacity onPress={this.onPressNegative}> <Text style={negativeLabelStyle}> {this.cancel} </Text> </TouchableOpacity> <TouchableOpacity onPress={this.onPressPositive}> <Text style={positiveLabelStyle}> {this.ok} </Text> </TouchableOpacity> </View> </ScrollView> </Modal> ); } getStyle(appLayout: Object): Object { const { colors, } = this.props; const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const { offlineColor, fontSizeFactorFive, } = Theme.Core; const adjustCelendar = !this.isTablet && !isPortrait; const posterHeight = adjustCelendar ? deviceWidth * 0.12 : deviceWidth * 0.25; const fontSizePosterTextOne = posterHeight * 0.2; const fontSizePosterTextTwo = posterHeight * 0.25; const fontSizeFooterText = adjustCelendar ? deviceWidth * 0.03 : deviceWidth * fontSizeFactorFive; const footerPadding = adjustCelendar ? fontSizeFooterText * 0.5 : fontSizeFooterText; const { inAppBrandSecondary, card, textFour, } = colors; return { containerStyle: { flexGrow: 1, justifyContent: 'center', }, posterWidth: width, posterHeight, posterItemsStyle: { flex: 1, position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, paddingLeft: 15, justifyContent: 'center', alignItems: 'flex-start', }, posterTextOneStyle: { fontSize: fontSizePosterTextOne, }, posterTextTwoStyle: { fontSize: fontSizePosterTextTwo, fontWeight: '500', }, calendarTheme: { backgroundColor: card, calendarBackground: card, textSectionTitleColor: offlineColor, selectedDayBackgroundColor: inAppBrandSecondary, todayTextColor: '#00adf5', arrowColor: textFour, monthTextColor: textFour, 'stylesheet.calendar.main': { week: { marginTop: 0, marginBottom: 0, flexDirection: 'row', justifyContent: 'space-around', }, }, }, footerStyle: { flexDirection: 'row', backgroundColor: card, justifyContent: 'flex-end', paddingVertical: footerPadding, paddingRight: adjustCelendar ? 10 : 0, }, positiveLabelStyle: { color: inAppBrandSecondary, fontSize: fontSizeFooterText, marginLeft: 20, marginRight: 15, }, negativeLabelStyle: { color: textFour, fontSize: fontSizeFooterText, }, }; } } export default (withTheme(CalendarModalComponent): Object);
client/scripts/components/WordCloud.js
ahoarfrost/metaseek
import React from 'react'; import { TagCloud } from 'react-tagcloud'; import ReactTooltip from 'react-tooltip'; var WordCloud = React.createClass({ getInitialState : function() { return {} }, showHover : function(value, event) { this.setState({"hoverValue":value}); }, render : function() { // Colors from color brewer http://colorbrewer2.org/#type=sequential&scheme=PuBuGn&n=8 // Order matters - higher values will get the later colors in this list // Another good option http://colorbrewer2.org/?type=sequential&scheme=BuGn&n=7 // var colors = ['#a6bddb','#67a9cf','#3690c0','#02818a','#016450']; var colors = [ "#516DBB", "#7188C7", "#24C991", "#1fb380", "#1A9C6E", "#16825C" ]; // Min / max font sizes in pixels for words in word cloud var min = 8; var max = 40; // has to be pretty small to fit in the word cloud box // this.props.wordinput is a field name that can be changed by the user // pull the right summary data from activeSummaryData var activeField = this.props.wordinput; var activeFieldData = this.props.activeSummaryData[activeField]; // remove nulls / boring values var activeFieldDataValidKeys = Object.keys(activeFieldData).filter( function(value, index) { if (value == "no data" || value == "other categories") { return false; // skip } else { return true; } } ); // Format data the way TagCloud wants it var wordCloudData = activeFieldDataValidKeys.map( function(value,index) { var count = activeFieldData[value]; return {"value":value,"count":count}; } ); // Use a customRenderer so we can make the color scale with the value vs. be random var customRenderer = function(tag, size) { // Find how far in between min and max the tag size is, find the right color for that slot var colorScaler = ((size - min) / (max - min)) * (colors.length - 1); var color = colors[Math.floor(Math.random() * colors.length)]; // var color = colors[Math.floor(colorScaler)]; // More styles in css for word-cloud-tag - only on-the-fly calculated styles go here return <div className='word-cloud-tag-wrapper'> <span key={activeField + '-word-' + tag.value} data-tip data-for={activeField + '-tip-' + tag.value} className='word-cloud-tag' style={{ fontSize: size + 'px', color: color }}> {tag.value} </span> <ReactTooltip id={activeField + '-tip-' + tag.value} key={activeField + '-tip-' + tag.value} className="word-cloud-tooltip" place="top" type="light" effect="solid" border={true} > <span>{tag.value + " : " + activeFieldData[tag.value] + ' datasets'}</span> </ReactTooltip> </div> }; return( <div> <TagCloud tags={wordCloudData} minSize={min} maxSize={max} renderer={customRenderer} /> </div> )} }); export default WordCloud;
client/gatsby-browser.js
HKuz/FreeCodeCamp
import React from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import { createStore } from './src/redux/createStore'; import AppMountNotifier from './src/components/AppMountNotifier'; import GuideNavContextProvider from './src/contexts/GuideNavigationContext'; const store = createStore(); export const wrapRootElement = ({ element }) => { return ( <Provider store={store}> <GuideNavContextProvider> <AppMountNotifier render={() => element} /> </GuideNavContextProvider> </Provider> ); }; wrapRootElement.propTypes = { element: PropTypes.any };
fields/types/html/HtmlField.js
wustxing/keystone
import _ from 'underscore'; import Field from '../Field'; import React from 'react'; import tinymce from 'tinymce'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on underscore */ var lastId = 0; function getId() { return 'keystone-html-' + lastId++; } module.exports = Field.create({ displayName: 'HtmlField', getInitialState () { return { id: getId(), isFocused: false }; }, initWysiwyg () { if (!this.props.wysiwyg) return; var self = this; var opts = this.getOptions(); opts.setup = function (editor) { self.editor = editor; editor.on('change', self.valueChanged); editor.on('focus', self.focusChanged.bind(self, true)); editor.on('blur', self.focusChanged.bind(self, false)); }; this._currentValue = this.props.value; tinymce.init(opts); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.initWysiwyg(); } if (_.isEqual(this.props.dependsOn, this.props.currentDependencies) && !_.isEqual(this.props.currentDependencies, prevProps.currentDependencies)) { var instance = tinymce.get(prevState.id); if (instance) { tinymce.EditorManager.execCommand('mceRemoveEditor', true, prevState.id); this.initWysiwyg(); } else { this.initWysiwyg(); } } }, componentDidMount () { this.initWysiwyg(); }, componentWillReceiveProps (nextProps) { if (this.editor && this._currentValue !== nextProps.value) { this.editor.setContent(nextProps.value); } }, focusChanged (focused) { this.setState({ isFocused: focused }); }, valueChanged () { var content; if (this.editor) { content = this.editor.getContent(); } else if (this.refs.editor) { content = this.refs.editor.getDOMNode().value; } else { return; } this._currentValue = content; this.props.onChange({ path: this.props.path, value: content }); }, getOptions () { var plugins = ['code', 'link'], options = _.defaults( {}, this.props.wysiwyg, Keystone.wysiwyg.options ), toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | link', i; if (options.enableImages) { plugins.push('image'); toolbar += ' | image'; } if (options.enableCloudinaryUploads || options.enableS3Uploads) { plugins.push('uploadimage'); toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage'; } if (options.additionalButtons) { var additionalButtons = options.additionalButtons.split(','); for (i = 0; i < additionalButtons.length; i++) { toolbar += (' | ' + additionalButtons[i]); } } if (options.additionalPlugins) { var additionalPlugins = options.additionalPlugins.split(','); for (i = 0; i < additionalPlugins.length; i++) { plugins.push(additionalPlugins[i]); } } if (options.importcss) { plugins.push('importcss'); var importcssOptions = { content_css: options.importcss, importcss_append: true, importcss_merge_classes: true }; _.extend(options.additionalOptions, importcssOptions); } if (!options.overrideToolbar) { toolbar += ' | code'; } var opts = { selector: '#' + this.state.id, toolbar: toolbar, plugins: plugins, menubar: options.menubar || false, skin: options.skin || 'keystone' }; if (this.shouldRenderField()) { opts.uploadimage_form_url = options.enableS3Uploads ? '/keystone/api/s3/upload' : '/keystone/api/cloudinary/upload'; } else { _.extend(opts, { mode: 'textareas', readonly: true, menubar: false, toolbar: 'code', statusbar: false }); } if (options.additionalOptions){ _.extend(opts, options.additionalOptions); } return opts; }, getFieldClassName () { var className = this.props.wysiwyg ? 'wysiwyg' : 'code'; return className; }, renderField () { var className = this.state.isFocused ? 'is-focused' : ''; var style = { height: this.props.height }; return ( <div className={className}> <FormInput multiline ref='editor' style={style} onChange={this.valueChanged} id={this.state.id} className={this.getFieldClassName()} name={this.props.path} value={this.props.value} /> </div> ); }, renderValue () { return <FormInput multiline noedit value={this.props.value} />; } });
src/components/stock/Stock.js
sebalopez111/countdown
import React, { Component } from 'react'; import moment from 'moment'; var embeddedScript = '<!-- TradingView Widget BEGIN -->' + ' <script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script>' + ' <script type="text/javascript">' + ' new TradingView.widget({' + ' "autosize": true,' + ' "symbol": "ARRS",' + ' "interval": "D",' + ' "timezone": "Etc/UTC",' + ' "theme": "Grey",' + ' "style": "3",' + ' "locale": "en",' + ' "toolbar_bg": "rgba(7, 55, 99, 1)",' + ' "hide_top_toolbar": true,' + ' "save_image": false,' + ' "details": true,' + ' "hideideas": true' + ' });' + ' </script>' + ' <!-- TradingView Widget END -->'; var Stock = React.createClass({ displayName: 'Stock', render: function() { return React.createElement('div', { id: "___stock" }, { __html: embeddedScript }); } }); export default { Stock : Stock }
src/Parser/Priest/Shadow/Modules/Features/AlwaysBeCasting.js
enragednuke/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'Main/StatisticBox'; import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting'; import SPELLS from 'common/SPELLS'; class AlwaysBeCasting extends CoreAlwaysBeCasting { static ABILITIES_ON_GCD = [ // handled in _removebuff SPELLS.VOID_TORRENT.id, SPELLS.MIND_FLAY.id, // SPELLS.DISPERSION.id, // rotational: SPELLS.VOID_BOLT.id, SPELLS.VOID_ERUPTION.id, SPELLS.MIND_BLAST.id, SPELLS.VAMPIRIC_TOUCH.id, SPELLS.SHADOW_WORD_DEATH.id, SPELLS.SHADOW_WORD_PAIN.id, SPELLS.SHADOWFIEND.id, SPELLS.SHADOWFIEND_WITH_GLYPH_OF_THE_SHA.id, // talents: SPELLS.MINDBENDER_TALENT_SHADOW.id, SPELLS.POWER_INFUSION_TALENT.id, SPELLS.SHADOW_CRASH_TALENT.id, SPELLS.SHADOW_WORD_VOID_TALENT.id, SPELLS.MIND_BOMB_TALENT.id, // utility: SPELLS.SHADOWFORM.id, SPELLS.MIND_VISION.id, SPELLS.POWER_WORD_SHIELD.id, SPELLS.SHADOW_MEND.id, SPELLS.DISPEL_MAGIC.id, SPELLS.MASS_DISPEL.id, SPELLS.LEVITATE.id, SPELLS.SHACKLE_UNDEAD.id, SPELLS.PURIFY_DISEASE.id, ]; get suggestionThresholds() { return { actual: this.downtimePercentage, isGreaterThan: { minor: 0.1, average: 0.15, major: 0.2, }, style: 'percentage', }; } suggestions(when) { const { actual, isGreaterThan: { minor, average, major, }, } = this.suggestionThresholds; when(actual).isGreaterThan(minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your downtime can be improved. Try to Always Be Casting (ABC), try to reduce the delay between casting spells. Even if you have to move, try casting something instant - maybe refresh your dots.</span>) .icon('spell_mage_altertime') .actual(`${formatPercentage(actual)}% downtime`) .recommended(`<${formatPercentage(recommended)}% is recommended`) .regular(average).major(major); }); } statisticOrder = STATISTIC_ORDER.CORE(6); } export default AlwaysBeCasting;
js/containers/NewChallengeContainer.js
SamyZ/BoomApp
import React from 'react'; import { connect } from 'react-redux'; import { Navigator } from 'react-native'; import { createChallenge } from '../actions/challengesActions'; import SportView from '../views/newChallenge/SportView'; import ExerciseView from '../views/newChallenge/ExerciseView'; import FriendsView from '../views/newChallenge/FriendsView'; import PrizeView from '../views/newChallenge/PrizeView'; import SummaryView from '../views/newChallenge/SummaryView'; import NavBarView from '../views/newChallenge/NavBarView'; const propTypes = { navigator: React.PropTypes.object, dispatch: React.PropTypes.func, }; const routeStack = [ { name: 'Sport', index: 0 }, { name: 'Exercise', index: 1 }, { name: 'Friends', index: 2 }, { name: 'Prize', index: 3 }, { name: 'Summary', index: 4 }, ]; class NewChallengeContainer extends React.Component { constructor(props) { super(props); this.state = { duration: { value: '2', unit: 'weeks' }, objective: {}, repetition: 7, }; } onChallengeUpdate = (challenge) => this.setState({ ...this.state, ...challenge }); configureScene = (/* route, routeStack */) => ({ ...Navigator.SceneConfigs.PushFromRight, gestures: {} }) navigateBackward = (leaveChallengeCreation) => { if (leaveChallengeCreation) { this.props.navigator.pop(); } else { this.challengeNavigator.jumpBack(); this.forceUpdate(); } } navigateForward = (leaveChallengeCreation) => { if (leaveChallengeCreation) { this.props.dispatch(createChallenge(this.state)); this.props.navigator.pop(); } else { this.challengeNavigator.jumpForward(); this.forceUpdate(); } } renderScene = (route) => { switch (route.name) { default: case 'Sport': return ( <SportView onChallengeUpdate={this.onChallengeUpdate} />); case 'Exercise': return ( <ExerciseView onChallengeUpdate={this.onChallengeUpdate} />); case 'Friends': return ( <FriendsView onChallengeUpdate={this.onChallengeUpdate} />); case 'Prize': return ( <PrizeView onChallengeUpdate={this.onChallengeUpdate} />); case 'Summary': return ( <SummaryView challenge={this.state} onSave={this.onSave} />); } } render = () => ( <Navigator ref={(challengeNavigator) => { this.challengeNavigator = challengeNavigator; }} initialRoute={routeStack[0]} initialRouteStack={routeStack} renderScene={this.renderScene} configureScene={this.configureScene} navigationBar={ <NavBarView routeStack={routeStack} navigateBackward={this.navigateBackward} navigateForward={this.navigateForward} challenge={this.state} />} /> ); } NewChallengeContainer.propTypes = propTypes; export default connect()(NewChallengeContainer);
admin/client/App/shared/FlashMessages.js
pr1ntr/keystone
/** * Render a few flash messages, e.g. errors, success messages, warnings,... * * Use like this: * <FlashMessages * messages={{ * error: [{ * title: 'There is a network problem', * detail: 'Please try again later...', * }], * }} * /> * * Instead of error, it can also be hilight, info, success or warning */ import React from 'react'; import _ from 'lodash'; import FlashMessage from './FlashMessage'; var FlashMessages = React.createClass({ displayName: 'FlashMessages', propTypes: { messages: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.shape({ error: React.PropTypes.array, hilight: React.PropTypes.array, info: React.PropTypes.array, success: React.PropTypes.array, warning: React.PropTypes.array, }), ]), }, // Render messages by their type renderMessages (messages, type) { if (!messages || !messages.length) return null; return messages.map((message, i) => { return <FlashMessage message={message} type={type} key={`i${i}`} />; }); }, // Render the individual messages based on their type renderTypes (types) { return Object.keys(types).map(type => this.renderMessages(types[type], type)); }, render () { if (!this.props.messages) return null; return ( <div className="flash-messages"> {_.isPlainObject(this.props.messages) && this.renderTypes(this.props.messages)} </div> ); }, }); module.exports = FlashMessages;
step8-unittest/node_modules/enzyme/src/ShallowTraversal.js
jintoppy/react-training
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import isSubset from 'is-subset'; import { coercePropValue, propsOfNode, splitSelector, isCompoundSelector, selectorType, AND, SELECTOR, nodeHasType, } from './Utils'; export function childrenOfNode(node) { if (!node) return []; const maybeArray = propsOfNode(node).children; const result = []; React.Children.forEach(maybeArray, child => { if (child !== null && child !== false && typeof child !== 'undefined') { result.push(child); } }); return result; } export function hasClassName(node, className) { let classes = propsOfNode(node).className || ''; classes = classes.replace(/\s/g, ' '); return ` ${classes} `.indexOf(` ${className} `) > -1; } export function treeForEach(tree, fn) { if (tree !== null && tree !== false && typeof tree !== 'undefined') { fn(tree); } childrenOfNode(tree).forEach(node => treeForEach(node, fn)); } export function treeFilter(tree, fn) { const results = []; treeForEach(tree, node => { if (fn(node)) { results.push(node); } }); return results; } function pathFilter(path, fn) { return path.filter(tree => treeFilter(tree, fn).length !== 0); } export function pathToNode(node, root) { const queue = [root]; const path = []; const hasNode = (testNode) => node === testNode; while (queue.length) { const current = queue.pop(); const children = childrenOfNode(current); if (current === node) return pathFilter(path, hasNode); path.push(current); if (children.length === 0) { // leaf node. if it isn't the node we are looking for, we pop. path.pop(); } queue.push.apply(queue, children); } return null; } export function parentsOfNode(node, root) { return pathToNode(node, root).reverse(); } export function nodeHasId(node, id) { return propsOfNode(node).id === id; } export function nodeHasProperty(node, propKey, stringifiedPropValue) { const nodeProps = propsOfNode(node); const propValue = coercePropValue(propKey, stringifiedPropValue); const descriptor = Object.getOwnPropertyDescriptor(nodeProps, propKey); if (descriptor && descriptor.get) { return false; } const nodePropValue = nodeProps[propKey]; if (nodePropValue === undefined) { return false; } if (propValue) { return nodePropValue === propValue; } return nodeProps.hasOwnProperty(propKey); } export function nodeMatchesObjectProps(node, props) { return isSubset(propsOfNode(node), props); } export function buildPredicate(selector) { switch (typeof selector) { case 'function': // selector is a component constructor return node => node && node.type === selector; case 'string': if (isCompoundSelector.test(selector)) { return AND(splitSelector(selector).map(buildPredicate)); } switch (selectorType(selector)) { case SELECTOR.CLASS_TYPE: return node => hasClassName(node, selector.substr(1)); case SELECTOR.ID_TYPE: return node => nodeHasId(node, selector.substr(1)); case SELECTOR.PROP_TYPE: { const propKey = selector.split(/\[([a-zA-Z\-]*?)(=|\])/)[1]; const propValue = selector.split(/=(.*?)\]/)[1]; return node => nodeHasProperty(node, propKey, propValue); } default: // selector is a string. match to DOM tag or constructor displayName return node => nodeHasType(node, selector); } case 'object': if (!Array.isArray(selector) && selector !== null && !isEmpty(selector)) { return node => nodeMatchesObjectProps(node, selector); } throw new TypeError( 'Enzyme::Selector does not support an array, null, or empty object as a selector' ); default: throw new TypeError('Enzyme::Selector expects a string, object, or Component Constructor'); } } export function getTextFromNode(node) { if (node === null || node === undefined) { return ''; } if (typeof node === 'string' || typeof node === 'number') { return String(node); } if (node.type && typeof node.type === 'function') { return `<${node.type.displayName || node.type.name} />`; } return childrenOfNode(node).map(getTextFromNode) .join('') .replace(/\s+/, ' '); }
dashboard/client/src/js/components/modules/EventVariationLineGraph.js
jigarjain/sieve
import React from 'react'; import {ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts'; import Loader from './base/Loader'; import Helpers from '../../utils/helpers'; /** * Renders a Line graph of for control & variations for each goal * * @param {Array} graphData * @param {Array} variations * @param {Array} colors * * @return {ReactElement} */ function renderGraph(graphData, variations, colors) { const interval = Math.floor(graphData.length / 15); return ( <ResponsiveContainer width="100%" height={500} > <LineChart width={600} height={300} data={graphData} margin={{top: 0, right: 0, left: 0, bottom: 0}} > <XAxis dataKey="timeLabel" interval={interval} domain={['dataMin', 'dataMax + 2']} /> <YAxis domain={['dataMin', 'dataMax + 2']} /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> { variations.map((v, i) => { return ( <Line key={v.id} type="monotone" name={v.name} dataKey={`variations.${v.id}`} stroke={colors[i % colors.length]} /> ); }) } </LineChart> </ResponsiveContainer> ); } export default function (props) { if (props.timelineApiStatus.isFetching) { return <Loader />; } if (props.timelineApiStatus.errors) { return <div className="has-text-centered">Some error occured</div>; } if (!props.expTimeline) { return <div className="has-text-centered">No data for reports to show</div>; } if (!props.selectedEvent) { return <div className="has-text-centered">Please select an event for which the graph needs to be shown</div>; } const colors = Helpers.getColors(); const graphData = props.expTimeline.eventTimeline[props.selectedEvent]; if (!graphData) { return <div className="has-text-centered">{`No reports present for event - ${props.selectedEvent}`}</div>; } return ( <div className="graph-holder"> {renderGraph(graphData, props.variations, colors)} </div> ); }
src/bundles/Story/scenes/StoryScene/index.js
CharlesMangwa/Chloe
/* @flow */ import React from 'react' import StoryContainer from '@Story/containers/StoryContainer' type Props = { current: Object, pages: Array<Object>, period: string, } const StoryScene = (props: Props): React$Element<any> => ( <StoryContainer current={props.current} pages={props.pages} period={props.period} /> ) export default StoryScene
src/components/picker-core/index.js
summerstream/react-practise
import React, { Component } from 'react'; import styles from './styles.js'; class PickerCore extends Component{ constructor(props){ super(props); this._startPosition = 0; this._dist = 0; this._translateY = 0; this._initValue = this.props.current; this._current = this.props.current; this._eventType = 'touch'; this._eventState=0;//0:initial 1:has started 2:has moved this._mouseMoveAllowed = false; Object.assign(styles.container, this.props.containerStyle); Object.assign(styles.item, this.props.itemStyle); this.start = this.start.bind(this); this.move = this.move.bind(this); this.stop = this.stop.bind(this); } start(e){ // console.info('picker start'); this._eventState = 1; if(e.pageY){ this._eventType = 'mouse'; this._mouseMoveAllowed = true; }else{ this._eventType = 'touch'; } this._startPosition = e.targetTouches && e.targetTouches[0].pageY || e.pageY; this.refs.list.style.transition = 'none'; this._beginTime = (new Date()).getTime(); } move(e){ if(e.pageY && !this._mouseMoveAllowed){ return; } // console.info('picker move'); this._eventState = 2; if(this._eventType == 'mouse'){ e.preventDefault(); } e.stopPropagation(); var dist = (e.targetTouches && e.targetTouches[0].pageY || e.pageY) - this._startPosition; this._dist = dist; // console.info('move _translateY:'+this._translateY); // console.info('move dist:'+dist); var y = this._translateY + dist; if(y>this._scrollRange[0]){ y = this._scrollRange[0]+this.getBezier(y-this._scrollRange[0]); }else if(y<this._scrollRange[1]){ y = this._scrollRange[1]-this.getBezier(this._scrollRange[1] - y); } // console.info(`move y:${y}`); this.refs.list.style.transform = 'translate3d(0px, '+y+'px, 0px)'; } getBezier(x){ var ratio = 0.5; var delta = (2*this._itemHeight); var y = 0; if(x>delta){ y = ratio*delta+0.3*(x-delta); }else{ var a = (0-ratio) /(delta); var b = -2*a*delta; y = a*x*x+b*x; } return y; } stop(e){ // console.info('picker stop'); this._mouseMoveAllowed = false; if(this._eventState == 0){ return; } this._eventState = 0; var itemHeight = this._itemHeight; this._translateY += this._dist; var now = (new Date()).getTime(); var touchTime = now - this._beginTime; touchTime*=0.001; var capacity = Math.round(this._boxHeight/itemHeight); var halfCapacity = Math.floor(capacity/2); if(Math.abs(this._dist) > itemHeight){ var speed = this._dist/touchTime; speed *= 0.5; var a = 500; var animTime = Math.abs(speed/a); var distance = speed*speed/(2*a)*(speed>0?1:-1); this._translateY += distance; }else{ animTime = 0.3; } var y = this._translateY; var ys = (y/itemHeight).toFixed(0); this._current = halfCapacity - ys; var overflow = false; if(this._current < 0){//超出上界 // console.info('超出上界'); ys=halfCapacity; this._current = 0; overflow = true; } if(this._current >= this.props.dataSource.length){//超出下界 overflow = true; ys =0 -(this.props.dataSource.length -halfCapacity-1); // console.info('超出下界 ys:'+ys); this._current = this.props.dataSource.length-1; } y = ys*itemHeight; this._translateY = y; // console.info(`stop move y:${y}`); this.refs.list.style.transform = 'translate3d(0px,'+this._translateY+'px,0px)'; this.refs.list.style.transition = 'all ,'+(overflow ? '0.3':animTime)+'s'; this.refs.list.style.transitionTimingFunction = 'cubic-bezier(0.1, 0.57, 0.1, 1)'; this.props.onChanged && this.props.onChanged(this._current); } // ListItem(props){ // return <div key={props.key} style={styles.item}>props..value</div> // } scrollTo(index){ this._current = index; var y = (2-index)*this._itemHeight; this._translateY = y; // console.info(`scrollTo y:${y}`); this.refs.list.style.transform = 'translate3d(0px,'+y+'px,0px)'; this.refs.list.style.transition = 'all 0.3s'; this.refs.list.style.transitionTimingFunction = 'cubic-bezier(0.1, 0.57, 0.1, 1)'; } componentWillReceiveProps(nextProps){ if(this._current>nextProps.dataSource.length){ this.scrollTo(0); } } componentDidUpdate(prevProps){ if(this.props.current != prevProps.current){//init value changed this.scrollTo(this.props.current); } this.resetScrollRange(); } resetScrollRange(){ var boxHeight = this._boxHeight = this.refs.box.clientHeight; var itemHeight = this._itemHeight = this.refs.list.firstChild.clientHeight; this._scrollRange = [boxHeight/2 -itemHeight/2,boxHeight/2 +itemHeight/2-this.refs.list.clientHeight]; return this._scrollRange; } componentDidMount(){ var boxHeight = this._boxHeight = this.refs.box.clientHeight; var itemHeight = this._itemHeight = this.refs.list.firstChild.clientHeight; var y = boxHeight/2 -itemHeight/2 - itemHeight*this._current; this._translateY = y; this.refs.list.style.transform = 'translate3d(0px,'+y+'px,0px)'; setTimeout(()=>{ // console.info('reflush'); this.refs.mask.style.position = 'relative'; this.refs.mask.style.position = 'absolute'; }, 80); this.resetScrollRange(); this._mounted = true; } render(){ if(this._mounted){ this.refs.mask.style.position = 'absolute'; } var list = this.props.dataSource.map((item,k)=>{ return <div key={k} style={styles.item}>{item}</div> }); return ( <div ref="box" style={Object.assign({},styles.container,this.props.style)} onTouchStart={this.start} onMouseDown={this.start} onTouchMove={this.move} onMouseMove={this.move} onTouchEnd={this.stop} onMouseUp={this.stop} onMouseLeave={this.stop} > <div ref="mask" style={styles.mask} /> <div style={styles.mark} /> <div style={styles.list} ref="list"> {list} </div> </div> ); } } export default PickerCore;
packages/demo/src/components/RaisedButtonWithTooltip.js
hoschi/yode
import React from 'react' import RaisedButton from 'material-ui/RaisedButton' import Tooltip from 'material-ui/internal/Tooltip' class RaisedButtonWithTooltip extends React.Component { constructor(props) { super(props) this.state = { showTooltip: false } } showTooltip = () => { this.setState({ tooltipShown: true }) }; hideTooltip = () => { this.setState({ tooltipShown: false }) }; render() { const {tooltip, ...buttonProps} = this.props return <RaisedButton {...buttonProps} onMouseEnter={ this.showTooltip } onMouseLeave={ this.hideTooltip }> <Tooltip label={ tooltip } show={ this.state.tooltipShown } verticalPosition='top' style={ tooltipStyle } /> </RaisedButton> } } export default RaisedButtonWithTooltip let tooltipStyle = { boxSizing: 'border-box', fontSize: '16px', marginTop: -8 }
components/Footer/Footer.js
andeemarks/conf-gen-div-react
import React from 'react'; import Link from '../Link'; import { html } from './index.md'; function Footer() { return ( <footer className="mdl-mini-footer" style={{ backgroundColor: '#000000' }}> <div className="mdl-mini-footer__left-section"> <div dangerouslySetInnerHTML={{ __html: html }} /> </div> <div className="mdl-mini-footer__right-section"> <ul className="mdl-mini-footer__link-list"> <li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}> <a href="https://github.com/andeemarks/conf-gen-div" role="button" title="GitHub"> <svg width="36" height="36" viewBox="0 0 24 24"> <path fill="#fff" d="M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58 9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14, 17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63, 16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17, 16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2, 7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85, 6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54 17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81, 16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27 14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z" /> </svg> </a> </li> <li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}> <a href="https://twitter.com/XXatTechConfs" role="button" title="Twitter"> <svg width="36" height="36" viewBox="0 0 24 24"> <path fill="#fff" d="M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26 17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97, 7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38 6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69 8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76 7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95 17.71,9.33M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2Z" /> </svg> </a> </li> </ul> </div> </footer> ); } export default Footer;