path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/FullOverview.js
sateez/salestracker
import React from 'react'; import PersonalInfoSection from './PersonalInfoSection'; import SalesInfoSection from './SalesInfoSection'; import FullAnalytics from './FullAnalytics'; const FullOverview = ({cars, totalCarsInfo}) => { console.log('fullOverview totalCarsInfo:--->', totalCarsInfo); return ( <div className='col-sm-12 my-audi full-overview'> <div className='col-sm-6'> <PersonalInfoSection /> </div> <div className='col-sm-6'> <SalesInfoSection cars={cars} totalCarsInfo={totalCarsInfo} /> </div> <div className='col-sm-12'> <FullAnalytics cars={cars} /> </div> </div> ) } export default FullOverview;
src/wdui/Text.js
phodal/play-app
import PropTypes from 'prop-types'; import React from 'react'; import {Text, StyleSheet, Platform} from 'react-native'; import fonts from './config/fonts'; import normalize from './helpers/normalizeText'; const styles = StyleSheet.create({ text: { ...Platform.select({ android: { ...fonts.android.regular } }) }, bold: { ...Platform.select({ android: { ...fonts.android.bold } }) } }); const TextElement = props => { const {style, children, h1, h2, h3, h4, fontFamily, ...rest} = props; return ( <Text style={[ styles.text, h1 && {fontSize: normalize(40)}, h2 && {fontSize: normalize(34)}, h3 && {fontSize: normalize(28)}, h4 && {fontSize: normalize(22)}, h1 && styles.bold, h2 && styles.bold, h3 && styles.bold, h4 && styles.bold, fontFamily && {fontFamily}, style && style ]} {...rest} > {children} </Text> ); }; TextElement.propTypes = { style: PropTypes.any, h1: PropTypes.bool, h2: PropTypes.bool, h3: PropTypes.bool, h4: PropTypes.bool, fontFamily: PropTypes.string, children: PropTypes.any }; export default TextElement;
src/svg-icons/communication/present-to-all.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPresentToAll = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z"/> </SvgIcon> ); CommunicationPresentToAll = pure(CommunicationPresentToAll); CommunicationPresentToAll.displayName = 'CommunicationPresentToAll'; CommunicationPresentToAll.muiName = 'SvgIcon'; export default CommunicationPresentToAll;
src/svg-icons/hardware/keyboard-voice.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardVoice = (props) => ( <SvgIcon {...props}> <path d="M12 15c1.66 0 2.99-1.34 2.99-3L15 6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 15 6.7 12H5c0 3.42 2.72 6.23 6 6.72V22h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/> </SvgIcon> ); HardwareKeyboardVoice = pure(HardwareKeyboardVoice); HardwareKeyboardVoice.displayName = 'HardwareKeyboardVoice'; HardwareKeyboardVoice.muiName = 'SvgIcon'; export default HardwareKeyboardVoice;
app/router.js
ashley-jelks-truss/DoDidDone
import React from 'react'; import { Router, Route, browserHistory, IndexRedirect } from 'react-router'; import requireAuth from './utils/requireAuth'; import App from './containers/App'; import TodoListContainer from './containers/TodoListContainer'; import LandingPageContainer from './containers/LandingPageContainer'; import About from './containers/About'; import Help from './containers/Help'; import FAQs from './components/FAQs'; import ContactTab from './components/ContactTab'; export default ( <Router history={browserHistory}> <Route component={App}> <Route path="start" component={LandingPageContainer} /> <Route path="/" component={requireAuth(TodoListContainer)} /> <Route path="about" component={About} /> <Route path="help" component={Help}> <IndexRedirect to="faqs" /> <Route path="faqs" component={FAQs} /> <Route path="contact" component={ContactTab} /> </Route> </Route> </Router> );
src/components/BusListItem.js
one-stop-team/ripta-app
import React from 'react' import { Col, Row } from 'react-bootstrap' import logo from '../images/ripta_logo.png' export default class BusListItem extends React.Component { render() { const { bus } = this.props return ( <Row> <Col xs={12}> Bus {bus.number} </Col> </Row> ) } }
website/Application.js
bvaughn/react-highlight.js
import React from 'react' import HighlightDemo from '../src/Highlight.example' import Highlight from '../src/Highlight' export default class Application extends React.Component { render () { return ( <div> <h1 className='page-header'> react-highlight.js &nbsp; <small> <a href='https://github.com/bvaughn/react-highlight.js'>view in Github</a> </small> </h1> <p className='lead'> A lightweight React wrapper around the&nbsp;<a href='https://highlightjs.org/'>Highlight.js</a>&nbsp;syntaxt highlighting library </p> <h2>Demo</h2> <HighlightDemo /> <h2>Usage</h2> <p>Install react-highlight.js using NPM</p> <Highlight language='bash'> npm install react-highlight.js --save </Highlight> <p>Choose a highlight.js theme and make sure it's included in your index file.</p> <Highlight language='html'> {'<link rel="stylesheet" href="https://highlightjs.org/static/demo/styles/railscasts.css" />'} </Highlight> <p>And then use react-highlight.js to display your text like so:</p> <Highlight language='html'> {`<Highlight language={language}> {content} </Highlight>`} </Highlight> <h2>License</h2> <p>react-highlight.js is available under the MIT License.</p> </div> ) } }
docs/app/Examples/modules/Rating/Types/RatingExampleClearable.js
mohammed88/Semantic-UI-React
import React from 'react' import { Rating } from 'semantic-ui-react' const RatingExampleClearable = () => ( <Rating maxRating={5} clearable /> ) export default RatingExampleClearable
src/components/user.js
voidxnull/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program 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, 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 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, { Component } from 'react'; import { Link } from 'react-router'; import Gravatar from 'react-gravatar'; import moment from 'moment'; import { URL_NAMES, getUrl } from '../utils/urlGenerator'; export default class User extends Component { render () { var { user, hideAvatar, hideText, isRound, avatarSize, timestamp, timestampLink, className } = this.props; var render = {}; render.cn = `user_box ${className}`; let user_url = getUrl(URL_NAMES.USER, { username: user.username }) if (!hideAvatar) { let avatarClassName = 'user_box__avatar'; if (isRound) { avatarClassName += ' user_box__avatar-round'; } render.avatar = ( <Link to={user_url} className={avatarClassName}> <Gravatar md5={user.gravatarHash} size={parseInt(avatarSize, 10)} default="retro" /> </Link> ); } if (!hideText) { let name = user.username; if (user.more && user.more.firstName && user.more.lastName) { name = `${user.more.firstName} ${user.more.lastName}`; } name = name.trim(); if (timestamp.length > 0 && timestampLink.length > 0) { let timestamp_string = moment(timestamp).format('MMMM D, HH:MM'); render.timestamp = <p className="user_box__text"> <Link to={timestampLink}> {timestamp_string} </Link> </p> } render.text = <div className="user_box__body"> <p className="user_box__name"><Link className="link" to={user_url}>{name}</Link></p> {render.timestamp} </div>; } return ( <div className={render.cn}> {render.avatar} {render.text} </div> ) } static propTypes = { user: React.PropTypes.shape({ id: React.PropTypes.string.isRequired, username: React.PropTypes.string.isRequired, avatar: React.PropTypes.string }).isRequired, avatarSize: React.PropTypes.any.isRequired, hideAvatar: React.PropTypes.bool, isRound: React.PropTypes.bool, hideText: React.PropTypes.bool, timestamp: React.PropTypes.string, timestampLink: React.PropTypes.string } static defaultProps = { hideAvatar: false, hideText: false, isRound: false, avatarSize: 24, timestamp: '', timestampLink: '' }; }
proto/data-refining/front/workdir/components/Footer.js
cttgroup/oceanhub
import React from 'react' import FilterLink from '../containers/FilterLink' const Footer = () => ( <p> Show: {' '} <FilterLink filter="SHOW_ALL"> All </FilterLink> {', '} <FilterLink filter="SHOW_ACTIVE"> Active </FilterLink> {', '} <FilterLink filter="SHOW_COMPLETED"> Completed </FilterLink> </p> ) export default Footer
app/javascript/mastodon/features/ui/components/tabs_bar.js
res-ac/mstdn.res.ac
import React from 'react'; import PropTypes from 'prop-types'; import { NavLink, withRouter } from 'react-router-dom'; import { FormattedMessage, injectIntl } from 'react-intl'; import { debounce } from 'lodash'; import { isUserTouching } from '../../../is_mobile'; export const links = [ <NavLink className='tabs-bar__link primary' to='/timelines/home' data-preview-title-id='column.home' data-preview-icon='home' ><i className='fa fa-fw fa-home' /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink>, <NavLink className='tabs-bar__link primary' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><i className='fa fa-fw fa-bell' /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink>, <NavLink className='tabs-bar__link secondary' to='/timelines/public/local' data-preview-title-id='column.community' data-preview-icon='users' ><i className='fa fa-fw fa-users' /><FormattedMessage id='tabs_bar.local_timeline' defaultMessage='Local' /></NavLink>, <NavLink className='tabs-bar__link secondary' exact to='/timelines/public' data-preview-title-id='column.public' data-preview-icon='globe' ><i className='fa fa-fw fa-globe' /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink>, <NavLink className='tabs-bar__link primary' to='/search' data-preview-title-id='tabs_bar.search' data-preview-icon='bell' ><i className='fa fa-fw fa-search' /><FormattedMessage id='tabs_bar.search' defaultMessage='Search' /></NavLink>, <NavLink className='tabs-bar__link primary' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started' data-preview-title-id='getting_started.heading' data-preview-icon='bars' ><i className='fa fa-fw fa-bars' /></NavLink>, ]; export function getIndex (path) { return links.findIndex(link => link.props.to === path); } export function getLink (index) { return links[index].props.to; } @injectIntl @withRouter export default class TabsBar extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, history: PropTypes.object.isRequired, } setRef = ref => { this.node = ref; } handleClick = (e) => { // Only apply optimization for touch devices, which we assume are slower // We thus avoid the 250ms delay for non-touch devices and the lag for touch devices if (isUserTouching()) { e.preventDefault(); e.persist(); requestAnimationFrame(() => { const tabs = Array(...this.node.querySelectorAll('.tabs-bar__link')); const currentTab = tabs.find(tab => tab.classList.contains('active')); const nextTab = tabs.find(tab => tab.contains(e.target)); const { props: { to } } = links[Array(...this.node.childNodes).indexOf(nextTab)]; if (currentTab !== nextTab) { if (currentTab) { currentTab.classList.remove('active'); } const listener = debounce(() => { nextTab.removeEventListener('transitionend', listener); this.props.history.push(to); }, 50); nextTab.addEventListener('transitionend', listener); nextTab.classList.add('active'); } }); } } render () { const { intl: { formatMessage } } = this.props; return ( <nav className='tabs-bar' ref={this.setRef}> {links.map(link => React.cloneElement(link, { key: link.props.to, onClick: this.handleClick, 'aria-label': formatMessage({ id: link.props['data-preview-title-id'] }) }))} </nav> ); } }
src/icons/KitchenIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class KitchenIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M36 4.02L12 4C9.79 4 8 5.79 8 8v32c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V8c0-2.21-1.79-3.98-4-3.98zM36 40H12V21.95h24V40zm0-22H12V8h24v10zm-20-8h4v6h-4zm0 14h4v10h-4z"/></svg>;} };
webpack/scenes/RedHatRepositories/components/RepositorySet.js
adamruzicka/katello
import React from 'react'; import PropTypes from 'prop-types'; import { ListView, Icon } from 'patternfly-react'; import RepositoryTypeIcon from './RepositoryTypeIcon'; import RepositorySetRepositories from './RepositorySetRepositories'; const RepositorySet = ({ type, id, name, label, product, recommended, }) => ( <ListView.Item id={id} className="listViewItem--listItemVariants" description={label} heading={name} leftContent={<RepositoryTypeIcon id={id} type={type} />} stacked actions={recommended ? <Icon type="fa" name="star" className="recommended-repository-set-icon" /> : ''} hideCloseIcon > <RepositorySetRepositories contentId={id} productId={product.id} type={type} label={label} /> </ListView.Item> ); RepositorySet.propTypes = { id: PropTypes.number.isRequired, type: PropTypes.string.isRequired, name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, product: PropTypes.shape({ name: PropTypes.string.isRequired, id: PropTypes.number.isRequired, }).isRequired, recommended: PropTypes.bool, }; RepositorySet.defaultProps = { recommended: false, }; export default RepositorySet;
src/Parser/Hunter/Marksmanship/Modules/Traits/LegacyOfTheWindrunners.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from "common/SpellIcon"; import SpellLink from "common/SpellLink"; import ItemDamageDone from 'Main/ItemDamageDone'; /** * Aimed Shot has a chance to coalesce 6 extra Wind Arrows that also shoot your target. */ class LegacyOfTheWindrunners extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; on_initialized() { this.active = this.combatants.selected.traitsBySpellId[SPELLS.LEGACY_OF_THE_WINDRUNNERS_TRAIT.id]; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.LEGACY_OF_THE_WINDRUNNERS_DAMAGE.id) { return; } this.damage += event.amount + (event.absorbed || 0); } subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.LEGACY_OF_THE_WINDRUNNERS_TRAIT.id}> <SpellIcon id={SPELLS.LEGACY_OF_THE_WINDRUNNERS_TRAIT.id} noLink /> Legacy </SpellLink> </div> <div className="flex-sub text-right"> <ItemDamageDone amount={this.damage} /> </div> </div> ); } } export default LegacyOfTheWindrunners;
src/svg-icons/notification/event-available.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationEventAvailable = (props) => ( <SvgIcon {...props}> <path d="M16.53 11.06L15.47 10l-4.88 4.88-2.12-2.12-1.06 1.06L10.59 17l5.94-5.94zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/> </SvgIcon> ); NotificationEventAvailable = pure(NotificationEventAvailable); NotificationEventAvailable.displayName = 'NotificationEventAvailable'; NotificationEventAvailable.muiName = 'SvgIcon'; export default NotificationEventAvailable;
app/components/ShippingCostsButton.js
Byte-Code/lm-digitalstore
/* eslint-disable */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import glamorous from 'glamorous'; import ShippingDialog from './ShippingDialog'; export default class ShippingCostsButton extends Component { constructor(props) { super(props); this.toggleDialog = this.toggleDialog.bind(this); this.state = { showDialog: false } } toggleDialog() { this.setState({ showDialog: !this.state.showDialog }); } renderDialog() { const { showDialog } = this.state; const { productInfo } = this.props; const shippingProps = { open: showDialog, toggleOpen: this.toggleDialog, productInfo }; return <ShippingDialog {...shippingProps} />; } render() { const { label, logo } = this.props; const { showDialog } = this.state; return ( <ButtonWrapper onClick={this.toggleDialog}> <IconContainer> <span className={logo} /> </IconContainer> <LabelContainer>{label}</LabelContainer> { showDialog && this.renderDialog()} </ButtonWrapper> ); } } ShippingCostsButton.propsTypes = { productInfo: PropTypes.shape({ name: PropTypes.string, code: PropTypes.string }).isRequired, label: PropTypes.string, logo: PropTypes.string }; ShippingCostsButton.defaultProps = { label: 'Calcola costo di spedizione', logo: 'truck' }; const ButtonWrapper = glamorous.div({ display: 'flex', flexDirection: 'row', marginTop: '4%' }); const LabelContainer = glamorous.p({ fontSize: '1.2em', textDecoration: 'underline', textAlign: 'left', marginLeft: '4%' }); const IconContainer = glamorous.div({ marginTop: '-11px' });
react/examples/Code/Prop_Types/src/index.js
jsperts/workshop_unterlagen
import React from 'react'; import { render } from 'react-dom'; import App from './App'; const list = [ { id: 1, title: 'Element 1' }, { id: 2, title: 'Element 2' }, { id: '3', title: 'Element 3' }, { id: 4 }, ]; render(<App list={list} />, document.getElementById('root'));
public/js/components/chat/ChatPrevious.react.js
rajikaimal/Coupley
import React from 'react'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import Colors from 'material-ui/lib/styles/colors'; import IconButton from 'material-ui/lib/icon-button'; import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/lib/menus/icon-menu'; import MenuItem from 'material-ui/lib/menus/menu-item'; import ThreadActions from '../../actions/Thread/ThreadActions'; import ThreadStore from '../../stores/ThreadStore'; import FlatButton from 'material-ui/lib/flat-button'; import Dialog from 'material-ui/lib/dialog'; import PaperExampleSimple from './Messages.react'; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={Colors.grey400} /> </IconButton> ); const ListStyle = { width: 300, }; const PreviousChat = React.createClass({ handleOpen: function () { this.setState({ open: true }); }, handleClose: function () { this.setState({ open: false }); }, getInitialState: function () { return { results:ThreadStore.getThreadMessage(), open: false, }; }, componentDidMount: function () { ThreadStore.addChangeListener(this._onChange); }, _onChange: function () { this.setState({results:ThreadStore.getThreadMessage()}); }, deleteconvo:function () { var user2 = this.props.thread_id; let deleteM = { user2:user2, user1:localStorage.getItem('username'), }; ThreadActions.deleteM(deleteM); console.log('Done deleting!'); }, getMessage:function () { let threadData = { threadId: this.props.id, }; ThreadActions.getMessage(threadData); return this.state.results.map((result) => { return (<Paper ExampleSimple key={result.thread_id} id={result.thread_id} firstname={result.firstname} message={result.message} created_at={result.created_at}/>); }); }, render:function () { const actions = [ <FlatButton label="No" secondary={true} onTouchTap={this.handleClose} />, <FlatButton label="Yes" primary={true} keyboardFocused={true} onTouchTap={this.deleteconvo} />, ]; return ( <List style={ListStyle}> <ListItem leftAvatar={<Avatar src={'img/profilepics/'+this.props.username} /> } rightIconButton={<IconMenu iconButtonElement={iconButtonElement}> <MenuItem onTouchTap={this.handleOpen}>Delete</MenuItem> </IconMenu> } onTouchTap={this.getMessage} primaryText={this.props.firstname} secondaryText={ <p> <span style={ { color: Colors.darkBlack } }>{this.props.message}</span><br/> { this.props.created_at } </p> } secondaryTextLines={2}/> <Divider inset={false} /> <Dialog title="Delete Conversation" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose}> Are you sure you want to delete this conversation?. </Dialog> </List> ); }, }); export default PreviousChat;
src/content/Skill.js
ericshortcut/ericshortcut.github.io
import React from 'react'; export default function content({ title, skillList }) { return ( <div className="skill"> {title}: <ul className="skill-list"> { skillList.map(skill => <li className="skill-list-item" key={skill.split(' ').join('-')}> <span className="badge"> {skill} </span> </li> ) } </ul> </div> ); }
src/containers/DevToolsWindow.js
daimagine/gh-milestone
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' export default createDevTools( <LogMonitor /> )
app/javascript/mastodon/features/video/index.js
mhffdq/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { throttle } from 'lodash'; import classNames from 'classnames'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen'; import { displaySensitiveMedia } from '../../initial_state'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, hide: { id: 'video.hide', defaultMessage: 'Hide video' }, expand: { id: 'video.expand', defaultMessage: 'Expand video' }, close: { id: 'video.close', defaultMessage: 'Close video' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, }); const formatTime = secondsNum => { let hours = Math.floor(secondsNum / 3600); let minutes = Math.floor((secondsNum - (hours * 3600)) / 60); let seconds = secondsNum - (hours * 3600) - (minutes * 60); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`; }; export const findElementPosition = el => { let box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0, }; } const docEl = document.documentElement; const body = document.body; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const scrollLeft = window.pageXOffset || body.scrollLeft; const left = (box.left + scrollLeft) - clientLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const scrollTop = window.pageYOffset || body.scrollTop; const top = (box.top + scrollTop) - clientTop; return { left: Math.round(left), top: Math.round(top), }; }; export const getPointerPosition = (el, event) => { const position = {}; const box = findElementPosition(el); const boxW = el.offsetWidth; const boxH = el.offsetHeight; const boxY = box.top; const boxX = box.left; let pageY = event.pageY; let pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; }; @injectIntl export default class Video extends React.PureComponent { static propTypes = { preview: PropTypes.string, src: PropTypes.string.isRequired, alt: PropTypes.string, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, startTime: PropTypes.number, onOpenVideo: PropTypes.func, onCloseVideo: PropTypes.func, detailed: PropTypes.bool, inline: PropTypes.bool, intl: PropTypes.object.isRequired, }; state = { currentTime: 0, duration: 0, paused: true, dragging: false, containerWidth: false, fullscreen: false, hovered: false, muted: false, revealed: !this.props.sensitive || displaySensitiveMedia, }; setPlayerRef = c => { this.player = c; if (c) { this.setState({ containerWidth: c.offsetWidth, }); } } setVideoRef = c => { this.video = c; } setSeekRef = c => { this.seek = c; } handlePlay = () => { this.setState({ paused: false }); } handlePause = () => { this.setState({ paused: true }); } handleTimeUpdate = () => { this.setState({ currentTime: Math.floor(this.video.currentTime), duration: Math.floor(this.video.duration), }); } handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove, true); document.addEventListener('mouseup', this.handleMouseUp, true); document.addEventListener('touchmove', this.handleMouseMove, true); document.addEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: true }); this.video.pause(); this.handleMouseMove(e); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove, true); document.removeEventListener('mouseup', this.handleMouseUp, true); document.removeEventListener('touchmove', this.handleMouseMove, true); document.removeEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: false }); this.video.play(); } handleMouseMove = throttle(e => { const { x } = getPointerPosition(this.seek, e); const currentTime = Math.floor(this.video.duration * x); this.video.currentTime = currentTime; this.setState({ currentTime }); }, 60); togglePlay = () => { if (this.state.paused) { this.video.play(); } else { this.video.pause(); } } toggleFullscreen = () => { if (isFullscreen()) { exitFullscreen(); } else { requestFullscreen(this.player); } } componentDidMount () { document.addEventListener('fullscreenchange', this.handleFullscreenChange, true); document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } componentWillUnmount () { document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } handleFullscreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } handleMouseEnter = () => { this.setState({ hovered: true }); } handleMouseLeave = () => { this.setState({ hovered: false }); } toggleMute = () => { this.video.muted = !this.video.muted; this.setState({ muted: this.video.muted }); } toggleReveal = () => { if (this.state.revealed) { this.video.pause(); } this.setState({ revealed: !this.state.revealed }); } handleLoadedData = () => { if (this.props.startTime) { this.video.currentTime = this.props.startTime; this.video.play(); } } handleProgress = () => { if (this.video.buffered.length > 0) { this.setState({ buffer: this.video.buffered.end(0) / this.video.duration * 100 }); } } handleOpenVideo = () => { this.video.pause(); this.props.onOpenVideo(this.video.currentTime); } handleCloseVideo = () => { this.video.pause(); this.props.onCloseVideo(); } render () { const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed } = this.props; const { containerWidth, currentTime, duration, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const progress = (currentTime / duration) * 100; const playerStyle = {}; let { width, height } = this.props; if (inline && containerWidth) { width = containerWidth; height = containerWidth / (16/9); playerStyle.width = width; playerStyle.height = height; } return ( <div className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen })} style={playerStyle} ref={this.setPlayerRef} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <video ref={this.setVideoRef} src={src} poster={preview} preload={startTime ? 'auto' : 'none'} loop role='button' tabIndex='0' aria-label={alt} width={width} height={height} onClick={this.togglePlay} onPlay={this.handlePlay} onPause={this.handlePause} onTimeUpdate={this.handleTimeUpdate} onLoadedData={this.handleLoadedData} onProgress={this.handleProgress} /> <button type='button' className={classNames('video-player__spoiler', { active: !revealed })} onClick={this.toggleReveal}> <span className='video-player__spoiler__title'><FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /></span> <span className='video-player__spoiler__subtitle'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> <div className={classNames('video-player__controls', { active: paused || hovered })}> <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> <div className='video-player__seek__progress' style={{ width: `${progress}%` }} /> <span className={classNames('video-player__seek__handle', { active: dragging })} tabIndex='0' style={{ left: `${progress}%` }} /> </div> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay}><i className={classNames('fa fa-fw', { 'fa-play': paused, 'fa-pause': !paused })} /></button> <button type='button' aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><i className={classNames('fa fa-fw', { 'fa-volume-off': muted, 'fa-volume-up': !muted })} /></button> {!onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><i className='fa fa-fw fa-eye' /></button>} {(detailed || fullscreen) && <span> <span className='video-player__time-current'>{formatTime(currentTime)}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(duration)}</span> </span> } </div> <div className='video-player__buttons right'> {(!fullscreen && onOpenVideo) && <button type='button' aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><i className='fa fa-fw fa-expand' /></button>} {onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><i className='fa fa-fw fa-compress' /></button>} <button type='button' aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} onClick={this.toggleFullscreen}><i className={classNames('fa fa-fw', { 'fa-arrows-alt': !fullscreen, 'fa-compress': fullscreen })} /></button> </div> </div> </div> </div> ); } }
src/svg-icons/action/language.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLanguage = (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 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z"/> </SvgIcon> ); ActionLanguage = pure(ActionLanguage); ActionLanguage.displayName = 'ActionLanguage'; ActionLanguage.muiName = 'SvgIcon'; export default ActionLanguage;
src/popup/app/components/Boobs/Post/BoobsCreatePost.js
BoomBoobs/chrome-extension
import React from 'react'; import cx from 'classnames'; import { props, pure, skinnable, t } from 'revenge'; import App from '../../../../BoomBoobsApp'; import Select from 'react-select'; import { includes } from 'lodash'; import { FlexView, LoadingSpinner } from 'Basic'; import 'buildo-react-components/src/loading-spinner/style.scss'; import 'react-select/dist/default.css'; import './boobsCreatePost.scss'; const initialState = { isBoobsFileChosen: false, addNewBoobsOwner: false, boobsPostCreated: false, loading: false, form: { boobsOwner: { id: null, firstName: null, lastName: null, website: null } } }; @skinnable() @pure @props({ app: App, boobsFile: t.maybe(t.Obj), prepareBoobsFile: t.Func, createBoobsPost: t.Func, boobsOwners: t.maybe(t.list(t.Obj)), boobsOwnersLoading: t.Bool }) export default class BoobsCreatePost extends React.Component { constructor(props) { super(props); this.state = initialState; } // POST CREATION onSubmit = (e) => { e.preventDefault(); this.setState({ loading: true }, () => { const { boobsOwner } = this.state.form; this.props.createBoobsPost(this.props.boobsFile.file, boobsOwner) .then(() => { // be VERY optimistic this.setState(initialState); }); }); } togglAddNewBoobsOwner = () => { this.setState({ addNewBoobsOwner: !this.state.addNewBoobsOwner, form: initialState.form }); } onBoobsFileChange = (e) => { this.props.prepareBoobsFile(e.target.files[0]); } isValidSelectedBoobsOwner = () => { const { id } = this.state.form.boobsOwner; return !!id; } isValidNewBoobsOwner = () => { const { firstName, lastName } = this.state.form.boobsOwner; return !!firstName && !!lastName; } bindBoobsOwnerKey = (key) => (e) => this.updateBoobsOwner(key, e.target.value) onBoobOwnerChange = (id) => this.updateBoobsOwner('id', id) updateBoobsOwner = (key, value) => { const boobsOwner = { ...this.state.form.boobsOwner, [key]: value }; this.setState({ form: { boobsOwner } }); } getLocals() { const { onBoobsFileChange, onBoobOwnerChange, onBoobsFileSubmit, isValidNewBoobsOwner, isValidSelectedBoobsOwner, onSubmit, props, state } = this; const { isBoobsFileChosen, addNewBoobsOwner, loading, form: { boobsOwner } } = state; const { boobsFile, boobsOwners, boobsOwnersLoading } = props; const boobsOwnersOptions = boobsOwners ? boobsOwners.map(bo => ({ value: bo.id, label: `${bo.get('firstName')} ${bo.get('lastName')}` })) : []; const boomBoobsPostCreationEnabled = isValidSelectedBoobsOwner() || isValidNewBoobsOwner(); const createButtonClasses = cx('create-post', { disabled: !boomBoobsPostCreationEnabled }); return { form: { boobsOwner }, loading, onSubmit: boomBoobsPostCreationEnabled && onSubmit, togglAddNewBoobsOwner: this.togglAddNewBoobsOwner, boobsFile, addNewBoobsOwner, boobsOwnersOptions, boobsOwnersLoading, bindBoobsOwnerKey: this.bindBoobsOwnerKey, onBoobOwnerChange, filterOptions: (options = [], filter) => options.filter(o => includes(o.label.toLowerCase(), filter.toLowerCase())), onBoobsFileChange, onBoobsFileSubmit: isBoobsFileChosen && onBoobsFileSubmit, createButtonClasses }; } template(locals) { const uploadBoobsFileBlock = () => ( <div className='boob-file'> <label htmlFor='boobsFile'>Choose the boobs to uplaod:</label> <FlexView grow row vAlignContent='center'> <FlexView column> <input ref='boobsFile' type='file' name='boobsFile' onChange={locals.onBoobsFileChange} accept='image/*' /> </FlexView> </FlexView> </div> ); const boobsOwnerBlock = () => ( <div> <img src={locals.boobsFile && locals.boobsFile.url} /> <FlexView column grow className='boobs-owner'> {!locals.addNewBoobsOwner ? ( <FlexView column grow> <h3>Select boobs owner!</h3> {!locals.boobsOwnersLoading && ( <Select options={locals.boobsOwnersOptions} filterOptions={locals.filterOptions} onChange={locals.onBoobOwnerChange} value={locals.form && locals.form.boobsOwner.id} placeholder={"Who is the owner of those boobs?"} /> )} </FlexView> ) : ( <FlexView column grow> <h3>New boobs owner</h3> <div> <label>Firstname</label> <input type='text' onChange={locals.bindBoobsOwnerKey('firstName')} value={locals.form.boobsOwner.firstName} /> </div> <div> <label>Lastname</label> <input type='text' onChange={locals.bindBoobsOwnerKey('lastName')} value={locals.form.boobsOwner.lastName} /> </div> <div> <label>Website (if any)</label> <input type='text' onChange={locals.bindBoobsOwnerKey('website')} value={locals.form.boobsOwner.website} /> </div> </FlexView> )} <label> Or <a onClick={locals.togglAddNewBoobsOwner}>{locals.addNewBoobsOwner ? 'choose' : 'add'}</a> a boobs owner! </label> </FlexView> </div> ); return ( <form className='boobs-post-create-form' onSubmit={locals.onSubmit}> {!locals.boobsFile && uploadBoobsFileBlock()} {locals.boobsFile && boobsOwnerBlock()} {locals.boobsFile && ( <button className={locals.createButtonClasses} onClick={locals.onSubmit} > Create BoobsPost! </button> )} {locals.loading && <LoadingSpinner size='20px' />} </form> ); } }
src/components/EditorItem.js
casesandberg/squash
'use strict'; import React from 'react'; import ReactCSS from 'reactcss'; // import SVGO from 'svgo'; // const convertSVG = new SVGO(); class EditorItem extends React.Component { classes() { return { 'default': { asset: { Absolute: '0 0 0 0', display: 'flex', alignItems: 'center', justifyContent: 'center', }, toolbar: { Absolute: 'null 0 0 0', }, }, }; } render() { return ( <div> <div is="asset"> <div dangerouslySetInnerHTML={{ __html: this.props.svg }} /> </div> <div is="toolbar"> <input defaultValue={ this.props.name } /> </div> </div> ); } } export default ReactCSS(EditorItem);
src/svg-icons/communication/chat.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationChat = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 9h12v2H6V9zm8 5H6v-2h8v2zm4-6H6V6h12v2z"/> </SvgIcon> ); CommunicationChat = pure(CommunicationChat); CommunicationChat.displayName = 'CommunicationChat'; CommunicationChat.muiName = 'SvgIcon'; export default CommunicationChat;
src/Gandalf/components/buttons.js
mrpotatoes/react-gandalf
import React from 'react' import PropTypes from 'prop-types' import SaveButton from 'Gandalf/components/saveButton' import ExitButton from 'Gandalf/components/cancelButton' /* eslint-disable */ const Bottons = ({ buttons, fn, save, cancel }) => ( <div className="gandalf-buttons"> <For each="item" index="idx" of={buttons}> <If condition={item.condition}> <button className="waves-effect waves-light btn" key={idx} type="button" onClick={item.fn}>{item.text}</button> </If> </For> <ExitButton condition={cancel.condtion} fn={cancel.cancelGandalf} /> <SaveButton condition={save.condition} fn={save.saveStep} /> </div> ) Bottons.propTypes = { buttons: PropTypes.object.isRequired, fn: PropTypes.object.isRequired, save: PropTypes.object.isRequired, cancel: PropTypes.object.isRequired, }; export default Bottons
app/components/views/todo-filter.js
joawan/todo-ui-react
import React from 'react'; import style from 'todomvc-app-css/index.css'; import classNames from 'classnames'; function TodoFilter(props) { return ( <div> <footer className={style.footer}> <span className={style.todoCount}> <strong>{props.count}</strong> left </span> <ul className={style.filters}> <li> <a href="#/" className={ classNames({ [style.selected]: true }) }> All </a> </li> {' '} <li> <a href="#/active" className={ classNames({ [style.selected]: false }) }> Active </a> </li> {' '} <li> <a href="#/completed" className={ classNames({ [style.selected]: false }) }> Completed </a> </li> </ul> </footer> </div> ); } TodoFilter.propTypes = { count: React.PropTypes.number.isRequired, }; export default TodoFilter;
client/components/settings/bank-accesses/confirm-delete-access.js
bnjbvr/kresus
import React from 'react'; import { connect } from 'react-redux'; import { displayLabel, translate as $t } from '../../../helpers'; import { get, actions } from '../../../store'; import { registerModal } from '../../ui/modal'; import ModalContent from '../../ui/modal/content'; import CancelAndDelete from '../../ui/modal/cancel-and-delete-buttons'; export const DELETE_ACCESS_MODAL_SLUG = 'confirm-delete-access'; const ConfirmDeleteModal = connect( state => { let accessId = get.modal(state).state; let access = get.accessById(state, accessId); let title = access ? access.title : null; let customLabel = access ? access.customLabel : null; return { title, customLabel, accessId }; }, dispatch => { return { deleteAccess(accessId) { actions.deleteAccess(dispatch, accessId); } }; }, ({ title, customLabel, accessId }, { deleteAccess }) => { return { title, customLabel, handleDelete() { deleteAccess(accessId); } }; } )(props => { return ( <ModalContent title={$t('client.confirmdeletemodal.title')} body={$t('client.settings.erase_access', { name: displayLabel(props) })} footer={<CancelAndDelete onDelete={props.handleDelete} />} /> ); }); registerModal(DELETE_ACCESS_MODAL_SLUG, () => <ConfirmDeleteModal />);
src/Adress.js
icaropires/Interlogex
import React from 'react'; import { Link } from 'react-router-dom'; import { Grid,Icon, Tooltip } from 'react-mdl'; import 'mdi/css/materialdesignicons.min.css'; export default class Adress extends React.Component { render(){ return ( <div className="contact-container-item"> <div className="home-subsubtitle"><span>Endereço</span></div> <div className="card-contact"> <Icon name="home" style={{marginRight: '10px', top: '3px', position: 'relative'}}/> SHVP Rua 10 Chácara 177 Casa 08 Condomínio Alphaville - Vicente Pires - DF </div> </div> ); } }
src/svg-icons/file/folder-open.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileFolderOpen = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z"/> </SvgIcon> ); FileFolderOpen = pure(FileFolderOpen); FileFolderOpen.displayName = 'FileFolderOpen'; FileFolderOpen.muiName = 'SvgIcon'; export default FileFolderOpen;
src/containers/Landing.js
AlexeySmolyakov/likeometer-redux
import React from 'react'; import API from 'api'; import splash02 from 'assets/splash-02.svg'; import splash03 from 'assets/splash-03.svg'; import splash04 from 'assets/splash-04.svg'; import splash05 from 'assets/splash-05.svg'; import splash06 from 'assets/splash-06.svg'; import splash07 from 'assets/splash-07.svg'; import likeometer from 'assets/likeometer.svg'; const getRandomImage = () => { const images = [ splash02, splash03, splash04, splash05, splash06, splash07, ]; const min = 0; const max = images.length - 1; const previewIndex = Math.floor(Math.random() * (max - min + 1)) + min; return images[previewIndex]; }; const Landing = () => { const onLoginClick = () => { API.auth.login(); }; return ( <div className="landing"> <div className="likeometer"> <img src={likeometer} alt="" /> </div> <div className="preview"> <img src={getRandomImage()} alt="Likeometer" /> </div> <div className="login-button"> <button type="button" onClick={onLoginClick}> Войти через <i className="fa fa-vk" /> </button> </div> </div> ); }; export default Landing;
app/javascript/mastodon/features/standalone/public_timeline/index.js
codl/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { refreshPublicTimeline, expandPublicTimeline, } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { defineMessages, injectIntl } from 'react-intl'; import { connectPublicStream } from '../../../actions/streaming'; const messages = defineMessages({ title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' }, }); @connect() @injectIntl export default class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch } = this.props; dispatch(refreshPublicTimeline()); this.disconnect = dispatch(connectPublicStream()); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = () => { this.props.dispatch(expandPublicTimeline()); } render () { const { intl } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='globe' title={intl.formatMessage(messages.title)} onClick={this.handleHeaderClick} /> <StatusListContainer timelineId='public' loadMore={this.handleLoadMore} scrollKey='standalone_public_timeline' trackScroll={false} /> </Column> ); } }
src/app/d3components/piechart/PieChart.js
cox-auto-kc/react-d3-responsive
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import d3 from 'd3'; import Legend from '../utilities/legend'; class PieChart extends React.Component { constructor(props) { super(props); this.state = { width: this.props.width, height: this.props.height }; } componentDidMount() { this.repaintComponent(); window.addEventListener('resize', this.updateSize, false); } componentWillUnmount() { window.removeEventListener('resize', this.updateSize, false); } updateSize = () => { const node = ReactDOM.findDOMNode(this); const parentWidth = node.offsetWidth; (parentWidth < this.props.width) ? this.setState({ width: parentWidth, height: parentWidth }) : this.setState({ width: this.props.width, height: this.props.height }); }; repaintComponent() { const forceResize = this.updateSize; function onRepaint(callback){ setTimeout(function(){ window.requestAnimationFrame(callback); }, 0); } onRepaint(forceResize); } createChart(_self) { if (this.props.colors) { this.color = d3.scale.ordinal() .range(this.props.colors); } else { this.color = d3.scale.category10(); } let pieHeight = _self.state.height; let pieWidth; if (_self.props.width < _self.state.width) { pieWidth = _self.props.width; } else { pieWidth = _self.state.width; pieHeight = _self.props.width; } let diameter; if (pieHeight < pieWidth) { diameter = pieHeight; } else { diameter = pieWidth; } const radius = diameter/2; const outerRadius = radius; const innerRadius = _self.props.innerRadiusRatio ? radius*_self.props.innerRadiusRatio : 0; const startAngle = _self.degreesToRadians(_self.props.startAngle); const endAngle = _self.degreesToRadians(_self.props.endAngle); this.arc = d3.svg.arc() .outerRadius(outerRadius) .innerRadius(innerRadius); this.pie = d3.layout.pie() .startAngle(startAngle) .endAngle(endAngle) .value(function (d) { return d[_self.props.valueKey]; }); if (this.props.pieSort) { this.pie.sort(null); } this.transform = 'translate(' + radius + ',' + radius + ')'; } degreesToRadians(d) { return (Math.PI/180)*d; } render() { this.createChart(this); const _self = this; const wedge = _self.pie(this.props.data).map(function(d,i) { const fill = _self.color(i); const centroid = _self.arc.centroid(d); const labelOffset = _self.props.labelOffset; const label = "translate(" + centroid[0]*labelOffset +"," + centroid[1]*labelOffset + ")"; return ( <g key={i}> <path fill={fill} d={_self.arc(d)} /> {_self.props.showLabel ? <text transform={label} textAnchor="middle"> {d.data[_self.props.valueKey]} </text> : null} </g> ); }); let customClassName = ""; if(this.props.chartClassName){ customClassName = " " + this.props.chartClassName; } return( <div> {this.props.title && <h3>{this.props.title}</h3>} <svg className={"rd3r-chart rd3r-pie-chart" + customClassName} id={this.props.chartId} width={this.state.width} height={this.state.height}> <g transform={this.transform}> {wedge} </g> </svg> {this.props.legend && <Legend data={this.props.data} labelKey={this.props.labelKey} colors={this.color} />} </div> ); } } PieChart.propTypes = { title: React.PropTypes.string, width: React.PropTypes.number, height: React.PropTypes.number, chartId: React.PropTypes.string, chartClassName: React.PropTypes.string, colors: React.PropTypes.array, data: React.PropTypes.array, valueKey: React.PropTypes.string, labelKey: React.PropTypes.string, showLabel: React.PropTypes.bool, pieSort: React.PropTypes.bool, labelOffset: React.PropTypes.number, startAngle: React.PropTypes.number, endAngle: React.PropTypes.number, innerRadiusRatio: React.PropTypes.number, legend: React.PropTypes.bool }; PieChart.defaultProps = { width: 300, height: 300, data: [], valueKey: "value", labelKey: "label", showLabel: true, labelOffset: 1, startAngle: 0, endAngle: 360, margin: { top: 50, right: 50, bottom: 50, left: 50 }, legend: true }; export default PieChart;
src/docs/examples/EyeIcon/Example.js
peadar33/react-component
import React from 'react'; import EyeIcon from 'ps-react/EyeIcon'; export default function EyeIconExample() { return <EyeIcon />; }
src/index.js
sean-m-mccullough/ReduxSimpleStarter
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
src/components/Views/ServicesSingle/index.js
jmikrut/keen-2017
import React, { Component } from 'react'; import ViewWrap from '../../ViewWrap'; import DocumentMeta from 'react-document-meta'; import ServicesContinue from '../../ServicesContinue'; import ProjectCTA from '../../Elements/ProjectCTA'; import servicesContent from '../../../content/services'; import PageNotFound from '../PageNotFound'; import ogImage from '../../../assets/og-image.jpg'; import './ServicesSingle.css'; class ServicesSingle extends Component { constructor(props) { super(props); this.active = this.props.service; this.servicesIndex = 0; this.service = servicesContent.find( (el, i) => { this.servicesIndex = i; return el.slug === this.active; }); this.prevService = servicesContent[(this.servicesIndex !== 0 ? this.servicesIndex - 1 : servicesContent.length - 1)]; this.nextService = servicesContent[(this.servicesIndex !== servicesContent.length - 1 ? this.servicesIndex + 1 : 0)] } shouldComponentUpdate(nextProps, nextState) { return false; } render() { if (this.service) { let Component = this.service.component; const meta = { title: `${this.service.title} - Keen Studio`, description: this.service.description, meta: { name: { keywords: this.service.keywords, 'twitter:image:alt': `An image representing ${this.service.title}.` }, property: { 'og:title': `Keen Studio - ${this.service.title}`, 'og:description': this.service.description, 'og:image': this.service.bg, 'og:url': window.location.href } } } return ( <ViewWrap view="services-single"> <DocumentMeta {...meta} /> <label data-animate="1" className={`title ${this.service.slug}`}>{this.service.title}</label> <Component service={this.service} /> <ProjectCTA color={this.service.slug} /> <ServicesContinue prev={this.prevService} next={this.nextService} /> </ViewWrap> ); } else { return <PageNotFound /> } } } export default ServicesSingle;
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-forms-v3-basic-form.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, SectionMixin} from './../common/common.js'; import {Button} from './../bricks/bricks.js'; import FormMixin from './mixins/form-mixin.js'; import './basic-form.less'; export const BasicForm = React.createClass({ mixins: [ BaseMixin, ElementaryMixin, SectionMixin, FormMixin ], statics: { tagName: 'UU5.Forms.BasicForm', classNames: { main: 'uu5-forms-basic-form', buttons: 'uu5-forms-basic-form-buttons', submit: 'uu5-forms-basic-form-submit-button', reset: 'uu5-forms-basic-form-reset-button', cancel: 'uu5-forms-basic-form-cancel-button' } }, propTypes: { // TODO not supported vertical and inline style: React.PropTypes.oneOf(['horizontal', 'vertical', 'inline']), ignoreValidation: React.PropTypes.bool, submitLabel: React.PropTypes.string, resetLabel: React.PropTypes.string, cancelLabel: React.PropTypes.string, onSubmit: React.PropTypes.func, onReset: React.PropTypes.func, onCancel: React.PropTypes.func, submitColorSchema: React.PropTypes.string, resetColorSchema: React.PropTypes.string, cancelColorSchema: React.PropTypes.string }, // Setting defaults getDefaultProps: function () { return { style: 'horizontal', ignoreValidation: false, submitLabel: null, resetLabel: null, cancelLabel: null, onSubmit: null, onReset: null, onCancel: null, submitColorSchema: null, resetColorSchema: null, cancelColorSchema: null }; }, // Interface // Component Specific Helpers _onSubmit: function (e) { if (this.props.ignoreValidation || this.isValid()) { typeof this.props.onSubmit === 'function' && this.props.onSubmit(this, e); } else { // TODO throw some error? } }, _onReset: function (e) { if (typeof this.props.onReset === 'function') { this.props.onReset(this, e); } else { this.reset(); } }, _onCancel: function (e) { typeof this.props.onCancel === 'function' && this.props.onCancel(this, e); }, _getMainAttrs: function() { var mainAttrs = this.buildMainAttrs(); mainAttrs.className += ' form-' + this.props.style; return mainAttrs; }, // Render render: function () { return ( <form {...this._getMainAttrs()}> {this.getHeaderChild()} {this.getChildren()} <div className={this.getClassName().buttons}> {this.props.submitLabel && <Button content={this.props.submitLabel} className={this.getClassName().submit} colorSchema={this.props.submitColorSchema || 'success'} onClick={this._onSubmit} />} {this.props.resetLabel && <Button content={this.props.resetLabel} className={this.getClassName().reset} colorSchema={this.props.resetColorSchema || 'primary'} onClick={this._onReset} />} {this.props.cancelLabel && <Button content={this.props.cancelLabel} className={this.getClassName().cancel} colorSchema={this.props.cancelColorSchema || 'default'} onClick={this._onCancel} />} </div> {this.getFooterChild()} {this.getDisabledCover()} </form> ); } }); export default BasicForm;
src/index.js
shuichitakano/ymf825playFA
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; //import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); //registerServiceWorker();
addons/comments/src/manager/components/CommentForm/index.js
enjoylife/storybook
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { window } from 'global'; import Textarea from 'react-textarea-autosize'; import marked from 'marked'; import style from './style'; const renderer = new marked.Renderer(); renderer.heading = text => text; marked.setOptions({ renderer, gfm: true, tables: false, breaks: true, pedantic: false, sanitize: true, smartLists: true, smartypants: false, }); export default class CommentForm extends Component { constructor(props, ...args) { super(props, ...args); this.state = { text: '' }; } onChange(e) { const text = e.target.value; this.setState({ text }); } onSubmit() { const { addComment } = this.props; const text = this.state.text.trim(); if (!text || text === '') { return; } addComment(marked(text)); this.setState({ text: '' }); } openLogin() { const signInUrl = `https://hub.getstorybook.io/sign-in?redirectUrl=${encodeURIComponent( window.location.href )}`; window.location.href = signInUrl; } handleKeyDown(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.onSubmit(); } } render() { if (!this.props.user) { return ( <div style={style.wrapper}> <Textarea style={style.input} disabled /> <button style={style.submitButton} onClick={() => this.openLogin()}> Sign in with Storybook Hub </button> </div> ); } const { text } = this.state; return ( <div style={style.wrapper}> <Textarea style={style.input} onChange={e => this.onChange(e)} onKeyDown={e => this.handleKeyDown(e)} placeholder="Add your comment..." value={text} /> <button style={style.submitButton} onClick={() => this.onSubmit()}> Submit </button> </div> ); } } CommentForm.defaultProps = { user: null, addComment: () => {}, }; CommentForm.propTypes = { user: PropTypes.object, // eslint-disable-line react/forbid-prop-types addComment: PropTypes.func, };
node_modules/react-router/es/Link.js
raptor1989/MobileHeader
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import createReactClass from 'create-react-class'; import { bool, object, string, func, oneOfType } from 'prop-types'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; import { ContextSubscriber } from './ContextUtils'; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> */ var Link = createReactClass({ displayName: 'Link', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object, func]), activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; var router = this.context.router; !router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); router.push(resolveToLocation(this.props.to, router)); }, render: function render() { var _props = this.props, to = _props.to, activeClassName = _props.activeClassName, activeStyle = _props.activeStyle, onlyActiveOnIndex = _props.onlyActiveOnIndex, props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); // Ignore if rendered outside the context of router to simplify unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (!to) { return React.createElement('a', props); } var toLocation = resolveToLocation(to, router); props.href = router.createHref(toLocation); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
src/meta/CalculatePlanList.js
guanzhou-zhao/calculate-cabinet-plan
import React, { Component } from 'react'; import _ from 'lodash'; import Category from '../model/Category'; import CalculatePlanForm from './CalculatePlanForm' export default class ClaculatePlanList extends Component { constructor(props) { super(props); this.showCalculatePlanForm = this.showCalculatePlanForm.bind(this); } showCalculatePlanForm() { var category = this.props.cat; var addingCalculatePlan = this.props.config.addingCalculatePlan; var updateState = this.props.config.updateState; var result; if (addingCalculatePlan.isAdding && category._id.equals(addingCalculatePlan.addingFor)) { result = <CalculatePlanForm /> } else { result = <input type="button" value="Add Calculate Plan" onClick={()=> { updateState({ addingCalculatePlan: { $set: { isAdding: true, addingFor: category._id } } }); }} /> } return result; } render () { return ( <div className="CalculatePlan"> <div className="CalculatePlanList"> </div> {this.showCalculatePlanForm()} </div> ) } }
src/components/pages/HomageToBarraganPage/index.js
RussHR/github_page_src
import React from 'react'; import ContentLayout from '../../layout/ContentLayout'; import VideoIFrame from '../../VideoIFrame'; export default function HomageToBarraganPage() { return ( <ContentLayout header="homage to Barrágan" subheader="completed - january 2017" links={[ 'http://russrinzler.com/homage-to-barragan', 'https://github.com/RussHR/homage-to-barragan-1-src' ]}> <p> homage to barragán is simply that: an homage to late architect <a href="https://en.wikipedia.org/wiki/Luis_Barrag%C3%A1n" target="_blank">Luis Barragán</a>. </p> <VideoIFrame style={{ width:"100%", paddingBottom: `${(439/640) * 100}%` }} src="https://player.vimeo.com/video/198635162" /> </ContentLayout> ); }
src/components/Dashboard/InstagramCard.js
jmporchet/bravakin-client
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Swing from 'react-swing'; import { Direction } from 'swing'; import { connect } from 'react-redux'; import './card.css'; import KeyHandler, {KEYPRESS} from 'react-key-handler'; class InstagramCard extends Component { constructor(props, context) { super(props, context); this.rendered = 0; // An instance of the Stack this.state = { stack: null, cards: [], currentIndex: 0, page: 0, fetching: true, hashtagIndex: 0 }; this.fetchLikeableMedia() } fetchLikeableMedia () { this.setState({fetching: true}); fetch(`http://192.168.0.49:3000/tags/${this.props.hashtags[this.state.hashtagIndex]}`, { method: "GET", headers: { 'Authorization': 'Bearer ' + this.props.access_token } }) .then((response) => response.json()) .then((likeableMedia) => { const newCards = this.state.cards.concat(likeableMedia.data); this.setState({ cards: newCards, floor: this.state.cards.length, currentIndex: newCards.length-1, fetching: false, hashtagIndex: (this.state.hashtagIndex+1)%this.props.hashtags.length }); }) .catch((error) => { console.error(error); }); } throwCard (direction) { return () => { if(this.state.currentIndex < this.state.floor) return; // get Target Dom Element const el = ReactDOM.findDOMNode(this.refs.stack.refs[`card${this.state.currentIndex}`]); if (direction === Direction.RIGHT) { const card = this.state.stack.getCard(el); card.throwOut(100, 200, direction); } else { const card = this.state.stack.getCard(el); card.throwOut(100, 200, direction); } const currentIndex = this.state.currentIndex - 1; this.setState({currentIndex: currentIndex}); if (currentIndex < this.state.floor) { this.fetchLikeableMedia(); } } } onThrowOut = (e)=> { const cardId = e.target.getAttribute('id').split('card')[1]; const media = this.state.cards[cardId]; if(e.throwDirection === Direction.LEFT) { } else { fetch(`http://192.168.0.49:3000/media/like`, { method: 'POST', body: JSON.stringify({ url: media.url }), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.props.access_token } }); } } // ============================================== RENDERING renderCards() { return this.state.cards.map((data, index) => { const style = { backgroundImage: 'url(' + data.imageURL + ')', backgroundSize: 'cover', backgroundPosition: 'center' }; return ( <div className="card" id={`card${index}`} key={`card${index}`} ref={`card${index}`} style={style} > {data.username} </div> ); }) } renderLoadingIndicator () { if(!this.state.fetching) return null; return ( <div className="loading-container"> <img className="loading" src="https://s-media-cache-ak0.pinimg.com/originals/86/07/37/86073779879c4777c617c6cea2e9eac6.gif" alt="loading" /> </div> ) } render() { this.rendered++ return ( <div> <div id="viewport"> {this.renderLoadingIndicator()} <Swing className="stack" tagName="div" setStack={(stack)=> { this.setState({stack:stack}) }} ref="stack" throwout={this.rendered === 1 ? this.onThrowOut : null} > {/* children elements is will be Card */} {this.renderCards()} </Swing> </div> <div className="control"> <KeyHandler keyEventName={KEYPRESS} keyValue="j" onKeyHandle={this.throwCard(Direction.LEFT)} /> <KeyHandler keyEventName={KEYPRESS} keyValue="l" onKeyHandle={this.throwCard(Direction.RIGHT)} /> </div> </div> ) } } const mapStateToProps = (state) => ({ hashtags: state.userProfile.like_tags, access_token: state.authorization.access_token }) export default connect(mapStateToProps)(InstagramCard);
pages/goodhart_campbell.js
mvasilkov/mvasilkov.ovh
import React from 'react' import Article from '../app/article' export const pagePath = 'goodhart_campbell' export const pageTitle = "Goodhart's law, Campbell's law" export default class extends React.Component { render() { return ( <Article path={pagePath} title={pageTitle}> <header> <h1>{pageTitle}</h1> <p>When a measure becomes a target, it ceases to be a good measure.</p> </header> <h3>Goodhart's law</h3> <p>Any observed statistical regularity will tend to collapse once pressure is placed upon it for control purposes.</p> <h3>Paraphrased by Biagioli</h3> <p>When a feature of the economy is picked as an indicator of the economy, then it inexorably ceases to function as that indicator because people start to game it.</p> <h3>Campbell's law</h3> <p>The more any quantitative social indicator is used for social decision-making, the more subject it will be to corruption pressures, and the more apt it will be to distort and corrupt the social processes it is intended to monitor.</p> </Article> ) } }
server/sonar-web/src/main/js/apps/settings/components/DefinitionsList.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. */ // @flow import React from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import Definition from './Definition'; export default class DefinitionsList extends React.Component { static propTypes = { component: React.PropTypes.object, settings: React.PropTypes.array.isRequired }; shouldComponentUpdate (nextProps: {}, nextState: ?{}) { return shallowCompare(this, nextProps, nextState); } render () { return ( <ul className="settings-definitions-list"> {this.props.settings.map(setting => ( <li key={setting.definition.key}> <Definition component={this.props.component} setting={setting}/> </li> ))} </ul> ); } }
packages/frint-react/src/components/observe.js
Travix-International/frint
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import composeHandlers from 'frint-component-utils/lib/composeHandlers'; import ObserveHandler from 'frint-component-handlers/lib/ObserveHandler'; import ReactHandler from '../handlers/ReactHandler'; import isObservable from '../isObservable'; export default function observe(fn) { return (Component) => { const componentName = (typeof Component.displayName !== 'undefined') ? Component.displayName : Component.name; class WrappedComponent extends React.Component { static displayName = (typeof componentName !== 'undefined') ? `observe(${componentName})` : 'observe'; static contextTypes = { app: PropTypes.object.isRequired }; constructor(props, context) { super(props, context); this._props$ = new BehaviorSubject(this.props); this.state = { computedProps: {}, }; const output = (typeof fn === 'function') ? fn(context.app, this._props$) : {}; if (!isObservable(output)) { // sync this.state.computedProps = output; return; } // async if (output.defaultProps) { this.state.computedProps = output.defaultProps; } this._handler = composeHandlers( ReactHandler, ObserveHandler, { component: this, getProps$: () => output, }, ); this.state.computedProps = { ...this.state.computedProps, ...this._handler.getInitialData().computedProps, }; } componentWillMount() { if (this._handler) { this._handler.app = this.context.app; this._handler.beforeMount(); } } componentWillReceiveProps(newProps) { if (this._handler) { this._props$.next(newProps); } } componentWillUnmount() { if (this._handler) { this._handler.beforeDestroy(); } } render() { const { computedProps } = this.state; return <Component {...computedProps} {...this.props} />; } } return WrappedComponent; }; }
client/views/setupWizard/steps/FinalStep.stories.js
iiet/iiet-chat
import React from 'react'; import FinalStep from './FinalStep'; export default { title: 'views/setupWizard/steps/FinalStep', component: FinalStep, }; export const _default = () => <FinalStep logoSrc='https://open.rocket.chat/images/logo/logo.svg' />;
examples/todo/js/app.js
heracek/relay
/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import 'babel/polyfill'; import 'todomvc-common'; import {createHashHistory} from 'history'; import {IndexRoute, Route} from 'react-router'; import React from 'react'; import ReactDOM from 'react-dom'; import {RelayRouter} from 'react-router-relay'; import TodoApp from './components/TodoApp'; import TodoList from './components/TodoList'; import ViewerQueries from './queries/ViewerQueries'; ReactDOM.render( <RelayRouter history={createHashHistory({queryKey: false})}> <Route path="/" component={TodoApp} queries={ViewerQueries}> <IndexRoute component={TodoList} queries={ViewerQueries} prepareParams={() => ({status: 'any'})} /> <Route path=":status" component={TodoList} queries={ViewerQueries} /> </Route> </RelayRouter>, document.getElementById('root') );
packages/ringcentral-widgets/components/IconField/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.scss'; export default function IconField(props) { return ( <div className={props.className}> <div className={styles.content}> {props.children} </div> <div className={styles.iconHolder}> <div className={styles.icon}> { props.icon } </div> </div> </div> ); } IconField.propTypes = { children: PropTypes.node, icon: PropTypes.node, className: PropTypes.string, };
src/svg-icons/av/volume-down.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVolumeDown = (props) => ( <SvgIcon {...props}> <path d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"/> </SvgIcon> ); AvVolumeDown = pure(AvVolumeDown); AvVolumeDown.displayName = 'AvVolumeDown'; AvVolumeDown.muiName = 'SvgIcon'; export default AvVolumeDown;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
paweljedrzejczyk/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-and-default"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/svg-icons/maps/local-printshop.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPrintshop = (props) => ( <SvgIcon {...props}> <path d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/> </SvgIcon> ); MapsLocalPrintshop = pure(MapsLocalPrintshop); MapsLocalPrintshop.displayName = 'MapsLocalPrintshop'; export default MapsLocalPrintshop;
src/js/components/grid/grid_pagination.js
rafaelfbs/realizejs
import React, { Component } from 'react'; import PropTypes from '../../prop_types'; import { mixin } from '../../utils/decorators'; import { CssClassMixin } from '../../mixins'; import { Input, Pagination } from '../../components'; @mixin(CssClassMixin) export default class GridPagination extends Component { static propTypes = { hidden: PropTypes.bool, count: PropTypes.number, page: PropTypes.number, perPage: PropTypes.number, window: PropTypes.number, onPagination: PropTypes.func, onChangePerPage: PropTypes.func, pageRowsCount: PropTypes.number, type: PropTypes.string, perPageOptions: PropTypes.array, }; static defaultProps = { themeClassKey: 'grid.pagination', onPagination() { return true; }, onChangePerPage() { return true; }, }; constructor(props) { super(props); this.handleChangePerPage = this.handleChangePerPage.bind(this); } renderRangePagination() { return ( <div className="range_pagination"> <span>{this.rangePaginationText()}</span> </div> ); } renderPerPage() { return ( <div className="per_page"> <Input value={this.props.perPage} component="select" includeBlank={false} clearTheme className="form__input input-field" options={this.props.perPageOptions} onChange={this.handleChangePerPage} /> </div> ); } renderPagination() { const { count, pageRowsCount } = this.props; if (count <= pageRowsCount) { return <span />; } return ( <div> <Pagination page={this.props.page} count={count} perPage={this.props.perPage} window={this.props.window} onPagination={this.props.onPagination} type={this.props.type} /> </div> ); } render() { if (this.props.hidden) return null; return ( <div className={this.className()}> {this.renderPagination()} {this.renderRangePagination()} {this.renderPerPage()} </div> ); } handleChangePerPage(event) { const perPage = parseInt(event.currentTarget.value); this.props.onChangePerPage(perPage); } rangePaginationText() { const { perPage, page, pageRowsCount } = this.props; const firstElement = (perPage * page - (perPage - 1)); const lastElement = (pageRowsCount < perPage) ? this.props.count : perPage * page; const totalElement = this.props.count; return `${firstElement} - ${lastElement} de ${totalElement}`; } }
src/svg-icons/device/battery-std.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryStd = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryStd = pure(DeviceBatteryStd); DeviceBatteryStd.displayName = 'DeviceBatteryStd'; DeviceBatteryStd.muiName = 'SvgIcon'; export default DeviceBatteryStd;
src/components/marker/index.js
datea/datea-webapp-react
import './marker.scss'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import L from 'leaflet'; const MARKER_CONFIG = { width : 29, height : 42, defaultColor : '#28BC45', path : `M14.087,0.485c-7.566,0-13.694,6.133-13.698,13.695c0.027,3.938,2.02,8.328,4.637,10.878c2.615,3.363,6.536,8.889,6.488,11.033v0.07c0,4.195,0.364,3.92,0.4,4.051c0.128,0.441,0.527,0.746,0.99,0.746h2.179c0.464,0,0.858-0.309,0.983-0.74c0.04-0.137,0.407,0.139,0.411-4.057c0-0.039-0.004-0.059-0.004-0.068c-0.038-2.047,3.399-7.35,6.109-10.877c2.875-2.498,5.175-6.814,5.196-11.035C27.779,6.618,21.65,0.485,14.087,0.485z` }; const MarkerDefs = ({children}) => <defs> <filter id="markerShadow" x="0" y="0" width="101%" height="101%"> <feDropShadow in="StrokePaint" dx="1" dy="1" stdDeviation="4" /> </filter> <clipPath id="markerPinPath"> <path d={MARKER_CONFIG.path} /> </clipPath> {children} </defs> const DefaultMarkerIcon = () => <svg width={MARKER_CONFIG.width} height={MARKER_CONFIG.height}> <g style={{clipPath: 'url(#markerPinPath)'}}> <rect height={MARKER_CONFIG.height} width={MARKER_CONFIG.width} fill={MARKER_CONFIG.defaultColor} x={0} y={0} /> <circle cx="14.5" cy="13" r="4" fill="white" /> <path className="marker-border" d={MARKER_CONFIG.path} stroke="#888888" fill="none" strokeWidth="1" /> </g> </svg> const CampaignMarkerIcon = ({dateo, subtags}) => { const coloredTags = dateo.tags .map(tag => typeof tag == 'string' ? tag : tag.tag) .filter(tag => subtags.has(tag)); const catWidth = MARKER_CONFIG.width / coloredTags.length; return ( <svg width={MARKER_CONFIG.width} height={MARKER_CONFIG.height}> <g style={{clipPath: 'url(#markerPinPath)'}}> {!!coloredTags.length && coloredTags.map((tag, i) => <rect key={tag} height={MARKER_CONFIG.height} width={catWidth} fill={subtags.get(tag).color} x={i*catWidth} y={0} /> )} {!coloredTags.length && <rect height={MARKER_CONFIG.height} width={MARKER_CONFIG.width} fill={MARKER_CONFIG.defaultColor} x={0} y={0} /> } </g> <g> <path className="marker-border" d={MARKER_CONFIG.path} stroke="#888888" fill="none" strokeWidth="1" /> <circle cx="14.5" cy="13" r="4" fill="white" /> </g> </svg> ) } const buildMarkerIcon = (svg) => { svg = svg || <DefaultMarkerIcon />; return L.divIcon({ iconSize : [MARKER_CONFIG.width, MARKER_CONFIG.height], iconAnchor : [MARKER_CONFIG.width/2, MARKER_CONFIG.height], popupAnchor : [0, -33], labelAnchor : [8, -25], html : ReactDOMServer.renderToStaticMarkup(svg), className : 'datea-marker-icon', }); } export {MARKER_CONFIG, MarkerDefs, DefaultMarkerIcon, CampaignMarkerIcon, buildMarkerIcon};
app/components/App.js
kensworth/olyranks
import React from 'react'; import Navbar from './Navbar'; import Footer from './Footer'; class App extends React.Component { render() { return ( <div> <Navbar history={this.props.history} /> {this.props.children} <Footer /> </div> ); } } export default App;
assets/jqwidgets/demos/react/app/datatable/aggregates/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js'; class App extends React.Component { render() { let source = { dataType: 'xml', dataFields: [ { name: 'SupplierName', type: 'string' }, { name: 'Quantity', type: 'number' }, { name: 'OrderDate', type: 'date' }, { name: 'OrderAddress', type: 'string' }, { name: 'Freight', type: 'number' }, { name: 'Price', type: 'number' }, { name: 'City', type: 'string' }, { name: 'ProductName', type: 'string' }, { name: 'Address', type: 'string' } ], url: '../sampledata/orderdetailsextended.xml', root: 'DATA', record: 'ROW' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Supplier Name', cellsAlign: 'center', align: 'center', dataField: 'SupplierName', width: 300 }, { text: 'Product', cellsAlign: 'center', align: 'center', dataField: 'ProductName', width: 300 }, { text: 'Quantity', dataField: 'Quantity', cellsFormat: 'd2', aggregates: ['avg', 'min', 'max'], cellsAlign: 'center', align: 'center', width: 120 }, { text: 'Price', dataField: 'Price', cellsFormat: 'c2', align: 'center', cellsAlign: 'center', aggregates: ['sum', 'min', 'max'] } ]; return ( <JqxDataTable width={850} source={dataAdapter} altRows={true} pageable={true} editable={true} columnsResize={true} showAggregates={true} autoRowHeight={false} aggregatesHeight={70} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
packages/idyll-document/src/components/author-tool.js
idyll-lang/idyll
import React from 'react'; import ReactTooltip from 'react-tooltip'; class AuthorTool extends React.PureComponent { constructor(props) { super(props); this.state = { isAuthorView: false, debugHeight: 0, componentHeight: 0, hasPressedButton: false }; this.handleClick = this.handleClick.bind(this); } // For all available props in metaValues, display them // If runtimeValues has a value for given prop, display it // Returns this in a single table row <tr> handleTableValues(metaValues, runtimeValues) { return metaValues.props.map(prop => { const runtimeValue = runtimeValues.props[prop.name]; let currentPropValue = null; if (runtimeValue !== undefined) { if ( runtimeValue && {}.toString.call(runtimeValue) === '[object Function]' ) { currentPropValue = <em>function</em>; } else { currentPropValue = runtimeValue; } } return ( <tr key={JSON.stringify(prop)} className="props-table-row"> <td>{prop.name}</td> <td className="props-table-type">{prop.type}</td> <td>{prop.example}</td> <td>{currentPropValue}</td> </tr> ); }); } // Returns authoring information for the prop values in table format // and includes a link to the docs page at the bottom handleFormatComponent(runtimeValues) { const metaValues = runtimeValues.type._idyll; const componentName = metaValues.name; // Docs use lowercase component name for link const componentLowerCase = componentName.charAt(0).toLowerCase() + componentName.slice(1); const componentDocsLink = 'https://idyll-lang.org/docs/components/default/' + componentLowerCase; const showProps = this.handleTableValues(metaValues, runtimeValues); const { isAuthorView, debugHeight, componentHeight } = this.state; const currentDebugHeight = isAuthorView ? debugHeight : 0; const marginToGive = isAuthorView ? 15 : 0; // If a component's height is too small, button will overlap with table // so add margin to get a minimal height (40px seems fine) const marginAboveTable = componentHeight < 40 && isAuthorView ? 40 - componentHeight : 0; return ( <div className="debug-collapse" style={{ height: currentDebugHeight + 'px', marginBottom: marginToGive + 'px', marginTop: marginAboveTable + 'px' }} > <div className="author-component-view" ref={inner => (this.innerHeight = inner)} > <table className="props-table"> <tbody> <tr className="props-table-row"> <th>Prop</th> <th>Type</th> <th>Example</th> <th>Current Value</th> </tr> {showProps} </tbody> </table> <div className="icon-links"> <a className="icon-link" href={componentDocsLink}> <img className="icon-link-image" src="https://raw.githubusercontent.com/google/material-design-icons/master/action/svg/design/ic_description_24px.svg?sanitize=true" /> </a> <a className="icon-link" href={componentDocsLink}> <span style={{ fontFamily: 'courier', fontSize: '12px', marginTop: '8px' }} > docs </span> </a> </div> </div> </div> ); } // Flips between whether we are in the author view of a component handleClick() { this.setState(prevState => ({ isAuthorView: !prevState.isAuthorView, debugHeight: this.innerHeight.getBoundingClientRect().height })); if (!this.state.hasPressedButton) { this.setState({ componentHeight: this._refContainer.getBoundingClientRect().height, hasPressedButton: true }); } } // Returns an entire author view, including the component itself, // a quill icon to indicate whether we're hovering in the component, // and debugging information when the icon is pressed render() { const { idyll, updateProps, hasError, ...props } = this.props; const addBorder = this.state.isAuthorView ? { boxShadow: '5px 5px 10px 1px lightGray', transition: 'box-shadow 0.35s linear', padding: '0px 10px 10px', margin: '0px -10px 20px' } : null; const putButtonBack = this.state.isAuthorView ? { right: '10px', top: '3px' } : null; return ( <div className="component-debug-view" style={addBorder} ref={ref => (this._refContainer = ref)} > {props.component} <button className="author-view-button" style={putButtonBack} onClick={this.handleClick} data-tip data-for={props.uniqueKey} /> <ReactTooltip className="button-tooltip" id={props.uniqueKey} type="info" effect="solid" place="bottom" // TODO not showing up ? disable={this.state.isAuthorView} > <div className="tooltip-header"> {props.authorComponent.type._idyll.name} Component </div> <div className="tooltip-subtitle">Click for more info</div> </ReactTooltip> {this.handleFormatComponent(props.authorComponent)} </div> ); } } export default AuthorTool;
lib/Navigation/Tabs/tabTwo/views/TabTwoScreenThree.js
Ezeebube5/Nairasense
import React from 'react'; import { View, Text } from 'react-native'; export default class TabTwoScreenThree extends React.Component { static navigationOptions = { tabBarLabel: 'Podcasts'} render() { return ( <View style={{ flex: 1, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center' }} > <Text>{ 'Tab Two Screen One' }</Text> </View> ); } }
wrappers/json.js
waigo/waigo.github.io
import React from 'react'; import ApiTemplate from '../components/apiTemplate'; export default class Layout extends React.Component { render () { return <ApiTemplate page={this.props.route.page} />; } } Layout.propTypes = { route: React.PropTypes.object, };
src/components/Tabs/Tabs.stories.js
Galernaya20/galernaya20.com
// @flow import React from 'react' import {storiesOf} from '@storybook/react' import {TabsComponent} from './Tabs' import {tabs} from '../pages/Equipment/fixture' storiesOf('TabsComponent', module).add('default', () => <TabsComponent tabs={tabs} />)
src/Parser/ElementalShaman/Modules/Talents/Aftershock.js
mwwscott0/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatNumber } from 'common/format'; import Module from 'Parser/Core/Module'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class Aftershock extends Module { refund = 0; on_initialized() { this.active = this.owner.modules.combatants.selected.hasTalent(SPELLS.AFTERSHOCK_TALENT.id); } on_byPlayer_energize(event) { if (event.ability.guid === SPELLS.AFTERSHOCK.id) { this.refund += event.resourceChange; } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.AFTERSHOCK_TALENT.id} />} value={`${formatNumber(this.refund)}`} label="Maelstrom refunded" /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(); } export default Aftershock;
ReactDialogBoxes.js
Apollo-11/react_dialog_boxes
import React from 'react'; /* usage import Msg from './ReactDialogBoxes'; <Msg ref={msg => {this.msg = msg;}}/> this.msg.alert('header', 'text' [,'buttonText']).then(() => { // code }); this.msg.confirm('header', 'text' [, 'okButtonText', 'cancelButtonText']).then(result => { // code }); this.msg.prompt( text: '', [promptPlaceholder: '',] [okButtonText: '',] [cancelButtonText: ''] ).then(result => { // code }); this.msg.showLoader(['Text to show']); // default is "Loading..." this.msg.hideLoader(); */ export default class ReactDialogBoxes extends React.Component { constructor (props) { super(props); this._defaultOkButtonText = 'Ok'; this._defaultCancelButtonText = 'Cancel'; this._defaultLoaderText = 'Loading...'; this.state = { type: 'alert', // other types: confirm, prompt, loader isVisible: false, messageText: 'Hello!', sendData: null, okButtonText: this._defaultOkButtonText, cancelButtonText: this._defaultCancelButtonText, promptValue: '' }; this.alert = this.alert.bind(this); this.confirm = this.confirm.bind(this); this.prompt = this.prompt.bind(this); this._okHandler = this._okHandler.bind(this); this._cancelHandler = this._cancelHandler.bind(this); this._promptHandler = this._promptHandler.bind(this); this.showLoader = this.showLoader.bind(this); this.hideLoader = this.hideLoader.bind(this); } alert (text, okButtonText) { this.setState({ type: 'alert', isVisible: true, messageText: text, okButtonText: okButtonText || this._defaultOkButtonText }); return new Promise((res, rej) => { this.setState({ sendData: res }); }); } confirm (text, okButtonText, cancelButtonText) { this.setState({ type: 'confirm', isVisible: true, messageText: text, okButtonText: okButtonText || this._defaultOkButtonText, cancelButtonText: cancelButtonText || this._defaultCancelButtonText }); return new Promise((res, rej) => { this.setState({ sendData: res }); }); } prompt ( text, okButtonText, cancelButtonText, promptPlaceholder ) { this.setState({ type: 'prompt', isVisible: true, messageText: text, okButtonText: okButtonText || this._defaultOkButtonText, cancelButtonText: cancelButtonText || this._defaultCancelButtonText, promptPlaceholder: promptPlaceholder || '' }); return new Promise((res, rej) => { this.setState({ sendData: res }); }); } _okHandler () { this.setState({ isVisible: false, okButtonText: this._defaultOkButtonText }); if (this.state.type === 'prompt') { this.state.sendData(this.state.promptValue); } else { this.state.sendData(true); } } _cancelHandler () { this.setState({ isVisible: false, okButtonText: this._defaultOkButtonText, cancelButtonText: this._defaultCancelButtonText }); this.state.sendData(false); } _promptHandler (ev) { this.setState({ promptValue: ev.target.value }); } showLoader (loaderText) { this.setState({ type: 'loader', isVisible: true, messageText: loaderText || this._defaultLoaderText }); } hideLoader () { this.setState({ type: 'loader', isVisible: false, messageText: '' }); } _renderAlertButtons () { return (<button className="_okButton" onClick={this._okHandler} > {this.state.okButtonText} </button>); } _renderConfirmButtons () { return (<div className="_confirmButtons"> <button className="_okButton" onClick={this._okHandler} > {this.state.okButtonText} </button> <button className="_cancelButton" onClick={this._cancelHandler} > {this.state.cancelButtonText} </button> </div>); } _renderPrompt () { return (<div className="_promptWrapper"> <div className="_prompt"> <input type="text" className="_promptInput" placeholder={this.state.promptPlaceholder} onChange={this._promptHandler} value={this.promptValue} /> </div> <button className="_okButton" onClick={this._okHandler} > {this.state.okButtonText} </button> <button className="_cancelButton" onClick={this._cancelHandler} > {this.state.cancelButtonText} </button> </div>); } render () { return (<div className="ReactDialogBoxes"> {this.state.isVisible && <div className="_container"> <div className="_background"/> <div className="_message"> {this.state.messageText && <p className="_text"> {this.state.messageText} </p> } {this.state.type === 'alert' && this._renderAlertButtons() } {this.state.type === 'confirm' && this._renderConfirmButtons() } {this.state.type === 'prompt' && this._renderPrompt() } </div> </div> } </div>); } }
js/jqwidgets/demos/react/app/formattedinput/righttoleftlayout/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxFormattedInput from '../../../jqwidgets-react/react_jqxformattedinput.js'; class App extends React.Component { render() { return ( <JqxFormattedInput width={250} height={25} radix={'binary'} rtl={true} value={10000} spinButtons={true} dropDown={true} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
assets/js/application/src/imaginery/component/Imaginery.js
ominidi/ominidi.org
import React from 'react'; import PropTypes from 'prop-types'; import Triangles from '../animation/Triangles'; /** * Render a canvas where the animation will be paint. * * @author Gabriele D'Arrigo <darrigo.g@gmail.com> */ export default class Imaginery extends React.Component { constructor(props) { super(props); } renderCanvas(el) { const {width, height, ratio, isMobile} = this.props.getRatio(); const scene = Triangles.getScene(); const camera = Triangles.getCamera((isMobile ? 30 : 75), ratio); const renderer = Triangles.getRenderer(width, height); const shapes = [ Triangles.getTetra(width / 1.7, 2, '#FFFFFF'), Triangles.getTetra(width / 1.6, 1, '#EFEFEF'), Triangles.getTetra(width / 1.5, 2, '#95989A'), Triangles.getTetra(width / 1.4, 1, '#2E2E2E'), ]; shapes.forEach(shape => { scene.add(shape); }); el.appendChild(renderer.domElement); Triangles.start(renderer, scene, camera, shapes)(); window.addEventListener('resize', () => { const {width, height, ratio} = this.props.getRatio(); camera.aspect = ratio; camera.updateProjectionMatrix(); renderer.setSize(width, height); }, false); } render() { return ( <figure className="masthead__picture imaginery" ref={(el) => {this.renderCanvas(el)}}/> ); } } Imaginery.propTypes = { width: PropTypes.number, height: PropTypes.number };
src/desktop/apps/auction/components/artwork_browser/sidebar/MediumFilter.js
kanaabe/force
import _BasicCheckbox from './BasicCheckbox' import PropTypes from 'prop-types' import React from 'react' import _, { contains } from 'underscore' import block from 'bem-cn-lite' import { connect } from 'react-redux' import { updateMediumParams } from 'desktop/apps/auction/actions/artworkBrowser' // FIXME: Rewire let BasicCheckbox = _BasicCheckbox function MediumFilter (props) { const { aggregatedMediums, allMediums, mediumIds, updateMediumParamsAction, allMediumsSelected, initialMediumMap } = props const b = block('auction-MediumFilter') return ( <div className={b()}> <div className={b('title')}> Medium </div> <BasicCheckbox key={allMediums.id} item={allMediums} onClick={updateMediumParamsAction} checked={allMediumsSelected} /> { _.map(initialMediumMap, (initialAgg) => { const mediumSelected = contains(mediumIds, initialAgg.id) const includedMedium = _.find(aggregatedMediums, (agg) => agg.id === initialAgg.id) return ( <BasicCheckbox key={initialAgg.id} item={{ id: initialAgg.id, name: initialAgg.name, count: includedMedium && includedMedium.count }} onClick={updateMediumParamsAction} checked={mediumSelected} disabled={includedMedium === undefined} /> ) }) } </div> ) } MediumFilter.propTypes = { aggregatedMediums: PropTypes.array.isRequired, allMediums: PropTypes.object.isRequired, allMediumsSelected: PropTypes.bool.isRequired, initialMediumMap: PropTypes.array.isRequired, mediumIds: PropTypes.array.isRequired, updateMediumParamsAction: PropTypes.func.isRequired } const mapStateToProps = (state) => { const { artworkBrowser: { aggregatedMediums, filterParams, initialMediumMap } } = state const mediumIds = filterParams.gene_ids const allMediums = { id: 'mediums-all', name: 'All' } const allMediumsSelected = mediumIds.length === 0 return { aggregatedMediums, allMediums, mediumIds, allMediumsSelected, initialMediumMap } } const mapDispatchToProps = { updateMediumParamsAction: updateMediumParams } export default connect( mapStateToProps, mapDispatchToProps )(MediumFilter) export const test = { MediumFilter }
app/javascript/mastodon/features/following/index.js
palon7/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { ScrollContainer } from 'react-router-scroll'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import LoadMore from '../../components/load_more'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'following', Number(props.params.accountId), 'items']), hasMore: !!state.getIn(['user_lists', 'following', Number(props.params.accountId), 'next']), }); @connect(mapStateToProps) export default class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchAccount(Number(this.props.params.accountId))); this.props.dispatch(fetchFollowing(Number(this.props.params.accountId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(Number(nextProps.params.accountId))); this.props.dispatch(fetchFollowing(Number(nextProps.params.accountId))); } } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) { this.props.dispatch(expandFollowing(Number(this.props.params.accountId))); } } handleLoadMore = (e) => { e.preventDefault(); this.props.dispatch(expandFollowing(Number(this.props.params.accountId))); } render () { const { accountIds, hasMore } = this.props; let loadMore = null; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } if (hasMore) { loadMore = <LoadMore onClick={this.handleLoadMore} />; } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='following'> <div className='scrollable' onScroll={this.handleScroll}> <div className='following'> <HeaderContainer accountId={this.props.params.accountId} /> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} {loadMore} </div> </div> </ScrollContainer> </Column> ); } }
src/account.js
angustas/company
import React, { Component } from 'react'; import Sidebar from './common/sidebar'; import $ from 'jquery'; import { Icon,Card,Input,Button,message,Modal,Table,Tag} from 'antd'; import { hashHistory } from 'react-router'; export default class Account extends Component { constructor(props) { super(props); this.state = {display: "none",visible: false}; this.editPassword = this.editPassword.bind(this); this.cancelSave = this.cancelSave.bind(this); this.savePassword = this.savePassword.bind(this); this.toCompanyDetail = this.toCompanyDetail.bind(this); this.toAccount = this.toAccount.bind(this); this.successmessage = this.successmessage.bind(this); this.errormessage = this.errormessage.bind(this); this.showModal = this.showModal.bind(this); this.submitAccount = this.submitAccount.bind(this); this.handleCancel = this.handleCancel.bind(this); this.fetchAccount = this.fetchAccount.bind(this); this.post = this.post.bind(this); this.onDelete = this.onDelete.bind(this); }; componentDidMount(){ this.fetchAccount(); }; toSecurity(){ hashHistory.push('/security'); }; toSetting(){ hashHistory.push('/setting'); }; toCompanyDetail(){ hashHistory.push('/companySetting'); } toAccount(){ hashHistory.push('/account'); }; errormessage(msg){ message.error(msg); }; successmessage(msg){ message.success(msg); }; showModal() { this.setState({ visible: true, }); }; fetchAccount(){ let url="//localhost/companyBACK/welcome/GetAccount"; let user_id=localStorage.getItem("user_id"); let company_id=localStorage.getItem("company_id"); this.post(url,"company_id="+company_id,function(list){ let a=[]; for(let i=0;i<list.data.length;i++){ let b={ key: list.data[i].user_id, name: list.data[i].name, account: list.data[i].email, password: list.data[i].password, id:list.data[i].user_id }; a.push(b); } console.log(a); this.setState({account:a}); }.bind(this)); }; post(url,res,callback){//公用API this.setState({loading:true}); fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: res }) .then(function(response) { if (response.status >= 400) { throw new Error("Bad response from server"); } return response.json(); }) .then(function (list) { if(list.status=="OK"){ this.setState({loading:false}); callback(list); }else if(list.status=="error"){ message.error("系统繁忙~"); } }.bind(this)); }; submitAccount () { var account=$(".account").val(); var name=$(".name").val(); var password=$(".password").val(); var company_id=localStorage.getItem("company_id"); if(account==""||name==""||password==""){ this.errormessage("请正确填写所有内容~"); return false; }else{ this.setState({ visible: false, show: false }); fetch('//localhost/companyBACK/welcome/JoinCompany?name='+name+'&account='+account+'&password='+password+'&company_id='+company_id, { method: "GET", headers: { "Content-Type": "application/x-www-form-urlencoded" } }) .then(function(response) { if (response.status >= 400) { throw new Error("Bad response from server"); } return response.json(); }) .then(function (list) { if(list.status=="OK"){ message.success("分配用户成功~"); }else if(list.status=="error"){ message.error("系统繁忙~"); } }.bind(this)); } }; handleCancel() { this.setState({ visible: false, show: false }); }; onDelete(e){ var user_id=$(e.target).data("id"); let url="//localhost/companyBACK/welcome/DeleteAccount"; // let company_id=localStorage.getItem("company_id"); this.post(url,"user_id="+user_id,function(list){ if(list.status=="OK"){ message.success("注销成功~"); this.fetchAccount(); } }.bind(this)); console.log(user_id); }; editPassword(){ this.successmessage("修改成功~"); }; savePassword(){ this.successmessage("保存成功~"); }; cancelSave(){ this.successmessage("保存成功~"); }; render() { const data = [ {value: 1, name: "是"}, {value: 2, name: "否"} ]; const dataSource = this.state.account; const columns = [{ title: '姓名', dataIndex: 'name', key: 'name', render: text => <a href="javascript:void(0);">{text}</a>, }, { title: '账号', dataIndex: 'account', key: 'account', }, { title: '密码', dataIndex: 'password', key: 'password', }, { title: '操作', dataIndex:"id", key: 'id', render: text => ( <span> <span className="ant-divider" /> <a href="javascript:void(0);" data-id={text} onClick={this.onDelete}>注销</a> <span className="ant-divider" /> </span> ), }]; if(localStorage.getItem("is_admin")=="true"){ var list= <li className="" onClick={this.toAccount}>分配账号</li> }else{ var list=""; } return ( <div className="missionContainer"> <Sidebar target="setting"/> <nav className="missionBoard"> <h2><Icon type="safety" /> &nbsp;分配账号</h2> <ul className="navUl"> <li className="" onClick={this.toSetting}>账户资料</li> <li className="" onClick={this.toSecurity}>安全</li> <li className="" onClick={this.toCompanyDetail}>公司信息</li> <li className="selected" onClick={this.toAccount}>分配账号</li> </ul> <ul className="newMission"> <li> <Button type="default" icon="plus" onClick={this.showModal} >分配账号</Button> </li> </ul> </nav> <div className="missionList"> <Table dataSource={dataSource} columns={columns} /> <Modal title="分配账号" visible={this.state.visible} onOk={this.submitAccount} onCancel={this.handleCancel} okText="确认" cancelText="取消" > <Card> 账号:<Input placeholder="输入账号" className="account" /> <br/> 姓名:<Input placeholder="输入姓名" className="name" /> <br/> 密码:<Input placeholder="输入密码" className="password" /> </Card> </Modal> </div> </div> ); }; }
app/javascript/mastodon/features/notifications/components/setting_toggle.js
koba-lab/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Toggle from 'react-toggle'; export default class SettingToggle extends React.PureComponent { static propTypes = { prefix: PropTypes.string, settings: ImmutablePropTypes.map.isRequired, settingPath: PropTypes.array.isRequired, label: PropTypes.node.isRequired, onChange: PropTypes.func.isRequired, defaultValue: PropTypes.bool, disabled: PropTypes.bool, } onChange = ({ target }) => { this.props.onChange(this.props.settingPath, target.checked); } render () { const { prefix, settings, settingPath, label, defaultValue, disabled } = this.props; const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-'); return ( <div className='setting-toggle'> <Toggle disabled={disabled} id={id} checked={settings.getIn(settingPath, defaultValue)} onChange={this.onChange} onKeyDown={this.onKeyDown} /> <label htmlFor={id} className='setting-toggle__label'>{label}</label> </div> ); } }
docs/src/app/components/pages/components/List/ExampleSimple.js
hai-cea/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ContentInbox from 'material-ui/svg-icons/content/inbox'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import ContentSend from 'material-ui/svg-icons/content/send'; import ContentDrafts from 'material-ui/svg-icons/content/drafts'; import Divider from 'material-ui/Divider'; import ActionInfo from 'material-ui/svg-icons/action/info'; const ListExampleSimple = () => ( <MobileTearSheet> <List> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} /> <ListItem primaryText="Starred" leftIcon={<ActionGrade />} /> <ListItem primaryText="Sent mail" leftIcon={<ContentSend />} /> <ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} /> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} /> </List> <Divider /> <List> <ListItem primaryText="All mail" rightIcon={<ActionInfo />} /> <ListItem primaryText="Trash" rightIcon={<ActionInfo />} /> <ListItem primaryText="Spam" rightIcon={<ActionInfo />} /> <ListItem primaryText="Follow up" rightIcon={<ActionInfo />} /> </List> </MobileTearSheet> ); export default ListExampleSimple;
client/pages/ImportExportJson.js
nb256/kanbanello
import React from 'react'; import { formElementsStyle } from '../styles/styles'; import { connect } from 'react-redux'; import actions from '../actions'; class ImportExportJson extends React.Component { handleFile() { const file = this.fileUpload.files[0]; const read = new FileReader(); read.readAsBinaryString(file); read.onloadend = () => { try { if (JSON.parse(read.result)) { localStorage.setItem('state', read.result); location.reload(); this.props.history.push('/'); } } catch (err) { console.log('Updating localStorage failed for some reason:' + err); } }; } render() { this.handleFile = this.handleFile.bind(this); return ( <div> <h1> Import a JSON file: </h1> <div className="w3-border-top w3-border-bottom w3-border-green"> <label>Import a JSON file: </label> <input id="input_open" type="file" accept='.json' ref={(ref) => this.fileUpload = ref} onChange={this.handleFile} style = { formElementsStyle }/> </div> <h1> Get the local state as JSON: </h1> <div className="w3-border-top w3-border-bottom w3-border-red"> <div className="w3-code jsHigh"> {JSON.stringify(this.props.allLanes)} </div> </div> </div> ); } } export default connect(actions.mapStateToProps, actions.mapDispatchToProps)(ImportExportJson);
src/ButtonToolbar.js
reactstrap/reactstrap
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; const propTypes = { tag: tagPropType, 'aria-label': PropTypes.string, className: PropTypes.string, cssModule: PropTypes.object, role: PropTypes.string, }; const defaultProps = { tag: 'div', role: 'toolbar', }; const ButtonToolbar = (props) => { const { className, cssModule, tag: Tag, ...attributes } = props; const classes = mapToCssModules(classNames( className, 'btn-toolbar' ), cssModule); return ( <Tag {...attributes} className={classes} /> ); }; ButtonToolbar.propTypes = propTypes; ButtonToolbar.defaultProps = defaultProps; export default ButtonToolbar;
frontend/src/Settings/General/AnalyticSettings.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import FieldSet from 'Components/FieldSet'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import { inputTypes, sizes } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; function AnalyticSettings(props) { const { settings, onInputChange } = props; const { analyticsEnabled } = settings; return ( <FieldSet legend={translate('Analytics')}> <FormGroup size={sizes.MEDIUM}> <FormLabel>{translate('SendAnonymousUsageData')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="analyticsEnabled" helpText={translate('AnalyticsEnabledHelpText')} helpTextWarning={translate('RestartRequiredHelpTextWarning')} onChange={onInputChange} {...analyticsEnabled} /> </FormGroup> </FieldSet> ); } AnalyticSettings.propTypes = { settings: PropTypes.object.isRequired, onInputChange: PropTypes.func.isRequired }; export default AnalyticSettings;
src/components/icons/SkipIcon.js
austinknight/ui-components
import React from 'react'; const SkipIcon = (props) => { const outline = props.outline ? { fill: 'none', strokeLinejoin: 'round', strokeWidth: '0.8', stroke: 'currentColor' } : {}; return ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z" {...outline} /> <path d="M0 0h24v24H0z" fill="none" /> </svg> ); }; export default SkipIcon;
src/components/sidebar/hiveInfo/demandChart.js
beehive-spg/beehive-frontend
import React from 'react' import { XYPlot, LineSeries, XAxis, YAxis, HorizontalGridLines, VerticalGridLines, } from 'react-vis' import { graphql } from 'react-apollo' import { addHours, subHours, addMinutes, differenceInMinutes, differenceInSeconds, } from 'date-fns' import { statistics } from 'graphql/queries' import 'react-vis/dist/style.css' @graphql(statistics, { options: ({ hive }) => ({ variables: { id: hive, }, pollInterval: 1000, }), }) export default class DemandChart extends React.Component { transformData = statistics => { if (statistics.length > 1) { return statistics.reduce( (acc, section) => { if (!acc.last) { acc.data.push({ x: parseInt(section.time, 10), y: section.value, }) } else { acc.data.push( { x: parseInt(section.time, 10), y: acc.last.value, }, { x: parseInt(section.time, 10), y: section.value, }, ) } acc.last = section return acc }, { data: [], last: null, }, ).data } else { let sections = [] for (let i = 0; i < 6; i++) { sections.push({ x: addHours(addMinutes(new Date(), i), 1), y: statistics[0].value, }) } return sections } } render() { const { data } = this.props if (data.loading) return null const statistics = this.transformData(data.statistics) let yTicks = statistics.map(section => section.y) yTicks = [...new Set([0, ...yTicks])] return ( <div className="demandChart"> <XYPlot height={200} width={275} stacked={'x'}> <XAxis tickLabelAngle={-22.5} tickFormat={v => { const date = new Date() let diff = differenceInSeconds(subHours(v, 1), date) if (diff / 60 >= 1) { diff = `${differenceInMinutes( subHours(v, 1), date, )} min` } else { diff = `${diff} sec` } return diff }} /> <YAxis tickValues={yTicks} /> <HorizontalGridLines /> <VerticalGridLines /> <LineSeries animation data={statistics} /> </XYPlot> </div> ) } }
node_modules/react-bootstrap/es/Image.js
CallumRocks/ReduxSimpleStarter
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Sets image as responsive image */ responsive: PropTypes.bool, /** * Sets image shape as rounded */ rounded: PropTypes.bool, /** * Sets image shape as circle */ circle: PropTypes.bool, /** * Sets image shape as thumbnail */ thumbnail: PropTypes.bool }; var defaultProps = { responsive: false, rounded: false, circle: false, thumbnail: false }; var Image = function (_React$Component) { _inherits(Image, _React$Component); function Image() { _classCallCheck(this, Image); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Image.prototype.render = function render() { var _classes; var _props = this.props, responsive = _props.responsive, rounded = _props.rounded, circle = _props.circle, thumbnail = _props.thumbnail, className = _props.className, props = _objectWithoutProperties(_props, ['responsive', 'rounded', 'circle', 'thumbnail', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (_classes = {}, _classes[prefix(bsProps, 'responsive')] = responsive, _classes[prefix(bsProps, 'rounded')] = rounded, _classes[prefix(bsProps, 'circle')] = circle, _classes[prefix(bsProps, 'thumbnail')] = thumbnail, _classes); return React.createElement('img', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Image; }(React.Component); Image.propTypes = propTypes; Image.defaultProps = defaultProps; export default bsClass('img', Image);
src/pages/password-reset.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program 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, 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 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 PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import noop from 'lodash/noop'; import ApiClient from '../api/client'; import { API_HOST } from '../config'; import { ActionsTrigger } from '../triggers'; import { createSelector } from '../selectors'; import { Page, PageMain, PageBody, PageContent } from '../components/page'; import ContextualRoutes from '../components/contextual'; import Footer from '../components/footer'; import Header from '../components/header'; import Message from '../components/message'; export const ResetForm = (props) => { return ( <form className="layout__grid layout__grid-responsive layout-align_end layout__space-double" onSubmit={props.submitHandler} action="" method="post"> <div className="layout__grid_item layout__grid_item-identical"> <label className="label label-before_input" htmlFor="resetPasswordEmail">Email</label> <input className="input input-big input-block" id="resetPasswordEmail" required="required" type="email" name="email" /> </div> <div className="layout__grid_item"> <button type="submit" className="button button-big button-green">Submit</button> </div> </form> ); }; export const SuccessMessage = () => { return ( <Message> If we found this email in our database, we have just sent you a message with further steps. </Message> ); }; export class PasswordResetPage extends React.Component { static contextualRoutes = ['login', 'signup']; static displayName = 'PasswordResetPage'; static propTypes = { dispatch: PropTypes.func, location: PropTypes.shape(), routes: PropTypes.arrayOf(PropTypes.shape()), ui: PropTypes.shape({ submitResetPassword: PropTypes.bool }).isRequired }; static defaultProps = { dispatch: noop, location: { hash: '', pathname: '', search: '' } }; constructor(props, ...args) { super(props, ...args); this.handleLogin = new ActionsTrigger( new ApiClient(API_HOST), props.dispatch ).login.bind(null, true); this.routesProps = { 'login': { onSubmit: this.handleLogin } }; } submitHandler = (event) => { event.preventDefault(); const form = event.target; const client = new ApiClient(API_HOST); const triggers = new ActionsTrigger(client, this.props.dispatch); triggers.resetPassword(form.email.value); }; render() { const { is_logged_in, ui } = this.props; let content = <ResetForm submitHandler={this.submitHandler} />; if (ui.get('submitResetPassword')) { content = <SuccessMessage />; } return ( <div className="font-light"> <Helmet title="Reset Password for " /> <section className="landing landing-big landing-bg landing-bg_house"> <Header className="header-transparent" is_logged_in={is_logged_in} needIndent={false} needMenu={false} /> <header className="landing__body"> <p className="layout__row layout__row-small landing__small_title" style={{ position: 'relative', left: 4 }}>Welcome to LibertySoil.org</p> <h1 className="landing__subtitle landing__subtitle-narrow">Education change network</h1> </header> </section> <Page className="page__container-no_spacing page__container-bg"> <PageMain> <PageBody className="page__body-small"> <PageContent> <div className="content__title layout__row">Reset Password</div> <div className="layout__row"> {content} </div> </PageContent> </PageBody> </PageMain> </Page> <Footer /> <ContextualRoutes location={this.props.location} predefProps={this.routesProps} routes={this.props.routes} scope={PasswordResetPage.displayName} /> </div> ); } } const selector = createSelector( state => !!state.getIn(['current_user', 'id']), state => state.get('ui'), (is_logged_in, ui) => ({ is_logged_in, ui }) ); export default connect(selector)(PasswordResetPage);
src/svg-icons/notification/phone-forwarded.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhoneForwarded = (props) => ( <SvgIcon {...props}> <path d="M18 11l5-5-5-5v3h-4v4h4v3zm2 4.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-1z"/> </SvgIcon> ); NotificationPhoneForwarded = pure(NotificationPhoneForwarded); NotificationPhoneForwarded.displayName = 'NotificationPhoneForwarded'; NotificationPhoneForwarded.muiName = 'SvgIcon'; export default NotificationPhoneForwarded;
src/svg-icons/places/all-inclusive.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesAllInclusive = (props) => ( <SvgIcon {...props}> <path d="M18.6 6.62c-1.44 0-2.8.56-3.77 1.53L12 10.66 10.48 12h.01L7.8 14.39c-.64.64-1.49.99-2.4.99-1.87 0-3.39-1.51-3.39-3.38S3.53 8.62 5.4 8.62c.91 0 1.76.35 2.44 1.03l1.13 1 1.51-1.34L9.22 8.2C8.2 7.18 6.84 6.62 5.4 6.62 2.42 6.62 0 9.04 0 12s2.42 5.38 5.4 5.38c1.44 0 2.8-.56 3.77-1.53l2.83-2.5.01.01L13.52 12h-.01l2.69-2.39c.64-.64 1.49-.99 2.4-.99 1.87 0 3.39 1.51 3.39 3.38s-1.52 3.38-3.39 3.38c-.9 0-1.76-.35-2.44-1.03l-1.14-1.01-1.51 1.34 1.27 1.12c1.02 1.01 2.37 1.57 3.82 1.57 2.98 0 5.4-2.41 5.4-5.38s-2.42-5.37-5.4-5.37z"/> </SvgIcon> ); PlacesAllInclusive = pure(PlacesAllInclusive); PlacesAllInclusive.displayName = 'PlacesAllInclusive'; PlacesAllInclusive.muiName = 'SvgIcon'; export default PlacesAllInclusive;
src/routes/index.js
mortenryum/loanCalculator
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import App from '../components/App'; // Child routes import home from './home'; import error from './error'; export default { path: '/', children: [ home, error, ], async action({ next, render, context }) { const component = await next(); if (component === undefined) return component; return render( <App context={context}>{component}</App> ); }, };
docs/src/examples/collections/Message/Variations/MessageExampleWarning.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Message } from 'semantic-ui-react' const MessageExampleWarning = () => ( <Message warning> <Message.Header>You must register before you can do that!</Message.Header> <p>Visit our registration page, then try again.</p> </Message> ) export default MessageExampleWarning
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/Popover.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import classNames from 'classnames'; import TooltipPopoverWrapper, { propTypes } from './TooltipPopoverWrapper'; const defaultProps = { placement: 'right', placementPrefix: 'bs-popover', trigger: 'click', }; const Popover = (props) => { const popperClasses = classNames( 'popover', 'show', props.popperClassName ); const classes = classNames( 'popover-inner', props.innerClassName ); return ( <TooltipPopoverWrapper {...props} popperClassName={popperClasses} innerClassName={classes} /> ); }; Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default Popover;
src/Spinner.entry.js
giovanni0918/react-component-catalog
import React from 'react'; import { render } from 'react-dom'; import {Spinner} from './components/Spinner/Spinner'; render( <Spinner status="Loading"></Spinner>, document.getElementById('Spinner') );
client/src/components/Draftail/Tooltip/Tooltip.js
torchbox/wagtail
import PropTypes from 'prop-types'; import React from 'react'; const TOP = 'top'; const LEFT = 'left'; const TOP_LEFT = 'top-left'; const getTooltipStyles = (target, direction) => { const top = window.pageYOffset + target.top; const left = window.pageXOffset + target.left; switch (direction) { case TOP: return { 'top': top + target.height, // Remove once we drop support for Safari 13. 'left': left + target.width / 2, 'inset-inline-start': left + target.width / 2, }; case LEFT: return { 'top': top + target.height / 2, // Remove once we drop support for Safari 13. 'left': left + target.width, 'inset-inline-start': left + target.width, }; case TOP_LEFT: default: return { 'top': top + target.height, // Remove once we drop support for Safari 13. 'left': left, 'inset-inline-start': left, }; } }; /** * A tooltip, with arbitrary content. */ const Tooltip = ({ target, children, direction }) => ( <div style={getTooltipStyles(target, direction)} className={`Tooltip Tooltip--${direction}`} role="tooltip" > {children} </div> ); Tooltip.propTypes = { target: PropTypes.shape({ top: PropTypes.number.isRequired, left: PropTypes.number.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, }).isRequired, direction: PropTypes.oneOf([TOP, LEFT, TOP_LEFT]).isRequired, children: PropTypes.node.isRequired, }; export default Tooltip;
src/main/resources/code/react/Apps/Admin/components/ManageUsers/UserRow.js
artieac/technologyradar
'use strict' import React from 'react'; import ReactDOM from 'react-dom'; import Reflux from 'reflux'; import createReactClass from 'create-react-class'; import { Link } from 'react-router-dom'; import { connect } from "react-redux"; import RoleDropdownItem from "./RoleDropdownItem"; class UserRow extends React.Component{ constructor(props){ super(props); this.state = { }; this.changeRowSelection = this.changeRowSelection.bind(this); this.getRadarUrl = this.getRadarUrl.bind(this); } componentDidUpdate(){ } changeRowSelection(newRole){ this.props.rowData.role = newRole; this.forceUpdate(); } getRadarUrl(){ return "/home/user/" + this.props.rowData.id + "/radars"; } render() { return ( <tr> <td>{ this.props.rowData.name}</td> <td>{ this.props.rowData.email}</td> <td> <div className="dropdown"> <button className="btn btn-techradar dropdown-toggle" type="button" id="roleDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> { this.props.rowData.role.name } <span className="caret"></span> </button> <ul className="dropdown-menu" aria-labelledby="roleDropdown"> {this.props.roles.map(function (currentRow, index) { return <RoleDropdownItem key={index} rowData={currentRow} container={this} /> }.bind(this))} </ul> </div> </td> <td>{ this.props.rowData.userType.name}</td> <td> <a className="btn btn-techradar" href={ this.getRadarUrl()}>Radars</a> </td> </tr> ); } }; function mapStateToProps(state) { return { }; }; const mapDispatchToProps = dispatch => { return { setSelectedUser : selectedUser => { dispatch(setSelectedUser(selectedUser))}, } }; export default connect(mapStateToProps, mapDispatchToProps)(UserRow);
src/routes.js
xebia-studio/lv-oneprofile
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Router from 'react-routing/src/Router'; import fetch from './core/fetch'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const query = `/graphql?query={content(path:"${state.path}"){path,title,content,component}}`; const response = await fetch(query); const { data } = await response.json(); return data && data.content && <ContentPage {...data.content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/ModalHeader.js
pivotal-cf/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalHeader extends React.Component { render() { return ( <div {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> { this.props.closeButton && <button className='close' onClick={this.props.onHide}> <span aria-hidden="true"> &times; </span> </button> } { this.props.children } </div> ); } } //used in liue of parent contexts right now to auto wire the close button ModalHeader.__isModalHeader = true; ModalHeader.propTypes = { /** * The 'aria-label' attribute is used to define a string that labels the current element. * It is used for Assistive Technology when the label text is not visible on screen. */ 'aria-label': React.PropTypes.string, /** * A css class applied to the Component */ modalClassName: React.PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: React.PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside a Modal component, the onHide will automatically * be propagated up to the parent Modal `onHide`. */ onHide: React.PropTypes.func }; ModalHeader.defaultProps = { 'aria-label': 'Close', modalClassName: 'modal-header', closeButton: false }; export default ModalHeader;
core/src/plugins/gui.ajax/res/js/ui/HOCs/animations/make-motion.js
ChuckDaniels87/pydio-core
/** * Copyright (c) 2013-present, Facebook, Inc. All rights reserved. * * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React from 'react'; import ReactDOM from 'react-dom'; import shallowCompare from 'react/lib/shallowCompare'; import { TransitionMotion } from 'react-motion'; import stripStyle from 'react-motion/lib/stripStyle'; import {springify, buildTransform} from './utils'; let counter=0 const DEFAULT_ANIMATION={stiffness: 200, damping: 22, precision: 0.1} const makeTransition = (originStyles, targetStyles, enter, leave) => { return (Target) => { class TransitionGroup extends React.PureComponent { constructor(props) { super(props); this.state = { styles: this.build(props) }; } componentWillReceiveProps(nextProps) { this.setState({ styles: this.build(nextProps) }); } build(props) { return React.Children .toArray(props.children) .filter(child => child) // Removing null values .map(child => { return !props.ready ? null : { key: child.key || `t${counter++}`, data: {element: child}, style: springify(targetStyles, enter || DEFAULT_ANIMATION) } }) .filter(child => child); // Removing null values } willEnter(transitionStyle) { console.log("Will enter ", this.props) return { ...stripStyle(transitionStyle.style), ...originStyles }; } willLeave(transitionStyle) { return { ...transitionStyle.style, ...springify(originStyles, leave || DEFAULT_ANIMATION) } } render() { // Making sure we fliter out properties const {ready, ...props} = this.props console.log("Transition styles ", this.state.styles) return ( <TransitionMotion styles={this.state.styles} willLeave={this.willEnter.bind(this)} willEnter={this.willEnter.bind(this)} > {styles => <Target {...props}> {styles.map(({key, style, data}) => { console.log("Transition child being rendered") const Child = data.element.type const itemProps = data.element.props const transform = buildTransform(style, { length: 'px', angle: 'deg' }); return ( <Child key={data.element.key} {...itemProps} style={{ ...itemProps.style, ...style, transform }} /> ); })} </Target> } </TransitionMotion> ); } } TransitionGroup.propTypes = { ready: React.PropTypes.bool.isRequired } TransitionGroup.defaultProps = { ready: true } return TransitionGroup } }; export default makeTransition;
src/components/MyNavbar.js
Korkemoms/amodahl.no
// @flow import React from 'react' import NavLink from '../components/NavLink' import NavIndexLink from '../components/NavIndexLink' import { Nav, Navbar, NavDropdown } from 'react-bootstrap' /* Purely presentational component */ const MyNavbar = (props: { user: Object, page: string }) => { const userSpecific = props.user === null ? <NavLink eventKey={4} to={{ pathname: '/login' }}>Log in</NavLink> : <NavLink eventKey={4} to={{ pathname: '/me' }}>Logged in: {props.user.name}</NavLink> return ( <Navbar style={{margin: '0', borderRadius: '0', border: '0'}} inverse collapseOnSelect> <Navbar.Header> <Navbar.Brand> <a href='/'>amodahl.no</a> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavIndexLink eventKey={1} to={{ pathname: '/' }}>Home</NavIndexLink> <NavDropdown id='MyProjectsDrowndown' eventKey={2} title='My projects'> <NavLink eventKey={2.1} to={{ pathname: '/amodahl-no' }}>Amodahl.no</NavLink> <NavLink eventKey={2.2} to={{ pathname: '/chess-project' }}>Chess</NavLink> <NavLink eventKey={2.3} to={{ pathname: '/matrix-multiplication' }}> Matrix multiplication game</NavLink> <NavLink eventKey={2.4} to={{ pathname: '/leveringmontering' }}> Leveringmontering.no (Order management system)</NavLink> </NavDropdown> <NavLink eventKey={3} to={{ pathname: '/about' }}>About me</NavLink> </Nav> <Nav pullRight> {userSpecific} </Nav> </Navbar.Collapse> </Navbar> ) } export default MyNavbar
src/views/WidgetList/widgets/Recommended/RecommendedWidget.js
GovReady/GovReady-Agent-Client
import React, { Component } from 'react'; import { PropTypes as PT } from 'prop-types'; import Accordion from 'react-bootstrap/lib/Accordion'; import Panel from 'react-bootstrap/lib/Panel'; class RecommendedWidget extends Component { recommendedList (plugins) { const header = (plugin) => { return ( <span> <span className={'pull-left ' + plugin.installed ? 'warning' : 'success' } style={ {marginRight: '10px' } }> {plugin.installed && <i className="fa fa-check-square-o" /> } {!plugin.installed && <i className="fa fa-square-o" /> } </span> <span>{plugin.title}</span> </span> ) } return ( <Accordion> {plugins.map((plugin, index) => { return ( <Panel header={header(plugin)} eventKey={index} key={index}> <p> {plugin.free && <span className="label label-success">Free version</span> } {plugin.paid && <span className="label label-info">Paid version</span> } </p> <p>{plugin.description}</p> <hr /> <div> <a href={this.props.pluginUrl + plugin.namespace}>{this.props.pluginText} page <i className="fa fa-chevron-right" /></a> </div> </Panel> ) })} </Accordion> ); } render () { return ( <div> <div className="text"> <h3>{this.props.headerText}</h3> </div> {this.recommendedList(this.props.plugins)} </div> ); } } RecommendedWidget.propTypes = { pluginText: PT.string.isRequired, pluginUrl: PT.string.isRequired, headerText: PT.string.isRequired, plugins: PT.array.isRequired }; export default RecommendedWidget;
assets/javascripts/kitten/components/action/button-question-mark-icon/index.js
KissKissBankBank/kitten
import React from 'react' import { Button } from '../../action/button' import { QuestionMarkIcon } from '../../graphics/icons/question-mark-icon' export const ButtonQuestionMarkIcon = props => ( <Button modifier="helium" size="nano" rounded fit="icon" type="button" {...props} > <QuestionMarkIcon width="10" height="10" /> </Button> )
es/components/PlaylistManager/SearchResults/SearchResultsList.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import React from 'react'; import PropTypes from 'prop-types'; import MediaList from '../../MediaList'; import AddToPlaylistAction from '../../MediaList/Actions/AddToPlaylist'; var makeActions = function makeActions(onOpenAddMediaMenu) { return function (media, selection) { return _jsx(React.Fragment, {}, void 0, _jsx(AddToPlaylistAction, { onAdd: function onAdd(position) { return onOpenAddMediaMenu(position, media, selection); } })); }; }; var SearchResultsList = function SearchResultsList(_ref) { var results = _ref.results, onOpenAddMediaMenu = _ref.onOpenAddMediaMenu, onOpenPreviewMediaDialog = _ref.onOpenPreviewMediaDialog; return _jsx(MediaList, { className: "PlaylistPanel-media", media: results, onOpenPreviewMediaDialog: onOpenPreviewMediaDialog, makeActions: makeActions(onOpenAddMediaMenu) }); }; SearchResultsList.propTypes = process.env.NODE_ENV !== "production" ? { results: PropTypes.array.isRequired, onOpenAddMediaMenu: PropTypes.func.isRequired, onOpenPreviewMediaDialog: PropTypes.func.isRequired } : {}; export default SearchResultsList; //# sourceMappingURL=SearchResultsList.js.map
src/svg-icons/image/grid-on.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGridOn = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"/> </SvgIcon> ); ImageGridOn = pure(ImageGridOn); ImageGridOn.displayName = 'ImageGridOn'; ImageGridOn.muiName = 'SvgIcon'; export default ImageGridOn;
src/components/search-bar.js
codingkapoor/technology-jukebox
import React, { Component } from 'react'; import { Form, FormGroup, Input, Button } from 'reactstrap'; import AutoSuggest from 'react-autosuggest'; export default class SearchBar extends Component { constructor(props) { super(props); this.state = { value: '', suggestions: [] }; this.onFormSubmit = this.onFormSubmit.bind(this); } onChange = (event, { newValue, method }) => { this.setState({ value: newValue }); if(!newValue) { this.props.onSearchTermChange(newValue); } }; onFormSubmit(event) { event.preventDefault(); this.props.onSearchTermChange(this.state.value); } onSuggestionsFetchRequested = ({ value }) => { let suggestions = getSuggestions(value, this.props.technologiesSearchPool); this.setState({ suggestions }); }; onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; render() { const { value, suggestions } = this.state; const inputProps = { placeholder: "Search projects by technologies", value, onChange: this.onChange }; return ( <div className = "search-bar col-lg-8 col-lg-offset-2"> <Form onSubmit = { this.onFormSubmit }> <FormGroup className = "search-form"> <AutoSuggest suggestions = { suggestions } onSuggestionsFetchRequested = { this.onSuggestionsFetchRequested } onSuggestionsClearRequested = { this.onSuggestionsClearRequested } getSuggestionValue = { getSuggestionValue } renderSuggestion = { renderSuggestion } inputProps = { inputProps } /> <Button color = "primary"> <i className = "fa fa-search" aria-hidden = "true"></i> </Button> </FormGroup> </Form> </div> ); } } function escapeRegexCharacters(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function getSuggestions(value, technologies) { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp('^' + escapedValue, 'i'); return technologies.filter(technology => regex.test(technology.name)); } function getSuggestionValue(suggestion) { return suggestion.name; } function renderSuggestion(suggestion) { return ( <span>{ suggestion.name }</span> ); }
client/trello/src/app/routes/login/Login.js
Madmous/madClones
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { push } from 'react-router-redux'; import { Link } from 'react-router'; import { LoginForm } from './components/index'; import './Login.css'; const propTypes = { isAuthenticatingSuccessful: PropTypes.bool.isRequired, isAuthenticated: PropTypes.bool.isRequired, loginActions: PropTypes.object.isRequired } export default class Login extends Component { componentWillMount() { const { isAuthenticated, dispatch } = this.props; if (isAuthenticated) { dispatch(push('/')); } } componentDidMount () { document.title = 'Login to Trello Clone'; } authenticate = (formInput) => { const { loginActions, location } = this.props; loginActions.authenticate(formInput, location); } render () { return ( <div className="Login"> <LoginForm onSubmit={ this.authenticate } /> <p>Don't have an account? <Link to={`/signup`}>Create a Trello Clone Account</Link></p> </div> ); } } Login.propTypes = propTypes;
test/test_helper.js
kevinw123/ReduxBlog
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};
app/addons/replication/components/common-activity.js
popojargo/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import PropTypes from 'prop-types'; import React from 'react'; export const ReplicationFilter = ({value, onChange}) => { return ( <div className="replication__filter"> <i className="replication__filter-icon fonticon-filter" /> <input type="text" placeholder="Filter replications" className="replication__filter-input" value={value} onChange={(e) => {onChange(e.target.value);}} /> </div> ); }; ReplicationFilter.propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; export const ReplicationHeader = ({filter, onFilterChange}) => { return ( <div className="replication__activity_header"> <div></div> <ReplicationFilter value={filter} onChange={onFilterChange} /> <a href="#/replication/_create" className="btn save replication__activity_header-btn btn-primary"> <i className="icon fonticon-plus-circled"></i> New Replication </a> </div> ); }; ReplicationHeader.propTypes = { filter: PropTypes.string.isRequired, onFilterChange: PropTypes.func.isRequired };
src/components/App.js
hongalex/mining-visualizer
import React, { Component } from 'react'; import './App.css'; import pick from '../img/pick.png'; import Blockchain from './Blockchain'; class App extends Component { constructor(props) { super(props); this.state = { blockData: '' } }; updateBlockData = (event) => { this.setState({blockData: event.target.value}) }; render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Simple Blockchain Mining Demo</h1> </header> <h1 className="App-intro"> To get started, press give some data as input and hit "Mine New Block" </h1> <form className="form-inline" onSubmit={e => { e.preventDefault(); this.refs.blockchain.createBlock() }}> <div className="form-group"> <input type="text" className="form-control" name="blockData" placeholder="Data" value={this.state.blockData} onChange={this.updateBlockData} /> </div> <button className="btn btn-primary" onClick={() => this.refs.blockchain.createBlock()} type="button"> Mine New Block&nbsp; <img src={pick} height="20" width="20" alt=""/> </button> </form> <Blockchain ref="blockchain" blockData={this.state.blockData}/> </div> ); }; }; export default App;
src/svg-icons/alert/add-alert.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertAddAlert = (props) => ( <SvgIcon {...props}> <path d="M10.01 21.01c0 1.1.89 1.99 1.99 1.99s1.99-.89 1.99-1.99h-3.98zm8.87-4.19V11c0-3.25-2.25-5.97-5.29-6.69v-.72C13.59 2.71 12.88 2 12 2s-1.59.71-1.59 1.59v.72C7.37 5.03 5.12 7.75 5.12 11v5.82L3 18.94V20h18v-1.06l-2.12-2.12zM16 13.01h-3v3h-2v-3H8V11h3V8h2v3h3v2.01z"/> </SvgIcon> ); AlertAddAlert = pure(AlertAddAlert); AlertAddAlert.displayName = 'AlertAddAlert'; AlertAddAlert.muiName = 'SvgIcon'; export default AlertAddAlert;
votrfront/js/router.js
fmfi-svt/votr
import PropTypes from 'prop-types'; import React from 'react'; import _ from 'lodash'; import $ from 'jquery'; export function trackPageView() { if (!window.ga) return; var current = location.protocol + '//' + location.hostname + location.pathname + location.search; if (current == trackPageView.last) return; trackPageView.last = current; ga('send', 'pageview', { location: current }); }; function parseQueryString(queryString) { if (!queryString) return {}; var result = {}; var pairs = queryString.split('&'); for (var i = 0; i < pairs.length; i++) { var index = pairs[i].indexOf('='); if (index == -1) { index = pairs[i].length; } var name = pairs[i].substring(0, index); var value = pairs[i].substring(index + 1); result[name] = decodeURIComponent(value.replace(/\+/g, ' ')); } return result; } export var QueryContext = React.createContext(); export function queryConsumer(callback) { return <QueryContext.Consumer>{callback}</QueryContext.Consumer>; } export class Root extends React.Component { handlePopState = () => { Votr.appRoot.forceUpdate(); } componentDidMount() { window.addEventListener('popstate', this.handlePopState, false); trackPageView(); } componentDidUpdate() { trackPageView(); } render() { var queryString = location.search.substring(1); if (queryString !== this.lastQueryString) { this.query = parseQueryString(queryString); this.lastQueryString = queryString; } return ( <React.StrictMode> <QueryContext.Provider value={this.query}> <this.props.app /> </QueryContext.Provider> </React.StrictMode> ); } } export function buildUrl(href) { if (_.isString(href)) return href; return '?' + $.param(_.omitBy(href, _.isUndefined), true); }; export function navigate(href) { Votr.didNavigate = true; history.pushState(null, '', Votr.settings.url_root + buildUrl(href)); Votr.appRoot.forceUpdate(); }; export class Link extends React.Component { handleClick = (event) => { // Chrome fires onclick on middle click. Firefox only fires it on document, // see <http://lists.w3.org/Archives/Public/www-dom/2013JulSep/0203.html>, // but React adds event listeners to document so we still see a click event. if (event.button != 0) return; event.preventDefault(); navigate(this.props.href); } render() { return <a {...this.props} href={buildUrl(this.props.href)} onClick={this.handleClick} />; } } // Looks and acts like a link, but doesn't have a href and cannot be opened in // a new tab when middle-clicked or ctrl-clicked. export class FakeLink extends React.Component { static propTypes = { onClick: PropTypes.func.isRequired }; // Pressing Enter on <a href=...> emits a click event, and the HTML5 spec // says elements with tabindex should do that too, but they don't. // <http://www.w3.org/TR/WCAG20-TECHS/SCR29> suggests using a keyup event: handleKeyUp = (event) => { if (event.which == 13) { event.preventDefault(); this.props.onClick(event); } } render() { return <a {...this.props} onKeyUp={this.handleKeyUp} tabIndex="0" role="button" />; } }