path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/components/siteComponents/DesktopSettingsUI/index.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Helmet } from 'react-helmet'; import { Button, ControlLabel, FormControl, FormGroup, Panel, ProgressBar } from 'react-bootstrap'; import { appendFlashVersion } from 'helpers/utils'; import Modal from 'components/Modal'; import SizeFormat from 'components/SizeFormat'; import { LoaderIcon } from 'components/icons'; import './style.scss'; const { ipcRenderer, shell } = window.require('electron'); class DesktopSettingsUI extends Component { static propTypes = { auth: PropTypes.object, collSum: PropTypes.number, deleting: PropTypes.bool, deleteError: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]), match: PropTypes.object, user: PropTypes.object }; constructor(props) { super(props); ipcRenderer.on('async-response', this.handleVersionResponse); ipcRenderer.send('async-call'); this.state = { confirmUser: '', dataPath: '', showModal: false, version: '' }; } componentWillUnmount() { ipcRenderer.removeListener('async-response', this.handleVersionResponse); } handleChange = evt => this.setState({ [evt.target.name]: evt.target.value }) handleVersionResponse = (evt, arg) => { const { dataPath, version } = arg.config; this.setState({ dataPath, version: appendFlashVersion(version) }); } openDataDir = () => { shell.openItem(this.state.dataPath); } sendDelete = (evt) => { if (this.validateConfirmDelete() === 'success') { this.props.deleteUser(this.props.auth.getIn(['user', 'username'])); } } toggleDelete = evt => this.setState({ showModal: !this.state.showModal }) closeDeleteModal = evt => this.setState({ showModal: false }) validateConfirmDelete = (evt) => { const { auth } = this.props; const { confirmUser } = this.state; if (!confirmUser) { return null; } if (auth.getIn(['user', 'username']).toLowerCase() !== confirmUser.toLowerCase()) { return 'error'; } return 'success'; } render() { const { deleting, match: { params }, user } = this.props; const { showModal } = this.state; const username = params.user; const usedSpace = user.getIn(['space_utilization', 'used']); const totalSpace = user.getIn(['space_utilization', 'total']); const confirmDeleteBody = ( <div> <p> Are you sure you want to delete the <b>{username}</b> account? If you continue, <b>all archived data in all collections will be permanently deleted.</b> You will need to re-register to use the service again. </p> <FormGroup validationState={this.validateConfirmDelete()}> <ControlLabel>Type your username to confirm:</ControlLabel> <FormControl aria-label="confirm user" autoFocus disabled={deleting} id="confirm-delete" name="confirmUser" onChange={this.handleChange} placeholder={username} type="text" value={this.state.confirmUser} /> </FormGroup> </div> ); const confirmDeleteFooter = ( <div> <button onClick={this.closeDeleteModal} disabled={deleting} type="button" className="btn btn-default">Cancel</button> <button onClick={this.sendDelete} disabled={deleting || this.validateConfirmDelete() !== 'success'} className="btn btn-danger btn-ok" type="button"> { deleting && <LoaderIcon /> } Confirm Delete </button> </div> ); return ( <div className="row col-xs-10 col-xs-push-1 space-block desktop-settings"> <Helmet> <title>{`${username}'s Account Settings`}</title> </Helmet> <div className="row top-buffer main-logo"> <h1>Webrecorder</h1> </div> <div className="row tagline"> <h4 className="text-center">Desktop App</h4> </div> <Panel> <Panel.Heading> <Panel.Title>Version Info</Panel.Title> </Panel.Heading> <Panel.Body> <p dangerouslySetInnerHTML={{ __html: this.state.version || 'Loading...' }} /> </Panel.Body> </Panel> <Panel> <Panel.Heading> <Panel.Title>Usage for <b>{ username }</b></Panel.Title> </Panel.Heading> <Panel.Body> <span><b>Data Directory:</b></span> <p> <button onClick={this.openDataDir} className="button-link" type="button">{this.state.dataPath}</button> </p> <span><b>Space Used:</b> </span> <SizeFormat bytes={usedSpace} /> <em>of <SizeFormat bytes={totalSpace} /></em> <ProgressBar now={(usedSpace / totalSpace) * 100} variant="success" /> </Panel.Body> </Panel> {/* <Panel className="buffer-top" variant="danger"> <Panel.Heading> <Panel.Title>Remove Local Data</Panel.Title> </Panel.Heading> <Panel.Body> <div className="row col-md-12"> <div> <b>Permanently remove all local archived data for this user</b> <p>This action can not be undone!</p> <Button variant="danger" size="sm" onClick={this.toggleDelete}>Clear Local Data</Button> </div> </div> </Panel.Body> </Panel> <Modal body={confirmDeleteBody} closeCb={this.closeDeleteModal} dialogClassName="wr-delete-modal" footer={confirmDeleteFooter} header="Confirm Delete Account?" visible={showModal} /> */} </div> ); } } export default DesktopSettingsUI;
packages/react-error-overlay/src/containers/StackFrame.js
ConnectedHomes/create-react-web-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { Component } from 'react'; import CodeBlock from './StackFrameCodeBlock'; import { getPrettyURL } from '../utils/getPrettyURL'; import { darkGray } from '../styles'; import type { StackFrame as StackFrameType } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const linkStyle = { fontSize: '0.9em', marginBottom: '0.9em', }; const anchorStyle = { textDecoration: 'none', color: darkGray, cursor: 'pointer', }; const codeAnchorStyle = { cursor: 'pointer', }; const toggleStyle = { marginBottom: '1.5em', color: darkGray, cursor: 'pointer', border: 'none', display: 'block', width: '100%', textAlign: 'left', background: '#fff', fontFamily: 'Consolas, Menlo, monospace', fontSize: '1em', padding: '0px', lineHeight: '1.5', }; type Props = {| frame: StackFrameType, contextSize: number, critical: boolean, showCode: boolean, editorHandler: (errorLoc: ErrorLocation) => void, |}; type State = {| compiled: boolean, |}; class StackFrame extends Component<Props, State> { state = { compiled: false, }; toggleCompiled = () => { this.setState(state => ({ compiled: !state.compiled, })); }; getErrorLocation(): ErrorLocation | null { const { _originalFileName: fileName, _originalLineNumber: lineNumber, } = this.props.frame; // Unknown file if (!fileName) { return null; } // e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1" const isInternalWebpackBootstrapCode = fileName.trim().indexOf(' ') !== -1; if (isInternalWebpackBootstrapCode) { return null; } // Code is in a real file return { fileName, lineNumber: lineNumber || 1 }; } editorHandler = () => { const errorLoc = this.getErrorLocation(); if (!errorLoc) { return; } this.props.editorHandler(errorLoc); }; onKeyDown = (e: SyntheticKeyboardEvent<>) => { if (e.key === 'Enter') { this.editorHandler(); } }; render() { const { frame, contextSize, critical, showCode } = this.props; const { fileName, lineNumber, columnNumber, _scriptCode: scriptLines, _originalFileName: sourceFileName, _originalLineNumber: sourceLineNumber, _originalColumnNumber: sourceColumnNumber, _originalScriptCode: sourceLines, } = frame; const functionName = frame.getFunctionName(); const compiled = this.state.compiled; const url = getPrettyURL( sourceFileName, sourceLineNumber, sourceColumnNumber, fileName, lineNumber, columnNumber, compiled ); let codeBlockProps = null; if (showCode) { if ( compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null ) { codeBlockProps = { lines: scriptLines, lineNum: lineNumber, columnNum: columnNumber, contextSize, main: critical, }; } else if ( !compiled && sourceLines && sourceLines.length !== 0 && sourceLineNumber != null ) { codeBlockProps = { lines: sourceLines, lineNum: sourceLineNumber, columnNum: sourceColumnNumber, contextSize, main: critical, }; } } const canOpenInEditor = this.getErrorLocation() !== null && this.props.editorHandler !== null; return ( <div> <div>{functionName}</div> <div style={linkStyle}> <span style={canOpenInEditor ? anchorStyle : null} onClick={canOpenInEditor ? this.editorHandler : null} onKeyDown={canOpenInEditor ? this.onKeyDown : null} tabIndex={canOpenInEditor ? '0' : null} > {url} </span> </div> {codeBlockProps && ( <span> <span onClick={canOpenInEditor ? this.editorHandler : null} style={canOpenInEditor ? codeAnchorStyle : null} > <CodeBlock {...codeBlockProps} /> </span> <button style={toggleStyle} onClick={this.toggleCompiled}> {'View ' + (compiled ? 'source' : 'compiled')} </button> </span> )} </div> ); } } export default StackFrame;
packages/reactor-tests/src/tests/rel/RelMenu.js
markbrocato/extjs-reactor
import React from 'react'; import { Container, Button, Menu, MenuItem } from '@extjs/ext-react'; export default function RelMenu() { return ( <Container> <div>This tests that the menu config is automatically set when a Menu appears inside a Button. The test should verify that the button has a menu.</div> <Button text="Menu" itemId="button"> <Menu itemId="menu"> <MenuItem text="Option 1"/> <MenuItem text="Option 2"/> <MenuItem text="Option 3"/> </Menu> </Button> </Container> ) }
test/integration/with-router/pages/_app.js
BlancheXu/test
import App from 'next/app' import React from 'react' import HeaderNav from '../components/header-nav' export default class MyApp extends App { static async getInitialProps ({ Component, router, ctx }) { let pageProps = {} if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { pageProps } } render () { const { Component, pageProps } = this.props return ( <> <HeaderNav /> <Component {...pageProps} /> </> ) } }
app/javascript/mastodon/features/compose/components/poll_form.js
pso2club/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import IconButton from 'mastodon/components/icon_button'; import Icon from 'mastodon/components/icon'; import AutosuggestInput from 'mastodon/components/autosuggest_input'; import classNames from 'classnames'; const messages = defineMessages({ option_placeholder: { id: 'compose_form.poll.option_placeholder', defaultMessage: 'Choice {number}' }, add_option: { id: 'compose_form.poll.add_option', defaultMessage: 'Add a choice' }, remove_option: { id: 'compose_form.poll.remove_option', defaultMessage: 'Remove this choice' }, poll_duration: { id: 'compose_form.poll.duration', defaultMessage: 'Poll duration' }, minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' }, hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' }, days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' }, }); @injectIntl class Option extends React.PureComponent { static propTypes = { title: PropTypes.string.isRequired, index: PropTypes.number.isRequired, isPollMultiple: PropTypes.bool, onChange: PropTypes.func.isRequired, onRemove: PropTypes.func.isRequired, onToggleMultiple: PropTypes.func.isRequired, suggestions: ImmutablePropTypes.list, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleOptionTitleChange = e => { this.props.onChange(this.props.index, e.target.value); }; handleOptionRemove = () => { this.props.onRemove(this.props.index); }; handleToggleMultiple = e => { this.props.onToggleMultiple(); e.preventDefault(); e.stopPropagation(); }; onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['poll', 'options', this.props.index]); } render () { const { isPollMultiple, title, index, intl } = this.props; return ( <li> <label className='poll__text editable'> <span className={classNames('poll__input', { checkbox: isPollMultiple })} onClick={this.handleToggleMultiple} role='button' tabIndex='0' /> <AutosuggestInput placeholder={intl.formatMessage(messages.option_placeholder, { number: index + 1 })} maxLength={25} value={title} onChange={this.handleOptionTitleChange} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} searchTokens={[':']} /> </label> <div className='poll__cancel'> <IconButton disabled={index <= 1} title={intl.formatMessage(messages.remove_option)} icon='times' onClick={this.handleOptionRemove} /> </div> </li> ); } } export default @injectIntl class PollForm extends ImmutablePureComponent { static propTypes = { options: ImmutablePropTypes.list, expiresIn: PropTypes.number, isMultiple: PropTypes.bool, onChangeOption: PropTypes.func.isRequired, onAddOption: PropTypes.func.isRequired, onRemoveOption: PropTypes.func.isRequired, onChangeSettings: PropTypes.func.isRequired, suggestions: ImmutablePropTypes.list, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleAddOption = () => { this.props.onAddOption(''); }; handleSelectDuration = e => { this.props.onChangeSettings(e.target.value, this.props.isMultiple); }; handleToggleMultiple = () => { this.props.onChangeSettings(this.props.expiresIn, !this.props.isMultiple); }; render () { const { options, expiresIn, isMultiple, onChangeOption, onRemoveOption, intl, ...other } = this.props; if (!options) { return null; } return ( <div className='compose-form__poll-wrapper'> <ul> {options.map((title, i) => <Option title={title} key={i} index={i} onChange={onChangeOption} onRemove={onRemoveOption} isPollMultiple={isMultiple} onToggleMultiple={this.handleToggleMultiple} {...other} />)} </ul> <div className='poll__footer'> {options.size < 4 && ( <button className='button button-secondary' onClick={this.handleAddOption}><Icon id='plus' /> <FormattedMessage {...messages.add_option} /></button> )} <select value={expiresIn} onChange={this.handleSelectDuration}> <option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option> <option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option> <option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option> <option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option> <option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option> <option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option> <option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option> </select> </div> </div> ); } }
src/components/UndoRemoveAlert.js
danesparza/centralconfig-ui
// React import React, { Component } from 'react'; // The API utils import CentralConfigAPIUtils from '../utils/CentralConfigAPIUtils'; // Actions import ConfigActions from '../actions/ConfigActions'; // The stores import RemovedConfigStore from '../stores/RemovedConfigStore'; class UndoRemoveAlert extends Component { constructor(props){ super(props); // Set initial state: this.state = { removedConfigItem: null }; } componentDidMount() { // Add store listeners ... and notify ME of changes this.undoListener = RemovedConfigStore.addListener(this._onRemoveUpdate); } componentWillUnmount() { // Remove store listeners this.undoListener.remove(); } render() { // If we don't have a removed item, don't show the alert if(this.state.removedConfigItem === null || this.state.removedConfigItem === undefined) { return null; } return ( <div className="alert alert-info" role="alert"> <button type="button" className="close" aria-label="Close" onClick={this._onClearUndo}><span aria-hidden="true">&times;</span></button> Config item <b>{this.state.removedConfigItem.application} / {this.state.removedConfigItem.name}</b> removed - <a className="btn btn-sm btn-outline-primary" onClick={this._undoRemoveClick}>UNDO</a> </div> ); } _onClearUndo = () => { ConfigActions.clearRemovedConfigData(); } _onRemoveUpdate = () => { this.setState({ removedConfigItem: RemovedConfigStore.getConfigItem() }); } _undoRemoveClick = (event) => { // Reset the item and get all items: let APIUtils = new CentralConfigAPIUtils(); APIUtils.setConfigItem(this.state.removedConfigItem).then(() => APIUtils.getAllConfigItems()); } } export default UndoRemoveAlert
actor-apps/app-web/src/app/components/sidebar/RecentSectionItem.react.js
ganquan0910/actor-platform
import React from 'react'; import classNames from 'classnames'; import DialogActionCreators from 'actions/DialogActionCreators'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; class RecentSectionItem extends React.Component { static propTypes = { dialog: React.PropTypes.object.isRequired }; constructor(props) { super(props); } onClick = () => { DialogActionCreators.selectDialogPeer(this.props.dialog.peer.peer); } render() { const dialog = this.props.dialog, selectedDialogPeer = DialogStore.getSelectedDialogPeer(); let isActive = false, title; if (selectedDialogPeer) { isActive = (dialog.peer.peer.id === selectedDialogPeer.id); } if (dialog.counter > 0) { const counter = <span className="counter">{dialog.counter}</span>; const name = <span className="col-xs title">{dialog.peer.title}</span>; title = [name, counter]; } else { title = <span className="col-xs title">{dialog.peer.title}</span>; } let recentClassName = classNames('sidebar__list__item', 'row', { 'sidebar__list__item--active': isActive, 'sidebar__list__item--unread': dialog.counter > 0 }); return ( <li className={recentClassName} onClick={this.onClick}> <AvatarItem image={dialog.peer.avatar} placeholder={dialog.peer.placeholder} size="tiny" title={dialog.peer.title}/> {title} </li> ); } } export default RecentSectionItem;
scripts/components/Header.js
BarukhOr/cuddly-giggle-reactjs
/* Header */ import React from 'react'; import autobind from 'autobind-decorator'; class Header extends React.Component{ render(){ return( <header className="top"> <h1>Catch <span className="ofThe"> <span className="of">of</span> <span className="the">the</span> </span> Day</h1> <h3 className="tagline"><span>{this.props.tagline}</span></h3> </header> ) } } Header.protoTypes = { tagline : React.PropTypes.string.isRequired } export default Header;
src/routes/home/Home.js
TodoWishlist/TodoWishlist
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import styles from './Home.css'; import HomeImageHero from './HomeImageHero/HomeImageHero'; import HomeStory from './HomeStory/HomeStory'; import HomeBottomSignup from './HomeBottomSignup/HomeBottomSignup'; class Home extends Component { constructor(props) { super(props); this.state = { isOpen: false, }; } render() { return ( <div className={styles.supremeContainer}> <HomeImageHero /> <h1 className={styles.header}>Todo&Wish make you easy</h1> <HomeStory /> <HomeBottomSignup /> </div> ); } } // App.propTypes = { // children: PropTypes.object.isRequired, // dispatch: PropTypes.func.isRequired, // intl: PropTypes.object.isRequired, // }; export default withStyles(styles)(Home);
docs/src/examples/elements/Button/Types/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' import ShorthandExample from 'docs/src/components/ComponentDoc/ShorthandExample' const ButtonTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Button' description='A standard button.' examplePath='elements/Button/Types/ButtonExampleButton' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleShorthand' /> <ComponentExample title='Emphasis' description='A button can be formatted to show different levels of emphasis.' examplePath='elements/Button/Types/ButtonExampleEmphasis' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleEmphasisShorthand' /> <ComponentExample title='Animated' description='Buttons can animate to show additional or hidden content.' examplePath='elements/Button/Types/ButtonExampleAnimated' /> <ComponentExample title='Labeled' description='A button can be accompanied by a label.' examplePath='elements/Button/Types/ButtonExampleLabeled' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleLabeledShorthand' /> <ComponentExample examplePath='elements/Button/Types/ButtonExampleLabeledBasic' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleLabeledBasicShorthand' /> <ComponentExample title='Icon' description='A button can be made of only an icon.' examplePath='elements/Button/Types/ButtonExampleIcon' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleIconShorthand' /> <ComponentExample title='Labeled Icon' description='A button can use an icon as a label.' examplePath='elements/Button/Types/ButtonExampleLabeledIcon' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleLabeledIconShorthand' /> <ComponentExample title='Basic' description='The basic button has a subtle appearance.' examplePath='elements/Button/Types/ButtonExampleBasic' /> <ShorthandExample examplePath='elements/Button/Types/ButtonExampleBasicShorthand' /> <ComponentExample title='Inverted' description='A button can be formatted to appear on a dark background.' examplePath='elements/Button/Types/ButtonExampleInverted' /> </ExampleSection> ) export default ButtonTypesExamples
src/container/RootContainer.js
jerryshew/test-redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import configStore from '../store/configStore'; import UserTableContainer from './UserTableContainer'; import Counter from './Counter'; import DevTools from './DevTools'; export default () => ( <Provider store={configStore}> <div> <UserTableContainer/> <br/> <Counter/> <DevTools/> </div> </Provider> )
src/components/Spendings.js
FrozenTear7/student-life-organizer
import React from 'react' import { connect } from 'react-redux' import { updateSpendings, subtractSpendings } from '../actions/spendingsActions' import renderField from './renderField' import { reduxForm, Field, reset } from 'redux-form' import moment from 'moment' import {required, positiveNumber} from '../utils/validateForm' const moneyDaily = (money) => { const a = moment().endOf('month') const b = moment().startOf('month') return (money/((a.diff(b, 'days'))+1)).toFixed(2) } const moneyDailyLeft = (money) => { const a = moment().endOf('month') const b = moment() return (money/((a.diff(b, 'days'))+1)).toFixed(2) } const submitSpendings = (values, dispatch) => { dispatch(updateSpendings(values.amount, values.amountLeft)) dispatch(reset('Spendings')) } const submitSubtractSpendings = (values, dispatch) => { dispatch(subtractSpendings(values.subtractAmount)) dispatch(reset('Spendings')) } const countDifference = (originalSum, left) => { return (left-originalSum) } let Spendings = ({ handleSubmit, spendings, onSpendingsEdit, onSpendingsDelete, onSpendingsSubtract }) => { if(!spendings.edit) { return ( <div className='container'> <ul className='list-group'> <li className='list-group-item'> Money for this month: {spendings.amount} </li> <li className='list-group-item'> Estimated daily spendings in this month: {moneyDaily(spendings.amount)} </li> <li className='list-group-item'> Money left this month: {spendings.amountLeft} </li> <li className='list-group-item'> Current daily spendings: {moneyDailyLeft(spendings.amountLeft)} </li> <li className='list-group-item' style={{ color: (countDifference(moneyDaily(spendings.amount), moneyDailyLeft(spendings.amountLeft))>=0.00) ? 'green' : 'red', fontSize: '30px' }} > Daily spendings difference: {(countDifference(moneyDaily(spendings.amount), moneyDailyLeft(spendings.amountLeft))).toFixed(2)} </li> </ul> <br/> <button onClick={() => onSpendingsEdit()} className='btn btn-info' > Edit spendings </button> <button onClick={() => onSpendingsDelete()} className='btn btn-danger' > Reset spendings </button> <br/><br/> <form onSubmit={handleSubmit(submitSubtractSpendings)} > <Field name='subtractAmount' type='number' label='Subtract amount' component={renderField} validate={[required, positiveNumber]} /> <button type='submit' className='btn btn-success btn-sm' > Subtract spendings </button> </form> </div> ) } else { return ( <form onSubmit={handleSubmit(submitSpendings)} > <Field name='amount' type='number' label='Edit amount' component={renderField} validate={[required, positiveNumber]} /> <Field name='amountLeft' type='number' label='Edit amount left' component={renderField} validate={required} /> <button type='submit' className='btn btn-success btn-sm' > Update Spendings </button> <button onClick={() => onSpendingsEdit()} className='btn btn-secondary btn-sm' > Go back </button> </form> ) } } Spendings = reduxForm({ form: 'Spendings', enableReinitialize: true })(Spendings) Spendings = connect( state => ({ initialValues: state.spendings.spendings }) )(Spendings) export default Spendings
src/Scrollbars/defaultRenderElements.js
zxlin/react-custom-scrollbars
import React from 'react'; /* eslint-disable react/prop-types */ export function renderViewDefault({ scrollbarWidth, ...props }) { // eslint-disable-line no-unused-vars return <div {...props}/>; } export function renderTrackHorizontalDefault({ style, ...props }) { const finalStyle = { ...style, right: 2, bottom: 2, left: 2, borderRadius: 3 }; return <div style={finalStyle} {...props} />; } export function renderTrackVerticalDefault({ style, ...props }) { const finalStyle = { ...style, right: 2, bottom: 2, top: 2, borderRadius: 3 }; return <div style={finalStyle} {...props} />; } export function renderThumbHorizontalDefault({ style, ...props }) { const finalStyle = { ...style, cursor: 'pointer', borderRadius: 'inherit', backgroundColor: 'rgba(0,0,0,.2)' }; return <div style={finalStyle} {...props} />; } export function renderThumbVerticalDefault({ style, ...props }) { const finalStyle = { ...style, cursor: 'pointer', borderRadius: 'inherit', backgroundColor: 'rgba(0,0,0,.2)' }; return <div style={finalStyle} {...props} />; }
src/NavItem.js
rapilabs/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const NavItem = React.createClass({ mixins: [BootstrapMixin], propTypes: { linkId: React.PropTypes.string, onSelect: React.PropTypes.func, active: React.PropTypes.bool, disabled: React.PropTypes.bool, href: React.PropTypes.string, role: React.PropTypes.string, title: React.PropTypes.node, eventKey: React.PropTypes.any, target: React.PropTypes.string, 'aria-controls': React.PropTypes.string }, render() { let { role, linkId, disabled, active, href, title, target, children, 'aria-controls': ariaControls, ...props } = this.props; let classes = { active, disabled }; let linkProps = { role, href, title, target, id: linkId, onClick: this.handleClick }; if (!role && href === '#') { linkProps.role = 'button'; } return ( <li {...props} role='presentation' className={classNames(props.className, classes)}> <SafeAnchor {...linkProps} aria-selected={active} aria-controls={ariaControls}> { children } </SafeAnchor> </li> ); }, handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); export default NavItem;
src/svg-icons/navigation/arrow-drop-down-circle.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDownCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"/> </SvgIcon> ); NavigationArrowDropDownCircle = pure(NavigationArrowDropDownCircle); NavigationArrowDropDownCircle.displayName = 'NavigationArrowDropDownCircle'; NavigationArrowDropDownCircle.muiName = 'SvgIcon'; export default NavigationArrowDropDownCircle;
src/js/modules/danmu/UI/danmu.js
zacyu/bilibili-helper
/** * Author: DrowsyFlesh * Create: 2018/10/22 * Description: */ import _ from 'lodash'; import $ from 'jquery'; import PropTypes from 'prop-types'; import React from 'react'; import apis from '../apis.js'; import Url from 'url-parse'; import styled from 'styled-components'; import {Button} from 'Components/common/Button'; import {Crc32Engine} from 'Libs/crc32'; import {List} from 'react-virtualized'; import {getFilename} from 'Utils'; import {parseTime} from 'Utils'; import {theme} from 'Styles'; import './styles.scss'; import 'react-virtualized/styles.css'; export default () => { const {color} = theme; const crcEngine = new Crc32Engine(); const Title = styled.div.attrs({className: 'bilibili-helper-danmu-title'})` margin-bottom: 6px; font-size: 12px; font-weight: bold; text-align: left; .count { margin-left: 10px; color: ${color('google-grey-500')}; } `; const DanmuList = styled(List).attrs({className: 'bilibili-helper-danmu-list'})` position: relative; height: 200px; margin-left: 4px; padding: 1px; border: 1px solid #eee; border-radius: 4px 4px 0 0; font-size: 12px; overflow: hidden; outline: none; & .no-data {} `; const DanmuSearchInput = styled.input.attrs({className: 'bilibili-helper-danmu-input'})` display: block; width: 418px; margin-left: 4px; padding: 4px 6px; box-sizing: border-box; border: 1px solid #eee; border-top: none; border-radius: 0 0 4px 4px; font-size: 12px; `; const DanmuListLine = styled.div` display: flex; margin-bottom: 1px; padding: 0 8px 1px; line-height: 20px; border-radius: 2px; background-color: ${({hasQueried}) => hasQueried ? '#d6e8f5' : 'white'}; cursor: pointer; &:hover { color: #fff; background-color: #00a1d6; .target-words { color: #fff; } } & .time { flex-grow: 0; flex-shrink: 0; width: 30px; padding-right: 7px; } & .danmu { flex-grow: 1; margin: 0 7px 0 3px; padding: 0 7px; border-left: 1px solid #fff; border-right: 1px solid #fff; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } & .author { flex-shrink: 0; width: 100px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } & .target-words { font-weight: bold; color: #00a1d6; } `; const LoadingMask = styled.div` display: flex; justify-content: center; align-items: center; position: absolute; top: 23px; right: 1px; bottom: 1px; left: 1px; border-radius: 4px; font-size: 12px; font-weight: bold; letter-spacing: 1px; background-color: rgba(255, 255, 255, 0.8); cursor: no-drop; user-select: none; `; const DownloadBtn = styled(Button)` float: right; border-radius: 4px; margin-left: 10px; button { padding: 0; min-width: 35px; font-size: 12px; border: 1px solid ${color('bilibili-pink')}; border-radius: 4px; color: ${({on}) => on ? '#fff' : color('bilibili-pink')}; background-color: ${({on}) => on ? color('bilibili-pink') : '#fff'}; } `; return class Danmu extends React.Component { propTypes = { settings: PropTypes.object, }; constructor(props) { super(props); this.orderedJSON = {}; // 经过弹幕发送时间排序的数据 this.userMap = {}; // uid -> data this.userCardMap = {}; // uid -> cardData this.queryUserModeTemplateMap = {}; // 切换到用户UID查询模式前,将之前的查询结果被分到该map中 this.danmuDocumentStr = null; const today = new Date(); this.danmuDate = `${today.getMonth() + 1}-${today.getDate()}`; // 当前弹幕日期 this.addListener(); this.danmuListRef = null; this.currentRowIndex = 0; this.authorHashMap = {}; // authorHash -> uid this.removeCardSign = null; this.lasetHeight = null; this.state = { loaded: false, loading: false, loadingText: null, danmuJSON: {list: []}, filterText: '', /** * 需要一个字段用于通知react重新渲染组件 * 这里选择使用较为简单的authorHashMap */ queryUserMode: null, // 用户UID查询模式 currentCid: NaN, }; } componentDidMount() { chrome.runtime.sendMessage({command: 'danmuDOMInitialized'}); } addListener = () => { const that = this; chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.command === 'loadHistoryDanmu') { // 被通知载入历史弹幕 if (message.date) { this.getDANMUList(message.cid, message.date); sendResponse(true); } else console.error(`Error history danmu date: ${message.date}`); } else if (message.command === 'loadCurrentDanmu') { // 被通知载入当日弹幕 this.getDANMUList(message.cid); sendResponse(true); } return true; }); // 对pakku的hack,仅发送历史弹幕的请求 window.addEventListener('message', function(e) { if (e.data.type === 'pakku_ajax_request' && /x\/v2\/dm\/history/.test(e.data.arg)) { chrome.runtime.sendMessage({command: 'pakkuGetHistoryDanmu', url: e.data.arg}); } }); let n, m; $(document).on('mouseenter', '[helper-data-usercard-mid]', function() { that.createCard(this, $(this).attr('helper-data-usercard-mid')); }); $(document).on('mouseenter', '[helper-data-usercard-mid], #helper-card', function() { that.removeCardSign = false; if (m) { clearTimeout(m); m = null; } m = setTimeout(() => { if (document.querySelector('#helper-card')) document.querySelector('#helper-card').style.display = 'block'; }, 300); if (n) { clearTimeout(n); n = null; } n = setTimeout(() => { that.removeCardSign = true; }, 300); }); $(document).on('mouseleave', '[helper-data-usercard-mid], #helper-card, .bilibili-helper-danmu-wrapper', function() { setTimeout(() => { const dom = document.querySelector('#helper-card'); if (that.removeCardSign && dom) dom.style.display = 'none'; }, 200); }); }; // 获取弹幕xml数据源 getDANMUList = (cid, date) => { if (!!cid && !this.state.loading) { const {list, historyList} = apis; const timer = setTimeout(() => { // 请求时长超过800毫秒则显示查询中 this.setState({ loading: true, loadingText: '弹幕加载中~(๑•̀ㅂ•́)و', }); }, 800); const url = new Url(date ? historyList : list); url.set('query', { oid: cid, type: 1, date, }); chrome.runtime.sendMessage({command: 'fetchDanmu', url: url.toString()}, (danmuDocumentStr) => { clearTimeout(timer); if (danmuDocumentStr) { if (date) this.danmuDate = date; const oSerializer = new DOMParser(); this.danmuDocumentStr = danmuDocumentStr; this.danmuDocument = oSerializer.parseFromString(danmuDocumentStr, 'application/xml'); const danmuJSON = this.danmuDocument2JSON(this.danmuDocument); danmuJSON.list = this.sortJSONByTime(danmuJSON.list); this.orderedJSON = {...danmuJSON}; this.setState({ danmuJSON: danmuJSON, loaded: true, loading: false, currentCid: cid, }); } else { this.setState({loadingText: '弹幕加载失败!请刷新页面!'}); } }); } }; // 通过uid获取用户信息 getUserInfoByUid = (uid) => { return new Promise((resolve) => { const url = new Url(apis.card); url.set('query', {mid: uid, photo: 1}); uid && chrome.runtime.sendMessage({command: 'fetchDanmu', url: url.toString()}, (res) => { if (res) { // 过滤掉可能是机器人的用户 const {code, data} = JSON.parse(res); if (code === 0) { if (this.isRobotUser(data)) resolve(false); const {card, space, follower, following} = data; this.userMap[uid] = {...card, ...space, follower, following}; resolve(uid); } else { console.error(res); this.setState({loadingText: '查询失败!'}, () => { // 查询失败3秒后关闭错误信息 setTimeout(() => this.setState({loading: false}), 3000); }); resolve(false); } } else { console.error(res); this.setState({loadingText: '查询失败!'}, () => { // 查询失败3秒后关闭错误信息 setTimeout(() => this.setState({loading: false}), 3000); }); resolve(false); } }); }); }; // 检查机器人用户 isRobotUser = (userData = {}) => { const {card} = userData; const {level_info} = card; const {current_level} = level_info; // 当前用户等级 //const {type} = official_verify; // 正式用户!?(・_・;? return current_level === 0; }; // 将弹幕数据以时间顺序排序 sortJSONByTime = (originJSON) => { return _.sortBy(originJSON, 'time'); }; // 将xml文档转化为json danmuDocument2JSON = (document) => { const list = []; _.forEach(document.getElementsByTagName('d'), (d) => { const [ time, danmuMode, fontSize, color, unixTime, unknow, // eslint-disable-line authorHash, rowId, ] = d.getAttribute('p').split(','); const danmu = d.innerHTML; list.push({danmuMode, fontSize, color, unixTime, authorHash, rowId, danmu, time: parseTime(time * 1000)}); }); this.setState({loaded: true}); return { cid: Number(document.getElementsByTagName('chatid')[0].innerHTML), maxLimit: Number(document.getElementsByTagName('maxlimit')[0].innerHTML), count: list.length, list, }; }; /** * 等级行号动态获取行高 * 当查询发送者后,可能会出现多解导致显示多行从而改变行高 * @param index * @return {number} */ getRowHeight = ({index}) => { const {danmuJSON} = this.state; const danmuData = danmuJSON.list[index]; const uidArray = this.authorHashMap[danmuData.authorHash]; return (uidArray && uidArray.length * 20) || 20; }; // 搜索框编辑事件 handleInputChange = (e) => { const value = e.target.value; const {danmuJSON} = this.state; const {cid} = danmuJSON; if (!e.target.value) { const {count, list} = this.orderedJSON; this.setState({danmuJSON: {cid, count, list}}); } else { const list = []; _.forEach(this.orderedJSON.list, (data) => { const index = data.danmu.indexOf(value); if (index >= 0) { // 这里一定要复制一份,不然会修改原数据 const danmu = data.danmu.replace(value, `<span class="target-words">${value}</span>`); list.push({...data, danmu}); } }); this.setState({danmuJSON: {cid, count: list.length, list}}); } }; // 当点击没有查询过用户名的弹幕列表行时触发 handleDanmuLineClick = (authorHash) => { let extracted = /^b(\d+)$/.exec(authorHash); let uids = []; if (extracted && extracted[1]) { uids = [extracted[1]]; } else { uids = crcEngine.crack(authorHash); } this.setState({ loading: true, loadingText: '努力查询中~(๑•̀ㅂ•́)و', }); let thisHashMap = []; Promise.all(uids.map((uid) => this.getUserInfoByUid(uid))).then((res) => { thisHashMap = thisHashMap.concat(_.compact(res)); }).then(() => { if (thisHashMap.length > 0) this.authorHashMap[authorHash] = thisHashMap; this.setState({loading: false}, () => { this.danmuListRef.recomputeRowHeights(); this.danmuListRef.forceUpdate(); }); }); }; // 当点击查询过用户名的弹幕行时 handleAuthorClick = (index, uids) => { if (!this.state.queryUserMode) { const queryList = []; this.queryUserModeTemplateMap = {...this.state.danmuJSON}; // 保存当前查询列表 _.each(uids, (uid) => { const authorHash = _.findKey(this.authorHashMap, (id) => !!~id.indexOf(uid)); _.each(this.orderedJSON.list, (data) => { if (data.authorHash === authorHash) { queryList.push({...data}); // 这里一定要复制一份,不然会修改原数据 } }); }); this.setState({ queryUserMode: true, danmuJSON: {cid: this.orderedJSON.cid, count: queryList.length, list: queryList}, }, () => { this.currentRowIndex = index; }); } else { this.setState({ queryUserMode: false, danmuJSON: this.queryUserModeTemplateMap, }, () => { this.danmuListRef.scrollToRow(this.currentRowIndex); }); } }; handleDownloadClick = (type) => { chrome.runtime.sendMessage({ command: type === 'ass' ? 'downloadDanmuASS' : 'downloadDanmuXML', cid: this.state.currentCid, danmuDocumentStr: this.danmuDocumentStr, date: this.danmuDate, filename: getFilename(document), origin: type === 'ass' ? document.location.href : null, }); }; createCardDOM = (data) => { if (!data) { return console.error('no user data to create card'); } const {mid, face, s_img, name, sign, sex, level_info, following} = data; let card, header, container, faceBlock, userBlock, nameBlock, signBlock, levelBlock, sexBlock, btnBlock, likeBtn, messageBtn; header = document.querySelector('.helper-card-header') || document.createElement('div'); container = document.querySelector('.helper-card-container') || document.createElement('div'); faceBlock = document.querySelector('.helper-card-face') || document.createElement('img'); userBlock = document.querySelector('.helper-card-user') || document.createElement('p'); nameBlock = document.querySelector('.helper-card-name') || document.createElement('a'); signBlock = document.querySelector('.helper-card-sign') || document.createElement('p'); levelBlock = document.querySelector('.helper-card-level') || document.createElement('a'); sexBlock = document.querySelector('.helper-card-sex') || document.createElement('i'); btnBlock = document.querySelector('.helper-card-feed') || document.createElement('div'); likeBtn = document.querySelector('.helper-card-like-btn') || document.createElement('a'); messageBtn = document.querySelector('.helper-card-like-btn') || document.createElement('a'); card = document.querySelector('#helper-card'); if (!card) { card = document.createElement('div'); header.setAttribute('class', 'helper-card-header bg'); container.setAttribute('class', 'helper-card-container info'); faceBlock.setAttribute('class', 'helper-card-face face'); userBlock.setAttribute('class', 'helper-card-user user'); nameBlock.setAttribute('class', 'helper-card-name name'); signBlock.setAttribute('class', 'helper-card-sign sign'); btnBlock.setAttribute('class', 'helper-card-btn btn-box'); card.setAttribute('id', 'helper-card'); card.setAttribute('class', 'user-card'); levelBlock.setAttribute('class', 'helper-card-level level'); levelBlock.setAttribute('href', '//www.bilibili.com/html/help.html#k_2'); levelBlock.setAttribute('target', '_blank'); likeBtn.setAttribute('class', 'like'); likeBtn.innerHTML = '<span class="hover-text">取消关注</span><span class="default-text">+关注</span>'; messageBtn.setAttribute('class', 'message'); messageBtn.setAttribute('target', '_blank'); messageBtn.innerText = '发消息'; userBlock.appendChild(nameBlock); userBlock.appendChild(sexBlock); userBlock.appendChild(levelBlock); container.appendChild(userBlock); container.appendChild(signBlock); btnBlock.appendChild(likeBtn); btnBlock.appendChild(messageBtn); card.appendChild(header); card.appendChild(faceBlock); card.appendChild(container); card.appendChild(btnBlock); } header.setAttribute('style', `background-image: url(${s_img});`); faceBlock.setAttribute('src', face); if (sex === '男') sexBlock.setAttribute('class', 'sex man'); else if (sex === '女') sexBlock.setAttribute('class', 'sex woman'); const levelInner = document.createElement('i'); levelInner.setAttribute('class', `level l${level_info.current_level}`); levelBlock.innerHTML = ''; levelBlock.appendChild(levelInner); likeBtn.setAttribute('mid', mid); likeBtn.setAttribute('uname', name); likeBtn.onclick = function() { if (following) this.userMap[mid].following = false; else this.userMap[mid].following = true; }; if (following) likeBtn.setAttribute('class', 'like liked'); messageBtn.setAttribute('href', '//message.bilibili.com/#whisper/mid' + mid); nameBlock.innerText = name; nameBlock.setAttribute('href', 'https://space.bilibili.com/' + mid); signBlock.innerText = sign; return card; }; createCard = (target, mid) => { const userData = this.userMap[mid]; const cardDOM = this.createCardDOM(userData); if (!document.querySelector('#helper-card')) document.querySelector('body').appendChild(cardDOM); this.setTargetPosition(target, cardDOM); }; setTargetPosition = (targetDOM, cardDOM) => { const {height, top, left} = targetDOM.getBoundingClientRect(); const {height: cardHeight} = cardDOM.getBoundingClientRect(); if (cardHeight) this.lastHeight = cardHeight; if (top >= cardHeight) { cardDOM.style.top = `${top - this.lastHeight - 2}px`; } else { cardDOM.style.top = `${top + height + 2}px`; } if (left + 377 <= window.innerWidth) cardDOM.style.left = `${left}px`; else cardDOM.style.left = `${window.innerWidth - 377}px`; }; renderHeader = (danmuJSON = this.state.danmuJSON) => ( <Title> <span>弹幕发送者查询{danmuJSON.count ? <span className="count">{danmuJSON.count} 条</span> : null}</span> <DownloadBtn title="下载 ASS 格式弹幕文件" onClick={() => this.handleDownloadClick('ass')}>ASS</DownloadBtn> <DownloadBtn title="下载 XML 格式弹幕文件" onClick={() => this.handleDownloadClick('xml')}>XML</DownloadBtn> </Title> ); renderLine = ({index, style}) => { const {danmuJSON} = this.state; const danmuData = danmuJSON.list[index]; const {rowId, danmu, authorHash, time} = danmuData; const uidArray = this.authorHashMap[authorHash]; let authorNames = _.map(uidArray, (uid) => this.userMap[uid] ? this.userMap[uid].name : ''); return ( <DanmuListLine key={rowId} title={`[${time}] ${danmu} ${authorNames ? `by:${authorNames.join(',')}` : ''}`} onClick={() => uidArray ? this.handleAuthorClick(index, uidArray) : this.handleDanmuLineClick(authorHash)} hasQueried={!_.isEmpty(authorNames)} style={style} > <span className="time">{time}</span> <span className="danmu" dangerouslySetInnerHTML={{__html: danmu}}/> <span className="author"> {authorNames.map((name, index) => ( <div key={name} helper-data-usercard-mid={uidArray[index]}>{name}</div>))} </span> </DanmuListLine> ); }; renderList = () => <DanmuList ref={i => this.danmuListRef = i} width={414} height={200} rowCount={this.state.danmuJSON.list.length} rowHeight={this.getRowHeight} rowRenderer={this.renderLine} noRowsRenderer={() => (<DanmuListLine>无数据</DanmuListLine>)} scrollToAlignment={'center'} />; render() { return ( <React.Fragment> {this.renderHeader()} {this.renderList()} <DanmuSearchInput placeholder="请输入需要查询的弹幕内容" onChange={this.handleInputChange}/> {this.state.loading && <LoadingMask>{this.state.loadingText}</LoadingMask>} </React.Fragment> ); } } }
src/components/common/Select.js
nbkhope/componentes-controlados
import React from 'react'; // <Select // name="pais" // value={this.state.pais} // onChange={this.onPaisChange} // options={paisOptions} // /> const Select = ({ name, value, onChange, options }) => { const optionChoices = options.map(option => ( <option key={option.id} value={option.value}> {option.label} </option> )); return ( <select name={name} value={value} onChange={onChange} > {optionChoices} </select> ); }; export { Select };
src/notebook/components/cell/display-area/richest-mime.js
0u812/nteract
// @flow import React from 'react'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import { richestMimetype, transforms, displayOrder } from '../../transforms'; type Props = { displayOrder: ImmutableList<string>, transforms: ImmutableMap<string, any>, bundle: ImmutableMap<string, any>, metadata: ImmutableMap<string, any>, theme: string, models?: ImmutableMap<string, any>, }; export default class RichestMime extends React.Component { props: Props; static defaultProps = { transforms, displayOrder, theme: 'light', metadata: new ImmutableMap(), bundle: new ImmutableMap(), models: new ImmutableMap(), }; shouldComponentUpdate(nextProps: Props): boolean { // eslint-disable-line class-methods-use-this if (nextProps && nextProps.theme && this.props && nextProps.theme !== this.props.theme) { return true; } // return false; return true; } render(): ?React.Element<any>|null { const mimetype = richestMimetype( this.props.bundle, this.props.displayOrder, this.props.transforms ); if (!mimetype) { // If no mimetype is supported, don't return a component return null; } const Transform = this.props.transforms.get(mimetype); const data = this.props.bundle.get(mimetype); const metadata = this.props.metadata.get(mimetype); return ( <Transform data={data} metadata={metadata} theme={this.props.theme} models={this.props.models} /> ); } }
src/main.react.js
matthias-reis/react-xi
import React from 'react'; export default class Xi extends React.Component { render() { return ( <div> <section className="card card-primary card-inverse"> <div className="card-block"> <h2 className="card-title">Core Actions</h2> <p className="card-text"> Er hörte leise Schritte hinter sich. Das bedeutete nichts Gutes. </p> </div> </section> <div className="card-columns"> <section className="card"> <div className="card-block"> <h5 className="card-title">CORE:ACTION</h5> <p className="card-text"> Wer würde ihm schon folgen, spät in der Nacht und dazu noch in dieser engen Gasse mitten im übel beleumundeten Hafenviertel? </p> </div> </section> <section className="card"> <div className="card-block"> <h5 className="card-title">CORE:ACTION2</h5> <p className="card-text"> Gerade jetzt, wo er das Ding seines Lebens gedreht hatte und mit der Beute verschwinden wollte! </p> </div> </section> <section className="card"> <div className="card-block"> <h5 className="card-title">CORE:ACTION3</h5> <p className="card-text"> Hatte einer seiner zahllosen Kollegen dieselbe Idee gehabt, ihn beobachtet und abgewartet, um ihn nun um die Früchte seiner Arbeit zu erleichtern? </p> </div> </section> <section className="card"> <div className="card-block"> <h5 className="card-title">CORE:ACTION4</h5> <p className="card-text"> Oder gehörten die Schritte hinter ihm zu einem der unzähligen Gesetzeshüter dieser Stadt, und die stählerne Acht um seine Handgelenke würde gleich zuschnappen? </p> </div> </section> <section className="card"> <div className="card-block"> <h5 className="card-title">CORE:ACTION5</h5> <p className="card-text"> Er konnte die Aufforderung stehen zu bleiben schon hören. </p> </div> </section> </div> </div> ); } }
internals/templates/containers/App/index.js
thuantrinh/math_is_hard
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
src/esm/components/graphics/icons/hourglass-icon/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "title"]; import React from 'react'; import PropTypes from 'prop-types'; export var HourglassIcon = function HourglassIcon(_ref) { var color = _ref.color, title = _ref.title, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("svg", _extends({ width: "7", height: "12", viewBox: "0 0 7 12", xmlns: "http://www.w3.org/2000/svg" }, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", { d: "M6.5002-.0003v3.107l-2.263 2.643 2.263 2.644v3.106h-6.5v-3.106l2.263-2.644-2.263-2.643v-3.107h6.5zm-3.25 6.904l-1.75 2.044v1.052l.422-.001.974-.974a.5011.5011 0 01.638-.058l.069.058.974.974.423.001v-1.051l-1.75-2.045zm1.75-5.404h-3.5v1.052l.676.789c.01-.001.02-.001.031-.001h2.053l.061.004.679-.793v-1.051z", fill: color })); }; HourglassIcon.propTypes = { color: PropTypes.string, title: PropTypes.string }; HourglassIcon.defaultProps = { color: '#222', title: '' };
frontend/app/components/Contributor/states/create.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import FVButton from 'components/FVButton' import File from 'components/Form/Common/File' import Text from 'components/Form/Common/Text' import Textarea from 'components/Form/Common/Textarea' import StringHelpers from 'common/StringHelpers' import ContributorDelete from 'components/Confirmation' import { getError, getErrorFeedback } from 'common/FormHelpers' const { string, element, array, bool, func, object } = PropTypes export class ContributorStateCreate extends React.Component { static propTypes = { className: string, copy: object, groupName: string, breadcrumb: element, errors: array, isBusy: bool, isEdit: bool, isTrashed: bool, deleteItem: func, onRequestSaveForm: func, setFormRef: func, valueName: string, valueDescription: string, valuePhotoName: string, valuePhotoData: string, } static defaultProps = { className: 'FormRecorder', groupName: 'Form__group', breadcrumb: null, errors: [], isBusy: false, isEdit: false, isTrashed: false, deleteItem: () => {}, onRequestSaveForm: () => {}, setFormRef: () => {}, valueName: '', valueDescription: '', valuePhotoName: '', valuePhotoData: '', copy: { default: {}, }, } state = { deleting: false, } // NOTE: Using callback refs since on old React // https://reactjs.org/docs/refs-and-the-dom.html#callback-refs btnDeleteInitiate = null btnDeleteDeny = null render() { const { className, copy, groupName, valueName, valueDescription, valuePhotoName, valuePhotoData, breadcrumb, errors, isBusy, isTrashed, isEdit, onRequestSaveForm, setFormRef, } = this.props const _copy = isEdit ? copy.edit : copy.create return ( <form className={`${className} Contributor Contributor--create`} ref={setFormRef} onSubmit={(e) => { e.preventDefault() onRequestSaveForm() }} encType="multipart/form-data" > {breadcrumb} <div className="Contributor__btnHeader"> <button className="_btn _btn--secondary Contributor__btnBack" type="button" onClick={() => { window.history.back() }} > {_copy.btnBack} </button> {/* BTN: Delete contributor ------------- */} {isEdit && !isTrashed ? ( <ContributorDelete confirmationAction={this.props.deleteItem} className="Contributor__delete" reverse copyIsConfirmOrDenyTitle={_copy.isConfirmOrDenyTitle} copyBtnInitiate={_copy.btnInitiate} copyBtnDeny={_copy.btnDeny} copyBtnConfirm={_copy.btnConfirm} /> ) : null} </div> {isTrashed ? <div className="alert alert-danger">{_copy.isTrashed}</div> : null} <h1 className="Contributor__heading">{_copy.title}</h1> <p>{_copy.requiredNotice}</p> {/* Name ------------- */} <Text className={groupName} disabled={isTrashed} error={getError({ errors, fieldName: 'dc:title' })} id={this._clean('dc:title')} isRequired labelText={_copy.name} name="dc:title" value={valueName} /> {/* Description ------------- */} <Textarea className={groupName} disabled={isTrashed} error={getError({ errors, fieldName: 'dc:description' })} id={this._clean('dc:description')} labelText={_copy.description} name="dc:description" value={valueDescription} wysiwyg /> {/* File --------------- */} <div className={`${groupName} Contributor__photoGroup`}> {valuePhotoData && ( <div className={groupName}> <h2>{_copy.profilePhotoCurrent}</h2> <p>{valuePhotoName}</p> <img className="Contributor__photo" src={valuePhotoData} alt={`Photo representing '${valueName}'`} /> </div> )} <File className={groupName} disabled={isTrashed} handleChange={(data) => { this.setState({ createItemFile: data }) }} id={this._clean('fvcontributor:profile_picture')} labelText={valuePhotoData ? _copy.profilePhotoExists : _copy.profilePhoto} name="fvcontributor:profile_picture" value="" /> </div> {getErrorFeedback({ errors })} <div className="Contributor__btn-container"> {/* BTN: Create contributor ------------- */} {/* <button className="_btn _btn--primary" disabled={isBusy || isTrashed} type="submit"> {_copy.submit} </button> */} <FVButton variant="contained" color="primary" disabled={isBusy || isTrashed} onClick={(e) => { e.preventDefault() onRequestSaveForm() }} > {_copy.submit} </FVButton> </div> </form> ) } _clean = (name) => { return StringHelpers.clean(name, 'CLEAN_ID') } } export default ContributorStateCreate
src/routes/account/Admin/List.js
pmg1989/dva-admin
import React from 'react' import PropTypes from 'prop-types' import { Modal, Menu } from 'antd' import { DataTable, DropMenu } from 'components' import { UPDATE, STATUS, DELETE } from 'constants/options' import styles from './List.less' const confirm = Modal.confirm function List ({ accountAdmin: { list, pagination, }, loading, updatePower, deletePower, onPageChange, onDeleteItem, onEditItem, onStatusItem, }) { const handleDeleteItem = (record) => { confirm({ title: '您确定要删除这条记录吗?', onOk () { onDeleteItem(record.id) }, }) } const handleMenuClick = (key, record) => { return { [UPDATE]: onEditItem, [STATUS]: onStatusItem, [DELETE]: handleDeleteItem, }[key](record) } const columns = [ { title: '头像', dataIndex: 'avatar', key: 'avatar', width: 64, className: styles.avatar, render: text => <img width={24} src={text} alt={text} />, }, { title: '用户名', dataIndex: 'name', key: 'name', }, { title: '性别', dataIndex: 'isMale', key: 'isMale', render: text => (<span>{text ? '男' : '女'}</span>), }, { title: '手机号', dataIndex: 'phone', key: 'phone', }, { title: '邮箱', dataIndex: 'email', key: 'email', }, { title: '角色', dataIndex: 'roleName', key: 'roleName', }, { title: '地区', dataIndex: 'address', key: 'address', }, { title: '创建时间', dataIndex: 'createTime', key: 'createTime', }, { title: '状态', dataIndex: 'status', key: 'status', render: status => <span>{status ? '已启用' : '已禁用'}</span>, }, { title: '操作', key: 'operation', // width: 100, render: (text, record) => ( <DropMenu> <Menu onClick={({ key }) => handleMenuClick(key, record)}> {updatePower && <Menu.Item key={STATUS}>{record.status ? '禁用' : '启用'}</Menu.Item>} {updatePower && <Menu.Item key={UPDATE}>编辑</Menu.Item>} {deletePower && <Menu.Item key={DELETE}>删除</Menu.Item>} </Menu> </DropMenu> ), // fixed: 'right' }, ] return ( <DataTable className={styles.table} columns={columns} dataSource={list} loading={loading.effects['accountAdmin/query']} pagination={pagination} onPageChange={onPageChange} rowKey={record => record.id} /> ) } List.propTypes = { loading: PropTypes.object.isRequired, accountAdmin: PropTypes.object.isRequired, updatePower: PropTypes.bool.isRequired, deletePower: PropTypes.bool.isRequired, onPageChange: PropTypes.func.isRequired, onStatusItem: PropTypes.func.isRequired, onDeleteItem: PropTypes.func.isRequired, onEditItem: PropTypes.func.isRequired, } export default List
src/component/Tabs.js
BristolPound/cyclos-mobile-3-TownPound
import React from 'react' import { View } from 'react-native' import ScrollableTabView from 'react-native-scrollable-tab-view' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { navigateToTab, hideModal, closeConfirmation, modalState, modalOpened } from '../store/reducer/navigation' import { openLoginForm, LOGIN_STATUSES } from '../store/reducer/login' import TabBar from './tabbar/TabBar' import SearchTab from './searchTab/SearchTab' import NetworkConnection from './NetworkConnection' import SpendingTab from './spending/SpendingTab' import { updatePage, resetForm } from '../store/reducer/sendMoney' import Account from './Account' import LoginToView, { emptyStateImage } from './loggedOutState/LoginToView' import TraderScreen from './TraderScreen' import PersonScreen from './PersonScreen' import DeveloperOptions from './DeveloperOptions' import Colors from '@Colors/colors' import Config from '@Config/config' import Modal from './Modal' import SecondModal from './SecondModal' import PaymentConfirmation from './PaymentConfirmation' import ContinuePaymentAlert from './ContinuePaymentAlert' const style = { tabs: { flex: 1, backgroundColor: Colors.white }, hiddenTabBar: { height: 0 }, flex: { flex: 1 } } const componentForModalState = (state) => { switch (state) { case modalState.traderScreen: return <TraderScreen/> case modalState.personScreen: return <PersonScreen/> case modalState.developerOptions: return <DeveloperOptions/> } } const WithNetworkConnection = (props) => <View style={style.flex}> {props.children} <NetworkConnection/> </View> const Tabs = (props) => <View style={style.flex}> <ScrollableTabView // On Android devices, when the keyboard is visible it pushes the entire // view upwards. In this instance we want to hide the tab bar renderTabBar={() => ((props.dialogOpen && props.modalVisible) || !Config.ALLOW_LOGIN) ? <View style={style.hiddenTabBar}/> : <TabBar/>} tabBarPosition='bottom' initialPage={props.tabIndex} tabBarActiveTextColor={Colors.primaryBlue} style={style.tabs} page={props.tabIndex} tabBarBackgroundColor={Colors.lightGray} scrollWithoutAnimation={true} locked={true} onChangeTab={({i}) => props.navigateToTab(i)} tabBarUnderlineColor={Colors.transparent}> <WithNetworkConnection tabLabel='Search'> <SearchTab/> </WithNetworkConnection> <WithNetworkConnection tabLabel='Spending'> { props.loggedIn ? <SpendingTab/> : <LoginToView image={emptyStateImage.spending} lineOne='Log in to view' lineTwo='your spending history' /> } </WithNetworkConnection> <WithNetworkConnection tabLabel='Account'> { props.loggedIn ? <Account/> : <LoginToView image={emptyStateImage.account} lineOne='Log in to view' lineTwo='your account details' /> } </WithNetworkConnection> </ScrollableTabView> <Modal visible={props.modalVisible} hideModal={() => {!props.confirmationOpen && props.hideModal() && props.resetForm()}} modalOpened={props.modalOpened}> {componentForModalState(props.modalState)} </Modal> <SecondModal visible={props.confirmationOpen} hideModal={() => {props.closeConfirmation() && props.updatePage(0)}}> <PaymentConfirmation /> </SecondModal> {props.alertShouldPopUp && props.loggedIn && <ContinuePaymentAlert />} </View> const mapDispatchToProps = (dispatch) => bindActionCreators({ navigateToTab, hideModal, closeConfirmation, openLoginForm, updatePage, resetForm, modalOpened }, dispatch) const mapStateToProps = (state) => ({ tabIndex: state.navigation.tabIndex, modalState: state.navigation.modalState, modalVisible: state.navigation.modalVisible, loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN, status: state.status, dialogOpen: state.login.loginFormOpen, online: state.networkConnection.status, confirmationOpen: state.navigation.confirmationOpen, alertShouldPopUp: state.sendMoney.alertShouldPopUp }) export default connect(mapStateToProps, mapDispatchToProps)(Tabs)
src/Parser/HolyPaladin/Modules/Traits/SacredDawn.js
mwwscott0/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import Module from 'Parser/Core/Module'; import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing'; import Combatants from 'Parser/Core/Modules/Combatants'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; const debug = false; const SACRED_DAWN_BUFF_SPELL_ID = 243174; const SACRED_DAWN_HEALING_INCREASE = 0.1; class SacredDawn extends Module { static dependencies = { combatants: Combatants, }; healing = 0; on_initialized() { this.active = this.combatants.selected.traitsBySpellId[SPELLS.SACRED_DAWN.id] === 1; } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (this.owner.constructor.abilitiesAffectedByHealingIncreases.indexOf(spellId) === -1) { return; } if (spellId === SPELLS.BEACON_OF_LIGHT.id) { // Beacon transfer doesn't double dip, so it relies on the buff having been applied to original heal target so we need `on_beacon_heal` to calculate this. (so if a beacon target gets 10% increased healing from SD it won't increase the received beacon heals except indirectly). return; } const combatant = this.combatants.players[event.targetID]; if (!combatant) { // If combatant doesn't exist it's probably a pet. debug && console.log('Skipping event since combatant couldn\'t be found:', event); return; } // When SD isn't up, a Light of Dawn applies Sacred Dawn to the players. Until 18/4/17 this sometimes happened BEFORE the heal was triggered, but the buff didn't increase the healing. While this should no longer happen, the below `minimalActiveTime` of 5ms should make sure that if it does still happen, the non existing healing gain isn't considered. const hasBuff = combatant.hasBuff(SACRED_DAWN_BUFF_SPELL_ID, event.timestamp, undefined, 5); if (debug && spellId === SPELLS.LIGHT_OF_DAWN_HEAL.id) { const secondsIntoFight = (event.timestamp - this.owner.fight.start_time) / 1000; console.log(secondsIntoFight.toFixed(3), event.timestamp, 'LoD heal on', combatant.name, 'Sacred Dawn:', hasBuff, 'event:', event); } if (!hasBuff) { return; } this.healing += calculateEffectiveHealing(event, SACRED_DAWN_HEALING_INCREASE); } on_beacon_heal(beaconTransferEvent, healEvent) { const spellId = healEvent.ability.guid; if (this.owner.constructor.abilitiesAffectedByHealingIncreases.indexOf(spellId) === -1) { return; } const combatant = this.combatants.players[healEvent.targetID]; if (!combatant) { // If combatant doesn't exist it's probably a pet. debug && console.log('Skipping beacon heal event since combatant couldn\'t be found:', beaconTransferEvent, 'for heal:', healEvent); return; } if (!combatant.hasBuff(SACRED_DAWN_BUFF_SPELL_ID, healEvent.timestamp)) { return; } this.healing += calculateEffectiveHealing(beaconTransferEvent, SACRED_DAWN_HEALING_INCREASE); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SACRED_DAWN.id} />} value={`${formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing))} %`} label="Sacred Dawn contribution" /> ); } statisticOrder = STATISTIC_ORDER.TRAITS(10); } export default SacredDawn;
docs/src/client-render.js
seekinternational/seek-asia-style-guide
// Polyfills import 'babel-polyfill'; import 'core-js/fn/array/fill'; import 'core-js/fn/array/includes'; import 'core-js/fn/array/from'; import 'core-js/fn/string/ends-with'; import 'core-js/fn/string/includes'; import 'core-js/fn/string/starts-with'; import 'core-js/fn/object/get-own-property-symbols'; import React from 'react'; import { hydrate, render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import BrowserRouter from './BrowserRouter'; const appElement = document.getElementById('app'); const renderMethod = module.hot ? render : hydrate; renderMethod( <AppContainer> <BrowserRouter /> </AppContainer>, appElement ); if (module.hot) { module.hot.accept('./BrowserRouter', () => { const NextBrowserRouter = require('./BrowserRouter').default; render( <AppContainer> <NextBrowserRouter /> </AppContainer>, appElement ); }); }
packages/spec/integration/lambda/index.js
xing/hops
import { render, withConfig } from 'hops'; import React from 'react'; import { Helmet } from 'react-helmet-async'; const App = withConfig(({ config }) => ( <> <Helmet> <link rel="icon" href="data:;base64,iVBORw0KGgo=" /> </Helmet> <h1>hello {config.subject}</h1> </> )); export default render(<App />);
src/routes/shows/index.js
ma489/listify
import React from 'react'; import Shows from './Shows'; var radioService = require('../../lib/radio-service'); export default { path: '/shows/:stationId', async action({ path, render, params }) { var stationId = params.stationId; var shows = await radioService.getShows(stationId); return <Shows shows={shows} stationId={stationId} />; } };
src/index.js
GTyexing/react-start-kit
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
app/containers/HomePage/index.js
vonkanehoffen/wp-react
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { connect } from 'react-redux'; import { FormattedMessage } from 'react-intl'; import Helmet from 'react-helmet'; import config from 'config' import HomeSplash from 'components/HomeSplash' import RecentPosts from 'containers/RecentPosts' import './style.scss' class HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="HomePage"> <Helmet title={`Home - ${config.blogTitle}`} meta={[ { name: 'description', content: 'Kane Clover - Full Stack Developer' }, ]} /> <HomeSplash/> <div className="container blogTitle"> <h3><i className="material-icons">send</i> Blog</h3> </div> <RecentPosts/> </div> ); } } // const mapStateToProps = createStructuredSelector({ // posts: state.posts // }); // Wrap the component to inject dispatch and state into it export default HomePage
src/svg-icons/image/flash-auto.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlashAuto = (props) => ( <SvgIcon {...props}> <path d="M3 2v12h3v9l7-12H9l4-9H3zm16 0h-2l-3.2 9h1.9l.7-2h3.2l.7 2h1.9L19 2zm-2.15 5.65L18 4l1.15 3.65h-2.3z"/> </SvgIcon> ); ImageFlashAuto = pure(ImageFlashAuto); ImageFlashAuto.displayName = 'ImageFlashAuto'; ImageFlashAuto.muiName = 'SvgIcon'; export default ImageFlashAuto;
cerberus-dashboard/src/components/SecureFileForm/SecureFileForm.js
Nike-Inc/cerberus-management-service
/* * Copyright (c) 2020 Nike, inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { Component } from 'react'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import * as mSDBActions from '../../actions/manageSafetyDepositBoxActions'; import * as modalActions from '../../actions/modalActions'; import * as messengerActions from '../../actions/messengerActions'; import './SecureFileForm.scss'; import FileInput from 'react-simple-file-input'; import ConfirmationBox from '../ConfirmationBox/ConfirmationBox'; const MAX_FILE_SIZE = 250000; const fields = [ 'path', 'uploadedFile' ]; // define our client side form validation rules const validate = values => { const errors = {}; errors.kvMap = {}; if (!values.path) { errors.path = 'Required'; } return errors; }; class SecureFileForm extends Component { render() { const { fields: { path, uploadedFile }, navigatedPath, dispatch, cerberusAuthToken, handleSubmit, pathReadOnly, isFileSelected, secureFileData, secureDataKeys, isActive, formKey } = this.props; return ( <div id="add-new-secure-file-container"> <form id="add-new-secure-file-form" onSubmit={handleSubmit(data => { let isNewSecureFilePath = formKey === 'add-new-secure-file'; if (data.path in secureDataKeys) { this.confirmFileOverwrite(dispatch, cerberusAuthToken, navigatedPath, data.path, data.uploadedFile, isNewSecureFilePath); } else { dispatch(mSDBActions.uploadFile(cerberusAuthToken, navigatedPath, data.path, data.uploadedFile, isNewSecureFilePath)); } })}> {pathReadOnly && <div id="new-secure-file-path"> <div id="new-secure-file-path-label">Path:</div> <div id="new-secure-file-path-full"> {navigatedPath} <span className="new-secure-file-path-user-value-read-only">{path.value}</span> </div> </div> } {!pathReadOnly && isFileSelected && <div id="new-secure-file-path"> <div id="new-secure-file-path-label">Path:</div> <div id="new-secure-file-path-full"> {navigatedPath} <span className="new-secure-file-path-user-value-read-only">{path.value}</span> </div> </div> } <div className="secure-file-operation-buttons-container"> {isFileSelected && !isActive && <div className="secure-file-name-label"> <div className="secure-file-name">Filename: {uploadedFile.value.name}</div> <div className="secure-file-size">{this.convertBytesToKilobytes(uploadedFile.value.sizeInBytes, 2, false)} KB</div> </div> } {!isFileSelected && !isActive && <div className="secure-file-name-label"> <div className="no-file-selected">No File Selected</div> <div className="max-file-size-label">Maximum Size: {this.convertBytesToKilobytes(MAX_FILE_SIZE, 0, false)} KB</div> </div> } {isActive && <div className="secure-file-name-label"> <div className="secure-file-name">Filename: {path.value}</div> <div className="secure-file-size"> {this.convertBytesToKilobytes(secureFileData[`${navigatedPath}${path.value}`].data.sizeInBytes, 2, false)} KB </div> </div> } {!pathReadOnly && /* this div/label structure is required by the react-simple-file-input plugin */ <div><label> <FileInput readAs='buffer' style={{ display: 'none' }} onLoad={(event, file) => { let fileContents = event.target.result; let fileData = { name: file.name, sizeInBytes: file.size, type: file.type, contents: fileContents }; uploadedFile.onChange(fileData); path.onChange(file.name); dispatch(mSDBActions.secureFileSelected()); }} cancelIf={(file) => this.fileIsTooLarge(dispatch, file)} /> <div className="ncss-btn-dark-grey btn ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt3-lg pb3-lg u-uppercase un-selectable" id="new-file-form-browse-btn"> Browse </div> </label></div> } {isActive && <div className="ncss-btn-dark-grey btn ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt3-lg pb3-lg u-uppercase un-selectable" onClick={() => { mSDBActions.downloadFile(cerberusAuthToken, `${navigatedPath}${path.value}`, `${path.value}`); }}> Download </div> } {isActive && deleteButton(dispatch, navigatedPath, path.value, cerberusAuthToken) } </div> {!pathReadOnly && <div className="secure-file-button-container"> <div id="submit-btn-container"> <div className="btn-wrapper"> <button className="ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt3-lg pb3-lg u-uppercase un-selectable" disabled={secureFileData[navigatedPath + path.value] ? secureFileData[navigatedPath + path.value].isUpdating : false}> Submit </button> </div> <div className="btn-wrapper"> <div id='cancel-btn' className="ncss-btn-accent ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase un-selectable" onClick={() => { dispatch(mSDBActions.hideAddNewSecureFile()); }}> Cancel </div> </div> </div> </div> } </form> </div> ); } convertBytesToKilobytes(sizeInBytes, numDecimalPlaces, divideByPowerOfTwo) { if (divideByPowerOfTwo) { return (sizeInBytes / 1024).toFixed(numDecimalPlaces); } else { return (sizeInBytes / 1000).toFixed(numDecimalPlaces); } } fileIsTooLarge(dispatch, file) { if (file.size > MAX_FILE_SIZE) { dispatch(messengerActions.addNewMessageWithTimeout( <div className="file-validation-error-msg-container"> <div className="file-validation-error-msg-header"> <h4>{`File: '${file.name}' is too large`}</h4> </div> </div>, 15000)); return true; } return false; } confirmFileOverwrite(dispatch, cerberusAuthToken, navigatedPath, secureFileName, fileContents, isNewSecureFilePath) { let yes = () => { dispatch(mSDBActions.uploadFile(cerberusAuthToken, navigatedPath, secureFileName, fileContents, isNewSecureFilePath)); dispatch(modalActions.popModal()); }; let no = () => { dispatch(modalActions.popModal()); }; let comp = <ConfirmationBox handleYes={yes} handleNo={no} message={`Are you sure you want to overwrite file: "${secureFileName}"?`} />; dispatch(modalActions.pushModal(comp)); } } const deleteButton = (dispatch, navigatedPath, label, cerberusAuthToken) => { return ( <div className="secure-file-delete-btn btn ncss-btn-accent ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt3-lg pb3-lg u-uppercase un-selectable" onClick={() => { dispatch(mSDBActions.deleteSecureFilePathConfirm(`${navigatedPath}`, `${label}`, cerberusAuthToken)); }}> <div className="secure-file-delete-btn-label">Delete</div> </div> ); }; const mapStateToProps = state => ({ cerberusAuthToken: state.auth.cerberusAuthToken, navigatedPath: state.manageSafetyDepositBox.navigatedPath, isFileSelected: state.manageSafetyDepositBox.isFileSelected, secureFileData: state.manageSafetyDepositBox.secureFileData, secureDataKeys: state.manageSafetyDepositBox.keysForSecureDataPath }); const form = reduxForm( { form: 'add-new-secure-file', fields: fields, validate } )(SecureFileForm); export default connect(mapStateToProps)(form);
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
bradparks/actor-platform___im_client_cross_platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react'; const getStateFromStores = (userId) => { const thisPeer = PeerStore.getUserPeer(userId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer) }; }; var UserProfile = React.createClass({ propTypes: { user: React.PropTypes.object.isRequired }, mixins: [PureRenderMixin], getInitialState() { return getStateFromStores(this.props.user.id); }, componentWillMount() { DialogStore.addNotificationsListener(this.whenNotificationChanged); }, componentWillUnmount() { DialogStore.removeNotificationsListener(this.whenNotificationChanged); }, componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.user.id)); }, addToContacts() { ContactActionCreators.addContact(this.props.user.id); }, removeFromContacts() { ContactActionCreators.removeContact(this.props.user.id); }, onNotificationChange(event) { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); }, whenNotificationChanged() { this.setState(getStateFromStores(this.props.user.id)); }, render() { const user = this.props.user; const isNotificationsEnabled = this.state.isNotificationsEnabled; let addToContacts; if (user.isContact === false) { addToContacts = <a className="link__blue" onClick={this.addToContacts}>Add to contacts</a>; } else { addToContacts = <a className="link__red" onClick={this.removeFromContacts}>Remove from contacts</a>; } return ( <div className="activity__body profile"> <div className="profile__name"> <AvatarItem image={user.bigAvatar} placeholder={user.placeholder} size="medium" title={user.name}/> <h3>{user.name}</h3> </div> <div className="notifications"> <label htmlFor="notifications">Enable Notifications</label> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </div> <UserProfileContactInfo phones={user.phones}/> <ul className="profile__list profile__list--usercontrols"> <li className="profile__list__item"> {addToContacts} </li> </ul> </div> ); } }); export default UserProfile;
ReactApp/src/Cards/Program/SundayProgram.js
hoh/FolkMarsinne
import React, { Component } from 'react'; import {blue100} from 'material-ui/styles/colors'; import {DayProgram} from './ProgramComponents' import {BandDescriptions} from './BandDescriptions' const sundayPlan = [ {hour: '', 'groups': []}, {hour: '11h00', 'groups':[false, {name: 'Vendée - Dames de Nage (FR) atelier de danse', kind: 'workshop', duration: 3, kind: 'learn'}, false, false]}, {hour: '11h30', 'groups':[false, true, false, false]}, {hour: '12h00', 'groups':[false, true, false, false]}, {hour: '12h30', 'groups':[false, false, {name: 'Suède - Aurélie Giet & Väsen (SE) atelier de danse', kind: 'workshop', duration: 3, kind: 'learn'}, false]}, {hour: '13h00', 'groups':[{name: 'Grand Air (BE) concert', kind: 'concert', duration: 2, kind: 'concert'}, {name: 'Dames de Nage (FR) bal', kind: 'bal', duration: 3, kind: 'bal'}, true, false]}, {hour: '13h30', 'groups':[true, true, true, false]}, {hour: '14h00', 'groups':[false, true, false, {name: 'Théâtre Mabotte (BE) théatre enfants', duration: 1, kind: 'theatre'}]}, {hour: '14h30', 'groups':[false, false, {name: 'Väsen (SE) bal', duration: 3, kind: 'bal'}, {name: 'Les Djoweus D\'danses (Podium libre)', duration: 2, kind: 'free'}]}, {hour: '15h00', 'groups':[false, false, true, true]}, {hour: '15h30', 'groups':[false, false, true, {name: 'Théâtre Mabotte (BE) théatre enfants', duration: 1, kind: 'theatre'}]}, {hour: '16h00', 'groups':[{name: 'Zim Boum Trad (BE) bal pour enfants', duration: 2, kind: 'bal'}, {name: 'Boutons & Ficelles (BE) bal', duration: 4, kind: 'bal'}, false, false]}, {hour: '16h30', 'groups':[true, true, false, false]}, {hour: '17h00', 'groups':[false, true, false, false]}, {hour: '17h30', 'groups':[false, true, false, {name: 'Théâtre Mabotte (BE) théatre enfants', duration: 1, kind: 'theatre'}]}, {hour: '18h00', 'groups':[false, false, {name: 'Grand Boeuf du 25ème bal', kind: 'bal', duration: 4}, {name: 'Podium libre', duration: 2, kind: 'free'}]}, {hour: '18h30', 'groups':[false, false, true, true]}, {hour: '19h00', 'groups':[{name: 'Duo Mc Gowan - Munelly (IE) concert', kind: 'concert', duration: 3}, false, true, false]}, {hour: '19h30', 'groups':[true, false, true, false]}, {hour: '20h00', 'groups':[true, {name: 'Carré Manchot (FR) bal', kind: 'bal', duration: 4}, false, false]}, {hour: '20h30', 'groups':[false, true, false, {name: 'EÄ (Podium libre)', duration: 2, kind: 'free'}]}, {hour: '21h00', 'groups':[false, true, false, true]}, {hour: '21h30', 'groups':[false, true, false, false]}, {hour: '22h00', 'groups':[{name: 'Duo Botasso (IT) bal', kind: 'bal', duration: 4}, false, false, false]}, {hour: '22h30', 'groups':[true, false, false, false]}, {hour: '23h00', 'groups':[true, false, false, false]}, {hour: '23h30', 'groups':[true, false, false, false]}, {hour: '00h00', 'groups':[false, false, false, false]}, ]; const sundayBands = [ { name: 'Atelier danse: Vendée', kind: 'learn', from: 'France', members: [ {name: 'Valérie Imbert', instruments: ['chant']}, {name: 'Brigitte Kloareg', instruments: ['chant']}, ], links: [ 'https://www.youtube.com/watch?v=RbrA4pb_ON4', 'https://www.youtube.com/watch?v=QCb6P7NkqS4', 'https://www.youtube.com/watch?v=EkMHfaA5P', ] }, { name: 'Dames de nage', kind: 'bal', from: 'France', members: [ {name: 'Valérie Imbert', instruments: ['chant']}, {name: 'Brigitte Kloareg', instruments: ['chant']}, ], links: [ 'https://www.youtube.com/watch?v=RbrA4pb_ON4', 'https://www.youtube.com/watch?v=QCb6P7NkqS4', 'https://www.youtube.com/watch?v=EkMHfaA5P', ] }, { name: 'Grand Air', kind: 'concert', from: 'Belgique - Wallonie', members: [ {name: 'Catherine Blanjean', instruments: ['violon','alto']}, {name: 'Pierre Brasseur', instruments: ['mandoline', 'clarinette']}, {name: 'Michel Jacqmain', instruments: ['cistre','guitare']}, {name: 'Julien Maréchal', instruments: ['violon']}, {name: 'Patrick Van Uffelen', instruments: ['bodhran', 'tin whistle']}, ], links: [ '', ] }, { name: 'Atelier de danse: Suède', kind: 'learn', from: 'Suède', members: [ {name: 'Olov Johansson', instruments: ['nyckelharpa']}, {name: 'Mickael Marin', instruments: ['alto']}, {name: 'Roger Tallroch', instruments: ['guitare']}, {name: 'Aurélie Giet', instruments: ['danse']}, ], links: [ 'http://www.aureliegiet.be', 'http://www.vasen.se/', ] }, { name: 'Väsen', kind: 'concert', from: 'Suède', members: [ {name: 'Olov Johansson', instruments: ['nyckelharpa']}, {name: 'Mickael Marin', instruments: ['alto']}, {name: 'Roger Tallroch', instruments: ['guitare']}, ], links: [ 'http://www.vasen.se/', 'https://www.youtube.com/watch?v=tWorsJwzycw', 'https://www.youtube.com/watch?v=770ig9bYZYM', 'https://www.youtube.com/watch?v=7gWLH7ZrMgw', 'https://www.youtube.com/watch?v=FcYliDfOQ6Q ', ] }, { name: 'Zim Boum Trad', kind: 'bal pour enfants', from: 'Belgique - Wallonie', members: [ {name: 'Etienne Evrats', instruments: ['']}, {name: 'Marinette Bonnert', instruments: ['accordéon diatonique']}, {name: 'Pierre Challe', instruments: ['guitare']}, ], links: [ 'http://zimboumtrad.weebly.com/?', 'https://www.facebook.com/zimboumtrad', 'https://youtu.be/PP2hRVRCK4Q', ] }, { name: 'Boutons & Ficelles', kind: 'bal', from: 'Belgique - Wallonie', members: [ {name: 'Vincent Jadot', instruments: ['guitares']}, {name: 'Benoît Marthus', instruments: ['accordéon diatonique', 'mandoline']}, {name: 'Pierre Matagne', instruments: ['guitares']}, {name: 'Frédéric Nicolas', instruments: ['cornemuse', 'flûtes', 'bodhran']}, {name: 'Joël Schallenbergh', instruments: ['guitare', 'bouzouki', 'banjo']}, {name: 'Alexandre Warnant', instruments: ['djembé']}, ], links: [ 'https://www.facebook.com/boutonsetficelles/ ', ] }, { name: 'Grand boeuf du 25e', kind: 'bal', from: '', members: [ {name: '-', instruments: ['']}, ], links: [ 'https://www.dropbox.com/sh/ksddlq7haz7e2me/AAA63LHOorATzDAyBZOZMaTMa?dl=0 ', ] }, { name: 'Duo McGowan - Munnelly', kind: 'concert', from: 'Irlande', members: [ {name: 'Shane mc Gowan', instruments: ['guitare']}, {name: 'David Munnelly', instruments: ['accordéon diatonique']}, ], links: [ 'http://davidmunnelly.com/munnelly-mcgowan/', 'https://www.youtube.com/watch?v=0ByfCReKTfA&feature=share', 'https://youtu.be/NHYISawoY3c', 'https://youtu.be/7vy7nJ-FcAo', 'https://youtu.be/tIugpzTj9p4', ] }, { name: 'Carré Manchot', kind: 'bal - fest-noz', from: 'France', members: [ {name: 'Yannig Alory', instruments: ['flûte traversière en bois']}, {name: 'Loïc Bléjean', instruments: ['uileann pipes', 'low whistles']}, {name: 'Yann-Loïc Joly', instruments: ['accordéon diatonique']}, {name: 'Gilbert Le Pennec', instruments: ['guitare']}, {name: 'Patrick Marie', instruments: ['chant']}, ], links: [ 'http://www.carremanchot.fr/', 'https://youtu.be/XytH9QHIojE', 'https://youtu.be/APXkRtxw2wA', ] }, { name: 'Duo Bottasso', kind: 'bal', from: 'Italie', members: [ {name: 'Nicolò Bottasso', instruments: ['violon']}, {name: 'Simone Bottasso', instruments: ['accordéon diatonique']}, ], links: [ 'http://www.duobottasso.com', 'https://www.youtube.com/watch?feature=player_embedded&v=c82PUHf7hww', 'https://www.youtube.com/watch?v=NBJTqHFA6h8', 'https://youtu.be/ELMpLOHkQbk', ] }, ] export default class SundayProgram extends React.Component { render() { return ( <div> <DayProgram plan={sundayPlan} lang={this.props.lang} /> <BandDescriptions bands={sundayBands} lang={this.props.lang} /> </div> ); } }
app/scripts/components/OrderForm.js
DDDas/reactjs-datagrid-widgets
import React from 'react'; import InputField from './InputField'; import OrderFluxStore from '../stores/flux/OrderFluxStore'; class OrderForm extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div> <label>Order Id</label> <InputField name='orderId' value={this.props.order.orderId} resource={'order'} handleChange={this.props.onChange}/> </div> <div> <label>Order Name</label> <InputField name='orderName' value={this.props.order.orderName} resource={'order'} handleChange={this.props.onChange}/> </div> <div> <label>Order Type</label> <InputField name='orderType' value={this.props.order.orderType} resource={'order'} handleChange={this.props.onChange}/> </div> <div> <label>Delivery Type</label> <InputField name='deliveryType' value={this.props.order.deliveryType} resource={'order'} handleChange={this.props.onChange}/> </div> </div> ); } } export default OrderForm;
examples/todos/index.js
vizidrix/cqjs
import React from 'react' import ReactDOM from 'react-dom' import Todo from './components/Todo' import { System, View } from 'cqjs' import * as DOMAINDEF from './domains/Todo' const SYSTEM = new System(DOMAINDEF.DOMAIN) const rootEl = document.getElementById('root') function render() { ReactDOM.render( <Todo />, rootEl ) } render() SYSTEM.subscribe(() => render())
src/icons/VideocamOffIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class VideocamOffIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M42 13l-8 8v-7c0-1.1-.9-2-2-2H19.64L42 34.36V13zM6.55 4L4 6.55 9.45 12H8c-1.1 0-2 .9-2 2v20c0 1.1.9 2 2 2h24c.41 0 .77-.15 1.09-.37L39.46 42 42 39.45 6.55 4z"/></svg>;} };
vertex_ui/src/components/Sidebar/components/Menu/Menu.js
zapcoop/vertex
import React from 'react'; import { PropTypes } from 'prop-types'; import { Link } from 'react-router'; import _ from 'underscore'; import classNames from 'classnames'; import velocity from 'velocity-animate'; import { SIDEBAR_STYLE_SLIM, SIDEBAR_STYLE_DEFAULT, SIDEBAR_STYLE_BIGICONS, } from 'layouts/AdminLayout/modules/layout'; import SIDEBAR_CONFIG, { findActiveNodes } from 'routes/routesStructure'; import classes from './../../Sidebar.scss'; let animationInProgress = false; let lastExpandedNodes = []; const findSubmenu = parentNodeElement => _.find( parentNodeElement.children, childElement => childElement.tagName === 'UL', ); // Animate open and close const animateOpenNode = ( nodeElement, cbComplete, cbStart, animationSettings, ) => { const subMenuElement = findSubmenu(nodeElement); animationInProgress = true; subMenuElement.style.display = 'block'; Velocity( subMenuElement, { height: [subMenuElement.scrollHeight, 0], }, { ...animationSettings, complete: () => { subMenuElement.style.height = null; animationInProgress = false; cbComplete(); }, }, ); cbStart({ heightDiff: subMenuElement.scrollHeight, }); }; const animateCloseNode = ( nodeElement, cbComplete, cbStart, animationSettings, ) => { const subMenuElement = findSubmenu(nodeElement); if (!subMenuElement) { return; } animationInProgress = true; Velocity( subMenuElement, { height: [0, subMenuElement.scrollHeight], }, { ...animationSettings, complete: () => { subMenuElement.style.height = null; animationInProgress = false; cbComplete(); }, }, ); cbStart({ heightDiff: -subMenuElement.scrollHeight, }); }; class Menu extends React.Component { static propTypes = { currentUrl: PropTypes.string, sidebarStyle: PropTypes.string, onHeightChange: PropTypes.func, animationDuration: PropTypes.node, animationEasing: PropTypes.string, }; static defaultProps = { sidebarStyle: SIDEBAR_STYLE_DEFAULT, onHeightChange: () => {}, animationDuration: 300, animationEasing: 'ease-in-out', }; constructor() { super(); this.state = Object.assign({}, this.state, { expandedNodes: [], }); } expandNode(nodeDef, expand = true) { if (animationInProgress) { return; } const { state, setState } = this; const currentLevelExpandedNode = _.find( state.expandedNodes, node => node.subMenuLevel === nodeDef.subMenuLevel, ); const nextExpandedNodes = _.without( state.expandedNodes, currentLevelExpandedNode, ); const updateState = expandedNodes => { const newState = Object.assign({}, state, { expandedNodes }); this.setState(newState); }; // Animate close and update state if no other node will be expanded if (currentLevelExpandedNode) { animateCloseNode( currentLevelExpandedNode.element, () => !expand && updateState(nextExpandedNodes), e => { this.props.onHeightChange(e.heightDiff); }, ); } if (expand) { nextExpandedNodes.push(nodeDef); animateOpenNode( nodeDef.element, () => updateState(nextExpandedNodes), e => { this.props.onHeightChange(e.heightDiff); }, ); } } isNodeExpanded(nodeDef) { const { state } = this; return _.some( state.expandedNodes, node => node.subMenuLevel === nodeDef.subMenuLevel && node.key === nodeDef.key, ); } toggleNode(nodeDef) { const isExpanded = this.isNodeExpanded(nodeDef); this.expandNode(nodeDef, !isExpanded); } setSidebarNodesHighlights(url) { if (this.props.currentUrl) { const activeNodes = findActiveNodes(SIDEBAR_CONFIG, url); this.setState( Object.assign({}, this.state, { activeNodes, expandedNodes: activeNodes, }), ); } } generateLink(nodeDef) { const linkContent = []; const clickHandler = nodeDef => { if ( this.props.sidebarStyle === SIDEBAR_STYLE_DEFAULT || (this.props.sidebarStyle === SIDEBAR_STYLE_BIGICONS && nodeDef.subMenuLevel > 0) ) { this.toggleNode(nodeDef); } }; if (nodeDef.children) { return ( <a href="javascript:void(0)" onClick={() => clickHandler(nodeDef)} className={classes.containerLink} > {nodeDef.icon ? <i className={nodeDef.icon} /> : null} <span className="nav-label">{nodeDef.title}</span> {nodeDef.sidebarElement ? ( nodeDef.sidebarElement ) : nodeDef.children ? ( <i className="fa arrow" /> ) : null} </a> ); } else { return nodeDef.external ? ( <a href={nodeDef.url} className={classes.sidebarLink} target={nodeDef.newTab ? '_blank' : '_self'} > {nodeDef.icon ? <i className={nodeDef.icon} /> : null} <div className={classes.sidebarLinkText}> <span className="nav-label">{nodeDef.title}</span> {nodeDef.sidebarElement} </div> </a> ) : ( <Link to={nodeDef.url} className={classes.sidebarLink}> {nodeDef.icon ? <i className={nodeDef.icon} /> : null} <div className={classes.sidebarLinkText}> <span className="nav-label">{nodeDef.title}</span> {nodeDef.sidebarElement} </div> </Link> ); } } generateSubNodes(nodeDefs, subMenuLevel = 1, title = false) { const nodes = _.map(nodeDefs, nodeDef => { const classes = classNames({ 'has-submenu': !!nodeDef.children, expanded: this.props.sidebarStyle !== SIDEBAR_STYLE_SLIM && this.isNodeExpanded(nodeDef), 'nested-active': nodeDef.children && _.contains(this.state.activeNodes, nodeDef), active: nodeDef.url && _.contains(this.state.activeNodes, nodeDef), }); return ( <li key={nodeDef.key} className={classes} ref={element => (nodeDef.element = element)} > {this.generateLink(nodeDef)} {nodeDef.children ? this.generateSubNodes(nodeDef.children, subMenuLevel + 1) : null} </li> ); }); return ( <ul className={`submenu-level-${subMenuLevel}`} style={{ display: this.props.sidebarStyle === SIDEBAR_STYLE_DEFAULT ? 'block' : '', }} data-submenu-title={title} > {nodes} </ul> ); } generateRootNodes(nodeDefs) { const { state } = this; const nodes = _.map(nodeDefs, nodeDef => { const classes = classNames('primary-submenu', { 'has-submenu': !!nodeDef.children, expanded: this.props.sidebarStyle === SIDEBAR_STYLE_DEFAULT && this.isNodeExpanded(nodeDef), 'nested-active': nodeDef.children && _.contains(this.state.activeNodes, nodeDef), active: nodeDef.url && _.contains(this.state.activeNodes, nodeDef), }); return ( <li key={nodeDef.key} className={classes} ref={element => (nodeDef.element = element)} > {this.generateLink(nodeDef)} {nodeDef.children ? this.generateSubNodes(nodeDef.children, 1, nodeDef.title) : null} </li> ); }); return nodes; } componentWillMount() { this.setSidebarNodesHighlights(this.props.currentUrl); } componentWillReceiveProps(nextProps) { if (nextProps.currentUrl !== this.props.currentUrl) { this.setSidebarNodesHighlights(nextProps.currentUrl); } if (nextProps.sidebarStyle !== this.props.sidebarStyle) { if (nextProps.sidebarStyle !== SIDEBAR_STYLE_DEFAULT) { this.setState(Object.assign({}, this.state, { expandedNodes: [] })); } else { this.setSidebarNodesHighlights(this.props.currentUrl); } } } render() { return ( <ul className="side-menu">{this.generateRootNodes(SIDEBAR_CONFIG)}</ul> ); } } export default Menu;
src/pages/UserApp.js
CurtisMBSmith/web-frontend-proto
import React from 'react'; import UserBox from '../containers/UserBox'; import SideBar from '../containers/SideBar'; import { createTask } from '../actions'; const UserApp = () => { return ( <div> <SideBar /> <div className="main-panel" > <UserBox /> </div> </div> )}; export default UserApp;
src/routes/message/index.js
nambawan/g-old
import React from 'react'; import Layout from '../../components/Layout'; import { getSessionUser } from '../../reducers'; import updateNotificationStatus from '../notificationHelper'; import { loadMessage } from '../../actions/message'; import MessageContainer from './MessageContainer'; import { createRedirectLink } from '../utils'; const title = 'Message'; async function action({ store, path, query }, { id }) { const state = store.getState(); const user = getSessionUser(state); if (!user) { return { redirect: createRedirectLink(path, query) }; } await store.dispatch(loadMessage(id)); updateNotificationStatus(store, query); return { title, chunks: ['message'], component: ( <Layout> <MessageContainer id={id} /> </Layout> ), }; } export default action;
src/layouts/CoreLayout/CoreLayout.js
shengnian/webpack2-react-redux-starter
import React from 'react' import Header from '../../components/Header' import './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='out-wrapper'> <Header /> <div className='row-fluid'> {children} </div> </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
client/packages/core-dashboard-worona/src/dashboard/loading-dashboard-theme-worona/components/Theme/index.js
worona/worona-dashboard
import React from 'react'; import Footer from '../Footer'; import styles from './style.css'; export const Theme = ({ children }) => ( <div className={styles.app}> <div></div> <div className={styles.main}> {children} </div> <div className={styles.footer}> <Footer /> </div> </div> ); Theme.propTypes = { children: React.PropTypes.node.isRequired, }; export default Theme;
assets/src/js/index.js
imperodesign/clever-pages-admin
'use strict' import 'babel-polyfill' import $ from 'jquery' import 'bootstrap' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { ReduxRouter } from 'redux-router' import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <ReduxRouter /> </Provider>, document.getElementById('reactPages') )
app/components/LandingPage.js
jaimemarijke/carbon-zero-ui
import React from 'react'; import styles from './LandingPage.scss'; const LandingPage = () => ( <div className={styles.banner}> <div className={styles.headline}> <b>Zero</b> your carbon impact. </div> <div> <div className={styles.totalFootprint}> <div className={styles.datum}> <div className={styles.number}>20</div> <div style={{display: 'inline'}}> tons CO<sub>2</sub>e<sup>*</sup></div> </div> <div className={styles.tagline}> (average US carbon footprint)</div> </div> <button className={styles.button}> Zero me </button> </div> <div className={styles.footer}>{`*https://www.sciencedaily.com/releases/2008/04/080428120658.htm`}</div> </div> ); export default LandingPage;
src/containers/devTools.js
ndxm/nd-react-scaffold
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'> <LogMonitor theme='tomorrow'/> </DockMonitor> );
src/components/HeaderBar/CurrentDJ.js
u-wave/web
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; function CurrentDJ({ className, dj }) { const { t } = useTranslator(); return ( <div className={className}> {t('booth.currentDJ', { user: dj.username })} </div> ); } CurrentDJ.propTypes = { className: PropTypes.string, dj: PropTypes.shape({ username: PropTypes.string.isRequired, }), }; export default CurrentDJ;
examples/huge-apps/routes/Profile/components/Profile.js
opichals/react-router
import React from 'react'; class Profile extends React.Component { render () { return ( <div> <h2>Profile</h2> </div> ); } } export default Profile;
demo/containers/forms.js
nbonamy/react-native-app-components
import React, { Component } from 'react'; import { StyleSheet, Alert, ScrollView, View, Text } from 'react-native'; import { theme, Input, Picker, PickerItem } from 'react-native-app-components'; export default class Forms extends Component { constructor(props) { super(props); this.state = { country: 'France' }; } render() { return ( <ScrollView style={{paddingBottom: 32, paddingLeft: 16, paddingRight: 16}}> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>INPUT</Text> <Input style={styles.input} placeholder="Username" autoCorrect={false} autoCapitalize="none" /> <Input secureTextEntry style={styles.input} placeholder="Password" /> </View> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>PICKER</Text> <Picker title="Picker" buttonLabel={'Select a country. Current value = ' + this.state.country} navigation={this.props.navigation} onValueChange={(value) => this.setState({country: value})} selectedValue={this.state.country} > <PickerItem label="France" value="France" /> <PickerItem label="Germany" value="Germany" /> <PickerItem label="Italy" value="Italy" /> <PickerItem label="Spain" value="Spain" /> </Picker> </View> </ScrollView> ); } } const styles = StyleSheet.create({ title: { fontSize: 18, marginTop: 32, marginBottom: 16, color: theme.colors.dark, }, input: { marginBottom: 16, }, });
src/svg-icons/av/web-asset.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvWebAsset = (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-.89-2-2-2zm0 14H5V8h14v10z"/> </SvgIcon> ); AvWebAsset = pure(AvWebAsset); AvWebAsset.displayName = 'AvWebAsset'; AvWebAsset.muiName = 'SvgIcon'; export default AvWebAsset;
docs/app/Examples/modules/Popup/Variations/PopupExampleOffset.js
shengnian/shengnian-ui-react
import React from 'react' import { Icon, Popup } from 'shengnian-ui-react' const PopupExampleOffset = () => ( <div> <Popup trigger={<Icon size='large' name='heart' circular />} content='Way off to the left' offset={50} position='left center' /> <Popup trigger={<Icon size='large' name='heart' circular />} content='As expected this popup is way off to the right' offset={50} position='right center' /> </div> ) export default PopupExampleOffset
packages/blog/client/index.js
matthias-reis/woodward
import React from 'react'; import jss from 'jss'; const styles = { hallo: { fontSize: 120, color: 'tomatored' } }; const { classes } = jss.createStyleSheet(styles).attach(); export default () => <h1 className={classes.hallo}>Hallo Woodward!</h1>;
envkey-react/src/components/shared/confirm_action.js
envkey/envkey-app
import React from 'react' import h from "lib/ui/hyperscript_with_helpers" export default function({confirmText, onConfirm, onCancel, cancelLabel="Cancel", confirmLabel="Confirm"}) { return h.div(".confirm-action", [ h.span(confirmText), h.div(".actions", [ h.button(".cancel", {onClick: onCancel}, cancelLabel), h.button(".confirm", {onClick: onConfirm}, confirmLabel) ]) ]) }
index.js
cuiyueshuai/react-native-radio-form
/** * react-native-radio-form * radio component for react native, it works on iOS and Android * https://github.com/cuiyueshuai/react-native-radio-form.git */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, ScrollView, TouchableWithoutFeedback, Dimensions } from 'react-native'; const WINDOW_WIDTH = Dimensions.get('window').width; class RadioForm extends Component { constructor(props) { super(props); this._onPress = this._onPress.bind(this); this.renderRadioCircle = this.renderRadioCircle.bind(this); this.renderRadioItem = this.renderRadioItem.bind(this); this.state = { is_active_index: props.initial }; } static propTypes = { dataSource: PropTypes.array, initial: PropTypes.any, formHorizontal: PropTypes.bool, labelHorizontal: PropTypes.bool, itemShowKey: PropTypes.string, itemRealKey: PropTypes.string, circleSize: PropTypes.number, outerColor: PropTypes.string, innerColor: PropTypes.string, onPress: PropTypes.func, }; static defaultProps = { dataSource: [], initial: 0, formHorizontal: false, labelHorizontal: true, itemShowKey: 'label', itemRealKey: 'value', circleSize: 20, outerColor: '#2f86d5', innerColor: '#2f86d5' }; componentDidMount() { const { itemShowKey, itemRealKey, initial, dataSource } = this.props; if (typeof (initial) === 'number') return; dataSource.map((item, i) => { // eslint-disable-line if ((item[itemShowKey] === initial || item[itemRealKey] === initial)) { this.setState({ is_active_index: i }); return i; } }); } _onPress(item, index) { this.setState({ is_active_index: index }); if (this.props.onPress) { this.props.onPress(item, index); } } renderRadioItem(item, i) { const { itemShowKey } = this.props; let isSelected = false; if (this.state.is_active_index === i) { isSelected = true; } return ( <TouchableWithoutFeedback key={i} onPress={() => this._onPress(item, i)} > <View style={{ padding: 2.5, flexDirection: this.props.labelHorizontal ? 'row' : 'column', justifyContent: 'center', alignItems: 'center' }} > {this.renderRadioCircle(isSelected)} <View style={{ marginLeft: 3 }} > <Text>{'' + item[itemShowKey]}</Text> </View> </View> </TouchableWithoutFeedback> ); } renderRadioCircle(isSelected) { const outerSize = this.props.circleSize > 11 ? this.props.circleSize : 11; const innerSize = this.props.circleSize - 7; return ( <View style={{ width: outerSize, height: outerSize, margin: 5, justifyContent: 'center', alignItems: 'center', borderRadius: outerSize / 2, borderWidth: 2, borderColor: this.props.outerColor }} > <View style={{ width: innerSize, height: innerSize, borderRadius: innerSize / 2, backgroundColor: isSelected ? this.props.innerColor : 'transparent' }} /> </View> ); } render() { return ( <ScrollView {...this.props} contentContainerStyle={{ alignItems: 'flex-start', flexDirection: this.props.formHorizontal ? 'row' : 'column', flexWrap: 'wrap', padding: 5 }} style={[{ width: WINDOW_WIDTH }, this.props.style]} > { this.props.dataSource.map((item, i) => this.renderRadioItem(item, i)) } </ScrollView> ); } } export default RadioForm;
src/components/heading/heading.js
bokuweb/re-bulma
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../../build/styles'; import { getCallbacks } from '../../helper/helper'; export default class Heading extends Component { static propTypes = { style: PropTypes.object, children: PropTypes.any, className: PropTypes.string, }; static defaultProps = { style: {}, className: '', }; createClassName() { return [ styles.heading, this.props.className, ].join(' ').trim(); } render() { return ( <p {...getCallbacks(this.props)} style={this.props.style} className={this.createClassName()} > {this.props.children} </p> ); } }
webpack/scenes/RedHatRepositories/components/SearchBar.js
ares/katello
/* eslint-disable import/no-extraneous-dependencies */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Form, FormGroup } from 'react-bootstrap'; import { selectOrganizationProducts } from '../../../redux/OrganizationProducts/OrganizationProductsSelectors'; import { loadOrganizationProducts } from '../../../redux/OrganizationProducts/OrganizationProductsActions'; import { loadEnabledRepos } from '../../../redux/actions/RedHatRepositories/enabled'; import { loadRepositorySets } from '../../../redux/actions/RedHatRepositories/sets'; import Search from './Search'; import MultiSelect from '../../../components/MultiSelect/index'; const filterOptions = [ { value: 'rpm', label: __('RPM') }, { value: 'sourceRpm', label: __('Source RPM') }, { value: 'debugRpm', label: __('Debug RPM') }, { value: 'kickstart', label: __('Kickstart') }, { value: 'ostree', label: __('OSTree') }, { value: 'beta', label: __('Beta') }, { value: 'other', label: __('Other') }, ]; class SearchBar extends Component { constructor(props) { super(props); this.state = { query: '', searchList: 'available', filters: ['rpm'], }; this.onSearch = this.onSearch.bind(this); this.onSelectSearchList = this.onSelectSearchList.bind(this); } componentDidMount() { // load all products until we use filtering and pagination this.props.loadOrganizationProducts({ per_page: 1000, redhat_only: true }); } onSearch(query) { this.updateSearch({ query }); } onSelectSearchList(searchList) { this.updateSearch({ searchList }); } onSelectFilterType(filters) { this.updateSearch({ filters }); } onSelectProduct(products) { this.updateSearch({ products }); } updateSearch(stateUpdate = {}) { const newState = { ...this.state, ...stateUpdate, }; this.setState(stateUpdate); const clearSearch = stateUpdate.searchList ? {} : null; if (newState.searchList === 'available') { this.reloadRepos(newState, clearSearch); } else if (newState.searchList === 'enabled') { this.reloadRepos(clearSearch, newState); } else { this.reloadRepos(newState, newState); } } reloadRepos(repoSetsSearch, enabledSearch) { if (repoSetsSearch !== null) { const setsParams = { perPage: this.props.repositorySets.pagination.perPage, search: repoSetsSearch, }; this.props.loadRepositorySets(setsParams); } if (enabledSearch !== null) { const enabledParams = { perPage: this.props.enabledRepositories.pagination.perPage, search: enabledSearch, }; this.props.loadEnabledRepos(enabledParams); } } render() { const { organizationProducts } = this.props; const getMultiSelectValuesFromEvent = e => [...e.target.options] .filter(({ selected }) => selected) .map(({ value }) => value); return ( <Form className="toolbar-pf-actions"> <div className="search-bar-row"> <FormGroup className="toolbar-pf-filter"> <Search onSearch={this.onSearch} onSelectSearchList={this.onSelectSearchList} /> </FormGroup> </div> <div className="search-bar-row search-bar-selects-row"> <MultiSelect className="product-select" value="product" options={organizationProducts.map(product => ({ value: product.id, label: product.name, }))} defaultValues={[]} noneSelectedText={__('Filter by Product')} maxItemsCountForFullLabel={2} onChange={(e) => { const values = getMultiSelectValuesFromEvent(e); this.onSelectProduct(values); }} /> <MultiSelect value={this.state.filters} options={filterOptions} defaultValues={['rpm']} noneSelectedText={__('Filter by type')} onChange={(e) => { const values = [...e.target.options] .filter(({ selected }) => selected) .map(({ value }) => value); this.onSelectFilterType(values); }} /> </div> </Form> ); } } SearchBar.propTypes = { loadEnabledRepos: PropTypes.func.isRequired, loadRepositorySets: PropTypes.func.isRequired, loadOrganizationProducts: PropTypes.func.isRequired, organizationProducts: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), name: PropTypes.string, })).isRequired, enabledRepositories: PropTypes.shape({ pagination: PropTypes.shape({ perPage: PropTypes.number, }), }).isRequired, repositorySets: PropTypes.shape({ pagination: PropTypes.shape({ perPage: PropTypes.number, }), }).isRequired, }; const mapStateToProps = (state) => { const { katello: { redHatRepositories: { enabled, sets } } } = state; return { enabledRepositories: enabled, repositorySets: sets, organizationProducts: selectOrganizationProducts(state), }; }; export default connect(mapStateToProps, { loadEnabledRepos, loadRepositorySets, loadOrganizationProducts, })(SearchBar);
dispatch/static/manager/src/js/components/inputs/selects/SubsectionSelectInput.js
ubyssey/dispatch
import React from 'react' import { connect } from 'react-redux' import ItemSelectInput from './ItemSelectInput' import subsectionsActions from '../../../actions/SubsectionsActions' class SubsectionSelectInputComponent extends React.Component { listSubsections(query) { let queryObj = {} if (query) { queryObj['q'] = query } this.props.listSubsections(this.props.token, queryObj) } render() { return ( <ItemSelectInput many={this.props.many} value={this.props.value} showSortableList={true} results={this.props.subsections.ids} entities={this.props.entities.subsections} onChange={(value) => this.props.update(value)} fetchResults={(query) => this.listSubsections(query)} attribute='name' editMessage={this.props.value ? 'Edit subsection' : 'Add subsection'} /> ) } } const mapStateToProps = (state) => { return { subsections: state.app.subsections.list, entities: { subsections: state.app.entities.subsections }, token: state.app.auth.token } } const mapDispatchToProps = (dispatch) => { return { listSubsections: (token, query) => { dispatch(subsectionsActions.list(token, query)) } } } const SubsectionSelectInput = connect( mapStateToProps, mapDispatchToProps )(SubsectionSelectInputComponent) export default SubsectionSelectInput
examples/demo-react-native/storybook/stories/CenterView/index.js
infinitered/reactotron
import React from 'react' import PropTypes from 'prop-types' import { View } from 'react-native' import style from './style' export default function CenterView (props) { return <View style={style.main}>{props.children}</View> } CenterView.defaultProps = { children: null } CenterView.propTypes = { children: PropTypes.node }
app/javascript/mastodon/components/permalink.js
SerCom-KC/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class Permalink extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { className: PropTypes.string, href: PropTypes.string.isRequired, to: PropTypes.string.isRequired, children: PropTypes.node, onInterceptClick: PropTypes.func, }; handleClick = e => { if (this.props.onInterceptClick && this.props.onInterceptClick()) { e.preventDefault(); return; } if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(this.props.to); } } render () { const { href, children, className, onInterceptClick, ...other } = this.props; return ( <a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}> {children} </a> ); } }
src/CollapsibleMixin.js
leozdgao/react-bootstrap
import React from 'react'; import TransitionEvents from './utils/TransitionEvents'; const CollapsibleMixin = { propTypes: { defaultExpanded: React.PropTypes.bool, expanded: React.PropTypes.bool }, getInitialState(){ let defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false; return { expanded: defaultExpanded, collapsing: false }; }, componentWillUpdate(nextProps, nextState){ let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded; if (willExpanded === this.isExpanded()) { return; } // if the expanded state is being toggled, ensure node has a dimension value // this is needed for the animation to work and needs to be set before // the collapsing class is applied (after collapsing is applied the in class // is removed and the node's dimension will be wrong) let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = '0'; if(!willExpanded){ value = this.getCollapsibleDimensionValue(); } node.style[dimension] = value + 'px'; this._afterWillUpdate(); }, componentDidUpdate(prevProps, prevState){ // check if expanded is being toggled; if so, set collapsing this._checkToggleCollapsing(prevProps, prevState); // check if collapsing was turned on; if so, start animation this._checkStartAnimation(); }, // helps enable test stubs _afterWillUpdate(){ }, _checkStartAnimation(){ if(!this.state.collapsing) { return; } let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = this.getCollapsibleDimensionValue(); // setting the dimension here starts the transition animation let result; if(this.isExpanded()) { result = value + 'px'; } else { result = '0px'; } node.style[dimension] = result; }, _checkToggleCollapsing(prevProps, prevState){ let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded; let isExpanded = this.isExpanded(); if(wasExpanded !== isExpanded){ if(wasExpanded) { this._handleCollapse(); } else { this._handleExpand(); } } }, _handleExpand(){ let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let complete = () => { this._removeEndEventListener(node, complete); // remove dimension value - this ensures the collapsible item can grow // in dimension after initial display (such as an image loading) node.style[dimension] = ''; this.setState({ collapsing:false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, _handleCollapse(){ let node = this.getCollapsibleDOMNode(); let complete = () => { this._removeEndEventListener(node, complete); this.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, // helps enable test stubs _addEndEventListener(node, complete){ TransitionEvents.addEndEventListener(node, complete); }, // helps enable test stubs _removeEndEventListener(node, complete){ TransitionEvents.removeEndEventListener(node, complete); }, dimension(){ return (typeof this.getCollapsibleDimension === 'function') ? this.getCollapsibleDimension() : 'height'; }, isExpanded(){ return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, getCollapsibleClassSet(className) { let classes = {}; if (typeof className === 'string') { className.split(' ').forEach(subClasses => { if (subClasses) { classes[subClasses] = true; } }); } classes.collapsing = this.state.collapsing; classes.collapse = !this.state.collapsing; classes.in = this.isExpanded() && !this.state.collapsing; return classes; } }; export default CollapsibleMixin;
src/components/Auth/Auth.js
wasong/hackr_matchr
import React from 'react' import { browserHistory } from 'react-router' import RaisedButton from 'material-ui/RaisedButton' import { AppBar } from 'material-ui' import css from './Auth.css' const Auth = (props) => { const { auth } = props.route const logOut = () => { auth.logout() browserHistory.push('/') } return ( <div> <AppBar title="Your Profile" /> <p>Logged In!</p> <RaisedButton label="Logout" onClick={logOut} /> <RaisedButton label="This is a button" /> </div> ) } export default Auth
app/components/ChatSiderBox/index.js
medevelopment/UMA
import React from 'react'; import { Link, browserHistory } from 'react-router'; import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; import styled from 'styled-components'; import firebase from 'firebase'; import LoadingIndicator from '../LoadingIndicator'; var ReactDOM = require('react-dom'); const ChatContentFrom = styled.div` position:relative; margin-top: 10px; float: right; clear: both; .speech-bubble { position: relative; background: #038c92; border-radius: .4em; float: left; margin-right: 22px; padding: 10px 20px; &:after { content: ''; position: absolute; right: 0; top: 50%; width: 0; height: 0; border: 0.406em solid transparent; border-left-color: #038c92; border-right: 0; margin-top: -0.406em; margin-right: -0.406em; } } .msg { color: #fff; margin-bottom: 2px; } .user-name { color: #fff; fontSize: 11px; margin-bottom: 2px; margin-top: 5px; } `; const ChatContentTo = styled.div` position:relative; padding:10px 20px; float: left; clear: both; margin: 10px 0px; width: 100%; display: flex; opacity: 0.01; transition: opacity 300ms ease-in; .speech-bubble { width: 92%; position: relative; border-radius: 34px; border: 1px #ececec solid; float: right; padding: 10px 20px; } .msg { margin-bottom: 2px; } .user-name { fontSize: 11px; margin-bottom: 2px; margin-top: 5px; } `; const SendBox = styled.div` margin-top: 10px; clear: both; display: flex; border: 1px #ccc solid; padding: 10px; justify-content: space-between; z-index: 999999; #send { background: #038c92; border-radius: 30px; padding: 3px 10px; color: #fff; } `; export default class ChatSiderBox extends React.Component { constructor(props) { super(props); this.state = { items: [], loading: true, text: '' }; this.handleChange = this.handleChange.bind(this); } scrollToBottom = () => { const node = ReactDOM.findDOMNode(this.messagesEnd); node.scrollIntoView({ behavior: "smooth" }); } componentDidMount() { this.scrollToBottom(); } componentDidUpdate() { this.scrollToBottom(); } sendMsg() { this.props.handleSubmit(this.props.msg['.userid'], this.state.text); this.setState({ text: '' }); } handleChange(event) { this.setState({text: event.target.value}); } render() { if (!this.props.loading) { return ( <div className="chat" id="chat" ref='email'> {this.props.msg.map((msg, i) => { if (msg.client) { return (<ChatContentFrom key={i} className="animated fadeIn"> <img style={{width: '30px', height: '30px', marginTop: '14px', marginRight: '1em', float: 'right', borderRadius: '50%'}} src="https://plus.google.com/u/0/_/focus/photos/public/AIbEiAIAAABECND6k6O2gLWavQEiC3ZjYXJkX3Bob3RvKigyMjgzNGM2ZWZkYjJhZDZhZjI1YTI0MzQxYzJkYTRkODEzNDBhY2UyMAHQr8BxOTmI3m0dZJGY3Vj4osnP9g?sz=48" alt=""/> <div className="speech-bubble"> <p className="msg">{msg.message}</p> <p className="user-name">{msg.user}</p> </div> </ChatContentFrom> ); } else { return (<ChatContentTo key={i} className="animated fadeIn"> <img style={{width: '30px', height: '30px', marginTop: '14px', marginRight: '1em', float: 'left', borderRadius: '50%'}} src="https://plus.google.com/u/0/_/focus/photos/public/AIbEiAIAAABECND6k6O2gLWavQEiC3ZjYXJkX3Bob3RvKigyMjgzNGM2ZWZkYjJhZDZhZjI1YTI0MzQxYzJkYTRkODEzNDBhY2UyMAHQr8BxOTmI3m0dZJGY3Vj4osnP9g?sz=48" alt=""/> <div className="speech-bubble"> <p className="msg">{msg.message}</p> <p className="user-name">{msg.user}</p> </div> </ChatContentTo> ); } })} <SendBox> <input type="text" id="chat_val" placeholder="Type here..." value={this.state.text} onChange={this.handleChange.bind(this)} /> <input type="submit" id="send" value="Submit" onClick={() => this.sendMsg()}/> </SendBox> <div style={{ float:"left", clear: "both" }} ref={(el) => { this.messagesEnd = el; }} /> </div> ); } else { return ( <LoadingIndicator/> ) } } }
server/sonar-web/src/main/js/apps/background-tasks/components/BackgroundTasksApp.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // @flow import React from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import { debounce, uniq } from 'lodash'; import { connect } from 'react-redux'; import { DEFAULT_FILTERS, DEBOUNCE_DELAY, STATUSES, CURRENTS } from './../constants'; import Header from './Header'; import Footer from './Footer'; import Stats from '../components/Stats'; import Search from '../components/Search'; import Tasks from '../components/Tasks'; import { getTypes, getActivity, getStatus, cancelAllTasks, cancelTask as cancelTaskAPI } from '../../../api/ce'; import { updateTask, mapFiltersToParameters } from '../utils'; import { Task } from '../types'; import { getComponent } from '../../../store/rootReducer'; import '../background-tasks.css'; import { fetchOrganizations } from '../../../store/rootActions'; type Props = { component: Object, location: Object, fetchOrganizations: (Array<string>) => string }; type State = { loading: boolean, tasks: Array<*>, types?: Array<*>, query: string, pendingCount: number, failingCount: number }; class BackgroundTasksApp extends React.Component { loadTasksDebounced: Function; mounted: boolean; props: Props; static contextTypes = { router: React.PropTypes.object.isRequired }; state: State = { loading: true, tasks: [], // filters query: '', // stats pendingCount: 0, failingCount: 0 }; componentWillMount() { this.loadTasksDebounced = debounce(this.loadTasks.bind(this), DEBOUNCE_DELAY); } componentDidMount() { this.mounted = true; getTypes().then(types => { this.setState({ types }); this.loadTasks(); }); } shouldComponentUpdate(nextProps: Props, nextState: State) { return shallowCompare(this, nextProps, nextState); } componentDidUpdate(prevProps: Props) { if ( prevProps.component !== this.props.component || prevProps.location !== this.props.location ) { this.loadTasksDebounced(); } } componentWillUnmount() { this.mounted = false; } loadTasks() { this.setState({ loading: true }); const status = this.props.location.query.status || DEFAULT_FILTERS.status; const taskType = this.props.location.query.taskType || DEFAULT_FILTERS.taskType; const currents = this.props.location.query.currents || DEFAULT_FILTERS.currents; const minSubmittedAt = this.props.location.query.minSubmittedAt || DEFAULT_FILTERS.minSubmittedAt; const maxExecutedAt = this.props.location.query.maxExecutedAt || DEFAULT_FILTERS.maxExecutedAt; const query = this.props.location.query.query || DEFAULT_FILTERS.query; const filters = { status, taskType, currents, minSubmittedAt, maxExecutedAt, query }; const parameters: Object = mapFiltersToParameters(filters); if (this.props.component) { parameters.componentId = this.props.component.id; } Promise.all([getActivity(parameters), getStatus(parameters.componentId)]).then(responses => { if (this.mounted) { const [activity, status] = responses; const tasks = activity.tasks; const pendingCount = status.pending; const failingCount = status.failing; const organizations = uniq(tasks.map(task => task.organization).filter(o => o)); this.props.fetchOrganizations(organizations); this.setState({ tasks, pendingCount, failingCount, loading: false }); } }); } handleFilterUpdate(nextState: Object) { const nextQuery = { ...this.props.location.query, ...nextState }; // remove defaults Object.keys(DEFAULT_FILTERS).forEach(key => { if (nextQuery[key] === DEFAULT_FILTERS[key]) { delete nextQuery[key]; } }); this.context.router.push({ pathname: this.props.location.pathname, query: nextQuery }); } handleCancelTask(task: Task) { this.setState({ loading: true }); cancelTaskAPI(task.id).then(nextTask => { if (this.mounted) { const tasks = updateTask(this.state.tasks, nextTask); this.setState({ tasks, loading: false }); } }); } handleFilterTask(task: Task) { this.handleFilterUpdate({ query: task.componentKey }); } handleShowFailing() { this.handleFilterUpdate({ ...DEFAULT_FILTERS, status: STATUSES.FAILED, currents: CURRENTS.ONLY_CURRENTS }); } handleCancelAllPending() { this.setState({ loading: true }); cancelAllTasks().then(() => { if (this.mounted) { this.loadTasks(); } }); } render() { const { component } = this.props; const { loading, types, tasks, pendingCount, failingCount } = this.state; if (!types) { return ( <div className="page"> <i className="spinner" /> </div> ); } const status = this.props.location.query.status || DEFAULT_FILTERS.status; const taskType = this.props.location.query.taskType || DEFAULT_FILTERS.taskType; const currents = this.props.location.query.currents || DEFAULT_FILTERS.currents; const minSubmittedAt = this.props.location.query.minSubmittedAt || ''; const maxExecutedAt = this.props.location.query.maxExecutedAt || ''; const query = this.props.location.query.query || ''; return ( <div className="page page-limited"> <Header /> <Stats component={component} pendingCount={pendingCount} failingCount={failingCount} onShowFailing={this.handleShowFailing.bind(this)} onCancelAllPending={this.handleCancelAllPending.bind(this)} /> <Search loading={loading} component={component} status={status} currents={currents} minSubmittedAt={minSubmittedAt} maxExecutedAt={maxExecutedAt} query={query} taskType={taskType} types={types} onFilterUpdate={this.handleFilterUpdate.bind(this)} onReload={this.loadTasksDebounced} /> <Tasks loading={loading} component={component} types={types} tasks={tasks} onCancelTask={this.handleCancelTask.bind(this)} onFilterTask={this.handleFilterTask.bind(this)} /> <Footer tasks={tasks} /> </div> ); } } const mapStateToProps = (state, ownProps) => ({ component: ownProps.location.query.id ? getComponent(state, ownProps.location.query.id) : undefined }); const mapDispatchToProps = { fetchOrganizations }; export default connect(mapStateToProps, mapDispatchToProps)(BackgroundTasksApp);
src/svg-icons/file/cloud-done.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudDone = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM10 17l-3.5-3.5 1.41-1.41L10 14.17 15.18 9l1.41 1.41L10 17z"/> </SvgIcon> ); FileCloudDone = pure(FileCloudDone); FileCloudDone.displayName = 'FileCloudDone'; FileCloudDone.muiName = 'SvgIcon'; export default FileCloudDone;
src/components/form/preview_item.js
n7best/react-weui
//1.0.0 components import React from 'react'; import PropTypes from 'prop-types'; import classNames from '../../utils/classnames'; /** * Preview Item for all purpose usage * */ const PreviewItem = (props) => { const { className, label, value, ...others } = props; const cls = classNames({ 'weui-form-preview__item': true, [className]: className }); return ( <div className={cls} {...others}> <label className="weui-form-preview__label">{label}</label> <em className="weui-form-preview__value">{value}</em> </div> ); }; PreviewItem.propTypes = { /** * The label of item * */ label: PropTypes.string, /** * Value of the label * */ value: PropTypes.string, }; PreviewItem.defaultProps = { label: false, value: false, }; export default PreviewItem;
ui/src/views/Main.js
Ion-Petcu/StockTrainer
import React from 'react' import Header from '../components/Header' import NewsContainer from '../components/NewsContainer' import Portfolio from '../components/Portfolio' import StockChart from '../components/StockChart' import ApiRequest from '../utils/ApiRequest' import ApiStream from '../utils/ApiStream' import cst from '../utils/constants' export class Main extends React.Component { constructor(props) { super(props); this.state = { error: null, portfolio: {cash: 0, positions: []}, news: [], priceCurves: {}, currentPrices: {} }; cst.STOCKS.map((e) => { this.state.priceCurves[e] = []; this.state.currentPrices[e] = 0; }) } componentDidMount() { this.fetchPortfolio(); this.streamPrices(); this.streamNews(); } fetchPortfolio() { ApiRequest.get('portfolio', (data) => this.updatePortfolio(data)) } resetPortfolio() { ApiRequest.post('portfolio', {action: 'reset'}, (data) => this.updatePortfolio(data)) } updatePosition(sym, units, price) { ApiRequest.post('portfolio', {sym: sym, units: units, price: price}, (data) => this.updatePortfolio(data)) } updatePortfolio(data) { if (typeof data === 'string') { this.setState({error: data}); setTimeout(() => this.setState({error: null}), 1000); } else { this.setState({portfolio: data}) } } streamPrices() { ApiStream.fetch('prices', (data) => { let sym = data.sym; let price = data.price; // let ts = data.ts; let currentPrices = this.state.currentPrices; currentPrices[sym] = price; let priceCurves = this.state.priceCurves; let priceCurve = priceCurves[sym]; priceCurve.push(['', price]); if (priceCurve.length > 30) { priceCurve = priceCurve.slice(1); } priceCurves[sym] = priceCurve; this.setState({ currentPrices: currentPrices, priceCurves: priceCurves }) }); } streamNews() { ApiStream.fetch('news', (data) => { let body = data.body; let ts = data.ts; let news = this.state.news; news.push({body: body, ts: ts * 1000}); this.setState({news: news}); }) } render() { let [s1, s2, s3, s4] = cst.STOCKS; return ( <div style={{height: '100%'}}> <Header /> <div className="w3-row w3-padding-24"> <div className="w3-col m4 w3-center"> <StockChart stock={s1} data={this.state.priceCurves[s1]} price={this.state.currentPrices[s1]} /> <StockChart stock={s2} data={this.state.priceCurves[s2]} price={this.state.currentPrices[s2]} /> </div> <div className="w3-col m4 w3-center"> <Portfolio data={this.state.portfolio} prices={this.state.currentPrices} resetPortfolio={this.resetPortfolio.bind(this)} updatePosition={this.updatePosition.bind(this)} /> <div className="w3-text-red w3-margin-top"> {this.state.error} </div> <hr /> <NewsContainer data={this.state.news} /> </div> <div className="w3-col m4 w3-center"> <StockChart stock={s3} data={this.state.priceCurves[s3]} price={this.state.currentPrices[s3]} /> <StockChart stock={s4} data={this.state.priceCurves[s4]} price={this.state.currentPrices[s4]} /> </div> </div> </div> ) } } export default Main;
src/js/components/TextInput/stories/WithTags.js
grommet/grommet
import React from 'react'; import { FormClose } from 'grommet-icons'; import { Box, Button, Keyboard, Text, TextInput } from 'grommet'; const allSuggestions = ['sony', 'sonar', 'foo', 'bar']; const Tag = ({ children, onRemove, ...rest }) => { const tag = ( <Box direction="row" align="center" background="brand" pad={{ horizontal: 'xsmall', vertical: 'xxsmall' }} margin={{ vertical: 'xxsmall' }} round="medium" {...rest} > <Text size="xsmall" margin={{ right: 'xxsmall' }}> {children} </Text> {onRemove && <FormClose size="small" color="white" />} </Box> ); if (onRemove) { return <Button onClick={onRemove}>{tag}</Button>; } return tag; }; const TagInput = ({ value = [], onAdd, onChange, onRemove, ...rest }) => { const [currentTag, setCurrentTag] = React.useState(''); const boxRef = React.useRef(); const updateCurrentTag = (event) => { setCurrentTag(event.target.value); if (onChange) { onChange(event); } }; const onAddTag = (tag) => { if (onAdd) { onAdd(tag); } }; const onEnter = () => { if (currentTag.length) { onAddTag(currentTag); setCurrentTag(''); } }; const renderValue = () => value.map((v, index) => ( <Tag margin="xxsmall" key={`${v}${index + 0}`} onRemove={() => onRemove(v)} > {v} </Tag> )); return ( <Keyboard onEnter={onEnter}> <Box direction="row" align="center" pad={{ horizontal: 'xsmall' }} border="all" ref={boxRef} wrap > {value.length > 0 && renderValue()} <Box flex style={{ minWidth: '120px' }}> <TextInput type="search" plain dropTarget={boxRef.current} {...rest} onChange={updateCurrentTag} value={currentTag} onSuggestionSelect={(event) => onAddTag(event.suggestion)} /> </Box> </Box> </Keyboard> ); }; export const WithTags = () => { const [selectedTags, setSelectedTags] = React.useState(['foo', 'sony']); const [suggestions, setSuggestions] = React.useState(allSuggestions); const onRemoveTag = (tag) => { const removeIndex = selectedTags.indexOf(tag); const newTags = [...selectedTags]; if (removeIndex >= 0) { newTags.splice(removeIndex, 1); } setSelectedTags(newTags); }; const onAddTag = (tag) => setSelectedTags([...selectedTags, tag]); const onFilterSuggestion = (value) => setSuggestions( allSuggestions.filter( (suggestion) => suggestion.toLowerCase().indexOf(value.toLowerCase()) >= 0, ), ); return ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <Box pad="small"> <TagInput placeholder="Search for aliases..." suggestions={suggestions} value={selectedTags} onRemove={onRemoveTag} onAdd={onAddTag} onChange={({ target: { value } }) => onFilterSuggestion(value)} /> </Box> // </Grommet> ); }; WithTags.storyName = 'With tags'; export default { title: 'Input/TextInput/With tags', };
src/client/pages/repositories/Repositories.js
developersdo/opensource
import React from 'react' import { Route, Redirect, Switch } from 'react-router-dom' import New from '~/pages/new-repositories/NewRepositories' import Popular from '~/pages/popular-repositories/PopularRepositories' import ByLanguage from '~/pages/repositories-by-language/RepositoriesByLanguage' import SubNavLink from '~/components/sub-nav-link/SubNavLink' const Repositories = (props) => ( <div> <div className="row center-align"> <SubNavLink to="/repositories/popular">Popular</SubNavLink> <SubNavLink to="/repositories/new">New</SubNavLink> </div> <Route exact path="/repositories" render={() => <Redirect to="/repositories/popular" />} /> <Switch> <Route path="/repositories/popular" component={Popular} /> <Route path="/repositories/new" component={New} /> <Route path="/repositories/:language" component={ByLanguage} /> </Switch> </div> ) export default Repositories
app/components/EditAdmins/index.js
dijahmac/JobWeasel-FrontEnd
/** * * EditAdmins * */ import React from 'react'; import './style.css'; import './styleM.css'; export default class EditAdmins extends React.PureComponent { constructor () { super (), this.state = { users: [], notification: "", } } componentWillMount() { this.getUsers(); } getUsers = () => { let url = "http://localhost:8000/api/getUsers"; let _this = this; fetch(url, {'method': 'GET'}).then( function(response) { return response.json(); }).then( function(json) { if (json.users) { _this.setState({ users: json.users.data }); } } ); } makeAdmin = (id) => { let data = new FormData; let _this = this; data.append('user_id', id); fetch('http://localhost:8000/api/makeAdmin', { method: 'POST', body:data, headers:{"Authorization":"Bearer "+ sessionStorage.getItem('token')} }) .then(function(response) { return response.json(); }) .then(function(json) { if(json.error) { _this.setState({ notification: json.error }) } else { _this.setState({ notification: json.success }) } setTimeout(function(){ _this.setState({ notification: "" }) }, 2500) }.bind(this)); } render() { if(this.props.open === true) { return ( <div> <div className="editAdminsContainer"> <div className="editAdminsUnderlay" onClick={this.props.onClose}> </div> <div className="editAdminsInput"> <h3>Add Administrators</h3> <div className="usersList"> <div className="usersDisplay"> {this.state.users.map((t,i) => (<div key={i} onClick={()=>this.makeAdmin(t.id)}> {t.name} </div>))} </div> </div> <p className="submitNote">{this.state.notification}</p> </div> </div> </div> ); } else { return( <div></div> ) } } } EditAdmins.contextTypes = { router: React.PropTypes.object };
src/js/containers/Search.js
slavapavlutin/pavlutin-node
import React from 'react'; import Icon from 'react-fontawesome'; import { connect } from 'react-redux'; import { changeSearchTerm } from '../store/searchTerm/actions'; class Search extends React.Component { constructor() { super(); this.state = { inFocus: false }; this.handleFocus = this.handleFocus.bind(this); this.handleChange = this.handleChange.bind(this); } handleFocus() { this.setState({ inFocus: !this.state.inFocus }); } handleChange(event) { this.props.onChange(event.target.value); } render() { const clsName = this.state.inFocus ? 'search search_focus' : 'search'; return ( <div className={clsName}> <label htmlFor="search" className="search__icon"> <Icon name="search" /> </label> <input id="search" autoComplete="off" type="search" className="search__input" placeholder="Search" value={this.props.searchTerm} onFocus={this.handleFocus} onBlur={this.handleFocus} onChange={this.handleChange} /> </div> ); } } function mapStateToProps({ searchTerm }) { return { searchTerm }; } function mapDispatchToProps(dispatch) { return { onChange(term) { dispatch(changeSearchTerm(term)); }, }; } export default connect(mapStateToProps, mapDispatchToProps)(Search);
src/routes.js
twreporter/twreporter-react
import Article from './containers/Article' import dataLoaders from './data-loaders/index' import FallbackPage from './containers/ServiceWorkerFallbackPage' import get from 'lodash/get' import Loadable from 'react-loadable' import PropTypes from 'prop-types' import React from 'react' import routesConst from './constants/routes' import statusCodeConst from './constants/status-code' import SystemError from './components/SystemError' const _ = { get, } class LoadingComponent extends React.Component { static propTypes = { error: PropTypes.object, } render() { const { error } = this.props if (error) { // error should be caught by scr/components/ErrorBoundary component throw error } return null } } const loadablePages = { home: Loadable({ loader: () => import( /* webpackChunkName: "index-page" */ './containers/Home' ), loading: LoadingComponent, }), topic: Loadable({ loader: () => import( /* webpackChunkName: "topic-page" */ './containers/TopicLandingPage' ), loading: LoadingComponent, }), topics: Loadable({ loader: () => import( /* webpackChunkName: "topic-list-page" */ './containers/Topics' ), loading: LoadingComponent, }), category: Loadable({ loader: () => import( /* webpackChunkName: "category-list-page" */ './containers/Category' ), loading: LoadingComponent, }), tag: Loadable({ loader: () => import( /* webpackChunkName: "tag-list-page" */ './containers/Tag' ), loading: LoadingComponent, }), author: Loadable({ loader: () => import( /* webpackChunkName: "author-page" */ './containers/Author' ), loading: LoadingComponent, }), authors: Loadable({ loader: () => import( /* webpackChunkName: "author-list-page" */ './containers/AuthorsList' ), loading: LoadingComponent, }), photography: Loadable({ loader: () => import( /* webpackChunkName: "photography-page" */ './containers/Photography' ), loading: LoadingComponent, }), search: Loadable({ loader: () => import( /* webpackChunkName: "search-page" */ './containers/Search' ), loading: LoadingComponent, }), aboutUs: Loadable({ loader: () => import( /* webpackChunkName: "about-us-page" */ './components/about-us' ), loading: LoadingComponent, }), bookmarkList: Loadable({ loader: () => import( /* webpackChunkName: "bookmark-list" */ '@twreporter/react-components/lib/bookmark-list' ), loading: LoadingComponent, }), } function ErrorPage({ match, staticContext }) { let statusCode const errorType = _.get(match, 'params.errorType') switch (errorType) { case '404': { statusCode = statusCodeConst.notFound break } case '500': default: { statusCode = statusCodeConst.internalServerError } } // there is no `staticContext` on the client, // so we need to guard against that here if (staticContext) { staticContext.statusCode = statusCode } return ( <SystemError error={{ statusCode, }} /> ) } ErrorPage.propTypes = { match: PropTypes.object, staticContext: PropTypes.object, } function NotFoundErrorPage({ staticContext }) { // there is no `staticContext` on the client, // so we need to guard against that here if (staticContext) { staticContext.statusCode = 404 } return ( <SystemError error={{ statusCode: 404, }} /> ) } NotFoundErrorPage.propTypes = { staticContext: PropTypes.object, } /** * getRoutes function * uses `react-loadable` to do the code splitting, * and adopts react-router * to render the corresponding React components * * @returns {object} Switch component of react-router v4 */ export default function getRoutes() { return [ { component: loadablePages.home, exact: true, loadData: dataLoaders.loadIndexPageData, path: routesConst.homePage.path, }, { component: FallbackPage, path: routesConst.serviceWorkerFallBackPage.path, }, { component: loadablePages.topic, loadData: dataLoaders.loadTopicPageData, path: routesConst.topicPage.path, }, { component: loadablePages.topics, loadData: dataLoaders.loadTopicListPageData, path: routesConst.topicListPage.path, }, { component: loadablePages.category, loadData: dataLoaders.loadCategoryListPageData, path: routesConst.categoryListPage.path, }, { component: loadablePages.tag, loadData: dataLoaders.loadTagListPageData, path: routesConst.tagListPage.path, }, { component: loadablePages.photography, loadData: dataLoaders.loadPhotographyPageData, path: routesConst.photographyPage.path, }, { component: loadablePages.search, path: routesConst.searchPage.path, }, { component: Article, loadData: props => Promise.all([ dataLoaders.loadArticlePageData(props), dataLoaders.loadBookmarkWidgetData(props), ]), path: routesConst.articlePage.path, }, { component: loadablePages.author, loadData: dataLoaders.loadAuthorPageData, path: routesConst.authorPage.path, }, { component: loadablePages.authors, loadData: dataLoaders.loadAuthorListPageData, path: routesConst.authorListPage.path, }, { component: loadablePages.aboutUs, path: routesConst.aboutUsPage.path, }, { component: loadablePages.bookmarkList, loadData: dataLoaders.loadBookmarkListData, path: routesConst.bookmarkListPage.path, authorizationRequired: true, }, // error page { path: routesConst.errorPage.path, component: ErrorPage, }, // no routes match { component: NotFoundErrorPage, }, ] }
app/components/PrimaryBlock/PrimaryBlock.js
klpdotorg/tada-frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import isEmpty from 'lodash.isempty'; import { Spinner } from '../../containers/common'; import { EditBlock } from '../../containers/PrimaryBlock'; import { CreateCluster } from '../../containers/PrimaryCluster'; const PrimaryBlockView = ({ paths, isLoading, district, block, params }) => { if (isLoading || isEmpty(block)) { return ( <div> <i className="fa fa-cog fa-spin fa-lg fa-fw" /> <span className="text-muted">Loading...</span> </div> ); } return ( <div> <Spinner /> <ol className="breadcrumb"> <li> <Link to={paths[0]}>{district.name}</Link> </li> <li className="active">{block.name}</li> </ol> <EditBlock blockNodeId={params.blockNodeId} districtNodeId={params.districtNodeId} districtId={district.id} /> <CreateCluster parent={block.id} parentNodeId={params.blockNodeId} /> </div> ); }; PrimaryBlockView.propTypes = { isLoading: PropTypes.bool, paths: PropTypes.array, district: PropTypes.object, block: PropTypes.object, params: PropTypes.object, }; export { PrimaryBlockView };
src/svg-icons/social/sentiment-very-satisfied.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentVerySatisfied = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied); SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied'; export default SocialSentimentVerySatisfied;
src/server.js
yogakurniawan/cerebral-app
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import compression from 'compression'; import httpProxy from 'http-proxy'; import cookieParser from 'cookie-parser'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import https from 'https'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const loopbackApiUrl = config.apiHost + '/api'; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: loopbackApiUrl, ws: true, changeOrigin: true }); app.use(compression()); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, { target: loopbackApiUrl }); }); setInterval(() => { https.get('https://cerebral-app.herokuapp.com'); // https.get('https://cerebral-api.herokuapp.com'); console.log('PING => https://cerebral-app.herokuapp.com'); // console.log('PING => https://cerebral-api.herokuapp.com'); }, 300000); // every 5 minutes (300000) app.use(cookieParser()); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, { 'content-type': 'application/json' }); } json = { error: 'proxy_error', reason: error.message }; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, client); const history = syncHistoryWithStore(memoryHistory, store); const token = req.cookies && req.cookies.token; function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets() } store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store, token), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { const notFound = renderProps.routes.filter((route) => (route.path === '*' && route.status === 404)); const pathLogin = renderProps.routes.filter((route) => (route.path === 'login')); if (pathLogin.length > 0) { console.log(renderProps.routes[0].path); res.clearCookie('token'); } loadOnServer({...renderProps, store, helpers: { client }}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); if (notFound.length > 0) { res.status(404); } else { res.status(200); } global.navigator = { userAgent: req.headers['user-agent'] }; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets() } component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server', config.app.title); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/components/RequestExecutor/index.js
evolving-cowboys/queensman
import React from 'react'; import './index.css'; const RequestExecutor = ({ enabled, loading, request, response, changeRequest, rpcCall, }) => ( <div className='RequestExecutor'> <div className='RequestExecutor-request'> <textarea className={` RequestExecutor-requestField ${request && request.data !== null ? '' : 'RequestExecutor-requestField__error' } `} value={request && request.raw} onChange={(e) => changeRequest(e.target.value)} /> <button className='RequestExecutor-button' type='button' disabled={!enabled || loading || !(request && request.data !== null)} onClick={rpcCall} > { loading ? 'Wait ...' : 'Call !!!' } </button> </div> <div className='RequestExecutor-response'> <pre className='RequestExecutor-responseViewer'> { response && response.repr } </pre> </div> </div> ); export default RequestExecutor;
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/containers/AuthContainer.js
advantys/workflowgen-templates
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { AuthComponent as Auth } from '../components'; import { ActionCreators as UserActionCreators } from '../redux/user'; class AuthContainer extends Component { constructor (props) { super(props); this.handleOnLoginButtonPress = this.handleOnLoginButtonPress.bind(this); } handleOnLoginButtonPress () { this.props.login(); } render () { return <Auth onLoginButtonPress={this.handleOnLoginButtonPress} />; } } AuthContainer.navigationOptions = { header: null }; export default connect( null, dispatch => bindActionCreators(UserActionCreators, dispatch) )(AuthContainer);
src/index.js
carlmanaster/stripes
import React from 'react' import ReactDOM from 'react-dom' import { browserHistory } from 'react-router' import Routes from './routes' import './index.css' ReactDOM.render( <Routes history={browserHistory} />, document.getElementById('root') )
lib/carbon-fields/vendor/htmlburger/carbon-fields/assets/js/fields/components/complex/tabs.js
boquiabierto/wherever-content
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { branch, renderNothing, withHandlers } from 'recompose'; /** * The internal dependencies. */ import ComplexTab from 'fields/components/complex/tab'; /** * Render the navigation of tabs when the layout of complex field is tabbed. * * @param {Object} props * @param {Object[]} props.groups * @param {Function} props.isTabActive * @param {Function} props.handleClick * @param {React.Element} props.children * @return {React.Element} */ export const ComplexTabs = ({ groups, isTabActive, onClick, children }) => { return <div className="group-tabs-nav-holder"> <ul className="group-tabs-nav"> { groups.map((group, index) => ( <ComplexTab key={index} index={index} group={group} active={isTabActive(group.id)} onClick={onClick} /> )) } </ul> {children} </div>; }; /** * Validate the props. * * @type {Object} */ ComplexTabs.propTypes = { groups: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, fields: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, name: PropTypes.string, })), })), show: PropTypes.bool, current: PropTypes.string, onClick: PropTypes.func, children: PropTypes.element, }; /** * The enhancer. * * @type {Function} */ export const enhance = branch( /** * Test to see if the tabs should be rendered. */ ({ show }) => show, /** * Pass some handlers to the component. */ withHandlers({ isTabActive: ({ current }) => groupId => groupId === current, }), /** * Render the empty component. */ renderNothing ); export default enhance(ComplexTabs);
src/icons/AndroidRadioButtonOn.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidRadioButtonOn extends React.Component { render() { if(this.props.bare) { return <g> <g id="Icon_21_"> <g> <path d="M256,152c-57.2,0-104,46.8-104,104s46.8,104,104,104s104-46.8,104-104S313.2,152,256,152z M256,48 C141.601,48,48,141.601,48,256s93.601,208,208,208s208-93.601,208-208S370.399,48,256,48z M256,422.4 c-91.518,0-166.4-74.883-166.4-166.4S164.482,89.6,256,89.6S422.4,164.482,422.4,256S347.518,422.4,256,422.4z"></path> </g> </g> </g>; } return <IconBase> <g id="Icon_21_"> <g> <path d="M256,152c-57.2,0-104,46.8-104,104s46.8,104,104,104s104-46.8,104-104S313.2,152,256,152z M256,48 C141.601,48,48,141.601,48,256s93.601,208,208,208s208-93.601,208-208S370.399,48,256,48z M256,422.4 c-91.518,0-166.4-74.883-166.4-166.4S164.482,89.6,256,89.6S422.4,164.482,422.4,256S347.518,422.4,256,422.4z"></path> </g> </g> </IconBase>; } };AndroidRadioButtonOn.defaultProps = {bare: false}
src/containers/DevTools.js
Outc4sted/AlgorithmAtelier
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; export default createDevTools(<LogMonitor />);
app/pages/Items/Item/Item.js
altiore/webpack_config_example
import React from 'react' import PropTypes from 'prop-types' const ItemPage = ({ styles, match }) => ( <div className={styles.wrapper}> This is a page: {match.path} </div> ) ItemPage.propTypes = { styles: PropTypes.object, match: PropTypes.shape({ path: PropTypes.string.isRequired, }).isRequired, } export default ItemPage
src/svg-icons/folder.js
und3fined/material-ui
/* eslint-disable */ import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../SvgIcon'; let Folder = (props) => ( <SvgIcon {...props}> <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/> </SvgIcon> ); Folder = pure(Folder); Folder.muiName = 'SvgIcon'; export default Folder;
assets/jqwidgets/jqwidgets-react/react_jqxmenu.js
juannelisalde/holter
/* jQWidgets v4.5.4 (2017-June) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export default class JqxMenu extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['animationShowDuration','animationHideDuration','animationHideDelay','animationShowDelay','autoCloseInterval','autoSizeMainItems','autoCloseOnClick','autoOpenPopup','autoOpen','clickToOpen','disabled','enableHover','easing','height','keyboardNavigation','minimizeWidth','mode','popupZIndex','rtl','showTopLevelArrows','source','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxMenu(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxMenu('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxMenu(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; animationShowDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('animationShowDuration', arg) } else { return JQXLite(this.componentSelector).jqxMenu('animationShowDuration'); } }; animationHideDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('animationHideDuration', arg) } else { return JQXLite(this.componentSelector).jqxMenu('animationHideDuration'); } }; animationHideDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('animationHideDelay', arg) } else { return JQXLite(this.componentSelector).jqxMenu('animationHideDelay'); } }; animationShowDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('animationShowDelay', arg) } else { return JQXLite(this.componentSelector).jqxMenu('animationShowDelay'); } }; autoCloseInterval(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('autoCloseInterval', arg) } else { return JQXLite(this.componentSelector).jqxMenu('autoCloseInterval'); } }; autoSizeMainItems(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('autoSizeMainItems', arg) } else { return JQXLite(this.componentSelector).jqxMenu('autoSizeMainItems'); } }; autoCloseOnClick(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('autoCloseOnClick', arg) } else { return JQXLite(this.componentSelector).jqxMenu('autoCloseOnClick'); } }; autoOpenPopup(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('autoOpenPopup', arg) } else { return JQXLite(this.componentSelector).jqxMenu('autoOpenPopup'); } }; autoOpen(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('autoOpen', arg) } else { return JQXLite(this.componentSelector).jqxMenu('autoOpen'); } }; clickToOpen(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('clickToOpen', arg) } else { return JQXLite(this.componentSelector).jqxMenu('clickToOpen'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('disabled', arg) } else { return JQXLite(this.componentSelector).jqxMenu('disabled'); } }; enableHover(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('enableHover', arg) } else { return JQXLite(this.componentSelector).jqxMenu('enableHover'); } }; easing(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('easing', arg) } else { return JQXLite(this.componentSelector).jqxMenu('easing'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('height', arg) } else { return JQXLite(this.componentSelector).jqxMenu('height'); } }; keyboardNavigation(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('keyboardNavigation', arg) } else { return JQXLite(this.componentSelector).jqxMenu('keyboardNavigation'); } }; minimizeWidth(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('minimizeWidth', arg) } else { return JQXLite(this.componentSelector).jqxMenu('minimizeWidth'); } }; mode(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('mode', arg) } else { return JQXLite(this.componentSelector).jqxMenu('mode'); } }; popupZIndex(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('popupZIndex', arg) } else { return JQXLite(this.componentSelector).jqxMenu('popupZIndex'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('rtl', arg) } else { return JQXLite(this.componentSelector).jqxMenu('rtl'); } }; showTopLevelArrows(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('showTopLevelArrows', arg) } else { return JQXLite(this.componentSelector).jqxMenu('showTopLevelArrows'); } }; source(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('source', arg) } else { return JQXLite(this.componentSelector).jqxMenu('source'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('theme', arg) } else { return JQXLite(this.componentSelector).jqxMenu('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMenu('width', arg) } else { return JQXLite(this.componentSelector).jqxMenu('width'); } }; closeItem(itemID) { JQXLite(this.componentSelector).jqxMenu('closeItem', itemID); }; close() { JQXLite(this.componentSelector).jqxMenu('close'); }; disable(itemID, value) { JQXLite(this.componentSelector).jqxMenu('disable', itemID, value); }; destroy() { JQXLite(this.componentSelector).jqxMenu('destroy'); }; focus() { JQXLite(this.componentSelector).jqxMenu('focus'); }; minimize() { JQXLite(this.componentSelector).jqxMenu('minimize'); }; open(left, top) { JQXLite(this.componentSelector).jqxMenu('open', left, top); }; openItem(itemID) { JQXLite(this.componentSelector).jqxMenu('openItem', itemID); }; restore() { JQXLite(this.componentSelector).jqxMenu('restore'); }; setItemOpenDirection(item, horizontaldirection, verticaldirection) { JQXLite(this.componentSelector).jqxMenu('setItemOpenDirection', item, horizontaldirection, verticaldirection); }; render() { let id = 'jqxMenu' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
examples/slorber-scalable-frontend/src/randomGifPairPair/RandomGifPairPair.js
ioof-holdings/redux-subspace
import React from 'react' import { SubspaceProvider } from 'react-redux-subspace' import { RandomGifPair } from '../randomGifPair' const RandomGifPairPair = () => ( <div> <SubspaceProvider namespace='randomGifPair1'> <RandomGifPair /> </SubspaceProvider> <SubspaceProvider namespace='randomGifPair2'> <RandomGifPair /> </SubspaceProvider> </div> ) export default RandomGifPairPair
src/parser/druid/feral/modules/azeritetraits/WildFleshrending.js
FaideWW/WoWAnalyzer
import React from 'react'; import { formatNumber } from 'common/format'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { calculateAzeriteEffects } from 'common/stats'; import HIT_TYPES from 'game/HIT_TYPES'; import RACES from 'game/RACES'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import StatTracker from 'parser/shared/modules/StatTracker'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import calculateBonusAzeriteDamage from 'parser/core/calculateBonusAzeriteDamage'; import { FERAL_DRUID_DAMAGE_AURA, INCARNATION_SHRED_DAMAGE, SAVAGE_ROAR_DAMAGE_BONUS, TIGERS_FURY_DAMAGE_BONUS, BLOODTALONS_DAMAGE_BONUS, MOMENT_OF_CLARITY_DAMAGE_BONUS, SHRED_SWIPE_BONUS_ON_BLEEDING } from '../../constants.js'; import Abilities from '../Abilities.js'; const debug = false; // Swipe has a bear and a cat version, both are affected by the trait. It can be replaced by the talent Brutal Slash which benefits in the same way. const SWIPE_SPELLS = [ SPELLS.SWIPE_BEAR.id, SPELLS.SWIPE_CAT.id, SPELLS.BRUTAL_SLASH_TALENT.id, ]; const HIT_TYPES_TO_IGNORE = [ HIT_TYPES.MISS, HIT_TYPES.DODGE, HIT_TYPES.PARRY, ]; /** * Wild Fleshrending * "Shred deals X additional damage, and Swipe (or Brutal Slash) deals Y additional damage, to enemies suffering from your Thrash." * The wording is slightly ambiguous but both bonuses require the player's Thrash debuff to be active. */ class WildFleshrending extends Analyzer { static dependencies = { abilities: Abilities, enemies: Enemies, statTracker: StatTracker, }; shredBonus = 0; shredsWithThrash = 0; shredsTotal = 0; shredDamage = 0; swipeBonus = 0; swipesWithThrash = 0; swipesTotal = 0; swipeDamage = 0; // Only cast events give us accurate attack power values, so have to temporarily store it. As we're dealing with instant damage abilites there's no problem with that. attackPower = 0; constructor(...args) { super(...args); if(!this.selectedCombatant.hasTrait(SPELLS.WILD_FLESHRENDING.id)) { this.active = false; return; } this.shredBonus = this.selectedCombatant.traitsBySpellId[SPELLS.WILD_FLESHRENDING.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.WILD_FLESHRENDING.id, rank)[0], 0); debug && console.log(`shredBonus from items: ${this.shredBonus}`); this.swipeBonus = this.selectedCombatant.traitsBySpellId[SPELLS.WILD_FLESHRENDING.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.WILD_FLESHRENDING.id, rank)[1], 0); debug && console.log(`swipeBonus from items: ${this.swipeBonus}`); } on_byPlayer_cast(event) { if (event.ability.guid !== SPELLS.SHRED.id && !SWIPE_SPELLS.includes(event.ability.guid)) { return; } this.attackPower = event.attackPower; } on_byPlayer_damage(event) { if (HIT_TYPES_TO_IGNORE.includes(event.hitType)) { // Attacks that don't hit cannot benefit from the trait's bonus return; } const isShred = event.ability.guid === SPELLS.SHRED.id; if (!isShred && !SWIPE_SPELLS.includes(event.ability.guid)) { // Only interested in shred and swipe return; } if (isShred) { this.shredsTotal += 1; } else { this.swipesTotal += 1; } const target = this.enemies.getEntities()[event.targetID]; if (!target || ( !target.hasBuff(SPELLS.THRASH_FERAL.id, event.timestamp, 0, 0, this.owner.playerId) && !target.hasBuff(SPELLS.THRASH_BEAR_DOT.id, event.timestamp, 0, 0, this.owner.playerId))) { // Only applies bonus damage if hitting a target with player's Thrash (either cat or bear version) active on it debug && console.log(`${this.owner.formatTimestamp(event.timestamp, 3)} hit without Thrash`); return; } if (isShred) { this.shredsWithThrash += 1; } else { this.swipesWithThrash += 1; } /** * Through in-game testing I've found that the Wild Fleshrending trait's damage is applied like this: * damageDone = (attackPower * ABILITY_COEFFICIENT + traitBonus) * modifier * * The important thing is that there's just one modifier term applied to both the ability's base damage and to the trait's bonus damage. * The modifier includes things like shred's 20% buff against bleeding targets, Tiger's Fury, Savage Roar, the Feral Druid aura that's used to adjust DPS balance, and even the damage increase from a critical strike. It also includes things that are difficult to see from our logs such as Mystic Touch or encounter-specific effects like MOTHER taking extra damage in the 3rd chamber. The effect of enemy armor is also included within the modifier. * We know the damageDone, attackPower, ABILITY_COEFFICIENT, and traitBonus which means we can calculate the modifier's value for this attack. With the modifier known we can multiply that by traitBonus to find how much damage it actually contributed to this attack. * * Assumptions: There are no effects in play that adjust damage by a set number rather than by multiplying, apart from those that appear in the log as absorbed damage. Everything that modifies the ability's base damage also modifies the trait's bonus damage in the same way. I've yet to find anything that violates these assumptions. */ const traitBonus = isShred ? this.shredBonus : this.swipeBonus; const coefficient = this.abilities.getAbility(event.ability.guid).primaryCoefficient; const [ traitDamageContribution ] = calculateBonusAzeriteDamage(event, [traitBonus], this.attackPower, coefficient); if (isShred) { this.shredDamage += traitDamageContribution; debug && console.log(`${this.owner.formatTimestamp(event.timestamp, 3)} Shred increased by ${traitDamageContribution.toFixed(0)}.`); } else { this.swipeDamage += traitDamageContribution; debug && console.log(`${this.owner.formatTimestamp(event.timestamp, 3)} Swipe (or BrS) increased by ${traitDamageContribution.toFixed(0)}.`); } // As an accuracy check, during debug also calculate the trait's damage bonus using a method based on that used for Frost Mage's Whiteout trait. if (debug) { const critMultiplier = this.selectedCombatant.race === RACES.Tauren ? 2.04 : 2.00; const externalModifier = (event.amount / event.unmitigatedAmount) / (event.hitType === HIT_TYPES.CRIT ? critMultiplier : 1.0); console.log(`externalModifier: ${externalModifier.toFixed(3)}`); let estimatedDamage = traitBonus * (1 + this.statTracker.currentVersatilityPercentage) * FERAL_DRUID_DAMAGE_AURA; if (event.ability.guid === SPELLS.SHRED.id || event.ability.guid === SPELLS.SWIPE_CAT.id) { estimatedDamage *= SHRED_SWIPE_BONUS_ON_BLEEDING; } if (isShred && this.selectedCombatant.hasBuff(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id)) { estimatedDamage *= INCARNATION_SHRED_DAMAGE; } if (this.selectedCombatant.hasTalent(SPELLS.MOMENT_OF_CLARITY_TALENT.id) && this.selectedCombatant.hasBuff(SPELLS.CLEARCASTING_FERAL.id, event.timestamp, 500)) { estimatedDamage *= 1 + MOMENT_OF_CLARITY_DAMAGE_BONUS; } if (this.selectedCombatant.hasBuff(SPELLS.TIGERS_FURY.id)) { estimatedDamage *= 1 + TIGERS_FURY_DAMAGE_BONUS; } if (this.selectedCombatant.hasBuff(SPELLS.BLOODTALONS_BUFF.id, null, 100)) { estimatedDamage *= 1 + BLOODTALONS_DAMAGE_BONUS; } if (this.selectedCombatant.hasBuff(SPELLS.SAVAGE_ROAR_TALENT.id)) { estimatedDamage *= 1 + SAVAGE_ROAR_DAMAGE_BONUS; } if (event.hitType === HIT_TYPES.CRIT) { estimatedDamage *= critMultiplier; } estimatedDamage *= externalModifier; console.log(`estimatedDamage: ${estimatedDamage.toFixed(0)}`); const variation = estimatedDamage / traitDamageContribution; console.log(`Matching of contribution calculations: ${(variation * 100).toFixed(1)}%`); } } statistic() { const swipeName = this.selectedCombatant.hasTalent(SPELLS.BRUTAL_SLASH_TALENT.id) ? 'Brutal Slash' : 'Swipe'; return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.WILD_FLESHRENDING.id} value={( <ItemDamageDone amount={this.shredDamage + this.swipeDamage} /> )} tooltip={`The Wild Fleshrending trait increased your Shred damage by a total of <b>${formatNumber(this.shredDamage)}</b> and ${swipeName} by <b>${formatNumber(this.swipeDamage)}</b>. <li><b>${(100 * this.shredsWithThrash / this.shredsTotal).toFixed(0)}%</b> of your Shreds benefited from Wild Fleshrending. <li><b>${(100 * this.swipesWithThrash / this.swipesTotal).toFixed(0)}%</b> of your ${swipeName}s benefited from Wild Fleshrending.`} /> ); } get shredBenefitThresholds() { return { actual: this.shredsTotal === 0 ? 1 : this.shredsWithThrash / this.shredsTotal, isLessThan: { minor: 0.95, average: 0.90, major: 0.80, }, style: 'percentage', }; } get swipeBenefitThresholds() { return { actual: this.swipesTotal === 0 ? 1 : this.swipesWithThrash / this.swipesTotal, isLessThan: { minor: 0.95, average: 0.90, major: 0.80, }, style: 'percentage', }; } suggestions(when) { when(this.shredBenefitThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <> You're not getting the full benefit of your <SpellLink id={SPELLS.WILD_FLESHRENDING.id} /> Azerite trait on <SpellLink id={SPELLS.SHRED.id} />. To receive the trait's bonus damage you must have <SpellLink id={SPELLS.THRASH_FERAL.id} /> active on the target when you hit it with <SpellLink id={SPELLS.SHRED.id} />. </> ) .icon(SPELLS.WILD_FLESHRENDING.icon) .actual(`${(actual * 100).toFixed(0)}% of Shreds benefited from Wild Fleshrending.`) .recommended(`>${(recommended * 100).toFixed(0)}% is recommended`); }); const swipeSpell = this.selectedCombatant.hasTalent(SPELLS.BRUTAL_SLASH_TALENT.id) ? SPELLS.BRUTAL_SLASH_TALENT : SPELLS.SWIPE_CAT; when(this.swipeBenefitThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <> You're not getting the full benefit of your <SpellLink id={SPELLS.WILD_FLESHRENDING.id} /> Azerite trait on <SpellLink id={swipeSpell.id} />. To receive the trait's bonus damage you must have <SpellLink id={SPELLS.THRASH_FERAL.id} /> active on the target when you hit it with <SpellLink id={swipeSpell.id} />. </> ) .icon(SPELLS.WILD_FLESHRENDING.icon) .actual(`${(actual * 100).toFixed(0)}% of ${swipeSpell.name} hits benefited from Wild Fleshrending.`) .recommended(`>${(recommended * 100).toFixed(0)}% is recommended`); }); } } export default WildFleshrending;
js/components/home/categoryBar.js
hz47/expensesApp
import React, { Component } from 'react'; import { Animated, TouchableOpacity,Dimensions, PropTypes,StyleSheet, TouchableHighlight } from 'react-native'; import { View, Content, Text} from 'native-base'; import styles from './styles'; class CategoryBarChart extends Component { constructor(props) { super(props) const sumAllCategories = this.props.SumAll //////////////////i need this data const category = this.props.Sum; //////////////////i need this data const categoryWidth = this.getWidth(sumAllCategories, category); const width = { categoryItem: categoryWidth } this.state = { categoryItem: new Animated.Value(width.categoryItem) } } getWidth(sumAllCategories, category) { const oneCategory = category * (Dimensions.get('window').width - this.props.Window); return oneCategory / sumAllCategories; } handeleAnimation () { const timing = Animated.timing const width = {categoryItem: Dimensions.get('window').width - this.props.Window} const indicators = ['categoryItem'] Animated.parallel(indicators.map(item => { return timing(this.state[item], {toValue: width[item]}) })).start() } render() { const {categoryItem} = this.state return ( <View style={styles.budgetWrap }> {categoryItem && <Animated.View style={[styles.barWrapper, {width: Dimensions.get('window').width - this.props.Window + 2}]} > <Animated.View style={[styles.bar, {width: categoryItem }]} > </Animated.View> </Animated.View> } <Text style={styles.budgetValue} onPress={this.handeleAnimation.bind(this)}>{this.props.Name} </Text> </View> ); } } export default CategoryBarChart;
docs/app/Examples/elements/Button/Variations/ButtonExampleSize.js
koenvg/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleSize = () => ( <div> <Button size='mini'> Mini </Button> <Button size='tiny'> Tiny </Button> <Button size='small'> Small </Button> <Button size='medium'> Medium </Button> <Button size='large'> Large </Button> <Button size='big'> Big </Button> <Button size='huge'> Huge </Button> <Button size='massive'> Massive </Button> </div> ) export default ButtonExampleSize
src/svg-icons/maps/local-pizza.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPizza = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); MapsLocalPizza = pure(MapsLocalPizza); MapsLocalPizza.displayName = 'MapsLocalPizza'; MapsLocalPizza.muiName = 'SvgIcon'; export default MapsLocalPizza;
src/components/footer.js
fiveinfinity/ic-crowdsale
import React from 'react'; import styles from '../stylesheets/footer.css'; export const Footer = (props) => { return ( <div className={styles.footer}> <div className={styles.content}> <i className="fa fa-copyright" aria-hidden="true"></i>I'M CONVENIENCED, LLC. All rights Reserved. </div> <div className={`${styles.content} ${styles.social}`}> <a href="https://twitter.com/imconvenienced"><i className="fa fa-twitter-square fa-inverse" aria-hidden="true"></i></a> <a href="https://imconvenienced.slack.com/join/shared_invite/enQtMjYyOTMzNjMwOTEyLWMyYTVlZTA1Y2EyZWIyOTI2ZTJmYzdmMTg2MDcwMDAzZjIyODlhZDNjZTFiNjkwMjdhYWJmNzdlZjIyZGYwOWI"><i className="fa fa-slack fa-inverse" aria-hidden="true"></i></a> <a href="https://www.reddit.com/r/imconvenienced/"><i className="fa fa-reddit-square fa-inverse" aria-hidden="true"></i></a> </div> <img className={styles.frog} src="../../public/images/frog.jpg" alt="For Soren." /> </div> ); };
pootle/static/js/admin/app.js
r-o-b-b-i-e/pootle
/* * 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 'imports?Backbone=>require("backbone")!backbone-move'; import React from 'react'; import ReactDOM from 'react-dom'; import { q } from 'utils/dom'; import AdminController from './components/AdminController'; import User from './components/User'; import Language from './components/Language'; import Project from './components/Project'; import AdminRouter from './AdminRouter'; window.PTL = window.PTL || {}; const itemTypes = { user: User, language: Language, project: Project, }; PTL.admin = { init(opts) { if (!itemTypes.hasOwnProperty(opts.itemType)) { throw new Error('Invalid `itemType`.'); } ReactDOM.render( <AdminController adminModule={itemTypes[opts.itemType]} appRoot={opts.appRoot} formChoices={opts.formChoices || {}} router={new AdminRouter()} />, q('.js-admin-app') ); }, };
src/ModalTitle.js
thealjey/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalTitle extends React.Component { render() { return ( <h4 {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> { this.props.children } </h4> ); } } ModalTitle.propTypes = { /** * A css class applied to the Component */ modalClassName: React.PropTypes.string }; ModalTitle.defaultProps = { modalClassName: 'modal-title' }; export default ModalTitle;
app/containers/App.js
mitchconquer/erb-sqlite-example
// @flow import React, { Component } from 'react'; import type { Children } from 'react'; export default class App extends Component { props: { children: Children }; render() { return ( <div> {this.props.children} </div> ); } }
templates/rubix/rails/rails-example/src/main.js
jeffthemaximum/jeffline
import React from 'react'; import ReactDOM from 'react-dom'; import routes from './routes'; import render, { setRoutes } from '@sketchpixy/rubix/lib/others/router'; import { isBrowser } from '@sketchpixy/rubix'; if (isBrowser()) { render(routes, () => { console.log('Completed rendering!'); }); if (module.hot) { module.hot.accept('./routes', () => { // reload routes again require('./routes').default; render(routes); }); } } else { // set routes for server-side rendering setRoutes(routes); }
components/RedditPost.js
turntwogg/final-round
import React from 'react'; import { MdLaunch } from 'react-icons/md'; import Typography from './Typography'; const RedditPost = ({ post }) => ( <div className="reddit-post"> <div className="reddit-post-content"> <Typography is="h4" className="reddit-post-title" style={{ margin: 0 }}> <a href={post.data.url} target="_blank" rel="noopener noreferrer" aria-label={post.data.title} > {post.data.title} </a> </Typography> <p className="reddit-post-subreddit"> {post.data.subreddit_name_prefixed} </p> </div> <a href={post.data.url} target="_blank" rel="noopener noreferrer" className="reddit-post-link" aria-label={post.data.title} > <MdLaunch /> </a> <style jsx>{` .reddit-post { display: flex; justify-content: space-between; } .reddit-post-link { margin-left: 16px; } .reddit-post-subreddit { font-size: 14px; margin: 0; } `}</style> </div> ); export default RedditPost;
src/js/page.js
banmunongtian/react-es6-webpack
import React from 'react'; import ReactDom from 'react-dom'; import '../css/img-styles.css'; export default class Hellos extends React.Component { constructor(props) { super(props) this.state = { id: 1 } } componentWillMont() { } render() { return ( <div> <img src={require('../img/Tulips.jpg')} className="img" /> </div> ) } } ReactDom.render(<Hellos/>, document.getElementById('page'))
src/EditorTest.js
builden/react-electron-boilerplate
import React, { Component } from 'react'; import MonacoContainer from './MonacoContainer'; import { Fill, Box, Flex } from './ui'; const supportLang = ['javascript', 'lua']; const themes = ['vs-dark', 'vs']; class EditorTest extends Component { state = { language: 'lua', theme: 'vs-dark', }; renderHeader = () => { return ( <Flex shrink={0} h={30} my={4}> <select onChange={e => this.setState({ language: e.target.value })} defaultValue={this.state.language}> {supportLang.map(lang => ( <option key={lang} value={lang}> {lang} </option> ))} </select> <select onChange={e => this.setState({ theme: e.target.value })} defaultValue={this.state.theme}> {themes.map(theme => ( <option key={theme} value={theme}> {theme} </option> ))} </select> </Flex> ); }; render() { const { language, theme } = this.state; return ( <Fill flex column> {this.renderHeader()} <Box grow={1} style={{ position: 'relative' }} ofxy="hidden"> <Fill> <MonacoContainer language={language} theme={theme} /> </Fill> </Box> </Fill> ); } } export default EditorTest;
src/client.js
PitayaX/pitayax-web
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill' import React from 'react' import ReactDOM from 'react-dom' import createHistory from 'history/lib/createBrowserHistory' import createStore from './redux/create' import ApiClient from './helpers/ApiClient' import io from 'socket.io-client' import { Provider } from 'react-redux' import { reduxReactRouter, ReduxRouter } from 'redux-router' import getRoutes from './routes' import makeRouteHooksSafe from './helpers/makeRouteHooksSafe' const client = new ApiClient() const dest = document.getElementById('content') const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), createHistory, client, window.__data) function initSocket () { const socket = io('', { path: '/api/ws', transports: [ 'polling' ] }) socket.on('news', (data) => { console.log(data) socket.emit('my other event', { my: 'data from client' }) }) socket.on('msg', (data) => { console.log(data) }) return socket } global.socket = initSocket() const component = ( <ReduxRouter routes={getRoutes(store)} /> ) ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ) if (process.env.NODE_ENV !== 'production') { window.React = React // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.') } } if (__DEVTOOLS__) { // const DevTools = require('./containers/DevTools/DevTools') const DevTools = require('./containers/DevTools/DevTools') ReactDOM.render( <Provider store={store} key="provider"> <div> {component} </div> </Provider>, dest ) }
examples/todomvc/index.js
iam4x/redux
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
client/admin/layout/Full/Full.js
bigwisu/josspoll
import React, { Component } from 'react'; import Header from '../../components/Header/'; import Sidebar from '../../components/Sidebar/'; import Aside from '../../components/Aside/'; import Footer from '../../components/Footer/'; // import Breadcrumbs from 'react-breadcrumbs'; class Full extends Component { render() { return ( <div className="app"> <Header /> <div className="app-body"> <Sidebar {...this.props}/> <main className="main"> {/*<Breadcrumbs wrapperElement="ol" wrapperClass="breadcrumb" itemClass="breadcrumb-item" separator="" routes={this.props.routes} params={this.props.params} />*/} <div className="container-fluid"> {this.props.children} </div> </main> <Aside /> </div> <Footer /> </div> ); } } export default Full;
src/client/depcy-injection/node-modules.js
boris91/hype
import React from 'react'; import ReactDom from 'react-dom'; import * as ReactRedux from 'react-redux'; import * as ReactRouter from 'react-router'; import * as Redux from 'redux'; import ReduxThunk from 'redux-thunk'; import ReduxLogger from 'redux-logger'; export default { React, ReactDom, ReactRedux, ReactRouter, Redux, ReduxThunk, ReduxLogger };
test/fixtures/proton/index.js
develar/electron-builder
import React, { Component } from 'react'; import { render, Window, App, Button } from 'proton-native'; class Example extends Component { render() { return ( <App> <Window title="Example" size={{w: 300, h: 300}} menuBar={false}> <Button stretchy={false} onClick={() => console.log('Hello')}> Button </Button> </Window> </App> ); } } render(<Example />);