path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
docs/src/app/components/pages/customization/InlineStyles.js
ruifortes/material-ui
import React from 'react'; import Title from 'react-title-component'; import Checkbox from 'material-ui/Checkbox'; import CodeExample from '../../CodeExample'; import typography from 'material-ui/styles/typography'; class InlineStyles extends React.Component { getStyles() { return { headline: { fontSize: 24, lineHeight: '32px', paddingTop: 16, marginBottom: 12, letterSpacing: 0, fontWeight: typography.fontWeightNormal, color: typography.textDarkBlack, }, title: { fontSize: 20, lineHeight: '28px', paddingTop: 19, marginBottom: 13, letterSpacing: 0, fontWeight: typography.fontWeightMedium, color: typography.textDarkBlack, }, }; } render() { const codeOverrideStyles = '<Checkbox\n' + ' id="checkboxId1"\n' + ' name="checkboxName1"\n' + ' value="checkboxValue1"\n' + ' label="went for a run today"\n' + ' style={{\n' + ' width: \'50%\',\n' + ' margin: \'0 auto\'\n' + ' }}\n' + ' iconStyle={{\n' + ' fill: \'#FF4081\'\n' + ' }}/>'; const codeMixStyles = '<Checkbox\n' + ' id="checkboxId1"\n' + ' name="checkboxName1"\n' + ' value="checkboxValue1"\n' + ' label="went for a run today"\n' + ' className="muidocs-checkbox-example"\n' + ' iconStyle={{\n' + ' fill: \'#FF9800\'\n' + ' }}/>\n\n' + '/* In our CSS file */\n' + '.muidocs-checkbox-example { \n' + ' border: 2px solid #0000FF;\n' + ' background-color: #FF9800;\n' + '}'; const styles = this.getStyles(); return ( <div> <Title render={(previousTitle) => `Inline Styles - ${previousTitle}`} /> <h2 style={styles.headline}>Inline Styles</h2> <p> All Material-UI components have their styles defined inline. You can read the <a href="https://github.com/callemall/material-ui/issues/30"> discussion thread</a> regarding this decision as well as <a href="https://speakerdeck.com/vjeux/react-css-in-js"> this presentation</a> discussing CSS in JS. </p> <h3 style={styles.title}>Overriding Inline Styles</h3> <CodeExample code={codeOverrideStyles} component={false}> <Checkbox id="checkboxId1" name="checkboxName1" value="checkboxValue1" label="Checked the mail" style={{ width: '50%', margin: '0 auto', }} iconStyle={{ fill: '#FF4081', }} /> </CodeExample> <p> If you would like to override a style property that has been defined inline, define your override via the style prop as demonstrated in the example above. These overrides take precedence over the theme (if any) that is used to render the component. The style prop is an object that applies its properties to the <b>root/outermost element</b> of the component. Some components provide additional style properties for greater styling control. If you need to override the inline styles of an element nested deep within a component and there is not a style property available to do so, please <a href="https://github.com/callemall/material-ui/issues"> submit an issue</a> requesting to have one added. </p> <h3 style={styles.title}>Mixing Inline and CSS Styles</h3> <CodeExample code={codeMixStyles} component={false}> <Checkbox id="checkboxId1" name="checkboxName1" value="checkboxValue1" label="Currently a UTD student" className="muidocs-checkbox-example" iconStyle={{ fill: '#FF9800', }} /> </CodeExample> <p> If you would like to add additional styling via CSS, pass in the class name via the className prop. The className prop is similar to the style prop in that it only applies to the root element. Note that CSS properties defined inline are given priority over those defined in a CSS class. Take a look at a component&#39;s <code>getStyles </code> function to see what properties are defined inline. </p> </div> ); } } export default InlineStyles;
examples/CarouselFullWidth.js
chris-gooley/react-materialize
import React from 'react'; import Carousel from '../src/Carousel'; export default <Carousel options={{ fullWidth: true }} images={[ 'https://lorempixel.com/800/400/food/1', 'https://lorempixel.com/800/400/food/2', 'https://lorempixel.com/800/400/food/3', 'https://lorempixel.com/800/400/food/4', 'https://lorempixel.com/800/400/food/5' ]} />;
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js
WangCrystal/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import classNames from 'classnames'; import DialogStore from 'stores/DialogStore'; export default React.createClass({ mixins: [PureRenderMixin], getInitialState() { return { typing: null, show: false }; }, componentDidMount() { DialogStore.addTypingListener(this.onTypingChange); }, componentWillUnmount() { DialogStore.removeTypingListener(this.onTypingChange); }, onTypingChange() { const typing = DialogStore.getSelectedDialogTyping(); if (typing === null) { this.setState({show: false}); } else { this.setState({typing: typing, show: true}); } }, render() { const typing = this.state.typing; const show = this.state.show; const typingClassName = classNames('typing', { 'typing--hidden': show === false }); return ( <div className={typingClassName}> <div className="typing-indicator"><i></i><i></i><i></i></div> <span>{typing}</span> </div> ); } });
examples/official-storybook/components/ImportedPropsButton.js
kadirahq/react-storybook
import React from 'react'; import { DocgenButton } from './DocgenButton'; /** Button component description */ const ImportedPropsButton = ({ disabled, label, onClick }) => ( <button type="button" disabled={disabled} onClick={onClick}> {label} </button> ); ImportedPropsButton.defaultProps = DocgenButton.defaultProps; ImportedPropsButton.propTypes = DocgenButton.propTypes; export default ImportedPropsButton;
apps/dashboard/components/Board.js
chengethem/fangxia_WIT
import React, { Component } from 'react'; class Board extends Component { render() { return (<div></div>); } } export default Board;
src/scripts/VideoImage.js
williamthing/yoda
'use strict'; import React from 'react'; import Join from 'react/lib/joinClasses'; import VideoDuration from './VideoDuration'; export default React.createClass({ componentDidMount() { var imgTag = React.findDOMNode(this.refs.image); var imgSrc = imgTag.getAttribute('src'); var img = new window.Image(); img.src = imgSrc; }, shouldComponentUpdate(nextProps) { return this.props.src !== nextProps.src; }, render() { var imgClasses = 'video-thumbnail image-thumbnail'; return ( <img ref="image" className={imgClasses} {...this.props} /> ); } });
app/javascript/flavours/glitch/features/composer/upload_form/item/index.js
vahnj/mastodon
// Package imports. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage, defineMessages, } from 'react-intl'; import spring from 'react-motion/lib/spring'; // Components. import IconButton from 'flavours/glitch/components/icon_button'; // Utils. import Motion from 'flavours/glitch/util/optional_motion'; import { assignHandlers } from 'flavours/glitch/util/react_helpers'; // Messages. const messages = defineMessages({ undo: { defaultMessage: 'Undo', id: 'upload_form.undo', }, description: { defaultMessage: 'Describe for the visually impaired', id: 'upload_form.description', }, }); // Handlers. const handlers = { // On blur, we save the description for the media item. handleBlur () { const { id, onChangeDescription, } = this.props; const { dirtyDescription } = this.state; if (id && onChangeDescription && dirtyDescription !== null) { this.setState({ dirtyDescription: null, focused: false, }); onChangeDescription(id, dirtyDescription); } }, // When the value of our description changes, we store it in the // temp value `dirtyDescription` in our state. handleChange ({ target: { value } }) { this.setState({ dirtyDescription: value }); }, // Records focus on the media item. handleFocus () { this.setState({ focused: true }); }, // Records the start of a hover over the media item. handleMouseEnter () { this.setState({ hovered: true }); }, // Records the end of a hover over the media item. handleMouseLeave () { this.setState({ hovered: false }); }, // Removes the media item. handleRemove () { const { id, onRemove, } = this.props; if (id && onRemove) { onRemove(id); } }, }; // The component. export default class ComposerUploadFormItem extends React.PureComponent { // Constructor. constructor (props) { super(props); assignHandlers(this, handlers); this.state = { hovered: false, focused: false, dirtyDescription: null, }; } // Rendering. render () { const { handleBlur, handleChange, handleFocus, handleMouseEnter, handleMouseLeave, handleRemove, } = this.handlers; const { description, intl, preview, } = this.props; const { focused, hovered, dirtyDescription, } = this.state; const computedClass = classNames('composer--upload_form--item', { active: hovered || focused }); // The result. return ( <div className={computedClass} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > <Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12, }), }} > {({ scale }) => ( <div style={{ transform: `scale(${scale})`, backgroundImage: preview ? `url(${preview})` : null, }} > <IconButton className='close' icon='times' onClick={handleRemove} size={36} title={intl.formatMessage(messages.undo)} /> <label> <span style={{ display: 'none' }}><FormattedMessage {...messages.description} /></span> <input maxLength={420} onBlur={handleBlur} onChange={handleChange} onFocus={handleFocus} placeholder={intl.formatMessage(messages.description)} type='text' value={dirtyDescription || description || ''} /> </label> </div> )} </Motion> </div> ); } } // Props. ComposerUploadFormItem.propTypes = { description: PropTypes.string, id: PropTypes.string, intl: PropTypes.object.isRequired, onChangeDescription: PropTypes.func, onRemove: PropTypes.func, preview: PropTypes.string, };
src/components/Navigation/NavItem.js
n3ssi3/liveaboard-express
import React from 'react' import PropTypes from 'prop-types' import { Route, Link } from 'react-router-dom' const NavItem = (props) => { const { to, exact, strict, activeClassName, className, activeStyle, style, isActive: getIsActive, ...rest } = props return ( <Route path={typeof to === 'object' ? to.pathname : to} exact={exact} strict={strict} children={({ location, match }) => { const isActive = !!(getIsActive ? getIsActive(match, location) : match) return ( <li className={ isActive ? [activeClassName, className].join(' ') : className } style={isActive ? { ...style, ...activeStyle } : style} > <Link to={to} {...rest} /> </li> ) }} /> ) } NavItem.propTypes = { to: PropTypes.string, exact: PropTypes.bool, strict: PropTypes.bool, activeClassName: PropTypes.string, className: PropTypes.string, activeStyle: PropTypes.object, style: PropTypes.object, isActive: PropTypes.bool, rest: PropTypes.object } export default NavItem
src/router.js
fishmankkk/mircowater2.0
import React from 'react' import PropTypes from 'prop-types' import { Router } from 'dva/router' import App from 'view/app' const registerModel = (app, model) => { if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) { app.model(model) } } const Routers = function ({ history, app }) { const routes = [ { path: '/', component: App, // getIndexRoute (nextState, cb) { // require.ensure([], (require) => { // registerModel(app, require('models/dashboard')) // cb(null, { component: require('view/dashboard/') }) // }, 'dashboard') // }, getIndexRoute (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/sms-dashboard')) cb(null, { component: require('view/sms/sms-dashboard/') }) }, 'sms-dashboard') }, childRoutes: [ { path: 'dashboard', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/dashboard')) cb(null, require('view/dashboard/')) }, 'dashboard') }, }, { path: 'sms/sms-signature', getComponent (nextState, cb) { require.ensure([], (require) => { // registerModel(app, require('models/user')) cb(null, require('view/sms/sms-signature/')) }, 'sms-signature') }, }, { path: 'sms/sms-account', getComponent (nextState, cb) { require.ensure([], (require) => { // registerModel(app, require('models/user')) cb(null, require('view/sms/sms-account/')) }, 'sms-account') }, }, { path: 'sms/sms-dashboard', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/sms-dashboard')) cb(null, require('view/sms/sms-dashboard/')) }, 'sms-dashboard') }, }, { path: 'user', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/user')) cb(null, require('view/user/')) }, 'user') }, }, { path: 'user/:id', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/user/detail')) cb(null, require('view/user/detail/')) }, 'user-detail') }, }, { path: 'component/base', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/base/')) }, 'component-base') }, }, { path: 'component/form', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/form/')) }, 'component-form') }, }, { path: 'component/base-expand', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/base-expand/')) }, 'component-base-expand') }, }, { path: 'component/base-expand2', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/base-expand2/')) }, 'component-base-expand2') }, }, { path: 'codeRules/codeCss', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/codeRules/codeCss/')) }, 'codeRules-codeCss') }, }, { path: 'component/table1', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/table/table1')) }, 'component-table1') }, }, { path: 'component/table2', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/component/table//table2')) }, 'component-table2') }, }, { path: 'testapi', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/testapi')) cb(null, require('view/testapi/')) }, 'testapi') }, }, { path: 'login', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/login')) cb(null, require('view/login/')) }, 'login') }, }, { path: 'logout', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/logout')) cb(null, require('view/logout/')) }, 'logout') }, }, { path: 'request', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/request/')) }, 'request') }, }, { path: 'UIElement/iconfont', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/iconfont/')) }, 'UIElement-iconfont') }, }, { path: 'UIElement/search', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/search/')) }, 'UIElement-search') }, }, { path: 'UIElement/dropOption', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/dropOption/')) }, 'UIElement-dropOption') }, }, { path: 'UIElement/layer', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/layer/')) }, 'UIElement-layer') }, }, { path: 'UIElement/dataTable', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/dataTable/')) }, 'UIElement-dataTable') }, }, { path: 'UIElement/editor', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/UIElement/editor/')) }, 'UIElement-editor') }, }, { path: 'chart/lineChart', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/chart/lineChart/')) }, 'chart-lineChart') }, }, { path: 'chart/barChart', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/chart/barChart/')) }, 'chart-barChart') }, }, { path: 'chart/areaChart', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/chart/areaChart/')) }, 'chart-areaChart') }, }, { path: 'post', getComponent (nextState, cb) { require.ensure([], (require) => { registerModel(app, require('models/post')) cb(null, require('view/post/')) }, 'post') }, }, { path: '*', getComponent (nextState, cb) { require.ensure([], (require) => { cb(null, require('view/error/')) }, 'error') }, }, ], }, ] return <Router history={history} routes={routes} /> } Routers.propTypes = { history: PropTypes.object, app: PropTypes.object, } export default Routers
src/app/components/footer.js
nazar/soapee-ui
import React from 'react'; import ShareThis from 'components/shareThis'; export default React.createClass( { shouldComponentUpdate() { return false; }, render() { return ( <footer className="footer hidden-print"> <div className="container"> <div className="row"> <div className="content col-md-7 col-sm-12"> <div>Soapee is a Saponification calculator, soap recipe and oils database</div> <div> Find us on <a href="https://www.reddit.com/r/soapee" target="_blank">Reddit</a> or <a href="https://www.facebook.com/soapeepage" target="_blank">Facebook</a>. All source code is published on <a href="https://github.com/nazar/soapee-ui" target="_blank">GitHub</a> </div> </div> <div className="col-md-5 col-sm-12 hidden-sm hidden-xs"> <div className="pull-right"> <ShareThis /> </div> </div> </div> </div> </footer> ); } } );
collect-webapp/frontend/src/datamanagement/components/recordeditor/NodeDefLabel.js
openforis/collect
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import { Label } from 'reactstrap' import InfoIcon from 'common/components/InfoIcon' import { NodeDefinition } from 'model/Survey' const NodeDefLabel = (props) => { const { nodeDefinition, limitWidth } = props const { numberLabel, labelOrName, description, labelWidth: labelWidthNodeDef } = nodeDefinition const hasNumberLabel = !!numberLabel const style = limitWidth ? { width: `${Math.max(labelWidthNodeDef || 0, 200)}px` } : {} return ( <div className={classNames('node-def-label-wrapper', { 'with-number': hasNumberLabel })} style={style}> {hasNumberLabel && ( <Label className="number-label"> {numberLabel} {NodeDefinition.NUMBER_LABEL_SUFFIX} </Label> )} <Label title={description}> {labelOrName} {description && <InfoIcon />} </Label> </div> ) } NodeDefLabel.propTypes = { nodeDefinition: PropTypes.instanceOf(NodeDefinition).isRequired, limitWidth: PropTypes.bool, } NodeDefLabel.defaultProps = { limitWidth: true, } export default NodeDefLabel
src/components/TrackerPad.js
KE-NIA/CircularitySolver
import React from 'react'; import FaroIonButtons from './FaroIonButtons'; import LeicaAt40xButtons from './LeicaButtons'; import FaroVantageButtons from './FaroVantageButtons'; export default class TrackerPad extends React.Component { constructor(props) { super(props); } render() { if (this.props.activeSensor === 'FaroIon') { return ( <FaroIonButtons connectSensor={() => { this.props.isConnected}}/> ); } else if (this.props.activeSensor === 'LeicaAt40x') { return ( <LeicaAt40xButtons connectSensor={() => {this.props.connectSensor}}/> ); }else if(this.props.activeSensor == 'FaroVantage'){ return ( <FaroVantageButtons connectSensor={() => {this.props.connectSensor}}/> ); }else{ return ( <div>"please choose a laser tracker"</div> ); } } }
fields/types/embedly/EmbedlyField.js
kumo/keystone
import React from 'react'; import Field from '../Field'; import { FormField, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'EmbedlyField', // always defers to renderValue; there is no form UI for this field renderField () { return this.renderValue(); }, renderValue (path, label, multiline) { return ( <FormField key={path} label={label} className="form-field--secondary"> <FormInput noedit multiline={multiline}>{this.props.value[path]}</FormInput> </FormField> ); }, renderAuthor () { if (!this.props.value.authorName) return; return ( <FormField key="author" label="Author" className="form-field--secondary"> <FormInput noedit href={this.props.value.authorUrl && this.props.value.authorUrl} target="_blank">{this.props.value.authorName}</FormInput> </FormField> ); }, renderDimensions () { if (!this.props.value.width || !this.props.value.height) return; return ( <FormField key="dimensions" label="Dimensions" className="form-field--secondary"> <FormInput noedit>{this.props.value.width} &times; {this.props.value.height}px</FormInput> </FormField> ); }, renderPreview () { if (!this.props.value.thumbnailUrl) return; var image = <img width={this.props.value.thumbnailWidth} height={this.props.value.thumbnailHeight} src={this.props.value.thumbnailUrl} />; var preview = this.props.value.url ? ( <a href={this.props.value.url} target="_blank" className="img-thumbnail">{image}</a> ) : ( <div className="img-thumbnail">{image}</div> ); return ( <FormField label="Preview" className="form-field--secondary"> {preview} </FormField> ); }, renderUI () { if (!this.props.value.exists) { return ( <FormField label={this.props.label}> <FormInput noedit>(not set)</FormInput> </FormField> ); } return ( <div className="field-type-embedly"> <FormField key="provider" label={this.props.label}> <FormInput noedit>{this.props.value.providerName} {this.props.value.type}</FormInput> </FormField> {this.renderValue('title', 'Title')} {this.renderAuthor()} {this.renderValue('description', 'Description', true)} {this.renderPreview()} {this.renderDimensions()} </div> ); } });
app/javascript/mastodon/components/media_gallery.js
amazedkoumei/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { is } from 'immutable'; import IconButton from './icon_button'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { isIOS } from '../is_mobile'; import classNames from 'classnames'; import { autoPlayGif, displaySensitiveMedia } from '../initial_state'; const messages = defineMessages({ toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' }, }); class Item extends React.PureComponent { static propTypes = { attachment: ImmutablePropTypes.map.isRequired, standalone: PropTypes.bool, index: PropTypes.number.isRequired, size: PropTypes.number.isRequired, onClick: PropTypes.func.isRequired, displayWidth: PropTypes.number, }; static defaultProps = { standalone: false, index: 0, size: 1, }; handleMouseEnter = (e) => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = (e) => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } hoverToPlay () { const { attachment } = this.props; return !autoPlayGif && attachment.get('type') === 'gifv'; } handleClick = (e) => { const { index, onClick } = this.props; if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); onClick(index); } e.stopPropagation(); } render () { const { attachment, index, size, standalone, displayWidth } = this.props; let width = 50; let height = 100; let top = 'auto'; let left = 'auto'; let bottom = 'auto'; let right = 'auto'; if (size === 1) { width = 100; } if (size === 4 || (size === 3 && index > 0)) { height = 50; } if (size === 2) { if (index === 0) { right = '2px'; } else { left = '2px'; } } else if (size === 3) { if (index === 0) { right = '2px'; } else if (index > 0) { left = '2px'; } if (index === 1) { bottom = '2px'; } else if (index > 1) { top = '2px'; } } else if (size === 4) { if (index === 0 || index === 2) { right = '2px'; } if (index === 1 || index === 3) { left = '2px'; } if (index < 2) { bottom = '2px'; } else { top = '2px'; } } let thumbnail = ''; if (attachment.get('type') === 'image') { const previewUrl = attachment.get('preview_url'); const previewWidth = attachment.getIn(['meta', 'small', 'width']); const originalUrl = attachment.get('url'); const originalWidth = attachment.getIn(['meta', 'original', 'width']); const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number'; const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null; const sizes = hasSize && (displayWidth > 0) ? `${displayWidth * (width / 100)}px` : null; const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0; const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0; const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; thumbnail = ( <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || originalUrl} onClick={this.handleClick} target='_blank' > <img src={previewUrl} srcSet={srcSet} sizes={sizes} alt={attachment.get('description')} title={attachment.get('description')} style={{ objectPosition: `${x}% ${y}%` }} /> </a> ); } else if (attachment.get('type') === 'gifv') { const autoPlay = !isIOS() && autoPlayGif; thumbnail = ( <div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}> <video className='media-gallery__item-gifv-thumbnail' aria-label={attachment.get('description')} title={attachment.get('description')} role='application' src={attachment.get('url')} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={autoPlay} loop muted /> <span className='media-gallery__gifv__label'>GIF</span> </div> ); } return ( <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> {thumbnail} </div> ); } } @injectIntl export default class MediaGallery extends React.PureComponent { static propTypes = { sensitive: PropTypes.bool, standalone: PropTypes.bool, media: ImmutablePropTypes.list.isRequired, size: PropTypes.object, height: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; static defaultProps = { standalone: false, }; state = { visible: !this.props.sensitive || displaySensitiveMedia, }; componentWillReceiveProps (nextProps) { if (!is(nextProps.media, this.props.media)) { this.setState({ visible: !nextProps.sensitive }); } } handleOpen = () => { this.setState({ visible: !this.state.visible }); } handleClick = (index) => { this.props.onOpenMedia(this.props.media, index); } handleRef = (node) => { if (node /*&& this.isStandaloneEligible()*/) { // offsetWidth triggers a layout, so only calculate when we need to this.setState({ width: node.offsetWidth, }); } } isStandaloneEligible() { const { media, standalone } = this.props; return standalone && media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']); } render () { const { media, intl, sensitive, height } = this.props; const { width, visible } = this.state; let children; const style = {}; if (this.isStandaloneEligible()) { if (width) { style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']); } } else if (width) { style.height = width / (16/9); } else { style.height = height; } if (!visible) { let warning; if (sensitive) { warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />; } else { warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />; } children = ( <button type='button' className='media-spoiler' onClick={this.handleOpen} style={style} ref={this.handleRef}> <span className='media-spoiler__warning'>{warning}</span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> ); } else { const size = media.take(4).size; if (this.isStandaloneEligible()) { children = <Item standalone onClick={this.handleClick} attachment={media.get(0)} displayWidth={width} />; } else { children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} index={i} size={size} displayWidth={width} />); } } return ( <div className='media-gallery' style={style} ref={this.handleRef}> <div className={classNames('spoiler-button', { 'spoiler-button--visible': visible })}> <IconButton title={intl.formatMessage(messages.toggle_visible)} icon={visible ? 'eye' : 'eye-slash'} overlay onClick={this.handleOpen} /> </div> {children} </div> ); } }
src/svg-icons/social/person-add.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPersonAdd = (props) => ( <SvgIcon {...props}> <path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/> </SvgIcon> ); SocialPersonAdd = pure(SocialPersonAdd); SocialPersonAdd.displayName = 'SocialPersonAdd'; SocialPersonAdd.muiName = 'SvgIcon'; export default SocialPersonAdd;
stack/src/routes.js
isabellewei/deephealth
'use strict'; import React from 'react' import { Route, IndexRoute } from 'react-router' import Layout from './components/Layout'; import IndexPage from './components/IndexPage'; import NotFoundPage from './components/NotFoundPage'; const routes = ( <Route path="/" component={Layout}> <IndexRoute component={IndexPage}/> <Route path="*" component={NotFoundPage}/> </Route> ); export default routes;
packages/arwes/src/Project/sandbox.js
romelperez/ui
import React from 'react'; import Arwes from '../Arwes'; import Words from '../Words'; import Project from './index'; export default () => ( <Arwes background="/images/background.jpg" pattern="/images/glow.png"> <div style={{ padding: 20 }}> <Project animate header="PROJECT, OFFICIA DESERUNT ANIM ID EST LABORUM"> {anim => ( <p> <Words animate show={anim.entered}> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis laboris nisi ut aliquip ex. Duis aute irure. Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </Words> </p> )} </Project> </div> </Arwes> );
src/App.js
roytang121/phaser-game-demo
import React, { Component } from 'react'; import leftpad from 'left-pad'; import Beat from './Beat'; import getUserMedia from 'getusermedia'; import Parser from './Parser'; let game = null; let player = null; let groundHeight = 25; let totalPointText = null; let totalPoint = 0; let fullPoint = 0; let comboCount = 0; let gameTime = 0; // in ms let gameStartTimestamp = null; // let kGameTimeInterval = 100; // let gameTimer = null; let gameShouldStart = false; let gameShouldEnd = false; let gameEnded = false; let startGameTime = 0; // in ms let kStartGameCounterInterval = 1500; let kStartGameCounterShouldEndAtTime = kStartGameCounterInterval * 3 let startGameCounter = null; let beats = []; let beatSprites = []; let tempo = 5; let self = null; let audioFile = null; import style from './style.css'; export default class App extends Component { constructor(props) { super(props) self = this; this.game = null; this.player = null; this.platforms = null; this.cursors = null; } componentDidMount() { console.log("onComponentDidMount"); // setupUserMedia this.setupUserMedia(); // 4th argument is the DOM id to be inserted in, default appending to body this.game = new Phaser.Game(800, 470, Phaser.AUTO, 'container', { preload: this.preload.bind(this), create: this.create.bind(this), update: this.update.bind(this) }); game = this.game; } preload() { console.log("onPreload"); this.game.load.image('sky', 'assets/img/sky.png'); this.game.load.image('ground', 'assets/img/bottombar.png'); this.game.load.image('star', 'assets/img/star.png'); this.game.load.spritesheet('dude', 'assets/img/rat_run.png', 45, 46); this.game.load.image('markbar', 'assets/img/markbar.png'); this.game.load.image('bottombg', 'assets/img/bottombg.png'); this.game.load.image('topbg', 'assets/img/topbg.png'); this.game.load.image('beat', 'assets/img/beat.png'); this.game.load.image('beat-placeholder', 'assets/img/beat_placeholder.png'); this.game.load.image('win-screen', 'assets/img/win_screen.png'); this.game.load.image('lose-screen', 'assets/img/lose_screen.png'); this.game.load.spritesheet('nyancat', 'assets/img/nyancat_run_sheet.png', 272, 168); // font // this.game.load.bitmapFont('riit', 'assets/font/riit.otf', null); // audio this.game.load.audio('win-audio', 'assets/audio/90.wav'); this.game.load.audio('lose-audio', 'assets/audio/lose.wav'); this.game.load.audio('ready', 'assets/audio/1.wav'); this.game.load.audio('count-low', 'assets/audio/count_low.wav'); } create() { console.log("onCreate"); var platforms = null; game.physics.startSystem(Phaser.Physics.ARCADE); game.add.sprite(0, 0, 'sky'); game.add.sprite(0, game.world.height - 25); game.add.sprite(0, 0, 'topbg'); var cat = game.add.sprite(-30, 15, 'nyancat'); cat.animations.add('run', null, 10, true); cat.scale.setTo(0.8,0.8); cat.angle = -10; cat.play('run'); game.add.sprite(0, 117, 'markbar'); game.add.sprite(0, 117 * 2, 'bottombg'); platforms = game.add.group(); this.platforms = platforms platforms.enableBody = true // var ground = platforms.create(0, game.world.height - groundHeight, 'ground'); // ground.scale.setTo(2, 2); ground.body.immovable = true; // // var ledge = platforms.create(400, 400, 'ground'); // ledge.body.immovable = true; // // ledge = platforms.create(-150, 250, 'ground'); // // ledge.body.immovable = true; // The player and its settings player = game.add.sprite(game.world.width / 2 - 22.5, game.world.height - 46 - groundHeight, 'dude'); this.player = player // We need to enable physics on the player game.physics.arcade.enable(player); // Player physics properties. Give the little guy a slight bounce. player.body.bounce.y = 0.2; player.body.gravity.y = 800; player.body.collideWorldBounds = true; // Our two animations, walking left and right. // player.animations.add('left', [0, 1, 2, 3], 10, true); player.animations.add('right', [0, 1, 2, 3], 10, true); this.cursors = game.input.keyboard.createCursorKeys(); // Text totalPointText = game.add.text(30 , 121, '00000'); totalPointText.font = 'Riit'; totalPointText.fontSize = 36; totalPointText.addColor("#ffffff", 0); // add beats to canvas game.add.sprite(240, 117.5, 'beat-placeholder'); // this.constructBeats(); } update() { // Collide the player and the stars with the platforms this.game.physics.arcade.collide(this.player, this.platforms); this.player.animations.play('right'); totalPointText.text = leftpad(totalPoint.toString(), 5, 0); if (gameShouldStart) { if (gameStartTimestamp === null) { gameStartTimestamp = Date.now(); } gameTime = Math.abs(Date.now() - gameStartTimestamp); // console.log(gameTime); // totalPoint += 1; this.computeBeats(); if (beatSprites.length <= 0) { gameShouldStart = false; gameShouldEnd = true; } } if (!gameEnded && gameShouldEnd) { console.log("Game Should End"); gameEnded = true; this.gameWillEnd(); } // if (!this.cursors) return; // // var cursors = this.cursors; // // Reset the players velocity (movement) // player.body.velocity.x = 0; // // if (cursors.left.isDown) // { // // Move to the left // player.body.velocity.x = -150; // // player.animations.play('left'); // } // else if (cursors.right.isDown) // { // // Move to the right // player.body.velocity.x = 150; // // player.animations.play('right'); // } // else // { // // Stand still // player.animations.stop(); // // player.frame = 4; // } // // // Allow the player to jump if they are touching the ground. // if (cursors.up.isDown && player.body.touching.down) // { // player.body.velocity.y = -350; // } } gameWillEnd() { let result = totalPoint/fullPoint; if (result > 0.5) { this.gameWillWin(); } else { this.gameWillLose(); } } gameWillWin() { var win = game.add.sprite(0, 0, 'win-screen'); // win.anchor.setTo(0.5,0.5); win.alpha = 0; game.add.tween(win).to({ alpha: 1 }, 750,Phaser.Easing.Linear.None, true, 0, 0, false); let counter = 0; let looper = setInterval(()=>{ var music = game.add.audio('win-audio'); music.play(); counter+=1; if (counter > 3) { clearInterval(looper); } }, 3000); } gameWillLose() { var lose = game.add.sprite(0, 0, 'lose-screen'); // win.anchor.setTo(0.5,0.5); lose.alpha = 0; game.add.tween(lose).to({ alpha: 1 }, 750,Phaser.Easing.Linear.None, true, 0, 0, false); let counter = 0; let looper = setInterval(()=>{ var music = game.add.audio('lose-audio'); music.play(); counter+=1; if (counter > 3) { clearInterval(looper); } }, 3000); } startgameCounterUpdate() { // console.log(startGameTime); // play game ready sound this.game.add.audio('count-low').play(); let time = 3 - (startGameTime / kStartGameCounterShouldEndAtTime * 3) console.log(time); startGameTime += kStartGameCounterInterval; // defer if (startGameTime >= kStartGameCounterShouldEndAtTime) { clearInterval(startGameCounter); // start Game Timer gameShouldStart = true; // play the audio file var audio = new Audio(audioFile.name); audio.play(); } } constructBeats() { let originX = 240; let originY = 117.5;  var sprites = []; for (var beat of beats) { var s = game.add.sprite(originX + beat.startTime * 60 * tempo, originY, 'beat'); sprites.push(s); } beatSprites = sprites fullPoint = sprites.length * 1000; console.log("fullPoint: " + fullPoint); } computeBeats() { let sprites = beatSprites; for (var sprite of sprites) { sprite.x -= 1 * tempo; if (sprite.x < 240) { beatSprites.shift(); beats.shift(); sprite.destroy(); } } } didTriggerClap() { console.log("clap"); if (beats.length <= 0 || beatSprites.length <= 0) { console.error('[Error] didTriggerClap but beats / beatSprites length <= 0'); return; } let firstBeat = beats[0]; let firstBeatSprite = beatSprites[0]; if (firstBeat.startTime * 1000 - gameTime < 800) { // add points totalPoint += 1000 } } // @Author Middle setupUserMedia() { var audioContext = new (window.AudioContext || window.webkitAudioContext)(); var lock = false; getUserMedia({audio:true}, (err, stream) => { if (err) { console.log(err); } else { console.log('got s stream', stream); var source = audioContext.createMediaStreamSource(stream); var node = audioContext.createScriptProcessor(256, 1,1); node.onaudioprocess = function(e){ var data = e.inputBuffer.getChannelData(0); if (lock==false){ for (var i =0 ; i<256; i++){ if (Math.abs(data[i])>0.9){ // console.log("up"); self.didTriggerClap(); lock=true; break; } } }else{ if (Math.abs(e.inputBuffer.getChannelData(0)[100])<0.001){ // console.log("down"); lock=false; } } } source.connect(node); node.connect(audioContext.destination); } }); // audio file $("document").ready(function() { $('#audio_file').change(function() { audioFile = this.files[0]; console.log(audioFile); var parser = new Parser(this.files[0], (peaks) => { // console.log(peaks); for (var peak of peaks) { beats.push(new Beat(peak/1000)); } self.constructBeats(); // count 3 seconds to start game startGameCounter = setInterval(self.startgameCounterUpdate.bind(self), kStartGameCounterInterval); }); }); }); } render() { return ( <div> <div id="bg"> </div> <input id="audio_file" type="file" accept="audio/*"></input> <h1>Comp 4441</h1> <div id="container" className="container"></div> </div> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/env/PublicUrl.js
reedsa/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; export default () => ( <span id="feature-public-url">{process.env.PUBLIC_URL}.</span> );
src/components/Links.js
hwclass/fe-as-microservices
import React from 'react' export default () => ( <div> <span>Links</span> </div> )
codes/chapter05/react-router-v4/advanced/demo01/app/components/NoMatch.js
atlantis1024/react-step-by-step
import React from 'react'; class NoMatch extends React.PureComponent { render() { return ( <div> <h2>无法匹配 <code>{this.props.location.pathname}</code></h2> </div> ) } } export default NoMatch;
src/components/Header.js
whirish/website
import React from 'react' import PropTypes from 'prop-types' const Header = props => ( <header id="header" style={props.timeout ? { display: 'none' } : {}}> <div className="logo"> <span className="icon fa-code" /> </div> <div className="content"> <div className="inner"> <h1>Liam O'Flynn</h1> <p> Full-stack web developer based in San Francisco {/* {' '} <a href="https://html5up.net">HTML5 UP</a> and released <br /> for free under the{' '} <a href="https://html5up.net/license">Creative Commons</a> license. */} </p> </div> </div> <nav> <ul> <li> <a href="#void" onClick={() => { props.onOpenArticle('intro') }} > Intro </a> </li> <li> <a href="#void" onClick={() => { props.onOpenArticle('work') }} > Work </a> </li> <li> <a href="#void" onClick={() => { props.onOpenArticle('about') }} > About </a> </li> <li> <a href="#void" onClick={() => { props.onOpenArticle('contact') }} > Contact </a> </li> </ul> </nav> </header> ) Header.propTypes = { onOpenArticle: PropTypes.func, timeout: PropTypes.bool, } export default Header
docs/client.js
pieter-lazzaro/react-bootstrap
import 'bootstrap/less/bootstrap.less'; import './assets/docs.css'; import './assets/style.css'; import './assets/carousel.png'; import './assets/logo.png'; import './assets/favicon.ico'; import './assets/thumbnail.png'; import './assets/thumbnaildiv.png'; import 'codemirror/mode/htmlmixed/htmlmixed'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/theme/solarized.css'; import 'codemirror/lib/codemirror.css'; import './assets/CodeMirror.css'; import React from 'react'; import CodeMirror from 'codemirror'; import 'codemirror/addon/runmode/runmode'; import Router from 'react-router'; import routes from './src/Routes'; global.CodeMirror = CodeMirror; Router.run(routes, Router.RefreshLocation, Handler => { React.render( React.createElement(Handler, window.INITIAL_PROPS), document); });
client/src/components/Dialog/index.js
dotkom/super-duper-fiesta
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Card from '../Card'; import css from './Dialog.css'; const Dialog = ({ visible, title, subtitle, onClose, children, hideCloseSymbol }) => { const dialogClass = classNames(css.component, { [css.visible]: visible, }); // eslint-disable-next-line jsx-a11y/no-static-element-interactions const corner = !hideCloseSymbol && <div onClick={onClose} className={css.close} />; return ( <div className={dialogClass}> <div // eslint-disable-line jsx-a11y/no-static-element-interactions onClick={onClose} className={css.backdrop} /> <Card classes={css.dialog} title={title} subtitle={subtitle} corner={corner} > {children} </Card> </div> ); }; Dialog.defaultProps = { hideCloseSymbol: false, subtitle: '', visible: false, }; Dialog.propTypes = { hideCloseSymbol: PropTypes.bool, visible: PropTypes.bool, title: PropTypes.string.isRequired, subtitle: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, onClose: PropTypes.func.isRequired, }; export default Dialog;
components/Spinner/Spinner.js
rpowis/pusscat.lol
import React, { Component } from 'react'; import './Spinner.scss'; export default class extends Component { render() { return ( <div className="spinner"> <div className="double-bounce1"></div> <div className="double-bounce2"></div> </div> ); } }
site/WorkHard_File/src/SideBar.js
harrydrippin/Workhard
import React, { Component } from 'react'; import {List, ListItem} from 'material-ui/List'; import AssignmentIcon from 'material-ui/svg-icons/action/assignment'; import NoteIcon from 'material-ui/svg-icons/av/note'; import AddIcon from 'material-ui/svg-icons/av/playlist-add'; class SideBar extends Component { constructor() { super(...arguments); } render() { return ( <div className="sidebar"> <div className="sidebar-title-wrapper"> <span className="sidebar-title">카테고리</span> </div> <List className="sidebar-list"> <ListItem primaryText="자료조사" leftIcon={<AssignmentIcon />}/> <ListItem primaryText="발표 자료" style={{color: "#2196f3"}} leftIcon={<NoteIcon color={"#2196f3"}/>}/> <ListItem primaryText="카테고리 추가" leftIcon={<AddIcon />}/> </List> </div> ); } } export default SideBar;
src/rsg-components/Methods/MethodsRenderer.js
bluetidepro/react-styleguidist
import React from 'react'; import PropTypes from 'prop-types'; import Markdown from 'rsg-components/Markdown'; import Argument from 'rsg-components/Argument'; import Arguments from 'rsg-components/Arguments'; import Name from 'rsg-components/Name'; import JsDoc from 'rsg-components/JsDoc'; import Table from 'rsg-components/Table'; const getRowKey = row => row.name; export const columns = [ { caption: 'Method name', // eslint-disable-next-line react/prop-types render: ({ name, tags = {} }) => <Name deprecated={!!tags.deprecated}>{`${name}()`}</Name>, }, { caption: 'Parameters', // eslint-disable-next-line react/prop-types render: ({ params = [] }) => <Arguments args={params} />, }, { caption: 'Description', // eslint-disable-next-line react/prop-types render: ({ description, returns, tags = {} }) => ( <div> {description && <Markdown text={description} />} {returns && <Argument block returns {...returns} />} <JsDoc {...tags} /> </div> ), }, ]; export default function MethodsRenderer({ methods }) { return <Table columns={columns} rows={methods} getRowKey={getRowKey} />; } MethodsRenderer.propTypes = { methods: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, description: PropTypes.string, returns: PropTypes.object, params: PropTypes.array, tags: PropTypes.object, }) ).isRequired, };
src/shared/components/form/formEmail/formEmail.js
alexspence/operationcode_frontend
import React, { Component } from 'react'; import FormInput from '../formInput/formInput'; class FormEmail extends Component { render() { return ( <FormInput {...this.props} validationRegex={/\S+@\S+\.\S+/} validationErrorMessage="Must be a valid email" /> ); } } export default FormEmail;
src/Parser/Core/Modules/NetherlightCrucibleTraits/SecureInTheLight.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import HealingDone from 'Parser/Core/Modules/HealingDone'; /** * Secure in the Light * Your harmful spells and abilities have the chance to deal 135000 additional damage and grant you Holy Bulwark, absorbing up to 135000 damage over 8 sec. */ class SecureInTheLight extends Analyzer { static dependencies = { combatants: Combatants, healingDone: HealingDone, }; damage = 0; on_initialized() { this.active = this.combatants.selected.traitsBySpellId[SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id] > 0; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SECURE_IN_THE_LIGHT_DAMAGE.id){ return; } this.damage += (event.amount || 0) + (event.absorbed || 0) + (event.overkill || 0); } subStatistic() { const healing = this.healingDone.byAbility(SPELLS.HOLY_BULWARK.id).effective; return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id}> <SpellIcon id={SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id} noLink /> Secure in the Light </SpellLink> </div> <div className="flex-sub text-right"> {formatPercentage(this.owner.getPercentageOfTotalHealingDone(healing))} % healing<br /> {formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damage))} % damage </div> </div> ); } } export default SecureInTheLight;
src/pages/404.js
growcss/docs
import React from 'react'; import Box from 'components/box'; import Layout from 'components/layout'; const NotFound = () => ( <Layout> <Box>Not found.</Box> </Layout> ); export default NotFound;
node_modules/expo/src/BlurView.android.js
RahulDesai92/PHR
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, ViewPropTypes } from 'react-native'; import deprecatedPropType from 'react-native/Libraries/Utilities/deprecatedPropType'; export default class BlurView extends Component { static propTypes = { tintEffect: deprecatedPropType( PropTypes.string, 'Use the `tint` prop instead.' ), tint: PropTypes.oneOf(['light', 'default', 'dark']), ...ViewPropTypes, }; render() { let { tint } = this.props; let backgroundColor; if (tint === 'dark') { backgroundColor = 'rgba(0,0,0,0.5)'; } else if (tint === 'light') { backgroundColor = 'rgba(255,255,255,0.7)'; } else { backgroundColor = 'rgba(255,255,255,0.4)'; } return ( <View {...this.props} style={[this.props.style, { backgroundColor }]} /> ); } }
app/scripts/components/view-mode-selector.js
hustbill/autorender-js
import React from 'react'; import { connect } from 'react-redux'; import classNames from 'classnames'; import MetricSelector from './metric-selector'; import { setGraphView, setTableView, setResourceView, setControlView} from '../actions/app-actions'; import { layersTopologyIdsSelector } from '../selectors/resource-view/layout'; import { availableMetricsSelector } from '../selectors/node-metric'; import { isGraphViewModeSelector, isTableViewModeSelector, isResourceViewModeSelector, isControlViewModeSelector, } from '../selectors/topology'; const Item = (icons, label, isSelected, onClick, isEnabled = true) => { const className = classNames('view-mode-selector-action', { 'view-mode-selector-action-selected': isSelected, }); return ( <div className={className} disabled={!isEnabled} onClick={isEnabled && onClick} title={`View ${label.toLowerCase()}`}> <span className={icons} style={{fontSize: 12}} /> <span className="label">{label}</span> </div> ); }; class ViewModeSelector extends React.Component { componentWillReceiveProps(nextProps) { if (nextProps.isResourceViewMode && !nextProps.hasResourceView) { nextProps.setGraphView(); } } render() { const { isGraphViewMode, isTableViewMode, isResourceViewMode, hasResourceView, isControlViewMode } = this.props; return ( <div className="view-mode-selector"> <div className="view-mode-selector-wrapper"> {Item('fa fa-share-alt', 'Topology', isGraphViewMode, this.props.setGraphView)} {Item('fa fa-area-chart', 'Report', isResourceViewMode, this.props.setResourceView, hasResourceView)} {Item('fa fa-external-link', 'Control', isControlViewMode, this.props.setControlView)} {Item('fa fa-table', 'Table', isTableViewMode, this.props.setTableView)} </div> <MetricSelector /> </div> ); } } function mapStateToProps(state) { return { isGraphViewMode: isGraphViewModeSelector(state), isTableViewMode: isTableViewModeSelector(state), isControlViewMode: isControlViewModeSelector(state), isResourceViewMode: isResourceViewModeSelector(state), hasResourceView: !layersTopologyIdsSelector(state).isEmpty(), showingMetricsSelector: availableMetricsSelector(state).count() > 0, }; } export default connect( mapStateToProps, { setGraphView, setTableView, setResourceView, setControlView } )(ViewModeSelector);
web/main.js
jgraichen/mnemosyne
import React from 'react' import { Toolbar } from './components/toolbar' import './main.sass' export class Main extends React.Component { render() { return ( <div> <Toolbar /> {this.props.children} </div> ) } }
js/components/home/placeDetails.js
crod93/googlePlacesEx-react-native
'use strict'; import React, { Component } from 'react'; import {Modal} from 'react-native'; import { connect } from 'react-redux'; import { openDrawer } from '../../actions/drawer'; import { replaceRoute } from '../../actions/route'; import { Container, Header, Title, Content, View, Text, Button, Icon} from 'native-base'; import { Grid, Col, Row } from 'react-native-easy-grid'; import myTheme from '../../themes/base-theme'; import styles from './styles'; class PlaceItem extends Component{ render(){ } } module.exports = PlaceItem;
js/components/reminder/index.js
ChiragHindocha/stay_fit
import React, { Component } from 'react'; import { StatusBar } from 'react-native'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Text, H3, Button, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; class Anatomy extends Component { static propTypes = { openDrawer: React.PropTypes.func, } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Left> <Body> <Title>Header</Title> </Body> <Right /> </Header> <Content padder> <Text> Content Goes Here </Text> </Content> <Footer> <FooterTab> <Button active full> <Text>Footer</Text> </Button> </FooterTab> </Footer> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Anatomy);
src/svg-icons/image/loupe.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLoupe = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.49 2 2 6.49 2 12s4.49 10 10 10h8c1.1 0 2-.9 2-2v-8c0-5.51-4.49-10-10-10zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ImageLoupe = pure(ImageLoupe); ImageLoupe.displayName = 'ImageLoupe'; ImageLoupe.muiName = 'SvgIcon'; export default ImageLoupe;
packages/material-ui-icons/src/SimCard.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SimCard = props => <SvgIcon {...props}> <path d="M19.99 4c0-1.1-.89-2-1.99-2h-8L4 8v12c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM9 19H7v-2h2v2zm8 0h-2v-2h2v2zm-8-4H7v-4h2v4zm4 4h-2v-4h2v4zm0-6h-2v-2h2v2zm4 2h-2v-4h2v4z" /> </SvgIcon>; SimCard = pure(SimCard); SimCard.muiName = 'SvgIcon'; export default SimCard;
src/components/Menu/Sale.js
shierby/storehome
import React from 'react'; class Sale extends React.Component { render() { return ( <div className="container-fluid catalog_page"> <div className="container"> <h1>Sale Page</h1> </div> </div> ) } } export default Sale;
src/svg-icons/av/slow-motion-video.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSlowMotionVideo = (props) => ( <SvgIcon {...props}> <path d="M13.05 9.79L10 7.5v9l3.05-2.29L16 12zm0 0L10 7.5v9l3.05-2.29L16 12zm0 0L10 7.5v9l3.05-2.29L16 12zM11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zm1.61 6.74C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43zM22 12c0 5.16-3.92 9.42-8.95 9.95v-2.02C16.97 19.41 20 16.05 20 12s-3.03-7.41-6.95-7.93V2.05C18.08 2.58 22 6.84 22 12z"/> </SvgIcon> ); AvSlowMotionVideo = pure(AvSlowMotionVideo); AvSlowMotionVideo.displayName = 'AvSlowMotionVideo'; AvSlowMotionVideo.muiName = 'SvgIcon'; export default AvSlowMotionVideo;
frontend/src/components/NavigationBar/index.js
andres81/auth-service
import React from 'react' import {connect} from 'react-redux' import {logout} from '../../actions/authActions' import UserDropDown from './UserDropDown' class NavigationBar extends React.Component { render() { const {user, logout} = this.props; return ( <header className="main-header layout-boxed"> <a href="index2.html" className="logo"> <span className="logo-mini"><b>A</b>LT</span> <span className="logo-lg"><b>Admin</b>LTE</span> </a> <nav className="navbar navbar-static-top"> <a className="sidebar-toggle" data-toggle="offcanvas" role="button"> <span className="sr-only">Toggle navigation</span> </a> <div className="navbar-custom-menu"> <ul className="nav navbar-nav"> <li className="dropdown messages-menu"> <a className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-envelope-o"></i> <span className="label label-success">4</span> </a> <ul className="dropdown-menu"> <li className="header">You have 4 messages</li> <li> <ul className="menu"> <li> <a> <div className="pull-left"> <img src={require('../../img/user2-160x160.jpg')} className="img-circle" alt="user pic" /> </div> <h4> Support Team <small><i className="fa fa-clock-o"></i> 5 mins</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a> <div className="pull-left"> <img src="dist/img/user3-128x128.jpg" className="img-circle" alt="user pic" /> </div> <h4> AdminLTE Design Team <small><i className="fa fa-clock-o"></i> 2 hours</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a> <div className="pull-left"> <img src="dist/img/user4-128x128.jpg" className="img-circle" alt="user pic" /> </div> <h4> Developers <small><i className="fa fa-clock-o"></i> Today</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a> <div className="pull-left"> <img src="dist/img/user3-128x128.jpg" className="img-circle" alt="user pic" /> </div> <h4> Sales Department <small><i className="fa fa-clock-o"></i> Yesterday</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a> <div className="pull-left"> <img src="dist/img/user4-128x128.jpg" className="img-circle" alt="user pic" /> </div> <h4> Reviewers <small><i className="fa fa-clock-o"></i> 2 days</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> </ul> </li> <li className="footer"><a>See All Messages</a></li> </ul> </li> <li className="dropdown notifications-menu"> <a className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-bell-o"></i> <span className="label label-warning">10</span> </a> <ul className="dropdown-menu"> <li className="header">You have 10 notifications</li> <li> <ul className="menu"> <li> <a> <i className="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> <li> <a> <i className="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems </a> </li> <li> <a> <i className="fa fa-users text-red"></i> 5 new members joined </a> </li> <li> <a> <i className="fa fa-shopping-cart text-green"></i> 25 sales made </a> </li> <li> <a> <i className="fa fa-user text-red"></i> You changed your username </a> </li> </ul> </li> <li className="footer"><a>View all</a></li> </ul> </li> <li className="dropdown tasks-menu"> <a className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-flag-o"></i> <span className="label label-danger">9</span> </a> <ul className="dropdown-menu"> <li className="header">You have 9 tasks</li> <li> <ul className="menu"> <li> <a> <h3> Design some buttons <small className="pull-right">20%</small> </h3> <div className="progress xs"> <div className="progress-bar progress-bar-aqua" style={{width: "20%"}} role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span className="sr-only">20% Complete</span> </div> </div> </a> </li> <li> <a> <h3> Create a nice theme <small className="pull-right">40%</small> </h3> <div className="progress xs"> <div className="progress-bar progress-bar-green" style={{width: "40%"}} role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span className="sr-only">40% Complete</span> </div> </div> </a> </li> <li> <a> <h3> Some task I need to do <small className="pull-right">60%</small> </h3> <div className="progress xs"> <div className="progress-bar progress-bar-red" style={{width: "60%"}} role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span className="sr-only">60% Complete</span> </div> </div> </a> </li> <li> <a> <h3> Make beautiful transitions <small className="pull-right">80%</small> </h3> <div className="progress xs"> <div className="progress-bar progress-bar-yellow" style={{width: "80%"}} role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span className="sr-only">80% Complete</span> </div> </div> </a> </li> </ul> </li> <li className="footer"> <a>View all tasks</a> </li> </ul> </li> <li className="dropdown user user-menu"> <a className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-user" aria-hidden="true"></i> <span className="hidden-xs">{user.fullName}</span> </a> <UserDropDown user={user} logout={logout}/> </li> </ul> </div> </nav> </header> ) } } const mapStateToProps = (state) => { return { isAuthenticated: state.auth.isAuthenticated }; } NavigationBar.contextTypes = { router: React.PropTypes.object.isRequired } export default connect(mapStateToProps, {logout})(NavigationBar);
client/web/views/About/About.js
bigwisu/josspoll
import React, { Component } from 'react'; class About extends Component { render() { return ( <div> <h1>About</h1> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ) } } export default About;
src/components/jobFilter/index.js
nickfranciosi/terminal-frontend
import React, { Component } from 'react'; import Select from 'react-select'; import axios from 'axios'; import 'react-select/dist/react-select.css'; import JobList from '../jobList'; import styles from './style.module.css'; export default class JobFilter extends Component { constructor(props) { super(props); this.state = { jobs: [], filteredJobs: [], placeValue: "all", companyValue: "all", }; this.handleFilter = this.handleFilter.bind(this); this.resetFilter = this.resetFilter.bind(this); this.getLocationOptions = this.getLocationOptions.bind(this); this.getTeamOptions = this.getTeamOptions.bind(this); this.fetchJobs = this.fetchJobs.bind(this); } componentDidMount() { this.fetchJobs(); } fetchJobs() { axios.get('https://api.lever.co/v0/postings/terminal?mode=json') .then(response => { const formattedJobs = response.data.filter(this.filterOutTerminalJobs).map(this.formatJob); this.setState({ jobs: formattedJobs, filteredJobs: formattedJobs, }) }) } filterOutTerminalJobs(item) { return item.categories.team !== "Terminal"; } formatJob(job){ return { title: job.text, place: job.categories.location, company: job.categories.team, link: job.hostedUrl, } } handleFilter(item, key) { const otherFilter = key === "place" ? "company" : "place"; if(item.value === "all") { this.resetFilter(key); }else { this.setState({ filteredJobs: this.state.jobs.filter(job => job[key] === item.value), [`${key}Value`]: item.value, [`${otherFilter}Value`]: "all", }) } } resetFilter() { this.setState({ filteredJobs: this.state.jobs, placeValue: "all", companyValue: "all", }); } renderOption(item) { return { value: item, label: item, } } onlyUnique(value, index, self) { return self.indexOf(value) === index; } getLocationOptions() { const locations = this.state.jobs .map(job => job.place) .filter(this.onlyUnique) .map(this.renderOption); return [{ value: "all", label: "all locations"}, ...locations]; } getTeamOptions() { const locations = this.state.jobs .map(job => job.company) .filter(this.onlyUnique) .map(this.renderOption); return [{ value: "all", label: "all teams"}, ...locations]; } render () { return ( <div> <div className={styles.selectContainer}> <Select name="form-field-location" options={this.getLocationOptions()} value={this.state.placeValue} onChange={(e) => this.handleFilter(e, 'place')} searchable={false} clearable={false} className={styles.select} /> <Select name="form-field-team" options={this.getTeamOptions()} value={this.state.companyValue} onChange={(e) => this.handleFilter(e, 'company')} searchable={false} clearable={false} className={styles.select} /> </div> <div> <JobList jobs={this.state.filteredJobs}/> </div> </div> ); } }
docs/src/app/components/pages/components/IconMenu/Page.js
pancho111203/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconMenuReadmeText from './README'; import IconMenuExampleSimple from './ExampleSimple'; import iconMenuExampleSimpleCode from '!raw!./ExampleSimple'; import IconMenuExampleControlled from './ExampleControlled'; import iconMenuExampleControlledCode from '!raw!./ExampleControlled'; import IconMenuExampleScrollable from './ExampleScrollable'; import iconMenuExampleScrollableCode from '!raw!./ExampleScrollable'; import IconMenuExampleNested from './ExampleNested'; import iconMenuExampleNestedCode from '!raw!./ExampleNested'; import iconMenuCode from '!raw!material-ui/IconMenu/IconMenu'; const IconMenusPage = () => ( <div> <Title render={(previousTitle) => `Icon Menu - ${previousTitle}`} /> <MarkdownElement text={iconMenuReadmeText} /> <CodeExample title="Icon Menu positioning" code={iconMenuExampleSimpleCode} > <IconMenuExampleSimple /> </CodeExample> <CodeExample title="Controlled Icon Menus" code={iconMenuExampleControlledCode} > <IconMenuExampleControlled /> </CodeExample> <CodeExample title="Scrollable Icon Menu" code={iconMenuExampleScrollableCode} > <IconMenuExampleScrollable /> </CodeExample> <CodeExample title="Nested Icon Menus" code={iconMenuExampleNestedCode} > <IconMenuExampleNested /> </CodeExample> <PropTypeDescription code={iconMenuCode} /> </div> ); export default IconMenusPage;
styleguide/Wrapper.js
mikebarkmin/gestyled
import React from 'react'; import ThemeProvider from '../src/components/ThemeProvider'; const Wrapper = props => <ThemeProvider> {props.children} </ThemeProvider>; export default Wrapper;
src/encoded/static/components/collection.js
T2DREAM/t2dream-portal
import React from 'react'; import PropTypes from 'prop-types'; import { Panel, PanelHeading, PanelBody } from '../libs/bootstrap/panel'; import * as globals from './globals'; import DataColors from './datacolors'; // Maximum number of facet charts to display. const MAX_FACET_CHARTS = 3; // Initialize a list of colors to use in the chart. const collectionColors = new DataColors(); // Get a list of colors to use for the lab chart const collectionColorList = collectionColors.colorList(); class FacetChart extends React.Component { constructor() { super(); this.chartInstance = null; } componentDidUpdate() { // This method might be called because we're drawing the chart for the first time (in // that case this is an update because we already rendered an empty canvas before the // chart.js module was loaded) or because we have new data to render into an existing // chart. const { chartId, facet, baseSearchUri } = this.props; const Chart = this.props.chartModule; // Before rendering anything into the chart, check whether we have a the chart.js module // loaded yet. If it hasn't loaded yet, we have nothing to do yet. Also see if we have any // values to render at all, and skip this if not. if (Chart && this.values.length) { // In case we don't have enough colors defined for all the values, make an array of // colors with enough entries to fill out the labels and values. const colors = this.labels.map((label, i) => collectionColorList[i % collectionColorList.length]); if (this.chartInstance) { // We've already created a chart instance, so just update it with new data. this.chartInstance.data.datasets[0].data = this.values; this.chartInstance.data.datasets[0].backgroundColor = colors; this.chartInstance.data.labels = this.labels; this.chartInstance.update(); document.getElementById(`${chartId}-legend`).innerHTML = this.chartInstance.generateLegend(); } else { // We've not yet created a chart instance, so make a new one with the initial set // of data. First extract the data in a way suitable for the chart API. const canvas = document.getElementById(chartId); const ctx = canvas.getContext('2d'); // Create and render the chart. this.chartInstance = new Chart(ctx, { type: 'doughnut', data: { labels: this.labels, datasets: [{ data: this.values, backgroundColor: colors, }], }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, animation: { duration: 200, }, legendCallback: (chart) => { const chartData = chart.data.datasets[0].data; const chartColors = chart.data.datasets[0].backgroundColor; const chartLabels = chart.data.labels; const text = []; text.push('<ul>'); for (let i = 0; i < chartData.length; i += 1) { const searchUri = `${baseSearchUri}&${facet.field}=${encodeURIComponent(chartLabels[i]).replace(/%20/g, '+')}`; if (chartData[i]) { text.push(`<li><a href="${searchUri}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${chartColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${chartLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: (e) => { // React to clicks on pie sections const activePoints = this.chartInstance.getElementAtEvent(e); if (activePoints[0]) { const clickedElementIndex = activePoints[0]._index; const chartLabels = this.chartInstance.data.labels; const searchUri = `${baseSearchUri}&${facet.field}=${encodeURIComponent(chartLabels[clickedElementIndex]).replace(/%20/g, '+')}`; this.context.navigate(searchUri); } }, }, }); // Create and render the legend by drawibg it into the <div> we set up for that // purposee. document.getElementById(`${chartId}-legend`).innerHTML = this.chartInstance.generateLegend(); } } } render() { const { chartId, facet } = this.props; // Extract the arrays of labels from the facet keys, and the arrays of corresponding counts // from the facet doc_counts. Only use non-zero facet terms in the charts. IF we have no // usable data, both these arrays have no entries. componentDidMount assumes these arrays // have been populated. this.values = []; this.labels = []; facet.terms.forEach((term) => { if (term.doc_count) { this.values.push(term.doc_count); this.labels.push(term.key); } }); // Check whether we have usable values in one array or the other we just collected (we'll // just use `this;values` here) to see if we need to render a chart or not. if (this.values.length) { return ( <div className="collection-charts__chart"> <div className="collection-charts__title">{facet.title}</div> <div className="collection-charts__canvas"> <canvas id={chartId} /> </div> <div id={`${chartId}-legend`} className="collection-charts__legend" /> </div> ); } return null; } } FacetChart.propTypes = { facet: PropTypes.object.isRequired, // Facet data to display in the chart chartId: PropTypes.string.isRequired, // HTML element ID to assign to the chart <canvas> chartModule: PropTypes.func, // chart.js NPM module as loaded by webpack baseSearchUri: PropTypes.string.isRequired, // Base URL of clicked chart elements }; FacetChart.defaultProps = { chartModule: null, }; FacetChart.contextTypes = { navigate: PropTypes.func, }; class Collection extends React.Component { constructor() { super(); // Initialize component React state. this.state = { chartModule: null, // Refers to chart.js npm module facetCharts: [], // Tracks all chart instances }; } componentDidMount() { // Have webpack load the chart.js npm module. Once the module's ready, set the chartModule // state so we can readraw the charts with the chart module in place. require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); this.setState({ chartModule: Chart }); }); } render() { const { context } = this.props; const { facets } = context; // Collect the three facets that will be included in the charts. This comprises the first // MAX_FACET_CHARTS facets, not counting any facets with "type" for the field which we never // chart, nor audit facets. const chartFacets = facets ? facets.filter(facet => facet.field !== 'type' && facet.field.substring(0, 6) !== 'audit.').slice(0, MAX_FACET_CHARTS) : []; return ( <div className={globals.itemClass(context, 'view-item')}> <header className="row"> <div className="col-sm-12"> <h2>{context.title}</h2> {context.schema_description ? <h4 className="collection-sub-header">{context.schema_description}</h4> : null} </div> </header> <Panel> <PanelHeading addClasses="collection-heading"> <h4>{context.total} total {context.title}</h4> <div className="collection-heading__controls"> {(context.actions || []).map(action => <a key={action.name} href={action.href} className="btn btn-info"> {action.title} </a> )} </div> </PanelHeading> <PanelBody> {chartFacets.length ? <div className="collection-charts"> {chartFacets.map(facet => <FacetChart key={facet.field} facet={facet} chartId={`${facet.field}-chart`} chartModule={this.state.chartModule} baseSearchUri={context.clear_filters} /> )} </div> : <p className="collection-no-chart">No facets defined in the &ldquo;{context.title}&rdquo; schema, or no data available.</p> } </PanelBody> </Panel> </div> ); } } Collection.propTypes = { context: PropTypes.object.isRequired, }; globals.contentViews.register(Collection, 'Collection');
app/components/channel/channelController.js
ongmin/cylinder-app
'use strict' import React from 'react' import Playlist from './playlist' import SearchBar from './searchBar' var ChannelController = React.createClass({ onChange: function () { }, render: function () { return ( <div> <div className='channelsContainer'> <h1>Channel</h1> <div id='container-main'> <div> <h1>Playlist</h1> <SearchBar onChange={this.onChange}/> </div> <Playlist /> </div> </div> </div> ) } }) module.exports = ChannelController
src/svg-icons/action/polymer.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPolymer = (props) => ( <SvgIcon {...props}> <path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z"/> </SvgIcon> ); ActionPolymer = pure(ActionPolymer); ActionPolymer.displayName = 'ActionPolymer'; ActionPolymer.muiName = 'SvgIcon'; export default ActionPolymer;
admin/client/App/index.js
ratecity/keystone
/** * This is the main entry file, which we compile the main JS bundle from. It * only contains the client side routing setup. */ // Needed for ES6 generators (redux-saga) to work import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { Provider } from 'react-redux'; import { syncHistoryWithStore } from 'react-router-redux'; import App from './App'; import Home from './screens/Home'; import Item from './screens/Item'; import List from './screens/List'; import store from './store'; // Sync the browser history to the Redux store const history = syncHistoryWithStore(browserHistory, store); // Initialise Keystone.User list import { listsByKey } from '../utils/lists'; Keystone.User = listsByKey[Keystone.userList]; ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path={Keystone.adminPath} component={App}> <IndexRoute component={Home} /> <Route path=":listId" component={List} /> <Route path=":listId/:itemId" component={Item} /> </Route> </Router> </Provider>, document.getElementById('react-root') );
src/packages/@ncigdc/components/Legacy/Nav.js
NCI-GDC/portal-ui
// @flow // Vendor import React from 'react'; import { Link } from 'react-router'; import AnnotationIcon from 'react-icons/lib/fa/align-left'; import FileIcon from 'react-icons/lib/fa/file-text'; import Color from 'color'; import { css } from 'glamor'; import ShoppingCartIcon from '@ncigdc/theme/icons/ShoppingCart'; // Custom import { Row } from '@ncigdc/uikit/Flex'; import { withTheme } from '@ncigdc/theme'; import { center } from '@ncigdc/theme/mixins'; import CartLink from '@ncigdc/components/Links/CartLink'; import LoginButton from '@ncigdc/components/LoginButton'; /*----------------------------------------------------------------------------*/ const styles = { nav: theme => ({ backgroundColor: theme.greyScale2, height: '36px', justifyContent: 'center', zIndex: 2000, }), link: theme => css({ color: 'white !important', padding: '10px 13px', textDecoration: 'none !important', transition: 'background-color 0.2s ease', ':hover': { backgroundColor: Color(theme.greyScale2) .darken(0.5) .rgbString(), }, ...center, }), faded: { color: 'rgb(191, 191, 191)', }, marginLeft: { marginLeft: '0.7rem', }, fileLength: { marginLeft: '0.5rem', padding: '0.4rem 0.6rem', fontSize: '1rem', backgroundColor: '#5b5151', }, }; const Nav = ({ theme }) => ( <Row style={styles.nav(theme)}> <Row flex="1" /> <Row flex="1"> <Link to="/files" className={`${styles.link(theme)}`}> <FileIcon style={styles.faded} /> <span style={styles.marginLeft}>Files</span> </Link> <Link to="/annotations" className={`${styles.link(theme)}`}> <AnnotationIcon style={styles.faded} /> <span style={styles.marginLeft}>Annotations</span> </Link> </Row> <Row> <LoginButton /> <CartLink className={`${styles.link(theme)}`}> {count => ( <span> <ShoppingCartIcon style={styles.faded} /> <span style={{ marginLeft: '0.7rem' }}>Cart</span> <span style={styles.fileLength}>{count}</span> </span> )} </CartLink> </Row> </Row> ); /*----------------------------------------------------------------------------*/ export default withTheme(Nav);
app/packs/src/components/ElementsTableSettings.js
ComPlat/chemotion_ELN
import React from 'react'; import Immutable from 'immutable'; import {Popover, Button, FormGroup, Checkbox, OverlayTrigger} from 'react-bootstrap'; import _ from 'lodash'; import TabLayoutContainer from './TabLayoutContainer'; import UserActions from './actions/UserActions'; import UIActions from './actions/UIActions'; import UIStore from './stores/UIStore'; import UserStore from './stores/UserStore'; export default class ElementsTableSettings extends React.Component { constructor(props) { super(props); this.state = { visible: props.visible, hidden: props.hidden, currentType: '', showSampleExternalName: false, tableSchemePreviews: true } this.handleOnExit = this.handleOnExit.bind(this); this.handleToggleSampleExt = this.handleToggleSampleExt.bind(this); this.handleToggleScheme = this.handleToggleScheme.bind(this); this.onChangeUser = this.onChangeUser.bind(this); this.onChangeUI = this.onChangeUI.bind(this); } componentDidMount() { UserStore.listen(this.onChangeUser); UIStore.listen(this.onChangeUI); } componentWillUnmount() { UserStore.unlisten(this.onChangeUser); UIStore.unlisten(this.onChangeUI); } onChangeUI(state) { const tableSchemePreviews = state.showPreviews; if (this.state.tableSchemePreviews != tableSchemePreviews) { this.setState({ tableSchemePreviews }); } } onChangeUser(state) { let { currentType, showSampleExternalName } = this.state; let showExt = showSampleExternalName; if (state.profile && state.profile.show_external_name) { showExt = state.profile.show_external_name; } if (currentType != state.currentType || showSampleExternalName != showExt) { this.setState({ currentType: state.currentType, showSampleExternalName: showExt }) } } handleOnExit() { this.updateLayout(); if (this.state.currentType == "sample" || this.state.currentType == "reaction") { const show_previews = UIStore.getState().showPreviews; const cur_previews = this.state.tableSchemePreviews; if (cur_previews != show_previews) { UIActions.toggleShowPreviews(cur_previews); } } const storeExt = UserStore.getState().profile.show_external_name; if (this.state.showSampleExternalName != storeExt) { UserActions.updateUserProfile( { show_external_name: this.state.showSampleExternalName } ); } } // eslint-disable-next-line camelcase UNSAFE_componentWillReceiveProps(nextProps) { this.setState({ visible: nextProps.visible, hidden: nextProps.hidden }); } handleToggleScheme() { const { tableSchemePreviews } = this.state; this.setState({ tableSchemePreviews: !tableSchemePreviews }); } handleToggleSampleExt() { const { showSampleExternalName } = this.state; this.setState({ showSampleExternalName: !showSampleExternalName }); } updateLayout() { const { visible, hidden } = this.layout.state; const layout = {}; visible.forEach((value, index) => { layout[value] = (index + 1); }); hidden.forEach((value, index) => { if (value !== 'hidden') layout[value] = (- index - 1) }); const userProfile = UserStore.getState().profile; _.set(userProfile, 'data.layout', layout); UserActions.updateUserProfile(userProfile); } render() { const { visible, hidden, currentType, tableSchemePreviews, showSampleExternalName } = this.state; const wd = 35 + ((visible && visible.size * 50) || 0) + ((hidden && hidden.size * 50) || 0); let sampleSettings = (<span />); if (currentType == "sample" || currentType == "reaction") { sampleSettings = ( <div> <h3 className="popover-title">Settings</h3> <div className="popover-content"> <FormGroup> <Checkbox onChange={this.handleToggleScheme} checked={tableSchemePreviews} > Show schemes images </Checkbox> </FormGroup> <FormGroup> <Checkbox onChange={this.handleToggleSampleExt} checked={showSampleExternalName} > Show sample external name on title </Checkbox> </FormGroup> </div> </div> ) } const popoverSettings = ( <Popover className="collection-overlay" id="popover-layout" style={{ maxWidth: 'none', width: `${wd}px` }} > <div> <h3 className="popover-title">Table Layout</h3> <div className="popover-content"> <TabLayoutContainer visible={visible} hidden={hidden} ref={(n) => { this.layout = n; }} /> </div> </div> {sampleSettings} </Popover> ) return ( <OverlayTrigger trigger="click" placement="left" overlay={popoverSettings} rootClose onExit={this.handleOnExit} > <Button bsSize="xsmall" style={{ margin: '10px 10px 10px 0', float: 'right' }} > <i className="fa fa-sliders" /> </Button> </OverlayTrigger> ); } }
node_modules/react-router/modules/Lifecycle.js
ibjohansen/acando-react-boilerplate-extended
import React from 'react' import invariant from 'invariant' const { object } = React.PropTypes /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ const Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount() { invariant( this.routerWillLeave, 'The Lifecycle mixin requires you to define a routerWillLeave method' ) const route = this.props.route || this.context.route invariant( route, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin' ) this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute( route, this.routerWillLeave ) }, componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute() } } export default Lifecycle
index.ios.js
rldona/taskfire
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class taskfire extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('taskfire', () => taskfire);
app/client/src/scenes/ManageCampaignProfileEdit/ManageCampaignProfileEdit.js
uprisecampaigns/uprise-app
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { compose, graphql } from 'react-apollo'; import { connect } from 'react-redux'; import camelCase from 'camelcase'; import FontIcon from 'material-ui/FontIcon'; import CampaignProfileForm from 'components/CampaignProfileForm'; import Link from 'components/Link'; import formWrapper from 'lib/formWrapper'; import { validateString, validateWebsiteUrl } from 'lib/validateComponentForms'; import CampaignQuery from 'schemas/queries/CampaignQuery.graphql'; import EditCampaignMutation from 'schemas/mutations/EditCampaignMutation.graphql'; import s from 'styles/Organize.scss'; const WrappedCampaignProfileForm = formWrapper(CampaignProfileForm); class ManageCampaignProfileEdit extends Component { static propTypes = { campaign: PropTypes.object, editCampaignMutation: PropTypes.func.isRequired, // eslint-disable-next-line react/no-unused-prop-types graphqlLoading: PropTypes.bool.isRequired, // eslint-disable-next-line react/no-unused-prop-types campaignSlug: PropTypes.string.isRequired, }; static defaultProps = { campaign: undefined, }; constructor(props) { super(props); const initialState = { formData: { title: '', websiteUrl: '', profileSubheader: '', description: '', profileImageUrl: '', }, }; this.state = Object.assign({}, initialState); } componentWillMount() { this.handleCampaignProps(this.props); } componentWillReceiveProps(nextProps) { this.handleCampaignProps(nextProps); } handleCampaignProps = (nextProps) => { if (nextProps.campaign && !nextProps.graphqlLoading) { // Just camel-casing property keys and checking for null/undefined const campaign = Object.assign( ...Object.keys(nextProps.campaign).map((k) => { if (nextProps.campaign[k] !== null) { return { [camelCase(k)]: nextProps.campaign[k] }; } return undefined; }), ); Object.keys(campaign).forEach((k) => { if (!Object.keys(this.state.formData).includes(camelCase(k))) { delete campaign[k]; } }); this.setState((prevState) => ({ formData: Object.assign({}, prevState.formData, campaign), })); } }; defaultErrorText = { titleErrorText: null, websiteUrlErrorText: null, descriptionErrorText: null, }; formSubmit = async (data) => { // A little hackish to avoid an annoying rerender with previous form data // If I could figure out how to avoid keeping state here // w/ the componentWillReceiveProps/apollo/graphql then // I might not need this this.setState({ formData: Object.assign({}, data), }); const formData = Object.assign({}, data); formData.id = this.props.campaign.id; try { await this.props.editCampaignMutation({ variables: { data: formData, }, // TODO: decide between refetch and update refetchQueries: ['CampaignQuery', 'CampaignsQuery', 'MyCampaignsQuery'], }); return { success: true, message: 'Changes Saved' }; } catch (e) { console.error(e); return { success: false, message: e.message }; } }; render() { if (this.props.campaign) { const { campaign } = this.props; const { formData } = this.state; const { formSubmit, defaultErrorText } = this; const validators = [ (component) => { validateString(component, 'title', 'titleErrorText', 'Campaign Name is Required'); }, (component) => { validateWebsiteUrl(component); }, ]; return ( <div className={s.outerContainer}> <div className={s.innerContainer}> <div className={s.sectionHeaderContainer}> <div className={s.pageHeader}>{campaign.title}</div> {campaign.profile_subheader && <div className={s.sectionSubheader}>{campaign.profile_subheader}</div>} </div> <div className={s.crumbs}> <div className={s.navHeader}> <Link to={`/organize/${campaign.slug}`}>{campaign.title}</Link> <FontIcon className={['material-icons', 'arrowRight'].join(' ')}>keyboard_arrow_right</FontIcon> Campaign Profile </div> </div> <WrappedCampaignProfileForm initialState={formData} initialErrors={defaultErrorText} validators={validators} submit={formSubmit} campaignId={campaign.id} submitText="Save Changes" /> </div> </div> ); } return null; } } export default compose( connect(), graphql(CampaignQuery, { options: (ownProps) => ({ variables: { search: { slug: ownProps.campaignSlug, }, }, fetchPolicy: 'cache-and-network', }), props: ({ data }) => ({ campaign: data.campaign, graphqlLoading: data.loading, }), }), graphql(EditCampaignMutation, { name: 'editCampaignMutation' }), )(ManageCampaignProfileEdit);
fields/types/url/UrlField.js
stosorio/keystone
import React from 'react'; import Field from '../Field'; import { Button, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'URLField', openValue () { var href = this.props.value; if (!href) return; if (!/^(mailto\:)|(\w+\:\/\/)/.test(href)) { href = 'http://' + href; } window.open(href); }, renderLink () { if (!this.props.value) return null; return ( <Button type="link" onClick={this.openValue} className="keystone-relational-button" title={'Open ' + this.props.value + ' in a new tab'}> <span className="octicon octicon-link" /> </Button> ); }, wrapField () { return ( <div style={{ position: 'relative' }}> {this.renderField()} {this.renderLink()} </div> ); }, renderValue () { return <FormInput noedit onClick={this.openValue}>{this.props.value}</FormInput>; } });
src/app/modals/trackStats.js
nazar/sound-charts-react-spa
import React from 'react'; import TrackStatsAndCharts from 'components/trackStatsAndCharts'; export default React.createClass({ componentDidMount() { $( this.getDOMNode() ).modal( { keyboard: false, backdrop: false } ); }, componentDidUpdate() { console.log('componentDidUpdate' ); }, render() { return ( <div className="modal fade track-stats"> <div className="modal-dialog modal-lg"> <div className="modal-content"> <div className="modal-header clearfix"> <button type="button" className="close" aria-label="Close" onClick={this.props.closePortal}> <i className="fa fa-times-circle" aria-hidden="true"></i> </button> </div> <div className="modal-body"> <TrackStatsAndCharts track={this.props.track} /> </div> </div> </div> </div> ); } });
app/javascript/mastodon/features/ui/components/modal_loading.js
Kirishima21/mastodon
import React from 'react'; import LoadingIndicator from '../../../components/loading_indicator'; // Keep the markup in sync with <BundleModalError /> // (make sure they have the same dimensions) const ModalLoading = () => ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <LoadingIndicator /> </div> <div className='error-modal__footer'> <div> <button className='error-modal__nav onboarding-modal__skip' /> </div> </div> </div> ); export default ModalLoading;
src/svg-icons/action/https.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHttps = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </SvgIcon> ); ActionHttps = pure(ActionHttps); ActionHttps.displayName = 'ActionHttps'; ActionHttps.muiName = 'SvgIcon'; export default ActionHttps;
app/javascript/mastodon/features/ui/components/columns_area.js
abcang/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import TabsBar, { links, getIndex, getLink } from './tabs_bar'; import { Link } from 'react-router-dom'; import { disableSwiping } from 'mastodon/initial_state'; import BundleContainer from '../containers/bundle_container'; import ColumnLoading from './column_loading'; import DrawerLoading from './drawer_loading'; import BundleColumnError from './bundle_column_error'; import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, BookmarkedStatuses, ListTimeline, Directory, } from '../../ui/util/async-components'; import Icon from 'mastodon/components/icon'; import ComposePanel from './compose_panel'; import NavigationPanel from './navigation_panel'; import { supportsPassiveEvents } from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'REMOTE': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'DIRECT': DirectTimeline, 'FAVOURITES': FavouritedStatuses, 'BOOKMARKS': BookmarkedStatuses, 'LIST': ListTimeline, 'DIRECTORY': Directory, }; const messages = defineMessages({ publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, }); const shouldHideFAB = path => path.match(/^\/statuses\/|^\/@[^/]+\/\d+|^\/publish|^\/search|^\/getting-started|^\/start/); export default @(component => injectIntl(component, { withRef: true })) class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, columns: ImmutablePropTypes.list.isRequired, isModalOpen: PropTypes.bool.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; // Corresponds to (max-width: 600px + (285px * 1) + (10px * 1)) in SCSS mediaQuery = 'matchMedia' in window && window.matchMedia('(max-width: 895px)'); state = { shouldAnimate: false, renderComposePanel: !(this.mediaQuery && this.mediaQuery.matches), } componentWillReceiveProps() { if (typeof this.pendingIndex !== 'number' && this.lastIndex !== getIndex(this.context.router.history.location.pathname)) { this.setState({ shouldAnimate: false }); } } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false); } if (this.mediaQuery) { if (this.mediaQuery.addEventListener) { this.mediaQuery.addEventListener('change', this.handleLayoutChange); } else { this.mediaQuery.addListener(this.handleLayoutChange); } this.setState({ renderComposePanel: !this.mediaQuery.matches }); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl'); this.setState({ shouldAnimate: true }); } componentWillUpdate(nextProps) { if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } componentDidUpdate(prevProps) { if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false); } const newIndex = getIndex(this.context.router.history.location.pathname); if (this.lastIndex !== newIndex) { this.lastIndex = newIndex; this.setState({ shouldAnimate: true }); } } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } if (this.mediaQuery) { if (this.mediaQuery.removeEventListener) { this.mediaQuery.removeEventListener('change', this.handleLayoutChange); } else { this.mediaQuery.removeListener(this.handleLayouteChange); } } } handleChildrenContentChange() { if (!this.props.singleColumn) { const modifier = this.isRtlLayout ? -1 : 1; this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier); } } handleLayoutChange = (e) => { this.setState({ renderComposePanel: !e.matches }); } handleSwipe = (index) => { this.pendingIndex = index; const nextLinkTranslationId = links[index].props['data-preview-title-id']; const currentLinkSelector = '.tabs-bar__link.active'; const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`; // HACK: Remove the active class from the current link and set it to the next one // React-router does this for us, but too late, feeling laggy. document.querySelector(currentLinkSelector).classList.remove('active'); document.querySelector(nextLinkSelector).classList.add('active'); if (!this.state.shouldAnimate && typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleAnimationEnd = () => { if (typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = (node) => { this.node = node; } renderView = (link, index) => { const columnIndex = getIndex(this.context.router.history.location.pathname); const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] }); const icon = link.props['data-preview-icon']; const view = (index === columnIndex) ? React.cloneElement(this.props.children) : <ColumnLoading title={title} icon={icon} />; return ( <div className='columns-area columns-area--mobile' key={index}> {view} </div> ); } renderLoading = columnId => () => { return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { columns, children, singleColumn, isModalOpen, intl } = this.props; const { shouldAnimate, renderComposePanel } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); if (singleColumn) { const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/publish' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><Icon id='pencil' /></Link>; const content = columnIndex !== -1 ? ( <ReactSwipeableViews key='content' hysteresis={0.2} threshold={15} index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }} disabled={disableSwiping}> {links.map(this.renderView)} </ReactSwipeableViews> ) : ( <div key='content' className='columns-area columns-area--mobile'>{children}</div> ); return ( <div className='columns-area__panels'> <div className='columns-area__panels__pane columns-area__panels__pane--compositional'> <div className='columns-area__panels__pane__inner'> {renderComposePanel && <ComposePanel />} </div> </div> <div className='columns-area__panels__main'> <TabsBar key='tabs' /> {content} </div> <div className='columns-area__panels__pane columns-area__panels__pane--start columns-area__panels__pane--navigational'> <div className='columns-area__panels__pane__inner'> <NavigationPanel /> </div> </div> {floatingActionButton} </div> ); } return ( <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}> {columns.map(column => { const params = column.get('params', null) === null ? null : column.get('params').toJS(); const other = params && params.other ? params.other : {}; return ( <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}> {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />} </BundleContainer> ); })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
src/views/SideNav.js
Huanzhang89/rss-feed-example
import React, { Component } from 'react'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom' import { fetchFeed, removeFeed, getSelectedFeed } from '../redux/actions'; const Nav = styled.div` flex: 1 1 0; border-right: 1px solid black; `; const Search = styled.form` min-height: 50px; width: 100%; display: flex; margin: 0; `; const Input = styled.input` width: 70%; margin: 10px; border-radius: 5px; padding: 5px; font-size: 12px; `; const Button = styled.input` width: 30px; margin: 10px; border-radius: 5px; padding: 0; background: #fff url(https://cdn4.iconfinder.com/data/icons/pictype-free-vector-icons/16/search-128.png) no-repeat; background-size: 25px 25px; `; const Feeds = styled.div` width: 100%; height: calc(100% - 50px); overflow-y: auto; `; const Feed = styled.div` width: 90%; overflow: hidden; display: flex; padding: 5px; border: 1px solid black; margin: 10px auto; background-color: ${props => props.active ? 'grey' : 'none'}; > div { margin-left: 20px; } > span { overflow: hidden; max-width: 240px; } ` class SideNav extends Component { constructor(props) { super(props); this.state = { url: '', feedData: this.props.rssFeeds.rssFeed || [], active: 0, }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({url: event.target.value}); } handleSubmit(event) { event.preventDefault(); this.props.fetchFeed(`https://api.rss2json.com/v1/api.json?rss_url=` + this.state.url); } renderFeeds(feeds) { return feeds && feeds.map((feedData, index) => { return <Feed key={index} active={index === this.state.active ? true : false} onClick={()=>this.setState({active: index})}> <Link to={{hash: '#' + index}} onClick={() => this.props.getSelectedFeed(feedData)}> {feedData.feed.url} </Link> <div key={index} onClick={() => {this.props.removeFeed(feedData)}}> x </div> </Feed> }) }; componentWillReceiveProps(nextProps) { this.setState((prevState, nextProps) => { return {feedData: nextProps.rssFeeds.rssFeed} }); } render() { return ( <Nav> <Search onSubmit={this.handleSubmit}> <Input type="text" value={this.state.url} onChange={this.handleChange}/> <Button type="submit" value=''/> </Search> <Feeds> {this.renderFeeds(this.state.feedData)} </Feeds> </Nav> ) } } export default connect(state => ({ rssFeeds: state.rssFeeds }), { fetchFeed, removeFeed, getSelectedFeed })(SideNav);
docs/app/Examples/elements/Image/Variations/ImageExampleSpaced.js
aabustamante/Semantic-UI-React
import React from 'react' import { Segment, Image } from 'semantic-ui-react' const src = '/assets/images/wireframe/image.png' const ImageExampleSpaced = () => ( <div> <Segment> <p> Te eum doming eirmod, nominati pertinacia <Image src={src} size='mini' spaced /> argumentum ad his. Ex eam alia facete scriptorem, est autem aliquip detraxit at. Usu ocurreret referrentur at, cu epicurei appellantur vix. Cum ea laoreet recteque electram, eos choro alterum definiebas in. Vim dolorum definiebas an. Mei ex natum rebum iisque. </p> </Segment> <p> <Image src={src} size='mini' spaced='right' />Audiam quaerendum eu sea, pro omittam definiebas ex. Te est latine definitiones. Quot wisi nulla ex duo. Vis sint solet expetenda ne, his te phaedrum referrentur consectetuer. Id vix fabulas oporteat, ei quo vide phaedrum, vim vivendum maiestatis in. </p> <p> Eu quo homero blandit intellegebat. Incorrupte consequuntur mei id. Mei ut facer dolores adolescens, no illum aperiri quo, usu odio brute at. Qui te porro electram, ea dico facete utroque quo. Populo quodsi te eam, wisi everti eos ex, eum elitr altera utamur at. Quodsi convenire mnesarchum eu per, quas minimum postulant per id.<Image src={src} size='mini' spaced='left' /> </p> </div> ) export default ImageExampleSpaced
views/containers/ServicesForm.js
gvaldambrini/madam
import React from 'react'; import { connect } from 'react-redux'; import { fetchServicesIfNeeded, saveServices } from '../redux/modules/services'; import { ServicesFormUi } from '../components'; // The services form container. const ServicesForm = React.createClass({ propTypes: { serviceList: React.PropTypes.array.isRequired, loaded: React.PropTypes.bool.isRequired }, getInitialState: function() { // The form local state is initialized from the one stored in redux // (if the related object already exists) and synced only on the save. let items = []; if (this.props.loaded) { items = this.prepareItems(this.props.serviceList); } return { items: items, errors: [], disabled: true }; }, componentDidMount: function() { if (!this.props.loaded) { this.props.dispatch(fetchServicesIfNeeded()); } }, componentWillReceiveProps: function(nextProps) { const items = this.prepareItems(nextProps.serviceList); this.setState({ items: items, disabled: true }); }, uuid4: function () { //// return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx let uuid = '', ii; for (ii = 0; ii < 32; ii += 1) { switch (ii) { case 8: case 20: uuid += '-'; uuid += (Math.random() * 16 | 0).toString(16); break; case 12: uuid += '-'; uuid += '4'; break; case 16: uuid += '-'; uuid += (Math.random() * 4 | 8).toString(16); break; default: uuid += (Math.random() * 16 | 0).toString(16); } } return uuid; }, addNewInput: function() { const items = this.state.items.slice(); const obj = this.newEmptyObj(); obj.id = this.uuid4(); items.push(obj); this.setState({ items: items }); }, removeInput: function(serviceId) { const items = this.state.items.slice(); let index; for (let i = 0; i < items.length; i++) { if (items[i].id === serviceId) { index = i; break; } } items.splice(index, 1); this.setState({ items: items }); }, newEmptyObj: function() { return { name: '' }; }, prepareItems: function(services) { const that = this; // We need an unique and stable id so that React can perform // the reconciliation to understand who is the child removed // or added. let items = []; if (services.length === 0) { const emptyItem = this.newEmptyObj(); emptyItem.id = this.uuid4(); items[0] = emptyItem; } else { items = services.map(function(item) { item.id = that.uuid4(); return item; }); } return items; }, submit: function() { const that = this; if (this.state.disabled) { this.setState({ disabled: false }); return; } const onError = function(xhr, _textStatus, _errorThrown) { that.setState({ errors: xhr.responseJSON.errors.map(item => item.msg) }); }; this.props.dispatch( saveServices(this.state.items) ).then(undefined, onError); }, inputChange: function(inputId, text) { const items = this.state.items.slice(); for (let i = 0; i < items.length; i++) { if (items[i].id === inputId) { if (items[i].name === text) { return; } items[i].name = text; break; } } this.setState({ items: items }); }, render: function() { return ( <ServicesFormUi {...this.props} loaded={this.props.loaded} errors={this.state.errors} items={this.state.items} addNewInput={this.addNewInput} removeInput={this.removeInput} disabled={this.state.disabled} inputChange={this.inputChange} submit={this.submit} /> ); } }); function mapStateToProps(state) { const services = state.services; return { serviceList: services.get('serviceList').toJS(), loaded: services.get('loaded') }; } export default connect(mapStateToProps)(ServicesForm);
src/client/js/components/NotFound.js
larbreapages/bookbuilder
import React from 'react'; export default NotFound = () => <div>Not found</div>;
src/routes/dashboard/components/quote.js
cuijiaxu/react-front
import React from 'react' import PropTypes from 'prop-types' import styles from './quote.less' function Quote ({ name, content, title, avatar }) { return ( <div className={styles.quote}> <div className={styles.inner}> {content} </div> <div className={styles.footer}> <div className={styles.description}> <p>-{name}-</p> <p>{title}</p> </div> <div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }} /> </div> </div> ) } Quote.propTypes = { name: PropTypes.string, content: PropTypes.string, title: PropTypes.string, avatar: PropTypes.string, } export default Quote
components/OfficerCard.js
uclaacm/website
import Image from 'next/image'; import React from 'react'; import styles from '../styles/components/OfficerCard.module.scss'; function Officer({ name, pronouns, position, /* eslint-disable-next-line no-unused-vars */ committee, // no officer card formats use committee yet major, year, img, alt, bio, size, style, }) { if (style && style.toLowerCase() === 'jedi') { return ( <div className={styles['mb-2']}> <div className={styles['jedi-profile-img']}> <Image src={img} alt={alt} width={250} height={250}/> </div> <div className={styles['jedi-card-body']}> <h2 className={styles['jedi-title']}> {name} <span className={styles['pronouns-jedi']}>{pronouns}</span> </h2> <p className={styles['my-tight']}>{bio}</p> </div> </div> ); } else if (size && size.toLowerCase() === 'compact') { return ( <div className={styles['officer-grid-row']}> <div className={styles['officer-grid-col']}> <Image className={styles['officer-image']} src={img} alt={alt} width={70} height={70} /> </div> <div className={`${styles['officer-grid-col']} ${styles['officer-info']}`}> <h3 className={styles['officer-title']}>{name}</h3> <p>{position}</p> </div> </div> ); } else { return ( <div className={`${styles['officer-card']} ${styles['grid-tablet-only-2']}`} > <div className={styles['officer-image-container']}> {/* eslint-disable-next-line @next/next/no-img-element */} <img src={img} alt={alt} style={{ maxWidth: '100%' }} /> </div> <div> <h3 className={styles.name}>{name}</h3> <h4 className={styles.pronouns}>{pronouns}</h4> <ul className="list-unstyled"> <li>{position}</li> <li>{major}</li> <li>Class of {year}</li> </ul> </div> </div> ); } } function Officers(props) { return ( // TODO: more flexible mobile views <> {props.officers.map((officer) => ( <Officer {...officer} size={props.size} style={props.style} key={props.officers.name} /> ))} </> ); } export default Officers;
src/common/components/Main.js
adamarthurryan/dubdiff
import React from 'react' import {connect} from 'react-redux' import {Segment, Grid, Form} from 'semantic-ui-react' import * as Actions from '../actions' import * as Selectors from '../selectors' import Header from './Header' import Footer from './Footer' import MainControls from './MainControls' const mapStateToProps = (state) => ({ input: state.input, safeInput: Selectors.safeInput(state) }) const mapDispatchToProps = dispatch => ({ onChangeOriginal: (text) => dispatch(Actions.updateOriginalInput(text)), onChangeFinal: (text) => dispatch(Actions.updateFinalInput(text)) }) class Main extends React.Component { render () { return ( <div> <Header /> <Segment basic padded> <Grid stackable columns={3}> <Grid.Column width='3'> <MainControls /> </Grid.Column> <Grid.Column width='6'> <Form> <Form.Field> <label>Original</label> <textarea value={this.props.input.original} onChange={event => this.props.onChangeOriginal(event.target.value)} /> </Form.Field> </Form> </Grid.Column> <Grid.Column width='6'> <Form> <Form.Field> <label>Final</label> <textarea value={this.props.input.final} onChange={event => this.props.onChangeFinal(event.target.value)} /> </Form.Field> </Form> </Grid.Column> </Grid> </Segment> <Footer /> </div> ) } } export default connect(mapStateToProps, mapDispatchToProps)(Main)
fields/types/date/DateField.js
nickhsine/keystone
import DateInput from '../../components/DateInput'; import Field from '../Field'; import moment from 'moment'; import React from 'react'; import { Button, InputGroup, FormInput } from 'elemental'; /* TODO: Implement yearRange Prop, or deprecate for max / min values (better) */ const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD ZZ'; const DEFAULT_FORMAT_STRING = 'YYYY-MM-DD ZZ'; module.exports = Field.create({ displayName: 'DateField', propTypes: { formatString: React.PropTypes.string, inputFormat: React.PropTypes.string, label: React.PropTypes.string, note: React.PropTypes.string, onChange: React.PropTypes.func, path: React.PropTypes.string, value: React.PropTypes.string, }, getDefaultProps () { return { formatString: DEFAULT_FORMAT_STRING, inputFormat: DEFAULT_INPUT_FORMAT, }; }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, moment (value) { var m = moment(value); return m; }, isValid (value) { return this.moment(value, this.inputFormat).isValid(); }, format (value) { return value ? this.moment(value).format(this.props.formatString) : ''; }, setToday () { this.valueChanged(this.moment(new Date()).format(this.props.inputFormat)); }, renderValue () { return <FormInput noedit>{this.format(this.props.value)}</FormInput>; }, renderField () { let value = this.moment(this.props.value); value = value.isValid() ? value.format(this.props.inputFormat) : this.props.value; return ( <InputGroup> <InputGroup.Section grow> <DateInput ref="dateInput" name={this.props.path} format={this.props.inputFormat} value={value} onChange={this.valueChanged} /> </InputGroup.Section> <InputGroup.Section> <Button onClick={this.setToday}>Today</Button> </InputGroup.Section> </InputGroup> ); }, });
src/containers/TermsOfService/container/TermsOfService.js
MeetDay/dreampark-web
import React from 'react' import PropTypes from 'prop-types' import { asyncConnect } from 'redux-async-connect' import { connect } from 'react-redux' import { isEmptyObject } from '../../Login/module/login' import { PageNotExist, CoverImage, TitleElement, TextElement, ImageElement, BigImageElement } from '../../../components' import { isTermLoaded, getUserTermsBy } from '../module/dreamparkTerms' @asyncConnect([{ deferred: true, promise: ({ params, store:{ dispatch, getState } }) => { const { serviceType } = params; if (!isTermLoaded(getState())) { return dispatch(getUserTermsBy(serviceType)) } } }]) @connect( state => ({ term: state.dreamparkTerms.term }) ) export default class TermsOfService extends React.Component { convertElementToComponet() { return (element) => { const { id, content } = element let mappedElement = null if (content.type === 'text') { mappedElement = <TextElement key={id} text={content.media.plain_text} /> } else if (content.type === 'image' && content.media.caption && content.media.caption.length > 0) { mappedElement = <BigImageElement key={id} src={content.media.name} captionText={content.media.caption} /> } else if (content.type === 'image') { mappedElement = <ImageElement key={id} src={content.media.name} /> } return mappedElement } } render() { if (!this.props.term || isEmptyObject(this.props.term)) return (<PageNotExist />); const styles = require('./TermsOfService.scss') const { title, cover_image: coverImage, elements } = this.props.term; return ( <div className={styles.container}> { !isEmptyObject(coverImage) && <CoverImage src={coverImage.name} /> } <div className={styles.termsWrapper}> { title && <TitleElement title={title} /> } { elements && elements.map(this.convertElementToComponet())} </div> </div> ); } }
tests/lib/rules/vars-on-top.js
jrvidal/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), EslintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var eslintTester = new EslintTester(eslint); eslintTester.addRuleTest("lib/rules/vars-on-top", { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), ecmaFeatures: { blockBindings: true } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
Component/Home/Home.js
outman1992/Taoertao
/** * Created by 58484 on 2016/9/9. */ /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, ScrollView, ListView, TouchableHighlight, Image, ActivityIndicator, RefreshControl, Platform } from 'react-native'; var PhotoSource = require('../Publish/Publish'); var Dimensions = require('Dimensions'); var {width} = Dimensions.get('window'); var request = require('../Common/request'); var config = require('../Common/config'); var Banner = require('../Common/Banner'); var Search = require('./Search'); var Detail = require('../Goods/Detail'); var cachedResults = { nextPage: 1, total: 0, items: [] } var Home = React.createClass({ getDefaultProps(){ return { imageRatioHeight: 298 * width / 600 - 50 } }, getInitialState(){ var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); // console.log(dataSource.job) return { NavBarBgOpacity: 0, isLoadingTail: false, isRefreshing: false, dataSource: ds.cloneWithRows([]) } }, pushToPhotoSource(){ this.props.navigator.push({ component: PhotoSource }) }, renderNavBar(){ return ( <View style={styles.NavBarWrapStyle}> <View style={[styles.NavBarBgStyle, {opacity: this.state.NavBarBgOpacity}]}></View> <TouchableOpacity style={styles.SearchTouchStyle} onPress={()=>{this.pushToSearch()}} activeOpacity={1} > <Text style={styles.SearchTextStyle}>搜索你喜欢的二货</Text> </TouchableOpacity> </View> ) }, onAnimationEnd(e){ var offSetY = e.nativeEvent.contentOffset.y; if(offSetY < this.props.imageRatioHeight){ //颜色渐变 var opacity = offSetY / this.props.imageRatioHeight; this.setState({NavBarBgOpacity: opacity}); }else{ //颜色固定 this.setState({NavBarBgOpacity: 1}) } }, pushToSearch(){ this.props.show(false); this.props.navigator.push( { component: Search, // params: { // show: function(is_show){ // show(is_show); // } // } } ); }, _fetchData(page){ if(page !== 0){ this.setState({ isLoadingTail: true }) }else{ this.setState({ isRefreshing: true }) } request.post(config.api.base + config.api.home, { page: page }) .then((data)=>{ if(data.status == 'success'){ var items = cachedResults.items.slice(); if(page !== 0){ items = items.concat(data.result.data); cachedResults.nextPage += 1; }else{ items = data.result.data.concat(items); } cachedResults.items = items; cachedResults.total = data.result.total; // console.log(data) setTimeout(()=>{ if(page !== 0){ this.setState({ isLoadingTail: false, dataSource: this.state.dataSource.cloneWithRows(cachedResults.items) }) }else{ this.setState({ isRefreshing: false, dataSource: this.state.dataSource.cloneWithRows(cachedResults.items) }) } }, 0) } }) .catch((error) => { if(page !== 0){ this.setState({ isLoadingTail: false }) }else{ this.setState({ isRefreshing: false }) } console.error(error); }); }, _renderRowImageList(imageArray){ var images = []; for(var i=0; i<imageArray.length; i++){ images.push( <Image key={i} source={{uri: imageArray[i]}} style={styles.ImageList} /> ) } return images }, componentDidMount(){ this._fetchData(1) }, _goDetail(rowData){ this.props.show(false); this.props.navigator.push({ component: Detail, name: '详情页', passProps: { id: rowData.id } }) }, _renderRow(rowData){ return( <View style={styles.goodsWrap}> <View style={styles.goodsHeader}> <TouchableOpacity style={styles.goodsHeaderBtn} activeOpacity={1}> <Image source={{uri: rowData.sellerHeader}} style={styles.sellerHeader} /> <Text style={styles.sellerName}>{rowData.sellerName}</Text> </TouchableOpacity> <Text style={styles.publishTime}>{rowData.publishTime}</Text> </View> <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} > <TouchableOpacity style={styles.goodsHeaderBtn} activeOpacity={1} onPress={()=>{ this._goDetail(rowData)}} > {this._renderRowImageList(rowData.image)} </TouchableOpacity> </ScrollView> <TouchableOpacity style={styles.goodsFooter} activeOpacity={1} onPress={()=>{ this._goDetail(rowData)}} > <Text style={styles.goodPrice}>¥{rowData.price}</Text> <Text style={styles.goodTitle}>{rowData.title}</Text> </TouchableOpacity> </View> ) }, _hasMore(){ return cachedResults.items.length !== cachedResults.total }, _fetchMoreData(){ if(!this._hasMore() || this.state.isLoadingTail){ return } var page = cachedResults.nextPage; this._fetchData(page) }, _renderFooter(){ if(!this._hasMore() && cachedResults.total !== 0){ return( <View style={styles.NoMoreData}><Text style={styles.NoMoreDataText}>没有更多数据了</Text></View> ) } if(!this.state.isLoadingTail){ return <View style={styles.NoMoreData} /> } return <ActivityIndicator style={styles.NoMoreData} /> }, _onRefresh(){ if(!this._hasMore() || this.state.isRefreshing){ return } this._fetchData(0) }, render() { return ( <View style={styles.container}> {this.renderNavBar()} <ScrollView showsVerticalScrollIndicator={false} onScroll={(e)=>this.onAnimationEnd(e)} scrollEventThrottle={16} refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh} colors={['#666']} /> } > <Banner /> <ListView dataSource={this.state.dataSource} renderRow={this._renderRow} enableEmptySections={true} onEndReached={this._fetchMoreData} onEndReachedThreshold={20} renderFooter={this._renderFooter} /> </ScrollView> </View> ); }, }); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eee', }, NavBarWrapStyle: { width: width, height: Platform.OS === 'ios' ? 65 : 50, position: 'absolute', zIndex: 1, justifyContent: 'center', alignItems: 'center', paddingTop: Platform.OS === 'ios' ? 15 : 0, }, NavBarBgStyle: { width: width, height: Platform.OS === 'ios' ? 65 : 50, backgroundColor: '#11cd6e', position: 'absolute', top: 0, opacity: 0 }, SearchTouchStyle: { width: width * 0.9, borderRadius: 15, height: 30, backgroundColor: '#fff', alignItems: 'center' }, SearchTextStyle: { textAlign: 'center', width: Platform.OS === 'ios' ? width * 0.8 : width * 0.9, lineHeight: Platform.OS === 'ios' ? 20 : 0, height: 30, marginTop: Platform.OS === 'ios' ? 0 : 5, }, goodsWrap: { paddingLeft: 10, paddingRight: 10, marginTop: 8, backgroundColor: '#fff' }, goodsHeader: { height: 40, flexDirection: 'row', alignItems: 'center' }, sellerHeader: { width: 26, height: 26, marginRight: 5, borderRadius: 13, }, sellerName: {}, publishTime: { position: 'absolute', right: 0, top: 8, fontSize: 12, color: '#999' }, ImageList: { width: 100, height: 100, marginRight: 3 }, goodPrice: { color: 'red', marginTop: 10, marginBottom: 10 }, goodTitle: { marginBottom: 10 }, NoMoreData: { marginVertical: 20 }, NoMoreDataText: { color: '#ccc', textAlign: 'center' }, goodsHeaderBtn:{ flexDirection: 'row', alignItems: 'center' } }); module.exports = Home;
src/svg-icons/action/list.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionList = (props) => ( <SvgIcon {...props}> <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/> </SvgIcon> ); ActionList = pure(ActionList); ActionList.displayName = 'ActionList'; ActionList.muiName = 'SvgIcon'; export default ActionList;
src/node_modules/react-router/es6/RouteUtils.js
oferkafry/gps-tracker-ui
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; export { isReactChildren }; export { createRouteFromReactElement }; export { createRoutesFromReactChildren }; export { createRoutes }; import React from 'react'; import warning from 'warning'; function isValidChild(object) { return object == null || React.isValidElement(object); } function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent'; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName); /* istanbul ignore if: error logging */ if (error instanceof Error) process.env.NODE_ENV !== 'production' ? warning(false, error.message) : undefined; } } } function createRoute(defaultProps, props) { return _extends({}, defaultProps, props); } function createRouteFromReactElement(element) { var type = element.type; var route = createRoute(type.defaultProps, element.props); if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route); if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route); if (childRoutes.length) route.childRoutes = childRoutes; delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ function createRoutesFromReactChildren(children, parentRoute) { var routes = []; React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
src/components/TabManager.js
RamonGebben/react-perf-tool
import React, { Component } from 'react'; import TabHeader from './TabHeader'; class TabManager extends Component { constructor(props) { super(props); this.children = [].concat(props.children); this.state = { activeTab: this.children[0].key, }; } componentDidMount() { } componentWillReceiveProps(nextProps) { this.children = [].concat(nextProps.children); } onTabClick(key) { this.setState({ activeTab: key }); } render() { const tabs = this.children.map((tab, i) => ( <TabHeader title={tab.key} isActive={tab.key === this.state.activeTab} key={i} align={tab.props.align} onClick={this.onTabClick.bind(this, tab.key)} /> )); return (<div className="tab-manager"> <div className="tab-bar"> {tabs} </div> {this.children.find(child => child.key === this.state.activeTab)} </div>); } } export default TabManager;
trsearch/src/App.js
balaSpyrus/code
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import request from 'request'; import cheerio from 'cheerio'; const URL ='http://tamilrockers.gs/index.php?' class App extends Component { state={ count:0, links:[] } getData=()=>{ let self=this; let datalinks =[]; request(URL,function(x,y,z){ let $ = cheerio.load(z) $('.bbc_url').each(function(i, link) { if($(link).attr('href').includes('tamilrockers.gs') && $(link).text().includes('720p')){ request($(link).attr('href'),function(x1,y1,z1){ let $$ = cheerio.load(z1) $$('a').each(function(index,link2) { if(!x1 && $$(link2).attr('title') && $$(link2).attr('title').includes('Download attachment')){ // console.log($$(link2).text() + ' - ' + $$(link2).attr('href')); datalinks.push(<a href={$$(link2).attr('href')}>{$$(link2).text()}</a>) self.setState((prevState)=>({ count:prevState.count +1, links:datalinks })) } }) }) } }); }) } render() { return ( <div className="App"> <div className="container"> <a href="#" className="btn cyan" onClick={this.getData}>GET TORRENTS</a> <h2>{this.state.count} torrents found !!</h2> <ul> { this.state.links.map(tags=><li>{tags}</li>) } </ul> </div> </div> ); } } export default App;
src/parser/druid/restoration/modules/items/azeritetraits/AutumnLeaves.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { formatPercentage, formatNumber } from 'common/format'; import SPELLS from 'common/SPELLS'; import Combatants from 'parser/shared/modules/Combatants'; import HealingDone from 'parser/shared/modules/throughput/HealingDone'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import StatWeights from '../../features/StatWeights'; import { getPrimaryStatForItemLevel, findItemLevelByPrimaryStat } from './common'; import Rejuvenation from '../../core/Rejuvenation'; /** Rejuvenation's duration is increased by 1 sec, and it heals for an additional 82 when it is your only heal over time on the target. */ class AutumnLeaves extends Analyzer { static dependencies = { statWeights: StatWeights, combatants: Combatants, rejuvenation: Rejuvenation, healingDone: HealingDone, }; healing = 0; avgItemLevel = 0; traitLevel = 0; // TODO: Additions for: mastery, cultivation and AL. // TODO: Subtractions for overheals on last tick and subtractions for early refreshes. // Tracks if the last tick of rejuv/germ on each player was overhealing. // Used to determine if a player still needed to be healed when rejuv fell. totalOneSecondValue = 0; lastTickTracker = { [SPELLS.REJUVENATION.id]: {}, [SPELLS.REJUVENATION_GERMINATION.id]: {} }; lastTickCount = 0; lastTickOverhealCount = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.AUTUMN_LEAVES_TRAIT.id); if (this.active) { this.avgItemLevel = this.selectedCombatant.traitsBySpellId[SPELLS.AUTUMN_LEAVES_TRAIT.id] .reduce((a, b) => a + b) / this.selectedCombatant.traitsBySpellId[SPELLS.AUTUMN_LEAVES_TRAIT.id].length; this.traitLevel = this.selectedCombatant.traitsBySpellId[SPELLS.AUTUMN_LEAVES_TRAIT.id].length; } } on_byPlayer_heal(event) { const spellId = event.ability.guid; const targetId = event.targetID; if (this.lastTickTracker[spellId]) { this.lastTickTracker[spellId][targetId] = (event.overheal > 0); } if (spellId === SPELLS.AUTUMN_LEAVES.id) { this.healing += event.amount + (event.absorbed || 0); } } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; const targetId = event.targetID; if (this.lastTickTracker[spellId]) { this.lastTickCount += 1; if (this.lastTickTracker[spellId][targetId]) { this.lastTickOverhealCount += 1; } } } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (SPELLS.REJUVENATION.id !== spellId && SPELLS.REJUVENATION_GERMINATION.id !== spellId) { return; } this.totalOneSecondValue += 1; } on_byPlayer_refreshbuff(event) { const spellId = event.ability.guid; if (SPELLS.REJUVENATION.id !== spellId && SPELLS.REJUVENATION_GERMINATION.id !== spellId) { return; } this.totalOneSecondValue += 1; } getSpellUptime(spellId) { return Object.keys(this.combatants.players) .map(key => this.combatants.players[key]) .reduce((uptime, player) => uptime + player.getBuffUptime(spellId), 0); } statistic() { // Calculating the "one second" part.. const rejuvUptimeInSeconds = (this.getSpellUptime(SPELLS.REJUVENATION.id) + this.getSpellUptime(SPELLS.REJUVENATION_GERMINATION.id)) / 1000; const totalRejuvenationHealing = this.rejuvenation.totalRejuvHealing; const rejuvHealingVal = this.healingDone.byAbility(SPELLS.REJUVENATION.id); const germHealingVal = this.healingDone.byAbility(SPELLS.REJUVENATION_GERMINATION.id); const rejuvGermHealingVal = rejuvHealingVal.add(germHealingVal.regular, germHealingVal.absorbed, germHealingVal.overheal); const rejuvGermEffetivePercent = rejuvGermHealingVal.effective / rejuvGermHealingVal.raw; const lastTickEffectivePercent = (this.lastTickCount - this.lastTickOverhealCount) / this.lastTickCount; const totalRejuvHealingOverhealAdjusted = totalRejuvenationHealing / rejuvGermEffetivePercent * lastTickEffectivePercent; const oneSecondRejuvenationHealing = totalRejuvHealingOverhealAdjusted / rejuvUptimeInSeconds; const totalOneSecondValue = this.owner.getPercentageOfTotalHealingDone(this.totalOneSecondValue * oneSecondRejuvenationHealing); const throughputPercent = this.owner.getPercentageOfTotalHealingDone(this.healing); const onePercentThroughputInInt = this.statWeights._ratingPerOnePercent(this.statWeights.totalOneInt); const intGain = onePercentThroughputInInt * (throughputPercent+totalOneSecondValue) * 100; const ilvlGain = findItemLevelByPrimaryStat(getPrimaryStatForItemLevel(this.avgItemLevel) + intGain) - this.avgItemLevel; return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.AUTUMN_LEAVES_TRAIT.id} value={( <> {formatPercentage(throughputPercent + totalOneSecondValue)} % </> )} tooltip={( <> <b>Disclaimer</b> - as of right now this is an estimate. We take the average healing of one second of rejuvenation and multiply that by amounts of rejuv applications. Finally, we adjust this number based on the average overhealing at the end of a rejuvenation against the avg overhealing of rejuvenation as a whole. These factors are not yet considered in the module and may decrease the overall accuracy of the results: <ul> <li>+ Cultivation</li> <li>+ Autumn Leaves</li> <li>- Early refreshes of rejuvenation.</li> </ul> Estimated accuracy of the result is 80%<br /> Autumn Leaves healing: <b>{formatPercentage(throughputPercent)}%</b><br /> Extra second of Rejuvenation equivalent to <b>{formatPercentage(totalOneSecondValue)}%</b><br /> Autumn Leaves gave you equivalent to <b>{formatNumber(intGain)}</b> ({formatNumber(intGain / this.traitLevel)} per level) int. This is worth roughly <b>{formatNumber(ilvlGain)}</b> ({formatNumber(ilvlGain / this.traitLevel)} per level) item levels. </> )} /> ); } } export default AutumnLeaves;
src/DropdownButton.js
nickuraltsev/react-bootstrap
import React from 'react'; import BootstrapMixin from './BootstrapMixin'; import Dropdown from './Dropdown'; import NavDropdown from './NavDropdown'; import CustomPropTypes from './utils/CustomPropTypes'; import deprecationWarning from './utils/deprecationWarning'; import omit from 'lodash-compat/object/omit'; class DropdownButton extends React.Component { constructor(props) { super(props); } render() { let { title, navItem, ...props } = this.props; let toggleProps = omit(props, Dropdown.ControlledComponent.propTypes); if (navItem) { return <NavDropdown {...this.props}/>; } return ( <Dropdown {...props}> <Dropdown.Toggle {...toggleProps}> {title} </Dropdown.Toggle> <Dropdown.Menu> {this.props.children} </Dropdown.Menu> </Dropdown> ); } } DropdownButton.propTypes = { /** * When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element. */ noCaret: React.PropTypes.bool, /** * Specify whether this Dropdown is part of a Nav component * * @type {bool} * @deprecated Use the `NavDropdown` instead. */ navItem: CustomPropTypes.all([ React.PropTypes.bool, props => { if (props.navItem) { deprecationWarning('navItem', 'NavDropdown component', 'https://github.com/react-bootstrap/react-bootstrap/issues/526'); } } ]), title: React.PropTypes.node.isRequired, ...Dropdown.propTypes, ...BootstrapMixin.propTypes }; DropdownButton.defaultProps = { pullRight: false, dropup: false, navItem: false, noCaret: false }; export default DropdownButton;
src/js/index.js
Jeowulf/hackathon
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { configureStore } from './store'; import Root from './containers/root'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); render( <Root store={store} history={history} />, document.getElementById('root') );
src/index.js
danchampion6/protozoa
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/css/bootstrap-theme.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/components/views/dialogs/SetMxIdDialog.js
aperezdc/matrix-react-sdk
/* Copyright 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Promise from 'bluebird'; import React from 'react'; import PropTypes from 'prop-types'; import sdk from '../../../index'; import MatrixClientPeg from '../../../MatrixClientPeg'; import classnames from 'classnames'; import { KeyCode } from '../../../Keyboard'; import { _t } from '../../../languageHandler'; // The amount of time to wait for further changes to the input username before // sending a request to the server const USERNAME_CHECK_DEBOUNCE_MS = 250; /** * Prompt the user to set a display name. * * On success, `onFinished(true, newDisplayName)` is called. */ export default React.createClass({ displayName: 'SetMxIdDialog', propTypes: { onFinished: PropTypes.func.isRequired, // Called when the user requests to register with a different homeserver onDifferentServerClicked: PropTypes.func.isRequired, // Called if the user wants to switch to login instead onLoginClick: PropTypes.func.isRequired, }, getInitialState: function() { return { // The entered username username: '', // Indicate ongoing work on the username usernameBusy: false, // Indicate error with username usernameError: '', // Assume the homeserver supports username checking until "M_UNRECOGNIZED" usernameCheckSupport: true, // Whether the auth UI is currently being used doingUIAuth: false, // Indicate error with auth authError: '', }; }, componentDidMount: function() { this.refs.input_value.select(); this._matrixClient = MatrixClientPeg.get(); }, onValueChange: function(ev) { this.setState({ username: ev.target.value, usernameBusy: true, usernameError: '', }, () => { if (!this.state.username || !this.state.usernameCheckSupport) { this.setState({ usernameBusy: false, }); return; } // Debounce the username check to limit number of requests sent if (this._usernameCheckTimeout) { clearTimeout(this._usernameCheckTimeout); } this._usernameCheckTimeout = setTimeout(() => { this._doUsernameCheck().finally(() => { this.setState({ usernameBusy: false, }); }); }, USERNAME_CHECK_DEBOUNCE_MS); }); }, onKeyUp: function(ev) { if (ev.keyCode === KeyCode.ENTER) { this.onSubmit(); } }, onSubmit: function(ev) { this.setState({ doingUIAuth: true, }); }, _doUsernameCheck: function() { // XXX: SPEC-1 // Check if username is valid // Naive impl copied from https://github.com/matrix-org/matrix-react-sdk/blob/66c3a6d9ca695780eb6b662e242e88323053ff33/src/components/views/login/RegistrationForm.js#L190 if (encodeURIComponent(this.state.username) !== this.state.username) { this.setState({ usernameError: _t('User names may only contain letters, numbers, dots, hyphens and underscores.'), }); return Promise.reject(); } // Check if username is available return this._matrixClient.isUsernameAvailable(this.state.username).then( (isAvailable) => { if (isAvailable) { this.setState({usernameError: ''}); } }, (err) => { // Indicate whether the homeserver supports username checking const newState = { usernameCheckSupport: err.errcode !== "M_UNRECOGNIZED", }; console.error('Error whilst checking username availability: ', err); switch (err.errcode) { case "M_USER_IN_USE": newState.usernameError = _t('Username not available'); break; case "M_INVALID_USERNAME": newState.usernameError = _t( 'Username invalid: %(errMessage)s', { errMessage: err.message}, ); break; case "M_UNRECOGNIZED": // This homeserver doesn't support username checking, assume it's // fine and rely on the error appearing in registration step. newState.usernameError = ''; break; case undefined: newState.usernameError = _t('Something went wrong!'); break; default: newState.usernameError = _t( 'An error occurred: %(error_string)s', { error_string: err.message }, ); break; } this.setState(newState); }, ); }, _generatePassword: function() { return Math.random().toString(36).slice(2); }, _makeRegisterRequest: function(auth) { // Not upgrading - changing mxids const guestAccessToken = null; if (!this._generatedPassword) { this._generatedPassword = this._generatePassword(); } return this._matrixClient.register( this.state.username, this._generatedPassword, undefined, // session id: included in the auth dict already auth, {}, guestAccessToken, ); }, _onUIAuthFinished: function(success, response) { this.setState({ doingUIAuth: false, }); if (!success) { this.setState({ authError: response.message }); return; } // XXX Implement RTS /register here const teamToken = null; this.props.onFinished(true, { userId: response.user_id, deviceId: response.device_id, homeserverUrl: this._matrixClient.getHomeserverUrl(), identityServerUrl: this._matrixClient.getIdentityServerUrl(), accessToken: response.access_token, password: this._generatedPassword, teamToken: teamToken, }); }, render: function() { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const InteractiveAuth = sdk.getComponent('structures.InteractiveAuth'); const Spinner = sdk.getComponent('elements.Spinner'); let auth; if (this.state.doingUIAuth) { auth = <InteractiveAuth matrixClient={this._matrixClient} makeRequest={this._makeRegisterRequest} onAuthFinished={this._onUIAuthFinished} inputs={{}} poll={true} />; } const inputClasses = classnames({ "mx_SetMxIdDialog_input": true, "error": Boolean(this.state.usernameError), }); let usernameIndicator = null; let usernameBusyIndicator = null; if (this.state.usernameBusy) { usernameBusyIndicator = <Spinner w="24" h="24" />; } else { const usernameAvailable = this.state.username && this.state.usernameCheckSupport && !this.state.usernameError; const usernameIndicatorClasses = classnames({ "error": Boolean(this.state.usernameError), "success": usernameAvailable, }); usernameIndicator = <div className={usernameIndicatorClasses} role="alert"> { usernameAvailable ? _t('Username available') : this.state.usernameError } </div>; } let authErrorIndicator = null; if (this.state.authError) { authErrorIndicator = <div className="error" role="alert"> { this.state.authError } </div>; } const canContinue = this.state.username && !this.state.usernameError && !this.state.usernameBusy; return ( <BaseDialog className="mx_SetMxIdDialog" onFinished={this.props.onFinished} title={_t('To get started, please pick a username!')} contentId='mx_Dialog_content' > <div className="mx_Dialog_content" id='mx_Dialog_content'> <div className="mx_SetMxIdDialog_input_group"> <input type="text" ref="input_value" value={this.state.username} autoFocus={true} onChange={this.onValueChange} onKeyUp={this.onKeyUp} size="30" className={inputClasses} /> { usernameBusyIndicator } </div> { usernameIndicator } <p> { _t( 'This will be your account name on the <span></span> ' + 'homeserver, or you can pick a <a>different server</a>.', {}, { 'span': <span>{ this.props.homeserverUrl }</span>, 'a': (sub) => <a href="#" onClick={this.props.onDifferentServerClicked}>{ sub }</a>, }, ) } </p> <p> { _t( 'If you already have a Matrix account you can <a>log in</a> instead.', {}, { 'a': (sub) => <a href="#" onClick={this.props.onLoginClick}>{ sub }</a> }, ) } </p> { auth } { authErrorIndicator } </div> <div className="mx_Dialog_buttons"> <input className="mx_Dialog_primary" type="submit" value={_t("Continue")} onClick={this.onSubmit} disabled={!canContinue} /> </div> </BaseDialog> ); }, });
addons/ondevice-knobs/src/panel.js
storybooks/react-storybook
import React from 'react'; import { View, Text } from 'react-native'; import PropTypes from 'prop-types'; import { SELECT_STORY, FORCE_RE_RENDER } from '@storybook/core-events'; import { SET, SET_OPTIONS, RESET, CHANGE, CLICK } from '@storybook/addon-knobs'; import styled from '@emotion/native'; import GroupTabs from './GroupTabs'; import PropForm from './PropForm'; const getTimestamp = () => +new Date(); const DEFAULT_GROUP_ID = 'Other'; const Touchable = styled.TouchableOpacity(({ theme }) => ({ borderRadius: 2, borderWidth: 1, borderColor: theme.borderColor, padding: 4, margin: 10, justifyContent: 'center', alignItems: 'center', })); const ResetButton = styled.Text(({ theme }) => ({ color: theme.buttonTextColor, })); export default class Panel extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); this.setKnobs = this.setKnobs.bind(this); this.reset = this.reset.bind(this); this.setOptions = this.setOptions.bind(this); this.onGroupSelect = this.onGroupSelect.bind(this); this.state = { knobs: {}, groupId: DEFAULT_GROUP_ID }; this.options = {}; this.lastEdit = getTimestamp(); this.loadedFromUrl = false; } componentDidMount() { const { channel } = this.props; channel.on(SET, this.setKnobs); channel.on(SET_OPTIONS, this.setOptions); channel.on(SELECT_STORY, this.reset); channel.emit(FORCE_RE_RENDER); } componentWillUnmount() { const { channel } = this.props; channel.removeListener(SET, this.setKnobs); channel.removeListener(SELECT_STORY, this.reset); } onGroupSelect(name) { this.setState({ groupId: name }); } setOptions(options = { timestamps: false }) { this.options = options; } setKnobs({ knobs, timestamp }) { if (!this.options.timestamps || !timestamp || this.lastEdit <= timestamp) { this.setState({ knobs }); } } reset = () => { const { channel } = this.props; this.setState({ knobs: {} }); channel.emit(RESET); }; emitChange(changedKnob) { const { channel } = this.props; channel.emit(CHANGE, changedKnob); } handleChange(changedKnob) { this.lastEdit = getTimestamp(); const { knobs } = this.state; const { name } = changedKnob; const newKnobs = { ...knobs }; newKnobs[name] = { ...newKnobs[name], ...changedKnob, }; this.setState({ knobs: newKnobs }); this.setState( { knobs: newKnobs }, this.emitChange( changedKnob.type === 'number' ? { ...changedKnob, value: parseFloat(changedKnob.value) } : changedKnob ) ); } handleClick(knob) { const { channel } = this.props; channel.emit(CLICK, knob); } render() { const { active } = this.props; if (!active) { return null; } const { knobs, groupId: stateGroupId } = this.state; const groups = {}; const groupIds = []; let knobsArray = Object.keys(knobs); const knobsWithGroups = knobsArray.filter(key => knobs[key].groupId); knobsWithGroups.forEach(key => { const knobKeyGroupId = knobs[key].groupId; groupIds.push(knobKeyGroupId); groups[knobKeyGroupId] = { render: () => <Text id={knobKeyGroupId}>{knobKeyGroupId}</Text>, title: knobKeyGroupId, }; }); const allHaveGroups = groupIds.length > 0 && knobsArray.length === knobsWithGroups.length; // If all of the knobs are assigned to a group, we don't need the default group. const groupId = stateGroupId === DEFAULT_GROUP_ID && allHaveGroups ? knobs[knobsWithGroups[0]].groupId : stateGroupId; if (groupIds.length > 0) { if (!allHaveGroups) { groups[DEFAULT_GROUP_ID] = { render: () => <Text id={DEFAULT_GROUP_ID}>{DEFAULT_GROUP_ID}</Text>, title: DEFAULT_GROUP_ID, }; } if (groupId === DEFAULT_GROUP_ID) { knobsArray = knobsArray.filter(key => !knobs[key].groupId); } if (groupId !== DEFAULT_GROUP_ID) { knobsArray = knobsArray.filter(key => knobs[key].groupId === groupId); } } knobsArray = knobsArray.map(key => knobs[key]); if (knobsArray.length === 0) { return <Text>NO KNOBS</Text>; } return ( <View style={{ flex: 1, paddingTop: 10 }}> {groupIds.length > 0 && ( <GroupTabs groups={groups} onGroupSelect={this.onGroupSelect} selectedGroup={groupId} /> )} <View> <PropForm knobs={knobsArray} onFieldChange={this.handleChange} onFieldClick={this.handleClick} /> </View> <Touchable onPress={this.reset}> <ResetButton>RESET</ResetButton> </Touchable> </View> ); } } Panel.propTypes = { active: PropTypes.bool.isRequired, channel: PropTypes.shape({ emit: PropTypes.func, on: PropTypes.func, removeListener: PropTypes.func, }).isRequired, onReset: PropTypes.object, // eslint-disable-line };
test/helpers/shallowRenderHelper.js
suda077/zzy-galery
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
app/components/Header/index.js
likesalmon/likesalmon-react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.jpg'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="https://twitter.com/mxstbr"> <Img src={Banner} alt="react-boilerplate - Logo" /> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/features"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
react_native_frontend/src/pages/accountsettings.js
CUNYTech/BudgetApp
import React, { Component } from 'react'; import { View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'; import { Container, Text, Left, Right, ListItem, Spinner } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { getPlatformValue } from '../utils'; export default class AccountSettings extends Component { render() { return ( <Container style={{ backgroundColor: 'black' }}> <View style={styles.header}> <TouchableOpacity> <Icon name="bars" size={30} color="white" onPress={this.props.sideMenu} /> </TouchableOpacity> <Text style={{color: 'white', fontSize:25, textAlign:'center', width:250, fontWeight:'300', marginBottom:5}}>Account Settings</Text> <Icon name="diamond" size={20} color="gold" /> </View> <ScrollView horizontal={false} showsHorizontalScrollIndicator={false} contentContainerStyle={{}}> <ListItem> <Left> <Text style={{color:'white', textAlign:'left'}}>Work In Progress</Text> </Left> <Right> <Spinner color="red" /> </Right> </ListItem> </ScrollView> </Container> ); } } const styles = StyleSheet.create({ totalPoints: { color: 'blue', fontWeight: 'bold', fontSize: 60, }, red: { color: 'red', }, headline: { fontWeight: 'bold', fontSize: 18, marginTop: 0, width: 200, textAlign: 'center', backgroundColor: 'yellow', }, header: { paddingTop: getPlatformValue('android', 25, 20), flex: 0, flexDirection: 'row', height: 60, backgroundColor: 'black', justifyContent: 'space-around', alignItems: 'center', borderBottomWidth: 1, borderColor: '#424242', }, });
src/docs/Navigation.js
zeegeek/ps-react-reusable-comp
import React from 'react'; import PropTypes from 'prop-types'; const Navigation = ({components}) => { return ( <ul className="navigation"> { components.map( name => { return ( <li key={name}> <a href={`#${name}`}>{name}</a> </li> ) }) } </ul> ) } Navigation.propTypes = { components: PropTypes.array.isRequired }; export default Navigation;
src/svg-icons/places/fitness-center.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesFitnessCenter = (props) => ( <SvgIcon {...props}> <path d="M20.57 14.86L22 13.43 20.57 12 17 15.57 8.43 7 12 3.43 10.57 2 9.14 3.43 7.71 2 5.57 4.14 4.14 2.71 2.71 4.14l1.43 1.43L2 7.71l1.43 1.43L2 10.57 3.43 12 7 8.43 15.57 17 12 20.57 13.43 22l1.43-1.43L16.29 22l2.14-2.14 1.43 1.43 1.43-1.43-1.43-1.43L22 16.29z"/> </SvgIcon> ); PlacesFitnessCenter = pure(PlacesFitnessCenter); PlacesFitnessCenter.displayName = 'PlacesFitnessCenter'; PlacesFitnessCenter.muiName = 'SvgIcon'; export default PlacesFitnessCenter;
components/layout/Panel.js
react-toolbox/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import { themr } from 'react-css-themr'; import { LAYOUT } from '../identifiers'; const Panel = ({ bodyScroll, children, className, theme, ...other }) => { const _className = cn(theme.panel, { [theme.bodyScroll]: bodyScroll }, className); return ( <div {...other} data-react-toolbox="panel" className={_className}> {children} </div> ); }; Panel.propTypes = { bodyScroll: PropTypes.bool, children: PropTypes.node, className: PropTypes.string, theme: PropTypes.shape({ panel: PropTypes.string, }), }; Panel.defaultProps = { bodyScroll: true, className: '', }; export default themr(LAYOUT)(Panel); export { Panel };
src/components/HeaderStrip/index.js
bhargav175/resume
import React from 'react'; import styles from './style.scss'; class HeaderStrip extends React.Component{ render(){ return <div className={styles.root}>Hi There! I am Bhargav</div>; } } export default HeaderStrip;
dva/porsche-e3/src/routes/RulePage.js
imuntil/React
import React from 'react' import { connect } from 'dva' import QueueAnim from 'rc-queue-anim' import TopBanner from '../components/TopBanner' import BottomBar from '../components/BottomBar' import './RulePage.scss' const Honor = () => { console.log('function') return ( <QueueAnim className="rule-box" type={['right', 'left']} ease={['easeOutQuart', 'easeInOutQuart']}> <p key={1} data-index="1"> 本次课前学习共有四轮活动,每参与完成一轮活动即可获得等级、称号以及勋章提升,具体规则如下: </p> <p key={2} data-index="2"> <span className="color--red">“等级”</span>提升规则:每参与完成一轮活动即可获得等级提升:1、2、3、4 </p> <p key={3} data-index="3"> <span className="color--red">“称号”</span>提升规则:每参与完成一轮活动即可获得对应称号:“新手上路”、“轻车熟路”、“老司机”以及“纽北之王” </p> <p key={4} data-index="4"> <span className="color--red">“勋章”</span>提升规则:每参与完成一轮活动即可获得对应勋章:“Cayenne”、“Cayenne S”、“Cayenne Turbo”、“齐心并驰” </p> <p key={5} data-index="5"> 等级、称号以及勋章将在所有活动结束后进行统计,并将折算在最终的测试总成绩中。 </p> <p key={6} data-index="6" className="small color--red"> *最终解释权归保时捷人才学院所有 </p> </QueueAnim> ) } const Activity = () => { return ( <QueueAnim className="rule-box" type={['right', 'left']} ease={['easeOutQuart', 'easeInOutQuart']}> <p key={1} data-index="1"> 本次课前学习共有四轮活动,每周随机分配,活动主题分别为:文字选择题、图形选择题、分享照片以及寄语活动。具体活动规则如下: </p> <p key={2} data-index="2"> <span className="color--red">“文字选择题”</span> 活动规则:每周随机出现 5 道题,全部答题正确即完成活动,并获得等级、称号以及勋章 </p> <p key={3} data-index="3"> <span className="color--red">“图形选择题”</span>活动规则:每周随机出现 5 道题,全部答题正确即完成活动,并获得等级、称号以及勋章 </p> <p key={4} data-index="4"> <span className="color--red">“分享照片”</span>活动规则:请上传一张您与保时捷 Cayenne 的合影,可以是您销售的第一台 Cayenne、您销售的最贵的一台 Cayenne、您参与过的印象最深刻的 Cayenne 活动等。成功上传即可获得等级、称号以及勋章。 </p> <p key={5} data-index="5"> <span className="color--red">“寄语”</span>活动规则:请以视频或图片形式上传一段您对于全新 Cayenne 的寄语。视频请限制在 10 秒以内,图片上可 PS 您最想说的一句寄语并上传。成功上传即可获得等级、称号以及勋章 </p> <p key={6} data-index="6" className="small color--red"> *所有视频或图片尽量压缩在 5M 以内 </p> </QueueAnim> ) } const RulePage = ({ match }) => { return ( <div className="container rule-page"> <div className="main-body"> <TopBanner title={'活动规则'} type={true}> <img src={require('../assets/test-banner.jpg')} alt="" width="100%" /> </TopBanner> {match.params.rule === 'honor' ? <Honor /> : <Activity />} </div> <BottomBar mode={2} /> </div> ) } export default connect()(RulePage)
src/html.js
lmammino/loige.co
import React from 'react' import PropTypes from 'prop-types' import { Global, css, jsx } from '@emotion/react' const colors = { char: '#D8DEE9', comment: '#999999', keyword: '#c5a5c5', lineHighlight: '#14161a', primitive: '#5a9bcf', string: '#8dc891', variable: '#d7deea', boolean: '#ff8b50', punctuation: '#5FB3B3', tag: '#fc929e', function: '#79b6f2', className: '#FAC863', method: '#6699CC', operator: '#fc929e' } const globalStyle = css` * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif; font-style: normal; font-weight: 400; fill: currentColor; @media (min-width: 780px) { margin: 60px 0 0 0; } } code, pre { font-family: source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace; font-weight: 300; } .content a { text-decoration: none; } blockquote .gatsby-highlight { margin: 1.5em 0 1.5em 0; padding: 0.5em; } .gatsby-highlight { font-size: 15px; line-height: 1.7; background: #282c34; color: #ffffff; border-radius: 10px; overflow: auto; tab-size: 1.5em; margin: 1.5em -1em 1.5em 0; padding: 1em; @media (min-width: 780px) { margin-left: -2em; padding-left: 2em; padding-right: 2em; font-size: 16px; } .token.attr-name { color: ${colors.keyword}; } .token.comment, .token.block-comment, .token.prolog, .token.doctype, .token.cdata { color: ${colors.comment}; } .token.property, .token.number, .token.function-name, .token.constant, .token.symbol, .token.deleted { color: ${colors.primitive}; } .token.boolean { color: ${colors.boolean}; } .token.tag { color: ${colors.tag}; } .token.string { color: ${colors.string}; } .token.punctuation { color: ${colors.punctuation}; } .token.selector, .token.char, .token.builtin, .token.inserted { color: ${colors.char}; } .token.function { color: ${colors.function}; } .token.operator, .token.entity, .token.url, .token.variable { color: ${colors.variable}; } .token.attr-value { color: ${colors.string}; } .token.keyword { color: ${colors.keyword}; } .token.atrule, .token.class-name { color: ${colors.className}; } .token.important { font-weight: 400; } .token.bold { font-weight: 700; } .token.italic { font-style: italic; } .token.entity { cursor: help; } } .gatsby-highlight > pre { height: auto !important; margin: 1rem; white-space: pre-wrap; word-break: break-word; } .gatsby-highlight + .gatsby-highlight { margin-top: 20px, } .gatsby-highlight-code-line { background-color: #14161a; display: block; margin: -0.125rem calc(-1rem - 15px); padding: 0.125rem calc(1rem + 15px); } ` export default class HTML extends React.Component { render () { return ( <html {...this.props.htmlAttributes}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> {this.props.headComponents} </head> <body {...this.props.bodyAttributes}> <Global styles={globalStyle}/> {this.props.preBodyComponents} <div key={'body'} id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ) } } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array }
src/components/ui/quote.js
xavier-besson/react-playground
import React from 'react'; import Default from 'components/ui/default'; /** * @class Quote * @extends Default */ class Quote extends Default { /** * React method. * Return a single React element. * This element can be either a representation of a native DOM component, * such as <div />, or another composite component that you've defined yourself. * You can also return null or false to indicate that you don't want anything rendered. * When returning null or false, ReactDOM.findDOMNode(this) will return null. * @method render * @return {Mixed} A representation of a native DOM component */ render() { const { children, ...other } = this.props; return ( <blockquote {...other} > {children} </blockquote> ); } } export default Quote;
packages/ringcentral-widgets-docs/src/app/pages/Components/ActiveCallPad/Demo.js
ringcentral/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import ActiveCallPad from 'ringcentral-widgets/components/ActiveCallPad'; import callCtrlLayouts from 'ringcentral-widgets/enums/callCtrlLayouts'; const props = {}; props.onMute = () => null; props.onUnmute = () => null; props.onHold = () => null; props.onUnhold = () => null; props.onRecord = () => null; props.onStopRecord = () => null; props.onHangup = () => null; props.onPark = () => null; props.onShowKeyPad = () => null; props.onAdd = () => null; props.onMerge = () => null; props.currentLocale = 'en-US'; props.flipNumbers = []; props.recordStatus = 'recordStatus-idle'; props.onShowFlipPanel = () => null; props.onToggleTransferPanel = () => null; props.layout = callCtrlLayouts.normalCtrl; /** * A example of `ActiveCallPad` */ const ActiveCallPadDemo = () => <ActiveCallPad {...props} />; export default ActiveCallPadDemo;
pages/blog/test-article-one.js
el-besto/examples
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Test Article 1</h1> <p>Coming soon.</p> </div> ); } }
packages/react/src/components/FluidForm/FluidForm.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; import { settings } from 'carbon-components'; import Form from '../Form'; import { FormContext } from './FormContext'; const { prefix } = settings; function FluidForm({ className, children, ...other }) { const classNames = classnames(`${prefix}--form--fluid`, className); return ( <FormContext.Provider value={{ isFluid: true }}> <Form className={classNames} {...other}> {children} </Form> </FormContext.Provider> ); } FluidForm.propTypes = { /** * Provide children to be rendered inside of the <form> element */ children: PropTypes.node, /** * Provide a custom className to be applied on the containing <form> node */ className: PropTypes.string, }; export default FluidForm;
docs/app/Examples/elements/Label/Types/LabelExamplePointingColored.js
ben174/Semantic-UI-React
import React from 'react' import { Divider, Form, Label } from 'semantic-ui-react' const LabelExamplePointing = () => ( <Form> <Form.Field> <input type='text' placeholder='First name' /> <Label basic color='red' pointing>Please enter a value</Label> </Form.Field> <Divider /> <Form.Field> <Label basic color='red' pointing='below'>Please enter a value</Label> <input type='text' placeholder='Last Name' /> </Form.Field> <Divider /> <Form.Field inline> <input type='text' placeholder='Username' /> <Label basic color='red' pointing='left'>That name is taken!</Label> </Form.Field> <Divider /> <Form.Field inline> <Label basic color='red' pointing='right'>Your password must be 6 characters or more</Label> <input type='password' placeholder='Password' /> </Form.Field> </Form> ) export default LabelExamplePointing
node_modules/react-bootstrap/es/Tabs.js
GregSantulli/react-drum-sequencer
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import requiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import uncontrollable from 'uncontrollable'; import Nav from './Nav'; import NavItem from './NavItem'; import UncontrolledTabContainer from './TabContainer'; import TabContent from './TabContent'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; import ValidComponentChildren from './utils/ValidComponentChildren'; var TabContainer = UncontrolledTabContainer.ControlledComponent; var propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: React.PropTypes.any, /** * Navigation style */ bsStyle: React.PropTypes.oneOf(['tabs', 'pills']), animation: React.PropTypes.bool, id: requiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: React.PropTypes.func, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: React.PropTypes.bool }; var defaultProps = { bsStyle: 'tabs', animation: true, unmountOnExit: false }; function getDefaultActiveKey(children) { var defaultActiveKey = void 0; ValidComponentChildren.forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var Tabs = function (_React$Component) { _inherits(Tabs, _React$Component); function Tabs() { _classCallCheck(this, Tabs); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tabs.prototype.renderTab = function renderTab(child) { var _child$props = child.props; var title = _child$props.title; var eventKey = _child$props.eventKey; var disabled = _child$props.disabled; var tabClassName = _child$props.tabClassName; if (title == null) { return null; } return React.createElement( NavItem, { eventKey: eventKey, disabled: disabled, className: tabClassName }, title ); }; Tabs.prototype.render = function render() { var _props = this.props; var id = _props.id; var onSelect = _props.onSelect; var animation = _props.animation; var unmountOnExit = _props.unmountOnExit; var bsClass = _props.bsClass; var className = _props.className; var style = _props.style; var children = _props.children; var _props$activeKey = _props.activeKey; var activeKey = _props$activeKey === undefined ? getDefaultActiveKey(children) : _props$activeKey; var props = _objectWithoutProperties(_props, ['id', 'onSelect', 'animation', 'unmountOnExit', 'bsClass', 'className', 'style', 'children', 'activeKey']); return React.createElement( TabContainer, { id: id, activeKey: activeKey, onSelect: onSelect, className: className, style: style }, React.createElement( 'div', null, React.createElement( Nav, _extends({}, props, { role: 'tablist' }), ValidComponentChildren.map(children, this.renderTab) ), React.createElement( TabContent, { bsClass: bsClass, animation: animation, unmountOnExit: unmountOnExit }, children ) ) ); }; return Tabs; }(React.Component); Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; setBsClass('tab', Tabs); export default uncontrollable(Tabs, { activeKey: 'onSelect' });
src/public/js/repository.js
TooAngel/democratic-collaboration
import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../static/css/repository.module.css'; /** * Repository class **/ export class Repository extends React.Component { // eslint-disable-line no-unused-vars /** * contructor - The constructor * * @param {object} props - The properties * @return {void} **/ constructor(props) { super(props); } /** * render - renders * @return {object} - The element to be renderd **/ render() { let content = <div className={styles.content}></div>; if (this.props.repository) { content = <div className={styles.content}> <a href={this.props.repository.html_url}><h1>{this.props.repository.full_name}</h1></a> <div>{this.props.repository.description}</div> </div>; } return content; } } Repository.propTypes = { repository: PropTypes.object, };
client/src/app/main/dashboard/dashboard-edit-profile/dashboard-edit-profile-page.js
opensupports/opensupports
import React from 'react'; import {connect} from 'react-redux'; import _ from 'lodash'; import API from 'lib-app/api-call'; import i18n from 'lib-app/i18n'; import { getCustomFieldParamName } from 'lib-core/APIUtils'; import SessionActions from 'actions/session-actions'; import AreYouSure from 'app-components/are-you-sure'; import Header from 'core-components/header'; import Form from 'core-components/form'; import FormField from 'core-components/form-field'; import SubmitButton from 'core-components/submit-button'; import Message from 'core-components/message'; class DashboardEditProfilePage extends React.Component { static propTypes = { userCustomFields: React.PropTypes.object, }; static defaultProps = { userCustomFields: {}, }; state = { loadingEmail: false, loadingPass: false, messageEmail: '', messagePass: '', customFields: [], customFieldsFrom: {}, loadingCustomFields: false, showChangeEmailMessage: true, showChangePasswordMessage: true }; componentDidMount() { this.retrieveCustomFields(); } render() { return ( <div className="edit-profile-page"> <Header title={i18n('EDIT_PROFILE')} description={i18n('EDIT_PROFILE_VIEW_DESCRIPTION')} /> {this.renderEditEmail()} {this.renderEditPassword()} {this.state.customFields.length ? this.renderCustomFields() : null} </div> ); } renderEditEmail() { return ( <div className="edit-profile-page__edit-email"> <span className="separator" /> <div className="edit-profile-page__title">{i18n('EDIT_EMAIL')}</div> <Form loading={this.state.loadingEmail} onSubmit={this.onSubmitEditEmail.bind(this)}> <div className="edit-profile-page__change-email-container"> <FormField name="newEmail" label={i18n('NEW_EMAIL')} field="input" validation="EMAIL" fieldProps={{size: 'large'}} required /> <SubmitButton type="secondary">{i18n('CHANGE_EMAIL')}</SubmitButton> </div> {this.renderMessageEmail()} </Form> </div> ); } renderEditPassword() { return ( <div className="edit-profile-page__edit-password"> <span className="separator" /> <div className="edit-profile-page__title">{i18n('EDIT_PASSWORD')}</div> <Form loading={this.state.loadingPass} onSubmit={this.onSubmitEditPassword.bind(this)}> <div className="edit-profile-page__change-password-container"> <div className="edit-profile-page__change-password-form-fields"> <FormField name="oldPassword" label={i18n('OLD_PASSWORD')} field="input" validation="PASSWORD" fieldProps={{password: true, size: 'large'}} required /> <FormField name="password" label={i18n('NEW_PASSWORD')} field="input" validation="PASSWORD" fieldProps={{password: true, size: 'large'}} required /> <FormField name="repeatNewPassword" label={i18n('REPEAT_NEW_PASSWORD')} field="input" validation="REPEAT_PASSWORD" fieldProps={{password: true, size: 'large'}} required /> </div> <SubmitButton type="secondary">{i18n('CHANGE_PASSWORD')}</SubmitButton> </div> {this.renderMessagePass()} </Form> </div> ); } renderCustomFields() { const { loadingCustomFields, customFieldsFrom, customFields } = this.state; return ( <div className="edit-profile-page__edit-custom-field"> <span className="separator" /> <div className="edit-profile-page__title">{i18n('ADDITIONAL_FIELDS')}</div> <Form className="edit-profile-page__edit-custom-field-form" loading={loadingCustomFields} values={customFieldsFrom} onChange={form => this.setState({customFieldsFrom: form})} onSubmit={this.onCustomFieldsSubmit.bind(this)}> <div className="edit-profile-page__custom-fields"> {customFields.map(this.renderCustomField.bind(this))} </div> <div className="edit-profile-page__update-custom-fields-button-container"> <SubmitButton className="edit-profile-page__update-custom-fields-button" type="secondary">{i18n('UPDATE_CUSTOM_FIELDS')}</SubmitButton> </div> </Form> </div> ); } renderCustomField(customField, key) { const { type, name, description, options } = customField; if(type === 'text') { return ( <div className="edit-profile-page__custom-field" key={key}> <FormField name={name} label={name} infoMessage={description} field="input" fieldProps={{size: 'small'}} /> </div> ); } else { const items = options.map(option => ({content: option.name, value: option.name})); return ( <div className="edit-profile-page__custom-field" key={key}> <FormField name={name} label={name} infoMessage={description} field="select" fieldProps={{size: 'small', items}} /> </div> ); } } renderMessageEmail() { const { messageEmail, showChangeEmailMessage } = this.state; switch (messageEmail) { case 'success': return ( <Message showMessage={showChangeEmailMessage} onCloseMessage={this.onCloseMessage.bind(this, "showChangeEmailMessage")} className="edit-profile-page__message" type="success"> {i18n('EMAIL_CHANGED')} </Message> ); case 'fail': return ( <Message showMessage={showChangeEmailMessage} onCloseMessage={this.onCloseMessage.bind(this, "showChangeEmailMessage")} className="edit-profile-page__message" type="error"> {i18n('EMAIL_EXISTS')} </Message> ); default: return null; } } renderMessagePass() { const { messagePass, showChangePasswordMessage } = this.state; switch (messagePass) { case 'success': return ( <Message showMessage={showChangePasswordMessage} onCloseMessage={this.onCloseMessage.bind(this, "showChangePasswordMessage")} className="edit-profile-page__message" type="success"> {i18n('PASSWORD_CHANGED')} </Message> ); case 'fail': return ( <Message showMessage={showChangePasswordMessage} onCloseMessage={this.onCloseMessage.bind(this, "showChangePasswordMessage")} className="edit-profile-page__message" type="error"> {i18n('OLD_PASSWORD_INCORRECT')} </Message> ); default: return null; } } onCustomFieldsSubmit(form) { const {customFields} = this.state; const parsedFrom = {}; customFields.forEach(customField => { const { type, name, options } = customField; if(type === 'select') { parsedFrom[getCustomFieldParamName(name)] = options[form[name]].name; } else { parsedFrom[getCustomFieldParamName(name)] = form[name]; } }); this.setState({ loadingCustomFields: true, }); API.call({ path: '/user/edit-custom-fields', data: parsedFrom }).then(() => { this.setState({loadingCustomFields: false}); this.props.dispatch(SessionActions.getUserData()); }); } onSubmitEditEmail(formState) { AreYouSure.openModal(i18n('EMAIL_WILL_CHANGE'), this.callEditEmailAPI.bind(this, formState)); } onSubmitEditPassword(formState) { AreYouSure.openModal(i18n('PASSWORD_WILL_CHANGE'), this.callEditPassAPI.bind(this, formState)); } callEditEmailAPI(formState){ this.setState({ loadingEmail: true }); return API.call({ path: "/user/edit-email", data: { newEmail: formState.newEmail } }).then(function () { this.setState({ loadingEmail: false, messageEmail: "success", showChangeEmailMessage: true }); }.bind(this)).catch(function (){ this.setState({ loadingEmail: false, messageEmail: 'fail', showChangeEmailMessage: true }) }.bind(this)); } callEditPassAPI(formState){ this.setState({ loadingPass: true }); return API.call({ path: "/user/edit-password", data: { oldPassword: formState.oldPassword, newPassword: formState.password } }).then(function () { this.setState({ loadingPass: false, messagePass: "success", showChangePasswordMessage: true }); }.bind(this)).catch(function (){ this.setState({ loadingPass: false, messagePass: 'fail', showChangePasswordMessage: true }) }.bind(this)); } retrieveCustomFields() { API.call({ path: '/system/get-custom-fields', data: {} }) .then(result => { const customFieldsFrom = {}; const {userCustomFields} = this.props; result.data.forEach(customField => { const { type, name, options } = customField; if(type === 'select') { const index = _.indexOf(options.map(option => option.name), userCustomFields[name]); customFieldsFrom[name] = ((index === -1) ? 0 : index); } else { customFieldsFrom[name] = userCustomFields[name] || ''; } }); this.setState({ customFields: result.data, customFieldsFrom, }); }); } onCloseMessage(showMessage) { this.setState({ [showMessage]: false }); } } export default connect((store) => { const userCustomFields = {}; store.session.userCustomFields.forEach(customField => { userCustomFields[customField.customfield] = customField.value; }); return { userCustomFields: userCustomFields || {}, }; })(DashboardEditProfilePage);
definitions/npm/radium_v0.19.x/test_radium-v0.19.x.js
davidohayon669/flow-typed
// @flow import React from 'react'; import Radium from 'radium'; import type { FunctionComponent } from 'radium' type Props1 = { a: number, b: string }; const C1: FunctionComponent<Props1, void> = (props: Props1) => <div>{props.a} {props.b}</div> type Props2 = { a: number, b: string, }; class C2 extends React.Component<void, Props2, void> { render () { return <div>{this.props.a} {this.props.b}</div> } } Radium(<div/>); Radium(<Radium.StyleRoot/>); Radium.keyframes({}); // $ExpectError Radium.keyframes(); // missing object Radium.getState({}, 'ref', ':hover'); // $ExpectError Radium.getState({}, 'ref', ':visible') // invalid property const RC1 = Radium(C1); <RC1 a={1} b="s" />; // $ExpectError <RC1 />; // missing a, b // $ExpectError <RC1 a={1} />; // missing b // $ExpectError <RC1 a="s" b="s" />; // wrong a type const RC2 = Radium(C2); <RC2 a={1} b="s" />; // $ExpectError <RC2 />; // missing a, b // $ExpectError <RC2 a={1} />; // missing b // $ExpectError <RC2 a="s" b="s" />; // wrong a type const ConfiguredRadium = Radium({ userAgent: 'foo' }) const CRC1 = ConfiguredRadium(C1); <CRC1 a={1} b="s" />; // $ExpectError <CRC1 />; // missing a, b // $ExpectError <CRC1 a={1} />; // missing b // $ExpectError <CRC1 a="s" b="s" />; // wrong a type const CRC2 = ConfiguredRadium(C2); <CRC2 a={1} b="s" />; // $ExpectError <CRC2 />; // missing a, b // $ExpectError <CRC2 a={1} />; // missing b // $ExpectError <CRC2 a="s" b="s" />; // wrong a type
templates/rubix/demo/src/routes/Maps.js
jeffthemaximum/jeffline
import React from 'react'; import { Row, Col, Grid, Form, Panel, Button, FormGroup, PanelBody, InputGroup, FormControl, PanelHeader, PanelContainer, } from '@sketchpixy/rubix'; class MapContainer extends React.Component { render() { return ( <PanelContainer> <Panel> <PanelBody style={{padding: 25}}> <h4 className='text-center' style={{marginTop: 0}}>{this.props.name}</h4> {this.props.children} <div id={this.props.id} style={{height: 300}}></div> </PanelBody> </Panel> </PanelContainer> ); } } export default class Maps extends React.Component { constructor(props) { super(props); this.geocode = null; this.routingmap = null; this.state = { routeslist: [] }; } geoCode(address) { GMaps.geocode({ address: address, callback: (results, status) => { if (status == 'OK') { var latlng = results[0].geometry.location; this.geocode.setCenter(latlng.lat(), latlng.lng()); this.geocode.addMarker({ lat: latlng.lat(), lng: latlng.lng(), infoWindow: { content: '<div><strong>Address:</strong> '+results[0].formatted_address+'</div>' } }); } } }); } componentDidMount() { (() => { new GMaps({ scrollwheel: false, div: '#basic-map', lat: -12.043333, lng: -77.028333 }); })(); (() => { new GMaps({ scrollwheel: false, div: '#map-events', zoom: 16, lat: -12.043333, lng: -77.028333, click: (e) => { alert('click'); }, dragend: (e) => { alert('dragend'); } }); })(); (() => { var map = new GMaps({ scrollwheel: false, div: '#markers', zoom: 16, lat: -12.043333, lng: -77.028333 }); map.addMarker({ lat: -12.043333, lng: -77.028333, title: 'Lima', click: (e) => { alert('You clicked in this marker'); } }); map.addMarker({ lat: -12.043333, lng: -77.029333, title: 'Lima', infoWindow: { content: '<p>Some content here!</p>' } }); })(); (() => { this.geocode = new GMaps({ scrollwheel: false, div: '#geocode', zoom: 16, lat: -12.043333, lng: -77.028333 }); this.geoCode('New York, NY, USA'); })(); (() => { var map = new GMaps({ scrollwheel: false, div: '#polyline', zoom: 12, lat: -12.043333, lng: -77.028333 }); var path = [[-12.044012922866312, -77.02470665341184], [-12.05449279282314, -77.03024273281858], [-12.055122327623378, -77.03039293652341], [-12.075917129727586, -77.02764635449216], [-12.07635776902266, -77.02792530422971], [-12.076819390363665, -77.02893381481931], [-12.088527520066453, -77.0241058385925], [-12.090814532191756, -77.02271108990476]]; map.drawPolyline({ path: path, strokeColor: '#FF0080', strokeOpacity: 0.75, strokeWeight: 8 }); })(); (() => { var map = new GMaps({ scrollwheel: false, div: '#overlays', zoom: 18, lat: 40.7638435, lng: -73.9729691 }); map.drawOverlay({ lat: 40.7640135, lng: -73.9729691, content: '<div class="overlay">Apple Store, NY, USA<div class="overlay_arrow above"></div></div>' }); })(); (() => { var map = new GMaps({ scrollwheel: false, div: '#polygon', lat: -12.043333, lng: -77.028333 }); var path = [[-12.040397656836609,-77.03373871559225], [-12.040248585302038,-77.03993927003302], [-12.050047116528843,-77.02448169303511], [-12.044804866577001,-77.02154422636042]]; var polygon = map.drawPolygon({ paths: path, // pre-defined polygon shape strokeColor: '#D71F4B', strokeOpacity: 1, strokeWeight: 3, fillColor: '#D71F4B', fillOpacity: 0.6 }); })(); (() => { var map = new GMaps({ scrollwheel: false, div: '#geojson', lat: 39.743296277167325, lng: -105.00517845153809 }); var paths = [ [ [ [-105.00432014465332, 39.74732195489861], [-105.00715255737305, 39.74620006835170], [-105.00921249389647, 39.74468219277038], [-105.01067161560059, 39.74362625960105], [-105.01195907592773, 39.74290029616054], [-105.00989913940431, 39.74078835902781], [-105.00758171081543, 39.74059036160317], [-105.00346183776855, 39.74059036160317], [-105.00097274780272, 39.74059036160317], [-105.00062942504881, 39.74072235994946], [-105.00020027160645, 39.74191033368865], [-105.00071525573731, 39.74276830198601], [-105.00097274780272, 39.74369225589818], [-105.00097274780272, 39.74461619742136], [-105.00123023986816, 39.74534214278395], [-105.00183105468751, 39.74613407445653], [-105.00432014465332, 39.74732195489861] ],[ [-105.00361204147337, 39.74354376414072], [-105.00301122665405, 39.74278480127163], [-105.00221729278564, 39.74316428375108], [-105.00283956527711, 39.74390674342741], [-105.00361204147337, 39.74354376414072] ] ],[ [ [-105.00942707061768, 39.73989736613708], [-105.00942707061768, 39.73910536278566], [-105.00685214996338, 39.73923736397631], [-105.00384807586671, 39.73910536278566], [-105.00174522399902, 39.73903936209552], [-105.00041484832764, 39.73910536278566], [-105.00041484832764, 39.73979836621592], [-105.00535011291504, 39.73986436617916], [-105.00942707061768, 39.73989736613708] ] ] ]; var polygon = map.drawPolygon({ paths: paths, useGeoJSON: true, strokeColor: '#2EB398', strokeOpacity: 1, strokeWeight: 3, fillColor: '#2EB398', fillOpacity: 0.6 }); })(); (() => { this.routingmap = new GMaps({ scrollwheel: false, div: '#routingmap', lat: -12.043333, lng: -77.028333 }); })(); } handleSubmit(e) { e.preventDefault(); e.stopPropagation(); this.geoCode($('#address').val()); } startRouting(e) { e.preventDefault(); e.stopPropagation(); this.setState({ routeslist: [] }, () => { var map = this.routingmap; var list = []; map.travelRoute({ origin: [-12.044012922866312, -77.02470665341184], destination: [-12.090814532191756, -77.02271108990476], travelMode: 'driving', step: (e) => { list.push({ instructions: e.instructions, lat: e.end_location.lat(), lng: e.end_location.lng(), path: e.path }); }, end: (e) => { var lat, lng, path; var processList = (i) => { if(list.length === i) return; lat = list[i].lat; lng = list[i].lng; path = list[i].path; setTimeout(() => { this.setState({ routeslist: list.slice(0, i+1) }); map.setCenter(lat, lng); map.drawPolyline({ path: path, strokeColor: '#FF6FCF', strokeWeight: 8 }); processList(i+1); }, 500); }; processList(0); } }); }); } render() { return ( <div> <Row> <Col sm={6} collapseRight> <MapContainer id='basic-map' name='Basic Map' /> <MapContainer id='markers' name='Map Markers' /> <MapContainer id='polyline' name='Polylines' /> <MapContainer id='polygon' name='Polygon' /> </Col> <Col sm={6}> <MapContainer id='map-events' name='Map Events' /> <MapContainer id='geocode' name='Geocoding'> <Form onSubmit={::this.handleSubmit}> <FormGroup> <InputGroup> <FormControl type='text' id='address' placeholder='Address' defaultValue='New York, NY, USA' /> <InputGroup.Button className='plain'> <Button outlined onlyOnHover type='submit' bsStyle='darkgreen45'>search</Button> </InputGroup.Button> </InputGroup> </FormGroup> </Form> </MapContainer> <MapContainer id='overlays' name='Overlays' /> <MapContainer id='geojson' name='GeoJSON Polygon' /> </Col> </Row> <Row> <Col xs={12}> <PanelContainer> <Panel> <PanelBody style={{padding: 25}}> <Grid> <Row> <Col xs={12} sm={6} collapseLeft> <div id='routingmap' style={{height: 300}}></div> </Col> <Col xs={12} sm={6} collapseRight> <hr className='visible-xs' /> <div className='text-center' style={{paddingBottom: 25}}> <Button outlined onlyOnHover type='button' bsStyle='darkgreen45' onClick={::this.startRouting}>Start routing</Button> </div> <div> <ul> {this.state.routeslist.map(function(route, i) { return (<li key={i} dangerouslySetInnerHTML={{__html: route.instructions}}></li>); })} </ul> </div> </Col> </Row> </Grid> </PanelBody> </Panel> </PanelContainer> </Col> </Row> </div> ); } }
src/components/general/Input.js
katima-g33k/blu-react-desktop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Col, ControlLabel, FormControl, FormGroup, } from 'react-bootstrap'; const styles = { label: { marginTop: '7px', textAlign: 'right', }, }; const types = { EMAIL: 'email', PHONE: 'phone', NUMBER: 'number', PASSWORD: 'password', TEXT: 'text', }; export default class Input extends Component { static propTypes = { data: PropTypes.shape(), disabled: PropTypes.bool, id: PropTypes.string, inputWidth: PropTypes.shape(), isValid: PropTypes.bool, label: PropTypes.string, labelWidth: PropTypes.shape(), onChange: PropTypes.func.isRequired, placeholder: PropTypes.string, required: PropTypes.bool, style: PropTypes.shape(), type: PropTypes.oneOf(Object.values(types)), value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; static defaultProps = { data: {}, disabled: false, id: '', inputWidth: { md: 9, sm: 10 }, isValid: true, label: '', labelWidth: { md: 3, sm: 2 }, placeholder: '', required: false, style: {}, type: types.TEXT, value: '', }; static TYPES = types; onChange = event => this.props.onChange(event, event.target.value); getDataAttributes = () => Object.keys(this.props.data).reduce((acc, cur) => ({ ...acc, [`data-${cur}`]: this.props.data[cur], }), {}); renderLabel = () => this.props.label && ( <Col {...this.props.labelWidth} componentClass={ControlLabel} style={styles.label} > {this.props.label}{this.props.required && '*'} </Col> ); render() { return ( <FormGroup style={this.props.style} validationState={!this.props.isValid ? 'error' : null} > {this.renderLabel()} <Col {...this.props.inputWidth}> <FormControl {...this.getDataAttributes()} disabled={this.props.disabled} id={this.props.id} onChange={this.onChange} placeholder={this.props.placeholder} type={this.props.type} value={this.props.value} /> <FormControl.Feedback /> </Col> </FormGroup> ); } }
imports/components/Toaster.js
naustudio/nau-jukebox
/* © 2017 NauStud.io * @author Eric */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Toaster extends Component { static propTypes = { open: PropTypes.bool, text: PropTypes.string, time: PropTypes.number, type: PropTypes.oneOf(['success', 'error']), onClose: PropTypes.func.isRequired, }; static defaultProps = { open: false, text: 'Toaster', time: 3000, type: 'success', }; componentWillReceiveProps(nextProps) { if (nextProps.open !== this.props.open && nextProps.open) { clearTimeout(this.timeout); if (nextProps.type === 'success') { this.timeout = setTimeout(() => { this.props.onClose(); }, this.props.time); } } } timeout; render() { const { open, text, type, onClose } = this.props; return ( <div className={`toaster ${open ? 'toaster--open' : ''} toaster--${type}`} onClick={onClose}> <span>{text}</span> </div> ); } } export default Toaster;