path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/svg-icons/device/access-alarm.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessAlarm = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); DeviceAccessAlarm = pure(DeviceAccessAlarm); DeviceAccessAlarm.displayName = 'DeviceAccessAlarm'; DeviceAccessAlarm.muiName = 'SvgIcon'; export default DeviceAccessAlarm;
src/index.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import { render } from 'react-dom'; import { install as installAnalytics } from 'common/analytics'; import 'interface/static/bootstrap/css/bootstrap.css'; import Root from './Root'; installAnalytics(); render(<Root />, document.getElementById('app-mount'));
public/index.js
ygkn/DJ-YAGICHAN-SYSTEM
import 'react-hot-loader/patch'; import { AppContainer } from 'react-hot-loader'; import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router } from '../redux-tower/lib/react'; import configureStore from './store'; const store = configureStore(); render( <AppContainer> <Provider store={store}> <div> <Router /> <DevTools /> </div> </Provider> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('./sagas', () => { render( <AppContainer> <Provider store={store}> <div> <Router /> <DevTools /> </div> </Provider> </AppContainer>, document.getElementById('root') ); }); }
js/components/Header/index.js
mxstbr/postcss.parts
import React from 'react'; import styled from 'styled-components'; import { colors } from '../../constants'; import Wrapper from './Wrapper'; import Link from './Link'; import Title from './Title'; import Subtitle from './Subtitle'; import Anchor from './AbsoluteAnchor'; const Logo = styled(Anchor)` right: initial; left: 0; font-size: 1.5em; font-family: Georgia, Times, 'Times New Roman', serif; `; const Header = () => { return( <Wrapper> <Logo href="https://twitter.com/mxstbr">&lt;mxstbr/&gt;</Logo> <Anchor href="https://github.com/himynameisdave/postcss-plugins#submitting-a-new-plugin">Add a plugin</Anchor> <Title><Link to="/">PostCSS.parts</Link></Title> <Subtitle>A searchable catalog of PostCSS plugins</Subtitle> </Wrapper> ); } export default Header;
src/components/ExternalLink.js
codeforboston/cliff-effects
import React from 'react'; /** Link that opens new tab */ const ExternalLink = function ({ href, children, ...otherProps }) { return ( <a href = { href } target = { `_blank` } { ...otherProps }> { children } </a> ); }; export { ExternalLink };
client/main.js
jcbages/prisoners-dilemma
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import App from '../imports/ui/App.jsx'; Meteor.startup(() => { WebFont.load({ google: { families: ['Josefin Slab'] }, active: () => { render(<App />, document.getElementById('render-target')); } }); });
src/js/components/TicTacToe.js
pablo-puga/webpack-react-electron-minimal-setup
import React, { Component } from 'react'; import { X, O } from '../reducers/tictactoe'; import '../../css/components/tictactoe.css'; function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } class Board extends Component { renderSquare(i) { return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />; } render() { return ( <div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } } class TicTacToe extends Component { constructor() { super(); this.state = { currentStep: 0, rewind: false }; } handleClick(i) { const { history, playNext, rewindAndPlay } = this.props; if (this.state.rewind) { const past = history[this.state.currentStep]; const squares = past.squares.slice(); if (calculateWinner(squares) || squares[i] !== null) return; rewindAndPlay(this.state.currentStep, i); this.setState({ currentStep: this.state.currentStep + 1, rewind: false }); } else { const current = history[history.length - 1]; const squares = current.squares.slice(); if (calculateWinner(squares) || squares[i] !== null) return; playNext(i); this.setState({ currentStep: this.state.currentStep + 1, }); } } jumpTo(step) { this.setState({ currentStep: step, rewind: true }); } restartGame() { const { restart } = this.props; this.setState({ currentStep: 0, rewind: false }); restart(); } render() { const { history } = this.props; let stepNumber = this.state.currentStep; const current = history[stepNumber]; const winner = calculateWinner(current.squares); const moves = history.map((step, move) => { const desc = move ? 'Move #' + move + ' (' + step.player + ')': 'Game start'; let style = {}; if (move === stepNumber) style.fontWeight = 'bold'; return ( <li key={move}> <span className="game-step" style={style} onClick={() => this.jumpTo(move)}>{desc}</span> </li> ); }); let status; let statusStyle = {}; if (winner) { status = 'Winner: ' + winner; statusStyle.color = 'red'; } else { status = 'Next player: ' + (current.player === X ? O : X); } const restartButton = (winner) => { if (winner) { let spanStyle = { color: 'green', fontWeight: 'bold', textDecoration: 'underline', cursor: 'pointer' }; return ( <span style={spanStyle} onClick={() => this.restartGame()}>Restart Game</span> ); } return(<span></span>); }; return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={(i) => this.handleClick(i)}/> </div> <div className="game-info"> <div style={statusStyle}>{status}</div> <ol>{moves}</ol> <div>{restartButton(winner)}</div> </div> </div> ); } } // ======================================== function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; } export default TicTacToe;
src/js/components/Carousel/stories/WithoutControls.js
HewlettPackard/grommet
import React from 'react'; import { Attraction, Car, TreeOption } from 'grommet-icons'; import { Grommet, Box, Carousel } from 'grommet'; export const NoControls = () => ( <Grommet> <Box align="center" pad="large"> <Carousel controls={false} play={1500}> <Box pad="xlarge" background="accent-1"> <Attraction size="xlarge" /> </Box> <Box pad="xlarge" background="accent-2"> <TreeOption size="xlarge" /> </Box> <Box pad="xlarge" background="accent-3"> <Car size="xlarge" /> </Box> </Carousel> </Box> </Grommet> ); NoControls.storyName = 'Without controls'; export default { title: 'Media/Carousel/Without controls', };
src/js/containers/DeckList.js
MarcusWasTaken/ArmelloCards
import React from 'react' import DeckTab from '../components/DeckTab' import DeckStore from '../stores/DeckStore' import DeckActions from '../actions/DeckActions' const getState = () => { return { decks: DeckStore.getAll(), activeName: DeckStore.getActiveName() } } const DeckList = React.createClass({ getInitialState: function() { return getState(); }, componentDidMount: function() { DeckStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { DeckStore.removeChangeListener(this._onChange); }, render: function() { let deckTabs = this.state.decks.map(deck => ( <DeckTab key={deck.id} {...deck} active={this.state.activeName} onClick={this._onTabClick} /> )) return ( <ul className="tab-list"> {deckTabs} </ul> ) }, _onTabClick: function(event) { event.preventDefault() DeckActions.setActive(event.currentTarget.getAttribute('value').toLowerCase()) }, _onChange: function() { this.setState(getState()); }, }) export default DeckList
examples/Reactnative.js
Adrianteri/hello-worlds
import React, { Component } from 'react'; import { Text } from 'react-native'; export default class HelloWorldApp extends Component { render() { return ( <Text>Hello world!</Text> ); } }
src/containers/tests/Film.spec.js
adrianha/swapii
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import { Film } from '../Film'; describe('<Film />', () => { it('should have a class .film', () => { const props = { films: { detail: { title: 'A New Hope' } } }; expect(shallow(<Film {...props} />).is('.film')).to.equal(true); }); });
src/app/components/public/Header.js
cherishstand/OA-react
import React, { Component } from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back'; import Settings from 'material-ui/svg-icons/action/settings'; import AccessTime from 'material-ui/svg-icons/device/access-time'; import {browserHistory, Link} from 'react-router'; import {grey100, grey900} from 'material-ui/styles/colors'; const styles={ text: { textAlign: 'center', fontSize:18, height:45, lineHeight:'45px', color: grey900, flex: '1 1 auto' }, bar:{ height:45, lineHeight:'45px', backgroundColor: '#fff', } }; class Header extends React.Component{ constructor(props){ super(props) } render(){ const pathname = this.props.path; const color = '#5e95c9' let title, leftIcons, rightIcons; switch(pathname) { case '/': title = '卓谷科技' rightIcons = <Link to='/setting'><IconButton><Settings color='#555'/></IconButton></Link> break; case '/check': title = '签到考勤' leftIcons = <ArrowBaclIcon color={color}/> rightIcons = <IconButton><AccessTime color={color}/></IconButton> break; case '/photo': case '/setting': case '/setting/about': case '/setting/opinion': title = '设置' leftIcons = <ArrowBaclIcon color={color}/> rightIcons = <IconButton><AccessTime color='#fff'/></IconButton> break; default: title = '最新更新人' leftIcons = <ArrowBaclIcon color={color}/> rightIcons = <IconButton><AccessTime color='#fff'/></IconButton> break; } return ( <AppBar titleStyle={styles.text} style={styles.bar} title={this.props.title || title} iconStyleRight={{marginTop:0}} iconStyleLeft={{marginTop:0,marginRight: 0}} iconElementLeft={<IconButton onTouchTap={this.context.router.goBack}>{leftIcons}</IconButton>} iconElementRight={rightIcons} /> ) } } Header.contextTypes = { router: React.PropTypes.object } export default Header;
app/jsx/account_settings/index.js
djbender/canvas-lms
/* * Copyright (C) 2018 - 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 {render} from 'react-dom' import {Provider} from 'react-redux' import {ConnectedSecurityPanel} from './components/SecurityPanel' import {configStore, defaultState} from './store' export function start(element, props = {}, state = defaultState) { const initialState = {...state} if (props.initialCspSettings) { initialState.cspEnabled = props.initialCspSettings.enabled initialState.cspInherited = props.initialCspSettings.inherited } const store = configStore(initialState, props.api) const config = { maxDomains: 50, accountId: window.ENV.ACCOUNT.id } render( <Provider store={store}> <ConnectedSecurityPanel {...config} {...props} /> </Provider>, element ) }
components/InteriorLeftNavList.js
hellobrian/carbon-components-react
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import classnames from 'classnames'; import InteriorLeftNavItem from './InteriorLeftNavItem'; import Icon from './Icon'; class InteriorLeftNavList extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.node, tabIndex: PropTypes.number, title: PropTypes.string, open: PropTypes.bool, onListClick: PropTypes.func, onItemClick: PropTypes.func, activeHref: PropTypes.string, iconDescription: PropTypes.string, id: PropTypes.string, }; static defaultProps = { title: 'Provide title', open: false, tabIndex: 0, activeHref: '#', iconDescription: 'display sub navigation items', onListClick: /* istanbul ignore next */ () => {}, onItemClick: /* istanbul ignore next */ () => {}, }; state = { open: this.props.open, }; toggle = evt => { if (evt.which === 13 || evt.which === 32 || evt.type === 'click') { if (!this.state.open) { this.props.onListClick(this.props.id); } this.setState({ open: !this.state.open }); } }; close = () => this.state.open && this.setState({ open: false }); buildNewItemChild = (child, index) => { const { onItemClick, activeHref } = this.props; const key = `listitem-${index}`; return ( <InteriorLeftNavItem {...child.props} key={key} onClick={onItemClick} activeHref={activeHref} tabIndex={this.state.open ? 0 : -1} /> ); }; render() { const { tabIndex, title, children, className, iconDescription, onListClick, // eslint-disable-line no-unused-vars onItemClick, // eslint-disable-line no-unused-vars activeHref, // eslint-disable-line no-unused-vars ...other } = this.props; const classNames = classnames( 'left-nav-list__item', 'left-nav-list__item--has-children', { 'left-nav-list__item--expanded': this.state.open, }, className ); const newChildren = React.Children.map(children, (child, index) => this.buildNewItemChild(child, index) ); return ( <li className={classNames} tabIndex={tabIndex} onClick={this.toggle} onKeyPress={this.toggle} role="menuitem" {...other}> <a className="left-nav-list__item-link"> {title} <div className="left-nav-list__item-icon"> <Icon name="chevron--down" description={iconDescription} className="left-nav-list__item-icon bx--interior-left-nav__icon" /> </div> </a> <ul role="menu" className="left-nav-list left-nav-list--nested" aria-hidden> {newChildren} </ul> </li> ); } } export default InteriorLeftNavList;
src/components/TextInputBEM/TextInputBEM.js
tlraridon/ps-react-train-tlr
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { return ( <div className='textinput'> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} className={error && 'textinput__input--state--error'} {...props}/> {children} {error && <div className='textinput__error'>{error}</div>} </div> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
github-battle-es6/app/components/App.js
josedab/react-exercises
import React from 'react'; import Popular from './Popular'; import {BrowserRouter as Router,Route, Switch} from 'react-router-dom'; import Nav from './Nav'; import Home from './Home'; import Battle from './Battle'; import Results from './Results'; class App extends React.Component { render() { return ( <Router> <div className='container'> <Nav /> <Switch> <Route exact path='/' component={Home}/> <Route exact path='/battle' component={Battle}/> <Route path='/battle/results' component={Results}/> <Route path='/popular' component={Popular}/> <Route render={ function(){ return <p>Not found</p> } }/> </Switch> </div> </Router> ) } } export default App;
src/svg-icons/notification/system-update.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSystemUpdate = (props) => ( <SvgIcon {...props}> <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z"/> </SvgIcon> ); NotificationSystemUpdate = pure(NotificationSystemUpdate); NotificationSystemUpdate.displayName = 'NotificationSystemUpdate'; NotificationSystemUpdate.muiName = 'SvgIcon'; export default NotificationSystemUpdate;
tests/framework.spec.js
SHBailey/echo-mvp
import assert from 'assert' import React from 'react' import {mount, render, shallow} from 'enzyme' class Fixture extends React.Component { render () { return ( <div> <input id='checked' defaultChecked /> <input id='not' defaultChecked={false} /> </div> ) } } describe('(Framework) Karma Plugins', function () { it('Should expose "expect" globally.', function () { assert.ok(expect) }) it('Should expose "should" globally.', function () { assert.ok(should) }) it('Should have chai-as-promised helpers.', function () { const pass = new Promise(res => res('test')) const fail = new Promise((res, rej) => rej()) return Promise.all([ expect(pass).to.be.fulfilled, expect(fail).to.not.be.fulfilled ]) }) it('should have chai-enzyme working', function() { let wrapper = shallow(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = mount(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = render(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() }) })
src/containers/challenges/Card/CardContainer.js
OlivierVillequey/hackathon
/** * Individual Challenge Card Container * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; // Actions import * as ChallengeActions from '@redux/challenges/actions'; // Components import ChallengeCardRender from './CardView'; /* Redux ==================================================================== */ // What data from the store shall we send to the component? const mapStateToProps = state => ({ user: state.user, favourites: (state.challenge && state.challenge.favourites) ? state.challenge.favourites : null, }); // Any actions to map to the component? const mapDispatchToProps = { replaceFavourites: ChallengeActions.replaceFavourites, }; /* Component ==================================================================== */ class ChallengeCard extends Component { static componentName = 'ChallengeCard'; static propTypes = { challenge: PropTypes.shape({ id: PropTypes.number.isRequired, title: PropTypes.string.isRequired, body: PropTypes.string.isRequired, image: PropTypes.string, }).isRequired, replaceFavourites: PropTypes.func.isRequired, favourites: PropTypes.arrayOf(PropTypes.number), user: PropTypes.shape({ uid: PropTypes.string, }), } static defaultProps = { favourites: null, user: null, } constructor(props) { super(props); this.state = { challenge: props.challenge }; } componentWillReceiveProps(props) { if (props.challenge) { this.setState({ challenge: props.challenge }); } } /** * On Press of Card */ onPressCard = () => { Actions.challengeView({ title: this.props.challenge.title, challenge: this.props.challenge, }); } /** * When user taps to favourite a challenge */ onPressFavourite = () => { if (this.props.user && this.props.user.uid) { const challengeId = this.props.challenge.id; if (challengeId && this.props.replaceFavourites) { const favs = this.props.favourites; // Toggle to/from current list if (this.isFavourite()) { favs.splice(favs.indexOf(this.props.challenge.id), 1); } else { favs.push(challengeId); } // Send new list to API this.props.replaceFavourites(favs); // Manually trigger a re-render - I wish I knew why this was required... this.setState({ challenge: this.state.challenge }); } } } /** * Check in Redux to find if this Challenge ID is a Favourite */ isFavourite = () => { const { favourites, challenge } = this.props; if (challenge && challenge.id && favourites) { if (favourites.length > 0 && favourites.indexOf(challenge.id) > -1) return true; } return false; } render = () => { const { challenge } = this.state; const { user } = this.props; return ( <ChallengeCardRender title={challenge.title} body={challenge.body} image={challenge.image} onPress={this.onPressCard} onPressFavourite={(user && user.uid) ? this.onPressFavourite : null} isFavourite={(user && user.uid && this.isFavourite()) && true} /> ); } } /* Export Component ==================================================================== */ export default connect(mapStateToProps, mapDispatchToProps)(ChallengeCard);
components/chip/__test__/index.spec.js
VACO-GitHub/vaco-components-library
import expect from 'expect'; import React from 'react'; import ReactDOM from 'react-dom'; import ReactTestUtils from 'react-addons-test-utils'; import { themr } from 'react-css-themr'; import { CHIP } from '../../identifiers.js'; import { chipFactory } from '../Chip'; import { tooltipFactory } from '../../tooltip'; const Avatar = ({title}) => <span>{title}</span>; // eslint-disable-line react/prop-types const Chip = themr(CHIP)(chipFactory(Avatar)); describe('Chip', function () { describe('with avatar', function () { it('adds the avatar class to the element', function () { const tree = ReactTestUtils.renderIntoDocument( <Chip theme={{avatar: 'avatar-class'}}> <Avatar title='Test'/> <span>Test</span> </Chip> ); const chip = ReactTestUtils.findRenderedComponentWithType(tree, Chip); const chipNode = ReactDOM.findDOMNode(chip); expect(chipNode.className).toMatch(/\bavatar-class\b/); }); it('works with non-flat children', function () { const TooltippedChip = tooltipFactory()(Chip); const tree = ReactTestUtils.renderIntoDocument( <TooltippedChip theme={{avatar: 'avatar-class'}} tooltip='Test tooltip'> <Avatar title='Test'/> <span>Test</span> </TooltippedChip> ); const chip = ReactTestUtils.findRenderedComponentWithType(tree, Chip); const chipNode = ReactDOM.findDOMNode(chip); expect(chipNode.className).toMatch(/\bavatar-class\b/); }); }); describe('without avatar', function () { it('does not add avatar class to the element', function () { const tree = ReactTestUtils.renderIntoDocument( <Chip theme={{avatar: 'avatar-class'}}> <span>Test</span> </Chip> ); const chip = ReactTestUtils.findRenderedComponentWithType(tree, Chip); const chipNode = ReactDOM.findDOMNode(chip); expect(chipNode.className).toNotMatch(/\bavatar-class\b/); }); }); });
app/javascript/mastodon/components/display_name.js
kagucho/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import escapeTextContentForBrowser from 'escape-html'; import emojify from '../emoji'; export default class DisplayName extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const displayName = this.props.account.get('display_name').length === 0 ? this.props.account.get('username') : this.props.account.get('display_name'); const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) }; return ( <span className='display-name'> <strong className='display-name__html' dangerouslySetInnerHTML={displayNameHTML} /> <span className='display-name__account'>@{this.props.account.get('acct')}</span> </span> ); } }
packages/core/src/components/Form/StarRating/StarRating.js
appearhere/bloom
// @flow import React, { Component } from 'react'; import cx from 'classnames'; import css from './StarRating.css'; import starCss from '../Star/Star.css'; import Star from '../Star/Star'; import RadioGroup from '../RadioGroup/RadioGroup'; type Props = { name: string, ratings: Array<number>, value: number, } export default class StarRating extends Component<Props> { group: HTMLInputElement; static defaultProps = { ratings: [1, 2, 3, 4, 5], }; focus = (): void => { this.group.focus(); }; blur = (): void => { this.group.blur(); }; render() { const { name, value, ratings, ...rest } = this.props; return ( <RadioGroup {...(rest: any)} ref={c => { this.group = c; }} name={name} value={value} Input={Star} > {radio => ( <span> {ratings.map(rating => radio({ key: `${name}-${rating}`, value: rating, className: cx(css.starContainer, value >= rating ? starCss.active : null), }), )} </span> )} </RadioGroup> ); } }
src/index.js
paulmusso/webpack-boilerplate
import React from 'react'; import ReactDom from 'react-dom'; import App from './App'; import styles from './assets/styles/styles.less'; ReactDom.render( <App />, document.getElementById('app') );
src/LinearProgress/LinearProgress.spec.js
igorbt/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import LinearProgress from './LinearProgress'; import getMuiTheme from '../styles/getMuiTheme'; describe('<LinearProgress />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); describe('props: min', () => { it('should work when min equal zero', () => { const wrapper = shallowWithContext( <LinearProgress mode="determinate" value={50} min={0} max={100} /> ); assert.strictEqual(wrapper.children().props().style.width, '50%', 'should compute the width correctly'); }); it('should work when min is different to zero', () => { const wrapper = shallowWithContext( <LinearProgress mode="determinate" value={75} min={50} max={100} /> ); assert.strictEqual(wrapper.children().props().style.width, '50%', 'should compute the width correctly'); }); it('should work when value equal min', () => { const wrapper = shallowWithContext( <LinearProgress mode="determinate" value={50} min={50} max={100} /> ); assert.strictEqual(wrapper.children().props().style.width, '0%', 'should compute the width correctly'); }); }); });
src/components/video_detail.js
viniciusmichelutti/react-videos
import React from 'react' const VideoDetail = ({video}) => { if (!video) return <div>Loading...</div>; const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe src={url} className="embed-responsive-item"></iframe> </div> <div className="details"> <div><h3>{video.snippet.title}</h3></div> <div><p>{video.snippet.description}</p></div> </div> </div> ); }; export default VideoDetail;
dev/src/entry.js
RealScout/redux-infinite-scroll
import React from 'react'; import ReactDOM from 'react-dom'; import InfScroller from '../../src/ReduxInfiniteScroll'; class App extends React.Component { state = { numOfItems: 40, loadingMore: false }; _createData(numOfItems=this.state.numOfItems) { const data = []; for (var i=0; i < numOfItems; i++) { data.push( <div key={i}>Item #{i}</div> ) } return data; } _loadMore() { console.log('loading More'); this.setState({loadingMore: true}, () => { // CB emulates an ajax request this.setState({ numOfItems: this.state.numOfItems + 40, loadingMore: false }) }) } render() { return ( <div> <h2>Dev Env</h2> <InfScroller loadMore={this._loadMore.bind(this)} hasMore={true} loadingMore={this.state.loadingMore} showLoader={true} threshold={50} containerHeight={200} animateItems={true} items={this._createData()} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('entry'));
docs/index.js
jie/douban-editor
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import {DoubanEditor} from 'douban-editor'; import '../dist/style.css' class MyDoubanEditor extends React.Component { constructor(props) { super(props); } render() { return <div className="container"> <DoubanEditor titlePlaceholder={'添加标题...'} placeholder={'写文章...'}/> </div> } } ReactDOM.render(<MyDoubanEditor />, document.getElementById('target'));
packages/babel-plugin-remove-graphql-queries/src/__tests__/index.js
mingaldrichgan/gatsby
const babel = require(`babel-core`) const plugin = require(`../`) function matchesSnapshot(query) { const { code } = babel.transform(query, { presets: [`@babel/preset-react`], plugins: [plugin], }) expect(code).toMatchSnapshot() } it(`Transforms queries in <StaticQuery>`, () => { matchesSnapshot(` import React from 'react' import { graphql, StaticQuery } from 'gatsby' export default () => ( <StaticQuery query={graphql\`{site { siteMetadata { title }}}\`} render={data => <div>{data.site.siteMetadata.title}</div>} /> ) `) }) it(`Transforms queries defined in own variable in <StaticQuery>`, () => { matchesSnapshot(` import React from 'react' import { graphql, StaticQuery } from 'gatsby' const query = graphql\`{site { siteMetadata { title }}}\` export default () => ( <StaticQuery query={query} render={data => <div>{data.site.siteMetadata.title}</div>} /> ) `) }) it(`Transforms queries in page components`, () => { matchesSnapshot(` import { graphql } from 'gatsby' export const query = graphql\` { site { siteMetadata { title }} } \` `) }) it(`allows the global tag`, () => { matchesSnapshot( ` export const query = graphql\` { site { siteMetadata { title }} } \` ` ) }) it(`distinguishes between the right tags`, () => { matchesSnapshot( ` const foo = styled('div')\` { $\{foo} } \` const pulse = keyframes\` 0% { transform: scale(1); animation-timing-function: ease-in; } 25% { animation-timing-function: ease-out; transform: scale(1.05); } 50% { transform: scale(1.12); animation-timing-function: ease-in; } to { transform: scale(1); animation-timing-function: ease-out; } \`; export const query = graphql\` { site { siteMetadata { title }} } \` ` ) }) it(`handles import aliasing`, () => { matchesSnapshot( ` import { graphql as gql } from 'gatsby' export const query = gql\` { site { siteMetadata { title }} } \` ` ) }) it(`handles require`, () => { matchesSnapshot( ` const { graphql } = require('gatsby') export const query = graphql\` { site { siteMetadata { title }} } \` ` ) }) it(`handles require namespace`, () => { matchesSnapshot( ` const Gatsby = require('gatsby') export const query = Gatsby.graphql\` { site { siteMetadata { title }} } \` ` ) }) it(`handles require alias`, () => { matchesSnapshot( ` const { graphql: gql } = require('gatsby') export const query = gql\` { site { siteMetadata { title }} } \` ` ) }) it(`Leaves other graphql tags alone`, () => { matchesSnapshot( ` import React from 'react' import { graphql } from 'relay' export default () => ( <div>{data.site.siteMetadata.title}</div> ) export const query = graphql\` { site { siteMetadata { title }} } \` ` ) }) it(`Removes all gatsby queries`, () => { matchesSnapshot( ` import { graphql } from 'gatsby' export default () => ( <div>{data.site.siteMetadata.title}</div> ) export const siteMetaQuery = graphql\` fragment siteMetaQuery on RootQueryType { site { siteMetadata { title } } } \` export const query = graphql\` { ...siteMetaQuery } \` ` ) }) it(`Handles closing StaticQuery tag`, () => { matchesSnapshot(` import React from 'react' import { graphql, StaticQuery } from 'gatsby' export default () => ( <StaticQuery query={graphql\`{site { siteMetadata { title }}}\`} > {data => <div>{data.site.siteMetadata.title}</div>} </StaticQuery> ) `) }) it(`Doesn't add data import for non static queries`, () => { matchesSnapshot(` import React from 'react' import { StaticQuery, graphql } from "gatsby" const Test = () => ( <StaticQuery query={graphql\` { site { siteMetadata { title } } } \`} render={data => <div>{data.site.siteMetadata.title}</div>} /> ) export default Test export const fragment = graphql\` fragment MarkdownNodeFragment on MarkdownRemark { html } \` `) })
docs/src/app/components/pages/components/Paper/ExampleSimple.js
lawrence-yu/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { height: 100, width: 100, margin: 20, textAlign: 'center', display: 'inline-block', }; const PaperExampleSimple = () => ( <div> <Paper style={style} zDepth={1} /> <Paper style={style} zDepth={2} /> <Paper style={style} zDepth={3} /> <Paper style={style} zDepth={4} /> <Paper style={style} zDepth={5} /> </div> ); export default PaperExampleSimple;
Realization/frontend/czechidm-acc/src/content/system/SystemProvisioningBreakConfigRecipientTable.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; // import { Basic, Advanced, Utils, Managers, Domain } from 'czechidm-core'; const ROLE_TYPE = 'roleType'; const IDENTITY_TYPE = 'identityType'; /** * Table of provisioning break recipient * * @author Ondrej Kopr * @author Radek Tomiška */ export class SystemProvisioningBreakConfigRecipientTable extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); this.state = { filterOpened: this.props.filterOpened, detail: { show: false, entity: { type: ROLE_TYPE } } }; } getContentKey() { return 'acc:content.provisioningBreakConfigRecipient'; } getManager() { const { manager } = this.props; // return manager; } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } cancelFilter(event) { if (event) { event.preventDefault(); } this.refs.table.cancelFilter(this.refs.filterForm); } showDetail(entity, event) { if (event) { event.preventDefault(); } const detail = _.merge({}, this.state.detail); detail.show = true; if (entity) { detail.entity = entity; if (entity.role != null) { detail.entity.type = ROLE_TYPE; } else { detail.entity.type = IDENTITY_TYPE; } } else { detail.entity = { type: ROLE_TYPE // role type }; } this.setState({ detail }); } saveDetail(event) { if (event) { event.preventDefault(); } const detail = _.merge({}, this.state.detail); const { provisioningBreakConfigId, uiKey, manager } = this.props; // if (!this.refs.form.isFormValid()) { return; } // const formEntity = this.refs.form.getData(); detail.showLoading = true; this.setState({ detail }, () => { // const savedEntity = { ...formEntity, breakConfig: provisioningBreakConfigId }; // // null unused value if (formEntity.type === ROLE_TYPE) { formEntity.identity = null; } else { formEntity.role = null; } // if (savedEntity.id === undefined) { this.context.store.dispatch(manager.createEntity(savedEntity, `${uiKey}-detail`, (createdEntity, error) => { this.afterSave(createdEntity, error, true); })); } else { this.context.store.dispatch(manager.updateEntity(savedEntity, `${uiKey}-detail`, this.afterSave.bind(this))); } }); } afterSave(entity, error, newEntity) { if (!error) { if (newEntity) { this.addMessage({ message: this.i18n('create.success', { entityType: entity.entityType, operationType: entity.operationType}) }); } else { this.addMessage({ message: this.i18n('save.success', {entityType: entity.entityType, operationType: entity.operationType}) }); } } else { this.addError(error); } const detail = _.merge({}, this.state.detail); // detail.show = false; detail.showLoading = false; this.setState({ detail }, () => { this.refs.table.reload(); super.afterSave(); }); } _closeModal(event) { if (event) { event.preventDefault(); } const detail = _.merge({}, this.state.detail); detail.show = false; this.setState({ detail }); } changeRecipientType(value, event) { if (event) { event.preventDefault(); } const detail = _.merge({}, this.state.detail); // clear identity and role after type was changed if (detail && detail.entity) { detail.entity.type = value.value; detail.entity.identity = null; detail.entity.role = null; if (detail.entity_embedded) { detail.entity._embedded.identity = null; detail.entity._embedded.role = null; } } this.setState({ detail }); } _getRecipientType(entity) { if (!entity) { return null; } if (entity.role) { return (<Basic.Label level="info" text={this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.role')}/>); } if (entity.identity) { return (<Basic.Label level="success" text={this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.identity')}/>); } return null; } _getRecipientName(entity) { if (entity && entity.role) { if (entity._embedded) { return ( <Advanced.EntityInfo entityType="role" entityIdentifier={ entity.role } entity={ entity._embedded.role } face="popover" showIcon/> ); } return entity.role; } if (entity && entity.identity) { if (entity._embedded) { return ( <Advanced.EntityInfo entityType="identity" entityIdentifier={ entity.identity } entity={ entity._embedded.identity } face="popover" showIcon/> ); } return entity.identity; } return null; } getTableButtons(showAddButton) { return ( [ <Basic.Button level="success" key="add_button" className="btn-xs" onClick={ this.showDetail.bind(this, null) } rendered={ Managers.SecurityManager.hasAuthority('SYSTEM_UPDATE') && showAddButton } icon="fa:plus"> { this.i18n('button.add') } </Basic.Button> ]); } render() { const { uiKey, manager, columns, forceSearchParameters, showAddButton, showRowSelection, rendered, className } = this.props; const { filterOpened, detail } = this.state; const isNew = detail.entity.id === undefined || detail.entity.id === null; if (!rendered) { return null; } // return ( <Basic.Div> <Basic.Confirm ref="confirm-delete" level="danger"/> <Basic.Modal show={ detail.show } showLoading={ detail.showLoading } onHide={ this._closeModal.bind(this) }> <form onSubmit={ this.saveDetail.bind(this) }> <Basic.Modal.Header text={ this.i18n('acc:content.provisioningBreakConfigRecipient.new') } rendered={ isNew } /> <Basic.Modal.Header text={ this.i18n('acc:content.provisioningBreakConfigRecipient.edit') } rendered={ !isNew } /> <Basic.Modal.Body> <Basic.AbstractForm ref="form" data={ detail.entity }> <Basic.EnumSelectBox ref="type" label={ this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.label') } value={ detail.type } clearable={ false } options={[ { value: ROLE_TYPE, niceLabel: this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.role') }, { value: IDENTITY_TYPE, niceLabel: this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.identity') } ]} onChange={ this.changeRecipientType.bind(this)} required/> <Advanced.IdentitySelect ref="identity" label={ this.i18n('acc:entity.ProvisioningBreakConfigRecipient.identity') } hidden={ detail.entity.type === ROLE_TYPE } required={ detail.entity.type === IDENTITY_TYPE } clearable={ false }/> <Advanced.RoleSelect ref="role" label={ this.i18n('acc:entity.ProvisioningBreakConfigRecipient.role') } hidden={ detail.entity.type === IDENTITY_TYPE } required={ detail.entity.type === ROLE_TYPE } clearable={ false }/> </Basic.AbstractForm> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={ this._closeModal.bind(this) }>{ this.i18n('button.cancel') }</Basic.Button> <Basic.Button ref="yesButton" level="success" onClick={ this.saveDetail.bind(this) } rendered={ isNew }> { this.i18n('button.create') } </Basic.Button> <Basic.Button ref="yesButton" level="success" onClick={ this.saveDetail.bind(this) } rendered={ !isNew }> {this.i18n('button.save')} </Basic.Button> </Basic.Modal.Footer> </form> </Basic.Modal> <Advanced.Table ref="table" uiKey={ uiKey } manager={ manager } filterOpened={ filterOpened } forceSearchParameters={ forceSearchParameters } showRowSelection={ Managers.SecurityManager.hasAuthority('SYSTEM_DELETE') && showRowSelection } className={ className } filter={ <Advanced.Filter onSubmit={ this.useFilter.bind(this) }> <Basic.AbstractForm ref="filterForm"> <Basic.Row className="last"> <Basic.Col lg={ 4 }> <Advanced.Filter.IdentitySelect label={ null } placeholder={ this.i18n('entity.Identity._type') } ref="identityId"/> </Basic.Col> <Basic.Col lg={ 4 }> <Advanced.Filter.RoleSelect label={ null } placeholder={ this.i18n('entity.Role._type') } ref="roleId"/> </Basic.Col> <Basic.Col lg={ 4 } className="text-right"> <Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/> </Basic.Col> </Basic.Row> </Basic.AbstractForm> </Advanced.Filter> } actions={ [ { value: 'delete', niceLabel: this.i18n('action.delete.action'), action: this.onDelete.bind(this), disabled: false } ] } buttons={ this.getTableButtons(showAddButton) } _searchParameters={ this.getSearchParameters() }> <Advanced.Column header="" className="detail-button" rendered={ Managers.SecurityManager.hasAnyAuthority(['SYSTEM_UPDATE']) } cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={this.i18n('button.detail')} onClick={ this.showDetail.bind(this, data[rowIndex]) }/> ); } } sort={false}/> <Advanced.Column property="type" rendered={_.includes(columns, 'type')} header={this.i18n('acc:entity.ProvisioningBreakConfigRecipient.type.label')} width={ 130 } cell={({ rowIndex, data }) => { return ( this._getRecipientType(data[rowIndex]) ); }}/> <Advanced.Column property="name" sort face="text" rendered={_.includes(columns, 'name')} header={this.i18n('acc:entity.ProvisioningBreakConfigRecipient.name')} cell={({ rowIndex, data }) => { return ( this._getRecipientName(data[rowIndex]) ); }}/> </Advanced.Table> </Basic.Div> ); } } SystemProvisioningBreakConfigRecipientTable.propTypes = { uiKey: PropTypes.string.isRequired, manager: PropTypes.object.isRequired, columns: PropTypes.arrayOf(PropTypes.string), filterOpened: PropTypes.bool, forceSearchParameters: PropTypes.object, showAddButton: PropTypes.bool, showRowSelection: PropTypes.bool, rendered: PropTypes.bool, provisioningBreakConfigId: PropTypes.string }; SystemProvisioningBreakConfigRecipientTable.defaultProps = { columns: ['name', 'type'], filterOpened: false, _showLoading: false, forceSearchParameters: new Domain.SearchParameters(), showAddButton: true, showRowSelection: true, rendered: true }; function select(state, component) { return { _searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey), _showLoading: component.manager.isShowLoading(state, `${component.uiKey}-detail`) }; } export default connect(select)(SystemProvisioningBreakConfigRecipientTable);
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
dunn/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages } from 'react-intl'; import IconButton from '../../../components/icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import detectPassiveEvents from 'detect-passive-events'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; 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 listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; class PrivacyDropdownMenu extends React.PureComponent { static propTypes = { style: PropTypes.object, items: PropTypes.array.isRequired, value: PropTypes.string.isRequired, placement: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } handleKeyDown = e => { const { items } = this.props; const value = e.currentTarget.getAttribute('data-index'); const index = items.findIndex(item => { return (item.value === value); }); let element; switch(e.key) { case 'Escape': this.props.onClose(); break; case 'Enter': this.handleClick(e); break; case 'ArrowDown': element = this.node.childNodes[index + 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'ArrowUp': element = this.node.childNodes[index - 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'Tab': if (e.shiftKey) { element = this.node.childNodes[index - 1] || this.node.lastChild; } else { element = this.node.childNodes[index + 1] || this.node.firstChild; } if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); e.preventDefault(); e.stopPropagation(); } break; case 'Home': element = this.node.firstChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'End': element = this.node.lastChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; } } handleClick = e => { const value = e.currentTarget.getAttribute('data-index'); e.preventDefault(); this.props.onClose(); this.props.onChange(value); } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem) this.focusedItem.focus(); this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } render () { const { mounted } = this.state; const { style, items, placement, value } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`privacy-dropdown__dropdown ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null, zIndex: 2 }} role='listbox' ref={this.setRef}> {items.map(item => ( <div role='option' tabIndex='0' key={item.value} data-index={item.value} onKeyDown={this.handleKeyDown} onClick={this.handleClick} className={classNames('privacy-dropdown__option', { active: item.value === value })} aria-selected={item.value === value} ref={item.value === value ? this.setFocusRef : null}> <div className='privacy-dropdown__option__icon'> <Icon id={item.icon} fixedWidth /> </div> <div className='privacy-dropdown__option__content'> <strong>{item.text}</strong> {item.meta} </div> </div> ))} </div> )} </Motion> ); } } export default @injectIntl class PrivacyDropdown extends React.PureComponent { static propTypes = { isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onModalOpen: PropTypes.func, onModalClose: PropTypes.func, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: false, placement: 'bottom', }; handleToggle = ({ target }) => { if (this.props.isUserTouching()) { if (this.state.open) { this.props.onModalClose(); } else { this.props.onModalOpen({ actions: this.options.map(option => ({ ...option, active: option.value === this.props.value })), onClick: this.handleModalActionClick, }); } } else { const { top } = target.getBoundingClientRect(); if (this.state.open && this.activeElement) { this.activeElement.focus(); } this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); this.setState({ open: !this.state.open }); } } handleModalActionClick = (e) => { e.preventDefault(); const { value } = this.options[e.currentTarget.getAttribute('data-index')]; this.props.onModalClose(); this.props.onChange(value); } handleKeyDown = e => { switch(e.key) { case 'Escape': this.handleClose(); break; } } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleClose = () => { if (this.state.open && this.activeElement) { this.activeElement.focus(); } this.setState({ open: false }); } handleChange = value => { this.props.onChange(value); } componentWillMount () { const { intl: { formatMessage } } = this.props; this.options = [ { icon: 'globe', value: 'public', text: formatMessage(messages.public_short), meta: formatMessage(messages.public_long) }, { icon: 'unlock', value: 'unlisted', text: formatMessage(messages.unlisted_short), meta: formatMessage(messages.unlisted_long) }, { icon: 'lock', value: 'private', text: formatMessage(messages.private_short), meta: formatMessage(messages.private_long) }, { icon: 'envelope', value: 'direct', text: formatMessage(messages.direct_short), meta: formatMessage(messages.direct_long) }, ]; } render () { const { value, intl } = this.props; const { open, placement } = this.state; const valueOption = this.options.find(item => item.value === value); return ( <div className={classNames('privacy-dropdown', placement, { active: open })} onKeyDown={this.handleKeyDown}> <div className={classNames('privacy-dropdown__value', { active: this.options.indexOf(valueOption) === (placement === 'bottom' ? 0 : (this.options.length - 1)) })}> <IconButton className='privacy-dropdown__value-icon' icon={valueOption.icon} title={intl.formatMessage(messages.change_privacy)} size={18} expanded={open} active={open} inverted onClick={this.handleToggle} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} style={{ height: null, lineHeight: '27px' }} /> </div> <Overlay show={open} placement={placement} target={this}> <PrivacyDropdownMenu items={this.options} value={value} onClose={this.handleClose} onChange={this.handleChange} placement={placement} /> </Overlay> </div> ); } }
renderer/components/Tab.js
markmarcelo/reactide
import React from 'react'; import PropTypes from 'prop-types'; const Tab = ({ name, setActiveTab, id, closeTab }) => { return ( <li className="texteditor tab" onClick={setActiveTab.bind(null, id)}> <div className="title">{name}</div> <div className="close-icon" onClick={closeTab.bind(null, id)} /> </li> ); }; Tab.propTypes = { name: PropTypes.string.isRequired, setActiveTab: PropTypes.func.isRequired, id: PropTypes.number.isRequired, closeTab: PropTypes.func.isRequired }; export default Tab;
src/svg-icons/device/access-time.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessTime = (props) => ( <SvgIcon {...props}> <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 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); DeviceAccessTime = pure(DeviceAccessTime); DeviceAccessTime.displayName = 'DeviceAccessTime'; DeviceAccessTime.muiName = 'SvgIcon'; export default DeviceAccessTime;
app/components/events/comments/CommentItem.js
alexko13/block-and-frame
import React from 'react'; const Comment = (props) => { return ( <div className="comment"> <div className="content"> <a className="author">{props.username}</a> <div className="metadata"> <span className="date">{props.timeCreated}</span> </div> <div className="text"> {props.text} </div> </div> </div> ); }; module.exports = Comment;
client/app/scripts/components/node-details/node-details-info.js
paulbellamy/scope
import React from 'react'; import { Map as makeMap } from 'immutable'; import MatchedText from '../matched-text'; import ShowMore from '../show-more'; import { formatDataType } from '../../utils/string-utils'; export default class NodeDetailsInfo extends React.Component { constructor(props, context) { super(props, context); this.state = { expanded: false }; this.handleClickMore = this.handleClickMore.bind(this); } handleClickMore() { const expanded = !this.state.expanded; this.setState({expanded}); } render() { const { matches = makeMap() } = this.props; let rows = (this.props.rows || []); let notShown = 0; const prime = rows.filter(row => row.priority < 10); if (!this.state.expanded && prime.length < rows.length) { // check if there is a search match in non-prime fields const hasNonPrimeMatch = matches && rows.filter(row => row.priority >= 10 && matches.has(row.id)).length > 0; if (!hasNonPrimeMatch) { notShown = rows.length - prime.length; rows = prime; } } return ( <div className="node-details-info"> {rows.map((field) => { const { value, title } = formatDataType(field); return ( <div className="node-details-info-field" key={field.id}> <div className="node-details-info-field-label truncate" title={field.label}> {field.label} </div> <div className="node-details-info-field-value truncate" title={title}> <MatchedText text={value} truncate={field.truncate} match={matches.get(field.id)} /> </div> </div> ); })} <ShowMore handleClick={this.handleClickMore} collection={this.props.rows} expanded={this.state.expanded} notShown={notShown} /> </div> ); } }
app/jsx/course_settings/renderCSPSelectionBox.js
djbender/canvas-lms
/* * Copyright (C) 2019 - 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 axios from 'axios' import ReactDOM from 'react-dom' import React from 'react' import CSPSelectionBox from './components/CSPSelectionBox' export function renderCSPSelectionBox(containerElement) { ReactDOM.render( <CSPSelectionBox courseId={ENV.COURSE_ID} canManage={ENV.PERMISSIONS.manage_account_settings} apiLibrary={axios} />, containerElement ) }
public/src/admin/admin.js
SLedunois/personal-website
import './admin.css'; import initOpbeat, { wrapRouter } from 'opbeat-react'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Route, Switch, HashRouter } from 'react-router-dom'; import createBrowserHistory from 'history/createBrowserHistory'; import AdminPanel from './AdminPanel.react'; import Blog from './blog/Blog.react'; import Content from './content/Content.react'; import Metrics from './metrics/Metrics.react'; initOpbeat({ orgId: '3d480c5736f24cd5b22edc2b73b74cd7', appId: 'd0513a1914', }); const OpbeatRouter = wrapRouter(Router); const history = createBrowserHistory(); ReactDOM.render( <div className="col-8 content"> <OpbeatRouter> <HashRouter history={history}> <AdminPanel location={location}> <Switch> <Route exact path="/" component={Content} /> <Route path="/blog" component={Blog} /> <Route path="/metrics" component={Metrics} /> </Switch> </AdminPanel> </HashRouter> </OpbeatRouter> </div>, document.getElementById('admin-app') );
src/components/header.js
baltazarparra/modal
import React from 'react' import PropTypes from 'prop-types' const Header = ({pageActive, handleBack}) => ( <header className="header"> {pageActive === 'checkout' && <button className="header__button header__button--back" onClick={handleBack}> 〈 </button>} <h1 className="header__title">Assine o Sexlog VIP</h1> <button className="header__button"> ✕ </button> {pageActive === 'home' && <div className="header__breadcrumb"> <p className="header__description active">Escolhe o plano ideal para você</p> <p className="header__description">Escolha a forma de pagamento</p> </div>} {pageActive === 'checkout' && <div className="header__breadcrumb"> <p className="header__description">Escolhe o plano ideal para você</p> <p className="header__description active">Escolha a forma de pagamento</p> </div>} </header> ) Header.propTypes = { handleBack: PropTypes.func.isRequired, pageActive: PropTypes.string.isRequired } export default Header
stories/Breadcrubms/ExampleUsingURL.js
skyiea/wix-style-react
import React from 'react'; import styles from './ExampleBreadcrumbs.scss'; import Breadcrumbs, {breadcrumbsPathFactory} from '../../src/Breadcrumbs/Breadcrumbs'; const items = breadcrumbsPathFactory('aa/bb/cc/dd'); const itemsAbsolute = breadcrumbsPathFactory('domain/names', 'http://www.wix.com', 'wix'); export default () => <div className={`${styles.onGrayBackground} ${styles.exampleWrapper}`}> <div>Relative url:<Breadcrumbs items={items} size={'medium'}/></div> <div>Absolute url:<Breadcrumbs items={itemsAbsolute} size={'medium'}/></div> </div>;
app/init/routes.js
spleenboy/pallium
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import ProjectPage from '../project/ProjectPage'; import SettingsPage from '../settings/SettingsPage'; export default ( <Route path="/" component={App}> <IndexRoute component={ProjectPage} /> <Route path="/settings" component={SettingsPage} /> </Route> );
fields/types/number/NumberColumn.js
ratecity/keystone
import React from 'react'; import numeral from 'numeral'; import 'whatwg-fetch' import FormData from 'form-data'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; import { FormInput } from '../../../admin/client/App/elemental'; var NumberColumn = React.createClass({ displayName: 'NumberColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, getInitialState () { return { value: null, editing: false, color: 'black' } }, value () { return this.state.value || this.props.data.fields[this.props.col.path]; }, renderValue () { const value = this.value(); if (this.state.editing) { return <FormInput autoComplete="off" onChange={this.onChange.bind(this)} onBlur={this.onBlur.bind(this)} onKeyPress={this.onKeyPress.bind(this)} ref={(input) => {if (input && this.shouldSelect) {input.select(); this.shouldSelect = false; } }} value={value} /> } else { if (!value || isNaN(value)) return value; return (this.props.col.path === 'money') ? numeral(value).format('$0,0.00') : value; } }, onKeyPress (event) { if (event.nativeEvent && event.nativeEvent.code === 'Enter') { this.onBlur(); } }, onChange (event) { this.setState({value: event.target.value}) }, onClick () { this.shouldSelect = true this.setState({editing: true}); }, onBlur () { const url = `/keystone/api/${this.props.list.path}/${this.props.data.id}` var form = new FormData(); form.append(this.props.col.path, this.value()); fetch(url, {method: 'POST', body: form, credentials: 'same-origin'}).then((response) => { response.json().then((json) => { if (json.error) { this.setState({color: 'red'}) } else { this.setState({color: 'green'}) } }) }); this.setState({editing: false}); }, render () { return ( <ItemsTableCell onClick={this.onClick.bind(this)}> <ItemsTableValue field={this.props.col.type} style={{color: this.state.color}}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = NumberColumn;
docs/app/Examples/elements/Label/Content/LabelExampleLink.js
ben174/Semantic-UI-React
import React from 'react' import { Icon, Label } from 'semantic-ui-react' const LabelExampleLink = () => ( <Label as='a'> <Icon name='mail' /> 23 </Label> ) export default LabelExampleLink
CompositeUi/src/views/component/PageHeader.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/components/_page-header.scss'; import React from 'react'; class PageHeader extends React.Component { static propTypes = { thumbnail: React.PropTypes.element, title: React.PropTypes.string, }; render() { const {thumbnail, title, children} = this.props; return ( <div className="page-header"> {thumbnail} <h2 className="page-header__title"> {title} </h2> <div className="page-header__actions"> {children} </div> </div> ); } } export default PageHeader;
src/components/PasswordInput/PasswordInput.spec.js
ibenavides/ps-react-ibenavides
import React from 'react'; import renderer from 'react-test-renderer'; import PasswordInput from './PasswordInput'; import {shallow} from 'enzyme'; test('', () =>{ const wrapper = shallow(<PasswordInput htmlId="test" name="test" value="" onChange={() => {}} showVisibilityToggle /> ); expect(wrapper.find({type:'password'})).toHaveLength(1); expect(wrapper.find({type:'text'})).toHaveLength(0); wrapper.find('a').simulate('click'); expect(wrapper.find({type:'password'})).toHaveLength(0); expect(wrapper.find({type:'text'})).toHaveLength(1); }); test('toggles input type when show/hide password clicked', () => { const wrapper = shallow(<PasswordInput htmlId="test" name="test" value="" onChange={() => {}} showVisibilityToggle /> ); // Password input should have a type of password initially expect(wrapper.find({type: 'password'})).toHaveLength(1); expect(wrapper.find({type: 'text'})).toHaveLength(0); wrapper.find('a').simulate('click'); // Password input should have a type of text after clicking toggle expect(wrapper.find({type: 'password'})).toHaveLength(0); expect(wrapper.find({type: 'text'})).toHaveLength(1); }); test('hides password quality by default', () => { const tree = renderer.create(<PasswordInput htmlId="test" name="test" onChange={() => {}} value="Uisi38#8iad" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('shows password quality when enabled and a password is entered', () => {   const tree = renderer.create(<PasswordInput     htmlId="test"     name="test"     onChange={() => {}}     showQuality     value="Uisi38#8iad" />).toJSON();   expect(tree).toMatchSnapshot(); }); test('hides password quality when enabled but no password is entered', () => {   const tree = renderer.create(<PasswordInput     htmlId="test"     name="test"     onChange={() => {}}     showQuality     value="" />).toJSON();   expect(tree).toMatchSnapshot(); });
fields/types/geopoint/GeoPointColumn.js
ONode/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/svg-icons/places/free-breakfast.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesFreeBreakfast = (props) => ( <SvgIcon {...props}> <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/> </SvgIcon> ); PlacesFreeBreakfast = pure(PlacesFreeBreakfast); PlacesFreeBreakfast.displayName = 'PlacesFreeBreakfast'; PlacesFreeBreakfast.muiName = 'SvgIcon'; export default PlacesFreeBreakfast;
src/default-props.js
hangarlabs/hangar-react-slick
import React from 'react'; var defaultProps = { className: '', accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', customPaging: function(i) { return <button>{i + 1}</button>; }, dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, pauseOnHover: true, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps;
src/App.js
mboperator/fractalTodoExample
import React, { Component } from 'react'; import { ModuleProvider } from 'redux-modules'; import generateStore from './store'; import TodoList from './components/TodoList'; // import todoSaga from './sagas/todos'; const store = generateStore(); // store.runSaga(todoSaga); export default class App extends Component { render() { return ( <ModuleProvider store={store}> <TodoList/> </ModuleProvider> ); } }
src/utils/createContextWrapper.js
zerkms/react-bootstrap
import React from 'react'; /** * Creates new trigger class that injects context into overlay. */ export default function createContextWrapper(Trigger, propName) { return function (contextTypes) { class ContextWrapper extends React.Component { getChildContext() { return this.props.context; } render() { // Strip injected props from below. const {wrapped, context, ...props} = this.props; return React.cloneElement(wrapped, props); } } ContextWrapper.childContextTypes = contextTypes; class TriggerWithContext { render() { const props = {...this.props}; props[propName] = this.getWrappedOverlay(); return ( <Trigger {...props}> {this.props.children} </Trigger> ); } getWrappedOverlay() { return ( <ContextWrapper context={this.context} wrapped={this.props[propName]} /> ); } } TriggerWithContext.contextTypes = contextTypes; return TriggerWithContext; }; }
examples/complex/src/routes.js
rocjs/roc-package-web-app-react
import React from 'react'; import Route from 'react-router/lib/Route'; import IndexRoute from 'react-router/lib/IndexRoute'; import App from './components/app'; import Main from './components/main'; import About from './components/about'; import Long from './components/long'; import Simple from './components/simple'; export default () => ( <Route component={ App } value={false}> <IndexRoute component={ Main } value={true} scrollToTop /> <Route path="about/" component={ About } data={2} ignoreScrollBehavior /> <Route path="long/" component={ Long } /> <Route path="simple/" component={ Simple } data={3} /> <Route path="async" getComponent={ (nextState, callback) => { require.ensure([], (require) => { const Async = require('./components/async').default; callback( null, Async ); }); }} data={4} /> </Route> ); export const middlewareConfig = { 'react-router-scroll-async': { /* This function will allow us to do two things. 1. Prevent the scroll behaviour on routes that has defined ignoreScrollBehavior on them to true or if a link has set the state with ignoreScrollBehavior to true. 2. Make sure we go to the top of the page if scrollToTop has been defined on the route or on the state of the link transition. Route: <Route path="about/" component={ About } ignoreScrollBehavior /> Link: <Link to={{ pathname: '/some/path', state: { scrollToTop: true } }} />Foo</Link> */ shouldUpdateScroll: (prevRouterProps, { routes, location }) => { if ( routes.some(route => route.ignoreScrollBehavior) || location.state && location.state.ignoreScrollBehavior ) { return false; } if ( routes.some(route => route.scrollToTop) || location.state && location.state.scrollToTop ) { return [0, 0]; } return true; }, }, };
src/svg-icons/notification/vibration.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationVibration = (props) => ( <SvgIcon {...props}> <path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/> </SvgIcon> ); NotificationVibration = pure(NotificationVibration); NotificationVibration.displayName = 'NotificationVibration'; NotificationVibration.muiName = 'SvgIcon'; export default NotificationVibration;
static/programming-tutorials-backup/src/pages/About.js
EdwardRees/EdwardRees.github.io
import React from 'react'; const About = () => ( <div> <h2>About</h2> </div> ); export { About };
client/reactComponents/Wall.js
iandeboisblanc/wikiMuseumVR
import React from 'react'; class Wall extends React.Component { constructor(props) { super(props); this.position = props.position || '0 0 0'; this.rotation = props.rotation || '0 0 0'; this.height = Number(props.height) || 4; this.width = Number(props.width) || 5; this.wallThickness = Number(props.wallThickness) || 0.3; this.trimHeight = props.trimHeight === undefined ? 0.2 : Number(props.trimHeight); this.trimThickness = props.trimThickness === undefined ? 0.05 : Number(props.trimThickness); this.material = props.material || 'color:grey;'; this.trimMaterial = props.trimMaterial || this.material; } render () { if(this.trimThickness && this.trimHeight) { return ( <a-entity className='wallEntity' position='0 0 0' rotation='0 0 0'> <a-box className='wall' static-body position={this.position} rotation={this.rotation} depth={this.wallThickness} width={this.width} height={this.height} material={this.material}> <a-box className='wallTrim' position={`0 ${(this.trimHeight - this.height)/2} ${(this.wallThickness + this.trimThickness)/2}`} rotation='0 0 0' depth={this.trimThickness} width={this.width} height={this.trimHeight} material={this.trimMaterial}/> </a-box> </a-entity> ) } else { // to avoid rendering trim if none is wanted return ( <a-entity className='wallEntity' position='0 0 0' rotation='0 0 0'> <a-box className='wall' static-body position={this.position} rotation={this.rotation} depth={this.wallThickness} width={this.width} height={this.height} material={this.material} /> </a-entity> ) } } } module.exports = Wall;
src/components/app.js
AikChun/react-redux-testing
import React, { Component } from 'react'; import CommentBox from './comment_box'; import CommentList from './comment_list'; export default class App extends Component { render() { return ( <div> <CommentBox /> <CommentList /> </div> ); } }
library/src/pivotal-ui-react/checkbox-dropdown/checkbox-dropdown.js
sjolicoeur/pivotal-ui
import React from 'react'; import PropTypes from 'prop-types'; import {Dropdown, DropdownItem} from 'pui-react-dropdowns'; // import {default as mixin} from 'pui-react-mixins'; import {Checkbox} from 'pui-react-checkbox'; function doNothing() { }; export class CheckboxDropdown extends React.Component { constructor(props, context) { super(props, context); const {labels} = this.props; const options = labels.reduce((result, item) => { result[item] = true; return result; }, {}); this.state = {open: false, options}; } componentDidMount() { const {onChange} = this.props; const {options} = this.state; onChange(options); } // static propTypes = { buttonAriaLabel: PropTypes.string, buttonClassName: PropTypes.string, flat: PropTypes.bool, labelAriaLabel: PropTypes.string, onChange: PropTypes.func, size: PropTypes.oneOf(['normal', 'large', 'small']), split: PropTypes.bool, labels: PropTypes.array }; // static defaultProps = { onChange: doNothing, size: 'normal' }; getTitle() { if (this.allSelected()) return 'ALL'; const {options} = this.state; const selectedOptions = Object.keys(options).filter(key => options[key]).join(', '); if (!selectedOptions) return 'NONE'; return selectedOptions; } allSelected() { const {options} = this.state; return Object.values(options).every(val => val); } toggleAll(e) { e.stopPropagation(); const {options} = this.state; const toggledVal = !this.allSelected(); Object.keys(options).forEach(key => options[key] = toggledVal); this.setState({options}); const {onChange} = this.props; onChange(options); } toggleOption(e, key) { e.stopPropagation(); const {options} = this.state; options[key] = !options[key]; this.setState({options}); const {onChange} = this.props; onChange(options); } render() { const {labels, onChange, ...dropDownProps} = this.props; const {options} = this.state; const dropdownItems = labels.map((label) => { return ( <DropdownItem className="checkbox-dropdown-item" key={label} onSelect={e => this.toggleOption(e, label)}> <Checkbox className="checkbox-dropdown-item-checkbox man" checked={options[label]} onChange={doNothing} onClick={e => this.toggleOption(e, label)} label={label}/> </DropdownItem> ); }); const checkBoxAllProps = { className: 'all-checkbox man', checked: this.allSelected(), onClick: e => this.toggleAll(e), onChange: doNothing, label: 'ALL' }; const title = <span className="type-ellipsis">{this.getTitle()}</span>; return (<Dropdown {...dropDownProps} {...{title}}> <DropdownItem className="checkbox-dropdown-item show-all" onSelect={e => this.toggleAll(e)} checked={this.allSelected()}> <Checkbox {...checkBoxAllProps}/> </DropdownItem> {dropdownItems} </Dropdown>); } }
vendor/tacit/src/styles/theme-decorator.js
vanHeemstraSystems/components
import React from 'react'; export default (customTheme) => { return function(Component) { return React.createClass({ childContextTypes: { muiTheme: React.PropTypes.object, }, getChildContext() { return { muiTheme: customTheme, }; }, render() { return React.createElement(Component, this.props); }, }); }; };
src/svg-icons/notification/phone-paused.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhonePaused = (props) => ( <SvgIcon {...props}> <path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/> </SvgIcon> ); NotificationPhonePaused = pure(NotificationPhonePaused); NotificationPhonePaused.displayName = 'NotificationPhonePaused'; export default NotificationPhonePaused;
src/svg-icons/maps/local-florist.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalFlorist = (props) => ( <SvgIcon {...props}> <path d="M12 22c4.97 0 9-4.03 9-9-4.97 0-9 4.03-9 9zM5.6 10.25c0 1.38 1.12 2.5 2.5 2.5.53 0 1.01-.16 1.42-.44l-.02.19c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5l-.02-.19c.4.28.89.44 1.42.44 1.38 0 2.5-1.12 2.5-2.5 0-1-.59-1.85-1.43-2.25.84-.4 1.43-1.25 1.43-2.25 0-1.38-1.12-2.5-2.5-2.5-.53 0-1.01.16-1.42.44l.02-.19C14.5 2.12 13.38 1 12 1S9.5 2.12 9.5 3.5l.02.19c-.4-.28-.89-.44-1.42-.44-1.38 0-2.5 1.12-2.5 2.5 0 1 .59 1.85 1.43 2.25-.84.4-1.43 1.25-1.43 2.25zM12 5.5c1.38 0 2.5 1.12 2.5 2.5s-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8s1.12-2.5 2.5-2.5zM3 13c0 4.97 4.03 9 9 9 0-4.97-4.03-9-9-9z"/> </SvgIcon> ); MapsLocalFlorist = pure(MapsLocalFlorist); MapsLocalFlorist.displayName = 'MapsLocalFlorist'; MapsLocalFlorist.muiName = 'SvgIcon'; export default MapsLocalFlorist;
src/routes/SingleEvent/components/SignupButton/SignupButton.js
athenekilta/ilmomasiina
import React from 'react'; import _ from 'lodash'; import signupState from '../../../../utils/signupStateText'; import './SignupButton.scss'; export class SignupButton extends React.Component { render() { const isOpen = this.props.isOpen; return ( <p> <button disabled={!isOpen} className="btn btn-default btn-block btn-whitespace-normal" onClick={() => (isOpen ? this.props.openForm() : {})} > {this.props.isOnly ? 'Ilmoittaudu nyt' : `Ilmoittaudu: ${this.props.title}`} </button> </p> ); } } SignupButton.propTypes = { openForm: React.PropTypes.func.isRequired, title: React.PropTypes.string.isRequired, isOpen: React.PropTypes.bool.isRequired, eventTime: React.PropTypes.string, isOnly: React.PropTypes.bool.isRequired, }; export default SignupButton;
packages/lore-mixins-infinite-scrolling/src/InfiniteScrolling.js
lore/lore
/* eslint no-undef: "off" */ /* eslint no-unused-vars: "off" */ import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; export default function(options = {}) { const propName = options.propName; const modelName = options.modelName; if (!propName) { throw new Error('propName is required'); } if (!modelName) { throw new Error('modelName is required'); } return { contextTypes: { store: PropTypes.object.isRequired }, getInitialState: function () { return { pages: [ this.props[propName] ] }; }, componentWillReceiveProps: function (nextProps) { const storeState = this.context.store.getState(); const pages = this.state.pages; // Whenever the component re-renders, we need to rebuild our collection of pages // by fetching them back out of the Store. If we don't do this, our state data // will always be stale - we'll never know when data finishes being fetched, and // in the cases where some of the data is being modified, such as being updated // or deleted, we won't get a change to react to those changes and inform the user. let nextPages = pages.map(function (page) { const query = JSON.stringify(page.query); return storeState[modelName].find[query]; }); const currentQuery = JSON.stringify(this.props[propName].query.where); const nextQuery = JSON.stringify(nextProps[propName].query.where); if (currentQuery !== nextQuery) { nextPages = [ nextProps[propName] ]; } this.setState({ pages: nextPages }); }, onLoadMore: function () { const storeState = this.context.store.getState(); const pages = this.state.pages; const lastPage = pages[pages.length - 1]; const nextPageNumber = Number(lastPage.query.pagination.page) + 1; const query = lastPage.query; // Build the next page's query from the previous page. The only // thing we're changing is the page of data we want to fetch const nextQuery = { where: query.where, pagination: _.defaults({ page: nextPageNumber }, query.pagination) }; // See if the next page has already been fetched, and used the cached page // if available let nextPage = storeState[modelName].find[JSON.stringify(nextQuery)]; if (!nextPage) { // The 'find' action has a slightly different interface than the 'getState' call // in 'lore.connect'. When calling the 'find' action directly, you need to pass // in the 'where' clause and the 'pagination' information as different arguments, // like 'lore.actions.tweet.find(where, pagination)' nextPage = lore.actions[modelName].find(nextQuery.where, nextQuery.pagination).payload; } pages.push(nextPage); this.setState({ pages: pages }); } }; }
src/routes.js
avantcontra/react-redux-custom-starter
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from './redux/actions/auth'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replace, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replace('/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
es/components/toolbar/toolbar-save-button.js
dearkaran/react-planner
import React from 'react'; import PropTypes from 'prop-types'; import IconSave from 'react-icons/lib/fa/floppy-o'; import ToolbarButton from './toolbar-button'; import { browserDownload } from '../../utils/browser'; import { unselectAll } from '../../utils/layer-operations'; export default function ToolbarSaveButton(_ref, _ref2) { var state = _ref.state; var translator = _ref2.translator, projectActions = _ref2.projectActions; var saveProjectToFile = function saveProjectToFile(event) { event.preventDefault(); var scene = state.get('scene').update('layers', function (layers) { return layers.map(function (layer) { return unselectAll(layer); }); }).toJS(); browserDownload(scene); }; return React.createElement( ToolbarButton, { active: false, tooltip: translator.t("Save project"), onClick: saveProjectToFile }, React.createElement(IconSave, null) ); } ToolbarSaveButton.propTypes = { state: PropTypes.object.isRequired }; ToolbarSaveButton.contextTypes = { projectActions: PropTypes.object.isRequired, translator: PropTypes.object.isRequired };
src/svg-icons/navigation/chevron-left.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationChevronLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); NavigationChevronLeft = pure(NavigationChevronLeft); NavigationChevronLeft.displayName = 'NavigationChevronLeft'; NavigationChevronLeft.muiName = 'SvgIcon'; export default NavigationChevronLeft;
react/Radio/Radio.demo.js
seekinternational/seek-asia-style-guide
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Radio from './Radio'; import Text from '../Text/Text'; import * as sketch from './Radio.sketch'; import demoStyles from './Radio.demo.less'; import classnames from 'classnames'; class RadioContainer extends Component { static propTypes = { component: PropTypes.func.isRequired, componentProps: PropTypes.object.isRequired }; constructor() { super(); this.state = { value: '' }; } handleYes = () => { this.setState({ value: 'Yes' }); }; handleNo = () => { this.setState({ value: 'No' }); }; handleMaybe = () => { this.setState({ value: 'Maybe' }); }; render() { const { component: DemoComponent, componentProps } = this.props; const { value } = this.state; const classNames = classnames({ [demoStyles.root]: true, // eslint-disable-line [demoStyles.fullWidth]: componentProps.fullWidth }); return ( <div className={classNames}> <Text shouting>Still in role</Text> <DemoComponent {...componentProps} id="Yes" label="Yes" checked={value === 'Yes'} onChange={this.handleYes} /> <DemoComponent {...componentProps} id="No" label="No" checked={value === 'No'} onChange={this.handleNo} /> <DemoComponent {...componentProps} id="Maybe" label="Maybe" checked={value === 'Maybe'} onChange={this.handleMaybe} /> </div> ); } } export default { route: '/radio', title: 'Radio', category: 'Form', component: Radio, container: RadioContainer, sketch, initialProps: { name: 'stillInRole', // Documentation only: id: 'myRadio', checked: false, onChange: () => {} }, options: [ { label: 'States', type: 'checklist', states: [ { label: 'Full width', transformProps: props => ({ ...props, fullWidth: true }) } ] }, { label: 'Disabled', type: 'checklist', states: [ { label: 'Disabled', transformProps: props => ({ ...props, disabled: true }) } ] }, { label: 'Icon style', type: 'radio', states: [ { label: 'Icon style', transformProps: props => ({ ...props }) }, { label: 'Tick', transformProps: props => ({ ...props, iconType: 'tick' }) } ] }, { label: 'Radio position', type: 'radio', states: [ { label: 'Icon at front', transformProps: props => ({ ...props }) }, { label: 'Icon at back', transformProps: props => ({ ...props, rtl: true }) } ] } ] };
app/components/browserwarning/browserwarning.js
tidepool-org/blip
/** * Copyright (c) 2016, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { translate, Trans } from 'react-i18next'; import utils from '../../core/utils'; const COPY_STATUS_NULL = 0; const COPY_STATUS_SUCCESS = 10; const COPY_STATUS_FAIL = 20; const playstoreImageUrl = require('./images/google-play-badge.png'); const appstoreImageUrl = require('./images/appstore-badge.svg'); export default translate()(class BrowserWarning extends Component { static propTypes = { trackMetric: PropTypes.func.isRequired }; constructor(props) { super(props); this.state = { copyStatus: COPY_STATUS_NULL }; } componentDidMount() { this.props.trackMetric('Chrome Required - Screen Displayed'); } render() { const { t } = this.props; var self = this; var downloadCopy = <div className="browser-warning-chrome-image"></div>; var copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>{t('Copy this page\’s URL')}</button>; var handleClickDownload = function() { self.props.trackMetric('Clicked Download Chrome'); }; var handleClickiOS = function() { self.props.trackMetric('No Data - Clicked iOS', {}, () => { window.location.assign('https://itunes.apple.com/us/app/tidepool-mobile/id1026395200'); }); }; var handleClickAndroid = function() { self.props.trackMetric('No Data - Clicked Android', {}, () => { window.location.assign('https://play.google.com/store/apps/details?id=io.tidepool.urchin'); }); }; if (this.state.copyStatus === COPY_STATUS_SUCCESS) { self.props.trackMetric('Clicked Copy blip.tidepool.org, automatically copied'); copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>{t('Copied!')}</button> } else if (this.state.copyStatus === COPY_STATUS_FAIL) { self.props.trackMetric('Clicked Copy blip.tidepool.org, manually copied'); copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>{t('Please press Ctrl + C now')}</button> } if (!utils.isMobile()) { downloadCopy = (<div> <a href="https://www.google.com/intl/en/chrome/browser/desktop/index.html" onClick={handleClickDownload} target="_blank" rel="noreferrer noopener"> <div className="browser-warning-chrome-image"></div> </a> {copyButton} <Trans className="browser-warning-text" i18nKey="html.browser-warning-text"> and paste it into <span className="dark-text">Chrome</span> to see this page on <span className="browser-warning-nowrap">your desktop computer.</span> </Trans> <div className="blip-link-text-wrap"> <input type="text" className="blip-link-text" value="app.tidepool.org" readOnly={true}></input> </div> </div>); } return ( <div className="browser-warning js-terms"> <div className="browser-warning-content browser-warning-box"> <h1 className="browser-warning-title"> {t('Tidepool Web works with Chrome on ')} <span className="browser-warning-nowrap">{t('Mac or Windows.')}</span> </h1> {downloadCopy} <div className="browser-warning-mobile"> <div className="browser-warning-mobile-message"> {t('Download Tidepool Mobile for iOS or Android to add notes and see your data on the go:')} </div> <div className="browser-warning-mobile-appstore-container"> <img alt='Download on the App Store' src={appstoreImageUrl} className="appstore-badge" onClick={handleClickiOS}/> <img alt='Get it on Google Play' src={playstoreImageUrl} className="playstore-badge" onClick={handleClickAndroid}/> </div> </div> </div> </div> ); } copyText() { var copyText = document.querySelector('.blip-link-text'); copyText.select(); try { var copyCmd = document.execCommand('copy'); this.setState( { copyStatus: (copyCmd) ? COPY_STATUS_SUCCESS : COPY_STATUS_FAIL }); } catch (err) { console.log('Unable to copy - unsupported browser'); this.setState({ copyStatus: COPY_STATUS_FAIL }); } } });
components/animals/krajtaKobercova.adult.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/krajtaKobercova/01.jpg'), require('../../images/animals/krajtaKobercova/02.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/krajtaKobercova/01-thumb.jpg'), require('../../images/animals/krajtaKobercova/02-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Hezký den! </AnimalText> <AnimalText> Jsme krajta a krajťák kobercoví, anglicky nám říkají <Text style={styles.italic}>carpet python</Text>. Je tomu tak nikoliv proto, že se z&nbsp;nás koberce vyrábějí, nýbrž proto, že svým výrazným zbarvením se žlutými a černými skvrnami připomínáme vzory tkaných orientálních koberců. </AnimalText> <AnimalText> Náš druh, krajty diamantové, se dělí na šest různých poddruhů. Každý z&nbsp;nich má specifické zbarvení podle toho, kde žije. My dva patříme k poddruhu <Text style={styles.italic}>Morelia spilotes variegata</Text>, tedy k&nbsp;již zmíněným krajtám kobercovým, a do brněnské zoo jsme se přistěhovali v&nbsp;únoru&nbsp;2014 ze Dvora Králové. </AnimalText> <AnimalText> Ve volné přírodě je naším domovem Austrálie, kde jsme mezi krajtami nejrozšířenějším druhem, a také Nová Guinea. Jsme přizpůsobivé a žijeme na různých místech, můžete nás najít jak v&nbsp;deštných tropických pralesech, tak v&nbsp;suchých křovinách. Tam se nejčastěji skrýváme v&nbsp;opuštěných norách či ve skalních rozsedlinách. V&nbsp;deštných lesích jsou naším oblíbeným úkrytem například díry pod kmeny, je možné nás najít i&nbsp;v&nbsp;rozsochách větví. </AnimalText> <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Dorůstáme do délky až 4&nbsp;metrů. I&nbsp;přes svou velikost však máme docela mírnou povahu. Aktivní jsme obvykle v&nbsp;noci, většinu dne trávíme stočeny v&nbsp;korunách stromů či na zemi, kde se podle teploty okolí buď sluníme, nebo jsme schované ve stínu. Naše kousnutí není jedovaté, svou kořist usmrcujeme škrcením. Živíme se převážně hlodavci, ale i&nbsp;králíky a menšími vačnatci. Možná vás překvapí, že nás proto v&nbsp;Austrálii tolerují ve svých domech jako postrach myší a potkanů. Tady v Evropě dáváte před hady přednost spíše kočkám, že? </AnimalText> <AnimalText> Když se rozhodneme založit rodinu, samička snese 25–30 vajec na dobře krytém místě a stará se o ně 75–80&nbsp;dní, aby byla hezky v&nbsp;teple. Když je potřeba, zahřívají samice svá vejce chvěním, aby měla optimální teplotu, která se pohybuje kolem 30&nbsp;°C. Když se hádě vyklube, má asi 39&nbsp;cm, není to tedy žádné vykraj(t)ovátko. </AnimalText> <AnimalText> Díky za návštěvu a na viděnou! </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
server/sonar-web/src/main/js/apps/project-admin/deletion/Form.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import ConfirmationModal from './ConfirmationModal'; import { translate } from '../../../helpers/l10n'; export default class Form extends React.Component { static propTypes = { component: React.PropTypes.object.isRequired }; handleDelete (e) { e.preventDefault(); new ConfirmationModal({ project: this.props.component }) .on('done', () => { window.location = window.baseUrl + '/'; }) .render(); } render () { return ( <form onSubmit={this.handleDelete.bind(this)}> <button id="delete-project" className="button-red"> {translate('delete')} </button> </form> ); } }
examples/layer-list/app.js
jjmulenex/sdk
/** Demo of layer list in an SDK map. * * Contains a Map and demonstrates adding many types of layers * And a layer list component to manage the layers * */ import {createStore, combineReducers} from 'redux'; import React from 'react'; import ReactDOM from 'react-dom'; import {DragSource, DropTarget} from 'react-dnd'; import {types, layerListItemSource, layerListItemTarget, collect, collectDrop} from '@boundlessgeo/sdk/components/layer-list-item'; import SdkMap from '@boundlessgeo/sdk/components/map'; import SdkZoomControl from '@boundlessgeo/sdk/components/map/zoom-control'; import SdkMapReducer from '@boundlessgeo/sdk/reducers/map'; import * as mapActions from '@boundlessgeo/sdk/actions/map'; import SdkLayerList from '@boundlessgeo/sdk/components/layer-list'; import SdkLayerListItem from '@boundlessgeo/sdk/components/layer-list-item'; import {Provider} from 'react-redux'; /* eslint-disable no-underscore-dangle */ const store = createStore(combineReducers({ map: SdkMapReducer, }), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); class LayerListItem extends SdkLayerListItem { render() { const layer = this.props.layer; const checkbox = this.getVisibilityControl(layer); const moveButtons = ( <span> <button className="sdk-btn" onClick={() => { this.moveLayerUp(); }}> { this.props.labels.up } </button> <button className="sdk-btn" onClick={() => { this.moveLayerDown(); }}> { this.props.labels.down } </button> <button className="sdk-btn" onClick={() => { this.removeLayer(); }}> { this.props.labels.remove } </button> </span> ); return this.props.connectDragSource(this.props.connectDropTarget(( <li className="layer"> <span className="checkbox">{checkbox}</span> <span className="name">{layer.id}</span> <span className="btn-container">{moveButtons}</span> </li> ))); } } LayerListItem.defaultProps = { labels: { up: 'Move up', down: 'Move down', remove: 'Remove layer', }, }; LayerListItem = DropTarget(types, layerListItemTarget, collectDrop)(DragSource(types, layerListItemSource, collect)(LayerListItem)); function main() { // Start with a reasonable global view of hte map. store.dispatch(mapActions.setView([-93, 45], 2)); store.dispatch(mapActions.updateMetadata({ 'mapbox:groups': { base: { name: 'Base Maps', }, }, })); // Background layers change the background color of // the map. They are not attached to a source. store.dispatch(mapActions.addLayer({ id: 'background', type: 'background', paint: { 'background-color': '#eee', }, metadata: { 'bnd:hide-layerlist': true, }, })); // add the OSM source store.dispatch(mapActions.addOsmSource('osm')); // and an OSM layer. // Raster layers need not have any paint styles. store.dispatch(mapActions.addLayer({ id: 'osm', source: 'osm', type: 'raster', metadata: { 'mapbox:group': 'base' } })); // add carto source store.dispatch(mapActions.addSource('cartolight', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', type: 'raster', tileSize: 256, tiles: [ 'http://s.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', ], })); // add an carto light layer store.dispatch(mapActions.addLayer({ metadata: { 'mapbox:group': 'base', 'bnd:title': 'CartoDB light', }, type: 'raster', layout: { visibility: 'none', }, id: 'cartolight', source: 'cartolight', })); // 'geojson' sources allow rendering a vector layer // with all the features stored as GeoJSON. "data" can // be an individual Feature or a FeatureCollection. store.dispatch(mapActions.addSource('dynamic-source', {type: 'geojson'})); store.dispatch(mapActions.addLayer({ id: 'dynamic-layer', type: 'circle', source: 'dynamic-source', paint: { 'circle-radius': 5, 'circle-color': '#552211', 'circle-stroke-color': '#00ff11', }, })); // This is called by the onClick, keeping the onClick HTML clean const runFetchGeoJSON = () => { store.dispatch(mapActions.addSource('dynamic-source', {type: 'geojson', data: './data/airports.json'})); }; runFetchGeoJSON(); // 'geojson' sources allow rendering a vector layer // with all the features stored as GeoJSON. "data" can // be an individual Feature or a FeatureCollection. store.dispatch(mapActions.addSource('points', { type: 'geojson', clusterRadius: 50, data: { type: 'FeatureCollection', features: [], }, })); // Show the unclustered points in a different colour. store.dispatch(mapActions.addLayer({ id: 'random-points', source: 'points', type: 'circle', paint: { 'circle-radius': 3, 'circle-color': '#756bb1', 'circle-stroke-color': '#756bb1', }, filter: ['!has', 'point_count'], })); // Add a random point to the map const addRandomPoints = (nPoints = 10) => { // loop over adding a point to the map. for (let i = 0; i < nPoints; i++) { // the feature is a normal GeoJSON feature definition, // 'points' referes to the SOURCE which will get the feature. store.dispatch(mapActions.addFeatures('points', [{ type: 'Feature', properties: { title: 'Random Point', isRandom: true, }, geometry: { type: 'Point', // this generates a point somewhere on the planet, unbounded. coordinates: [(Math.random() * 360) - 180, (Math.random() * 180) - 90], }, }])); } }; // add 200 random points to the map on startup addRandomPoints(200); // add the wms source store.dispatch(mapActions.addSource('states', { type: 'raster', tileSize: 256, tiles: ['https://demo.boundlessgeo.com/geoserver/usa/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&SRS=EPSG:900913&LAYERS=topp:states&STYLES=&WIDTH=256&HEIGHT=256&BBOX={bbox-epsg-3857}'], })); // add the wms layer store.dispatch(mapActions.addLayer({ id: 'states', source: 'states', type: 'raster', })); // place the map on the page. ReactDOM.render(<Provider store={store}> <SdkMap> <SdkZoomControl /> </SdkMap> </Provider>, document.getElementById('map')); // add some buttons to demo some actions. ReactDOM.render(( <div> <h3>Try it out</h3> <div className="sdk-layerlist"> <Provider store={store}> <SdkLayerList layerClass={LayerListItem} /> </Provider> </div> </div> ), document.getElementById('controls')); } main();
app/components/MessageButton/index.js
MameeV/suzette
/** * * MessageButton * */ import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'Material-ui/TextField'; class MessageButton extends React.PureComponent { constructor(props){ super(props); this.state={ contactOpen: false, message: "", email: "" } } handleOpen = () => { this.setState({ contactOpen: true }) } handleClose = () => { this.setState({ contactOpen: false }) } handleMessage = (event) => { this.setState({ message:event.target.value }) } handleEmail = (event) => { this.setState({ email:event.target.value }) } contact = () => { var data = new FormData(); data.append("message",this.state.message); data.append("email",this.state.email); fetch("http://mrsverbeck.com/api/contact",{ method:"post", body:data }) .then(function(response){ return response.json(); }) .then(function(json){ if(json.error){ alert(json.error); } else if(json.success){ alert(json.success); } }) } render() { const buttonStyle={ fontFamily: "Raleway", fontWeight: "Bold", fontStyle: "Italic", fontSize: "100%", color: "#B4938C" } const footerStyle={ background: "#74D1EA", position: "fixed", bottom: "40px", right: "10px", padding: "15px", borderRadius: "50px", } const messageBoxStyle={ fontFamily: "Raleway", color: "3E262A" } const actions = [ <FlatButton label="Cancel" onTouchTap={this.handleClose}/>, <FlatButton label="Submit" onTouchTap={()=>this.contact()}/> ] return ( <div> <footer style={footerStyle}> <FlatButton style={buttonStyle} label="Message Me!" onTouchTap={this.handleOpen}/> </footer> <Dialog titleStyle={messageBoxStyle} title="Send me a message. I look forward to hearing from you." actions={actions} open={this.state.contactOpen}> <br/> <TextField onChange={this.handleEmail} hintText="Enter your eMail address here."/> <br/> <TextField onChange={this.handleMessage} hintText="Enter your message here!"/> </Dialog> </div> ); } } export default MessageButton;
test/specs/elements/Loader/Loader-test.js
vageeshb/Semantic-UI-React
import faker from 'faker' import React from 'react' import Loader from 'src/elements/Loader/Loader' import { SUI } from 'src/lib' import * as common from 'test/specs/commonTests' describe('Loader', () => { common.isConformant(Loader) common.hasUIClassName(Loader) common.rendersChildren(Loader) common.propKeyOnlyToClassName(Loader, 'active') common.propKeyOnlyToClassName(Loader, 'disabled') common.propKeyOnlyToClassName(Loader, 'indeterminate') common.propKeyOnlyToClassName(Loader, 'inverted') common.propKeyOrValueAndKeyToClassName(Loader, 'inline', ['centered']) common.propValueOnlyToClassName(Loader, 'size', SUI.SIZES) describe('content', () => { it('renders text', () => { const text = faker.hacker.phrase() shallow(<Loader content={text} />) .should.contain.text(text) }) }) describe('text (class)', () => { it('omitted by default', () => { shallow(<Loader />) .should.not.have.className('text') }) it('add class when has children', () => { const text = faker.hacker.phrase() shallow(<Loader>{text}</Loader>) .should.have.className('text') }) it('add class when has content prop', () => { const text = faker.hacker.phrase() shallow(<Loader content={text} />) .should.have.className('text') }) }) })
src/templates/tags.js
JoshBarr/joshbarr.github.io
import React from 'react' import SEO from '../components/seo' import Layout from '../components/layout' import { Link, graphql } from 'gatsby' import PostListing from '../components/PostListing' export default function Template({ pageContext, data, // this prop will be injected by the GraphQL query we'll write in a bit }) { const { tag } = pageContext const { edges, totalCount } = data.allMarkdownRemark const tagHeader = `${totalCount} post${ totalCount === 1 ? '' : 's' } tagged with "${tag}"` return ( <Layout> <SEO title={tag} /> <div className="container generic-page"> <h1 className="section-top">{tag}</h1> <ul className="list-inline space--large"> <li>{tagHeader}</li> <li> <Link to="/tags">See all tags</Link> </li> </ul> <div className="article"> {edges.map(({ node }) => { const { path, title } = node.frontmatter return <PostListing key={path} post={node} /> })} </div> </div> </Layout> ) } export const pageQuery = graphql` query($tag: String) { allMarkdownRemark( limit: 2000 sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { tags: { in: [$tag] } } } ) { totalCount edges { node { frontmatter { path date(formatString: "MMMM DD, YYYY") title blurb tags cover_image { childImageSharp { fluid(maxWidth: 450) { ...GatsbyImageSharpFluid } } } } } } } } `
src/svg-icons/content/weekend.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentWeekend = (props) => ( <SvgIcon {...props}> <path d="M21 10c-1.1 0-2 .9-2 2v3H5v-3c0-1.1-.9-2-2-2s-2 .9-2 2v5c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-5c0-1.1-.9-2-2-2zm-3-5H6c-1.1 0-2 .9-2 2v2.15c1.16.41 2 1.51 2 2.82V14h12v-2.03c0-1.3.84-2.4 2-2.82V7c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ContentWeekend = pure(ContentWeekend); ContentWeekend.displayName = 'ContentWeekend'; ContentWeekend.muiName = 'SvgIcon'; export default ContentWeekend;
packages/babel-plugin-transform-react-pure-annotations/test/fixtures/react/cloneElement/input.js
babel/babel
import React from 'react'; React.cloneElement(React.createElement('div'));
app/javascript/mastodon/components/intersection_observer_article.js
codl/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import scheduleIdleTask from '../features/ui/util/schedule_idle_task'; import getRectFromEntry from '../features/ui/util/get_rect_from_entry'; import { is } from 'immutable'; // Diff these props in the "rendered" state const updateOnPropsForRendered = ['id', 'index', 'listLength']; // Diff these props in the "unrendered" state const updateOnPropsForUnrendered = ['id', 'index', 'listLength', 'cachedHeight']; export default class IntersectionObserverArticle extends React.Component { static propTypes = { intersectionObserverWrapper: PropTypes.object.isRequired, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), saveHeightKey: PropTypes.string, cachedHeight: PropTypes.number, onHeightChange: PropTypes.func, children: PropTypes.node, }; state = { isHidden: false, // set to true in requestIdleCallback to trigger un-render } shouldComponentUpdate (nextProps, nextState) { const isUnrendered = !this.state.isIntersecting && (this.state.isHidden || this.props.cachedHeight); const willBeUnrendered = !nextState.isIntersecting && (nextState.isHidden || nextProps.cachedHeight); if (!!isUnrendered !== !!willBeUnrendered) { // If we're going from rendered to unrendered (or vice versa) then update return true; } // Otherwise, diff based on props const propsToDiff = isUnrendered ? updateOnPropsForUnrendered : updateOnPropsForRendered; return !propsToDiff.every(prop => is(nextProps[prop], this.props[prop])); } componentDidMount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.observe( id, this.node, this.handleIntersection ); this.componentMounted = true; } componentWillUnmount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.unobserve(id, this.node); this.componentMounted = false; } handleIntersection = (entry) => { this.entry = entry; scheduleIdleTask(this.calculateHeight); this.setState(this.updateStateAfterIntersection); } updateStateAfterIntersection = (prevState) => { if (prevState.isIntersecting && !this.entry.isIntersecting) { scheduleIdleTask(this.hideIfNotIntersecting); } return { isIntersecting: this.entry.isIntersecting, isHidden: false, }; } calculateHeight = () => { const { onHeightChange, saveHeightKey, id } = this.props; // save the height of the fully-rendered element (this is expensive // on Chrome, where we need to fall back to getBoundingClientRect) this.height = getRectFromEntry(this.entry).height; if (onHeightChange && saveHeightKey) { onHeightChange(saveHeightKey, id, this.height); } } hideIfNotIntersecting = () => { if (!this.componentMounted) { return; } // When the browser gets a chance, test if we're still not intersecting, // and if so, set our isHidden to true to trigger an unrender. The point of // this is to save DOM nodes and avoid using up too much memory. // See: https://github.com/tootsuite/mastodon/issues/2900 this.setState((prevState) => ({ isHidden: !prevState.isIntersecting })); } handleRef = (node) => { this.node = node; } render () { const { children, id, index, listLength, cachedHeight } = this.props; const { isIntersecting, isHidden } = this.state; if (!isIntersecting && (isHidden || cachedHeight)) { return ( <article ref={this.handleRef} aria-posinset={index} aria-setsize={listLength} style={{ height: `${this.height || cachedHeight}px`, opacity: 0, overflow: 'hidden' }} data-id={id} tabIndex='0' > {children && React.cloneElement(children, { hidden: true })} </article> ); } return ( <article ref={this.handleRef} aria-posinset={index} aria-setsize={listLength} data-id={id} tabIndex='0'> {children && React.cloneElement(children, { hidden: false })} </article> ); } }
src/components/Account.js
chatch/stellarexplorer
import React from 'react' import Col from 'react-bootstrap/lib/Col' import Glyphicon from 'react-bootstrap/lib/Glyphicon' import Grid from 'react-bootstrap/lib/Grid' import Panel from 'react-bootstrap/lib/Panel' import Row from 'react-bootstrap/lib/Row' import Table from 'react-bootstrap/lib/Table' import Tab from 'react-bootstrap/lib/Tab' import Tabs from 'react-bootstrap/lib/Tabs' import {injectIntl, FormattedMessage} from 'react-intl' import {FederationServer, MuxedAccount, StrKey} from 'stellar-sdk' import has from 'lodash/has' import knownAccounts from '../data/known_accounts' import {isFederatedAddress, isMuxedAddress, isPublicKey} from '../lib/stellar/utils' import {base64Decode, handleFetchDataFailure, setTitle} from '../lib/utils' import {withServer} from './shared/HOCs' import {withSpinner} from './shared/Spinner' import {titleWithJSONButton} from './shared/TitleWithJSONButton' import AccountLink from './shared/AccountLink' import Asset from './shared/Asset' import ClipboardCopy from './shared/ClipboardCopy' import EffectTable from './EffectTable' import FormattedAmount from './shared/FormattedAmount' import Logo from './shared/Logo' import OperationTable from './OperationTable' import OfferTable from './OfferTable' import PaymentTable from './PaymentTable' import TradeTable from './TradeTable' import TransactionTable from './TransactionTableContainer' const NameValueTable = ({data, decodeValue = false}) => { if (!data || Object.keys(data).length === 0) return <div style={{marginTop: 20, marginBottom: 20}}>No Data</div> return ( <Table> <thead> <tr> <th> <FormattedMessage id="name" /> </th> <th> <FormattedMessage id="value" /> </th> </tr> </thead> <tbody> {Object.keys(data).map(key => ( <tr key={key}> <td>{key}</td> <td> {typeof data[key] === 'boolean' ? data[key].toString() : decodeValue ? base64Decode(data[key]) : data[key]} </td> </tr> ))} </tbody> </Table> ) } const balanceRow = bal => ( <tr key={bal.asset_code ? `${bal.asset_code}-${bal.asset_issuer}` : 'XLM'}> <td> <Asset type={bal.asset_type} code={bal.asset_code} issuer={bal.asset_issuer} /> </td> <td> <span className="break"> <FormattedAmount amount={bal.balance} /> </span> </td> <td> <span className="break">{bal.limit}</span> </td> </tr> ) const Balances = props => ( <Table> <thead> <tr> <th> <FormattedMessage id="asset" /> </th> <th> <FormattedMessage id="balance" /> </th> <th> <FormattedMessage id="limit" /> </th> </tr> </thead> <tbody>{props.balances.map(balanceRow)}</tbody> </Table> ) const Thresholds = ({thresholds}) => ( <Table> <thead> <tr> <th> <FormattedMessage id="threshold.low" /> </th> <th> <FormattedMessage id="threshold.medium" /> </th> <th> <FormattedMessage id="threshold.high" /> </th> </tr> </thead> <tbody> <tr> <td>{thresholds.low_threshold}</td> <td>{thresholds.med_threshold}</td> <td>{thresholds.high_threshold}</td> </tr> </tbody> </Table> ) const Signers = props => ( <Table> <thead> <tr> <th> <FormattedMessage id="key" /> </th> <th> <FormattedMessage id="weight" /> </th> <th> <FormattedMessage id="type" /> </th> </tr> </thead> <tbody> {props.signers.map(signer => ( <tr key={signer.key}> <td> {signer.type === 'ed25519_public_key' && ( <AccountLink account={signer.key} /> )} {signer.type === 'sha256_hash' && StrKey.decodeSha256Hash(signer.key).toString('hex')} {signer.type === 'preauth_tx' && StrKey.decodePreAuthTx(signer.key).toString('hex')} </td> <td>{signer.weight}</td> <td>{signer.type}</td> </tr> ))} </tbody> </Table> ) const MuxedAccountInfoPanel = ({ address, }) => { return ( <Panel> <Glyphicon glyph="info-sign" onClick={this.handleClick} /> &nbsp; NOTE: This view shows the base account of the multiplexed account &nbsp; <span style={{color: 'white', overflowWrap: 'break-word'}}> {address} </span> </Panel> ) } const Flags = ({flags}) => <NameValueTable data={flags} /> const Data = ({data}) => <NameValueTable data={data} decodeValue /> const AccountSummaryPanel = ({ account: a, accountUrl, federatedAddress, formatMessageFn, knownAccounts, }) => { setTitle(`Account ${a.id}`) const header = titleWithJSONButton( formatMessageFn({id: 'account'}), accountUrl ) return ( <Panel header={header}> <Grid style={{paddingLeft: 0}}> <Row> <Col md={10}> <Row> <Col md={3}> <FormattedMessage id="key.public" />: </Col> <Col md={9}> <span className="break" style={{color: 'white'}}>{a.id}</span> <ClipboardCopy text={a.id} /> </Col> </Row> {federatedAddress && ( <Row> <Col md={3}> <FormattedMessage id="stellar.address" />: </Col> <Col md={9}>{federatedAddress}</Col> </Row> )} <Row> <Col md={3}> <FormattedMessage id="home.domain" />: </Col> <Col md={9}> <a href={`https://${a.home_domain}`} target="_blank"> {a.home_domain} </a> </Col> </Row> <Row> <Col md={3}> <FormattedMessage id="subentry.count" />: </Col> <Col md={9}>{a.subentry_count}</Col> </Row> </Col> {has(knownAccounts, a.id) && knownAccounts[a.id].logo && ( <Col md={2}> <div style={{marginBottom: 10}}> <Logo type={knownAccounts[a.id].type} name={knownAccounts[a.id].logo} /> </div> </Col> )} </Row> </Grid> </Panel> ) } class Account extends React.Component { state = { key: 'balances', renderEffects: false, } constructor(props, context) { super(props, context) this.handleURIHash = this.handleURIHash.bind(this) this.handleSelect = this.handleSelect.bind(this) this.setNewState = this.setNewState.bind(this) } componentDidMount() { this.handleURIHash() } componentWillReceiveProps(nextProps) { this.handleURIHash() } setNewState(tabKey) { const newState = {key: tabKey} if (tabKey === 'effects') newState.renderEffects = true this.setState(newState) } handleURIHash() { if (has(window.location, 'hash') && window.location.hash.length > 1) { const tab = window.location.hash.substring(1) // string after '#' this.setNewState(tab) } } handleSelect(key) { window.location.hash = `#${key}` this.setNewState(key) } render() { const {formatMessage} = this.props.intl const a = this.props.account return ( <Grid> {this.props.muxedAddress && <Row> <MuxedAccountInfoPanel address={this.props.muxedAddress}/> </Row> } <Row> <AccountSummaryPanel account={a} accountUrl={this.props.urlFn(a.id)} federatedAddress={this.props.federatedAddress} formatMessageFn={formatMessage} knownAccounts={knownAccounts} /> </Row> <Row> <Tabs id="account-tabs" activeKey={this.state.key} onSelect={this.handleSelect} style={{border: '1px solid #ddd', borderRadius: 4}} > <Tab eventKey="balances" title={formatMessage({id: 'balances'})}> <Balances balances={a.balances} /> </Tab> <Tab eventKey="payments" title={formatMessage({id: 'payments'})}> <PaymentTable key={a.id} account={a.id} compact={false} limit={20} usePaging /> </Tab> <Tab eventKey="offers" title={formatMessage({id: 'offers'})}> <OfferTable key={a.id} account={a.id} compact={false} limit={20} showSeller={false} usePaging /> </Tab> <Tab eventKey="trades" title={formatMessage({id: 'trades'})}> <TradeTable key={a.id} account={a.id} limit={20} usePaging /> </Tab> <Tab eventKey="effects" title={formatMessage({id: 'effects'})}> {// OPTIMISATION: render on focus only as it hits the server for every effect this.state.renderEffects === true && ( <EffectTable key={a.id} account={a.id} limit={20} showAccount={false} usePaging /> )} </Tab> <Tab eventKey="operations" title={formatMessage({id: 'operations'})} > <OperationTable key={a.id} account={a.id} compact={false} limit={20} usePaging /> </Tab> <Tab eventKey="transactions" title={formatMessage({id: 'transactions'})} > <TransactionTable key={a.id} account={a.id} compact={false} limit={20} showSource={false} usePaging /> </Tab> <Tab eventKey="signing" title={formatMessage({id: 'signing'})}> <Row> <Col md={7}> <Signers signers={a.signers} /> </Col> <Col md={3} mdOffset={1} style={{border: '1px solid white', marginTop: 30}} > <h4> <FormattedMessage id="thresholds" /> </h4> <Thresholds thresholds={a.thresholds} /> </Col> </Row> </Tab> <Tab eventKey="flags" title={formatMessage({id: 'flags'})}> <Flags flags={a.flags} /> </Tab> <Tab eventKey="data" title={formatMessage({id: 'data'})}> <Data data={a.data_attr} /> </Tab> </Tabs> </Row> </Grid> ) } } const AccountWithSpinner = withSpinner()(Account) class AccountContainer extends React.Component { state = { isLoading: true, account: null, federatedAddress: null, muxedAddress: null, } componentDidMount() { this.loadAccount(this.props.match.params.id) } componentWillReceiveProps(nextProps) { this.loadAccount(nextProps.match.params.id) } loadAccount(accountId) { if (isPublicKey(accountId)) { this.loadAccountByKey(accountId) } else if (isFederatedAddress(accountId)) { this.loadAccountByFederatedAddress(accountId) } else if (isMuxedAddress(accountId)) { this.loadAccountByMuxedAddress(accountId) } else { handleFetchDataFailure(accountId)( new Error(`Unrecognized account: ${accountId}`) ) } } loadAccountByKey(accountId) { this.loadAccountFromServer(accountId).then(res => { this.setState({account: res, isLoading: false}) return null }) .catch(handleFetchDataFailure(accountId)) } loadAccountByFederatedAddress(address) { const [name, domain] = address.split('*') FederationServer.createForDomain(domain) .then(fed => fed.resolveAddress(name)) .then(acc => this.loadAccountFromServer(acc.account_id)) .then(account => { this.setState({account, federatedAddress: address, isLoading: false}) return null }) .catch(handleFetchDataFailure(address)) } loadAccountByMuxedAddress(address) { const muxedAccount = MuxedAccount.fromAddress(address, '1') const publicAddress = muxedAccount.account.accountId() this.loadAccountFromServer(publicAddress).then(account => { this.setState({account, muxedAddress: address, isLoading: false}) return null }) } loadAccountFromServer(accountId) { return this.props.server .accounts() .accountId(accountId) .call() } render() { return ( <AccountWithSpinner isLoading={this.state.isLoading} account={this.state.account} federatedAddress={this.state.federatedAddress} muxedAddress={this.state.muxedAddress} urlFn={this.props.server.accountURL} {...this.props} /> ) } } export default injectIntl(withServer(AccountContainer))
src/components/BigCalendarWrapper/components/BigCalendarServicePicker/BigCalendarServicePicker.js
TheModevShop/craft-app
import React from 'react'; import FlyOut from 'components/uiElements/FlyOut/FlyOut'; import Select from 'react-select'; import _ from 'lodash'; import 'react-day-picker/lib/style.css'; import './big-calendar-service-picker.less'; class BigCalendarServicePicker extends React.Component { constructor(...args) { super(...args); this.state = {}; } render() { let options = []; const services = _.get(this.props.services, 'items', []); const selected = _.get(this.props, 'selectedService[0]', null); if (services.length) { options = _.map(services, (s) => { const obj = { value: _.get(s, 'service.id', ''), label: `${_.get(s, 'service.name', '')}` }; return obj; }); } return ( <section className="big-calendar-service-picker" onMouseUp={(e) => {e.stopPropagation()}}> <div className="agent small dark"> <Select placeholder="All services" name="select-client" value={selected} options={[{value: null, label: 'All Services'}, ...options]} onChange={this.onChangeService.bind(this)}/> <div className="shield" onMouseUp={(e) => {e.stopPropagation()}}></div> </div> </section> ); } toggleFlyout() { this.setState({flyout: !this.state.flyout}); } onChangeService(agent) { this.props.onSelectService(agent.value); this.timeout = setTimeout(() => { this.toggleFlyout(); }, 200); } componentWillUnmount() { clearTimeout(this.timeout); } } BigCalendarServicePicker.propTypes = {}; export default BigCalendarServicePicker; // <div className="agent-display" onClick={this.toggleFlyout.bind(this)}> // {this.props.selectedAgent || 'All Staff'} // <span className="ion-ios-arrow-down"></span> // </div> // <FlyOut className="agent-flyout" active={this.state.flyout}> // </FlyOut>
src/components/property_image/property_image.spec.js
thoiberg/frontend-coding-exercise
import React from 'react' import {shallow} from 'enzyme' import {random} from 'utils/test' import {PropertyImage} from 'components' describe('<PropertyImage />', () => { const cxt = {} beforeEach(() => { cxt.mainImageUrl = random.string() cxt.wrapper = shallow(<PropertyImage mainImageUrl={cxt.mainImageUrl}/>) }) it('renders an image with the mainImageUrl as the source', () => { expect(cxt.wrapper.prop('src')).to.eq(cxt.mainImageUrl) }) })
app/javascript/mastodon/features/notifications/index.js
danhunsaker/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandNotifications, scrollTopNotifications, loadPending, mountNotifications, unmountNotifications, markNotificationsAsRead, } from '../../actions/notifications'; import { submitMarkers } from '../../actions/markers'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import NotificationContainer from './containers/notification_container'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import FilterBarContainer from './containers/filter_bar_container'; import { createSelector } from 'reselect'; import { List as ImmutableList } from 'immutable'; import { debounce } from 'lodash'; import ScrollableList from '../../components/scrollable_list'; import LoadGap from '../../components/load_gap'; import Icon from 'mastodon/components/icon'; import compareId from 'mastodon/compare_id'; import NotificationsPermissionBanner from './components/notifications_permission_banner'; const messages = defineMessages({ title: { id: 'column.notifications', defaultMessage: 'Notifications' }, markAsRead : { id: 'notifications.mark_as_read', defaultMessage: 'Mark every notification as read' }, }); const getExcludedTypes = createSelector([ state => state.getIn(['settings', 'notifications', 'shows']), ], (shows) => { return ImmutableList(shows.filter(item => !item).keys()); }); const getNotifications = createSelector([ state => state.getIn(['settings', 'notifications', 'quickFilter', 'show']), state => state.getIn(['settings', 'notifications', 'quickFilter', 'active']), getExcludedTypes, state => state.getIn(['notifications', 'items']), ], (showFilterBar, allowedType, excludedTypes, notifications) => { if (!showFilterBar || allowedType === 'all') { // used if user changed the notification settings after loading the notifications from the server // otherwise a list of notifications will come pre-filtered from the backend // we need to turn it off for FilterBar in order not to block ourselves from seeing a specific category return notifications.filterNot(item => item !== null && excludedTypes.includes(item.get('type'))); } return notifications.filter(item => item === null || allowedType === item.get('type')); }); const mapStateToProps = state => ({ showFilterBar: state.getIn(['settings', 'notifications', 'quickFilter', 'show']), notifications: getNotifications(state), isLoading: state.getIn(['notifications', 'isLoading'], true), isUnread: state.getIn(['notifications', 'unread']) > 0 || state.getIn(['notifications', 'pendingItems']).size > 0, hasMore: state.getIn(['notifications', 'hasMore']), numPending: state.getIn(['notifications', 'pendingItems'], ImmutableList()).size, lastReadId: state.getIn(['notifications', 'readMarkerId']), canMarkAsRead: state.getIn(['notifications', 'readMarkerId']) !== '0' && getNotifications(state).some(item => item !== null && compareId(item.get('id'), state.getIn(['notifications', 'readMarkerId'])) > 0), needsNotificationPermission: state.getIn(['settings', 'notifications', 'alerts']).includes(true) && state.getIn(['notifications', 'browserSupport']) && state.getIn(['notifications', 'browserPermission']) === 'default' && !state.getIn(['settings', 'notifications', 'dismissPermissionBanner']), }); export default @connect(mapStateToProps) @injectIntl class Notifications extends React.PureComponent { static propTypes = { columnId: PropTypes.string, notifications: ImmutablePropTypes.list.isRequired, showFilterBar: PropTypes.bool.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, isLoading: PropTypes.bool, isUnread: PropTypes.bool, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, numPending: PropTypes.number, lastReadId: PropTypes.string, canMarkAsRead: PropTypes.bool, needsNotificationPermission: PropTypes.bool, }; static defaultProps = { trackScroll: true, }; componentWillMount() { this.props.dispatch(mountNotifications()); } componentWillUnmount () { this.handleLoadOlder.cancel(); this.handleScrollToTop.cancel(); this.handleScroll.cancel(); this.props.dispatch(scrollTopNotifications(false)); this.props.dispatch(unmountNotifications()); } handleLoadGap = (maxId) => { this.props.dispatch(expandNotifications({ maxId })); }; handleLoadOlder = debounce(() => { const last = this.props.notifications.last(); this.props.dispatch(expandNotifications({ maxId: last && last.get('id') })); }, 300, { leading: true }); handleLoadPending = () => { this.props.dispatch(loadPending()); }; handleScrollToTop = debounce(() => { this.props.dispatch(scrollTopNotifications(true)); }, 100); handleScroll = debounce(() => { this.props.dispatch(scrollTopNotifications(false)); }, 100); handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('NOTIFICATIONS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setColumnRef = c => { this.column = c; } handleMoveUp = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) - 1; this._selectChild(elementIndex, true); } handleMoveDown = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) + 1; this._selectChild(elementIndex, false); } _selectChild (index, align_top) { const container = this.column.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } handleMarkAsRead = () => { this.props.dispatch(markNotificationsAsRead()); this.props.dispatch(submitMarkers({ immediate: true })); }; render () { const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore, numPending, showFilterBar, lastReadId, canMarkAsRead, needsNotificationPermission } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." />; let scrollableContent = null; const filterBarContainer = showFilterBar ? (<FilterBarContainer />) : null; if (isLoading && this.scrollableContent) { scrollableContent = this.scrollableContent; } else if (notifications.size > 0 || hasMore) { scrollableContent = notifications.map((item, index) => item === null ? ( <LoadGap key={'gap:' + notifications.getIn([index + 1, 'id'])} disabled={isLoading} maxId={index > 0 ? notifications.getIn([index - 1, 'id']) : null} onClick={this.handleLoadGap} /> ) : ( <NotificationContainer key={item.get('id')} notification={item} accountId={item.get('account')} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} unread={lastReadId !== '0' && compareId(item.get('id'), lastReadId) > 0} /> )); } else { scrollableContent = null; } this.scrollableContent = scrollableContent; const scrollContainer = ( <ScrollableList scrollKey={`notifications-${columnId}`} trackScroll={!pinned} isLoading={isLoading} showLoading={isLoading && notifications.size === 0} hasMore={hasMore} numPending={numPending} prepend={needsNotificationPermission && <NotificationsPermissionBanner />} alwaysPrepend emptyMessage={emptyMessage} onLoadMore={this.handleLoadOlder} onLoadPending={this.handleLoadPending} onScrollToTop={this.handleScrollToTop} onScroll={this.handleScroll} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} > {scrollableContent} </ScrollableList> ); let extraButton = null; if (canMarkAsRead) { extraButton = ( <button aria-label={intl.formatMessage(messages.markAsRead)} title={intl.formatMessage(messages.markAsRead)} onClick={this.handleMarkAsRead} className='column-header__button' > <Icon id='check' /> </button> ); } return ( <Column bindToDocument={!multiColumn} ref={this.setColumnRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='bell' active={isUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} extraButton={extraButton} > <ColumnSettingsContainer /> </ColumnHeader> {filterBarContainer} {scrollContainer} </Column> ); } }
src/components/grid.js
nordsoftware/react-foundation
import React from 'react'; import PropTypes from 'prop-types'; import { HorizontalAlignments, VerticalAlignments } from '../enums'; import { GeneralPropTypes, FlexboxPropTypes, createClassName, generalClassNames, removeProps, objectKeys, isDefined } from '../utils'; /** * Row component. * * @param {Object} props * @returns {Object} */ export const Row = (props) => { const className = createClassName( props.noDefaultClassName ? null : 'row', props.className, isDefined(props.upOnSmall) ? `small-up-${props.upOnSmall}` : null, isDefined(props.upOnMedium) ? `medium-up-${props.upOnMedium}` : null, isDefined(props.upOnLarge) ? `large-up-${props.upOnLarge}` : null, { 'align-right': props.horizontalAlignment === HorizontalAlignments.RIGHT, 'align-center': props.horizontalAlignment === HorizontalAlignments.CENTER, 'align-justify': props.horizontalAlignment === HorizontalAlignments.JUSTIFY, 'align-spaced': props.horizontalAlignment === HorizontalAlignments.SPACED, 'align-top': props.verticalAlignment === VerticalAlignments.TOP, 'align-middle': props.verticalAlignment === VerticalAlignments.MIDDLE, 'align-bottom': props.verticalAlignment === VerticalAlignments.BOTTOM, 'align-stretch': props.verticalAlignment === VerticalAlignments.STRETCH, 'small-unstack': props.unstackOnSmall, 'medium-unstack': props.unstackOnMedium, 'large-unstack': props.unstackOnLarge, 'small-collapse': props.collapseOnSmall, 'medium-collapse': props.collapseOnMedium, 'large-collapse': props.collapseOnLarge, 'small-uncollapse': props.uncollapseOnSmall, 'medium-uncollapse': props.uncollapseOnMedium, 'large-uncollapse': props.uncollapseOnLarge, 'collapse': props.isCollapsed, 'expanded': props.isExpanded, 'column': props.isColumn }, generalClassNames(props) ); const passProps = removeProps(props, objectKeys(Row.propTypes)); return <div {...passProps} className={className}/>; }; Row.propTypes = { ...GeneralPropTypes, ...FlexboxPropTypes, upOnSmall: PropTypes.number, upOnMedium: PropTypes.number, upOnLarge: PropTypes.number, horizontalAlignment: PropTypes.string, verticalAlignment: PropTypes.string, unstackOnSmall: PropTypes.bool, unstackOnMedium: PropTypes.bool, unstackOnLarge: PropTypes.bool, collapseOnSmall: PropTypes.bool, collapseOnMedium: PropTypes.bool, collapseOnLarge: PropTypes.bool, uncollapseOnSmall: PropTypes.bool, uncollapseOnMedium: PropTypes.bool, uncollapseOnLarge: PropTypes.bool, isCollapsed: PropTypes.bool, isExpanded: PropTypes.bool, isColumn: PropTypes.bool }; /** * Column component. * * @param {Object} props * @returns {Object} */ export const Column = (props) => { const defaultClassName = props.isColumn ? 'column' : 'columns'; const className = createClassName( props.noDefaultClassName ? null : defaultClassName, props.className, props.small ? `small-${props.small}` : null, props.medium ? `medium-${props.medium}` : null, props.large ? `large-${props.large}` : null, isDefined(props.offsetOnSmall) ? `small-offset-${props.offsetOnSmall}` : null, isDefined(props.offsetOnMedium) ? `medium-offset-${props.offsetOnMedium}` : null, isDefined(props.offsetOnLarge) ? `large-offset-${props.offsetOnLarge}` : null, isDefined(props.pushOnSmall) ? `small-push-${props.pushOnSmall}` : null, isDefined(props.pushOnMedium) ? `medium-push-${props.pushOnMedium}` : null, isDefined(props.pushOnLarge) ? `large-push-${props.pushOnLarge}` : null, isDefined(props.pullOnSmall) ? `small-pull-${props.pullOnSmall}` : null, isDefined(props.pullOnMedium) ? `medium-pull-${props.pullOnMedium}` : null, isDefined(props.pullOnLarge) ? `large-pull-${props.pullOnLarge}` : null, isDefined(props.orderOnSmall) ? `small-order-${props.orderOnSmall}` : null, isDefined(props.orderOnMedium) ? `medium-order-${props.orderOnMedium}` : null, isDefined(props.orderOnLarge) ? `large-order-${props.orderOnLarge}` : null, { 'small-centered': props.centerOnSmall, 'medium-centered': props.centerOnMedium, 'large-centered': props.centerOnLarge, 'small-uncentered': props.uncenterOnSmall, 'medium-uncentered': props.uncenterOnMedium, 'large-uncentered': props.uncenterOnLarge, 'small-expand': props.expandOnSmall, 'medium-expand': props.expandOnMedium, 'large-expand': props.expandOnLarge, 'shrink': props.isShrunk, 'end': props.isLast }, generalClassNames(props) ); const passProps = removeProps(props, objectKeys(Column.propTypes)); return <div {...passProps} className={className}/>; }; Column.propTypes = { ...GeneralPropTypes, ...FlexboxPropTypes, small: PropTypes.number, medium: PropTypes.number, large: PropTypes.number, offsetOnSmall: PropTypes.number, offsetOnMedium: PropTypes.number, offsetOnLarge: PropTypes.number, pushOnSmall: PropTypes.number, pushOnMedium: PropTypes.number, pushOnLarge: PropTypes.number, pullOnSmall: PropTypes.number, pullOnMedium: PropTypes.number, pullOnLarge: PropTypes.number, orderOnSmall: PropTypes.number, orderOnMedium: PropTypes.number, orderOnLarge: PropTypes.number, centerOnSmall: PropTypes.bool, centerOnMedium: PropTypes.bool, centerOnLarge: PropTypes.bool, uncenterOnSmall: PropTypes.bool, uncenterOnMedium: PropTypes.bool, uncenterOnLarge: PropTypes.bool, expandOnSmall: PropTypes.bool, expandOnMedium: PropTypes.bool, expandOnLarge: PropTypes.bool, isShrunk: PropTypes.bool, isLast: PropTypes.bool, isColumn: PropTypes.bool, };
src/js/components/Carousel/stories/Controlled.js
HewlettPackard/grommet
import React from 'react'; import { Attraction, Car, TreeOption } from 'grommet-icons'; import { Grommet, Box, Button, Carousel, Text } from 'grommet'; export const Controlled = () => { const [activeSlide, setActiveSlide] = React.useState(2); return ( <Grommet> <Box align="center" pad="large"> <Box direction="row" gap="small" align="center"> <Button label="-" onClick={() => setActiveSlide(activeSlide - 1)} /> <Text>{activeSlide}</Text> <Button label="+" onClick={() => setActiveSlide(activeSlide + 1)} /> </Box> <Carousel activeChild={activeSlide} onChild={setActiveSlide}> <Box pad="xlarge" background="accent-1"> <Attraction size="xlarge" /> </Box> <Box pad="xlarge" background="accent-2"> <TreeOption size="xlarge" /> </Box> <Box pad="xlarge" background="accent-3"> <Car size="xlarge" /> </Box> </Carousel> </Box> </Grommet> ); }; Controlled.parameters = { chromatic: { disable: true }, }; export default { title: 'Media/Carousel/Controlled', };
client/src/containers/TagList.js
richb-hanover/reactathon
import React from 'react'; export const TagList = () => ( <section> <h1>TODO: Update me</h1> </section> );
src/containers/CustomerEdit/CustomerEdit.js
kingpowerclick/kpc-web-backend
import React, { Component } from 'react'; import classNames from 'classnames'; import { Link } from 'react-router'; import { FilterPage, Breadcrumb, CustomerDetail } from 'components'; import { Tabs, Tab, Collapse } from 'react-bootstrap'; export default class CustomerEdit extends Component { constructor(...args) { super(...args); this.state = {}; } render() { const styles = require('./customerOrder.scss'); const avatar = require('./avatar.png'); return ( <div className="container-fluid"> <div className="row"> <div className={ classNames(styles['customer-order-view']) }> <header className={ styles['page-header'] }> <div className={ styles['page-title'] }> <h1 className={ styles.header }>Mr Sarannuth Chanluang</h1> <Breadcrumb breadcrumb={ "Customer > Mr Sarannuth Chanluang" }/> </div> <CustomerDetail/> <div className={ styles.back }> <Link to={`/orders`}> <i className="fa fa-chevron-left"></i> Back </Link> <div className={ styles['sub-breadcrumb'] }>|</div> <a href="#"> <i className="fa fa-refresh"></i> Reset Password </a> <div className={ styles['sub-breadcrumb'] }>|</div> <a href="#"> <i className="fa fa-unlock"></i> Unlock User </a> </div> </header> <section className={ styles['wrapper-content']}> <Tabs defaultActiveKey={1} id="uncontrolled-tab-example"> <Tab eventKey={1} title="Information"> <div id="customer-order-tab-infomation" className={ styles['customer-order-tab-infomation'] }> <div className={ classNames(styles['my-personal-detail'], 'row')}> <div className={ styles['customer-title'] }>My Personal Detail</div> <div className={ styles['personal-avatar'] }> <div className="row"> <div className={ styles.avatar }> <img src={ avatar } className={ styles['avatar-image']} /> </div> <div className={ styles['avatar-name'] }> <div className={ styles['customer-title'] }>Mr Sarannuth Chanluang</div> My Personal Detail </div> </div> </div> <div className={ styles['personal-detail'] }> <div className={ styles['personal-detail-left'] }> <form className="form-horizontal"> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Passport No.</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="420601197409120000" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Citizen ID</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="420601197409120000" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Member ID</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="420601197409120000" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Emboss ID</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="420601197409120000" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Phone</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="420601197409120000" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Cuatomer Level</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">a</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Contact with Facebook</div> <div className={ styles['infomation-detail'] }>420601197409120000</div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Contact with Google</div> <div className={ styles['infomation-detail'] }>420601197409120000</div> </div> </form> </div> <div className={ styles['personal-detail-right'] }> <form className="form-horizontal"> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Name</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="MR. Sarannuth Chanluang" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Email</div> <div className={ styles['infomation-detail'] }> <input type="email" className="form-control" value="080525.shiningshinee@gmail.com" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Date of Birth</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="11/16/1995" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Nationality</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">a</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Send Welcome Email For Launguage</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">a</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> <div className="form-group"> <div className={ styles['infomation-detail'] }> <div className="checkbox"> <label> <input type="checkbox" /> Subscribed to Newsletter </label> </div> </div> </div> </form> </div> <div className={ styles['personal-detail-mid'] }> <button className={ classNames('btn btn-default', styles['btn-blue']) }>save</button> </div> </div> </div> <div className={ classNames(styles['personal-address'], 'row') }> <div className={ classNames(styles['customer-title'], styles['customer-title-address']) }>Address</div> <div className={ styles['select-address'] }> <div className={ classNames(styles['panel-default'], 'panel') }> <div className={ classNames(styles['panel-body'], styles['personal-address-title']) } onClick={ ()=> this.setState({ open: !this.state.open }) }> Default Billing Address </div> <Collapse className={ styles['panel-collapse'] } in={ !this.state.open }> <div className={styles['personal-address-detail']}> <div className={ styles['personal-address-detail-name'] }>Mr Sarannuth Chanluang </div> <div className={ styles['personal-address-detail-address'] }> 58/7 Soi Thewet 1, Krungkasem rd. Phranakorn, Bangkok, 10200 Thailand T: 894575507 </div> </div> </Collapse> </div> <div className={ classNames(styles['panel-default'], 'panel') }> <div className={ classNames(styles['panel-body'], styles['personal-address-title']) } onClick={ ()=> this.setState({ open: !this.state.open }) }> Default Shipping Address </div> <Collapse className={ styles['panel-collapse'] } in={ !this.state.open }> <div className={styles['personal-address-detail']}> <div className={ styles['personal-address-detail-name'] }>Mr Sarannuth Chanluang </div> <div className={ styles['personal-address-detail-address'] }> 58/7 Soi Thewet 1, Krungkasem rd. Phranakorn, Bangkok, 10200 Thailand T: 894575507 </div> </div> </Collapse> </div> <div className={ classNames(styles['panel-default'], 'panel') }> <div className={ classNames(styles['panel-body'], styles['personal-address-title']) } onClick={ ()=> this.setState({ open: !this.state.open }) }> Other Address </div> <Collapse className={ styles['panel-collapse'] } in={ !this.state.open }> <div className={styles['personal-address-detail']}> <div className={ styles['personal-address-detail-name'] }>Mr Sarannuth Chanluang </div> <div className={ styles['personal-address-detail-address'] }> 58/7 Soi Thewet 1, Krungkasem rd. Phranakorn, Bangkok, 10200 Thailand T: 894575507 </div> </div> </Collapse> </div> </div> <div className={ styles['address-info'] }> <div className={ classNames(styles['panel-default'], 'panel') }> <div className={ classNames(styles['panel-body'], styles['personal-address-title']) } > Default Billing Address </div> <div className={ styles['panel-collapse'] } > <form className="form-horizontal"> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Select from added address</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">a</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> </form> <div className="row"> <div className={ styles['personal-detail-left'] }> <form className="form-horizontal"> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Title</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="MR." /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >First Name</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="Sarannuth" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Last Name</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="Chanluang" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Phone Number</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="894575507" /> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >VAT Number</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="-" /> </div> </div> </form> </div> <div className={ styles['personal-detail-right'] }> <form className="form-horizontal"> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Street Address</div> <div className={ styles['infomation-detail'] }> <textarea className="form-control" rows="3"> 58/7 Soi Thewet 1, Krungkasem rd. </textarea> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Country</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">Thailand</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >State/Province</div> <div className={ styles['infomation-detail'] }> <select className="form-control"> <option value="">a</option> <option value="">b</option> <option value="">c</option> </select> </div> </div> <div className="form-group"> <div className={ classNames( styles['detail-label'], 'control-label') } >Zip/Postal Code</div> <div className={ styles['infomation-detail'] }> <input type="text" className="form-control" value="10230" /> </div> </div> </form> </div> </div> <div className="row"> <div className={ styles['personal-detail-mid'] }> <button className={ classNames('btn btn-default', styles['btn-blue']) }>Save Address</button> </div> </div> </div> </div> </div> </div> </div> </Tab> <Tab eventKey={2} title="Order History"> <div id="customer-order-tab-history"> <div className={ classNames(styles['filter-customer-order'])}> <div className={ classNames(styles['wrapper-filter'])}> <div className={ styles['customer-order-title'] }>Order History</div> <div className={ styles['filter-left']}> <div className={ styles['filter-radio']}> <div className="radio"> <label> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked />Complete Order </label> <label> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" />Return Order </label> </div> </div> </div> <div className={ classNames(styles['filter-right']) }> <FilterPage/> </div> </div> </div> <div className={ styles['table-detail'] }> <div className={ styles['tab-content'] }> <table className="table table-striped"> <thead> <tr className={ styles['title-table']}> <th className={ styles['order-no'] }>Order No.</th> <th className={ styles['order-date'] }>Order Date</th> <th className={ styles['ship-to-name'] }>Ship-to-name</th> <th className={ styles['order-total'] }>Order Total</th> <th className={ styles['order-status'] }>Order Status</th> </tr> </thead> <tbody> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> <tr> <td>503576</td> <td>May 08, 2017, 16:05:00 PM</td> <td>จิรพร พริกบางเข็ม</td> <td>14,590.00 THB</td> <td>Packing</td> </tr> </tbody> </table> </div> <div className={ classNames(styles['filter-bottom'])}> <FilterPage/> </div> </div> </div> </Tab> </Tabs> </section> </div> </div> </div> ); } }
src/components/Accounts.js
chatch/stellarexplorer
import React from 'react' import Grid from 'react-bootstrap/lib/Grid' import Row from 'react-bootstrap/lib/Row' import AccountTable from './AccountTable' class Accounts extends React.Component { render() { return ( <Grid> <Row> <AccountTable limit={10} /> </Row> </Grid> ) } } export default Accounts
src/lib/plugins/battery/critical.js
Hyperline/hyperline
import React from 'react' import Component from 'hyper/component' import SvgIcon from '../../utils/svg-icon' export default class Critical extends Component { render() { return ( <SvgIcon> <g fillRule="evenodd"> <g className='cpu-critical-icon'> <path d="M7,1 L9,1 L9,2 L7,2 L7,1 Z M4,2 L12,2 L12,15 L4,15 L4,2 Z M5,3 L11,3 L11,11 L5,11 L5,3 Z"></path> </g> </g> <style jsx>{` .cpu-critical-icon { fill: #fff; } `}</style> </SvgIcon> ) } }
app/components/OnResult.js
elyamad/brocantelab
import React from 'react'; import { ListGroupItem, ListGroup } from 'react-bootstrap'; var OnResult = React.createClass({ propsType: { visible: React.PropTypes.bool, value: React.PropTypes.string, // "success", "warning", "danger" headerMsg: React.PropTypes.string, contentMsg: React.PropTypes.string }, render() { if(this.props.visible){ return ( <ListGroup> <ListGroupItem header={this.props.headerMsg} bsStyle={this.props.result}>{this.props.contentMsg}</ListGroupItem> </ListGroup> ); } else { return null; } } }); module.exports = OnResult;
src/app/components/StreamWidget/StreamDropZone.js
smitch88/multi-stream-twitch
import React from 'react'; import CheckIcon from 'react-icons/lib/md/check'; import PropTypes from 'prop-types'; import uuid from 'uuidv4'; import theme from '../../theme'; /* * Returns a component tht handles dragging a link into the frame and passes back * the stream data configuration. * * Currently only supports youtube and twitch. */ const styles = { stream__configure: { height: 'calc(100% - 25px)', width: '100%', backgroundColor: '#222222' }, configure__inner: { height: 'calc(100% - 25px)', width: '100%', color: theme.colors.white, fontFamily: 'Roboto, sans-serif', overflowY: 'auto' }, configure__error: { marginTop: 10, fontSize: '2em', color: theme.colors.red, fontWeight: 500 }, padding: { padding: 20 }, input__container: { display: 'inline-flex', marginTop: theme.spacing, height: 32, width: '100%', border: '1px solid #333333', maxWidth: 300 }, manual__input: { height: '100%', width: 'calc(100% - 50px)', padding: '0 10px', border: 'none', outline: 'none' }, button: { cursor: 'pointer', height: '100%', width: 50, backgroundColor: theme.colors.primary, border: 'none' }, icon: { fontSize: '1.2em', color: theme.colors.white } }; class StreamDropZone extends React.Component { constructor(props){ super(props); this.dropzoneInstance = undefined; this.regex = { youtube: /https:\/\/www.(youtube).com\/.+v=(.+)/ig, twitch: /https:\/\/www.(twitch).tv\/(.+)/ig }; this.configurationHelp = ( 'You can enter a channel name or auto-magically drag a twitch or stream channel into this panel.' ); this.state = { dropzoneError: undefined, channelInput: props.channelInput || '' }; } dropzoneId = () => { return `dropzone_${this.props.id}`; } destroyDropzone = () => { // Destroy the dropzone instance listeners if(this.dropzoneInstance){ this.dropzoneInstance.removeEventListener('dragover', this.handleDragOver); this.dropzoneInstance.removeEventListener('drop', this.handleDrop); } } handleDragOver(e){ e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; } extractedUrlObject = (droppedUrl) => { // TODO: make generic when we have more url types that are valid to drop const youtubeMatch = this.regex.youtube.exec(droppedUrl); const twitchMatch = this.regex.twitch.exec(droppedUrl); const matchedOnUrl = twitchMatch || youtubeMatch; // extract out stream type and stream data i.e videoId or channelId if(matchedOnUrl){ const [_, type, playerId] = matchedOnUrl; const playerTypeReference = type === 'twitch' ? 'channelId' : 'videoId'; return [true, { type, playerId, [playerTypeReference]: playerId }]; } return [false, {}]; } handleDrop = (e) => { e.stopPropagation(); e.preventDefault(); const streamUrlDropped = e.dataTransfer.getData('url'); const [isValid, urlData] = this.extractedUrlObject(streamUrlDropped); if(isValid){ // Set new widget configuration that was dragged into the panel this.setState({ dropzoneError: undefined }, this.props.onDrop.bind(null, this.props.id, urlData)); } else { console.warn('Invalid URL was dragged into dropzone container.'); this.setState({ dropzoneError: new Error( `Invalid URL dropped "${streamUrlDropped}". Please try a youtube or twitch stream.` ) }); } } setupDropzone = () => { this.dropzoneInstance = document.getElementById(this.dropzoneId()); if(this.dropzoneInstance){ // Handle when a user drags something overtop the dropzone // Maybe validate its some data we can actually deal with this.dropzoneInstance.addEventListener('dragover', this.handleDragOver); // Configure the widget w/ the proper data i.e update the layout object this.dropzoneInstance.addEventListener('drop', this.handleDrop); } else { console.warn('There was an issue while trying to setup the widgets dropzone container.'); } } handleInputChange = (e) => { this.setState({ channelInput: e.target.value }) } handleChannelInputSelection = (e) => { e.preventDefault(); if(this.props.onChannelSelected){ this.props.onChannelSelected(this.state.channelInput); } } componentDidMount(){ /* * Allow for external component callback, like in the case of state in the parent * depending on knowing the dropzone has initialized e.g, `LoadingIndicator` state * is autoset to isReady true in `StreamWidget` */ if(this.props.onLoad){ this.props.onLoad(); }; this.setupDropzone(); } componentWillUnmount(){ this.destroyDropzone(); } render(){ const { channelInput, dropzoneError } = this.state; return ( <div className="stream-container" style={ styles.stream__configure } > <div id={ this.dropzoneId() } className="dropzone" style={ styles.configure__inner } > <form onSubmit={ this.handleChannelInputSelection } style={ styles.padding } > <h3>Configure Stream</h3> <p>{ this.configurationHelp }</p> <div style={ styles.input__container }> <input style={ styles.manual__input } value={ channelInput } onChange={ this.handleInputChange } placeholder="Enter a channel" /> <button type="submit" style={ styles.button } > <CheckIcon style={ styles.icon } /> </button> </div> { dropzoneError && <div style={ styles.configure__error }> { dropzoneError.message } </div> } </form> </div> </div> ); } } StreamDropZone.propTypes = { id: PropTypes.string.isRequired, onChannelSelected: PropTypes.func.isRequired, onDrop: PropTypes.func.isRequired, onLoad: PropTypes.func }; export default StreamDropZone;
src/pages/startegy/StrategyDetail.js
i-July/footballgo
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; class StrategyDetail extends Component { render() { const id = this.props.match.params.id; return ( <div> <h2>这是战略{id}</h2> </div> ); } } export default withRouter(StrategyDetail);
test/test_helper.js
alxDiaz/reactFirstProject
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
client/main.js
srojas19/feedback
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import '../imports/startup/accounts-config.js'; import App from '../imports/ui/App.jsx'; Meteor.startup(() => { render(<App />, document.getElementById('render-target')); });
src/Controls/ControlBool.js
rpominov/react-demo
import React from 'react' import createReactClass from 'create-react-class' import T from 'prop-types' import Group from './Group' import InputCheckbox from './InputCheckbox' export default createReactClass({ displayName: 'Demo.Controls.ControlBool', propTypes: { name: T.string.isRequired, value: T.bool.isRequired, onChange: T.func.isRequired, }, render() { const {name, value, onChange} = this.props return <Group name={name}> <InputCheckbox value={value} onChange={onChange} /> </Group> }, })
src/components/partials/Elements.js
MattMcFarland/codepix-client
import React from 'react'; import { Collapse } from 'react-bootstrap'; export const Button = ({ children, onClick, kind = 'info' }) => ( <button onClick={onClick} type='button' className={'btn btn-' + kind}> {children} </button> ); export const Icon = ({ name }) => ( <span className={'icon icon-' + name}/> ); export const Alert = ({ children, kind = 'info' }) => ( <div className={'alert alert-' + kind}> {children} </div> ); const selectAll = (e) => { let target = e.target; target.setSelectionRange(0, target.value.length); }; export const PastaLink = ({ label, value }) => ( <div className='form-group'> <label>{label}</label> <input className='form-control' readOnly type='text' value={value} onClick={selectAll} /> </div> ); const Title = ({ children }) => ( <strong> {children} </strong> ); export const Radio = ({ name, value, children, onChange, set }) => ( <label className="radio-inline"> <input onChange = {onChange} checked = {set === value} type = 'radio' name = {name} id = {name} value = {value} /> {children} </label> ); export const Expander = ({ isExpanded = false, title, children, onToggle }) => ( <span> <Title> <Button kind="link btn-sm" onClick={onToggle}> {title} &nbsp; <Icon name={isExpanded ? 'caret-down' : 'caret-right'}/> </Button> </Title> <Collapse in={isExpanded}> <div> {children} </div> </Collapse> </span> );
modules/genomic_browser/jsx/genomicBrowserIndex.js
kongtiaowang/Loris
import React from 'react'; import PropTypes from 'prop-types'; import {TabPane, Tabs} from 'jsx/Tabs'; import Profiles from './tabs_content/profiles'; import GWAS from './tabs_content/gwas'; import SNP from './tabs_content/snp'; import CNV from './tabs_content/cnv'; import Methylation from './tabs_content/methylation'; import Files from './tabs_content/files'; /** * Genomic Browser. * * @description the Genomic Browser of LORIS. * @param {param} props the react properties for the component. * @return {react} element tabPane of the GenomicBrowser. * * @author Alizée Wickenheiser * @version 1.0.0 * */ const GenomicBrowser = (props) => { const tabList = [ {id: 'tabProfiles', label: 'Profiles'}, {id: 'tabGWAS', label: 'GWAS'}, {id: 'tabSNP', label: 'SNP'}, {id: 'tabCNV', label: 'CNV'}, {id: 'tabMethylation', label: 'Methylation'}, {id: 'tabFiles', label: 'Files'}, ]; /** * @return {React} render the panels of the GenomicBrowser. */ return ( <div className={'col-sm-12'}> <div className={'row'}> <Tabs tabs={tabList} defaultTab='tabProfiles'> <TabPane TabId={tabList[0].id}> <Profiles baseURL={props.baseURL}/> </TabPane> <TabPane TabId={tabList[1].id}> <GWAS baseURL={props.baseURL}/> </TabPane> <TabPane TabId={tabList[2].id}> <SNP baseURL={props.baseURL}/> </TabPane> <TabPane TabId={tabList[3].id}> <CNV baseURL={props.baseURL}/> </TabPane> <TabPane TabId={tabList[4].id}> <Methylation baseURL={props.baseURL}/> </TabPane> <TabPane TabId={tabList[5].id}> <Files baseURL={props.baseURL}/> </TabPane> </Tabs> </div> </div> ); }; GenomicBrowser.propTypes = { baseURL: PropTypes.string.isRequired, }; /** * Render Genomic Browser on page load. */ window.addEventListener('load', () => { ReactDOM.render( <GenomicBrowser baseURL={loris.BaseURL} />, document.getElementById('lorisworkspace') ); });
components/Toggle/Toggle.js
zendesk/linksf
import React from 'react' import s from './Toggle.css' const Toggle = (props) => ( <div className={`${s.switch} ${props.disabled ? s.disabled : ''}`} tabIndex="0" onMouseUp={(e) => props.onMouseUp && props.onMouseUp(e)} > <div className={s.mask}> <div className={`${s.container} ${props.on ? s.containerOn : s.containerOff}`}> <div className={s.switchUpper}> <span className={s.handle}></span> </div> <div className={s.switchLower}> <div className={s.labels}> <span className={s.on} tabIndex="-1">{props.onLabel || 'YES'}</span> <span className={s.off} tabIndex="-1">{props.offLabel || 'NO'}</span> </div> </div> </div> </div> <div className={s.switchMiddle}></div> </div> ) export default Toggle
src/js/layout/MainPanel.js
Robert-W/esri-react-prerender
import {Map} from 'js/map/Map'; import React from 'react'; export class MainPanel extends React.Component { render () { return ( <div className='app-body'> <Map /> </div> ); } }
src/client/demo4/select.js
hihl/react-demo
import React from 'react'; import res from '../../data.json'; const adminPartners = res.data.adminPartners; export default function Select() { return ( <select> { adminPartners.map(partner => <option key={partner.partnerCode} value={partner.partnerCode}>{partner.displayName}</option>) } </select> ); }
src/CHANGELOG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Anomoly, blazyb, Dyspho, fasib, Fyruna, Gurupitka, Juko8, Mamtooth, sref, Versaya, Yuyz0112, Zerotorescue, Hartra344, Putro, Sharrq } from 'MAINTAINERS'; import Wrapper from 'common/Wrapper'; import ItemLink from 'common/ItemLink'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2018-01-11'), changes: 'Fixed a bug where item damage/healing/mana statistics (with the icons) stopped updating after the last damage/healing/mana event. This will lower most displayed item values, the impact depends on the time between the last event that increased the damage/healing/mana of the thing being analyzed and the fight ending.', contributors: [Zerotorescue], }, { date: new Date('2018-01-10'), changes: 'Added a note about unlisted logs to the report selector.', contributors: [Zerotorescue], }, { date: new Date('2018-01-09'), changes: <Wrapper>Updated the tooltip for <ItemLink id={ITEMS.GOLGANNETHS_VITALITY.id} icon /> to show uptime aswell as damage contribution of the two procs</Wrapper>, contributors: [Putro], }, { date: new Date('2018-01-08'), changes: 'Replaced the articles on the frontpage with a basic news system so we can more easily add and maintain articles.', contributors: [Zerotorescue], }, { date: new Date('2018-01-04'), changes: 'Fixed a bug where procs that changed an ability from a cast time ability to instant might not properly register the GCD.', contributors: [Zerotorescue], }, { date: new Date('2017-12-31'), changes: 'Changed the way Mastery percentage is calculated and implemented the coefficients for all specs. Let us know if Mastery still doesn\'t match the character pane.', contributors: [Zerotorescue], }, { date: new Date('2017-12-30'), changes: 'Added icons indicating the stat type to most item stats.', contributors: [Zerotorescue], }, { date: new Date('2017-12-27'), changes: 'Added Death Tracking to the parser.', contributors: [Sharrq], }, { date: new Date('2017-12-26'), changes: 'Mark the Warlords of Draenor cloak enchants as a part of the good enchants', contributors: [Putro], }, { date: new Date('2017-12-25'), changes: <Wrapper>Added a <i>casting time</i> bar to the spell timeline that shows you the amount of time spent channeling or waiting for the GCD.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-12-18'), changes: <Wrapper>Added <ItemLink id={ITEMS.INSIGNIA_OF_THE_GRAND_ARMY.id} /> to the parser.</Wrapper>, contributors: [Putro], }, { date: new Date('2017-12-06'), changes: <Wrapper><SpellLink id={SPELLS.EONARS_COMPASSION_HEAL.id} /> is now ignored in the cooldowns tab.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-12-06'), changes: <Wrapper>Added <ItemLink id={ITEMS.ISHKARS_FELSHIELD_EMITTER.id} /> to items </Wrapper>, contributors: [Hartra344], }, { date: new Date('2017-12-05'), changes: 'Included some NLC traits and trinkets to stat weights module.', contributors: [blazyb], }, { date: new Date('2017-12-03'), changes: <Wrapper>Improve Player Selection user interface.</Wrapper>, contributors: ['kyle-glick'], }, { date: new Date('2017-12-01'), changes: <Wrapper>Improved WCL API error handling to avoid caching corrupt responses (and show more informative errors).</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-11-29'), changes: <Wrapper>Added a <i>talents</i> panel, replacing the tab.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-11-29'), changes: <Wrapper>Added a <i>stats on pull</i> panel.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-11-28'), changes: 'Reworked the frontpage layout.', contributors: [Zerotorescue], }, { date: new Date('2017-11-11'), changes: <Wrapper>Changed the Changelog tab to mark <i>shared changes</i> as grey and provided a toggle to hide them.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-11-11'), changes: 'Added a larger call for help for specs that are marked "Not actively maintained".', contributors: [Zerotorescue], }, { date: new Date('2017-11-11'), changes: 'Added a timeline tab. Right now this only shows spell casts and their cooldowns so you can see what you cast and could have cast.', contributors: [Zerotorescue], }, { date: new Date('2017-11-08'), changes: 'Automatically try again when WCL sends a corrupt fights response.', contributors: [Zerotorescue], }, { date: new Date('2017-11-08'), changes: 'Changed the API is down and rendering errors to be more amazing.', contributors: [Zerotorescue], }, { date: new Date('2017-11-08'), changes: 'The changelog tab now includes entries in the shared changelog.', contributors: [Zerotorescue], }, { date: new Date('2017-11-08'), changes: 'Added a suggestion for healers if their mana percentage is too high at the end of an encounter.', contributors: [blazyb], }, { date: new Date('2017-11-06'), changes: 'Added a changelog tab to results page and changed the layout of changelogs.', contributors: [Zerotorescue], }, { date: new Date('2017-11-05'), changes: 'Added a spell cooldown timeline to cast efficiency suggestions.', contributors: [Zerotorescue], }, { date: new Date('2017-11-02'), changes: <Wrapper>Changed the <i>default</i> recommended <ItemLink id={ITEMS.VELENS_FUTURE_SIGHT.id} /> healing contribution to be at least 4% (down from 4.5%).</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-11-01'), changes: 'Always show the navigation bar and stick it to the top of the window.', contributors: [Zerotorescue], }, { date: new Date('2017-10-29'), changes: <Wrapper>Update layout a bit: <a href="https://imgur.com/a/edymi">comparison</a>.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-10-25'), changes: 'Added T21 healing trinkets: Tarratus Keystone and Highfather\'s Machination.', contributors: [Dyspho], }, { date: new Date('2017-10-22'), changes: 'Fixed a crash when a player\'s info errored. Instead the affected player will become unselectable.', contributors: [Zerotorescue], }, { date: new Date('2017-10-22'), changes: 'Change a bunch of less important statistics to a smaller statistic box to reduce their emphasis and reduce clutter.', contributors: [Zerotorescue], }, { date: new Date('2017-10-22'), changes: 'Fixed a bunch of crashes and improved browser support.', contributors: [Zerotorescue], }, { date: new Date('2017-10-22'), changes: 'Removed overhealing from cast efficiency.', contributors: [Zerotorescue], }, { date: new Date('2017-10-22'), changes: 'Improved layout on a small screens such as mobile devices.', contributors: [Zerotorescue], }, { date: new Date('2017-10-22'), changes: 'Changed polyfill usage to be more reliable (but slightly increase download size).', contributors: [Zerotorescue], }, { date: new Date('2017-10-21'), changes: 'Added a panel to advertize the Discord bot.', contributors: [Zerotorescue], }, { date: new Date('2017-10-20'), changes: 'Rename "Not yet supported" completion status to "Not actively maintained" so it can also be used for abandoned specs.', contributors: [Zerotorescue], }, { date: new Date('2017-10-20'), changes: 'Don\'t show a tooltip for the distance moved icon (previously showed a Mage ability).', contributors: [Zerotorescue], }, { date: new Date('2017-10-19'), changes: 'Enable Sentry to record client side errors.', contributors: [Zerotorescue], }, { date: new Date('2017-10-17'), changes: <Wrapper>Fix issue with <i>distance moved</i> that caused it to include the movement from <b>all</b> players.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-10-16'), changes: 'Added Cinidaria, the Symbiote damage and healing tracker.', contributors: [Juko8], }, { date: new Date('2017-10-15'), changes: 'Added a statistic to track total distance moved during the analyzed fight.', contributors: [Fyruna], }, { date: new Date('2017-10-14'), changes: 'Sephuz\'s Secret now displays average haste gain. Uptime still available in tooltip.', contributors: [sref], }, { date: new Date('2017-10-14'), changes: 'Added a suggestion when a legendary haven\'t been upgraded to the max item level.', contributors: [Fyruna], }, { date: new Date('2017-10-10'), changes: 'Changed the buff tracking implementation to be much more developer friendly. This should have no side-effects except to improve accuracy of modules that didn\'t take this into account in the past. If you notice something strange please let us know.', contributors: [Zerotorescue], }, { date: new Date('2017-10-02'), changes: <Wrapper>Added a <i>help wanted</i> panel to the frontpage.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-10-02'), changes: 'The developer only Events tab can now be filtered with JS expressions to be much more powerful.', contributors: [Zerotorescue], }, { date: new Date('2017-09-29'), changes: 'Added a spec analyzer info overlay for maintainers to configure.', contributors: [Zerotorescue], }, { date: new Date('2017-09-27'), changes: 'Hot Fix: Add in check to disable Netherlight Crucible statistics box if a user has no Netherlight Crucible traits active', contributors: [Anomoly], }, { date: new Date('2017-09-25'), changes: 'Added Netherlight Crucible traits contribution as a common module across specs', contributors: [Anomoly], }, { date: new Date('2017-09-25'), changes: 'The GitHub repository is now available under WoWAnalyzer/WoWAnalyzer instead of MartijnHols/WoWAnalyzer to give us all the benefits an organization provides on GitHub.', contributors: [Zerotorescue], }, { date: new Date('2017-09-25'), changes: 'Separated damage absorbed and healing absorbed in the healing done bar and made the overhealing bar gray to de-emphasize it.', contributors: [Zerotorescue], }, { date: new Date('2017-09-23'), changes: 'Changed all Damage Done / Healing Done / Damage Taken modules to use a shared renderer that can easily be improved in one spot.', contributors: [Zerotorescue], }, { date: new Date('2017-09-17'), changes: 'Fight parsing now happens in batches allowing the progress bar to function again, in addition the progress bar will slightly move while waiting on a network request to indicate it\'s doing something.', contributors: [Zerotorescue], }, { date: new Date('2017-09-16'), changes: 'Archimonde\'s Hatred Reborn now shows total damage done % and DPS contribution on it\'s tooltip.', contributors: [Mamtooth], }, { date: new Date('2017-09-12'), changes: ( <Wrapper>The Always Be Casting module has the following changes:<br /> <ul> <li>It now properly supports the passive Haste gain from Sephuz.</li> <li>Fixed an issue where the downtime between the last cast and the fight end time wasn't included (this also makes it so dying before the boss dies will affect your downtime).</li> <li>Haste buffs from items now scale with item level.</li> <li>Changed how Haste from stacking (de)buffs are applied.</li> </ul> </Wrapper> ), contributors: [Zerotorescue], }, { date: new Date('2017-09-03'), changes: 'Reworked the WCL API cache to use a database so it persists between patches, improved performance and corrupt response detection.', contributors: [Zerotorescue], }, { date: new Date('2017-09-01'), changes: 'All players in a log now appear and selecting a spec that\'s not yet supported will show information on adding support for it.', contributors: [Zerotorescue], }, { date: new Date('2017-09-01'), changes: 'Added role icons to player selection list and it\'s now sorted by role then playername to make finding players easier.', contributors: [Zerotorescue], }, { date: new Date('2017-08-28'), changes: 'Select fights for the currently selected player with a pull down menu.', contributors: [fasib], }, { date: new Date('2017-08-28'), changes: 'Select other players with a pull down menu from the currently selected player.', contributors: [fasib], }, { date: new Date('2017-08-27'), changes: 'Added a small line showing the maintainer of a spec to the results page.', contributors: [Zerotorescue], }, { date: new Date('2017-08-24'), changes: 'Better error handling when the WCL API is sending weird responses.', contributors: [Zerotorescue], }, { date: new Date('2017-08-24'), changes: 'Slightly improve layouts for both desktop and mobile.', contributors: [Zerotorescue], }, { date: new Date('2017-08-24'), changes: 'Changelogs are now seperated by a select box.', contributors: [blazyb], }, { date: new Date('2017-08-24'), changes: 'Added a mana usage graph to the mana tab for all healers.', contributors: [Zerotorescue], }, { date: new Date('2017-08-20'), changes: 'The background image will now be a screenshot of the boss currently analyzing when available.', contributors: [Zerotorescue], }, { date: new Date('2017-08-14'), changes: 'Major under the hood changes, you might see some things move around but no data should be lost or changed.', contributors: [Zerotorescue], }, { date: new Date('2017-08-09'), changes: <Wrapper>Healers with a <i>non-healing time</i> statistic will no longer have their <i>dead GCD time</i> suggestion marked as major importance.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-08-09'), changes: 'Changed suggestions tab layout to be less cluttered, specs may need additional work to be fully migrated', contributors: [Zerotorescue], }, { date: new Date('2017-08-03'), changes: 'Fix a bug that caused DRPS displays to not always work properly.', contributors: [Zerotorescue], }, { date: new Date('2017-08-02'), changes: 'When there\'s a new version available ask the user if he wants to refresh.', contributors: [Zerotorescue], }, { date: new Date('2017-08-02'), changes: 'Gnawed Thumb Ring should now show DPS values when applicable.', contributors: [Gurupitka], }, { date: new Date('2017-08-01'), changes: 'Enabled aggressive caching to the app which should allow offline usage as well as improve consecutive load times.', contributors: [Zerotorescue], }, { date: new Date('2017-07-31'), changes: 'Added Vantus Rune gain display.', contributors: [Zerotorescue], }, { date: new Date('2017-07-22'), changes: 'Shit browsers will now be told they\'re shit and redirected to a Google Chrome download page instead of just crashing.', contributors: [Zerotorescue], }, { date: new Date('2017-07-22'), changes: 'URLs will now show the fight name to make it easier to compare URLs.', contributors: [Zerotorescue], }, { date: new Date('2017-07-21'), changes: 'Changed fight selection styling and fixed back buttons.', contributors: [Zerotorescue], }, { date: new Date('2017-07-20'), changes: 'Added fight progress indicator to the fight selection page.', contributors: [Yuyz0112], }, { date: new Date('2017-07-06'), changes: <Wrapper>The <i>report code</i> input field now accepts WCL urls and entering what looks to be valid input will now automatically start loading the report.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-07-04'), changes: 'All healing specs: Added low health healing tab to give more insight into how often you\'re saving people\'s lives.', contributors: [Zerotorescue], }, { date: new Date('2017-07-01'), changes: <Wrapper>Added a few new tools for developers to use; <code>ModuleComponent</code> to more cleanly add statistic modules (see <code>DevotionAura</code> for an example), and <code>LazyLoadStatisticBox</code> for statistics that require additional API calls.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-06-24'), changes: 'Fixed an issue with some items not showing up properly', contributors: [Zerotorescue], }, { date: new Date('2017-06-23'), changes: 'Change home page layout', contributors: [Zerotorescue], }, { date: new Date('2017-06-20'), changes: 'Added prepot/second pot suggestions', contributors: [blazyb], }, { date: new Date('2017-06-18'), changes: 'Added Archive of Faith, Barbaric Mindslaver, The Deceiver\'s Grand Design and Sea Star of the Depthmother to all specs, trinket implementations by anomoly.', contributors: [Zerotorescue], }, { date: new Date('2017-06-17'), changes: 'Improved the Cooldown tab healing done display.', contributors: [Zerotorescue], }, { date: new Date('2017-06-15'), changes: 'Updated Darkmoon Deck: Promises mana reduction values to scale with item level.', contributors: [Zerotorescue], }, { date: new Date('2017-06-15'), changes: 'Generic: Tier 20 Healing Trinket Implementation', contributors: [Anomoly], }, { date: new Date('2017-06-06'), changes: 'Added refresh button to fights list.', contributors: [Zerotorescue], }, { date: new Date('2017-05-29'), changes: 'Fixed a crash when trying to parse a corrupt combatlog.', contributors: [Versaya], }, { date: new Date('2017-05-28'), changes: 'Added overhealing percentages to the Cast Efficiency tab.', contributors: [Zerotorescue], }, { date: new Date('2017-05-25'), changes: 'Added Patreon links to the specs I (Zerotorescue) maintain. Please let me know if you think this is inappropriate or makes you hesitate to contribute. Added Discord link.', contributors: [Zerotorescue], }, { date: new Date('2017-05-21'), changes: 'An informative message is now shown when trying to parse a report without combatants (usually due to not having advanced combat logging enabled).', contributors: [Zerotorescue], }, { date: new Date('2017-05-21'), changes: 'Fixed a rare crash when auto attacking something.', contributors: [Zerotorescue], }, { date: new Date('2017-05-20'), changes: 'Added Cooldowns tab to show casts and healing when affected by a cooldown. Added Amalgam\'s Seventh Spine mana gained statistic. Promises no longer includes mana reduction during Innervate.', contributors: [Zerotorescue], }, { date: new Date('2017-05-17'), changes: 'Added Sephuz\'s Secret uptime indicator.', contributors: [Zerotorescue], }, { date: new Date('2017-05-16'), changes: 'Disabled Retribution Paladin spec since it never really came out of the experimental phase.', contributors: [Zerotorescue], }, { date: new Date('2017-05-13'), changes: 'Added full multispec support! The right spec specific parser is now selected based on the spec of the selected person. Only players with supported specs will be displayed in the player selection.', contributors: [Zerotorescue], }, { date: new Date('2017-05-11'), changes: 'Fixed a bunch of bugs. The Always Be Casting/Healing module now supports debuffs which allows me to implement boss Haste buffs to make it more accurate. Elisande\'s Haste buffs are now implemented.', contributors: [Zerotorescue], }, { date: new Date('2017-05-11'), changes: <Wrapper><b>A lot</b> more changes under the hood in order to make the analyzer multi-spec compatible. Almost everything was changed, so anything might have gotten broken. Please let me know.</Wrapper>, contributors: [Zerotorescue], }, { date: new Date('2017-05-07'), changes: 'Untangled many lines - you shouldn\'t notice a difference.', contributors: [Zerotorescue], }, ];
app/components/Toggle/index.js
rlagman/raphthelagman
/** * * LocaleToggle * */ import React from 'react'; import PropTypes from 'prop-types'; import Select from './Select'; import ToggleOption from '../ToggleOption'; function Toggle(props) { let content = <option>--</option>; // If we have items, render them if (props.values) { content = props.values.map(value => ( <ToggleOption key={value} value={value} message={props.messages[value]} /> )); } return ( <Select value={props.value} onChange={props.onToggle}> {content} </Select> ); } Toggle.propTypes = { onToggle: PropTypes.func, values: PropTypes.array, value: PropTypes.string, messages: PropTypes.object, }; export default Toggle;
src/components/Tooltip/Tooltip.js
nolawi/champs-dialog-sg
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import React, { Component } from 'react'; import { Text } from '@dlghq/react-l10n'; import Trigger from '../Trigger/Trigger'; import classNames from 'classnames'; import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'; import styles from './Tooltip.css'; export type Props = { className?: string, children?: any, /** * Tooltip text. Will be translated using @dlghq/react-l10n. */ text: string | React.Element<*>, /** * [Tether options](http://tether.io/#options) */ options?: Object }; class Tooltip extends Component { props: Props; trigger: ?Trigger; componentWillUpdate(): void { if (this.trigger) { this.trigger.forceUpdate(); } } setTrigger = (trigger: ?Trigger): void => { this.trigger = trigger; }; renderContent() { if (typeof this.props.text === 'string') { return ( <Text id={this.props.text} /> ); } return this.props.text; } renderTooltip = () => { return ( <CSSTransitionGroup transitionAppear transitionEnter={false} transitionLeave={false} transitionAppearTimeout={100} transitionName={{ appear: styles.appear, appearActive: styles.appearActive }} > <div className={styles.tooltip}> {this.renderContent()} </div> </CSSTransitionGroup> ); }; renderTrigger = (handlers: Object) => { const className = classNames(styles.wrapper, this.props.className); return ( <div {...handlers} className={className}>{this.props.children}</div> ); }; render() { const options = { attachment: 'bottom center', targetAttachment: 'top center', constraints: [ { to: 'scrollParent', attachment: 'together', pin: true } ], ...this.props.options }; return ( <Trigger options={options} openHandler={['onMouseEnter']} closeHandler={['onMouseLeave']} ref={this.setTrigger} renderTrigger={this.renderTrigger} renderChild={this.renderTooltip} /> ); } } export default Tooltip;
packages/react-devtools-shared/src/hooks/__tests__/__source__/ComponentWithExternalCustomHooks.js
facebook/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import useTheme from './useTheme'; export function Component() { const theme = useTheme(); return <div>theme: {theme}</div>; }
src/svg-icons/social/people-outline.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPeopleOutline = (props) => ( <SvgIcon {...props}> <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"/> </SvgIcon> ); SocialPeopleOutline = pure(SocialPeopleOutline); SocialPeopleOutline.displayName = 'SocialPeopleOutline'; SocialPeopleOutline.muiName = 'SvgIcon'; export default SocialPeopleOutline;