path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/Animations/intro-animation.js
adrienhobbs/redux-glow
import React, { Component } from 'react'; import styles from './intro-animation.scss'; export default class IntroAnimation extends Component { constructor (props) { super(props); this.state = { hasPlayed: false }; this.TL = new TimelineMax(); this.TL.pause(); } animate () { var TL = new TimelineMax(); // // settings for 'we are' animation const weAreVars = { y: -60.5, ease: Back.easeOut.config(3.4), dur: 0.35, staggerDur: 0.08 }; // // Settings for 'GLOW' animation const glowVars = { x: 0, ease: Quart.easeOut, dur: 0.7 }; TL.staggerTo(this.refs.weAreGroup.children, weAreVars.dur, weAreVars, weAreVars.staggerDur) .to(this.refs.glowGroup.children[3], glowVars.dur, glowVars, '+=0.05') .to(this.refs.glowGroup.children[2], glowVars.dur, glowVars, '-=0.6') .to(this.refs.glowGroup.children[1], glowVars.dur, glowVars, '-=0.55') .to(this.refs.glowGroup.children[0], glowVars.dur, glowVars, '-=0.525') .to(this.refs.introAnimation, 0.8, {autoAlpha: 0, display: 'none', onComplete: () => this.setState({hasPlayed: true})}, '+=1.8') .set('#intro-animation', {display: 'none'}); } componentDidMount () { this.animate(); } render () { return ( <div className={styles.introAnimation} ref='introAnimation'> <div className={styles.introAnimationInner}> <svg fill='white' id='we_are_glow' className={styles.weAreGlowSvg} ref='svg' viewBox='0 0 500.3 60.5'> <g id='glow' ref='glowGroup'> <path transform='translate(-255)' id='glow_g' className={styles.cls1} d='M291.8,27.3h26.7V38.5c-2.1,13.2-12,22.1-28.9,22.1-19.7,0-30.6-13.8-30.6-30.2C259,14.7,270.2.2,289.5,0.2c16.6,0,27.4,9.8,28.5,21.5H299.2c-0.6-3.3-3.8-6.9-9.8-6.9-9.2,0-12.9,7.8-12.9,15.9,0,8.9,4.6,16,14,16,6.4,0,10-3.6,10.8-8.1h-9.5V27.3h0Z'/> <path transform='translate(-255)' id='glow_l' className={styles.cls1} d='M354.7,44.5V59.1h-32V1.8h17V44.6h15V44.5Z'/> <path id='glow_o' className={styles.cls1} d='M354.3,30.4c0-15.8,11.4-30.2,31.1-30.2s31.1,14.4,31.1,30.2-11.4,30.2-31.1,30.2S354.3,46.2,354.3,30.4Zm44.9,0c0-7.6-5.1-14.7-13.8-14.7s-13.8,7-13.8,14.7,5.2,14.7,13.8,14.7C394.2,45.1,399.2,38.1,399.2,30.4Z' transform='translate(-255, 0)'/> <path id='glow_w' className={styles.cls1} d='M455.3,27.9l-9.6,31.2H430.9L410.2,1.8h18L438.4,36,448.5,1.8h13.6l10,34.2L482.3,1.8h18L479.7,59.2H464.8Z' transform='translate(-255, 0)'/> </g> <rect id='we_are_mask' className={styles.cls2} width='248' height='62.5' transform='translate(0)'/> <g id='we_are' ref='weAreGroup' transform='translate(0, 60.5)'> <path id='we_are_w' className={styles.cls1} d='M34.7,34.35l-8.1,25.2H16.4L1.7,20H14.6l7.3,23.5,7-23.5H40.5l7,23.5L54.7,20h13L52.9,59.55H42.7Z' transform='translate(0 -0.15)'/> <path id='we_are_e' className={styles.cls1} d='M76.8,42.85c0.2,4.8,2.2,8.8,8.8,8.8,4.3,0,6.5-2,7.3-4.5h12.3c-1.1,7.5-8.2,13.5-19.5,13.5-13.8,0-21.3-8.6-21.3-20.8,0-11.6,7.3-20.8,21-20.8,12.4,0,20.3,8.4,20.3,18a32.45,32.45,0,0,1-.4,5.8H76.8Zm0-7.2H93.3c0-5.1-3.4-8.3-8.1-8.3S76.8,30.25,76.8,35.65Z' transform='translate(0 -0.15)'/> <path id='we_are_a' className={styles.cls1} d='M167.3,20v39.5H154.8v-5.6c-1.9,3.6-7,6.6-12,6.6-11.4,0-19.3-8.9-19.3-20.7s7.9-20.7,19.3-20.7c5.1,0,10.2,3,12,6.6V20h12.5Zm-12.5,19.7c0-5.4-3.8-10.1-9.4-10.1s-9.4,4.7-9.4,10.1,3.8,10.1,9.4,10.1S154.8,45.25,154.8,39.75Z' transform='translate(0 -0.15)'/> <path id='we_are_r' className={styles.cls1} d='M200.6,31.45a16.66,16.66,0,0,0-4.4-.6c-6.9,0-11.4,3.6-11.4,13.3v15.4H172.3V20h12.4v6.4c1.8-3.7,6.6-7,12-7a8.9,8.9,0,0,1,3.8.7v11.3h0.1Z' transform='translate(0 -0.15)'/> <path id='we_are_e_two' className={styles.cls1} d='M213,42.85c0.2,4.8,2.2,8.8,8.8,8.8,4.3,0,6.5-2,7.3-4.5h12.3c-1.1,7.5-8.2,13.5-19.5,13.5-13.8,0-21.3-8.6-21.3-20.8,0-11.6,7.3-20.8,21-20.8,12.4,0,20.3,8.4,20.3,18a32.45,32.45,0,0,1-.4,5.8H213Zm0-7.2h16.6c0-5.1-3.4-8.3-8.1-8.3C216.5,27.35,213,30.25,213,35.65Z' transform='translate(0 -0.15)'/> </g> </svg> </div> </div> ); } }
src/styleguide/Wrapper.js
mariusespejo/semantic-redux-form-fields
import React, { Component } from 'react'; const Provider = require('react-redux').Provider; const configureStore = require('../utils/configureStore').default; const store = configureStore({}); export default class Wrapper extends Component { render() { return <Provider store={store}>{this.props.children}</Provider>; } }
src/pages/404.js
kbrgl/kbrgl.github.io
import React from 'react' import { Link } from 'gatsby' import { Row, Column } from '../components/grid' import Layout from '../components/layout' const IndexPage = () => ( <Layout> <Row> <Column size="six" offset="three"> <h1 style={{ marginTop: '4rem' }}>Not Found.</h1> <p> Whatever you’re looking for wasn’t found, but you can always{' '} <Link to="/">go home</Link>. </p> </Column> </Row> </Layout> ) export default IndexPage
DEPRECATED/node_modules/react-router/es6/IndexRoute.js
vanHeemstraDesigns/CreationsEcosystemStatic
'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React, { Component } from 'react'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './PropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = (function (_Component) { _inherits(IndexRoute, _Component); function IndexRoute() { _classCallCheck(this, IndexRoute); _Component.apply(this, arguments); } /* istanbul ignore next: sanity check */ IndexRoute.prototype.render = function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; }; return IndexRoute; })(Component); IndexRoute.propTypes = { path: falsy, component: component, components: components, getComponent: func, getComponents: func }; IndexRoute.createRouteFromReactElement = function (element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : undefined; } }; export default IndexRoute;
react-redux-tutorial/redux-examples/shopping-cart/index.js
react-scott/react-learn
import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware,compose } from 'redux' import { Provider } from 'react-redux' import logger from 'redux-logger' import thunk from 'redux-thunk' import reducer from './reducers' import { getAllProducts } from './actions' import App from './containers/App' const middleware = process.env.NODE_ENV === 'production' ? [ thunk ] : [ thunk, logger() ] const createStoreWithMiddleware = compose(applyMiddleware(...middleware), window.devToolsExtension ? window.devToolsExtension() : f => f)(createStore) const store = createStoreWithMiddleware(reducer) store.dispatch(getAllProducts()) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
react-starter/examples/UnigridExample5.js
yoonka/unigrid
/* Copyright (c) 2018, Grzegorz Junka All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import React from 'react'; import {tableData} from './data/Resp1'; import { Unigrid, UnigridHeader, UnigridSegment, UnigridFooter, UnigridRow, UnigridEmptyCell, UnigridTextCell } from '../unigrid'; export class UnigridExample5 extends React.Component { constructor() { super(); this.idCounter = () => { var counter = 0; return () => counter += 1; } } handleClick() { console.log(this.props.item); } render() { const cellTypes = { empty: UnigridEmptyCell, string: UnigridTextCell }; return ( <div> <p>Example 5 : Multitable (JSX - specialized components)</p> <Unigrid data={tableData} cellTypes={cellTypes}> <Unigrid className={'unigrid-main-class'}> <UnigridHeader className={'unigrid-header'}> <UnigridRow rowAs={'header'}> <UnigridTextCell show="hAgent" /> <UnigridTextCell show="hDate" /> <UnigridTextCell show="hStreet" /> <UnigridTextCell show="hName" className={'name-header-cell'} /> <UnigridTextCell show="hNumber" /> </UnigridRow> </UnigridHeader> </Unigrid> <Unigrid select={'all'}> <UnigridSegment className={'unigrid-segment'}> <Unigrid condition={{ ifDoes: 'exist', property: 'list' }} fromProperty={'list'} select={0}> <UnigridRow rowAs={'header'}> <UnigridTextCell show={'hCategory'} /> <UnigridEmptyCell colSpan={3} /> <UnigridTextCell show={'hNumber'} /> </UnigridRow> </Unigrid> <Unigrid condition={{ ifDoes: 'exist', property: 'list' }} fromProperty={'list'}> <UnigridRow rowAs={'header'}> <UnigridTextCell cell={'category2'} /> <UnigridEmptyCell colSpan={3} /> <UnigridTextCell show={'hNumber'} /> </UnigridRow> </Unigrid> <UnigridRow className={'some-row-class'}> <UnigridTextCell show="agent" /> <UnigridTextCell show="date" /> <UnigridTextCell show="street" /> <UnigridTextCell show="name" /> <UnigridTextCell show={'number'} className={'number-cell'} onClick={this.handleClick} bindToCell={['onClick']} /> </UnigridRow> <Unigrid condition={{ ifDoes: 'exist', property: 'list' }} fromProperty={'list'} select={'all'} > <UnigridRow mixIn={{ onClick: this.handleClick, bindToCell: 'onClick' }}> <UnigridEmptyCell colSpan={3} /> <UnigridTextCell show={'name'} /> <UnigridTextCell show={'number'} /> </UnigridRow> </Unigrid> </UnigridSegment> </Unigrid> <UnigridFooter className={'unigrid-footer'}> <Unigrid select={0}> <Unigrid cells={[null, null, null, 'fSum', 'fTotal']} /> <Unigrid cells={[null, null, null, 'sum', 'total']} /> </Unigrid> </UnigridFooter> </Unigrid> </div> ); } }
src/containers/FuelSavingsPage.js
ryan4888/smart-toy
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../actions/fuelSavingsActions'; import FuelSavingsForm from '../components/FuelSavingsForm'; export const FuelSavingsPage = (props) => { return ( <FuelSavingsForm saveFuelSavings={props.actions.saveFuelSavings} calculateFuelSavings={props.actions.calculateFuelSavings} fuelSavings={props.fuelSavings} /> ); }; FuelSavingsPage.propTypes = { actions: PropTypes.object.isRequired, fuelSavings: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavings: state.fuelSavings }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(FuelSavingsPage);
app/scripts/components/kuchyne/kitchen_b.js
kroupaTomass/Rondo-kuchyne
import React from 'react'; import { Link } from 'react-router'; class Kitchen_b extends React.Component { constructor(props, context) { super(props); } render() { return ( <div className="col-md-4 no_padding"> <div className="single_image"> <a id="kitchen_b" href="#animatedModal_b"><img src="images/kitchen/img/02/01.jpg" alt="" /></a> </div> <div id="animatedModal_b"> <div className="close-animatedModal_b" id="closebt-container"> <img className="closebt" src="images/closebt.svg" /> </div> <div className="modal-content div-kitchen-content"> <h4>Moderní kuchyně</h4> <div className="row"> <div className="col-md-4"> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/01.jpg" alt="" /> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/02.jpg" alt="" /> </div> </div> <div className="row"> <div className="col-md-4"> <img src="images/kitchen/img/02/07.jpg" alt="" /> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/06.jpg" alt="" /> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/05.jpg" alt="" /> </div> </div> <div className="row"> <div className="col-md-4"> <img src="images/kitchen/img/02/08.jpg" alt="" /> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/03.jpg" alt="" /> </div> <div className="col-md-4"> <img src="images/kitchen/img/02/04.jpg" alt="" /> </div> </div> </div> </div> <h2>Kuchyně</h2> <h4>moderní kuchyně</h4> </div> ); } } export default Kitchen_b;
docs/app/Examples/elements/Button/Content/ButtonExampleMultipleConditionals.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleMultipleConditionals = () => ( <Button.Group> <Button>One</Button> <Button.Or /> <Button>Two</Button> <Button.Or /> <Button>Three</Button> </Button.Group> ) export default ButtonExampleMultipleConditionals
src/pages/number/Freivalds/Freivalds.js
hyy1115/react-redux-webpack2
import React from 'react' class Freivalds extends React.Component { render() { return ( <div>Freivalds</div> ) } } export default Freivalds
milestones/05-webpack-intro-css/Before/src/slide.js
jaketrent/react-drift
import PropTypes from 'prop-types' import React from 'react' function Slide(props) { return ( <article style={props.style}> <img src={props.image} alt={props.title} /> <footer> <h2>{props.title}</h2> <div>{props.children}</div> </footer> </article> ) } Slide.propTypes = { image: PropTypes.string.isRequired, style: PropTypes.object, title: PropTypes.string } export default Slide
node_modules/react-bootstrap/es/Tooltip.js
NathanBWaters/jb_club
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
src/svg-icons/action/shopping-basket.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShoppingBasket = (props) => ( <SvgIcon {...props}> <path d="M17.21 9l-4.38-6.56c-.19-.28-.51-.42-.83-.42-.32 0-.64.14-.83.43L6.79 9H2c-.55 0-1 .45-1 1 0 .09.01.18.04.27l2.54 9.27c.23.84 1 1.46 1.92 1.46h13c.92 0 1.69-.62 1.93-1.46l2.54-9.27L23 10c0-.55-.45-1-1-1h-4.79zM9 9l3-4.4L15 9H9zm3 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); ActionShoppingBasket = pure(ActionShoppingBasket); ActionShoppingBasket.displayName = 'ActionShoppingBasket'; ActionShoppingBasket.muiName = 'SvgIcon'; export default ActionShoppingBasket;
src/Upload.js
tanbo800/react-ui
'use strict' import classnames from 'classnames' import React from 'react' import Events from './utils/events' import { nextUid, format } from './utils/strings' import getGrid from './higherorder/grid' import Message from './Message' import upload from './utils/upload' import { requireCss } from './themes' requireCss('upload') import { getLang, setLang } from './lang' setLang('validation', 'buttons') @getGrid export default class Upload extends React.Component { static displayName = 'Upload' static propTypes = { accept: React.PropTypes.string, action: React.PropTypes.string.isRequired, autoUpload: React.PropTypes.bool, className: React.PropTypes.string, content: React.PropTypes.object, cors: React.PropTypes.bool, disabled: React.PropTypes.bool, fileSize: React.PropTypes.number, limit: React.PropTypes.number, name: React.PropTypes.string.isRequired, readOnly: React.PropTypes.bool, style: React.PropTypes.object, withCredentials: React.PropTypes.bool } static defaultProps = { autoUpload: false, cors: true, fileSize: 4096, limit: 1, withCredentials: false } state = { files: {} } isCompleted () { let completed = true, files = this.state.files Object.keys(files).forEach(id => { if (files[id].status !== 2) { completed = false } }) return completed } getValue () { let values = [], files = this.state.files Object.keys(files).forEach(id => { if (this.props.autoUpload) { values.push(files[id].value) } else { values.push(files[id].file.files[0]) } }) return values } // nope setValue() {} addFile () { if (this.props.disabled || this.props.readOnly) { return } let files = this.state.files, file = document.createElement('input'), autoUpload = this.props.autoUpload file.type = 'file' file.accept = this.props.accept file.click() Events.on(file, 'change', () => { let blob = file.files[0] if (blob.size / 1024 > this.props.fileSize) { Message.show(format(getLang('validation.tips.fileSize'), this.props.fileSize), 'error') return } let id = nextUid() files[id] = { file, name: file.files[0].name, status: autoUpload ? 1 : 0 } if (autoUpload) { files[id].xhr = this.uploadFile(file, id) } this.setState({ files }) }) } removeFile (id) { if (this.props.disabled || this.props.readOnly) { return } let files = this.state.files let file = files[id] if (file.xhr) { file.xhr.abort() } delete files[id] this.setState({ files }) } uploadFile (file, id) { return upload({ url: this.props.action, name: this.props.name, cors: this.props.cors, withCredentials: this.props.withCredentials, file: file.files[0], onProgress: (e) => { let progress = React.findDOMNode(this.refs[id]) progress.style.width = (e.loaded / e.total) * 100 + '%' }, onLoad: (e) => { let files = this.state.files files[id].status = 2 files[id].value = e.currentTarget.responseText this.setState({ files }) }, onError: () => { let files = this.state.files files[id].status = 3 this.setState({ files }) } }) } start () { let files = this.state.files Object.keys(files).forEach(id => { this.uploadFile(files[id].file, id) }) } renderFiles () { let files = this.state.files return Object.keys(files).map((id, i) => { let file = this.state.files[id] let className = classnames( `rct-file`, { 'uploaded': file.status === 2, 'has-error': file.status === 3 } ) return ( <div key={i}> <div className={className}> <span>{file.name}</span> <a className="remove" onClick={this.removeFile.bind(this, id)}>&times; {getLang('buttons.cancel')}</a> </div> <div ref={id} className={`rct-upload-progress`}></div> </div> ) }) } render () { let className = classnames( this.getGrid(), `rct-upload-container`, this.props.className ) return ( <div className={className} style={this.props.style}> { Object.keys(this.state.files).length < this.props.limit && <div onClick={this.addFile.bind(this)}>{this.props.content}</div> } { this.renderFiles() } </div> ) } } require('./FormControl').register( 'upload', function (props) { return <Upload {...props} /> }, Upload, 'array' )
src/index.js
wix/react-templates-transform-boilerplate
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; var elem = React.createElement(App); render(elem, document.getElementById('root'));
src/Parser/Paladin/Holy/CombatLogParser.js
enragednuke/WoWAnalyzer
import React from 'react'; import Tab from 'Main/Tab'; import Mana from 'Main/Mana'; import CoreCombatLogParser from 'Parser/Core/CombatLogParser'; import LowHealthHealing from 'Parser/Core/Modules/LowHealthHealing'; import HealingDone from 'Parser/Core/Modules/HealingDone'; import LightOfDawnNormalizer from './Normalizers/LightOfDawn'; import DivinePurposeNormalizer from './Normalizers/DivinePurpose'; import PaladinAbilityTracker from './Modules/PaladinCore/PaladinAbilityTracker'; import BeaconHealOriginMatcher from './Modules/PaladinCore/BeaconHealOriginMatcher'; import BeaconTargets from './Modules/PaladinCore/BeaconTargets'; import BeaconHealing from './Modules/PaladinCore/BeaconHealing'; import CastBehavior from './Modules/PaladinCore/CastBehavior'; import Overhealing from './Modules/PaladinCore/Overhealing'; import FillerLightOfTheMartyrs from './Modules/PaladinCore/FillerLightOfTheMartyrs'; import LightOfDawn from './Modules/PaladinCore/LightOfDawn'; import Abilities from './Modules/Abilities'; import Checklist from './Modules/Features/Checklist'; import MasteryEffectiveness from './Modules/Features/MasteryEffectiveness'; import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting'; import TyrsDeliverance from './Modules/Features/TyrsDeliverance'; import CooldownThroughputTracker from './Modules/Features/CooldownThroughputTracker'; import StatValues from './Modules/Features/StatValues'; import RuleOfLaw from './Modules/Talents/RuleOfLaw'; import DevotionAura from './Modules/Talents/DevotionAura'; import AuraOfSacrifice from './Modules/Talents/AuraOfSacrifice'; import AuraOfMercy from './Modules/Talents/AuraOfMercy'; import HolyAvenger from './Modules/Talents/HolyAvenger'; import DivinePurpose from './Modules/Talents/DivinePurpose'; import CrusadersMight from './Modules/Talents/CrusadersMight'; import JudgmentOfLight from './Modules/Talents/JudgmentOfLight'; import RelicTraits from './Modules/Traits/RelicTraits'; import DeliverTheLight from './Modules/Traits/DeliverTheLight'; import ExpelTheDarkness from './Modules/Traits/ExpelTheDarkness'; import SacredDawn from './Modules/Traits/SacredDawn'; import SecondSunrise from './Modules/Traits/SecondSunrise'; import ShockTreatment from './Modules/Traits/ShockTreatment'; import TyrsMunificence from './Modules/Traits/TyrsMunificence'; import JusticeThroughSacrifice from './Modules/Traits/JusticeThroughSacrifice'; import DrapeOfShame from './Modules/Items/DrapeOfShame'; import Ilterendi from './Modules/Items/Ilterendi'; import ChainOfThrayn from './Modules/Items/ChainOfThrayn'; import ObsidianStoneSpaulders from './Modules/Items/ObsidianStoneSpaulders'; import MaraadsDyingBreath from './Modules/Items/MaraadsDyingBreath'; import SoulOfTheHighlord from './Modules/Items/SoulOfTheHighlord'; import Tier19_4set from './Modules/Items/Tier19_4set'; import Tier20_4set from './Modules/Items/Tier20_4set'; import Tier21_2set from './Modules/Items/Tier21_2set'; import Tier21_4set from './Modules/Items/Tier21_4set'; import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from './Constants'; class CombatLogParser extends CoreCombatLogParser { static abilitiesAffectedByHealingIncreases = ABILITIES_AFFECTED_BY_HEALING_INCREASES; static specModules = { // Normalizers lightOfDawnNormalizer: LightOfDawnNormalizer, divinePurposeNormalizer: DivinePurposeNormalizer, // Override the ability tracker so we also get stats for IoL and beacon healing abilityTracker: PaladinAbilityTracker, lowHealthHealing: LowHealthHealing, // PaladinCore healingDone: [HealingDone, { showStatistic: true }], beaconHealOriginMatcher: BeaconHealOriginMatcher, beaconTargets: BeaconTargets, beaconHealing: BeaconHealing, castBehavior: CastBehavior, overhealing: Overhealing, fillerLightOfTheMartyrs: FillerLightOfTheMartyrs, lightOfDawn: LightOfDawn, // Features checklist: Checklist, abilities: Abilities, masteryEffectiveness: MasteryEffectiveness, alwaysBeCasting: AlwaysBeCasting, tyrsDeliverance: TyrsDeliverance, cooldownThroughputTracker: CooldownThroughputTracker, statValues: StatValues, // Talents ruleOfLaw: RuleOfLaw, devotionAura: DevotionAura, auraOfSacrifice: AuraOfSacrifice, auraOfMercy: AuraOfMercy, holyAvenger: HolyAvenger, divinePurpose: DivinePurpose, crusadersMight: CrusadersMight, judgmentOfLight: JudgmentOfLight, // Traits relicTraits: RelicTraits, deliverTheLight: DeliverTheLight, expelTheDarkness: ExpelTheDarkness, sacredDawn: SacredDawn, secondSunrise: SecondSunrise, shockTreatment: ShockTreatment, tyrsMunificence: TyrsMunificence, justiceThroughSacrifice: JusticeThroughSacrifice, // Items: drapeOfShame: DrapeOfShame, ilterendi: Ilterendi, chainOfThrayn: ChainOfThrayn, obsidianStoneSpaulders: ObsidianStoneSpaulders, maraadsDyingBreath: MaraadsDyingBreath, soulOfTheHighlord: SoulOfTheHighlord, tier19_4set: Tier19_4set, tier20_4set: Tier20_4set, tier21_2set: Tier21_2set, tier21_4set: Tier21_4set, }; generateResults() { const results = super.generateResults(); // TODO: Suggestion for enchants results.tabs = [ ...results.tabs, { title: 'Mana', url: 'mana', render: () => ( <Tab title="Mana" style={{ padding: '15px 22px' }}> <Mana parser={this} /> </Tab> ), }, ]; return results; } } export default CombatLogParser;
src/components/Ellipsis/index.js
zuiidea/antd-admin
import React, { Component } from 'react'; import { Tooltip } from 'antd'; import classNames from 'classnames'; import styles from './index.less'; /* eslint react/no-did-mount-set-state: 0 */ /* eslint no-param-reassign: 0 */ const isSupportLineClamp = document.body.style.webkitLineClamp !== undefined; const TooltipOverlayStyle = { overflowWrap: 'break-word', wordWrap: 'break-word', }; export const getStrFullLength = (str = '') => str.split('').reduce((pre, cur) => { const charCode = cur.charCodeAt(0); if (charCode >= 0 && charCode <= 128) { return pre + 1; } return pre + 2; }, 0); export const cutStrByFullLength = (str = '', maxLength) => { let showLength = 0; return str.split('').reduce((pre, cur) => { const charCode = cur.charCodeAt(0); if (charCode >= 0 && charCode <= 128) { showLength += 1; } else { showLength += 2; } if (showLength <= maxLength) { return pre + cur; } return pre; }, ''); }; const getTooltip = ({ tooltip, overlayStyle, title, children }) => { if (tooltip) { const props = tooltip === true ? { overlayStyle, title } : { ...tooltip, overlayStyle, title }; return <Tooltip {...props}>{children}</Tooltip>; } return children; }; const EllipsisText = ({ text, length, tooltip, fullWidthRecognition, ...other }) => { if (typeof text !== 'string') { throw new Error('Ellipsis children must be string.'); } const textLength = fullWidthRecognition ? getStrFullLength(text) : text.length; if (textLength <= length || length < 0) { return <span {...other}>{text}</span>; } const tail = '...'; let displayText; if (length - tail.length <= 0) { displayText = ''; } else { displayText = fullWidthRecognition ? cutStrByFullLength(text, length) : text.slice(0, length); } const spanAttrs = tooltip ? {} : { ...other }; return getTooltip({ tooltip, overlayStyle: TooltipOverlayStyle, title: text, children: ( <span {...spanAttrs}> {displayText} {tail} </span> ), }); }; export default class Ellipsis extends Component { state = { text: '', targetCount: 0, }; componentDidMount() { if (this.node) { this.computeLine(); } } componentDidUpdate(perProps) { const { lines } = this.props; if (lines !== perProps.lines) { this.computeLine(); } } computeLine = () => { const { lines } = this.props; if (lines && !isSupportLineClamp) { const text = this.shadowChildren.innerText || this.shadowChildren.textContent; const lineHeight = parseInt(getComputedStyle(this.root).lineHeight, 10); const targetHeight = lines * lineHeight; this.content.style.height = `${targetHeight}px`; const totalHeight = this.shadowChildren.offsetHeight; const shadowNode = this.shadow.firstChild; if (totalHeight <= targetHeight) { this.setState({ text, targetCount: text.length, }); return; } // bisection const len = text.length; const mid = Math.ceil(len / 2); const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode); this.setState({ text, targetCount: count, }); } }; bisection = (th, m, b, e, text, shadowNode) => { const suffix = '...'; let mid = m; let end = e; let begin = b; shadowNode.innerHTML = text.substring(0, mid) + suffix; let sh = shadowNode.offsetHeight; if (sh <= th) { shadowNode.innerHTML = text.substring(0, mid + 1) + suffix; sh = shadowNode.offsetHeight; if (sh > th || mid === begin) { return mid; } begin = mid; if (end - begin === 1) { mid = 1 + begin; } else { mid = Math.floor((end - begin) / 2) + begin; } return this.bisection(th, mid, begin, end, text, shadowNode); } if (mid - 1 < 0) { return mid; } shadowNode.innerHTML = text.substring(0, mid - 1) + suffix; sh = shadowNode.offsetHeight; if (sh <= th) { return mid - 1; } end = mid; mid = Math.floor((end - begin) / 2) + begin; return this.bisection(th, mid, begin, end, text, shadowNode); }; handleRoot = n => { this.root = n; }; handleContent = n => { this.content = n; }; handleNode = n => { this.node = n; }; handleShadow = n => { this.shadow = n; }; handleShadowChildren = n => { this.shadowChildren = n; }; render() { const { text, targetCount } = this.state; const { children, lines, length, className, tooltip, fullWidthRecognition, ...restProps } = this.props; const cls = classNames(styles.ellipsis, className, { [styles.lines]: lines && !isSupportLineClamp, [styles.lineClamp]: lines && isSupportLineClamp, }); if (!lines && !length) { return ( <span className={cls} {...restProps}> {children} </span> ); } // length if (!lines) { return ( <EllipsisText className={cls} length={length} text={children || ''} tooltip={tooltip} fullWidthRecognition={fullWidthRecognition} {...restProps} /> ); } const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`; // support document.body.style.webkitLineClamp if (isSupportLineClamp) { const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`; const node = ( <div id={id} className={cls} {...restProps}> <style>{style}</style> {children} </div> ); return getTooltip({ tooltip, overlayStyle: TooltipOverlayStyle, title: children, children: node, }); } const childNode = ( <span ref={this.handleNode}> {targetCount > 0 && text.substring(0, targetCount)} {targetCount > 0 && targetCount < text.length && '...'} </span> ); return ( <div {...restProps} ref={this.handleRoot} className={cls}> <div ref={this.handleContent}> {getTooltip({ tooltip, overlayStyle: TooltipOverlayStyle, title: text, children: childNode, })} <div className={styles.shadow} ref={this.handleShadowChildren}> {children} </div> <div className={styles.shadow} ref={this.handleShadow}> <span>{text}</span> </div> </div> </div> ); } }
actor-apps/app-web/src/app/components/Deactivated.react.js
jiguoling/actor-platform
import React from 'react'; class Deactivated extends React.Component { render() { return ( <div className="deactivated row center-xs middle-xs"> <div className="deactivated__window"> <h2>Tab deactivated</h2> <p> Oops, you have opened another tab with Actor, so we had to deactivate this one to prevent some dangerous things happening. </p> </div> </div> ); } } export default Deactivated;
src/view/Login.js
blockkeeper/blockkeeper-frontend-web
import React from 'react' import Button from '@material-ui/core/Button' import Typography from '@material-ui/core/Typography' import TextField from '@material-ui/core/TextField' import Paper from '@material-ui/core/Paper' import Grid from '@material-ui/core/Grid' import { withStyles } from '@material-ui/core/styles' import LinearProgress from '@material-ui/core/LinearProgress' import {Lock} from '@material-ui/icons' import {theme, paperStyle, loginStyle, fullWidth, actnBtnClr, styleGuide} from './Style' import {Modal, BrowserGate, NtAllwd} from './Lib' import __ from '../util' class LoginView extends React.Component { constructor (props) { super(props) this.cx = props.cx this._cryptId = false this.reset = { loginBusy: false, upd: false, userId: '', cryptId: '', err: undefined } this.state = {...this.reset} this.goBack = props.history.goBack this.login = this.login.bind(this) this.set = this.set.bind(this) this.reload = () => this.setState(this.reset) } componentDidMount () { // set body bg document.body.style.backgroundColor = styleGuide.backgroundDark Object.assign(this, __.initView(this, 'login')) } set (ilk, val) { const vldUuid = (uuid, emsg) => __.vld.isUUID(uuid, 4) ? '' : emsg this.setState({[ilk]: val, emsg: undefined}, () => { let d = {upd: false} if (this.state.userId && this._cryptId) { d.userIdEmsg = vldUuid(this.state.userId, 'Invalid identifier') } if (this.state.cryptId) { this._cryptId = true d.userIdEmsg = vldUuid(this.state.userId, 'Invalid identifier') // ensure compatibility: use password- instead of uuid-check // this should also be a vldUuid() check, but first (beta) generation // users have passwords instead of uuids as cryptIds d.cryptIdEmsg = __.vldPw(this.state.cryptId, true) if (d.cryptIdEmsg) d.cryptIdEmsg = 'Invalid crypto-key' } if (this.state.userId && this.state.cryptId && !d.userIdEmsg && !d.cryptIdEmsg) { d.upd = true } this.setState(d) }) } async login () { this.setState({err: undefined, loginBusy: true}) try { await this.cx.core.login(this.state.userId, this.state.cryptId) this.props.history.push('/depot') } catch (e) { if (e.sts >= 400 && e.sts < 500) { this.setState({ ...this.reset, userId: this.state.userId, cryptId: this.state.cryptId, emsg: e.message }) } else { if (__.cfg('isDev')) throw e return this.setState({err: e.message}) } } } render () { if (this.state.err) { return ( <Modal onClose={async () => await this.reload()} actions={[{lbl: 'OK', onClick: async () => await this.reload()}]} > {this.state.err} </Modal> ) } else { return ( <div> <div className={this.props.classes.loginStyle}> <Grid container spacing={0} justify='center'> <Grid item xs={12} sm={8} md={6} lg={4} xl={4}> <Typography variant='h2' color='inherit' align='center'> BlockKeeper <span style={{fontSize: '14px'}}>[BETA]</span> </Typography> <Typography variant='h4' color='inherit' align='center' gutterBottom > Please enter your credentials </Typography> {this.state.loginBusy && <LinearProgress /> } <Paper square className={this.props.classes.paperStyle} elevation={24} > <TextField autoFocus fullWidth label='Identifier' margin='normal' value={this.state.userId} error={ Boolean(this.state.emsg) || Boolean(this.state.userIdEmsg) } helperText={this.state.emsg || this.state.userIdEmsg} onChange={evt => this.set('userId', evt.target.value)} /> <TextField fullWidth label='Crypto-Key' type='password' margin='normal' autoComplete='current-crypto-key' value={this.state.cryptId} error={ Boolean(this.state.emsg) || Boolean(this.state.cryptIdEmsg) } helperText={this.state.emsg || this.state.cryptIdEmsg} onChange={evt => this.set('cryptId', evt.target.value)} /> <BrowserGate allwd={ <div> <Button variant='contained' color='primary' className={this.props.classes.loginButton} onClick={async (event) => this.login(event)} disabled={!this.state.upd || this.state.loginBusy} classes={{ contained: this.props.classes.actnBtnClr }} > <Lock className={this.props.classes.lockIcon} /> Login </Button> <br /> <Button href='/rgstr' disabled={this.state.loginBusy} className={this.props.classes.fullWidth} > Register </Button> </div> } ntAll={<NtAllwd />} /> </Paper> </Grid> </Grid> </div> </div> ) } } } export default withStyles({ loginStyle, paperStyle, fullWidth, actnBtnClr, loginButton: { width: '100%', marginTop: theme.spacing.unit * 2, marginBottom: theme.spacing.unit }, lockIcon: { width: theme.spacing.unit * 2, height: theme.spacing.unit * 2 } })(LoginView)
src/components/AssetCard/index.js
khankuan/asset-library-demo
import React from 'react'; import { Link } from 'react-router'; import Card from '../Card'; import Text from '../Text'; import Button from '../Button'; import LikeButton from '../LikeButton'; import Modal from '../Modal'; import LikeList from '../../views/LikeList'; export default class AssetCard extends React.Component { static propTypes = { asset: React.PropTypes.object.isRequired, liked: React.PropTypes.bool, onLikeChange: React.PropTypes.func, } state = {} _getBackground(asset) { if (asset.category === 'image') { return { backgroundImage: 'url(/api/assets/' + asset.id + '/download)', backgroundSize: 'cover', }; } if (asset.category === 'audio') { return { backgroundImage: 'url(/static/audio.png)', backgroundSize: 'cover', }; } } _handleLikeClick = () => { if (this.props.onLikeChange) { this.props.onLikeChange(!this.props.asset.isLiked); } } _handleLikeListClick = () => { this.setState({ showLikeList: true }); } _handleLikeListClose = () => { this.setState({ showLikeList: false }); } renderLikeListModal() { if (!this.state.showLikeList) { return null; } const asset = this.props.asset; return ( <Modal onClose={ this._handleLikeListClose }> <LikeList assetId={ asset.id } /> </Modal> ); } render() { const asset = this.props.asset; return ( <Card className="asset-card" style={ this._getBackground(asset) }> <Link className="asset-card-link" to={`/assets/${asset.id}`} /> <Text block className="asset-card-title">{ asset.title } <Text size="tiny" padding="base">{ asset.category }</Text> <div className="asset-card-liked-by"> <Button type="flat" onClick={ this._handleLikeListClick } > { asset.likedByCount } liked this </Button> </div> </Text> <Button type="default" size="small" className="asset-download"> <a href={`/api/assets/${asset.id}/download`} target="_blank" download={asset.title}>Download</a> </Button> <LikeButton className="asset-card-like" liked={ this.props.asset.isLiked } onClick={ this._handleLikeClick }/> { this.renderLikeListModal() } </Card> ); } }
cli/base-antd-pro/src/routes/User/Register.js
CFshuming/react-demo-gather
import React, { Component } from 'react'; import { connect } from 'dva'; import { routerRedux, Link } from 'dva/router'; import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd'; import styles from './Register.less'; const FormItem = Form.Item; const { Option } = Select; const InputGroup = Input.Group; const passwordStatusMap = { ok: <div className={styles.success}>强度:强</div>, pass: <div className={styles.warning}>强度:中</div>, poor: <div className={styles.error}>强度:太短</div>, }; const passwordProgressMap = { ok: 'success', pass: 'normal', poor: 'exception', }; @connect(({ register, loading }) => ({ register, submitting: loading.effects['register/submit'], })) @Form.create() export default class Register extends Component { state = { count: 0, confirmDirty: false, visible: false, help: '', prefix: '86', }; componentWillReceiveProps(nextProps) { const account = this.props.form.getFieldValue('mail'); if (nextProps.register.status === 'ok') { this.props.dispatch(routerRedux.push({ pathname: '/user/register-result', state: { account, }, })); } } componentWillUnmount() { clearInterval(this.interval); } onGetCaptcha = () => { let count = 59; this.setState({ count }); this.interval = setInterval(() => { count -= 1; this.setState({ count }); if (count === 0) { clearInterval(this.interval); } }, 1000); }; getPasswordStatus = () => { const { form } = this.props; const value = form.getFieldValue('password'); if (value && value.length > 9) { return 'ok'; } if (value && value.length > 5) { return 'pass'; } return 'poor'; }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields({ force: true }, (err, values) => { if (!err) { this.props.dispatch({ type: 'register/submit', payload: { ...values, prefix: this.state.prefix, }, }); } }); }; handleConfirmBlur = (e) => { const { value } = e.target; this.setState({ confirmDirty: this.state.confirmDirty || !!value }); }; checkConfirm = (rule, value, callback) => { const { form } = this.props; if (value && value !== form.getFieldValue('password')) { callback('两次输入的密码不匹配!'); } else { callback(); } }; checkPassword = (rule, value, callback) => { if (!value) { this.setState({ help: '请输入密码!', visible: !!value, }); callback('error'); } else { this.setState({ help: '', }); if (!this.state.visible) { this.setState({ visible: !!value, }); } if (value.length < 6) { callback('error'); } else { const { form } = this.props; if (value && this.state.confirmDirty) { form.validateFields(['confirm'], { force: true }); } callback(); } } }; changePrefix = (value) => { this.setState({ prefix: value, }); }; renderPasswordProgress = () => { const { form } = this.props; const value = form.getFieldValue('password'); const passwordStatus = this.getPasswordStatus(); return value && value.length ? ( <div className={styles[`progress-${passwordStatus}`]}> <Progress status={passwordProgressMap[passwordStatus]} className={styles.progress} strokeWidth={6} percent={value.length * 10 > 100 ? 100 : value.length * 10} showInfo={false} /> </div> ) : null; }; render() { const { form, submitting } = this.props; const { getFieldDecorator } = form; const { count, prefix } = this.state; return ( <div className={styles.main}> <h3>注册</h3> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('mail', { rules: [ { required: true, message: '请输入邮箱地址!', }, { type: 'email', message: '邮箱地址格式错误!', }, ], })(<Input size="large" placeholder="邮箱" />)} </FormItem> <FormItem help={this.state.help}> <Popover content={ <div style={{ padding: '4px 0' }}> {passwordStatusMap[this.getPasswordStatus()]} {this.renderPasswordProgress()} <div style={{ marginTop: 10 }}> 请至少输入 6 个字符。请不要使用容易被猜到的密码。 </div> </div> } overlayStyle={{ width: 240 }} placement="right" visible={this.state.visible} > {getFieldDecorator('password', { rules: [ { validator: this.checkPassword, }, ], })( <Input size="large" type="password" placeholder="至少6位密码,区分大小写" /> )} </Popover> </FormItem> <FormItem> {getFieldDecorator('confirm', { rules: [ { required: true, message: '请确认密码!', }, { validator: this.checkConfirm, }, ], })(<Input size="large" type="password" placeholder="确认密码" />)} </FormItem> <FormItem> <InputGroup compact> <Select size="large" value={prefix} onChange={this.changePrefix} style={{ width: '20%' }} > <Option value="86">+86</Option> <Option value="87">+87</Option> </Select> {getFieldDecorator('mobile', { rules: [ { required: true, message: '请输入手机号!', }, { pattern: /^1\d{10}$/, message: '手机号格式错误!', }, ], })( <Input size="large" style={{ width: '80%' }} placeholder="11位手机号" /> )} </InputGroup> </FormItem> <FormItem> <Row gutter={8}> <Col span={16}> {getFieldDecorator('captcha', { rules: [ { required: true, message: '请输入验证码!', }, ], })(<Input size="large" placeholder="验证码" />)} </Col> <Col span={8}> <Button size="large" disabled={count} className={styles.getCaptcha} onClick={this.onGetCaptcha} > {count ? `${count} s` : '获取验证码'} </Button> </Col> </Row> </FormItem> <FormItem> <Button size="large" loading={submitting} className={styles.submit} type="primary" htmlType="submit" > 注册 </Button> <Link className={styles.login} to="/user/login"> 使用已有账户登录 </Link> </FormItem> </Form> </div> ); } }
client/views/setupWizard/SideBar.js
iiet/iiet-chat
import { Box, Margins, Scrollable } from '@rocket.chat/fuselage'; import { useMediaQuery } from '@rocket.chat/fuselage-hooks'; import React from 'react'; import { useTranslation } from '../../contexts/TranslationContext'; import Logo from '../../components/basic/Logo'; import './SideBar.css'; function SideBar({ logoSrc = 'images/logo/logo.svg', currentStep = 1, steps = [], }) { const t = useTranslation(); const small = useMediaQuery('(max-width: 760px)'); return <Box is='aside' className='SetupWizard__SideBar' flexGrow={0} flexShrink={1} flexBasis={small ? 'auto' : '350px'} maxHeight='sh' display='flex' flexDirection='column' flexWrap='nowrap' style={{ overflow: 'hidden' }} > <Box is='header' marginBlockStart={small ? 'x16' : 'x32'} marginBlockEnd={small ? 'none' : 'x32'} marginInline='x24' display='flex' flexDirection='row' flexWrap='wrap' alignItems='center' > <Logo src={logoSrc} width='auto' height='x24' margin='x4' /> <Box is='span' margin='x4' paddingBlock='x4' paddingInline='x8' color='alternative' fontScale='micro' style={{ whiteSpace: 'nowrap', textTransform: 'uppercase', backgroundColor: 'var(--color-dark, #2f343d)', borderRadius: '9999px', }} > {t('Setup_Wizard')} </Box> </Box> {!small && <Scrollable> <Box flexGrow={1} marginBlockEnd='x16' paddingInline='x32' > <Margins blockEnd='x16'> <Box is='h2' fontScale='h1' color='default'>{t('Setup_Wizard')}</Box> <Box is='p' color='hint' fontScale='p1'>{t('Setup_Wizard_Info')}</Box> </Margins> <Box is='ol'> {steps.map(({ step, title }) => <Box key={step} is='li' className={[ 'SetupWizard__SideBar-step', step < currentStep && 'SetupWizard__SideBar-step--past', ].filter(Boolean).join(' ')} data-number={step} marginBlock='x32' marginInline='neg-x8' display='flex' alignItems='center' fontScale='p2' color={(step === currentStep && 'primary') || (step < currentStep && 'default') || 'disabled'} style={{ position: 'relative' }} > {title} </Box>, )} </Box> </Box> </Scrollable>} </Box>; } export default SideBar;
src/js/components/_registerFields/ExploreField.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Button from '../ui/Button'; import translate from '../../i18n/Translate'; @translate('ExploreField') export default class ExploreField extends Component { static propTypes = { profile : PropTypes.object.isRequired, showContinue : PropTypes.bool, onSaveHandler : PropTypes.func.isRequired, onClickField : PropTypes.func.isRequired, onBackHandler : PropTypes.func.isRequired, onDetailSelection: PropTypes.func.isRequired, // Injected by @translate: strings : PropTypes.object }; constructor(props) { super(props); this.onClickObjective = this.onClickObjective.bind(this); this.handleClickSave = this.handleClickSave.bind(this); this.renderWorkDetail = this.renderWorkDetail.bind(this); this.renderHobbiesDetail = this.renderHobbiesDetail.bind(this); this.renderLeisureDetail = this.renderLeisureDetail.bind(this); this.backToHome = this.backToHome.bind(this); this.getButtonText = this.getButtonText.bind(this); this.state = { objectiveSelected: null, savedDetails : null, } } handleClickSave() { this.setState({selectedObjective: null, savedDetails: true}); } onClickObjective(objective) { this.setState({ selectedObjective: objective }); this.props.onClickField(); } backToHome() { this.setState({selectedObjective: null, savedDetails: null}); this.props.onBackHandler(); } renderFieldDetail = function(objective) { let detail; switch (objective) { case 'work': detail = this.renderWorkDetail(); break; case 'hobbies': detail = this.renderHobbiesDetail(); break; case 'explore': detail = this.renderLeisureDetail(); break; } return <div className="register-field-detail objectives-field-detail">{detail}</div> }; renderWorkDetail() { const {profile, strings} = this.props; return <div> <div className="register-field-detail-title">{strings.work1 + ' ' + strings.work2}</div> <div className={this.profileHasField(profile, 'industry') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('industry')}>{strings.industry}</Button> </div> <div className={this.profileHasField(profile, 'profession') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('profession')}>{strings.skills}</Button> </div> <div className={this.profileHasField(profile, 'proposal') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('proposal')}>{strings.proposals}</Button> </div> {profile.objective && profile.objective.some(objective => objective === 'work') ? <div className="button-wrapper active"> <Button type="submit" onClick={this.handleClickSave}>{strings.save}</Button> </div> : null } </div> }; renderHobbiesDetail() { const {profile, strings} = this.props; return <div> <div className="register-field-detail-title">{strings.hobbies1 + ' ' + strings.hobbies2}</div> <div className={this.profileHasField(profile, 'sports') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('sports')}>{strings.sports}</Button> </div> <div className={this.profileHasField(profile, 'games') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('games')}>{strings.games}</Button> </div> <div className={this.profileHasField(profile, 'creative') ? "button-wrapper active" : "button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('creative')}>{strings.creative}</Button> </div> {profile.objective && profile.objective.some(objective => objective === 'hobbies') ? <div className="button-wrapper active"> <Button type="submit" onClick={this.handleClickSave}>{strings.save}</Button> </div> : null } </div> }; renderLeisureDetail() { const {profile, strings} = this.props; return <div> <div className="register-field-detail-title">{strings.leisure1 + ' ' + strings.leisure2}</div> <div className={this.profileHasField(profile, 'leisureMoney') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('leisureMoney')}>{strings.leisureMoney}</Button> </div> <div className={this.profileHasField(profile, 'leisureTime') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('leisureTime')}>{strings.leisureTime}</Button> </div> <div className={this.profileHasField(profile, 'travelling') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('travelling')}>{strings.travels}</Button> </div> <div className={this.profileHasField(profile, 'activity') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('activity')}>{strings.activities}</Button> </div> <div className={this.profileHasField(profile, 'tickets') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('tickets')}>{strings.tickets}</Button> </div> <div className={this.profileHasField(profile, 'leisurePlan') ? "button-wrapper small-width active" : "small-width button-wrapper"}> <Button type="submit" onClick={() => this.props.onDetailSelection('leisurePlan')}>{strings.leisurePlans}</Button> </div> {profile.objective && profile.objective.some(objective => objective === 'explore') ? <div className="button-wrapper active"> <Button type="submit" onClick={this.handleClickSave}>{strings.save}</Button> </div> : null } </div> }; getButtonText() { const {profile, showContinue, strings} = this.props; if(!showContinue) { return strings.finish; } else if(this.profileHasAnyField(profile, ['industry', 'profession', 'proposal', 'sports', 'games', 'creative', 'travelling', 'activity', 'tickets', 'leisureTime', 'leisureMoney', 'leisurePlan'])) { return strings.save; } return strings.skip; } profileHasAnyField = function(profile, fields) { return fields.some(field => profile && profile[field] && profile[field].length !== 0); }; profileHasField = function(profile, field) { return profile && profile[field] && profile[field].length !== 0; }; render() { const {profile, showContinue, strings} = this.props; const {selectedObjective, savedDetails} = this.state; const objectivesClass = "register-field objectives-field"; return ( <div className="register-fields"> {selectedObjective || savedDetails && !showContinue ? <div className="back-button-icon" onClick={selectedObjective ? this.handleClickSave : this.backToHome}> <span className="icon-left-arrow"/> </div> : null } {(selectedObjective || savedDetails) && !showContinue ? <div className="main-icon"> <span className="icon-compass2"/> <div className="main-icon-text">{strings.explore}</div> </div> : null } <div className={selectedObjective ? "hide " + objectivesClass : savedDetails || showContinue ? "show " + objectivesClass : objectivesClass}> <div className="register-field-icons"> <div className={profile.objective && profile.objective.some(objective => objective === 'work') ? "register-field-icon active" : "register-field-icon"} onClick={this.onClickObjective.bind(this, 'work')}> <span className="icon-lightbulb"/> <div className="register-filed-icon-text">{strings.work1}</div> <div className="register-filed-icon-text">{strings.work2}</div> </div> <div className={profile.objective && profile.objective.some(objective => objective === 'hobbies') ? "register-field-icon active" : "register-field-icon"} onClick={this.onClickObjective.bind(this, 'hobbies')}> <span className="icon-gamepad"/> <div className="register-filed-icon-text">{strings.hobbies1}</div> <div className="register-filed-icon-text">{strings.hobbies2}</div> </div> <div className={profile.objective && profile.objective.some(objective => objective === 'explore') ? "register-field-icon active" : "register-field-icon"} onClick={this.onClickObjective.bind(this, 'explore')}> <span className="icon-compass"/> <div className="register-filed-icon-text">{strings.leisure1}</div> <div className="register-filed-icon-text">{strings.leisure2}</div> </div> </div> {savedDetails || showContinue ? <div className="register-fields-continue"> <Button onClick={this.props.onSaveHandler}>{this.getButtonText()}</Button> <div className="title">{strings.selectOther}</div> </div> : null } </div> {selectedObjective ? this.renderFieldDetail(selectedObjective) : null} </div> ); } } ExploreField.defaultProps = { strings: { explore : 'Explore', work1 : 'Work', work2 : '& ideas', hobbies1 : 'Hobbies', hobbies2 : '& games', leisure1 : 'Adventures', leisure2 : '& activity', industry : 'Industry', skills : 'Skills', proposals : 'Proposals', sports : 'Sports', games : 'Games', creative : 'Creative', leisureTime : 'Time', leisureMoney: 'Money', travels : 'Travels', tickets : 'Tickets', activities : 'Activities', leisurePlans: 'Plans', save : 'Continue', finish : 'Finish', skip : 'Skip', selectOther : 'You can select more than one' } };
src/FormGroup.js
glenjamin/react-bootstrap
import classNames from 'classnames'; import PropTypes from 'prop-types'; import { elementType } from 'prop-types-extra'; import React from 'react'; import FormContext from './FormContext'; import { createBootstrapComponent } from './ThemeProvider'; const propTypes = { /** * @default 'form-group' */ bsPrefix: PropTypes.string, as: elementType, /** * Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`. */ controlId: PropTypes.string, /** * The FormGroup `ref` will be forwarded to the underlying element. * Unless the FormGroup is rendered `as` a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ innerRef: PropTypes.any, }; const defaultProps = { as: 'div', }; function FormGroup({ bsPrefix, innerRef, className, children, controlId, as: Component, ...props }) { return ( <FormContext.Provider value={{ controlId }}> <Component {...props} ref={innerRef} className={classNames(className, bsPrefix)} > {children} </Component> </FormContext.Provider> ); } FormGroup.propTypes = propTypes; FormGroup.defaultProps = defaultProps; export default createBootstrapComponent(FormGroup, 'form-group');
app/components/TransferDialog/TokenDialog.js
VonIobro/ab-web
import React from 'react'; import PropTypes from 'prop-types'; import { Form, Field } from 'redux-form/immutable'; import BigNumber from 'bignumber.js'; import Web3Alerts from '../../containers/Web3Alerts'; import { ErrorMessage } from '../FormMessages'; import SubmitButton from '../SubmitButton'; import FormField from '../Form/FormField'; import TokenAmountField from '../Form/TokenAmountField'; class TokenDialog extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(values) { return this.props.handleTransfer( values.get('amount'), values.get('address'), ).then(() => this.props.reset()); } render() { const { error, handleSubmit, submitting, maxAmount, minAmount, invalid, canSendTx, normalizer, placeholder, } = this.props; return ( <div style={{ maxWidth: 480 }}> <Form onSubmit={handleSubmit(this.handleSubmit)}> <Field normalize={normalizer} name="amount" component={TokenAmountField} label="Amount" autoFocus maxAmount={maxAmount} minAmount={minAmount} modalAdd={this.props.modalAdd} modalDismiss={this.props.modalDismiss} amountUnit={this.props.amountUnit} setAmountUnit={this.props.setAmountUnit} reset={this.props.reset} placeholder={placeholder} /> <Field name="address" component={FormField} type="text" label="Ethereum address" /> {error && <ErrorMessage>{error}</ErrorMessage>} <Web3Alerts /> <SubmitButton type="submit" disabled={invalid || !canSendTx} submitting={submitting} > Submit </SubmitButton> </Form> </div> ); } } TokenDialog.propTypes = { canSendTx: PropTypes.bool, submitting: PropTypes.bool, invalid: PropTypes.bool, maxAmount: PropTypes.object, // BigNumber minAmount: PropTypes.object, // BigNumber handleSubmit: PropTypes.func, handleTransfer: PropTypes.func, error: PropTypes.any, modalAdd: PropTypes.func, modalDismiss: PropTypes.func, amountUnit: PropTypes.string, setAmountUnit: PropTypes.func, reset: PropTypes.func, normalizer: PropTypes.func, placeholder: PropTypes.string, }; TokenDialog.defaultProps = { minAmount: new BigNumber(0), }; export default TokenDialog;
src/controls/ColorPicker/Component/index.js
jpuri/react-draft-wysiwyg
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { stopPropagation } from '../../../utils/common'; import Option from '../../../components/Option'; import './styles.css'; class LayoutComponent extends Component { static propTypes = { expanded: PropTypes.bool, onExpandEvent: PropTypes.func, onChange: PropTypes.func, config: PropTypes.object, currentState: PropTypes.object, translations: PropTypes.object, }; state = { currentStyle: 'color', }; componentDidUpdate(prevProps) { const { expanded } = this.props; if (expanded && !prevProps.expanded) { this.setState({ currentStyle: 'color', }); } } onChange = color => { const { onChange } = this.props; const { currentStyle } = this.state; onChange(currentStyle, color); }; setCurrentStyleColor = () => { this.setState({ currentStyle: 'color', }); }; setCurrentStyleBgcolor = () => { this.setState({ currentStyle: 'bgcolor', }); }; renderModal = () => { const { config: { popupClassName, colors }, currentState: { color, bgColor }, translations, } = this.props; const { currentStyle } = this.state; const currentSelectedColor = currentStyle === 'color' ? color : bgColor; return ( <div className={classNames('rdw-colorpicker-modal', popupClassName)} onClick={stopPropagation} > <span className="rdw-colorpicker-modal-header"> <span className={classNames('rdw-colorpicker-modal-style-label', { 'rdw-colorpicker-modal-style-label-active': currentStyle === 'color', })} onClick={this.setCurrentStyleColor} > {translations['components.controls.colorpicker.text']} </span> <span className={classNames('rdw-colorpicker-modal-style-label', { 'rdw-colorpicker-modal-style-label-active': currentStyle === 'bgcolor', })} onClick={this.setCurrentStyleBgcolor} > {translations['components.controls.colorpicker.background']} </span> </span> <span className="rdw-colorpicker-modal-options"> {colors.map((c, index) => ( <Option value={c} key={index} className="rdw-colorpicker-option" activeClassName="rdw-colorpicker-option-active" active={currentSelectedColor === c} onClick={this.onChange} > <span style={{ backgroundColor: c }} className="rdw-colorpicker-cube" /> </Option> ))} </span> </div> ); }; render() { const { config: { icon, className, title }, expanded, onExpandEvent, translations, } = this.props; return ( <div className="rdw-colorpicker-wrapper" aria-haspopup="true" aria-expanded={expanded} aria-label="rdw-color-picker" title={ title || translations['components.controls.colorpicker.colorpicker'] } > <Option onClick={onExpandEvent} className={classNames(className)}> <img src={icon} alt="" /> </Option> {expanded ? this.renderModal() : undefined} </div> ); } } export default LayoutComponent;
src/routes/Home/modules/home.js
CERNSummerWebfest/webfest-2017-physics-concepts
import { Result } from '../components/ResultComponent' import React from 'react' import Concept from '../components/Concept' export const SEARCH_START = 'SEARCH_START' export const SEARCH_END = 'SEARCH_END' export const GET_COMPONENT = 'GET_COMPONENT' export function search (str) { return (dispatch, getState) => { dispatch({ type: SEARCH_START, str: str }) if (str === '') { dispatch({ type: SEARCH_END, results: [] }) } else { fetch(`http://localhost:3000/api/compare?str=${str}`) .then(response => response.json()) .then(json => { dispatch({ type: SEARCH_END, results: json }) }) } } } export function getComponent (id) { return (dispatch, getState) => { fetch(`http://localhost:3000/api/concept/${id}`) .then(response => response.json()) .then(json => { dispatch({ type: GET_COMPONENT, concept: json }) }) } } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [SEARCH_START]: (state, action) => Object.assign({}, state, { str: action.str }), [SEARCH_END]: (state, action) => { return Object.assign({}, state, { results: action.results.map(res => ( <Result key={res._id} concept={res.concept} definition={res.definition} id={res.id} /> )) }) }, [GET_COMPONENT]: (state, action) => Object.assign({}, state, { concept: action.concept }) } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { results: [], str: '', concept: { title: '', definition: '' } } export default function homeReducer (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
src/App.js
dereksweet/ComedyCompanion
import React, { Component } from 'react'; import { createStore, applyMiddleware, combineReducers, bindActionCreators } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import * as reducers from './reducers'; import MainApp from './containers/mainApp'; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const reducer = combineReducers(reducers); export const store = createStoreWithMiddleware(reducer); export default class App extends Component { render() { return ( <Provider store={store}> <MainApp /> </Provider> ); } }
app/containers/LanguageProvider/index.js
Voltmod/productSaver
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
narabo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages } from 'react-intl'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ public_short: { id: 'privacy.public.short', defaultMessage: 'Public' }, public_long: { id: 'privacy.public.long', defaultMessage: 'Post to public timelines' }, unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' }, unlisted_long: { id: 'privacy.unlisted.long', defaultMessage: 'Do not show in public timelines' }, private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' }, private_long: { id: 'privacy.private.long', defaultMessage: 'Post to followers only' }, direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' }, direct_long: { id: 'privacy.direct.long', defaultMessage: 'Post to mentioned users only' }, change_privacy: { id: 'privacy.change', defaultMessage: 'Adjust status privacy' }, }); const iconStyle = { height: null, lineHeight: '27px', }; class PrivacyDropdown extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: false, }; handleToggle = () => { this.setState({ open: !this.state.open }); } handleClick = (e) => { const value = e.currentTarget.getAttribute('data-index'); e.preventDefault(); this.setState({ open: false }); this.props.onChange(value); } onGlobalClick = (e) => { if (e.target !== this.node && !this.node.contains(e.target) && this.state.open) { this.setState({ open: false }); } } componentDidMount () { window.addEventListener('click', this.onGlobalClick); window.addEventListener('touchstart', this.onGlobalClick); } componentWillUnmount () { window.removeEventListener('click', this.onGlobalClick); window.removeEventListener('touchstart', this.onGlobalClick); } setRef = (c) => { this.node = c; } render () { const { value, onChange, intl } = this.props; const { open } = this.state; const options = [ { icon: 'globe', value: 'public', shortText: intl.formatMessage(messages.public_short), longText: intl.formatMessage(messages.public_long) }, { icon: 'unlock-alt', value: 'unlisted', shortText: intl.formatMessage(messages.unlisted_short), longText: intl.formatMessage(messages.unlisted_long) }, { icon: 'lock', value: 'private', shortText: intl.formatMessage(messages.private_short), longText: intl.formatMessage(messages.private_long) }, { icon: 'envelope', value: 'direct', shortText: intl.formatMessage(messages.direct_short), longText: intl.formatMessage(messages.direct_long) }, ]; const valueOption = options.find(item => item.value === value); return ( <div ref={this.setRef} className={`privacy-dropdown ${open ? 'active' : ''}`}> <div className='privacy-dropdown__value'><IconButton className='privacy-dropdown__value-icon' icon={valueOption.icon} title={intl.formatMessage(messages.change_privacy)} size={18} active={open} inverted onClick={this.handleToggle} style={iconStyle}/></div> <div className='privacy-dropdown__dropdown'> {open && options.map(item => <div role='button' tabIndex='0' key={item.value} data-index={item.value} onClick={this.handleClick} className={`privacy-dropdown__option ${item.value === value ? 'active' : ''}`}> <div className='privacy-dropdown__option__icon'><i className={`fa fa-fw fa-${item.icon}`} /></div> <div className='privacy-dropdown__option__content'> <strong>{item.shortText}</strong> {item.longText} </div> </div> )} </div> </div> ); } } export default injectIntl(PrivacyDropdown);
packages/idyll-template-projects/templates/slideshow/components/slide.js
idyll-lang/idyll
import React from 'react'; import TextContainer from 'idyll-components/dist/cjs/text-container'; class Slide extends React.Component { render() { const { hasError, idyll, updateProps, children, ...props } = this.props; return ( <div {...props} className="slide"> <TextContainer idyll={idyll}>{children}</TextContainer> </div> ); } } export default Slide;
app/javascript/mastodon/components/poll.js
imas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Motion from 'mastodon/features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import escapeTextContentForBrowser from 'escape-html'; import emojify from 'mastodon/features/emoji/emoji'; import RelativeTimestamp from './relative_timestamp'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ closed: { id: 'poll.closed', defaultMessage: 'Closed' }, voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer', description: 'Tooltip of the "voted" checkmark in polls' }, }); const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => { obj[`:${emoji.get('shortcode')}:`] = emoji.toJS(); return obj; }, {}); export default @injectIntl class Poll extends ImmutablePureComponent { static propTypes = { poll: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, disabled: PropTypes.bool, refresh: PropTypes.func, onVote: PropTypes.func, }; state = { selected: {}, expired: null, }; static getDerivedStateFromProps (props, state) { const { poll, intl } = props; const expires_at = poll.get('expires_at'); const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < intl.now(); return (expired === state.expired) ? null : { expired }; } componentDidMount () { this._setupTimer(); } componentDidUpdate () { this._setupTimer(); } componentWillUnmount () { clearTimeout(this._timer); } _setupTimer () { const { poll, intl } = this.props; clearTimeout(this._timer); if (!this.state.expired) { const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now(); this._timer = setTimeout(() => { this.setState({ expired: true }); }, delay); } } _toggleOption = value => { if (this.props.poll.get('multiple')) { const tmp = { ...this.state.selected }; if (tmp[value]) { delete tmp[value]; } else { tmp[value] = true; } this.setState({ selected: tmp }); } else { const tmp = {}; tmp[value] = true; this.setState({ selected: tmp }); } } handleOptionChange = ({ target: { value } }) => { this._toggleOption(value); }; handleOptionKeyPress = (e) => { if (e.key === 'Enter' || e.key === ' ') { this._toggleOption(e.target.getAttribute('data-index')); e.stopPropagation(); e.preventDefault(); } } handleVote = () => { if (this.props.disabled) { return; } this.props.onVote(Object.keys(this.state.selected)); }; handleRefresh = () => { if (this.props.disabled) { return; } this.props.refresh(); }; renderOption (option, optionIndex, showResults) { const { poll, disabled, intl } = this.props; const pollVotesCount = poll.get('voters_count') || poll.get('votes_count'); const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100; const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count')); const active = !!this.state.selected[`${optionIndex}`]; const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex)); let titleEmojified = option.get('title_emojified'); if (!titleEmojified) { const emojiMap = makeEmojiMap(poll); titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap); } return ( <li key={option.get('title')}> <label className={classNames('poll__option', { selectable: !showResults })}> <input name='vote-options' type={poll.get('multiple') ? 'checkbox' : 'radio'} value={optionIndex} checked={active} onChange={this.handleOptionChange} disabled={disabled} /> {!showResults && ( <span className={classNames('poll__input', { checkbox: poll.get('multiple'), active })} tabIndex='0' role={poll.get('multiple') ? 'checkbox' : 'radio'} onKeyPress={this.handleOptionKeyPress} aria-checked={active} aria-label={option.get('title')} data-index={optionIndex} /> )} {showResults && <span className='poll__number'> {Math.round(percent)}% </span>} <span className='poll__option__text translate' dangerouslySetInnerHTML={{ __html: titleEmojified }} /> {!!voted && <span className='poll__voted'> <Icon id='check' className='poll__voted__mark' title={intl.formatMessage(messages.voted)} /> </span>} </label> {showResults && ( <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}> {({ width }) => <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} /> } </Motion> )} </li> ); } render () { const { poll, intl } = this.props; const { expired } = this.state; if (!poll) { return null; } const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />; const showResults = poll.get('voted') || expired; const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item); let votesCount = null; if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) { votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />; } else { votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />; } return ( <div className='poll'> <ul> {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))} </ul> <div className='poll__footer'> {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>} {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>} {votesCount} {poll.get('expires_at') && <span> · {timeRemaining}</span>} </div> </div> ); } }
node_modules/react-bootstrap/es/NavItem.js
premcool/getmydeal
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: React.PropTypes.bool, disabled: React.PropTypes.bool, role: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props, active = _props.active, disabled = _props.disabled, onClick = _props.onClick, className = _props.className, style = _props.style, props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
components/Contact.js
mariosandoz/mariosandoz.github.io
import React from 'react'; class Contact extends React.Component{ render(){ return ( <section id="contact"> <div className="container"> <div className="row"> <div className="col-lg-12 text-center"> <h2>Contact Me</h2> <hr className="star-primary"/> </div> </div> <div className="row"> <div className="col-lg-8 col-lg-offset-2"> <form name="sentMessage" id="contactForm" method="POST" action="https://mariosandoz.github.io/mail/contact_me.php" noValidate> <div className="row control-group"> <div className="form-group col-xs-12 floating-label-form-group controls"> <label>Name</label> <input type="text" className="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name." /> <p className="help-block text-danger"></p> </div> </div> <div className="row control-group"> <div className="form-group col-xs-12 floating-label-form-group controls"> <label>Email Address</label> <input type="email" className="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address." /> <p className="help-block text-danger"></p> </div> </div> <div className="row control-group"> <div className="form-group col-xs-12 floating-label-form-group controls"> <label>Phone Number</label> <input type="tel" className="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number." /> <p className="help-block text-danger"></p> </div> </div> <div className="row control-group"> <div className="form-group col-xs-12 floating-label-form-group controls"> <label>Message</label> <textarea rows="5" className="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea> <p className="help-block text-danger"></p> </div> </div> <br/> <div id="success"></div> <div className="row"> <div className="form-group col-xs-12"> <button type="submit" className="btn btn-success btn-lg">Send</button> </div> </div> </form> </div> </div> </div> </section> ) } } export default Contact
demo/icons/social.js
jahglow/MDIcon
/** * Created by IvanP on 23.01.2017. */ import React from 'react'; export const ic_cake = <path d="M12 6c1.11 0 2-.9 2-2 0-.38-.1-.73-.29-1.03L12 0l-1.71 2.97c-.19.3-.29.65-.29 1.03 0 1.1.9 2 2 2zm4.6 9.99l-1.07-1.07-1.08 1.07c-1.3 1.3-3.58 1.31-4.89 0l-1.07-1.07-1.09 1.07C6.75 16.64 5.88 17 4.96 17c-.73 0-1.4-.23-1.96-.61V21c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-4.61c-.56.38-1.23.61-1.96.61-.92 0-1.79-.36-2.44-1.01zM18 9h-5V7h-2v2H6c-1.66 0-3 1.34-3 3v1.54c0 1.08.88 1.96 1.96 1.96.52 0 1.02-.2 1.38-.57l2.14-2.13 2.13 2.13c.74.74 2.03.74 2.77 0l2.14-2.13 2.13 2.13c.37.37.86.57 1.38.57 1.08 0 1.96-.88 1.96-1.96V12C21 10.34 19.66 9 18 9z"/>; export const ic_domain = <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/>; export const ic_group = <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>; export const ic_group_add = <path d="M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z"/>; export const ic_location_city = <path d="M15 11V5l-3-3-3 3v2H3v14h18V11h-6zm-8 8H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm6 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm6 12h-2v-2h2v2zm0-4h-2v-2h2v2z"/>; export const ic_mood = <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>; export const ic_mood_bad = <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 3c-2.33 0-4.31 1.46-5.11 3.5h10.22c-.8-2.04-2.78-3.5-5.11-3.5z"/>; export const ic_notifications = <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>; export const ic_notifications_active = <path d="M7.58 4.08L6.15 2.65C3.75 4.48 2.17 7.3 2.03 10.5h2c.15-2.65 1.51-4.97 3.55-6.42zm12.39 6.42h2c-.15-3.2-1.73-6.02-4.12-7.85l-1.42 1.43c2.02 1.45 3.39 3.77 3.54 6.42zM18 11c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2v-5zm-6 11c.14 0 .27-.01.4-.04.65-.14 1.18-.58 1.44-1.18.1-.24.15-.5.15-.78h-4c.01 1.1.9 2 2.01 2z"/>; export const ic_notifications_none = <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z"/>; export const ic_notifications_off = <path d="M20 18.69L7.84 6.14 5.27 3.49 4 4.76l2.8 2.8v.01c-.52.99-.8 2.16-.8 3.42v5l-2 2v1h13.73l2 2L21 19.72l-1-1.03zM12 22c1.11 0 2-.89 2-2h-4c0 1.11.89 2 2 2zm6-7.32V11c0-3.08-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68c-.15.03-.29.08-.42.12-.1.03-.2.07-.3.11h-.01c-.01 0-.01 0-.02.01-.23.09-.46.2-.68.31 0 0-.01 0-.01.01L18 14.68z"/>; export const ic_notifications_paused = <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.93 6 11v5l-2 2v1h16v-1l-2-2zm-3.5-6.2l-2.8 3.4h2.8V15h-5v-1.8l2.8-3.4H9.5V8h5v1.8z"/>; export const ic_pages = <path d="M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z"/>; export const ic_party_mode = <path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>; export const ic_people = <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>; export const ic_people_outline = <path d="M16.5 13c-1.2 0-3.07.34-4.5 1-1.43-.67-3.3-1-4.5-1C5.33 13 1 14.08 1 16.25V19h22v-2.75c0-2.17-4.33-3.25-6.5-3.25zm-4 4.5h-10v-1.25c0-.54 2.56-1.75 5-1.75s5 1.21 5 1.75v1.25zm9 0H14v-1.25c0-.46-.2-.86-.52-1.22.88-.3 1.96-.53 3.02-.53 2.44 0 5 1.21 5 1.75v1.25zM7.5 12c1.93 0 3.5-1.57 3.5-3.5S9.43 5 7.5 5 4 6.57 4 8.5 5.57 12 7.5 12zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 5.5c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z"/>; export const ic_person = <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>; export const ic_person_add = <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"/>; export const ic_person_outline = <path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/>; export const ic_plus_one = <path d="M10 8H8v4H4v2h4v4h2v-4h4v-2h-4zm4.5-1.92V7.9l2.5-.5V18h2V5z"/>; export const ic_poll = <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>; export const ic_public = <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>; export const ic_school = <path d="M5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82zM12 3L1 9l11 6 9-4.91V17h2V9L12 3z"/>; export const ic_sentiment_dissatisfied = <g><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/></g>; export const ic_sentiment_neutral = <g><path d="M9 14h6v1.5H9z"/><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/></g>; export const ic_sentiment_satisfied = <g><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-4c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2z"/></g>; export const ic_sentiment_very_dissatisfied = <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm4.18-12.24l-1.06 1.06-1.06-1.06L13 8.82l1.06 1.06L13 10.94 14.06 12l1.06-1.06L16.18 12l1.06-1.06-1.06-1.06 1.06-1.06zM7.82 12l1.06-1.06L9.94 12 11 10.94 9.94 9.88 11 8.82 9.94 7.76 8.88 8.82 7.82 7.76 6.76 8.82l1.06 1.06-1.06 1.06zM12 14c-2.33 0-4.31 1.46-5.11 3.5h10.22c-.8-2.04-2.78-3.5-5.11-3.5z"/>; export const ic_sentiment_very_satisfied = <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>; export const ic_share = <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>; export const ic_whatshot = <path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/>;
utils/typography.js
agoldenduck/agoldenduck.github.io
import ReactDOM from 'react-dom/server'; import React from 'react'; import Typography from 'typography'; import { GoogleFont } from 'react-typography'; // import styles from '../pages/styles.css'; const options = { googleFonts: [ { name: 'Source Code Pro', styles: [ '300', '400', '700', ], }, { name: 'Source Sans Pro', styles: [ '400', '400i', '700', ], }, { name: 'Raleway', styles: [ '400', ], }, ], headerFontFamily: ['Raleway', 'sans-serif'], headerWeight: '400', bodyFontFamily: ['Source Sans Pro', 'sans-serif'], bodyWeight: '400', baseFontSize: '20px', baseLineHeight: 1.65, scaleRatio: 3, // plugins: [ // new CodePlugin(), // ], overrideStyles: () => ({ pre: { background: '#FBFBF8', fontFamily: ['Source Code Pro', 'monospace'].join(','), fontWeight: 400, }, code: { fontFamily: ['Source Code Pro', 'monospace'].join(','), fontWeight: 400, }, '.markdown': { paddingBottom: rhythm(1) } }), }; const typography = new Typography(options); export const rhythm = typography.rhythm; // Hot reload typography in development. if (process.env.NODE_ENV !== 'production') { typography.injectStyles(); if (typeof document !== 'undefined') { const googleFonts = ReactDOM.renderToStaticMarkup( React.createFactory(GoogleFont)({ typography }), ); const head = document.getElementsByTagName('head')[0]; head.insertAdjacentHTML('beforeend', googleFonts); } } export default typography;
src/svg-icons/navigation/apps.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationApps = (props) => ( <SvgIcon {...props}> <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z"/> </SvgIcon> ); NavigationApps = pure(NavigationApps); NavigationApps.displayName = 'NavigationApps'; NavigationApps.muiName = 'SvgIcon'; export default NavigationApps;
webpack/components/AnsibleRolesSwitcher/components/AssignedRolesList.js
theforeman/foreman_ansible
import React from 'react'; import { DndProvider } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import { ListView } from 'patternfly-react'; import { orderable, orderDragged, } from 'foremanReact/components/common/forms/OrderableSelect/helpers'; import PropTypes from 'prop-types'; import AnsibleRole from './AnsibleRole'; import AnsibleRoleInputs from './AnsibleRoleInputs'; const OrderableRole = orderable(AnsibleRole, { type: 'ansibleRole', getItem: props => ({ id: props.role.id }), direction: 'vertical', }); const AssignedRolesList = ({ unassignedRoles, assignedRoles, toDestroyRoles, onRemoveRole, onMoveRole, resourceName, }) => { const moveValue = (dragIndex, hoverIndex) => { onMoveRole(orderDragged(assignedRoles, dragIndex, hoverIndex)); }; const allOwnRoles = roles => roles.filter(role => !role.inherited); const renderRole = (role, idx) => role.inherited ? renderInherited(role, idx) : renderOwn(role, idx); const renderInherited = (role, idx) => ( <AnsibleRole key={role.id} role={role} index={idx} icon="fa fa-minus-circle" onClick={onRemoveRole} resourceName={resourceName} /> ); const renderOwn = (role, idx) => ( <OrderableRole key={role.id} role={role} index={idx} moveValue={moveValue} icon="fa fa-minus-circle" onClick={onRemoveRole} resourceName={resourceName} /> ); return ( <DndProvider backend={HTML5Backend}> <ListView>{assignedRoles.map(renderRole)}</ListView> <div> {allOwnRoles(assignedRoles) .concat(toDestroyRoles) .map((role, idx) => ( <AnsibleRoleInputs key={role.id} role={role} idx={idx} resourceName={resourceName} /> ))} </div> </DndProvider> ); }; AssignedRolesList.propTypes = { unassignedRoles: PropTypes.arrayOf(PropTypes.object).isRequired, assignedRoles: PropTypes.arrayOf(PropTypes.object).isRequired, onRemoveRole: PropTypes.func.isRequired, onMoveRole: PropTypes.func.isRequired, resourceName: PropTypes.string.isRequired, toDestroyRoles: PropTypes.arrayOf(PropTypes.object).isRequired, }; export default AssignedRolesList;
node_modules/react-color/src/components/PhotoshopPicker.js
ottomajik/react-demo
'use strict'; /* @flow */ import React from 'react'; import ReactCSS from 'reactcss'; import merge from 'merge'; import _ from 'lodash'; import color from '../helpers/color'; import Photoshop from './photoshop/Photoshop'; class ColorPicker extends ReactCSS.Component { constructor(props: any) { super(); this.state = merge(color.toState(props.color, 0), { visible: props.display, }); this.debounce = _.debounce(function(fn: any, data: any) { fn(data); }, 100); this.handleChange = this.handleChange.bind(this); this.handleHide = this.handleHide.bind(this); this.handleAccept = this.handleAccept.bind(this); this.handleCancel = this.handleCancel.bind(this); } classes(): any { return { 'show': { wrap: { zIndex: '999', position: 'absolute', display: 'block', }, picker: { zIndex: '2', position: 'relative', }, cover: { position: 'fixed', top: '0', bottom: '0', left: '0', right: '0', }, }, 'hide': { wrap: { zIndex: '999', position: 'absolute', display: 'none', }, }, 'right': { wrap: { left: '100%', marginLeft: '20px', top: '0', }, }, 'left': { wrap: { right: '100%', marginRight: '20px', top: '0', }, }, 'below': { wrap: { left: '0', marginLeft: '0', top: '100%', marginTop: '20px', }, }, 'override': { wrap: this.props.positionCSS, }, }; } styles(): any { return this.css({ 'below': this.props.position === 'below' && this.props.display !== null, 'right': this.props.position === 'right' && this.props.display !== null, 'left': this.props.position === 'left' && this.props.display !== null, 'show': this.state.visible === true, 'hide': this.state.visible === false, 'override': _.isPlainObject(this.props.positionCSS), }); } handleHide() { if (this.state.visible === true) { this.setState({ visible: false, }); this.props.onClose && this.props.onClose({ hex: this.state.hex, hsl: this.state.hsl, rgb: this.state.rgb, }); } } handleAccept() { this.handleHide(); } handleCancel() { if (this.state.visible === true) { this.setState({ visible: false, }); } } handleChange(data: any) { data = color.simpleCheckForValidColor(data); if (data) { var colors = color.toState(data, data.h || this.state.oldHue); this.setState(colors); this.props.onChangeComplete && this.debounce(this.props.onChangeComplete, colors); this.props.onChange && this.props.onChange(colors); } } componentWillReceiveProps(nextProps: any) { this.setState(merge(color.toState(nextProps.color, this.state.oldHue), { visible: nextProps.display, })); } render(): any { return ( <div is="wrap"> <div is="picker"> <Photoshop {...this.props} {...this.state} onChange={ this.handleChange } onAccept={ this.handleAccept } onCancel={ this.handleCancel } /> </div> <div is="cover" onClick={ this.handleHide }/> </div> ); } } ColorPicker.defaultProps = { color: { h: 250, s: .50, l: .20, a: 1, }, display: null, type: 'sketch', position: 'right', positionCSS: {}, }; export default ColorPicker;
client/domain/Home/Dashboard/components/DashboardItem.js
briefguo/learn-js
import React from 'react' import { Spin } from 'antd' import Styles from './DashboardItem.css' export default class DashboardItem extends React.Component { static propTypes = { title: React.PropTypes.string, data: React.PropTypes.object, impactKey: React.PropTypes.string, describe: React.PropTypes.array, } constructor(props) { super(props) } render() { const { data, title, impactKey, describe, } = this.props return ( <Spin spinning={data.loading}> <div className={Styles.itemHeader}> {title} </div> <div className={Styles.itemBody}> <h2> {data[impactKey]} </h2> <div> {describe.map((item,key)=>( <span key={key}> {item[0]} {data[item[1]]} <br/> </span> ))} </div> </div> </Spin> ) } }
src/svg-icons/maps/local-pharmacy.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPharmacy = (props) => ( <SvgIcon {...props}> <path d="M21 5h-2.64l1.14-3.14L17.15 1l-1.46 4H3v2l2 6-2 6v2h18v-2l-2-6 2-6V5zm-5 9h-3v3h-2v-3H8v-2h3V9h2v3h3v2z"/> </SvgIcon> ); MapsLocalPharmacy = pure(MapsLocalPharmacy); MapsLocalPharmacy.displayName = 'MapsLocalPharmacy'; MapsLocalPharmacy.muiName = 'SvgIcon'; export default MapsLocalPharmacy;
jenkins-design-language/src/js/components/material-ui/svg-icons/hardware/power-input.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwarePowerInput = (props) => ( <SvgIcon {...props}> <path d="M2 9v2h19V9H2zm0 6h5v-2H2v2zm7 0h5v-2H9v2zm7 0h5v-2h-5v2z"/> </SvgIcon> ); HardwarePowerInput.displayName = 'HardwarePowerInput'; HardwarePowerInput.muiName = 'SvgIcon'; export default HardwarePowerInput;
src/index.js
cloudsherpas-gdc/react-chat-v1
import React from 'react'; import { App } from './App'; React.render(<App url="chat.json" pollInterval={2000} />, document.getElementById('root'));
src/svg-icons/av/call-to-action.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvCallToAction = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3v-3h18v3z"/> </SvgIcon> ); AvCallToAction = pure(AvCallToAction); AvCallToAction.displayName = 'AvCallToAction'; AvCallToAction.muiName = 'SvgIcon'; export default AvCallToAction;
src/components/Track/Description/index.js
lukekarrys/repeatone.club
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import CSSModules from 'react-css-modules'; import Radium from 'radium'; import { random } from 'lodash'; import { sync as imageToStyles } from '../../../helpers/imageToStyles'; @Radium @CSSModules(require('./style.less')) export default class Description extends Component { static propTypes = { count: PropTypes.number.isRequired, track: PropTypes.object.isRequired, user: PropTypes.string.isRequired, image: PropTypes.instanceOf(window.Image), }; state = { darkBg: random(), }; render() { const { count, track, user, image } = this.props; const { name, url, artist } = track; const artistName = artist['#text']; const colors = imageToStyles({ image, darkBg: this.state.darkBg }); return ( <div style={colors.background} styleName="root"> <div style={colors.text} styleName="text"> <a style={colors.link} key="userLink" href={`http://www.last.fm/user/${user}`} > {user} </a>{' '} {count > 1 ? 'has listened to' : "isn't listening to anything on repeat but is currently listening to"}{' '} <a style={colors.link} key="trackLink" href={url}> {name} by {artistName} </a> {count > 1 ? ' on repeat ' : null} {count > 1 ? count : null} {count > 1 ? ' times' : null} </div> </div> ); } }
src/svg-icons/device/data-usage.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceDataUsage = (props) => ( <SvgIcon {...props}> <path d="M13 2.05v3.03c3.39.49 6 3.39 6 6.92 0 .9-.18 1.75-.48 2.54l2.6 1.53c.56-1.24.88-2.62.88-4.07 0-5.18-3.95-9.45-9-9.95zM12 19c-3.87 0-7-3.13-7-7 0-3.53 2.61-6.43 6-6.92V2.05c-5.06.5-9 4.76-9 9.95 0 5.52 4.47 10 9.99 10 3.31 0 6.24-1.61 8.06-4.09l-2.6-1.53C16.17 17.98 14.21 19 12 19z"/> </SvgIcon> ); DeviceDataUsage = pure(DeviceDataUsage); DeviceDataUsage.displayName = 'DeviceDataUsage'; DeviceDataUsage.muiName = 'SvgIcon'; export default DeviceDataUsage;
client/extensions/woocommerce/app/settings/shipping/shipping-zone-list-entry.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Gridicon from 'gridicons'; import { localize } from 'i18n-calypso'; /** * Internal dependencies */ import Button from 'components/button'; import { getLink } from 'woocommerce/lib/nav-utils'; import { getMethodSummary } from './shipping-zone/shipping-methods/utils'; import { getSelectedSite } from 'state/ui/selectors'; import { getShippingZoneMethods } from 'woocommerce/state/ui/shipping/zones/methods/selectors'; import { getCurrencyWithEdits } from 'woocommerce/state/ui/payments/currency/selectors'; const ShippingZoneEntry = ( { translate, id, name, methods, currency, loaded, isValid, site } ) => { if ( ! loaded ) { return ( <div className="shipping__zones-row is-placeholder"> <div className="shipping__zones-row-icon"> <Gridicon icon="globe" size={ 24 } /> </div> <div className="shipping__zones-row-location"> <p className="shipping__zones-row-location-name" /> <p className="shipping__zones-row-location-description" /> </div> <div className="shipping__zones-row-methods"> <div className="shipping__zones-row-method"> <p className="shipping__zones-row-method-name" /> <p className="shipping__zones-row-method-description" /> </div> <div className="shipping__zones-row-method"> <p className="shipping__zones-row-method-name" /> <p className="shipping__zones-row-method-description" /> </div> </div> <div className="shipping__zones-row-actions"> <Button compact>{ translate( 'Edit' ) }</Button> </div> </div> ); } const renderMethodCell = ( title, summary = '', key = 0 ) => { return ( <div key={ key } className="shipping__zones-row-method"> <p className="shipping__zones-row-method-name">{ title }</p> <p className="shipping__zones-row-method-description">{ summary }</p> </div> ); }; const renderMethod = methodKey => { const method = methods[ methodKey ]; let summary = getMethodSummary( method, currency ); if ( ! method.enabled ) { summary = translate( '%(summary)s - Disabled', { args: { summary }, comment: 'Summary of a disabled shipping method in WooCommerce', } ); } return renderMethodCell( method.title, summary, methodKey ); }; const icon = 0 === id ? 'globe' : 'location'; const onEditClick = event => { if ( ! isValid ) { event.preventDefault(); } }; return ( <div className="shipping__zones-row"> <div className="shipping__zones-row-icon"> <Gridicon icon={ icon } size={ 24 } /> </div> <div className="shipping__zones-row-location"> <p className="shipping__zones-row-location-name">{ name }</p> { /*<p className="shipping__zones-row-location-description">{ locationDescription }</p>*/ } </div> <div className="shipping__zones-row-methods"> { methods && methods.length ? Object.keys( methods ).map( renderMethod ) : renderMethodCell( translate( 'No shipping methods' ) ) } </div> <div className="shipping__zones-row-actions"> <Button compact href={ getLink( `/store/settings/shipping/zone/:site/${ id }`, site ) } disabled={ ! isValid } onClick={ onEditClick } > { translate( 'Edit' ) } </Button> </div> </div> ); }; ShippingZoneEntry.propTypes = { id: PropTypes.oneOfType( [ PropTypes.number, PropTypes.object ] ), name: PropTypes.string, loaded: PropTypes.bool.isRequired, isValid: PropTypes.bool.isRequired, }; export default connect( ( state, ownProps ) => ( { site: getSelectedSite( state ), methods: ownProps.loaded && getShippingZoneMethods( state, ownProps.id ), currency: ownProps.loaded && getCurrencyWithEdits( state ), } ) )( localize( ShippingZoneEntry ) );
pootle/static/js/auth/components/RequestPasswordResetForm.js
claudep/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import assign from 'object-assign'; import React from 'react'; import { PureRenderMixin } from 'react-addons-pure-render-mixin'; import FormElement from 'components/FormElement'; import FormMixin from 'mixins/FormMixin'; import { gotoScreen, requestPasswordReset } from '../actions'; import AuthContent from './AuthContent'; import RequestPasswordResetProgress from './RequestPasswordResetProgress'; const RequestPasswordResetForm = React.createClass({ propTypes: { canRegister: React.PropTypes.bool.isRequired, dispatch: React.PropTypes.func.isRequired, formErrors: React.PropTypes.object.isRequired, isLoading: React.PropTypes.bool.isRequired, }, mixins: [PureRenderMixin, FormMixin], /* Lifecycle */ getInitialState() { this.initialData = { email: '', }; return { formData: assign({}, this.initialData), }; }, componentWillReceiveProps(nextProps) { if (this.state.errors !== nextProps.formErrors) { this.setState({ errors: nextProps.formErrors }); } }, /* Handlers */ handleSignIn(e) { e.preventDefault(); this.props.dispatch(gotoScreen('signIn')); }, handleSignUp(e) { e.preventDefault(); this.props.dispatch(gotoScreen('signUp')); }, handleFormSubmit(e) { e.preventDefault(); this.props.dispatch(requestPasswordReset(this.state.formData)); }, /* Others */ hasData() { return this.state.formData.email !== ''; }, /* Layout */ render() { if (this.props.isLoading) { return <RequestPasswordResetProgress email={this.state.formData.email} />; } const { errors } = this.state; const { formData } = this.state; return ( <AuthContent> <form method="post" onSubmit={this.handleFormSubmit} > <div className="fields"> {this.renderAllFormErrors()} <FormElement autoFocus type="email" label={gettext('Email Address')} help={gettext('Enter your email address, and we will send you a ' + 'message with the special link to reset your password.')} handleChange={this.handleChange} name="email" errors={errors.email} value={formData.email} /> </div> <div className="actions"> <div> <a href="#" onClick={this.handleSignIn}> {gettext('No, thanks')} </a> </div> <div> <input type="submit" className="btn btn-primary" disabled={!this.hasData()} value={gettext('Send Email')} /> </div> {this.props.canRegister && <div> <a href="#" onClick={this.handleSignUp}> {gettext('Sign up as a new user')} </a> </div> } </div> </form> </AuthContent> ); }, }); export default RequestPasswordResetForm;
springboot/GReact/src/main/resources/static/app/routes/widgets/components/Widgets.js
ezsimple/java
/** * Created by griga on 11/30/15. */ import React from 'react' import {Alert , OverlayTrigger , Popover , Dropdown , MenuItem} from 'react-bootstrap' import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../components' import TabbedWidgetDemo from './TabbedWidgetDemo' import SwitchWidgetDemo from './SwitchWidgetDemo' export default class Widgets extends React.Component { render() { return ( <div id="content"> <div className="row"> <BigBreadcrumbs items={['Widgets']} icon="list-alt" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/> <Stats /> </div> <div className="row"> <div className="col-sm-12"> <Alert bsStyle="info" className="fade in"> <button className="close" data-dismiss="alert"> × </button> <i className="fa-fw fa fa-info"/> <strong>Heads up!</strong> If the widgets are not reacting to your drag and drop events on chrome, try to turn off chrome touch events by going to, <a href="chrome://flags/#touch-events">chrome:\/\/flags/#touch-events</a> if you do not have a touch screen. </Alert> <Alert className="well"> <button className="close" data-dismiss="alert"> &#xD7; </button> <h1><span className="semi-bold">Smart</span> <i className="ultra-light">Widgets</i> (aka JarvisWidgets) <sup className="badge bg-color-red bounceIn animated">v 2.0</sup> <br /> <small className="text-danger slideInRight fast animated"><strong>Exclusive to SmartAdmin!</strong></small> </h1> <p>The all new and revolutionary JarvisWidgets v2.0 (<strong>$35 value</strong>) is now only exclusive to SmartAdmin. JarvisWidgets allows you to do more than your normal widgets. You can now use realtime <OverlayTrigger placement="bottom" overlay={ <Popover id="ajax-loading-popover"> <span className=''>You can load content with ajax. You can even set a 'last updated' timestamp (customizable) a refresh button and set an auto refresh timer.</span> </Popover> }> <a className="semi-bold"> AJAX loading </a> </OverlayTrigger> in a snap with auto refresh. Add <OverlayTrigger placement="bottom" overlay={ <Popover id="action-buttons-popover"> You can use 5 types of action buttons, toggle, edit, fullscreen, delete and custom button(s) which you can set for a custom action(s). You can even change the order of the action buttons. You can set a custom icon for every button. You can also add your own custom buttons, tabs, progress bars and more. </Popover> }> <a className="semi-bold"> Infinite </a> </OverlayTrigger> buttons and controls to widget header. All widgets are <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-sortable-popover"> The Jarvis Widgets are sortable, on tablet and some phones. Dont want sortable widgets on tables/phones, no problem you can remove this. </Popover> }> <a className="semi-bold"> Sortable </a> </OverlayTrigger> across all bootstrap col-spans and uses <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-localStorage-popover"> This plugin gives you the option to let you save a couple of settings for example the position, color and title of the widget. </Popover> }> <a className="semi-bold"> HTML5 localStorage </a> </OverlayTrigger> . Also now supports <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-RTL-popover"> This plugin is by default ltr, but it has a rtl option. </Popover> }> <a className="semi-bold"> RTL Support </a> </OverlayTrigger> , <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-Crosbrowser-popover"> The Jarvis Widget works in every modern browser on windows, ios, osx, android, blackberry and windows phone. </Popover> }> <a className="semi-bold"> Crosbrowser Support </a> </OverlayTrigger> , <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-Callback-popover"> The Jarvis Widget plugin has a couple of callback function wich you can use for several things, for example, use AJAX to store the data into a database. </Popover> }> <a className="semi-bold"> Callback functions </a> </OverlayTrigger> and <OverlayTrigger placement="bottom" overlay={ <Popover id="jarvis-More-popover"> To give you more control you can set a lot of options per widget by using a dataset tag which will override the main plugin settings. </Popover> }> <a className="semi-bold"> More </a> </OverlayTrigger> ..</p> </Alert> </div> </div> {/* widget grid */} <WidgetGrid> {/* row */} <div className="row"> {/* NEW WIDGET START */} <article className="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <JarvisWidget > <header> <h2><strong>Default</strong> <i>Widget</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <p> Widget comes with a default 10 padding to the body which can be removed by adding the class <code>.no-padding</code> to the <code>.widget-body</code> class. The default widget also comes with 5 widget buttons as displayed on top right corner of the widget header. </p> <a href="#" className="btn btn-default btn-lg"> <strong>Big</strong> <i>Button</i> </a> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} <JarvisWidget colorbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} color="blue"> <header> <h2><strong>Title</strong> <i>Change</i></h2> </header> <div> {/* widget content */} <div className="widget-body"> <h3 className="alert alert-info"> Activate Options Button </h3> <code>data-widget-editbutton</code> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} color="greenLight"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>Full</strong> <i>Screen</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <h2 className="alert alert-success"> Make any widget full screen</h2> <code>data-widget-fullscreenbutton</code> <br /><br /> <p>Usefull when viewing images, gallery, tables with large data and maps. There are much useful applications to this method</p> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} togglebutton={false} editbutton={false} fullscreenbutton={false} color="red"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>Delete</strong> <i>Widget </i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <h6 className="alert alert-warning semi-bold"> <i className="fa fa-times"/> By deleting a widget you will <strong>remove</strong> the widget from the page and will need to connect the backend with the onevent handler to delete it from database. </h6> <code>data-widget-deletebutton</code> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget togglebutton={false} editbutton={false} deletebutton={false} fullscreenbutton={false}> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>Widget</strong> <i>Colors</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <div className="row"> <div className="col-md-6 col-lg-8"> <h5><strong>Change</strong> and <i>save</i> widget <u>color</u></h5> <code>colorbutton</code> <br /> <br /> <p>Change widget color at will and SmartAdmin will permanently remember the color of your chosen widget. Do this to any widget in any page and SmartAdmin will keep track of all your widgets!</p> </div> <div className="col-md-6 col-lg-4"> <img src="assets/img/demo/widget-colorpicker.png" alt="widget colorpicker" className="pull-right hover-transparent img-responsive"/> </div> </div> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} color="pink"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <span className="widget-icon"> <i className="fa fa-comments"/> </span> <h2><strong>Label &amp; Badges</strong></h2> <div className="widget-toolbar"> <div className="label label-success"> <i className="fa fa-arrow-up"/> 2.35% </div> </div> <div className="widget-toolbar"> <div className="badge bg-color-blue"> 99 </div> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> {/* widget toolbar */} <div className="widget-body-toolbar text-center"> <div className="badge bg-color-purple"> small badge </div> <div className="label label-warning"> <i className="fa fa-check"/> I am a big label </div> </div> {/* end widget toolbar */} {/* widget body text*/} <p className="alert alert-info"> Add label inside widget footer / toolbar </p> {/* end widget body text*/} {/* widget footer */} <div className="widget-footer"> <div className="badge bg-color-greenLight pull-left"> 13 </div> <div className="label label-danger"> <i className="fa fa-arrow-down"/> -1.75% </div> </div> {/* end widget footer */} </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} <TabbedWidgetDemo /> {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget load="assets/api/html/widget-demo.html" colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false}> <header> <h2><strong>Refresh</strong> <i>Widget</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> {/* widget body text*/} <p>This content will be replaced via ajax loader...</p> {/* end widget body text*/} </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} </article> {/* WIDGET END */} {/* NEW WIDGET START */} <article className="col-xs-12 col-sm-6 col-md-6 col-lg-6"> {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget editbutton={false} colorbutton={false} deletebutton={false} fullscreenbutton={false} color="darken"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <span className="widget-icon"> <i className="fa fa-arrows-v"/> </span> <h2 className="font-md"><strong>Collapsable</strong> <i>Widget</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <h2 className="alert alert-warning"> This widget is opened by default </h2> <code>data-widget-togglebutton</code> <br /><br /> <p>Notice the header text size slightly larger than other widget headers</p> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget editbutton={false} colorbutton={false} deletebutton={false} fullscreenbutton={false} collapsed={true}> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <span className="widget-icon"> <i className="fa fa-arrows-v"/> </span> <h2><strong><i>Collapsed </i></strong> <small>Widget</small> </h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <h2 className="alert alert-warning"> This widget is collapsed by default </h2> <code>data-widget-collapsed</code> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} togglebutton={false} editbutton={false} fullscreenbutton={false} deletebutton={false} color="purple"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>Progress</strong> <i>bars</i></h2> <div className="widget-toolbar"> <div className="progress progress-striped active" data-tooltip="55%" data-tooltip-placement="bottom"> <div className="progress-bar progress-bar-success" role="progressbar" style={{width: '55%'}}>55 % </div> </div> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body no-padding"> <div className="widget-body-toolbar"> <div className="btn-group"> <button type="button" className="btn btn-default"> <i className="fa fa-bold"/> </button> <button type="button" className="btn btn-default"> <i className="fa fa-italic"/> </button> <button type="button" className="btn btn-default"> <i className="fa fa-underline"/> </button> </div> <div className="btn-group"> <button type="button" className="btn btn-default"> <i className="fa fa-align-left"/> </button> <button type="button" className="btn btn-default"> <i className="fa fa-align-center"/> </button> <button type="button" className="btn btn-default"> <i className="fa fa-align-right"/> </button> <button type="button" className="btn btn-default"> <i className="fa fa-align-justify"/> </button> </div> </div> <textarea className="form-control no-border" placeholder="Textarea" rows="4" defaultValue={' This is a textarea - below me is widget footer and above is the widget toolbar!'}/> <div className="widget-footer"> <button className="btn btn-sm btn-primary" type="button"> Save </button> <button className="btn btn-sm btn-danger disabled pull-left" type="button"> Delete </button> </div> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget editbutton={false} colorbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} color="blueLight"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <span className="widget-icon"> <i className="fa fa-hand-o-up"/> </span> <h2><strong>Widget</strong> <i>buttons</i></h2> <div className="widget-toolbar"> <a href="#" className="btn btn-primary">Btn</a> </div> <div className="widget-toolbar"> <div className="btn-group" data-toggle="buttons"> <label className="btn btn-default btn-xs active"> <input type="radio" name="style-a1" id="style-a1"/> <i className="fa fa-play"></i> </label> <label className="btn btn-default btn-xs"> <input type="radio" name="style-a2" id="style-a2"/> <i className="fa fa-pause"></i> </label> <label className="btn btn-default btn-xs"> <input type="radio" name="style-a2" id="style-a3"/> <i className="fa fa-stop"></i> </label> </div> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <h4 className="alert alert-info"> Insert buttons to header manually or dynamically </h4> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} togglebutton={false} editbutton={false} fullscreenbutton={false} deletebutton={false} color="orange"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>With</strong> <i>Paging</i></h2> <div className="widget-toolbar"> <ul className="pagination pagination-xs"> <li className="disabled"> <a href="#">Prev</a> </li> <li className="active"> <a href="#">1</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">Next</a> </li> </ul> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body no-padding"> <p className="alert alert-success"><strong><i className="fa fa-check"/> Alert</strong> without body padding... </p> <p className="padding-10"> Notice this widget body has no padding!</p> <div className="widget-footer"> <button className="btn btn-sm btn-success disabled" type="button"> Previous </button> <button className="btn btn-sm btn-success" type="button"> Next </button> </div> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} <JarvisWidget colorbutton={false} togglebutton={false} editbutton={false} fullscreenbutton={false} deletebutton={false} color="blueDark"> <header> <span className="widget-icon"> <i className="fa fa-arrow-down"/> </span> <h2><strong>Widget</strong> <i><u>with</u> Dropdown</i></h2> <div className="widget-toolbar"> <Dropdown className="btn-group" id="widget-demo-dropdown"> <Dropdown.Toggle className="btn btn-xs dropdown-toggle btn-warning"> Dropdown </Dropdown.Toggle> <Dropdown.Menu className="dropdown-menu pull-right"> <MenuItem> Option 1 </MenuItem> <MenuItem> Option 2 </MenuItem> <MenuItem> Option 3 </MenuItem> <MenuItem divider/> <MenuItem> Option 4 </MenuItem> </Dropdown.Menu> </Dropdown> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> Add dropdowns to header with ease. Making sure to add btn-xs class when using dropdowns on the widget header. </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> <SwitchWidgetDemo /> {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget sortable={false} colorbutton={false} togglebutton={false} editbutton={false} fullscreenbutton={false} deletebutton={false} color="darken"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <span className="widget-icon"> <i className="fa fa-lock"/> </span> <h2><strong>Locked</strong> <i>Widget</i></h2> <div className="widget-toolbar smart-form"> <label className="input"> <i className="icon-append fa fa-question-circle"/> <input type="text" placeholder="Focus to view the tooltip"/> <b className="tooltip tooltip-top-right"> <i className="fa fa-warning txt-color-teal"/> Some helpful information</b> </label> </div> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body"> <p className="alert alert-success"><i className="fa fa-lock"/> Locked widgets lock the widget to the base grid (<i>you will not be able to drag this widget</i> ). This also allows you to append and use input text elmenets on the widget header. </p> <code>data-widget-sortable=&quot;<strong>false</strong>&quot;</code> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} editbutton={false} color="greenDark"> {/* widget options: usage: <div id="wid-id-0" editbutton={false}> colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} fullscreenbutton={false} custombutton={false} collapsed={true} sortable={false} */} <header> <h2><strong>Fixed</strong> <i>Height</i></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body no-padding"> <div className="widget-body-toolbar"> <div className="row"> <div className="col-xs-9 col-sm-5 col-md-5 col-lg-5"> <div className="input-group"> <span className="input-group-addon"><i className="fa fa-search"></i></span> <input className="form-control" id="prepend" placeholder="Filter" type="text"/> </div> </div> <div className="col-xs-3 col-sm-7 col-md-7 col-lg-7 text-right"> <button className="btn btn-success"> <i className="fa fa-plus"/> <span className="hidden-mobile">Add New Row</span> </button> </div> </div> </div> <div className="custom-scroll table-responsive" style={{height:'290px', overflowY: 'scroll'}}> <table className="table table-bordered"> <thead> <tr> <th><i className="fa fa-key text-warning"/> License Key</th> <th>Username <i className="text-danger">!</i></th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>C87E48EF-605A-B4FF</td> <td>erat@montesnasceturridiculus.org</td> <td>10/03/13</td> </tr> <tr> <td>5DDA79E7-890F-064D</td> <td>Nunc.lectus@ipsum.co.uk</td> <td>28/12/13</td> </tr> <tr> <td>468459AA-7933-C017</td> <td>vitae.mauris.sit@tempordiamdictum.net</td> <td>25/02/14</td> </tr> <tr> <td>C3006C18-4677-D2CE</td> <td>nec.urna.suscipit@acrisusMorbi.edu</td> <td>06/07/14</td> </tr> <tr> <td>E535C188-FDF4-90CB</td> <td>lobortis@pedeacurna.com</td> <td>28/12/12</td> </tr> <tr> <td>95489E95-9602-18B7</td> <td>egestas.lacinia.Sed@In.ca</td> <td>17/07/14</td> </tr> <tr> <td>D34E6661-D81A-9328</td> <td>arcu@lectus.ca</td> <td>14/10/14</td> </tr> <tr> <td>C72D2C04-458F-EBD0</td> <td>ut.pharetra.sed@vulputatevelit.net</td> <td>30/04/14</td> </tr> <tr> <td>10CAFA5C-AB4B-8B45</td> <td>arcu.eu.odio@Duis.co.uk</td> <td>14/02/13</td> </tr> <tr> <td>AA4F5CBA-1CE8-85B7</td> <td>nec@rutrum.net</td> <td>06/02/14</td> </tr> <tr> <td>2D816071-8F99-B315</td> <td>Praesent.luctus.Curabitur@elementum.ca</td> <td>27/09/13</td> </tr> <tr> <td>41BDB60C-C6EA-54EB</td> <td>Nunc.sed.orci@sitamet.org</td> <td>18/11/13</td> </tr> <tr> <td>43F3D48B-FEF3-776E</td> <td>eu.erat@nequevitaesemper.com</td> <td>23/04/13</td> </tr> <tr> <td>2521899F-79B9-B309</td> <td>mattis.velit@risusQuisque.ca</td> <td>04/07/13</td> </tr> <tr> <td>D08994C9-DCB1-948B</td> <td>Proin@metusAliquam.net</td> <td>27/07/13</td> </tr> <tr> <td>7AD2C774-36BA-0B2B</td> <td>tincidunt@Lorem.com</td> <td>01/07/14</td> </tr> <tr> <td>162C0373-FF3B-2469</td> <td>ante.dictum.cursus@ultrices.org</td> <td>10/02/13</td> </tr> <tr> <td>05641987-3D48-DD72</td> <td>lorem.ut.aliquam@Sednecmetus.org</td> <td>16/08/14</td> </tr> <tr> <td>3A173E5A-192A-0D5D</td> <td>nunc.risus@vitae.org</td> <td>04/04/13</td> </tr> <tr> <td>67081066-E0B5-9E37</td> <td>lectus@sed.org</td> <td>10/12/14</td> </tr> <tr> <td>C677C05F-7D98-C3E9</td> <td>auctor.quis@Morbi.org</td> <td>30/03/13</td> </tr> </tbody> </table> </div> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} </article> {/* WIDGET END */} </div> {/* end row */} {/* row */} <div className="row"> <div className="col-sm-12"> <div className="well"> <h1>Basic Usage</h1> <div className="alert alert-info"> Note: You must delete the data-attribute* associated in order to act as true. For example <code> data-widget-togglebutton=&quot;true&quot;</code> will still act as <code>false</code>, you must remove the <strong>data-attribute</strong> for the statement to be true. </div> <table className="table table-bordered"> <thead> <tr> <th style={{width:'25%'}}>HTML5 data attributes / CSS / HTML</th> <th style={{width:'15%'}}>Place after</th> <th style={{width:'15%'}}>Example value(s)</th> <th style={{width:'45%'}}>Desctription</th> </tr> </thead> <tbody> <tr> <td>data-widget-sortable</td> <td><code>header</code></td> <td>false</td> <td>Prevent a widget from being sortable <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-icon</td> <td><code>.jarviswidget</code></td> <td>fa fa-trash</td> <td>Use a icon in the widgets header <i>(see icons section for all list of icons)</i>. </td> </tr> <tr> <td>data-widget-togglebutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Prevent a widget from having a toggle button <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-deletebutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Prevent a widget from having a delete button <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-editbutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Prevent a widget from having a edit button <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-fullscreenbutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Prevent a widget from having a fullscreen button <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-load</td> <td><code>.jarviswidget</code></td> <td>widget-ajax.php</td> <td>The file that is loaded with ajax.</td> </tr> <tr> <td>data-widget-refresh</td> <td><code>.jarviswidget</code></td> <td>10</td> <td>Seconds to refresh a ajax file <i>(see 'data-widget-load')</i>.</td> </tr> <tr> <td>data-widget-refreshbutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Prevent a ajax widget from showing a refresh button <i>(can only be used with the value 'false')</i>. </td> </tr> <tr> <td>data-widget-hidden</td> <td><code>.jarviswidget</code></td> <td>true</td> <td>Hide a widget at load <i>(can only be used with the value 'true')</i>.</td> </tr> <tr> <td> colorbutton</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>This is active by default, set it to false to hide.</td> </tr> <tr> <td>data-widget-collapsed</td> <td><code>.jarviswidget</code></td> <td>false</td> <td>Collapse a widget upon load <i>(can only be used with the value 'true')</i>. This will allways be collapsed every page load. </td> </tr> <tr> <td>data-widget-grid</td> <td><code>article</code></td> <td>false</td> <td>You can exclude grids from being a sortable/droppable area, this means that all widgets in this area will work, but cant be sortable/droppable and that all other widgets cant be dropped in this area. Add this attribute <i>(can only be used with the value 'false')</i> to a grid element. </td> </tr> <tr> <td><code>.no-padding</code></td> <td><code>.widget-body</code></td> <td>n/a</td> <td>Removes all padding inside widget body</td> </tr> <tr> <td><code>.well</code></td> <td><code>.jarviswidget</code></td> <td>n/a</td> <td>Converts a widget to a well</td> </tr> </tbody> <tfoot> <tr> <td colSpan="4">These HTML5 attributes are used as individual widget options. Main options can be changed in the widgets plugin it self. Notice: data attributes can only have 1 boolan value(see above)! </td> </tr> </tfoot> </table> </div> </div> </div> {/* end row */} </WidgetGrid> {/* end widget grid */} </div> ) } }
analysis/deathknightblood/src/modules/talents/RapidDecomposition.js
yajinni/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import TalentStatisticBox from 'parser/ui/TalentStatisticBox'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import Events from 'parser/core/Events'; class RapidDecomposition extends Analyzer { bpDamage = 0; dndDamage = 0; totalDamage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.RAPID_DECOMPOSITION_TALENT.id); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.BLOOD_PLAGUE, SPELLS.DEATH_AND_DECAY_DAMAGE_TICK]), this.onDamage); } onDamage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.BLOOD_PLAGUE.id) { this.bpDamage += calculateEffectiveDamage(event, 0.15); }else { this.dndDamage += calculateEffectiveDamage(event, 0.15); } this.totalDamage = this.bpDamage + this.dndDamage; } statistic() { return ( <TalentStatisticBox talent={SPELLS.RAPID_DECOMPOSITION_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(2)} value={this.owner.formatItemDamageDone(this.totalDamage)} tooltip={( <> <strong>Blood Plague:</strong> {this.owner.formatItemDamageDone(this.bpDamage)}<br /> <strong>Death And Decay:</strong> {this.owner.formatItemDamageDone(this.dndDamage)} </> )} /> ); } } export default RapidDecomposition;
src/toolbar/InsertModalHeader.js
prajapati-parth/react-bootstrap-table
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Util from '../util'; class InsertModalHeader extends Component { handleCloseBtnClick = e => { const { onModalClose, beforeClose } = this.props; beforeClose && beforeClose(e); onModalClose(); } renderContent(closeBtn) { const { version, title: titleText } = this.props; const title = <h4 key='title' className='modal-title'>{ titleText }</h4>; if (Util.isBootstrap4(version)) { return [ title, closeBtn ]; } else { return ( <span> { closeBtn } { title } </span> ); } } render() { const { hideClose, className, children } = this.props; const closeBtn = hideClose ? null : ( <button type='button' className='close' onClick={ this.handleCloseBtnClick }> <span aria-hidden='true'>&times;</span> <span className='sr-only'>Close</span> </button> ); const content = children || this.renderContent(closeBtn); return ( <div className={ `modal-header ${className}` }> { content } </div> ); } } InsertModalHeader.propTypes = { version: PropTypes.string, className: PropTypes.string, title: PropTypes.string, onModalClose: PropTypes.func, hideClose: PropTypes.bool, beforeClose: PropTypes.func }; InsertModalHeader.defaultProps = { version: '3', className: '', title: 'Add Row', onModalClose: undefined, hideClose: false, beforeClose: undefined }; export default InsertModalHeader;
app/modules/core/components/Route/index.js
anton-drobot/frontend-starter
import React, { Component } from 'react'; import { observer } from 'mobx-react'; /*type Props = { router?: RouterStore, route: string, match: boolean, children?: Node, component?: ComponentType<any> };*/ @observer export default class Router extends Component { static defaultProps = { match: false }; render() { const { match, children, component: Component } = this.props; if (match) { if (Component) { return ( <Component /> ); } if (children) { return children; } } return null; } }
src/CarouselItem.js
deerawan/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const CarouselItem = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, caption: React.PropTypes.node, index: React.PropTypes.number }, getInitialState() { return { direction: null }; }, getDefaultProps() { return { active: false, animateIn: false, animateOut: false }; }, handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.handleAnimateOutEnd ); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render() { let classes = { item: true, active: (this.props.active && !this.props.animateIn) || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} {this.props.caption ? this.renderCaption() : null} </div> ); }, renderCaption() { return ( <div className="carousel-caption"> {this.props.caption} </div> ); } }); export default CarouselItem;
src/components/FileUploader/FileUploader-story.js
wfp/ui
/** * 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. */ /* eslint-disable no-console */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, array, boolean, number, select, text, } from '@storybook/addon-knobs'; import settings from '../../globals/js/settings'; import FileUploader, { FileUploaderButton } from '.'; import FileUploaderSkeleton from './FileUploader.Skeleton'; import FileUploaderItem from './FileUploaderItem'; import FileUploaderDropContainer from './FileUploaderDropContainer'; const { prefix } = settings; const buttonKinds = { 'Primary (primary)': 'primary', 'Secondary (secondary)': 'secondary', 'Danger (danger)': 'danger', 'Ghost (ghost)': 'ghost', 'Danger Primary (danger--primary)': 'danger--primary', 'Tertiary (tertiary)': 'tertiary', }; const filenameStatuses = { 'Edit (edit)': 'edit', 'Complete (complete)': 'complete', 'Uploading (uploading)': 'uploading', }; const props = { fileUploaderButton: () => { const buttonKind = select('Button kind (buttonKind)', buttonKinds, ''); return { className: 'bob', labelText: text('Label text (labelText)', 'Add files'), name: text('Form item name: (name)', ''), multiple: boolean('Supports multiple files (multiple)', true), disabled: boolean('Disabled (disabled)', false), buttonKind: buttonKind || 'primary', disableLabelChanges: boolean( 'Prevent the label from being replaced with file selected file (disableLabelChanges)', false ), role: text('ARIA role of the button (role)', 'button'), tabIndex: number('Tab index (tabIndex)', 0), onChange: action('onChange'), }; }, fileUploader: () => ({ labelTitle: text('The label title (labelTitle)', 'Upload'), labelDescription: text( 'The label description (labelDescription)', 'only .jpg files at 500mb or less' ), buttonLabel: text('The button label (buttonLabel)', 'Add files'), filenameStatus: select( 'Status for file name (filenameStatus)', filenameStatuses, 'edit' ), accept: array('Accepted file extensions (accept)', ['.jpg', '.png'], ','), name: text('Form item name: (name)', ''), multiple: boolean('Supports multiple files (multiple)', true), iconDescription: text( 'Close button icon description (iconDescription)', 'Clear file' ), }), fileUploaderItem: () => ({ name: text('Filename (name)', 'README.md'), status: select('Status for file name (status)', filenameStatuses, 'edit'), iconDescription: text( 'Close button icon description (iconDescription)', 'Clear file' ), onDelete: action('onDelete'), invalid: boolean('Invalid (invalid)', false), errorSubject: text( 'Error subject (errorSubject)', 'File size exceeds limit' ), errorBody: text( 'Error body (errorBody)', '500kb max file size. Select a new file and try again.' ), }), fileUploaderDropContainer: () => ({ labelText: text( 'Label text (labelText)', 'Drag and drop files here or click to upload' ), name: text('Form item name (name)', ''), multiple: boolean('Supports multiple files (multiple)', true), accept: array( 'Accepted MIME types or file extensions (accept)', ['image/jpeg', 'image/png'], ',' ), disabled: boolean('Disabled (disabled)', false), role: text('ARIA role of the button (role)', ''), tabIndex: number('Tab index (tabIndex)', 0), onChange: action('onChange'), }), }; storiesOf('Components|FileUploader', module) .addDecorator(withKnobs) .add('FileUploaderButton', () => ( <FileUploaderButton {...props.fileUploaderButton()} /> )) .add('FileUploader', () => { return ( <div className={`${prefix}--file__container`}> <FileUploader {...props.fileUploader()} /> </div> ); }) .add('FileUploaderItem', () => ( <FileUploaderItem {...props.fileUploaderItem()} /> )) .add('FileUploaderDropContainer', () => ( <FileUploaderDropContainer {...props.fileUploaderDropContainer()} /> )) .add('Drag and drop upload container example application', () => require('./stories/drop-container').default( props.fileUploaderDropContainer() ) ) .add('skeleton', () => ( <div style={{ width: '500px' }}> <FileUploaderSkeleton /> </div> ));
packages/wix-style-react/src/TableActionCell/docs/examples/PrimarySecondaryExample.js
wix/wix-style-react
import React from 'react'; import Star from 'wix-ui-icons-common/Star'; import Download from 'wix-ui-icons-common/Download'; import Duplicate from 'wix-ui-icons-common/Duplicate'; import Print from 'wix-ui-icons-common/Print'; import { classes } from '../TableActionCell.story.st.css'; import { TableActionCell } from 'wix-style-react'; const Example = () => ( <div className={classes.exampleRow}> <TableActionCell dataHook="story-primary-secondary" primaryAction={{ text: 'Edit', skin: 'inverted', onClick: () => window.alert('Primary action was triggered!'), }} secondaryActions={[ { text: 'Star', icon: <Star />, onClick: () => window.alert('Star action was triggered.'), }, { text: 'Download', icon: <Download />, onClick: () => window.alert('Download action was triggered.'), }, { text: 'Duplicate', icon: <Duplicate />, onClick: () => window.alert('Duplicate action was triggered.'), }, { text: 'Print', icon: <Print />, onClick: () => window.alert('Print action was triggered.'), }, ]} numOfVisibleSecondaryActions={1} /> </div> ); export default Example;
src/ResourceHeader.js
intljusticemission/react-big-calendar
import PropTypes from 'prop-types' import React from 'react' const ResourceHeader = ({ label }) => { return <React.Fragment>{label}</React.Fragment> } ResourceHeader.propTypes = { label: PropTypes.node, index: PropTypes.number, resource: PropTypes.object, } export default ResourceHeader
src/svg-icons/action/shopping-cart.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShoppingCart = (props) => ( <SvgIcon {...props}> <path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); ActionShoppingCart = pure(ActionShoppingCart); ActionShoppingCart.displayName = 'ActionShoppingCart'; ActionShoppingCart.muiName = 'SvgIcon'; export default ActionShoppingCart;
examples/react-native/src/screens/Home.js
supasate/connected-react-router
import React from 'react'; import {View, Text, StyleSheet, Button} from 'react-native'; const Home = ({history}) => ( <View> <Text style={styles.title}>Home</Text> <Button color="blue" onPress={() => { history.push({ pathname: '/account', search: '?accountId=42', }); }} title="Go to account with accountId: 42" /> </View> ); const styles = StyleSheet.create({ title: { color: 'black', fontSize: 24, fontWeight: '600', }, }); export default Home;
src/svg-icons/image/crop.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop = (props) => ( <SvgIcon {...props}> <path d="M17 15h2V7c0-1.1-.9-2-2-2H9v2h8v8zM7 17V1H5v4H1v2h4v10c0 1.1.9 2 2 2h10v4h2v-4h4v-2H7z"/> </SvgIcon> ); ImageCrop = pure(ImageCrop); ImageCrop.displayName = 'ImageCrop'; ImageCrop.muiName = 'SvgIcon'; export default ImageCrop;
components/Form/Star/Star.js
NGMarmaduke/bloom
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import cx from 'classnames'; import css from './Star.css'; import Icon from '../../Icon/Icon'; import Radio from '../Radio/Radio'; export default class Star extends Component { static propTypes = { className: PropTypes.string, iconClassName: PropTypes.string, } focus = () => { this.component.focus(); } blur = () => { this.component.blur(); } render() { const { className, iconClassName, ...rest } = this.props; return ( <Radio { ...rest } className={ cx(css.root, className) } ref={ (c) => { this.component = c; } } > <Icon name="star" className={ cx(css.star, iconClassName) } /> </Radio> ); } }
src/components/views/globals/PasswordNagBar.js
aperezdc/matrix-react-sdk
/* Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import sdk from '../../../index'; import Modal from '../../../Modal'; import { _t } from '../../../languageHandler'; export default React.createClass({ onUpdateClicked: function() { const SetPasswordDialog = sdk.getComponent('dialogs.SetPasswordDialog'); Modal.createTrackedDialog('Set Password Dialog', 'Password Nag Bar', SetPasswordDialog); }, render: function() { const toolbarClasses = "mx_MatrixToolbar mx_MatrixToolbar_clickable"; return ( <div className={toolbarClasses} onClick={this.onUpdateClicked}> <img className="mx_MatrixToolbar_warning" src="img/warning.svg" width="24" height="23" alt="Warning" /> <div className="mx_MatrixToolbar_content"> { _t( "To return to your account in future you need to <u>set a password</u>", {}, { 'u': (sub) => <u>{ sub }</u> }, ) } </div> <button className="mx_MatrixToolbar_action"> { _t("Set Password") } </button> </div> ); }, });
src/components/distributions/summary/index.js
getguesstimate/guesstimate-app
import React from 'react' import numberShow from 'lib/numberShower/numberShower' import './style.css' const PrecisionNumber = ({value, precision, number=numberShow(value, precision)}) => ( <span> {number.value}{number.symbol} {number.power && (<span>{`\u00b710`}<span className='sup'>{number.power}</span></span>)} </span> ) const PointDisplay = ({value, precision=6}) => ( <div className='mean'> <PrecisionNumber value={value} precision={precision}/> </div> ) const DistributionDisplay = ({mean, range: [low, high]}) => ( <div> <PointDisplay value={mean} precision={2}/> <div className='UncertaintyRange'> <PrecisionNumber value={low}/> to <PrecisionNumber value={high}/> </div> </div> ) // TODO(matthew): Ostensibly I'd like to handle the defensivity upstream, but this is a good quick fix for the problem // exposed to customers presently. export const DistributionSummary = ({length, mean, adjustedConfidenceInterval, precision=6}) => ( <div className="DistributionSummary"> {length === 1 || _.some(adjustedConfidenceInterval, e => !_.isFinite(e)) ? <PointDisplay value={mean} precision={precision}/> : <DistributionDisplay mean={mean} range={adjustedConfidenceInterval}/> } </div> )
src/Thumbnail.js
laran/react-bootstrap
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const Thumbnail = React.createClass({ mixins: [BootstrapMixin], propTypes: { alt: React.PropTypes.string, href: React.PropTypes.string, src: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'thumbnail' }; }, render() { let classes = this.getBsClassSet(); if (this.props.href) { return ( <SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </SafeAnchor> ); } if (this.props.children) { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> <div className="caption"> {this.props.children} </div> </div> ); } return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </div> ); } }); export default Thumbnail;
react-twitter-save-data-loading(client-hint)/src/components/Twitter/Context.js
GoogleChromeLabs/adaptive-loading
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles'; class Context extends React.Component { render () { const {data, linkProps} = this.props; return ( <div className="context" style={styles.context}> <div className="tweet-context"> <svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 24 24" style={{'verticalAlign': 'sub'}}> <path opacity="0" d="M0 0h24v24H0z"></path> <path fill="rgb(101, 119, 134)" d="M23.615 15.477c-.47-.47-1.23-.47-1.697 0l-1.326 1.326V7.4c0-2.178-1.772-3.95-3.95-3.95h-5.2c-.663 0-1.2.538-1.2 1.2s.537 1.2 1.2 1.2h5.2c.854 0 1.55.695 1.55 1.55v9.403l-1.326-1.326c-.47-.47-1.23-.47-1.697 0s-.47 1.23 0 1.697l3.374 3.375c.234.233.542.35.85.35s.613-.116.848-.35l3.375-3.376c.467-.47.467-1.23-.002-1.697zM12.562 18.5h-5.2c-.854 0-1.55-.695-1.55-1.55V7.547l1.326 1.326c.234.235.542.352.848.352s.614-.117.85-.352c.468-.47.468-1.23 0-1.697L5.46 3.8c-.47-.468-1.23-.468-1.697 0L.388 7.177c-.47.47-.47 1.23 0 1.697s1.23.47 1.697 0L3.41 7.547v9.403c0 2.178 1.773 3.95 3.95 3.95h5.2c.664 0 1.2-.538 1.2-1.2s-.535-1.2-1.198-1.2z"></path> </svg> <span className="retweet-text" style={styles.retweet}> <a className={styles.prettyLink} href={`https://twitter.com/${data.user.screen_name}`} style={{'textDecoration': 'none', 'color': '#657786'}} {...linkProps}> {data.user.name} </a> {' Retweeted'} </span> </div> </div> ); }; } Context.propTypes = { 'data': PropTypes.object }; Context.displayName = 'Context'; export default Context;
src/svg-icons/device/signal-cellular-1-bar.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M12 12L2 22h10z"/> </SvgIcon> ); DeviceSignalCellular1Bar = pure(DeviceSignalCellular1Bar); DeviceSignalCellular1Bar.displayName = 'DeviceSignalCellular1Bar'; DeviceSignalCellular1Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular1Bar;
src/segment/StatisticSegment.js
alelk/houses-building-website
/** * Statistic Segment * * Created by Alex Elkin on 31.10.2017. */ import './StatisticSegment.css' import React from 'react' import PropTypes from 'prop-types' import {Container, Header, Icon, Segment, Statistic} from 'semantic-ui-react' const mapStatistics = (statistic, key) => { const {color, topLabel, valueLabel, iconName, bottomLabel} = statistic; return ( <Statistic key={key} color={color || 'black'} className="companyStatistic" size="small"> {topLabel && <Statistic.Label>{topLabel}</Statistic.Label>} <Statistic.Value> {iconName && <Icon name={iconName}/>} {valueLabel} </Statistic.Value> {bottomLabel && <Statistic.Label>{bottomLabel}</Statistic.Label>} </Statistic> ) }; class StatisticSegment extends React.Component { render() { const {statistics} = this.props; return ( <Segment className="StatisticSegment" raised> <Header as='h3'>Преимущества работы с нами</Header> <Container> { statistics && statistics.map(mapStatistics) } </Container> </Segment> ) } } StatisticSegment.propTypes = { statistics : PropTypes.arrayOf(PropTypes.shape({ topLabel : PropTypes.string, bottomLabel : PropTypes.string, valueLabel : PropTypes.string, iconName : PropTypes.string, color : PropTypes.string })) }; export default StatisticSegment;
src/components/time/TimePicker.js
wayofthefuture/react-input-moment
import cx from 'classnames'; import React from 'react'; import InputSlider from 'react-input-slider'; export default class extends React.Component { constructor(props) { super(props); } render() { let mom = this.props.moment; return ( <div className={cx('im-time-picker', this.props.className)}> <div className="time-picker-wrapper"> <div className="showtime"> <span className="time">{mom.format('HH')}</span> <span className="separator">:</span> <span className="time">{mom.format('mm')}</span> {this.props.showSeconds && <span> <span className="separator">:</span> <span className="time">{mom.format('ss')}</span> </span> } </div> <div className="sliders"> <div className="time-text">Hours:</div> <InputSlider className="im-slider" xmin={0} xmax={23} x={mom.hour()} onChange={this.changeHours.bind(this)} /> <div className="time-text">Minutes:</div> <InputSlider className="im-slider" xmin={0} xmax={59} x={mom.minute()} onChange={this.changeMinutes.bind(this)} /> {this.props.showSeconds && <div className="time-text">Seconds:</div> } {this.props.showSeconds && <InputSlider className="im-slider" xmin={0} xmax={59} x={mom.second()} onChange={this.changeSeconds.bind(this)} /> } </div> </div> </div> ); } changeHours(pos) { if (window.event && window.event.stopPropagation) window.event.stopPropagation(); //bug fix for picker within react modal component let mom = this.props.moment.clone(); mom.hours(parseInt(pos.x, 10)); this.props.onChange(mom); } changeMinutes(pos) { if (window.event && window.event.stopPropagation) window.event.stopPropagation(); //bug fix for picker within react modal component let mom = this.props.moment.clone(); mom.minutes(parseInt(pos.x, 10)); this.props.onChange(mom); } changeSeconds(pos) { if (window.event && window.event.stopPropagation) window.event.stopPropagation(); //bug fix for picker within react modal component let mom = this.props.moment.clone(); mom.seconds(parseInt(pos.x, 10)); this.props.onChange(mom); } }
cm19/ReactJS/your-first-react-app-exercises-master/exercise-9/Exercise.js
Brandon-J-Campbell/codemash
import React from 'react'; import PropTypes from 'prop-types'; export default function Exercise() { return <Friends friends={myFriends} />; } function Friends({ friends }) { return ( <Page> {friends.map(friend => ( <FriendProfile key={friend.id} name={friend.name} image={friend.image} /> ))} </Page> ); } function Page({ children }) { return ( <div className="page"> <div className="content">{children}</div> </div> ); } function Card({ children }) { return <div className="card">{children}</div>; } function FriendProfile({ name, image }) { return ( <Card> <div className="friend-profile"> <img src={image} alt={name} /> <h3>{name}</h3> </div> </Card> ); } const myFriends = [ { id: 1, name: 'Potatoes', image: 'http://placekitten.com/150/150?image=1', }, { id: 2, name: 'Flower', image: 'http://placekitten.com/150/150?image=12', }, { id: 3, name: 'Turtle', image: 'http://placekitten.com/150/150?image=15', }, ];
docs/src/app/components/pages/components/TextField/Page.js
mtsandeep/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 textFieldReadmeText from './README'; import TextFieldExampleSimple from './ExampleSimple'; import textFieldExampleSimpleCode from '!raw!./ExampleSimple'; import TextFieldExampleCustomize from './ExampleCustomize'; import textFieldExampleCustomizeCode from '!raw!./ExampleCustomize'; import TextFieldExampleError from './ExampleError'; import textFieldExampleErrorCode from '!raw!./ExampleError'; import TextFieldExampleDisabled from './ExampleDisabled'; import textFieldExampleDisabledCode from '!raw!./ExampleDisabled'; import TextFieldExampleControlled from './ExampleControlled'; import textFieldExampleControlledCode from '!raw!./ExampleControlled'; import textFieldCode from '!raw!material-ui/TextField/TextField'; const descriptions = { simple: 'Examples demonstrating key Text Field features.', error: 'The `errorText` property used in combination with various other features.', styled: 'Examples of styling various Text Field features.', disabled: 'Various examples of `disabled` Text Fields.', controlled: 'A controlled Text Field example.', }; const TextFieldsPage = () => ( <div> <Title render={(previousTitle) => `Text Field - ${previousTitle}`} /> <MarkdownElement text={textFieldReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={textFieldExampleSimpleCode} > <TextFieldExampleSimple /> </CodeExample> <CodeExample title="Error examples" description={descriptions.error} code={textFieldExampleErrorCode} > <TextFieldExampleError /> </CodeExample> <CodeExample title="Styled examples" description={descriptions.styled} code={textFieldExampleCustomizeCode} > <TextFieldExampleCustomize /> </CodeExample> <CodeExample title="Disabled examples" description={descriptions.disabled} code={textFieldExampleDisabledCode} > <TextFieldExampleDisabled /> </CodeExample> <CodeExample title="Controlled example" description={descriptions.controlled} code={textFieldExampleControlledCode} > <TextFieldExampleControlled /> </CodeExample> <PropTypeDescription code={textFieldCode} /> </div> ); export default TextFieldsPage;
scratch/App.js
dmod/fdcallstats.com
import React, { Component } from 'react'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Container, Row, Col, Jumbotron, Button } from 'reactstrap'; class App extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { message: null, isOpen: false, fetching: true }; } componentDidMount() { fetch('/api') .then(response => { if (!response.ok) { throw new Error(`status ${response.status}`); } console.log(response) return response.json(); }) .then(json => { this.setState({ message: json.message, fetching: false }); }).catch(e => { this.setState({ message: `API call failed: ${e}`, fetching: false }); }) } toggle() { this.setState({ isOpen: !this.state.isOpen }); } render() { return ( <div> <Navbar color="inverse" light expand="md"> <NavbarBrand href="/">reactstrap</NavbarBrand> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className="ml-auto" navbar> <NavItem> <NavLink href="/components/">Components</NavLink> </NavItem> <NavItem> <NavLink href="https://github.com/reactstrap/reactstrap">Github</NavLink> </NavItem> </Nav> </Collapse> </Navbar> <Jumbotron> <Container> <Row> <Col> <h1>Welcome to React</h1> <p> <Button tag="a" color="success" size="large" href="http://reactstrap.github.io" target="_blank" > View Reactstrap Docs </Button> </p> </Col> </Row> </Container> </Jumbotron> <p className="App-intro"> {this.state.fetching ? 'Fetching message from API' : this.state.message} </p> </div> ); } } export default App;
examples/with-custom-webpack-config/src/client.js
jaredpalmer/razzle
import React from 'react'; import { hydrate } from 'react-dom'; import App from './App'; hydrate(<App />, document.getElementById('root')); if (module.hot) { module.hot.accept(); }
src/containers/foiRequests/FoiRequestsPublicBodyScreen.js
jfilter/frag-den-staat-app
import { ActivityIndicator, Text, View } from 'react-native'; import { NavigationActions } from 'react-navigation'; import { connect } from 'react-redux'; import React from 'react'; import { fetchPublicBody } from '../../actions/publicBodies'; import { foiRequestsFilterChange } from '../../actions/foiRequests'; import { primaryColorLight } from '../../globals/colors'; import PublicBodyDetails from '../../components/screens/PublicBodyDetails'; // eslint-disable-next-line react/prop-types class FoiRequestPublicBodyScreen extends React.Component { componentDidMount() { const { publicBody, publicBodyId, fetchPB } = this.props; if (!publicBody || publicBody.id != publicBodyId) { fetchPB(publicBodyId); } } render() { const { isPending, error, publicBody, changeFilter, navigateToFoiRequests1, navigateToFoiRequests2, navigateToCreateRequest, } = this.props; if (!publicBody || isPending) { return ( <View style={{ backgroundColor: 'white', paddingTop: 10, height: '100%' }} > <ActivityIndicator animating size="large" color={primaryColorLight} /> </View> ); } else if (error) { return ( <View> <Text>Error: {error}</Text> </View> ); } return ( <PublicBodyDetails publicBody={publicBody} navigateToFoiRequests1={navigateToFoiRequests1} navigateToFoiRequests2={navigateToFoiRequests2} navigateToCreateRequest={navigateToCreateRequest} changeFilter={changeFilter} /> ); } } FoiRequestPublicBodyScreen.navigationOptions = PublicBodyDetails.navigationOptions; const mapStateToProps = (state, props) => { return { publicBody: state.publicBodies.publicBody, isPending: state.publicBodies.isPending, error: state.publicBodies.error, publicBodyId: props.navigation.state.params.publicBodyId, }; }; const mapDispatchToProps = dispatch => { return { changeFilter: publicBody => dispatch(foiRequestsFilterChange(publicBody)), fetchPB: publicBodyId => dispatch(fetchPublicBody(publicBodyId)), navigateToFoiRequests1: () => dispatch( NavigationActions.navigate({ routeName: 'Requests', }) ), navigateToFoiRequests2: () => dispatch(NavigationActions.navigate({ routeName: 'FoiRequestsMaster' })), navigateToCreateRequest: publicBody => dispatch( NavigationActions.navigate({ routeName: 'NewRequestWrite', params: { publicBody }, }) ), }; }; export default connect( mapStateToProps, mapDispatchToProps )(FoiRequestPublicBodyScreen);
src/components/DeveloperMenu.js
justinhaaheim/empower-app
import React from 'react'; import {View} from 'react-native'; // For tests const DeveloperMenu = () => <View/>; export default DeveloperMenu;
spec/javascripts/jsx/gradebook/default_gradebook/GradebookGrid/headers/TotalGradeColumnHeaderSpec.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import TotalGradeColumnHeader from 'jsx/gradebook/default_gradebook/GradebookGrid/headers/TotalGradeColumnHeader' import {blurElement, getMenuContent, getMenuItem} from './ColumnHeaderSpecHelpers' /* eslint-disable qunit/no-identical-names */ QUnit.module('GradebookGrid TotalGradeColumnHeader', suiteHooks => { let $container let $menuContent let component let gradebookElements let props suiteHooks.beforeEach(() => { $container = document.body.appendChild(document.createElement('div')) gradebookElements = [] props = { addGradebookElement($el) { gradebookElements.push($el) }, gradeDisplay: { currentDisplay: 'points', disabled: false, hidden: false, onSelect() {} }, onMenuDismiss() {}, position: { isInBack: false, isInFront: false, onMoveToBack() {}, onMoveToFront() {} }, removeGradebookElement($el) { gradebookElements.splice(gradebookElements.indexOf($el), 1) }, sortBySetting: { direction: 'ascending', disabled: false, isSortColumn: true, onSortByGradeAscending() {}, onSortByGradeDescending() {}, settingKey: 'grade' } } }) suiteHooks.afterEach(() => { ReactDOM.unmountComponentAtNode($container) $container.remove() }) function mountComponent() { component = ReactDOM.render(<TotalGradeColumnHeader {...props} />, $container) } function getOptionsMenuTrigger() { return [...$container.querySelectorAll('button')].find( $button => $button.textContent === 'Total Options' ) } function getOptionsMenuContent() { const $button = getOptionsMenuTrigger() return document.querySelector(`[aria-labelledby="${$button.id}"]`) } function openOptionsMenu() { getOptionsMenuTrigger().click() $menuContent = getOptionsMenuContent() } function mountAndOpenOptionsMenu() { mountComponent() openOptionsMenu() } function closeOptionsMenu() { getOptionsMenuTrigger().click() } test('displays "Total" as the column title', () => { mountComponent() ok($container.textContent.includes('Total')) }) QUnit.module('"Options" menu trigger', () => { test('is labeled with "Total Options"', () => { mountComponent() const $trigger = getOptionsMenuTrigger() ok($trigger.textContent.includes('Total Options')) }) test('opens the options menu when clicked', () => { mountComponent() getOptionsMenuTrigger().click() ok(getOptionsMenuContent()) }) test('closes the options menu when clicked', () => { mountAndOpenOptionsMenu() getOptionsMenuTrigger().click() notOk(getOptionsMenuContent()) }) }) QUnit.module('"Options" menu', () => { QUnit.module('when opened', contextHooks => { contextHooks.beforeEach(() => { mountAndOpenOptionsMenu() }) test('is added as a Gradebook element', () => { notEqual(gradebookElements.indexOf($menuContent), -1) }) test('adds the "menuShown" class to the action container', () => { const $actionContainer = $container.querySelector('.Gradebook__ColumnHeaderAction') ok($actionContainer.classList.contains('menuShown')) }) }) QUnit.module('when closed', contextHooks => { contextHooks.beforeEach(() => { props.onMenuDismiss = sinon.stub() mountAndOpenOptionsMenu() closeOptionsMenu() }) test('is removed as a Gradebook element', () => { strictEqual(gradebookElements.indexOf($menuContent), -1) }) test('calls the onMenuDismiss callback', () => { strictEqual(props.onMenuDismiss.callCount, 1) }) test('removes the "menuShown" class from the action container', () => { const $actionContainer = $container.querySelector('.Gradebook__ColumnHeaderAction') notOk($actionContainer.classList.contains('menuShown')) }) }) }) QUnit.module('"Options" > "Sort by" setting', () => { function getSortByOption(label) { return getMenuItem($menuContent, 'Sort by', label) } test('is added as a Gradebook element when opened', () => { mountAndOpenOptionsMenu() const $sortByMenuContent = getMenuContent($menuContent, 'Sort by') notEqual(gradebookElements.indexOf($sortByMenuContent), -1) }) test('is removed as a Gradebook element when closed', () => { mountAndOpenOptionsMenu() const $sortByMenuContent = getMenuContent($menuContent, 'Sort by') closeOptionsMenu() strictEqual(gradebookElements.indexOf($sortByMenuContent), -1) }) QUnit.module('"Grade - Low to High" option', () => { test('is selected when sorting by grade ascending', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'ascending' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - Low to High').getAttribute('aria-checked'), 'true') }) test('is not selected when sorting by grade descending', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'descending' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - Low to High').getAttribute('aria-checked'), 'false') }) test('is not selected when sorting by a different setting', () => { props.sortBySetting.settingKey = 'missing' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - Low to High').getAttribute('aria-checked'), 'false') }) test('is not selected when isSortColumn is false', () => { props.sortBySetting.isSortColumn = false mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - Low to High').getAttribute('aria-checked'), 'false') }) test('is optionally disabled', () => { props.sortBySetting.disabled = true mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - Low to High').getAttribute('aria-disabled'), 'true') }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.sortBySetting.onSortByGradeAscending = sinon.stub() }) test('calls the .sortBySetting.onSortByGradeAscending callback', () => { mountAndOpenOptionsMenu() getSortByOption('Grade - Low to High').click() strictEqual(props.sortBySetting.onSortByGradeAscending.callCount, 1) }) test('returns focus to the "Options" menu trigger', () => { mountAndOpenOptionsMenu() getSortByOption('Grade - Low to High').focus() getSortByOption('Grade - Low to High').click() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) // TODO: GRADE-____ QUnit.skip( 'does not call the .sortBySetting.onSortByGradeAscending callback when already selected', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'ascending' mountAndOpenOptionsMenu() getSortByOption('Grade - Low to High').click() strictEqual(props.sortBySetting.onSortByGradeAscending.callCount, 0) } ) }) }) QUnit.module('"Grade - High to Low" option', () => { test('is selected when sorting by grade descending', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'descending' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - High to Low').getAttribute('aria-checked'), 'true') }) test('is not selected when sorting by grade ascending', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'ascending' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - High to Low').getAttribute('aria-checked'), 'false') }) test('is not selected when sorting by a different setting', () => { props.sortBySetting.settingKey = 'missing' mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - High to Low').getAttribute('aria-checked'), 'false') }) test('is not selected when isSortColumn is false', () => { props.sortBySetting.isSortColumn = false mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - High to Low').getAttribute('aria-checked'), 'false') }) test('is optionally disabled', () => { props.sortBySetting.disabled = true mountAndOpenOptionsMenu() strictEqual(getSortByOption('Grade - High to Low').getAttribute('aria-disabled'), 'true') }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.sortBySetting.onSortByGradeDescending = sinon.stub() }) test('calls the .sortBySetting.onSortByGradeDescending callback', () => { mountAndOpenOptionsMenu() getSortByOption('Grade - High to Low').click() strictEqual(props.sortBySetting.onSortByGradeDescending.callCount, 1) }) test('returns focus to the "Options" menu trigger', () => { mountAndOpenOptionsMenu() getSortByOption('Grade - High to Low').focus() getSortByOption('Grade - High to Low').click() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) // TODO: GRADE-____ QUnit.skip( 'does not call the .sortBySetting.onSortByGradeDescending callback when already selected', () => { props.sortBySetting.settingKey = 'grade' props.sortBySetting.direction = 'ascending' mountAndOpenOptionsMenu() getSortByOption('Grade - High to Low').click() strictEqual(props.sortBySetting.onSortByGradeDescending.callCount, 0) } ) }) }) }) QUnit.module('"Options" > "Display as Percentage" action', hooks => { hooks.beforeEach(() => { props.gradeDisplay.currentDisplay = 'points' }) test('is present when the total grade is being displayed as points', () => { mountAndOpenOptionsMenu() ok(getMenuItem($menuContent, 'Display as Percentage')) }) test('is not present when the total grade is being displayed as a percentage', () => { props.gradeDisplay.currentDisplay = 'percentage' mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Display as Percentage')) }) test('is not present when the total grade display cannot be changed', () => { props.gradeDisplay.hidden = true mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Display as Percentage')) }) test('is disabled when .gradeDisplay.disabled is true', () => { props.gradeDisplay.disabled = true mountAndOpenOptionsMenu() const $menuItem = getMenuItem($menuContent, 'Display as Percentage') strictEqual($menuItem.getAttribute('aria-disabled'), 'true') }) test('is not disabled when .gradeDisplay.disabled is false', () => { props.gradeDisplay.disabled = false mountAndOpenOptionsMenu() const $menuItem = getMenuItem($menuContent, 'Display as Percentage') strictEqual($menuItem.getAttribute('aria-disabled'), null) }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.gradeDisplay.onSelect = sinon.stub() }) test('does not immediately restore focus', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Percentage').click() notEqual(document.activeElement, getOptionsMenuTrigger()) }) test('calls the .gradeDisplay.onSelect callback', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Percentage').click() strictEqual(props.gradeDisplay.onSelect.callCount, 1) }) test('includes a focus-restoring callback when calling .gradeDisplay.onSelect', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Percentage').click() const [callback] = props.gradeDisplay.onSelect.lastCall.args callback() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) }) }) QUnit.module('"Options" > "Display as Points" action', hooks => { hooks.beforeEach(() => { props.gradeDisplay.currentDisplay = 'percentage' }) test('is present when the total grade is being displayed as percentage', () => { mountAndOpenOptionsMenu() ok(getMenuItem($menuContent, 'Display as Points')) }) test('is not present when the total grade is being displayed as a points', () => { props.gradeDisplay.currentDisplay = 'points' mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Display as Points')) }) test('is not present when the total grade display cannot be changed', () => { props.gradeDisplay.hidden = true mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Display as Points')) }) test('is disabled when .gradeDisplay.disabled is true', () => { props.gradeDisplay.disabled = true mountAndOpenOptionsMenu() const $menuItem = getMenuItem($menuContent, 'Display as Points') strictEqual($menuItem.getAttribute('aria-disabled'), 'true') }) test('is not disabled when .gradeDisplay.disabled is false', () => { props.gradeDisplay.disabled = false mountAndOpenOptionsMenu() const $menuItem = getMenuItem($menuContent, 'Display as Points') strictEqual($menuItem.getAttribute('aria-disabled'), null) }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.gradeDisplay.onSelect = sinon.stub() }) test('does not immediately restore focus', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Points').click() notEqual(document.activeElement, getOptionsMenuTrigger()) }) test('calls the .gradeDisplay.onSelect callback', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Points').click() strictEqual(props.gradeDisplay.onSelect.callCount, 1) }) test('includes a focus-restoring callback when calling .gradeDisplay.onSelect', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Display as Points').click() const [callback] = props.gradeDisplay.onSelect.lastCall.args callback() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) }) }) QUnit.module('"Options" > "Move to Front" action', hooks => { hooks.beforeEach(() => { props.position.isInFront = false }) test('is present when the column is in the scrollable section', () => { mountAndOpenOptionsMenu() ok(getMenuItem($menuContent, 'Move to Front')) }) test('is not present when the column is in the frozen section', () => { props.position.isInFront = true mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Move to Front')) }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.position.onMoveToFront = sinon.stub() }) test('restores focus to the "Options" menu trigger', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Move to Front').click() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) test('calls the .position.onMoveToFront callback', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Move to Front').click() strictEqual(props.position.onMoveToFront.callCount, 1) }) }) }) QUnit.module('"Options" > "Move to End" action', hooks => { hooks.beforeEach(() => { props.position.isInBack = false }) test('is present when the column is in the scrollable section', () => { mountAndOpenOptionsMenu() ok(getMenuItem($menuContent, 'Move to End')) }) test('is not present when the column is in the frozen section', () => { props.position.isInBack = true mountAndOpenOptionsMenu() notOk(getMenuItem($menuContent, 'Move to End')) }) QUnit.module('when clicked', contextHooks => { contextHooks.beforeEach(() => { props.position.onMoveToBack = sinon.stub() }) test('restores focus to the "Options" menu trigger', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Move to End').click() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) test('calls the .position.onMoveToBack callback', () => { mountAndOpenOptionsMenu() getMenuItem($menuContent, 'Move to End').click() strictEqual(props.position.onMoveToBack.callCount, 1) }) }) }) QUnit.module('#handleKeyDown()', hooks => { let preventDefault hooks.beforeEach(() => { preventDefault = sinon.spy() mountComponent() }) function handleKeyDown(which, shiftKey = false) { return component.handleKeyDown({which, shiftKey, preventDefault}) } QUnit.module('when the "Options" menu trigger has focus', contextHooks => { contextHooks.beforeEach(() => { getOptionsMenuTrigger().focus() }) test('does not handle Tab', () => { // This allows Grid Support Navigation to handle navigation. const returnValue = handleKeyDown(9, false) // Tab equal(typeof returnValue, 'undefined') }) test('does not handle Shift+Tab', () => { // This allows Grid Support Navigation to handle navigation. const returnValue = handleKeyDown(9, true) // Shift+Tab equal(typeof returnValue, 'undefined') }) test('Enter opens the the "Options" menu', () => { handleKeyDown(13) // Enter ok($menuContent) }) test('returns false for Enter', () => { // This prevents additional behavior in Grid Support Navigation. const returnValue = handleKeyDown(13) // Enter strictEqual(returnValue, false) }) }) QUnit.module('when the header does not have focus', () => { test('does not handle Tab', () => { const returnValue = handleKeyDown(9, false) // Tab equal(typeof returnValue, 'undefined') }) test('does not handle Shift+Tab', () => { const returnValue = handleKeyDown(9, true) // Shift+Tab equal(typeof returnValue, 'undefined') }) test('does not handle Enter', () => { const returnValue = handleKeyDown(13) // Enter equal(typeof returnValue, 'undefined') }) }) }) QUnit.module('focus', hooks => { hooks.beforeEach(() => { mountComponent() }) test('#focusAtStart() sets focus on the "Options" menu trigger', () => { component.focusAtStart() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) test('#focusAtEnd() sets focus on the "Options" menu trigger', () => { component.focusAtEnd() strictEqual(document.activeElement, getOptionsMenuTrigger()) }) test('adds the "focused" class to the header when the "Options" menu trigger receives focus', () => { getOptionsMenuTrigger().focus() ok($container.firstChild.classList.contains('focused')) }) test('removes the "focused" class from the header when focus leaves', () => { getOptionsMenuTrigger().focus() blurElement(getOptionsMenuTrigger()) notOk($container.firstChild.classList.contains('focused')) }) }) }) /* eslint-enable qunit/no-identical-names */
src/components/todo/container.js
shawnzhang009/react-starter
import React from 'react' import Paper from 'material-ui/Paper' import AppBar from 'material-ui/AppBar' import IconButton from 'material-ui/IconButton' import IconMenu from 'material-ui/IconMenu' import MenuItem from 'material-ui/MenuItem' import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert' import TodoInput from './todoInput' import TodoList from './todoList' export default class Container extends React.Component { constructor(props) { super(props) this._setNewItem = this._setNewItem.bind(this) this.state = { newItem: '' } } componentDidMount() { } _setNewItem(d) { if (d != null && d != undefined && d != '') { this.setState({ newItem: d }) } } render() { const Logged = (props) => ( <IconMenu {...props} iconButtonElement={ <IconButton ><MoreVertIcon /></IconButton> } targetOrigin={{ horizontal: 'right', vertical: 'top' }} anchorOrigin={{ horizontal: 'right', vertical: 'top' }} > <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help" /> <MenuItem primaryText="Sign out" /> </IconMenu> ) Logged.muiName = 'IconMenu' return ( <div> <AppBar className="todo-container" onLeftIconButtonTouchTap={this.props.toggleDrawer} title='Todoer' iconElementRight={<Logged />} /> <div> <Paper className='todo-paper' zDepth={2}> <TodoInput setNewItem={this._setNewItem} /> <TodoList newItem={this.state.newItem} /> </Paper> </div> </div> ) } }
src/containers/Interfaces/OrdinalBin.js
codaco/Network-Canvas
import React from 'react'; import { compose } from 'redux'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { isNil } from 'lodash'; import withPrompt from '../../behaviours/withPrompt'; import { PromptSwiper, OrdinalBins } from '../'; import { makeGetPromptVariable, makeNetworkNodesForType } from '../../selectors/interface'; import { MultiNodeBucket } from '../../components'; import { entityAttributesProperty } from '../../ducks/modules/network'; /** * OrdinalBin Interface */ const OrdinalBin = ({ promptForward, promptBackward, prompt, nodesForPrompt, stage, }) => { const { prompts, } = stage; return ( <div className="ordinal-bin-interface"> <div className="ordinal-bin-interface__prompt"> <PromptSwiper forward={promptForward} backward={promptBackward} prompt={prompt} prompts={prompts} /> </div> <div className="ordinal-bin-interface__bucket"> <MultiNodeBucket nodes={nodesForPrompt} listId={`${stage.id}_${prompt.id}_NODE_BUCKET`} itemType="EXISTING_NODE" sortOrder={prompt.bucketSortOrder} /> </div> <div className="ordinal-bin-interface__bins"> <OrdinalBins stage={stage} prompt={prompt} /> </div> </div> ); }; OrdinalBin.propTypes = { stage: PropTypes.object.isRequired, prompt: PropTypes.object.isRequired, promptForward: PropTypes.func.isRequired, promptBackward: PropTypes.func.isRequired, nodesForPrompt: PropTypes.array.isRequired, }; function makeMapStateToProps() { const getStageNodes = makeNetworkNodesForType(); const getPromptVariable = makeGetPromptVariable(); return (state, props) => { const stageNodes = getStageNodes(state, props); const activePromptVariable = getPromptVariable(state, props); return { nodesForPrompt: stageNodes.filter( node => isNil(node[entityAttributesProperty][activePromptVariable]), ), }; }; } export default compose( withPrompt, connect(makeMapStateToProps), )(OrdinalBin);
app/packs/src/admin/generic/UploadModal.js
ComPlat/chemotion_ELN
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dropzone from 'react-dropzone'; import { Modal } from 'react-bootstrap'; export default class UploadModal extends Component { constructor(props) { super(props); this.formRef = React.createRef(); this.handleUploadTemplate = this.handleUploadTemplate.bind(this); } handleReaderLoaded(e) { const reader = e.target; const pt = reader.result; let properties = {}; let isVaild = true; let message = ''; try { properties = JSON.parse(pt); } catch (err) { isVaild = false; message = `Error Format:${err}`; } if (isVaild && properties.klass !== this.props.klass) { isVaild = false; message = `Error, the template is from [${properties.klass}]` ; } if (isVaild) { this.props.fnUpload(properties); } else { this.props.fnUpload(null, message, false); } } handleUploadTemplate(file) { const reader = new FileReader(); reader.onload = this.handleReaderLoaded.bind(this); reader.readAsText(file[0]); } render() { const { content, showModal, fnClose } = this.props; return ( <Modal show={showModal} onHide={() => fnClose()}> <Modal.Header closeButton><Modal.Title>{`Upload ${content} Templates`}</Modal.Title></Modal.Header> <Modal.Body style={{ overflow: 'auto' }}> <Dropzone onDrop={attach => this.handleUploadTemplate(attach)} style={{ height: 50, width: '100%', border: '3px dashed lightgray' }}> <div style={{ textAlign: 'center', paddingTop: 12, color: 'gray' }}> Drop File, or Click to Select. </div> </Dropzone> </Modal.Body> </Modal> ); } } UploadModal.propTypes = { content: PropTypes.string.isRequired, showModal: PropTypes.bool.isRequired, fnClose: PropTypes.func.isRequired, fnUpload: PropTypes.func.isRequired, };
src/server.js
zangrafx/react-redux-universal-hot-example
import Express from 'express'; import React from 'react'; import Location from 'react-router/lib/Location'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import api from './api/api'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; import Html from './Html'; import PrettyError from 'pretty-error'; const pretty = new PrettyError(); const app = new Express(); const proxy = httpProxy.createProxyServer({ target: 'http://localhost:' + config.apiPort }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(require('serve-static')(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const store = createStore(client); const location = new Location(req.path, req.query); if (__DISABLE_SSR__) { res.send('<!doctype html>\n' + React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={<div/>} store={store}/>)); } else { universalRouter(location, undefined, store) .then(({component, transition, isRedirect}) => { if (isRedirect) { res.redirect(transition.redirectInfo.pathname); return; } res.send('<!doctype html>\n' + React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }) .catch((error) => { if (error.redirect) { res.redirect(error.redirect); return; } console.error('ROUTER ERROR:', pretty.render(error)); res.status(500).send({error: error.stack}); }); } }); if (config.port) { app.listen(config.port, (err) => { if (err) { console.error(err); } else { api().then(() => { console.info('==> ✅ Server is listening'); console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort); console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port); }); } }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
jenkins-design-language/src/js/components/material-ui/svg-icons/action/favorite-border.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionFavoriteBorder = (props) => ( <SvgIcon {...props}> <path d="M16.5 3c-1.74 0-3.41.81-4.5 2.09C10.91 3.81 9.24 3 7.5 3 4.42 3 2 5.42 2 8.5c0 3.78 3.4 6.86 8.55 11.54L12 21.35l1.45-1.32C18.6 15.36 22 12.28 22 8.5 22 5.42 19.58 3 16.5 3zm-4.4 15.55l-.1.1-.1-.1C7.14 14.24 4 11.39 4 8.5 4 6.5 5.5 5 7.5 5c1.54 0 3.04.99 3.57 2.36h1.87C13.46 5.99 14.96 5 16.5 5c2 0 3.5 1.5 3.5 3.5 0 2.89-3.14 5.74-7.9 10.05z"/> </SvgIcon> ); ActionFavoriteBorder.displayName = 'ActionFavoriteBorder'; ActionFavoriteBorder.muiName = 'SvgIcon'; export default ActionFavoriteBorder;
app/components/DropBox/DropBox.js
celikmus/MathWise
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Text, View } from 'react-native'; import styles from './styles'; import { addDropZone } from '../../actions/interactions'; class DropBox extends Component { constructor() { super(); this.setDropZoneValues = this.setDropZoneValues.bind(this); } static propTypes = { dispatch: PropTypes.func.isRequired, zoneId: PropTypes.number.isRequired }; setDropZoneValues = event => { const { dispatch, zoneId } = this.props; dispatch(addDropZone(zoneId, event.nativeEvent.layout)); }; render() { return ( <View style={styles.square} onLayout={this.setDropZoneValues}> <Text style={styles.text}>Drop here</Text> </View> ); } } export default connect()(DropBox);
packages/material-ui-icons/src/School.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let School = props => <SvgIcon {...props}> <path d="M5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82zM12 3L1 9l11 6 9-4.91V17h2V9L12 3z" /> </SvgIcon>; School = pure(School); School.muiName = 'SvgIcon'; export default School;
admin/src/components/PopoutPane.js
lastjune/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; var PopoutPane = React.createClass({ displayName: 'PopoutPane', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, onLayout: React.PropTypes.func }, componentDidMount () { this.props.onLayout && this.props.onLayout(this.getDOMNode().offsetHeight); }, render () { let className = classnames('Popout__pane', this.props.className); let props = blacklist(this.props, 'className', 'onLayout'); return <div className={className} {...props} />; } }); module.exports = PopoutPane;
src/svg-icons/image/timer-off.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimerOff = (props) => ( <SvgIcon {...props}> <path d="M19.04 4.55l-1.42 1.42C16.07 4.74 14.12 4 12 4c-1.83 0-3.53.55-4.95 1.48l1.46 1.46C9.53 6.35 10.73 6 12 6c3.87 0 7 3.13 7 7 0 1.27-.35 2.47-.94 3.49l1.45 1.45C20.45 16.53 21 14.83 21 13c0-2.12-.74-4.07-1.97-5.61l1.42-1.42-1.41-1.42zM15 1H9v2h6V1zm-4 8.44l2 2V8h-2v1.44zM3.02 4L1.75 5.27 4.5 8.03C3.55 9.45 3 11.16 3 13c0 4.97 4.02 9 9 9 1.84 0 3.55-.55 4.98-1.5l2.5 2.5 1.27-1.27-7.71-7.71L3.02 4zM12 20c-3.87 0-7-3.13-7-7 0-1.28.35-2.48.95-3.52l9.56 9.56c-1.03.61-2.23.96-3.51.96z"/> </SvgIcon> ); ImageTimerOff = pure(ImageTimerOff); ImageTimerOff.displayName = 'ImageTimerOff'; ImageTimerOff.muiName = 'SvgIcon'; export default ImageTimerOff;
varOne-web/src/main/webapp/app/components/navigator/brand.js
SparkMonitor/varOne
import React from 'react'; class Brand extends React.Component { render() { return ( <div className='navbar-header'> <button type='button' className='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'> <span className='sr-only'>Toggle navigation</span> <span className='icon-bar'></span> <span className='icon-bar'></span> <span className='icon-bar'></span> </button> <a className='navbar-brand' href='index.html' style={ { color: 'white' } }>varOne</a> </div> ); } } export default Brand;
src/routes/Library/components/SongList/SongList.js
bhj/karaoke-forever
import PropTypes from 'prop-types' import React from 'react' import SongItem from '../SongItem' const SongList = (props) => props.songIds.map(songId => ( <SongItem {...props.songs[songId]} artist={props.showArtist ? props.artists[props.songs[songId].artistId].name : ''} filterKeywords={props.filterKeywords} isQueued={props.queuedSongs.includes(songId)} isStarred={props.starredSongs.includes(songId)} isAdmin={props.isAdmin} key={songId} numStars={props.starredSongCounts[songId] || 0} onSongQueue={props.queueSong} onSongStarClick={props.toggleSongStarred} onSongInfo={props.showSongInfo} /> )) SongList.propTypes = { artists: PropTypes.object.isRequired, filterKeywords: PropTypes.array.isRequired, queuedSongs: PropTypes.array.isRequired, showArtist: PropTypes.bool.isRequired, songs: PropTypes.object.isRequired, songIds: PropTypes.array.isRequired, starredSongs: PropTypes.array.isRequired, starredSongCounts: PropTypes.object.isRequired, // actions queueSong: PropTypes.func.isRequired, showSongInfo: PropTypes.func.isRequired, toggleSongStarred: PropTypes.func.isRequired, } export default SongList
src/components/pages/Home.js
Painatalman/fortunecookie
import React, { Component } from 'react'; import styles from './Home.css' import FortuneCookie from '../FortuneCookie/FortuneCookie.js'; export default class Home extends Component { render() { return ( <div className={styles.home}> <h1>Fortune Cookie</h1> <FortuneCookie></FortuneCookie> </div>) } }
src/docs/Start.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Anchor from 'grommet/components/Anchor'; import Button from 'grommet/components/Button'; import Footer from 'grommet/components/Footer'; import Heading from 'grommet/components/Heading'; import Paragraph from 'grommet/components/Paragraph'; import Section from 'grommet/components/Section'; import DocsArticle from '../components/DocsArticle'; export default class Start extends Component { render () { return ( <DocsArticle title="Start"> <Paragraph size='large'> There are a bunch of ways to get started with Grommet. Whether you’re a designer, developer, or just interested in technology, we’ve got you covered. </Paragraph> <Section> <Heading tag='h3'>Design System</Heading> <Paragraph margin='none'> Grommet was created to align the design and developer workflow into one seamless experience. We recommend that everyone take some time and familiarize themselves with the <Anchor path="/docs/components" id='components-anchor'> Components </Anchor> area (especially the examples) to see how the designs translate to code before downloading the various resources. </Paragraph> <Paragraph> Our resources provide everything one would need to design a modern application; icons, fonts, sticker sheets, and design templates -- Have fun! </Paragraph> <Footer direction='column' align='start' pad={{ between: 'small' }}> <Button label="Download Resources" primary={true} path="/docs/resources"/> <Anchor href="https://github.com/grommet/grommet-design" primary={true} target='_blank'> View on Github</Anchor> </Footer> </Section> <Section separator='top'> <Heading tag ='h3'>Component Library</Heading> <Paragraph margin='none'> The Grommet component library is designed to be a perfect complement to the design system. With little setup, you&#39;ll be able to create a Grommet application from scratch in minutes and take the pain out of translating design files into running application code. </Paragraph> <Paragraph> To run Grommet on your local machine, get access to all the components, and the user interface goodness, you don&#39;t have to be a developer. With the power of <Anchor href="https://nodejs.org/" target="_blank"> Node.js </Anchor>, Grommet will take care of all the details through our command line interface (CLI). </Paragraph> <Footer direction='column' align='start' pad={{ between: 'small' }}> <Button label="Get Started" primary={true} path="/docs/get-started"/> </Footer> </Section> </DocsArticle> ); } };
client/src/research/DataBubble.js
mit-teaching-systems-lab/swipe-right-for-cs
import React from 'react'; import PropTypes from 'prop-types'; import chroma from 'chroma-js'; // A colored in bubble for a chart like Milkman et al. 2015 class DataBubble extends React.Component { render() { const {percentage, n} = this.props; const colors = chroma.scale(['white','#006837']); const color = colors(n/50).brighten(1).hex(); const title = `${Math.round(percentage)}%\nn=${n}`; const styles = { backgroundColor: color, height: percentage, width: percentage, borderRadius: 100, }; return <div className="DataBubble" style={styles} title={title} />; } } DataBubble.propTypes = { percentage: PropTypes.number.isRequired, n: PropTypes.number.isRequired }; export default DataBubble;
src/util/CompoundDecorator.js
yqy980210/verse-ink
import { CompositeDecorator } from 'draft-js'; import { List } from 'immutable'; import React from 'react'; const Span = (props) => <span>{props.children}</span>; export class CompoundDecorator { constructor(decorators = []) { this.decorators = decorators.map((decorator) => { return decorator.strategy && decorator.component ? new CompositeDecorator([ decorator ]) : decorator; }); } getDecorations(block,contentState) { const emptyTuples = Array(block.getText().length).fill( Array(this.decorators.length).fill(null) ); const decorations = this.decorators.reduce((tuples, decorator, index) => { const blockDecorations = decorator.getDecorations(block,contentState); return tuples.map((tuple, tupleIndex) => { return [ ...tuple.slice(0, index), blockDecorations.get(tupleIndex), ...tuple.slice(index + 1) ]; }); }, emptyTuples); return List(decorations.map(JSON.stringify)); } getComponentForKey(key) { const tuple = JSON.parse(key); return (props) => { const { decoratorProps, ...compositionProps } = props; const Composed = tuple.reduce((Composition, decoration, index) => { if (decoration !== null) { const decorator = this.decorators[index]; const Component = decorator.getComponentForKey(decoration); const componentProps = { ...compositionProps, ...decoratorProps[index] }; return () => ( <Component {...componentProps}> <Composition {...compositionProps} /> </Component> ); } return Composition; }, Span); return ( <Composed>{props.children}</Composed> ); }; } getPropsForKey(key) { const tuple = JSON.parse(key); return { decoratorProps: tuple.map((decoration, index) => { const decorator = this.decorators[index]; return decoration !== null ? decorator.getPropsForKey(decoration) : {}; }) }; } }
src/components/header/MoreMenuComponent.js
Philin-Anton/prototypeApp
'use strict'; import React from 'react'; import { connect } from 'react-redux' import { createSelector } from 'reselect' require('styles/ActionIcons.scss'); require('styles/header/MoreMenu.scss'); import { getContent, clearLocalStore} from '../../api/maggo'; import {handleSave, handlePublish, handleDelete} from '../../api/handlers'; import { actionWidgetList, actionWidgetTag, actionWidgetTitle, actionArrayImageBlob} from '../../actions/index'; const setTitle = actionWidgetTitle.setTitle; const addToTag = actionWidgetTag.addToTag; const setArrayImage = actionArrayImageBlob.setArrayImage; const setWidgetBlock = actionWidgetList.setWidgetBlock; class MoreMenuComponent extends React.Component { constructor(props, context) { super(props, context); this.state = {}; } savedContent() { const {widgetBlocks} = this.props; const goOutJSON = JSON.stringify(getContent(widgetBlocks)); clearLocalStore(); return goOutJSON } save() { const goOutJSON = this.savedContent.call(this); handleSave.call(this, goOutJSON); } publish() { const goOutJSON = this.savedContent.call(this); handlePublish.call(this, goOutJSON); } remove() { const {setWidgetBlock, addToTag, setTitle, setArrayImage} = this.props; setTitle(''); addToTag(''); setArrayImage([]); setWidgetBlock([]); handleDelete.call(this); } render() { return ( <div className="moremenu-component"> <ul className="fix-wrapper"> <li onClick={this.save.bind(this)}> <span className="action-icon icon-style-dark action-icon-save"></span> </li> <li onClick={this.publish.bind(this)}> <span className="action-icon icon-style-dark action-icon-publish"></span> </li> <li onClick={this.remove.bind(this)}> <span className="action-icon icon-style-dark action-icon-remove"></span> </li> </ul> </div> ); } } MoreMenuComponent.displayName = 'HeaderMoreMenuComponent'; // Uncomment properties you need // MoreMenuComponent.propTypes = {}; // MoreMenuComponent.defaultProps = {}; const getWidgetBlocksState = state => state.WidgetBlocks; const select = createSelector([getWidgetBlocksState], (widgetBlocks) => { return {widgetBlocks}; }); export default connect(select, {setWidgetBlock, addToTag, setTitle, setArrayImage} )(MoreMenuComponent);
docs/src/components/nav.js
colindresj/nuclear-js
import React from 'react' import { BASE_URL } from '../globals' function urlize(uri) { return BASE_URL + uri } export default React.createClass({ render() { const logo = this.props.includeLogo ? <a href={BASE_URL} className="brand-logo">NuclearJS</a> : null return <div className="navbar-fixed"> <nav className="nav"> <div className="nav-wrapper"> {logo} <ul id="nav-mobile" className="right hide-on-med-and-down"> <li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li> <li><a href={urlize("docs/05-api.html")}>API</a></li> <li><a href="https://github.com/optimizely/nuclear-js">Github</a></li> </ul> </div> </nav> </div> } })
docs/src/PropTable.js
adampickeral/react-bootstrap
import merge from 'lodash/object/merge'; import React from 'react'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; import Table from '../../src/Table'; let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, ''); let capitalize = str => str[0].toUpperCase() + str.substr(1); function getPropsData(component, metadata){ let componentData = metadata[component] || {}; let props = componentData.props || {}; if (componentData.composes) { componentData.composes.forEach(other => { if (other !== component) { props = merge({}, getPropsData(other, metadata), props); } }); } if (componentData.mixins) { componentData.mixins.forEach( other => { if (other !== component && componentData.composes.indexOf(other) === -1) { props = merge({}, getPropsData(other, metadata), props); } }); } return props; } const PropTable = React.createClass({ contextTypes: { metadata: React.PropTypes.object }, componentWillMount(){ this.propsData = getPropsData(this.props.component, this.context.metadata); }, render(){ let propsData = this.propsData; if ( !Object.keys(propsData).length){ return <span/>; } return ( <Table bordered striped className="prop-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> { this._renderRows(propsData) } </tbody> </Table> ); }, _renderRows(propsData){ return Object.keys(propsData) .sort() .filter(propName => propsData[propName].type && !propsData[propName].doclets.private ) .map(propName => { let propData = propsData[propName]; return ( <tr key={propName} className='prop-table-row'> <td> {propName} {this.renderRequiredLabel(propData)} </td> <td> <div>{this.getType(propData)}</div> </td> <td>{propData.defaultValue}</td> <td> { propData.doclets.deprecated && <div className='prop-desc-heading'> <strong className='text-danger'>{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong> </div> } { this.renderControllableNote(propData, propName) } <div className='prop-desc' dangerouslySetInnerHTML={{__html: propData.descHtml }} /> </td> </tr> ); }); }, renderRequiredLabel(prop) { if (!prop.required) { return null; } return ( <Label>required</Label> ); }, renderControllableNote(prop, propName){ let controllable = prop.doclets.controllable; let isHandler = this.getDisplayTypeName(prop.type.name) === 'function'; if (!controllable) { return false; } let text = isHandler ? ( <span> controls <code>{controllable}</code> </span> ) : ( <span> controlled by: <code>{controllable}</code>, initial prop: <code>{'default' + capitalize(propName)}</code> </span> ); return ( <div className='prop-desc-heading'> <small> <em className='text-info'> <Glyphicon glyph='info-sign'/> &nbsp;{ text } </em> </small> </div> ); }, getType(prop) { let type = prop.type || {}; let name = this.getDisplayTypeName(type.name); let doclets = prop.doclets || {}; switch (name) { case 'object': return name; case 'union': return type.value.reduce((current, val, i, list) => { let item = this.getType({ type: val }); if (React.isValidElement(item)) { item = React.cloneElement(item, {key: i}); } current = current.concat(item); return i === (list.length - 1) ? current : current.concat(' | '); }, []); case 'array': let child = this.getType({ type: type.value }); return <span>{'array<'}{ child }{'>'}</span>; case 'enum': return this.renderEnum(type); case 'custom': return cleanDocletValue(doclets.type || name); default: return name; } }, getDisplayTypeName(typeName) { if (typeName === 'func') { return 'function'; } else if (typeName === 'bool') { return 'boolean'; } else { return typeName; } }, renderEnum(enumType) { const enumValues = enumType.value || []; const renderedEnumValues = []; enumValues.forEach(function renderEnumValue(enumValue, i) { if (i > 0) { renderedEnumValues.push( <span key={`${i}c`}>, </span> ); } renderedEnumValues.push( <code key={i}>{enumValue}</code> ); }); return ( <span>one of: {renderedEnumValues}</span> ); } }); export default PropTable;
src/auth/Login/Register.js
elarasu/roverz-chat
/** * tasks package */ import React, { Component } from 'react'; import { TouchableOpacity, Text, View, TextInput, Keyboard, StyleSheet, Image, Alert, ScrollView, Dimensions, KeyboardAvoidingView, Platform, } from 'react-native'; import { Actions } from 'react-native-router-flux'; import * as UserActions from '../../redux/user/actions'; // import { Icon } from 'react-native-elements'; import Application from '../../constants/config'; import { Alerts } from '../../components/ui/'; import { AppColors } from '../../theme/'; import Network from '../../network'; const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; const namePattern = /^[a-zA-Z. ]{3,20}$/; const unamePattern = /^[a-zA-Z.]{3,20}$/; const passPattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/; const styles = StyleSheet.create({ titleText: { fontFamily: 'OpenSans-Regular', color: 'rgba(255,255,255,0.7)', fontSize: 18, fontWeight: '400', marginTop: 15, }, inputLabel: { fontFamily: 'OpenSans-Regular', fontSize: 14, color: '#FFF', marginBottom: 5, marginTop: 15, }, inputStyle: { fontFamily: 'OpenSans-Regular', fontSize: 14, height: 40, backgroundColor: '#FFF', borderColor: 'rgba(0,0,0,0.2)', borderWidth: 1, paddingHorizontal: 10, color: '#000', }, errorMessage: { fontFamily: 'OpenSans-Regular', fontSize: 13, color: '#ff5132', marginTop: 5, }, signup: { height: 50, alignItems: 'center', justifyContent: 'center', marginTop: 15, }, }); export default class Register extends Component { constructor(props) { super(props); this._net = new Network(); // console.log('RegCB1'); this.state = { inputName: '', inputEmail: '', inputPass: '', inputUsername: '', alert: { status: '', success: '', error: '', }, inputError: { name: false, email: false, password: false, username: false, }, setUsername: false, }; } validateRegistrationForm = () => { if (this.state.inputName.length > 0 && this.state.inputEmail.length > 0 && this.state.inputPass.length > 0 ) { this.setState({ alert: { status: 'Please wait...' } }); } const errorStates = {}; if (!namePattern.test(this.state.inputName)) { errorStates.name = true; } if (!emailPattern.test(this.state.inputEmail)) { errorStates.email = true; } if (!passPattern.test(this.state.inputPass)) { errorStates.password = true; } this.setState({ inputError: errorStates }); if (namePattern.test(this.state.inputName) && emailPattern.test(this.state.inputEmail) && passPattern.test(this.state.inputPass)) { this._net.service.registerUser(this.state.inputEmail, this.state.inputPass, this.state.inputName, (err, res) => { // console.log('RegCB', err, res); if (err && !res) { this.setState({ alert: { error: 'Error in registration!' } }); } this.setState({ alert: { success: 'Registration successful!' } }); UserActions.loginAfterRegister({ username: this.state.inputEmail, password: this.state.inputPass, }, () => { // console.log('RegCB 01', lerr, lres); if (this._net.service.loggedInUser && this._net.service.loggedInUser.username) { Actions.app({ type: 'reset' }); } else { this.setState({ setUsername: true, alert: { success: '' } }); this._net.service.getUsernameSuggestion((Uerr, Ures) => { if (Uerr) { this.setState({ alert: { error: 'Error fetching username!' } }); } else if (Ures) { this.setState({ inputUsername: Ures }); } }); } }); }); } else { this.setState({ alert: { error: 'Enter valid details' } }); } } renderRegistration = () => { const { height } = Dimensions.get('window'); if (!this.state.setUsername) { return ( <View style={{ flex: 1, zIndex: 100, }} > <ScrollView style={{ flexDirection: 'column', backgroundColor: AppColors.brand().third, }} > <KeyboardAvoidingView behavior={(Platform.OS === 'ios') ? 'position' : null} style={{ paddingVertical: 15, paddingHorizontal: 30 }} > <View style={{ height: height / 3, alignItems: 'center', justifyContent: 'flex-end', paddingVertical: 15, }} > <Image source={Application.logo} style={{ width: 250, height: 50 }} /> <Text style={styles.titleText}>Create a new account</Text> </View> <Alerts status={this.state.alert.status} success={this.state.alert.success} error={this.state.alert.error} /> <Text style={styles.inputLabel}>Name</Text> <TextInput placeholder={'Your name'} onChangeText={inputName => this.setState({ inputName })} value={this.state.name} autoCorrect={false} clearButtonMode={'while-editing'} autoCapitalize="none" disableFullscreenUI style={styles.inputStyle} /> { this.state.inputError.name && <Text style={styles.errorMessage}>Please enter a valid name</Text> } <Text style={styles.inputLabel}>Email</Text> <TextInput placeholder={'you@domain.com'} onChangeText={inputEmail => this.setState({ inputEmail })} autoCorrect={false} value={this.state.email} keyboardType="email-address" clearButtonMode={'while-editing'} autoCapitalize="none" disableFullscreenUI style={styles.inputStyle} /> { this.state.inputError.email && <Text style={styles.errorMessage}>Please enter a valid email</Text> } <Text style={styles.inputLabel}>Password</Text> <TextInput placeholder={'Create a new password'} onChangeText={inputPass => this.setState({ inputPass })} value={this.state.password} secureTextEntry autoCorrect={false} clearButtonMode={'while-editing'} autoCapitalize="none" disableFullscreenUI style={styles.inputStyle} /> { this.state.inputError.password && <Text style={styles.errorMessage}>Please enter a stronger password</Text> } <TouchableOpacity style={[styles.signup, { backgroundColor: AppColors.brand().res_signBg }]} onPress={() => { Keyboard.dismiss(); this.validateRegistrationForm(); }} > <Text style={{ marginLeft: 10, color: '#FFF', fontSize: 16, fontWeight: '400', }} >Sign up</Text> </TouchableOpacity> <TouchableOpacity style={{ height: 40, alignItems: 'center', justifyContent: 'center', marginBottom: 30, }} onPress={() => { Actions.pop(); }} > <Text style={{ marginLeft: 10, color: '#FFF', fontSize: 16, fontWeight: '400', }} >Cancel</Text> </TouchableOpacity> </KeyboardAvoidingView> </ScrollView> </View> ); } } renderSetUsername = () => { const { height } = Dimensions.get('window'); if (this.state.setUsername) { return ( <View style={{ flex: 1, zIndex: 100, }} > <ScrollView style={{ flexDirection: 'column', backgroundColor: AppColors.brand().third, }} > <KeyboardAvoidingView behavior={(Platform.OS === 'ios') ? 'position' : null} style={{ paddingVertical: 15, paddingHorizontal: 30 }} > <View style={{ height: height / 3, alignItems: 'center', justifyContent: 'flex-end', paddingVertical: 15, }} > <Image source={Application.logo} style={{ width: 250, height: 50 }} /> <Text style={styles.titleText}>Choose your username</Text> </View> <Alerts status={this.state.alert.status} success={this.state.alert.success} error={this.state.alert.error} /> <Text style={styles.inputLabel}>Username</Text> <TextInput placeholder={'Your username'} onChangeText={inputUsername => this.setState({ inputUsername })} value={this.state.inputUsername} autoCorrect={false} clearButtonMode={'while-editing'} autoCapitalize="none" disableFullscreenUI style={styles.inputStyle} /> { this.state.inputError.name && <Text style={styles.errorMessage}>Please enter a valid username</Text> } <TouchableOpacity style={[styles.signup, { backgroundColor: AppColors.brand().res_signBg }]} onPress={() => { Keyboard.dismiss(); const errorStates = {}; if (!unamePattern.test(this.state.inputUsername)) { errorStates.username = true; this.setState({ inputError: errorStates }); } else if (unamePattern.test(this.state.inputUsername)) { this._net.service.setUsername(this.state.inputUsername, (err, res) => { // console.log('another', err, res); if (err && !res) { this.setState({ alert: { error: 'Try another username!' } }); } else { Alert.alert( 'Success', 'Please login with your username and password.', [ { text: 'OK', onPress: () => { this._net.logout(); }, }, ], { cancelable: false }, ); } }); } }} > <Text style={{ marginLeft: 10, color: '#FFF', fontSize: 16, fontWeight: '400', }} >Set username</Text> </TouchableOpacity> </KeyboardAvoidingView> </ScrollView> </View> ); } } render() { return ( <View style={{ flex: 1, zIndex: 100, }} > {this.renderRegistration()} {this.renderSetUsername()} </View> ); } }
src/Parser/Monk/Mistweaver/Modules/Spells/ThunderFocusTea.js
hasseboulen/WoWAnalyzer
import React from 'react'; import { Doughnut as DoughnutChart } from 'react-chartjs-2'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Wrapper from 'common/Wrapper'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import StatisticsListBox, { STATISTIC_ORDER } from 'Main/StatisticsListBox'; const debug = false; const CHART_SIZE = 75; class ThunderFocusTea extends Analyzer { static dependencies = { combatants: Combatants, }; legend(items, total) { const numItems = items.length; return items.map(({ color, label, tooltip, value, spellId }, index) => { label = tooltip ? ( <dfn data-tip={tooltip}>{label}</dfn> ) : label; label = spellId ? ( <SpellLink id={spellId}>{label}</SpellLink> ) : label; return ( <div className="flex" style={{ borderBottom: '3px solid rgba(255,255,255,0.1)', marginBottom: ((numItems - 1) === index) ? 0 : 5, }} key={index} > <div className="flex-sub"> <div style={{ display: 'inline-block', background: color, borderRadius: '50%', width: 16, height: 16, marginBottom: -3, }} /> </div> <div className="flex-main" style={{ paddingLeft: 5 }}> {label} </div> <div className="flex-sub"> <dfn data-tip={value}> {formatPercentage(value / total, 0)}% </dfn> </div> </div> ); }); } chart(items) { return ( <DoughnutChart data={{ datasets: [{ data: items.map(item => item.value), backgroundColor: items.map(item => item.color), borderColor: '#666', borderWidth: 1.5, }], labels: items.map(item => item.label), }} options={{ legend: { display: false, }, tooltips: { bodyFontSize: 8, }, cutoutPercentage: 45, animation: false, responsive: false, }} width={CHART_SIZE} height={CHART_SIZE} /> ); } castsTftEff = 0; castsTftEf = 0; castsTftViv = 0; castsTftEnm = 0; castsTftRem = 0; castsTft = 0; castsUnderTft = 0; castBufferTimestamp = null; ftActive = false; on_initialized() { this.ftActive = this.combatants.selected.hasTalent(SPELLS.FOCUSED_THUNDER_TALENT.id); } on_toPlayer_applybuff(event) { const spellId = event.ability.guid; if (SPELLS.THUNDER_FOCUS_TEA.id === spellId) { this.castsTft += 1; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; // Implemented as a way to remove non-buffed REM or EF casts that occur at the same timestamp as the buffed Viv cast. // Need to think of cleaner solution if ((event.timestamp - this.castBufferTimestamp) < 25) { return; } if (this.combatants.selected.hasBuff(SPELLS.THUNDER_FOCUS_TEA.id)) { if (SPELLS.VIVIFY.id === spellId && !event.classResources.cost) { this.castsUnderTft += 1; this.castsTftViv += 1; debug && console.log('Viv TFT Check ', event.timestamp); this.castBufferTimestamp = event.timestamp; } if (SPELLS.EFFUSE.id === spellId) { this.castsUnderTft += 1; this.castsTftEff += 1; debug && console.log('Eff TFT Check ', event.timestamp); } if (SPELLS.ENVELOPING_MISTS.id === spellId) { this.castsUnderTft += 1; this.castsTftEnm += 1; debug && console.log('Enm TFT Check ', event.timestamp); } if (SPELLS.ESSENCE_FONT.id === spellId) { this.castsUnderTft += 1; this.castsTftEf += 1; debug && console.log('EF TFT Check ', event.timestamp); } if (SPELLS.RENEWING_MIST.id === spellId) { this.castsUnderTft += 1; this.castsTftRem += 1; debug && console.log('REM TFT Check ', event.timestamp); } } } tftCastRatioChart() { const items = [ { color: '#00b159', label: 'Vivify', spellId: SPELLS.VIVIFY.id, value: this.castsTftViv, }, { color: '#00aedb', label: 'Renewing Mist', spellId: SPELLS.RENEWING_MIST.id, value: this.castsTftRem, }, { color: '#f37735', label: 'Enveloping Mists', spellId: SPELLS.ENVELOPING_MISTS.id, value: this.castsTftEnm, }, { color: '#ffc425', label: 'Effuse', spellId: SPELLS.EFFUSE.id, value: this.castsTftEff, }, { color: '#d11141', label: 'Essence Font', spellId: SPELLS.ESSENCE_FONT.id, value: this.castsTftEf, }, ]; return ( <div className="flex"> <div className="flex-sub" style={{ paddingRight: 12 }}> {this.chart(items)} </div> <div className="flex-main" style={{ fontSize: '80%', paddingTop: 3 }}> {this.legend(items, this.castsUnderTft)} </div> </div> ); } on_finished() { if (this.ftActive) { this.castsTft += this.castsTft; } if (debug) { console.log(`TFT Casts:${this.castsTft}`); console.log(`Eff Buffed:${this.castsTftEff}`); console.log(`Enm Buffed:${this.castsTftEnm}`); console.log(`EF Buffed:${this.castsTftEf}`); console.log(`Viv Buffed:${this.castsTftViv}`); console.log(`REM Buffed:${this.castsTftRem}`); } } get incorrectTFTCasts() { return this.castsUnderTft - (this.castsTftViv + this.castsTftRem); } get suggestionThresholds() { return { actual: this.incorrectTFTCasts, isGreaterThan: { minor: 1, average: 1.5, major: 2, }, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> You are currently using <SpellLink id={SPELLS.THUNDER_FOCUS_TEA.id} /> to buff spells other than <SpellLink id={SPELLS.VIVIFY.id} /> or <SpellLink id={SPELLS.RENEWING_MIST.id} />. It is advised to limit the number of spells buffed to only these two. </Wrapper> ) .icon(SPELLS.THUNDER_FOCUS_TEA.icon) .actual(`${this.incorrectTftCasts} incorrect casts with Thunder Focus Tea`) .recommended(`<${recommended} incorrect cast is recommended`); }); } statistic() { return ( <StatisticsListBox title={<Wrapper><SpellLink id={SPELLS.THUNDER_FOCUS_TEA.id}>Thunder Focus Tea</SpellLink> usage</Wrapper>} > {this.tftCastRatioChart()} </StatisticsListBox> ); } statisticOrder = STATISTIC_ORDER.CORE(20); } export default ThunderFocusTea;
fields/types/geopoint/GeoPointColumn.js
benkroeger/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var GeoPointColumn = React.createClass({ displayName: 'GeoPointColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; const formattedValue = `${value[1]}, ${value[0]}`; const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`; return ( <ItemsTableValue title={formattedTitle} field={this.props.col.type}> {formattedValue} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = GeoPointColumn;
src/imports/ui/builder/components/product/ProductVariationSelect.js
hwillson/meteor-recommendation-builder
import React from 'react'; import { FormGroup, FormControl } from 'react-bootstrap'; import products from '../../../../api/products/collection'; const ProductVariationSelect = ({ product }) => ( <FormGroup className="product-variation-select"> <FormControl componentClass="select" onChange={(event) => { product.changeProductVariation(event.target.value); }} value={product._id} > {products.getVariationsForProduct(product.productId).map((variation) => ( <option key={variation._id} value={variation._id}> {variation.variationName} </option> ))} </FormControl> </FormGroup> ); ProductVariationSelect.propTypes = { product: React.PropTypes.object.isRequired, }; export default ProductVariationSelect;
src/components/ListCol/ListColOrder/ListColOrder.js
hahoocn/hahoo-admin
import React from 'react'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import FormControl from 'react-bootstrap/lib/FormControl'; import toFloat from 'validator/lib/toFloat'; import isDecimal from 'validator/lib/isDecimal'; import Tap from '../../hahoo/Tap'; import styles from './ListColOrder.css'; class ListColOrder extends React.Component { static propTypes = { className: React.PropTypes.string, orderId: React.PropTypes.number.isRequired, itemId: React.PropTypes.number, onUpClick: React.PropTypes.func, onDownClick: React.PropTypes.func, onChangeOrderId: React.PropTypes.func } constructor(props) { super(props); this.upClick = this.upClick.bind(this); this.downClick = this.downClick.bind(this); this.orderIdChange = this.orderIdChange.bind(this); this.onOrderIdChange = this.onOrderIdChange.bind(this); this.orderIdKeyPress = this.orderIdKeyPress.bind(this); } state = { orderId: 0 } onOrderIdChange() { if (isDecimal(`${this.state.orderId}`)) { const newOrderId = toFloat(`${this.state.orderId}`); if (newOrderId && newOrderId > 0 && newOrderId !== toFloat(`${this.props.orderId}`)) { this.props.onChangeOrderId(this.props.itemId, newOrderId); } } } upClick() { this.props.onUpClick(this.props.itemId); } downClick() { this.props.onDownClick(this.props.itemId); } orderIdChange(e) { this.setState({ orderId: e.target.value }); } orderIdKeyPress(e) { if (e.key === 'Enter') { this.onOrderIdChange(); } } render() { const { className, orderId, ...rest } = this.props; delete rest.itemId; delete rest.onUpClick; delete rest.onDownClick; delete rest.onChangeOrderId; return ( <div className={`hidden-xs ${styles.order}${className ? ` ${className}` : ''}`} {...rest}> <Tap className={`fa fa-chevron-up fa-fw ${styles.pointer}`} onTap={this.upClick} /> <Tap className={`fa fa-chevron-down fa-fw ${styles.pointer}`} onTap={this.downClick} /> <FormGroup bsSize="small" className={styles.orderNum}> <FormControl type="text" onChange={this.orderIdChange} placeholder={orderId} onKeyPress={this.orderIdKeyPress} /> </FormGroup> </div> ); } } export default ListColOrder;
frontend/src/widgets/Weather.js
BrechtBa/homecon
import React from 'react'; function HomeconWeatherBlock(props){ const config = props.config; const states = props.states; let state = undefined; if(states!== null){ let path = ''; if(config.daily){ path = `/weather/forecast/daily/${config.timeoffset}`; } else if(config.hourly){ path = `/weather/forecast/hourly/${config.timeoffset}`; } for (const value of Object.values(states)) { if(value.path === path){ state = value; break; } } } if(state === undefined){ state = {value: {}}; } const getIcon = (value) => { if(value.icon !== undefined && value.icon !== null){ return `/weather/${value.icon}.png`; } else{ return '/weather/blank.png'; } } const getDate = (value) => { if(value.timestamp !== undefined && value.timestamp !== null){ const date = new Date(value.timestamp * 1000); const locale = config.locale || 'nl-BE'; const options = config.dateOptions || {weekday: 'long'}; return date.toLocaleDateString(locale, options) } else { return ''; } } const getTemperature = (value) => { if(value.temperature_max !== undefined && value.temperature_max !== null){ return `${(value.temperature_max).toFixed(1)} °C` } else{ return '' } } const getWindSpeed = (value) => { if(value.wind_speed !== undefined && value.wind_speed !== null){ return `${(value.wind_speed*3.6).toFixed(0)} km/h` } else{ return '' } } const getWindDirection = (value) => { const dirs = ['N','NO','O','ZO','Z','ZW','W','NW','N']; if(value.wind_direction !== undefined && value.wind_direction !== null){ return dirs[Math.round(value.wind_direction/360*8)]; } else{ return '' } } const getRain = (value) => { if(value.rain !== undefined && value.rain !== null){ return `Regen: ${(value.rain).toFixed(0)} mm` } else{ return '' } } return ( <div> <img src={getIcon(state.value)} style={{width: "100%"}} alt="weather forecast"/> <div style={{textAlign: "center"}}>{getDate(state.value)}</div> <div style={{textAlign: "center"}}>{getTemperature(state.value)}</div> <div style={{textAlign: "center"}}>{getWindSpeed(state.value)} {getWindDirection(state.value)}</div> <div style={{textAlign: "center"}}>{getRain(state.value)}</div> </div> ) } function HomeconWeatherForecastSummary(props) { const states = props.states; return ( <div style={{display: "flex", flexDirection: "row", marginLeft: "-20px", marginRight: "-20px"}}> <HomeconWeatherBlock config={{daily: true, timeoffset: 0}} states={states} style={{width: "60px", flexGrow: 1}}/> <HomeconWeatherBlock config={{daily: true, timeoffset: 1}} states={states} style={{width: "60px", flexGrow: 1}}/> <HomeconWeatherBlock config={{daily: true, timeoffset: 2}} states={states} style={{width: "60px", flexGrow: 1}}/> <HomeconWeatherBlock config={{daily: true, timeoffset: 3}} states={states} style={{width: "60px", flexGrow: 1}}/> </div> ) } export {HomeconWeatherBlock, HomeconWeatherForecastSummary};
project/src/scenes/Admin/Articles/NewArticle/components/RenderTags/RenderTags.js
boldr/boldr
/* eslint-disable react/prop-types */ import React from 'react'; import TagsInput from 'react-tagsinput'; import { FormGroup } from '@boldr/ui/Form'; const RenderTags = ({ input, label, meta: { touched, error, warning } }) => ( <FormGroup color={`${touched && error ? 'danger' : ''}`}> <TagsInput value={input.value || []} onChange={input.onChange} state={`${touched && error ? 'danger' : ''}`} inputProps={{ placeholder: label }} /> {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))} </FormGroup> ); export default RenderTags;
src/Tab.js
nickuraltsev/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const Tab = React.createClass({ propTypes: { /** * @private */ active: React.PropTypes.bool, animation: React.PropTypes.bool, /** * It is used by 'Tabs' - parent component * @private */ onAnimateOutEnd: React.PropTypes.func, disabled: React.PropTypes.bool, title: React.PropTypes.node, /** * tabClassName is used as className for the associated NavItem */ tabClassName: React.PropTypes.string }, getDefaultProps() { return { animation: true }; }, getInitialState() { return { animateIn: false, animateOut: false }; }, componentWillReceiveProps(nextProps) { if (this.props.animation) { if (!this.state.animateIn && nextProps.active && !this.props.active) { this.setState({ animateIn: true }); } else if (!this.state.animateOut && !nextProps.active && this.props.active) { this.setState({ animateOut: true }); } } }, componentDidUpdate() { if (this.state.animateIn) { setTimeout(this.startAnimateIn, 0); } if (this.state.animateOut) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.stopAnimateOut ); } }, startAnimateIn() { if (this.isMounted()) { this.setState({ animateIn: false }); } }, stopAnimateOut() { if (this.isMounted()) { this.setState({ animateOut: false }); if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(); } } }, render() { let classes = { 'tab-pane': true, 'fade': true, 'active': this.props.active || this.state.animateOut, 'in': this.props.active && !this.state.animateIn }; return ( <div {...this.props} title={undefined} role="tabpanel" aria-hidden={!this.props.active} className={classNames(this.props.className, classes)} > {this.props.children} </div> ); } }); export default Tab;