path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/counter/containers/App.js
joshblack/redux
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createRedux } from 'redux'; import { Provider } from 'redux/react'; import * as stores from '../stores'; const redux = createRedux(stores); export default class App extends Component { render() { return ( <Provider redux={redux}> {() => <CounterApp />} </Provider> ); } }
client/src/containers/drived_gate/DrivedGate.js
thewizardplusplus/vk-group-stats
import React from 'react' import {fetchLogin} from '../../actions/login' import {connect} from 'react-redux' import StatefulGate from '../../components/stateful_gate/StatefulGate' function mapStateToProps(state) { return { state: state.login.state, open: state.login.isLogged, } } function mapDispatchToProps(dispatch) { return { onMount() { dispatch(fetchLogin()) }, } } export const DrivedGate = connect( mapStateToProps, mapDispatchToProps )(StatefulGate) DrivedGate.propTypes = { children: React.PropTypes.node.isRequired, }
NavigationReact/sample/isomorphic/index.js
grahammendick/navigation
import React from 'react'; import ReactDOM from 'react-dom'; import { NavigationHandler } from 'navigation-react'; import getStateNavigator from './getStateNavigator'; import App from './App'; var stateNavigator = getStateNavigator(); registerControllers(stateNavigator); stateNavigator.start(); ReactDOM.hydrate( <NavigationHandler stateNavigator={stateNavigator}> <App /> </NavigationHandler>, document.getElementById('content') ); function registerControllers(stateNavigator) { stateNavigator.states.people.navigating = stateNavigator.states.person.navigating = function(data, url, navigate) { fetchData(url, navigate); } } function fetchData(url, navigate) { if (serverProps) { navigate(serverProps); serverProps = null; return; } var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState === 4){ navigate(JSON.parse(req.responseText)); } }; req.open('get', url); req.setRequestHeader('Content-Type', 'application/json'); req.send(null); }
app/js/components/Header.js
arcsecw/myfd
import React from 'react'; import { Link, } from 'react-router'; import { Topbar, CollapsibleNav, Nav, NavItem, Icon, Badge, Dropdown, } from 'amazeui-react'; import auth from './auth' import Logout from '../pages/Logout'; const Header = React.createClass({ handleClick() { if (matchMedia && matchMedia('(max-width: 640px)').matches) { this.refs.topbar.handleToggle(); } }, render() { return ( <Topbar brand="谷雨医生" toggleNavKey="nav" inverse fluid ref="topbar" > <CollapsibleNav eventKey="nav" > <Nav className="am-topbar-right" topbar > {auth.getRole()=='1'||auth.getRole()=='3'||auth.getRole()=='4'||auth.getRole()=='5'?( <NavItem className = "am-dropdown" href = '#'> <Link to = '/index_home'> <Icon icon="home" /> {'网站首页'} </Link> </NavItem>):''} {auth.getRole()=='1'?( <Dropdown title={[<Icon icon="group" key="hey" />, auth.getUsername()]} navItem > <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/user_index'}, onClick: this.handleClick }} > <Icon icon="user" /> {'用户首页'} </Dropdown.Item> </Dropdown>):(<NavItem></NavItem>)} {auth.getRole()=='5'?( <Dropdown title={[<Icon icon="group" key="hey" />, auth.getUsername()]} navItem > <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/manageRoot'}, onClick: this.handleClick }} > <Icon icon="user" /> {'系统管理'} </Dropdown.Item> <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/system_manage'}, onClick: this.handleClick }} > <Icon icon="user" /> {'订单管理'} </Dropdown.Item> <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/user_manage'}, onClick: this.handleClick }} > <Icon icon="user" /> {'用户管理'} </Dropdown.Item> <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/price_manage'}, onClick: this.handleClick }} > <Icon icon="user" /> {'价格管理'} </Dropdown.Item> <Dropdown.Item closeOnClick linkComponent={Link} linkProps={{ to: {pathname: '/account_manage'}, onClick: this.handleClick }} > <Icon icon="user" /> {'账户管理'} </Dropdown.Item> </Dropdown>):(<NavItem></NavItem>)} <NavItem className="am-dropdown" href="#" > {auth.loggedIn()?( <Link to = '/Logout'> <Icon icon="sign-out" /> {' 退出登录'} </Link> ) :( <Link to = '/login'> <Icon icon="sign-in" /> {' 登录'} </Link>) } </NavItem> </Nav> </CollapsibleNav> </Topbar> ); } }); export default Header;
src/people/PeopleList.js
dash-/netjumpio-tabs-web
/// // Dependencies /// import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as types from './types'; import CardsList from '../elements/CardsList'; import PeopleListItem from './PeopleListItem'; /// // View /// class PeopleListView extends Component { renderPeople(people) { return people.map((item, key) => ( <PeopleListItem item={item} key={key} /> )); } render() { return ( <CardsList className="people-list"> {this.renderPeople(this.props.people)} </CardsList> ); } } PeopleListView.propTypes = { people: types.List.isRequired, }; export { PeopleListView }; /// // Container /// function mapStateToProps(state) { return { people: state.get('people'), }; } function mapDispatchToProps(dispatch) { return {}; } const connector = connect( mapStateToProps, mapDispatchToProps ); export default connector(PeopleListView);
mochasetup.js
panayi/react-styleguidist
import React from 'react'; import { expect } from 'chai'; import expectReactShallow from 'expect-react-shallow'; import 'css-modules-require-hook'; global.React = React; global.expect = expect; global.expectReactShallow = expectReactShallow;
app/containers/NotFoundPage/index.js
GuiaLa/guiala-web-app
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import Navbar from 'Navbar'; export function NotFound() { return ( <div> <Navbar /> <article style={{paddingTop: 100}}> <p>Página não encontrada.</p> </article> </div> ); } // react-redux stuff function mapDispatchToProps(dispatch) { return { changeRoute: (url) => dispatch(push(url)), }; } // Wrap the component to inject dispatch and state into it export default connect(null, mapDispatchToProps)(NotFound);
node_modules/react-select/src/Option.js
xuan6/admin_dashboard_local_dev
import React from 'react'; import createClass from 'create-react-class'; import PropTypes from 'prop-types'; import classNames from 'classnames'; const Option = createClass({ propTypes: { children: PropTypes.node, className: PropTypes.string, // className (based on mouse position) instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: PropTypes.bool, // the option is disabled isFocused: PropTypes.bool, // the option is focused isSelected: PropTypes.bool, // the option is selected onFocus: PropTypes.func, // method to handle mouseEnter on option element onSelect: PropTypes.func, // method to handle click on option element onUnfocus: PropTypes.func, // method to handle mouseLeave on option element option: PropTypes.object.isRequired, // object that is base for that option optionIndex: PropTypes.number, // index of the option, used to generate unique ids for aria }, blockEvent (event) { event.preventDefault(); event.stopPropagation(); if ((event.target.tagName !== 'A') || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }, handleMouseDown (event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter (event) { this.onFocus(event); }, handleMouseMove (event) { this.onFocus(event); }, handleTouchEnd(event){ // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if(this.dragging) return; this.handleMouseDown(event); }, handleTouchMove (event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart (event) { // Set a flag that the view is not being dragged this.dragging = false; }, onFocus (event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } }, render () { var { option, instancePrefix, optionIndex } = this.props; var className = classNames(this.props.className, option.className); return option.disabled ? ( <div className={className} onMouseDown={this.blockEvent} onClick={this.blockEvent}> {this.props.children} </div> ) : ( <div className={className} style={option.style} role="option" onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseMove={this.handleMouseMove} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd} id={instancePrefix + '-option-' + optionIndex} title={option.title}> {this.props.children} </div> ); } }); module.exports = Option;
node_modules/react-router/es/Router.js
ge6285790/test
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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for putting history on context. */ var Router = function (_React$Component) { _inherits(Router, _React$Component); function Router() { var _temp, _this, _ret; _classCallCheck(this, Router); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { match: _this.computeMatch(_this.props.history.location.pathname) }, _temp), _possibleConstructorReturn(_this, _ret); } Router.prototype.getChildContext = function getChildContext() { return { router: _extends({}, this.context.router, { history: this.props.history, route: { location: this.props.history.location, match: this.state.match } }) }; }; Router.prototype.computeMatch = function computeMatch(pathname) { return { path: '/', url: '/', params: {}, isExact: pathname === '/' }; }; Router.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var _props = this.props, children = _props.children, history = _props.history; invariant(children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element'); // Do this here so we can setState when a <Redirect> changes the // location in componentWillMount. This happens e.g. when doing // server rendering using a <StaticRouter>. this.unlisten = history.listen(function () { _this2.setState({ match: _this2.computeMatch(history.location.pathname) }); }); }; Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { warning(this.props.history === nextProps.history, 'You cannot change <Router history>'); }; Router.prototype.componentWillUnmount = function componentWillUnmount() { this.unlisten(); }; Router.prototype.render = function render() { var children = this.props.children; return children ? React.Children.only(children) : null; }; return Router; }(React.Component); Router.propTypes = { history: PropTypes.object.isRequired, children: PropTypes.node }; Router.contextTypes = { router: PropTypes.object }; Router.childContextTypes = { router: PropTypes.object.isRequired }; export default Router;
src/svg-icons/action/turned-in.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTurnedIn = (props) => ( <SvgIcon {...props}> <path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionTurnedIn = pure(ActionTurnedIn); ActionTurnedIn.displayName = 'ActionTurnedIn'; ActionTurnedIn.muiName = 'SvgIcon'; export default ActionTurnedIn;
examples/src/components/BooleanSelect.js
Dem0n3D/react-select
import React from 'react'; import Select from 'react-select'; var ValuesAsBooleansField = React.createClass({ displayName: 'ValuesAsBooleansField', propTypes: { label: React.PropTypes.string }, getInitialState () { return { options: [ { value: true, label: 'Yes' }, { value: false, label: 'No' } ], matchPos: 'any', matchValue: true, matchLabel: true, value: null, multi: false }; }, onChangeMatchStart(event) { this.setState({ matchPos: event.target.checked ? 'start' : 'any' }); }, onChangeMatchValue(event) { this.setState({ matchValue: event.target.checked }); }, onChangeMatchLabel(event) { this.setState({ matchLabel: event.target.checked }); }, onChange(value) { this.setState({ value }); console.log('Boolean Select value changed to', value); }, onChangeMulti(event) { this.setState({ multi: event.target.checked }); }, render () { var matchProp = 'any'; if (this.state.matchLabel && !this.state.matchValue) { matchProp = 'label'; } if (!this.state.matchLabel && this.state.matchValue) { matchProp = 'value'; } return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select matchPos={this.state.matchPos} matchProp={matchProp} multi={this.state.multi} onChange={this.onChange} options={this.state.options} simpleValue value={this.state.value} /> <div className="checkbox-list"> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} /> <span className="checkbox-label">Multi-Select</span> </label> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} /> <span className="checkbox-label">Match value</span> </label> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} /> <span className="checkbox-label">Match label</span> </label> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} /> <span className="checkbox-label">Only include matches from the start of the string</span> </label> </div> <div className="hint">This example uses simple boolean values</div> </div> ); } }); module.exports = ValuesAsBooleansField;
src/calculator/HouseBuildingCalc.js
alelk/houses-building-website
/** * House Building Calculator * * Created by Alex Elkin on 23.10.2017. */ import calculateFoundationCost from './foundationCalc' import React from 'react'; import PropTypes from 'prop-types' import {Card, CardTitle, CardText} from 'material-ui/Card'; import Slider from 'material-ui/Slider'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import TextField from 'material-ui/TextField'; import Toggle from 'material-ui/Toggle'; const heaters = { none : "Без утеплителя", mineralWool : "Минеральная вата", stoneWool : "Каменная вата" }; const roofCoatings = { none : "Без покрытия", corrugatedBoard : "Профнастил", metalTile : "Металлочерепица" }; class HouseBuildingCalc extends React.Component { constructor(props) { super(props); this.onAreaChanged = this.onAreaChanged.bind(this); this.onFloorsCountChanged = this.onFloorsCountChanged.bind(this); this.onInsulationChanged = this.onInsulationChanged.bind(this); this.onMakeFoundationToggle = this.onMakeFoundationToggle.bind(this); this.onMakeCarcassToggle = this.onMakeCarcassToggle.bind(this); this.onRoofCoatingChanged = this.onRoofCoatingChanged.bind(this); this.state = { floorsCount: 1, houseArea: 36, makeFoundation: true, makeCarcass: true, heater : "mineralWool", roofCoating : "corrugatedBoard" } } onAreaChanged(value) { this.setState({houseArea:value}) } onFloorsCountChanged(event, index, value) { this.setState({floorsCount:value}) } onMakeFoundationToggle(event, value) { this.setState({makeFoundation:value}) } onMakeCarcassToggle(event, value) { this.setState({makeCarcass:value}); if (!value) this.setState({heater:'none'}) } onInsulationChanged(event, index, value) { this.setState({heater:value}) } onRoofCoatingChanged(event, index, value) { this.setState({roofCoating:value}) } render() { return ( <div className="HouseBuildingCalc"> <Card style={{backgroundColor:"rgba(255,255,255,0.3)"}}> <CardTitle title="Рассчет стоимости строительства каркасного дома"/> <CardText> <TextField floatingLabelText="Жилая площадь" hintText="Общая площадь дома" value={this.state.houseArea} onChange={(e) => this.onAreaChanged(e.target.value)} style={{width:'100%'}} type={"number"} /> <Slider name="Площадь" value={this.state.houseArea} min={10} max={200} step={1} onChange={(ignored, value) => this.onAreaChanged(value)} /> <SelectField floatingLabelText="Количество этажей" value={this.state.floorsCount} onChange={this.onFloorsCountChanged} style={{width:'100%'}} > <MenuItem value={1} primaryText="1 этаж"/> <MenuItem value={2} primaryText="2 этажа"/> </SelectField> <Toggle label="Залить фундамент" toggled={this.state.makeFoundation} onToggle={this.onMakeFoundationToggle} /> <Toggle label="Построить каркас" toggled={this.state.makeCarcass} onToggle={this.onMakeCarcassToggle} /> <SelectField floatingLabelText="Утеплитель" style={{width:'100%'}} value={this.state.heater} onChange={this.onInsulationChanged} > { heaters && Object.keys(heaters).map(k => <MenuItem key={k} value={k} primaryText={heaters[k]}/>) } </SelectField> <SelectField floatingLabelText="Покрытие кровли" value={this.state.roofCoating} style={{width:'100%'}} onChange={this.onRoofCoatingChanged} > { roofCoatings && Object.keys(roofCoatings).map(k => <MenuItem key={k} value={k} primaryText={roofCoatings[k]}/>) } </SelectField> <br/> <div> <label>Стоимость фундамента: {calculateFoundationCost(this.state.houseArea, this.state.floorsCount)}</label> </div> </CardText> </Card> </div> ) } } export default HouseBuildingCalc;
src/routes/poll/index.js
binyuace/vote
import React from 'react'; import { connect } from 'react-redux'; import Layout from '../../components/Layout'; import initialPoll from '../../actions/initialPoll'; import Poll from '../../components/Poll'; import voteAsync from '../../actions/voteAsync'; import Votes from './Votes'; import NewVote from './NewVote'; import Share from './Share'; import Remove from './Remove'; import Chart from './Chart'; async function action({ fetch, params, store, location }) { // initializing the state with fetch const response = await fetch(`/api/poll/${params.poll}`, { method: 'GET', }); const result = await response.json(); store.dispatch(initialPoll(result)); const ShowPollState = connect(state => state.poll)(Poll); // connect votes with state and dispach const mapDispatchToProps = dispatch => ({ handleClick: idx => { dispatch(voteAsync(fetch, params.poll, idx)); }, }); const AllVotes = connect( state => ({ votes: state.poll.votes }), mapDispatchToProps, )(Votes); // connect async message const MessageAsync = ({ message }) => <p> {message} </p>; const Message = connect(state => ({ message: state.poll.messageAsync }))( MessageAsync, ); const BinChartComponent = ({ votes }) => <Chart votes={votes} />; const BinChart = connect(state => ({ votes: state.poll.votes }))( BinChartComponent, ); return { chunks: ['home'], title: result.title, component: ( <Layout> <h1> poll:{result.title} <br /> Options:{result.votes.length ? result.votes.length : 'no Options curretly,feel free to creat options for this poll'} </h1> <BinChart /> <ShowPollState /> <AllVotes /> <Message /> <NewVote fetch={fetch} params={params} store={store} /> <Share title={result.title} location={location} /> {store.getState().user !== null && store.getState().poll.creatorId === store.getState().user.id ? <Remove fetch={fetch} params={params} /> : null} </Layout> ), }; } export default action;
src/components/Header/Header.js
veskoy/ridiko
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present 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 withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import logoUrl from './logo-small.png'; import logoUrl2x from './[email protected]'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Link className={s.brand} to="/"> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" /> <span className={s.brandTxt}>Ridiko</span> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}>Ridiko</h1> <p className={s.bannerDesc}>Carpool bot</p> </div> </div> </div> ); } } export default withStyles(s)(Header);
app/javascript/mastodon/features/status/index.js
Arukas/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchStatus } from '../../actions/statuses'; import MissingIndicator from '../../components/missing_indicator'; import DetailedStatus from './components/detailed_status'; import ActionBar from './components/action_bar'; import Column from '../ui/components/column'; import { favourite, unfavourite, reblog, unreblog, pin, unpin, } from '../../actions/interactions'; import { replyCompose, mentionCompose, } from '../../actions/compose'; import { blockAccount } from '../../actions/accounts'; import { muteStatus, unmuteStatus, deleteStatus } from '../../actions/statuses'; import { initMuteModal } from '../../actions/mutes'; import { initReport } from '../../actions/reports'; import { makeGetStatus } from '../../selectors'; import { ScrollContainer } from 'react-router-scroll-4'; import ColumnBackButton from '../../components/column_back_button'; import StatusContainer from '../../containers/status_container'; import { openModal } from '../../actions/modal'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { HotKeys } from 'react-hotkeys'; import { boostModal, deleteModal } from '../../initial_state'; import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../../features/ui/util/fullscreen'; const messages = defineMessages({ deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' }, blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' }, }); const makeMapStateToProps = () => { const getStatus = makeGetStatus(); const mapStateToProps = (state, props) => ({ status: getStatus(state, props.params.statusId), ancestorsIds: state.getIn(['contexts', 'ancestors', props.params.statusId]), descendantsIds: state.getIn(['contexts', 'descendants', props.params.statusId]), }); return mapStateToProps; }; @injectIntl @connect(makeMapStateToProps) export default class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, status: ImmutablePropTypes.map, ancestorsIds: ImmutablePropTypes.list, descendantsIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; state = { fullscreen: false, }; componentWillMount () { this.props.dispatch(fetchStatus(this.props.params.statusId)); } componentDidMount () { attachFullscreenListener(this.onFullScreenChange); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this._scrolledIntoView = false; this.props.dispatch(fetchStatus(nextProps.params.statusId)); } } handleFavouriteClick = (status) => { if (status.get('favourited')) { this.props.dispatch(unfavourite(status)); } else { this.props.dispatch(favourite(status)); } } handlePin = (status) => { if (status.get('pinned')) { this.props.dispatch(unpin(status)); } else { this.props.dispatch(pin(status)); } } handleReplyClick = (status) => { this.props.dispatch(replyCompose(status, this.context.router.history)); } handleModalReblog = (status) => { this.props.dispatch(reblog(status)); } handleReblogClick = (status, e) => { if (status.get('reblogged')) { this.props.dispatch(unreblog(status)); } else { if (e.shiftKey || !boostModal) { this.handleModalReblog(status); } else { this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog })); } } } handleDeleteClick = (status) => { const { dispatch, intl } = this.props; if (!deleteModal) { dispatch(deleteStatus(status.get('id'))); } else { dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.deleteMessage), confirm: intl.formatMessage(messages.deleteConfirm), onConfirm: () => dispatch(deleteStatus(status.get('id'))), })); } } handleMentionClick = (account, router) => { this.props.dispatch(mentionCompose(account, router)); } handleOpenMedia = (media, index) => { this.props.dispatch(openModal('MEDIA', { media, index })); } handleOpenVideo = (media, time) => { this.props.dispatch(openModal('VIDEO', { media, time })); } handleMuteClick = (account) => { this.props.dispatch(initMuteModal(account)); } handleConversationMuteClick = (status) => { if (status.get('muted')) { this.props.dispatch(unmuteStatus(status.get('id'))); } else { this.props.dispatch(muteStatus(status.get('id'))); } } handleBlockClick = (account) => { const { dispatch, intl } = this.props; dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.blockConfirm), onConfirm: () => dispatch(blockAccount(account.get('id'))), })); } handleReport = (status) => { this.props.dispatch(initReport(status.get('account'), status)); } handleEmbed = (status) => { this.props.dispatch(openModal('EMBED', { url: status.get('url') })); } handleHotkeyMoveUp = () => { this.handleMoveUp(this.props.status.get('id')); } handleHotkeyMoveDown = () => { this.handleMoveDown(this.props.status.get('id')); } handleHotkeyReply = e => { e.preventDefault(); this.handleReplyClick(this.props.status); } handleHotkeyFavourite = () => { this.handleFavouriteClick(this.props.status); } handleHotkeyBoost = () => { this.handleReblogClick(this.props.status); } handleHotkeyMention = e => { e.preventDefault(); this.handleMentionClick(this.props.status); } handleHotkeyOpenProfile = () => { this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`); } handleMoveUp = id => { const { status, ancestorsIds, descendantsIds } = this.props; if (id === status.get('id')) { this._selectChild(ancestorsIds.size - 1); } else { let index = ancestorsIds.indexOf(id); if (index === -1) { index = descendantsIds.indexOf(id); this._selectChild(ancestorsIds.size + index); } else { this._selectChild(index - 1); } } } handleMoveDown = id => { const { status, ancestorsIds, descendantsIds } = this.props; if (id === status.get('id')) { this._selectChild(ancestorsIds.size + 1); } else { let index = ancestorsIds.indexOf(id); if (index === -1) { index = descendantsIds.indexOf(id); this._selectChild(ancestorsIds.size + index + 2); } else { this._selectChild(index + 1); } } } _selectChild (index) { const element = this.node.querySelectorAll('.focusable')[index]; if (element) { element.focus(); } } renderChildren (list) { return list.map(id => ( <StatusContainer key={id} id={id} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} /> )); } setRef = c => { this.node = c; } componentDidUpdate () { if (this._scrolledIntoView) { return; } const { status, ancestorsIds } = this.props; if (status && ancestorsIds && ancestorsIds.size > 0) { const element = this.node.querySelectorAll('.focusable')[ancestorsIds.size - 1]; element.scrollIntoView(true); this._scrolledIntoView = true; } } componentWillUnmount () { detachFullscreenListener(this.onFullScreenChange); } onFullScreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } render () { let ancestors, descendants; const { status, ancestorsIds, descendantsIds } = this.props; const { fullscreen } = this.state; if (status === null) { return ( <Column> <ColumnBackButton /> <MissingIndicator /> </Column> ); } if (ancestorsIds && ancestorsIds.size > 0) { ancestors = <div>{this.renderChildren(ancestorsIds)}</div>; } if (descendantsIds && descendantsIds.size > 0) { descendants = <div>{this.renderChildren(descendantsIds)}</div>; } const handlers = { moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, openProfile: this.handleHotkeyOpenProfile, }; return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='thread'> <div className={classNames('scrollable', 'detailed-status__wrapper', { fullscreen })} ref={this.setRef}> {ancestors} <HotKeys handlers={handlers}> <div className='focusable' tabIndex='0'> <DetailedStatus status={status} onOpenVideo={this.handleOpenVideo} onOpenMedia={this.handleOpenMedia} /> <ActionBar status={status} onReply={this.handleReplyClick} onFavourite={this.handleFavouriteClick} onReblog={this.handleReblogClick} onDelete={this.handleDeleteClick} onMention={this.handleMentionClick} onMute={this.handleMuteClick} onMuteConversation={this.handleConversationMuteClick} onBlock={this.handleBlockClick} onReport={this.handleReport} onPin={this.handlePin} onEmbed={this.handleEmbed} /> </div> </HotKeys> {descendants} </div> </ScrollContainer> </Column> ); } }
gh-page/src/Components/GitHubRepoList.js
metodiobetsanov/metodiobetsanov.github.io
import React from 'react'; import axios from 'axios'; import CardHeader from "@material-ui/core/CardHeader"; import {Divider, makeStyles} from "@material-ui/core"; import CardContent from "@material-ui/core/CardContent"; import List from "@material-ui/core/List"; import Card from "@material-ui/core/Card"; import GitHubRepoListItem from "./GitHubRepoListItem"; const API_URL = 'https://api.github.com/users/metodiobetsanov/repos'; const classes = makeStyles(theme => ({ root: { flexGrow: 1, }, card: { margin: theme.spacing(2,2), padding: theme.spacing(2,2), }, })); class GetRepoList extends React.Component { state = { repos: [] }; componentWillMount() { axios.get(API_URL).then(response => response.data) .then((data) => { this.setState({ repos: data }); console.log(data); }) } render(){ return( <Card className={classes.card}> <CardHeader title="My GitHub" /> <Divider /> <CardContent> <List> {this.state.repos.map((repo) => GitHubRepoListItem(repo))} </List> </CardContent> </Card> ) } } export default GetRepoList;
1.YouTube-API-Search/src/components/video-list-item.js
Branimir123/Learning-React
import React from 'react'; const VideoListItem = ({video, onVideoSelect}) => { const imageUrl = video.snippet.thumbnails.default.url; const videoTitle = video.snippet.title; return ( <li onClick={() => onVideoSelect(video)} className="list-group-item"> <div className="video-list media"> <div className="media-left"> <img className="media-object" src={imageUrl} alt=""/> </div> </div> <div className="media-body"> <div className="media-heading">{videoTitle}</div> </div> </li> ); }; export default VideoListItem;
src/components/images/adventure-boss.js
vFujin/HearthLounge
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; const ExtensionBossImg = ({extension, wing, boss}) =>{ return <img src={boss.img} alt={_.startCase(boss.url)} />; }; export default ExtensionBossImg; ExtensionBossImg.propTypes = { extension: PropTypes.string.isRequired, wing: PropTypes.string.isRequired, boss: PropTypes.shape({ img: PropTypes.string, url: PropTypes.string }).isRequired };
app/javascript/mastodon/features/ui/components/column_subheading.js
dwango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
app/javascript/mastodon/features/ui/components/doodle_modal.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Button from '../../../components/button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Atrament from 'atrament'; // the doodling library import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { doodleSet, uploadCompose } from '../../../actions/compose'; import IconButton from '../../../components/icon_button'; import { debounce, mapValues } from 'lodash'; import classNames from 'classnames'; // palette nicked from MyPaint, CC0 const palette = [ ['rgb( 0, 0, 0)', 'Black'], ['rgb( 38, 38, 38)', 'Gray 15'], ['rgb( 77, 77, 77)', 'Grey 30'], ['rgb(128, 128, 128)', 'Grey 50'], ['rgb(171, 171, 171)', 'Grey 67'], ['rgb(217, 217, 217)', 'Grey 85'], ['rgb(255, 255, 255)', 'White'], ['rgb(128, 0, 0)', 'Maroon'], ['rgb(209, 0, 0)', 'English-red'], ['rgb(255, 54, 34)', 'Tomato'], ['rgb(252, 60, 3)', 'Orange-red'], ['rgb(255, 140, 105)', 'Salmon'], ['rgb(252, 232, 32)', 'Cadium-yellow'], ['rgb(243, 253, 37)', 'Lemon yellow'], ['rgb(121, 5, 35)', 'Dark crimson'], ['rgb(169, 32, 62)', 'Deep carmine'], ['rgb(255, 140, 0)', 'Orange'], ['rgb(255, 168, 18)', 'Dark tangerine'], ['rgb(217, 144, 88)', 'Persian orange'], ['rgb(194, 178, 128)', 'Sand'], ['rgb(255, 229, 180)', 'Peach'], ['rgb(100, 54, 46)', 'Bole'], ['rgb(108, 41, 52)', 'Dark cordovan'], ['rgb(163, 65, 44)', 'Chestnut'], ['rgb(228, 136, 100)', 'Dark salmon'], ['rgb(255, 195, 143)', 'Apricot'], ['rgb(255, 219, 188)', 'Unbleached silk'], ['rgb(242, 227, 198)', 'Straw'], ['rgb( 53, 19, 13)', 'Bistre'], ['rgb( 84, 42, 14)', 'Dark chocolate'], ['rgb(102, 51, 43)', 'Burnt sienna'], ['rgb(184, 66, 0)', 'Sienna'], ['rgb(216, 153, 12)', 'Yellow ochre'], ['rgb(210, 180, 140)', 'Tan'], ['rgb(232, 204, 144)', 'Dark wheat'], ['rgb( 0, 49, 83)', 'Prussian blue'], ['rgb( 48, 69, 119)', 'Dark grey blue'], ['rgb( 0, 71, 171)', 'Cobalt blue'], ['rgb( 31, 117, 254)', 'Blue'], ['rgb(120, 180, 255)', 'Bright french blue'], ['rgb(171, 200, 255)', 'Bright steel blue'], ['rgb(208, 231, 255)', 'Ice blue'], ['rgb( 30, 51, 58)', 'Medium jungle green'], ['rgb( 47, 79, 79)', 'Dark slate grey'], ['rgb( 74, 104, 93)', 'Dark grullo green'], ['rgb( 0, 128, 128)', 'Teal'], ['rgb( 67, 170, 176)', 'Turquoise'], ['rgb(109, 174, 199)', 'Cerulean frost'], ['rgb(173, 217, 186)', 'Tiffany green'], ['rgb( 22, 34, 29)', 'Gray-asparagus'], ['rgb( 36, 48, 45)', 'Medium dark teal'], ['rgb( 74, 104, 93)', 'Xanadu'], ['rgb(119, 198, 121)', 'Mint'], ['rgb(175, 205, 182)', 'Timberwolf'], ['rgb(185, 245, 246)', 'Celeste'], ['rgb(193, 255, 234)', 'Aquamarine'], ['rgb( 29, 52, 35)', 'Cal Poly Pomona'], ['rgb( 1, 68, 33)', 'Forest green'], ['rgb( 42, 128, 0)', 'Napier green'], ['rgb(128, 128, 0)', 'Olive'], ['rgb( 65, 156, 105)', 'Sea green'], ['rgb(189, 246, 29)', 'Green-yellow'], ['rgb(231, 244, 134)', 'Bright chartreuse'], ['rgb(138, 23, 137)', 'Purple'], ['rgb( 78, 39, 138)', 'Violet'], ['rgb(193, 75, 110)', 'Dark thulian pink'], ['rgb(222, 49, 99)', 'Cerise'], ['rgb(255, 20, 147)', 'Deep pink'], ['rgb(255, 102, 204)', 'Rose pink'], ['rgb(255, 203, 219)', 'Pink'], ['rgb(255, 255, 255)', 'White'], ['rgb(229, 17, 1)', 'RGB Red'], ['rgb( 0, 255, 0)', 'RGB Green'], ['rgb( 0, 0, 255)', 'RGB Blue'], ['rgb( 0, 255, 255)', 'CMYK Cyan'], ['rgb(255, 0, 255)', 'CMYK Magenta'], ['rgb(255, 255, 0)', 'CMYK Yellow'], ]; // re-arrange to the right order for display let palReordered = []; for (let row = 0; row < 7; row++) { for (let col = 0; col < 11; col++) { palReordered.push(palette[col * 7 + row]); } palReordered.push(null); // null indicates a <br /> } // Utility for converting base64 image to binary for upload // https://stackoverflow.com/questions/35940290/how-to-convert-base64-string-to-javascript-file-object-like-as-from-file-input-f function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } const DOODLE_SIZES = { normal: [500, 500, 'Square 500'], tootbanner: [702, 330, 'Tootbanner'], s640x480: [640, 480, '640×480 - 480p'], s800x600: [800, 600, '800×600 - SVGA'], s720x480: [720, 405, '720x405 - 16:9'], }; const mapStateToProps = state => ({ options: state.getIn(['compose', 'doodle']), }); const mapDispatchToProps = dispatch => ({ /** Set options in the redux store */ setOpt: (opts) => dispatch(doodleSet(opts)), /** Submit doodle for upload */ submit: (file) => dispatch(uploadCompose([file])), }); /** * Doodling dialog with drawing canvas * * Keyboard shortcuts: * - Delete: Clear screen, fill with background color * - Backspace, Ctrl+Z: Undo one step * - Ctrl held while drawing: Use background color * - Shift held while clicking screen: Use fill tool * * Palette: * - Left mouse button: pick foreground * - Ctrl + left mouse button: pick background * - Right mouse button: pick background */ @connect(mapStateToProps, mapDispatchToProps) export default class DoodleModal extends ImmutablePureComponent { static propTypes = { options: ImmutablePropTypes.map, onClose: PropTypes.func.isRequired, setOpt: PropTypes.func.isRequired, submit: PropTypes.func.isRequired, }; //region Option getters/setters /** Foreground color */ get fg () { return this.props.options.get('fg'); } set fg (value) { this.props.setOpt({ fg: value }); } /** Background color */ get bg () { return this.props.options.get('bg'); } set bg (value) { this.props.setOpt({ bg: value }); } /** Swap Fg and Bg for drawing */ get swapped () { return this.props.options.get('swapped'); } set swapped (value) { this.props.setOpt({ swapped: value }); } /** Mode - 'draw' or 'fill' */ get mode () { return this.props.options.get('mode'); } set mode (value) { this.props.setOpt({ mode: value }); } /** Base line weight */ get weight () { return this.props.options.get('weight'); } set weight (value) { this.props.setOpt({ weight: value }); } /** Drawing opacity */ get opacity () { return this.props.options.get('opacity'); } set opacity (value) { this.props.setOpt({ opacity: value }); } /** Adaptive stroke - change width with speed */ get adaptiveStroke () { return this.props.options.get('adaptiveStroke'); } set adaptiveStroke (value) { this.props.setOpt({ adaptiveStroke: value }); } /** Smoothing (for mouse drawing) */ get smoothing () { return this.props.options.get('smoothing'); } set smoothing (value) { this.props.setOpt({ smoothing: value }); } /** Size preset */ get size () { return this.props.options.get('size'); } set size (value) { this.props.setOpt({ size: value }); } //endregion /** Key up handler */ handleKeyUp = (e) => { if (e.target.nodeName === 'INPUT') return; if (e.key === 'Delete') { e.preventDefault(); this.handleClearBtn(); return; } if (e.key === 'Backspace' || (e.key === 'z' && (e.ctrlKey || e.metaKey))) { e.preventDefault(); this.undo(); } if (e.key === 'Control' || e.key === 'Meta') { this.controlHeld = false; this.swapped = false; } if (e.key === 'Shift') { this.shiftHeld = false; this.mode = 'draw'; } }; /** Key down handler */ handleKeyDown = (e) => { if (e.key === 'Control' || e.key === 'Meta') { this.controlHeld = true; this.swapped = true; } if (e.key === 'Shift') { this.shiftHeld = true; this.mode = 'fill'; } }; /** * Component installed in the DOM, do some initial set-up */ componentDidMount () { this.controlHeld = false; this.shiftHeld = false; this.swapped = false; window.addEventListener('keyup', this.handleKeyUp, false); window.addEventListener('keydown', this.handleKeyDown, false); }; /** * Tear component down */ componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp, false); window.removeEventListener('keydown', this.handleKeyDown, false); if (this.sketcher) this.sketcher.destroy(); } /** * Set reference to the canvas element. * This is called during component init * * @param elem - canvas element */ setCanvasRef = (elem) => { this.canvas = elem; if (elem) { elem.addEventListener('dirty', () => { this.saveUndo(); this.sketcher._dirty = false; }); elem.addEventListener('click', () => { // sketcher bug - does not fire dirty on fill if (this.mode === 'fill') { this.saveUndo(); } }); // prevent context menu elem.addEventListener('contextmenu', (e) => { e.preventDefault(); }); elem.addEventListener('mousedown', (e) => { if (e.button === 2) { this.swapped = true; } }); elem.addEventListener('mouseup', (e) => { if (e.button === 2) { this.swapped = this.controlHeld; } }); this.initSketcher(elem); this.mode = 'draw'; // Reset mode - it's confusing if left at 'fill' } }; /** * Set up the sketcher instance * * @param canvas - canvas element. Null if we're just resizing */ initSketcher (canvas = null) { const sizepreset = DOODLE_SIZES[this.size]; if (this.sketcher) this.sketcher.destroy(); this.sketcher = new Atrament(canvas || this.canvas, sizepreset[0], sizepreset[1]); if (canvas) { this.ctx = this.sketcher.context; this.updateSketcherSettings(); } this.clearScreen(); } /** * Done button handler */ onDoneButton = () => { const dataUrl = this.sketcher.toImage(); const file = dataURLtoFile(dataUrl, 'doodle.png'); this.props.submit(file); this.props.onClose(); // close dialog }; /** * Cancel button handler */ onCancelButton = () => { if (this.undos.length > 1 && !confirm('Discard doodle? All changes will be lost!')) { return; } this.props.onClose(); // close dialog }; /** * Update sketcher options based on state */ updateSketcherSettings () { if (!this.sketcher) return; if (this.oldSize !== this.size) this.initSketcher(); this.sketcher.color = (this.swapped ? this.bg : this.fg); this.sketcher.opacity = this.opacity; this.sketcher.weight = this.weight; this.sketcher.mode = this.mode; this.sketcher.smoothing = this.smoothing; this.sketcher.adaptiveStroke = this.adaptiveStroke; this.oldSize = this.size; } /** * Fill screen with background color */ clearScreen = () => { this.ctx.fillStyle = this.bg; this.ctx.fillRect(-1, -1, this.canvas.width+2, this.canvas.height+2); this.undos = []; this.doSaveUndo(); }; /** * Undo one step */ undo = () => { if (this.undos.length > 1) { this.undos.pop(); const buf = this.undos.pop(); this.sketcher.clear(); this.ctx.putImageData(buf, 0, 0); this.doSaveUndo(); } }; /** * Save canvas content into the undo buffer immediately */ doSaveUndo = () => { this.undos.push(this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)); }; /** * Called on each canvas change. * Saves canvas content to the undo buffer after some period of inactivity. */ saveUndo = debounce(() => { this.doSaveUndo(); }, 100); /** * Palette left click. * Selects Fg color (or Bg, if Control/Meta is held) * * @param e - event */ onPaletteClick = (e) => { const c = e.target.dataset.color; if (this.controlHeld) { this.bg = c; } else { this.fg = c; } e.target.blur(); e.preventDefault(); }; /** * Palette right click. * Selects Bg color * * @param e - event */ onPaletteRClick = (e) => { this.bg = e.target.dataset.color; e.target.blur(); e.preventDefault(); }; /** * Handle click on the Draw mode button * * @param e - event */ setModeDraw = (e) => { this.mode = 'draw'; e.target.blur(); }; /** * Handle click on the Fill mode button * * @param e - event */ setModeFill = (e) => { this.mode = 'fill'; e.target.blur(); }; /** * Handle click on Smooth checkbox * * @param e - event */ tglSmooth = (e) => { this.smoothing = !this.smoothing; e.target.blur(); }; /** * Handle click on Adaptive checkbox * * @param e - event */ tglAdaptive = (e) => { this.adaptiveStroke = !this.adaptiveStroke; e.target.blur(); }; /** * Handle change of the Weight input field * * @param e - event */ setWeight = (e) => { this.weight = +e.target.value || 1; }; /** * Set size - clalback from the select box * * @param e - event */ changeSize = (e) => { let newSize = e.target.value; if (newSize === this.oldSize) return; if (this.undos.length > 1 && !confirm('Change size? This will erase your drawing!')) { return; } this.size = newSize; }; handleClearBtn = () => { if (this.undos.length > 1 && !confirm('Clear screen? This will erase your drawing!')) { return; } this.clearScreen(); }; /** * Render the component */ render () { this.updateSketcherSettings(); return ( <div className='modal-root__modal doodle-modal'> <div className='doodle-modal__container'> <canvas ref={this.setCanvasRef} /> </div> <div className='doodle-modal__action-bar'> <div className='doodle-toolbar'> <Button text='Done' onClick={this.onDoneButton} /> <Button text='Cancel' onClick={this.onCancelButton} /> </div> <div className='filler' /> <div className='doodle-toolbar with-inputs'> <div> <label htmlFor='dd_smoothing'>Smoothing</label> <span className='val'> <input type='checkbox' id='dd_smoothing' onChange={this.tglSmooth} checked={this.smoothing} /> </span> </div> <div> <label htmlFor='dd_adaptive'>Adaptive</label> <span className='val'> <input type='checkbox' id='dd_adaptive' onChange={this.tglAdaptive} checked={this.adaptiveStroke} /> </span> </div> <div> <label htmlFor='dd_weight'>Weight</label> <span className='val'> <input type='number' min={1} id='dd_weight' value={this.weight} onChange={this.setWeight} /> </span> </div> <div> <select aria-label='Canvas size' onInput={this.changeSize} defaultValue={this.size}> { Object.values(mapValues(DOODLE_SIZES, (val, k) => <option key={k} value={k}>{val[2]}</option> )) } </select> </div> </div> <div className='doodle-toolbar'> <IconButton icon='pencil' title='Draw' label='Draw' onClick={this.setModeDraw} size={18} active={this.mode === 'draw'} inverted /> <IconButton icon='bath' title='Fill' label='Fill' onClick={this.setModeFill} size={18} active={this.mode === 'fill'} inverted /> <IconButton icon='undo' title='Undo' label='Undo' onClick={this.undo} size={18} inverted /> <IconButton icon='trash' title='Clear' label='Clear' onClick={this.handleClearBtn} size={18} inverted /> </div> <div className='doodle-palette'> { palReordered.map((c, i) => c === null ? <br key={i} /> : <button key={i} style={{ backgroundColor: c[0] }} onClick={this.onPaletteClick} onContextMenu={this.onPaletteRClick} data-color={c[0]} title={c[1]} className={classNames({ 'foreground': this.fg === c[0], 'background': this.bg === c[0], })} /> ) } </div> </div> </div> ); } }
src/popup/components/Pack/MorePakage.js
fluany/fluany
/** * @fileOverview A component to click and see more packages * @name MorePakage.js * @license GNU General Public License v3.0 */ import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { changePagination } from 'actions/flags' import * as translator from 'shared/constants/i18n' export const MorePackage = ({ packs, filterPackage, paginationPackage, onChangePagination }) => { const isPagination = paginationPackage >= packs.length || filterPackage !== '' return ( <section className={`more-package--content ${ isPagination ? 'more-package--hidden' : '' }`} > <button className='more-package--button btn' onClick={() => onChangePagination()} > + {translator.PACK_LOAD_MORE} </button> </section> ) } const mapStateToProps = state => ({ paginationPackage: state.flags.paginationPackage, filterPackage: state.flags.filterPackage, packs: state.packs }) function mapDispatchToProps (dispatch) { return { onChangePagination: () => dispatch(changePagination()) } } const { func, string, number, array } = PropTypes /** * PropTypes * @property {Function} onChangePagination A action to change pagination flag * @property {Array} packs All the packs availables * @property {String} filterPackage A flag to know if is search anything(input value) * @property {Number} paginationPackage A flag to know pagination number */ MorePackage.propTypes = { onChangePagination: func.isRequired, packs: array.isRequired, filterPackage: string.isRequired, paginationPackage: number.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(MorePackage)
app/containers/LocaleToggle/index.js
omniva/react
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { selectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
frontend/src/app/components/ExperimentPreFeedbackDialog.js
mozilla/testpilot
import React from 'react'; import classnames from 'classnames'; export default class ExperimentPreFeedbackDialog extends React.Component { render() { const { experiment, surveyURL } = this.props; const l10nArgs = JSON.stringify({ title: experiment.title }); return ( <div className="modal-container"> <div className={classnames('modal', 'tour-modal')}> <header className="tour-header-wrapper"> <h3 className="tour-header" data-l10n-id="experimentPreFeedbackTitle" data-l10n-args={l10nArgs}>{experiment.title} Feedback</h3> <div className="tour-cancel" onClick={e => this.cancel(e)}/> </header> <div className="tour-content"> <div className="tour-image"> <img src={experiment.pre_feedback_image} /> <div className="fade" /> </div> <div className="tour-text" dangerouslySetInnerHTML={{ __html: experiment.pre_feedback_copy }} /> <div className="tour-text"> <a data-l10n-id="experimentPreFeedbackLinkCopy" data-l10n-args={l10nArgs} onClick={e => this.feedback(e)} href={surveyURL}>Give feedback about the {experiment.title} experiment</a> </div> </div> </div> </div> ); } feedback(e) { e.preventDefault(); this.props.sendToGA('event', { eventCategory: 'ExperimentDetailsPage Interactions', eventAction: 'button click', eventLabel: 'give feedback', outboundURL: e.target.getAttribute('href') }); } cancel(e) { e.preventDefault(); this.props.sendToGA('event', { eventCategory: 'ExperimentDetailsPage Interactions', eventAction: 'button click', eventLabel: 'cancel feedback' }); this.props.onCancel(e); } } ExperimentPreFeedbackDialog.propTypes = { experiment: React.PropTypes.object.isRequired, surveyURL: React.PropTypes.string.isRequired, onCancel: React.PropTypes.func.isRequired, sendToGA: React.PropTypes.func.isRequired };
src/containers/app/vouchers/voucher_summary.js
w280561543/financial
import React from 'react'; class VoucherSummary extends React.Component { render() { return(<div>VoucherSummary</div>); } } export default VoucherSummary;
src/svg-icons/image/filter-frames.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterFrames = (props) => ( <SvgIcon {...props}> <path d="M20 4h-4l-4-4-4 4H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H4V6h4.52l3.52-3.5L15.52 6H20v14zM18 8H6v10h12"/> </SvgIcon> ); ImageFilterFrames = pure(ImageFilterFrames); ImageFilterFrames.displayName = 'ImageFilterFrames'; ImageFilterFrames.muiName = 'SvgIcon'; export default ImageFilterFrames;
lib/animatedPull.ios.js
evetstech/react-native-animated-ptr
import React from 'react' import { View, StyleSheet, Animated, } from 'react-native' import TimedAnimation from '../animations/TimedAnimation'; import ScrollAnimation from '../animations/ScrollAnimation'; import FadeAnimation from '../animations/FadeAnimation'; class AnimatedPTR extends React.Component { constructor(props) { super(props); this.state = { shouldTriggerRefresh: false, scrollY : new Animated.Value(0), isScrollFree: true, } } static propTypes = { /** * Refresh state set by parent to trigger refresh * @type {Boolean} */ isRefreshing : React.PropTypes.bool.isRequired, /** * Sets pull distance for how far the Y axis needs to be pulled before a refresh event is triggered * @type {Integer} */ minPullDistance : React.PropTypes.number, /** * Callback for when the refreshing state occurs * @type {Function} */ onRefresh : React.PropTypes.func.isRequired, /** * The content view which should be passed in as a scrollable type (i.e ScrollView or ListView) * @type {Object} */ contentComponent: React.PropTypes.object.isRequired, /** * The content view's background color, not to be mistaken with the content component's background color * @type {string} */ contentBackgroundColor: React.PropTypes.string, /** * The pull to refresh background color. * @type {string} */ PTRbackgroundColor: React.PropTypes.string, /** * Custom onScroll event * @type {Function} */ onScroll: React.PropTypes.func } static defaultProps = { minPullDistance : 120, PTRbackgroundColor: 'white', contentBackgroundColor: 'white' } componentDidMount() { this.state.scrollY.addListener((value) => this.onScrollTrigger(value)); } componentWillUnmount() { this.state.scrollY.removeAllListeners(); } onScrollTrigger(distance) { if(distance.value <= -this.props.minPullDistance) { if(!this.state.shouldTriggerRefresh) { return this.setState({shouldTriggerRefresh: true}); } } else if(this.state.shouldTriggerRefresh) { return this.setState({shouldTriggerRefresh: false}); } } onScrollRelease() { if(!this.props.isRefreshing && this.state.shouldTriggerRefresh) { this.refs.PTR_ScrollComponent.scrollTo({y: -this.props.minPullDistance}) this.setState({isScrollFree: false}); this.props.onRefresh(); } } componentWillReceiveProps(props) { if(this.props.isRefreshing !== props.isRefreshing) { if(!props.isRefreshing) { this.refs.PTR_ScrollComponent.scrollTo({y: 0}); this.setState({isScrollFree: true}); } } } render() { const onScroll = this.props.onScroll let onScrollEvent = (event) => { if (onScroll) { onScroll(event) } this.state.scrollY.setValue(event.nativeEvent.contentOffset.y) }; let animateHeight = this.state.scrollY.interpolate({ inputRange: [-this.props.minPullDistance,0], outputRange: [this.props.minPullDistance, 0] }); return ( <View style={{flex:1, zIndex:-100,backgroundColor: this.props.contentBackgroundColor}}> <Animated.View style={{height: animateHeight,backgroundColor: this.props.PTRbackgroundColor}}> {React.Children.map(this.props.children, (child) => { return React.cloneElement(child, { isRefreshing: this.props.isRefreshing, scrollY: this.state.scrollY, minPullDistance: this.props.minPullDistance }); })} </Animated.View> <View style={styles.contentView}> {React.cloneElement(this.props.contentComponent, { scrollEnabled: this.state.isScrollFree, onScroll: onScrollEvent, scrollEventThrottle: 16, onResponderRelease: this.onScrollRelease.bind(this), ref:'PTR_ScrollComponent', })} </View> </View> ) } } const styles = StyleSheet.create({ contentView: { backgroundColor: 'transparent', position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }, }); AnimatedPTR.TimedAnimation = TimedAnimation; AnimatedPTR.ScrollAnimation = ScrollAnimation; AnimatedPTR.FadeAnimation = FadeAnimation; module.exports = AnimatedPTR;
src/scripts/views/components/avatar.js
TayLang/IronPong
import React from 'react' import ACTIONS from '../../actions.js' import STORE from '../../store.js' var Avatar = React.createClass({ render: function(){ return(<div className = 'avatar-wrapper'> </div>) } }) export default Avatar
src/store/shared/containers/category.js
cezerin/cezerin
import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { mapStateToProps, mapDispatchToProps } from '../containerProps'; import { CategoryContainer } from 'theme'; export default withRouter( connect( mapStateToProps, mapDispatchToProps )(CategoryContainer) );
test/integration/initial-ref/pages/index.js
JeromeFitz/next.js
import React from 'react' class App extends React.Component { constructor() { super() this.divRef = React.createRef() this.state = { refHeight: 0, } } componentDidMount() { const refHeight = this.divRef.current.clientHeight this.setState({ refHeight }) } render() { const { refHeight } = this.state return ( <div ref={this.divRef}> <h1>DOM Ref test using 9.2.0</h1> <code id="ref-val">{`this component is ${refHeight}px tall`}</code> </div> ) } } export default App
src/components/LocaleFormattedMessage/index.js
hasibsahibzada/quran.com-frontend
import React from 'react'; import { intlShape, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; const LocaleFormattedMessage = ({ id, defaultMessage, intl, values, className }) => ( <span className={`${intl.messages.local} ${className}`}> <FormattedMessage id={id} defaultMessage={defaultMessage} values={values} /> </span> ); LocaleFormattedMessage.propTypes = { id: PropTypes.string.isRequired, className: PropTypes.string, defaultMessage: PropTypes.string, intl: intlShape.isRequired, values: PropTypes.object // eslint-disable-line }; LocaleFormattedMessage.defaultPropTypes = { className: '' }; export default injectIntl(LocaleFormattedMessage);
src/routes/Login/Login.js
peksi/ilmomasiina
import React from 'react'; import PropTypes from 'prop-types'; import Formsy from 'formsy-react'; import { Input } from 'formsy-react-components'; import { connect } from 'react-redux'; import * as AdminActions from '../../modules/admin/actions'; class Login extends React.Component { static propTypes = { loginError: PropTypes.bool, loginLoading: PropTypes.bool, login: PropTypes.func, }; constructor(props) { super(props); this.state = { email: '', password: '', }; } render() { return ( <div className="container" style={{ maxWidth: '400px' }}> <h1>Kirjaudu</h1> {this.props.loginError ? <p>Kirjautuminen epäonnistui</p> : ''} <Formsy.Form> <Input value={this.state.email} onChange={(key, value) => this.setState({ email: value })} name="email" label="Sähköposti" title="Sähköposti" placeholder="[email protected]" layout="vertical" required /> <Input value={this.state.password} onChange={(key, value) => this.setState({ password: value })} name="password" label="Salasana" title="Salasana" type="password" placeholder="••••••••" layout="vertical" required /> <button className="btn btn-default" onClick={(e) => { e.preventDefault(); this.props.login(this.state.email, this.state.password); }} > Kirjaudu </button> </Formsy.Form> </div> ); } } const mapStateToProps = state => ({ loginError: state.admin.loginError, loginLoading: state.admin.loginLoading, }); const mapDispatchToProps = { login: AdminActions.login, }; export default connect( mapStateToProps, mapDispatchToProps, )(Login);
src/components/user/LoginFormContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { Grid, Row, Col } from 'react-flexbox-grid/lib'; import { FormattedMessage, FormattedHTMLMessage, injectIntl } from 'react-intl'; import LoginForm from './LoginForm'; import PageTitle from '../common/PageTitle'; const localMessages = { loginTitle: { id: 'login.title', defaultMessage: 'Login' }, }; class LoginContainer extends React.Component { UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.isLoggedIn) { this.context.router.push('/home'); } } render() { const { isLoggedIn } = this.props.intl; const className = `logged-in-${isLoggedIn}`; return ( <> <Grid> <PageTitle value={localMessages.loginTitle} /> <Row> <Col lg={12} className={className}> <h2><FormattedMessage {...localMessages.loginTitle} /></h2> </Col> </Row> <Row> <Col lg={4} className={className}> <LoginForm location={this.props.location} /> </Col> </Row> </Grid> </> ); } } LoginContainer.propTypes = { isLoggedIn: PropTypes.bool.isRequired, intl: PropTypes.object.isRequired, location: PropTypes.object, }; LoginContainer.contextTypes = { router: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ isLoggedIn: state.user.isLoggedIn, }); export default injectIntl( connect(mapStateToProps)( LoginContainer ) );
indico/modules/events/editing/client/js/management/editable_type/review_conditions/context.js
pferreir/indico
// This file is part of Indico. // Copyright (C) 2002 - 2021 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import React from 'react'; const ReviewConditionsContext = React.createContext(null); export default ReviewConditionsContext;
tests/Rules-equals-spec.js
yesmeck/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import immediate from './utils/immediate'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="equals:foo" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass when the value is equal': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail when the value is not equal': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="fo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={''}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } };
src/components/ui/List.js
shojil/bifapp
/** * List * <List><ListView /></List> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { List } from 'react-native-elements'; // Consts and Libs import { AppColors } from '@theme/'; /* Component ==================================================================== */ class CustomList extends Component { static propTypes = { containerStyle: PropTypes.oneOfType([ PropTypes.array, PropTypes.shape({}), ]), } static defaultProps = { containerStyle: [], } listProps = () => { // Defaults const props = { ...this.props, containerStyle: [{ margin: 0, backgroundColor: AppColors.background, borderTopColor: AppColors.border, borderBottomWidth: 0, }], }; if (this.props.containerStyle) { props.containerStyle.push(this.props.containerStyle); } return props; } render = () => <List {...this.listProps()} />; } /* Export Component ==================================================================== */ export default CustomList;
src/Grid.js
tonylinyy/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Grid = React.createClass({ propTypes: { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: React.PropTypes.bool, /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; let className = this.props.fluid ? 'container-fluid' : 'container'; return ( <ComponentClass {...this.props} className={classNames(this.props.className, className)}> {this.props.children} </ComponentClass> ); } }); export default Grid;
src/index.js
dynamitechetan/susi_skill_wiki
import React from 'react'; import ReactDOM from 'react-dom'; // import registerServiceWorker from './registerServiceWorker'; import Sidebar from './components/Sidebar/Sidebar'; import Header from './components/Header/Header'; import Chatbox from "./components/Chatbox/Chatbox"; import Home from "./components/Home/Home"; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { BrowserRouter as Router, Route} from "react-router-dom"; class App extends React.Component { render() { return ( <Router> <MuiThemeProvider> <div style={styles.app}> <Sidebar /> <Route path="/home" component={Home} /> <Header /> {/*<Home />*/} </div> </MuiThemeProvider> </Router> ); } } const styles = { app: { width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#eee', flexDirection: "column" } }; ReactDOM.render(<App />, document.getElementById('root'));
app/scenes/Info/components/CodeOfConduct/index.js
Thinkmill/react-conf-app
// @flow import React, { Component } from 'react'; import Icon from 'react-native-vector-icons/Ionicons'; import { ScrollView, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import theme from '../../../../theme'; import Modal from '../../../../components/Modal'; export default class CodeOfConduct extends Component { props: { onClose: () => mixed, }; render() { const { onClose } = this.props; return ( <Modal onClose={onClose} ref="modal" align="bottom" style={{ margin: 30 }} forceDownwardAnimation > <View style={styles.wrapper}> <ScrollView contentContainerStyle={styles.content}> <View> <Text style={[styles.heading, styles.heading1]}> Code of Conduct </Text> </View> <View> <Text style={styles.text}> All delegates, speakers and volunteers at React Conf are required to agree with the following code of conduct. Organizers will enforce this code throughout the event. </Text> </View> <View> <Text style={[styles.heading, styles.heading2]}> The Quick Version </Text> <Text style={styles.text}> Facebook is dedicated to providing a harassment-free conference experience for everyone, regardless of gender, sexual orientation, disability, physical appearance, body size, race, or religion. We do not tolerate harassment of conference participants in any form. Sexual language and imagery is not appropriate for any conference venue, including talks. </Text> <Text style={styles.text}> Conference participants violating these rules may be sanctioned or expelled from the conference without a refund at the discretion of the conference organizers. </Text> </View> <View> <Text style={[styles.heading, styles.heading2]}> The Less Quick Version </Text> <Text style={styles.text}> Harassment includes offensive verbal comments related to gender, sexual orientation, disability, physical appearance, body size, race, religion, sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention. </Text> <Text style={styles.text}> Participants asked to stop any harassing behavior are expected to comply immediately. </Text> <Text style={styles.text}> If a participant engages in harassing behavior, the conference organizers may take any action they deem appropriate, including warning the offender or expulsion from the conference with no refund. </Text> <Text style={styles.text}> If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of conference staff immediately. </Text> <Text style={styles.text}> Conference staff will be happy to help participants contact venue security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the conference. We value your attendance. </Text> <Text style={styles.text}> We expect participants to follow these rules at all conference venues and conference-related social events. </Text> </View> </ScrollView> <TouchableOpacity onPress={() => this.refs.modal.onClose()} style={styles.close} activeOpacity={0.75} > <Icon color={theme.color.gray40} name="ios-arrow-down" size={24} style={{ height: 16, marginTop: -6 }} /> </TouchableOpacity> </View> </Modal> ); } } const BORDER_RADIUS = 6; const styles = StyleSheet.create({ wrapper: { backgroundColor: 'white', borderRadius: BORDER_RADIUS, maxHeight: 400, shadowColor: 'black', shadowOffset: { height: 1, width: 0 }, shadowOpacity: 0.25, shadowRadius: 5, }, content: { padding: theme.fontSize.default, }, // text text: { color: theme.color.gray60, fontSize: 13, lineHeight: theme.fontSize.default, marginTop: theme.fontSize.small, }, heading: { color: theme.color.gray70, fontSize: theme.fontSize.small, fontWeight: 'bold', }, heading1: { fontSize: theme.fontSize.default, }, heading2: { fontSize: theme.fontSize.small, marginTop: theme.fontSize.large, }, // close close: { alignItems: 'center', backgroundColor: theme.color.gray05, borderBottomLeftRadius: BORDER_RADIUS, borderBottomRightRadius: BORDER_RADIUS, height: 40, justifyContent: 'center', shadowColor: 'black', shadowOffset: { height: -1, width: 0 }, shadowOpacity: 0.1, shadowRadius: 0, }, closeText: { color: theme.color.gray40, fontWeight: '500', }, });
client/components/Input/BorderBottom.js
jkettmann/universal-react-relay-starter-kit
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import classnames from 'classnames' const Wrapper = styled.div` position: relative; width: 100%; margin-top: 3px; ` const InactiveBorderBottom = styled.div` width: 100%; height: 1px; background: ${props => props.theme.color.grey3} ` const ActiveBorderBottom = styled.div` position: absolute; left: 49%; width: 2%; height: 2px; top: 0; background: ${props => props.theme.color.primary}; transition: ${props => props.theme.animation.default}; left: 49%; transform-origin: center; opacity: 0; &.active { opacity: 1; transform: scaleX(50); } &.error { background: ${props => props.theme.color.error}; } ` const BorderBottom = ({ className, active, error }) => ( <Wrapper className={className}> <InactiveBorderBottom /> <ActiveBorderBottom className={classnames( active && 'active', error && 'error', )} /> </Wrapper> ) BorderBottom.propTypes = { className: PropTypes.string, active: PropTypes.bool.isRequired, error: PropTypes.bool.isRequired, } BorderBottom.defaultProps = { className: null, } export default BorderBottom
src/config.js
uber-common/vis-academy
import React from 'react'; export const PROJECT_TYPE = 'github'; // 'github' || 'phab' export const PROJECT_NAME = 'vis-academy'; export const PROJECT_ORG = 'uber-common'; export const PROJECT_URL = `https://github.com/${PROJECT_ORG}/${PROJECT_NAME}`; export const PROJECT_DESC = 'An introduction to Uber Visualization libraries.'; export const PROJECTS = { 'deck.gl': 'https://uber.github.io/deck.gl', 'luma.gl': 'https://uber.github.io/luma.gl', 'react-map-gl': 'https://uber.github.io/react-map-gl', 'react-vis': 'https://uber.github.io/react-vis', }; export const HOME_RIGHT = ( <div> <h2>Uber Visualization tutorial</h2> <p className='m-bottom'> This tutorial will show you how to build an app that showcases three of Uber visualization libraries: ReactMapGL for maps, DeckGL to create WebGL-based data overlays and React-Vis for simple charts. </p> <p className='m-bottom'> You will learn how to use these libraries separately, but also how they can be combined to work together. </p> </div> ); export const HOME_BULLETS = [{ text: 'React-friendly', img: 'images/icon-react.svg', }, { text: 'Learn the vis stack', img: 'images/icon-layers.svg', }]; export const GA_TRACKING = 'UA-64694404-18'; export const ADDITIONAL_LINKS = []
client/apps/web/routes.js
defe266/keystone-starter
import React from 'react' import { Route, IndexRoute } from 'react-router' var sd = require('sharify').data; var I18N = sd.I18N; //import Counter from './components/Counter.js' import App from './components/index';//./containers/ import Home from './components/pages/Home'; import Page from './components/pages/Page'; import PageTest from './components/pages/PageTest'; import Page404 from './components/pages/Page404'; function createI18nIndexRoutes(component){ return I18N.langs.map((lang) => { if(lang == I18N.default) return <IndexRoute key={lang} component={component} lang={lang}/> return <Route key={lang} path={'/'+lang} component={component} lang={lang}/> }) } function createI18nRoutes(base, component){ return I18N.langs.map((lang) => { var langPath = lang == I18N.default ? '' : lang+'/'; var url = langPath+base; return <Route key={lang} path={url} component={component} lang={lang}/> }) } /* <IndexRoute component={Home}/> <Route path="/:slug" component={Page} /> <Route path="*" component={Page404} /> */ export default <Route path="/" component={App}> {createI18nIndexRoutes(Home)} {createI18nRoutes("page/:slug", PageTest)} {createI18nRoutes(":slug", Page)} {createI18nRoutes("*", Page404)} </Route>
components/tree/demo/loadData.js
TDFE/td-ui
/* eslint-disable no-unused-vars */ import React from 'react'; import ReactDOM from 'react-dom'; let Tree = require('../index').default; let TreeNode = Tree.TreeNode; function generateTreeNodes(treeNode) { const arr = []; const key = treeNode.props.eventKey; for (let i = 0; i < 3; i++) { arr.push({ name: `leaf ${key}-${i}`, key: `${key}-${i}` }); } return arr; } function setLeaf(treeData, curKey, level) { const loopLeaf = (data, lev) => { const l = lev - 1; data.forEach((item) => { if ((item.key.length > curKey.length) ? item.key.indexOf(curKey) !== 0 : curKey.indexOf(item.key) !== 0) { return; } if (item.children) { loopLeaf(item.children, l); } else if (l < 1) { item.isLeaf = true; } }); }; loopLeaf(treeData, level + 1); } function getNewTreeData(treeData, curKey, child, level) { const loop = (data) => { if (level < 1 || curKey.length - 3 > level * 2) return; data.forEach((item) => { if (curKey.indexOf(item.key) === 0) { if (item.children) { loop(item.children); } else { item.children = child; } } }); }; loop(treeData); setLeaf(treeData, curKey, level); } export default class LoadData extends React.Component { state = { treeData: [] } componentDidMount() { setTimeout(() => { this.setState({ treeData: [ { name: 'pNode 01', key: '0-0' }, { name: 'pNode 02', key: '0-1' }, { name: 'pNode 03', key: '0-2', isLeaf: true } ] }); }, 100); } onSelect = (info) => { console.log('selected', info); } onLoadData = (treeNode) => { return new Promise((resolve) => { setTimeout(() => { const treeData = [...this.state.treeData]; getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2); this.setState({ treeData }); resolve(); }, 1000); }); } onCheck = (checkedKeys, info) => { console.log(checkedKeys); } render() { const loop = data => data.map((item) => { if (item.children) { return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>; } return <TreeNode title={item.name} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0'} />; }); const treeNodes = loop(this.state.treeData); return ( <Tree checkable onCheck={this.onCheck} onSelect={this.onSelect} defaultCheckedKeys={['0-0']} loadData={this.onLoadData}> {treeNodes} </Tree> ); } }
src/Parser/DemonologyWarlock/Modules/Features/GrimoireOfService.js
mwwscott0/WoWAnalyzer
import React from 'react'; import Module from 'Parser/Core/Module'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Combatants from 'Parser/Core/Modules/Combatants'; import { calculateMaxCasts } from 'Parser/Core/getCastEfficiency'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; const SUMMON_COOLDOWN = 90; const GRIMOIRE_IDS = [ SPELLS.GRIMOIRE_FELGUARD.id, // usually useless but for the sake of completeness SPELLS.GRIMOIRE_IMP.id, SPELLS.GRIMOIRE_VOIDWALKER.id, SPELLS.GRIMOIRE_FELHUNTER.id, SPELLS.GRIMOIRE_SUCCUBUS.id, ]; class GrimoireOfService extends Module { static dependencies = { abilityTracker: AbilityTracker, combatants: Combatants, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.GRIMOIRE_OF_SERVICE_TALENT.id); } suggestions(when) { const maxCasts = Math.ceil(calculateMaxCasts(SUMMON_COOLDOWN, this.owner.fightDuration)); const actualCasts = GRIMOIRE_IDS.map(id => this.abilityTracker.getAbility(id).casts || 0).reduce((total, casts) => total + casts, 0); const percentage = actualCasts / maxCasts; when(percentage).isLessThan(0.9) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You should use <SpellLink id={SPELLS.GRIMOIRE_OF_SERVICE_TALENT.id} /> more often, preferably on <SpellLink id={SPELLS.GRIMOIRE_FELGUARD.id} />.</span>) .icon(SPELLS.GRIMOIRE_OF_SERVICE_TALENT.icon) .actual(`${actualCasts} out of ${maxCasts} (${formatPercentage(actual)} %) Grimoire of Service casts.`) .recommended(`> ${formatPercentage(recommended)} % is recommended`) .regular(recommended - 0.1).major(recommended - 0.2); }); } } export default GrimoireOfService;
src/modules/AppRouter.js
Kortelainen/Softala3SuperAda
/*eslint-disable react/prop-types*/ import React from 'react'; import CounterViewContainer from './counter/CounterViewContainer'; import ColorViewContainer from './colors/ColorViewContainer'; import ExampleViewContainer from './exampleView/ExampleViewContainer'; import LoginViewContainer from './login/LoginViewContainer'; import FeedbackViewContainer from './feedback/FeedbackViewContainer'; import MapViewContainer from './map/MapViewContainer'; import TeamViewContainer from './team/TeamViewContainer'; import WelcomeViewContainer from './welcome/WelcomeViewContainer'; import CheckPointViewContainer from './checkpoints/CheckPointViewContainer'; import GoodbyeViewContainer from './goodbye/GoodbyeViewContainer'; import GoodbyeFeedbackViewContainer from './goodbyeFeedback/GoodbyeFeedbackViewContainer'; import TeamPointsViewContainer from './teamPoints/TeamPointsViewContainer'; /** * AppRouter is responsible for mapping a navigator scene to a view */ export default function AppRouter(props) { const key = props.scene.route.key; if (key === 'Counter') { return <CounterViewContainer />; } if (key.indexOf('Color') === 0) { const index = props.scenes.indexOf(props.scene); return ( <ColorViewContainer index={index} /> ); } if (key === 'ExampleView') { return <ExampleViewContainer />; } if (key === 'LoginView') { return <LoginViewContainer />; } if (key === 'FeedbackView') { return <FeedbackViewContainer />; } if (key === 'Welcome') { return <WelcomeViewContainer />; } if (key === 'MapView') { return <MapViewContainer />; } if (key === 'CheckPoints') { return <CheckPointViewContainer />; } if (key === 'TeamView') { return <TeamViewContainer />; } if (key === 'Goodbye') { return <GoodbyeViewContainer />; } if (key === 'GoodbyeFB') { return <GoodbyeFeedbackViewContainer />; } if (key === 'TeamPointsView') { return <TeamPointsViewContainer />; } throw new Error('Unknown navigation key: ' + key); }
src/main.js
abdih17/celebrityMatch
import React from 'react' import ReactDom from 'react-dom' import App from './component/app' ReactDom.render(<App />, document.getElementById('root'))
src/components/common/svg-icons/action/android.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAndroid = (props) => ( <SvgIcon {...props}> <path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/> </SvgIcon> ); ActionAndroid = pure(ActionAndroid); ActionAndroid.displayName = 'ActionAndroid'; ActionAndroid.muiName = 'SvgIcon'; export default ActionAndroid;
tests/fixtures/fixture-children-jsx.js
brekk/glass-menagerie
import React from 'react' const types = React.PropTypes export const ComponentWithKids = (props) => ( <article> <h1>{props.text}</h1> {props.children} </article> ) ComponentWithKids.propTypes = { text: types.string.isRequired, children: types.node } export default ComponentWithKids
app/components/stations/StationValuesGrid.js
sheldhur/Vector
import { remote } from 'electron'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Icon, Popconfirm } from 'antd'; import moment from 'moment'; import resourcePath from '../../lib/resourcePath'; import Grid from '../grid/Grid'; import * as uiActions from '../../actions/ui'; import * as stationActions from '../../actions/station'; import * as app from '../../constants/app'; const { Menu } = remote; class StationGrid extends Component { state = { availableHeight: 'auto', pageSize: 5, pageCurrent: null, }; componentDidMount = () => { window.addEventListener('resize', this.handlerResize); }; componentWillReceiveProps = (nextProps) => { if (!nextProps.isLoading) { if (this.state.availableHeight === 'auto') { setTimeout(() => { this.setPagination(nextProps); }, 300); } else { this.setState({ pageCurrent: this.calcPageCurrent(nextProps, this.state.pageSize) }); } } }; componentWillUnmount = () => { window.removeEventListener('resize', this.handlerResize); this.props.uiActions.setGridSelectedRows(null); }; handlerResize = () => { const { pageSize, availableHeight } = this.calcPageSize(); this.setState({ availableHeight, pageSize, }); }; setPagination = (props) => { const { availableHeight, pageSize } = this.calcPageSize(); const pageCurrent = this.calcPageCurrent(props, pageSize); this.setState({ availableHeight, pageSize, pageCurrent, }); }; calcPageCurrent = (props, pageSize) => { const { values, currentTime } = props; const data = values ? Object.values(values) : []; const currentTimeStr = moment(currentTime).format(app.FORMAT_DATE_SQL); let currentPage = 0; for (let i = 0; i < data.length; i++) { if (data[i].time === currentTimeStr) { currentPage = Math.floor(i / pageSize) + 1; break; } } return currentPage; }; calcPageSize = () => { const grid = ReactDOM.findDOMNode(this.refs.grid); const pagination = grid.querySelector('.ant-pagination'); const theadHeight = grid.querySelector('thead').clientHeight || 0; const paginationHeight = pagination ? pagination.clientHeight : 0; const row = grid.querySelector('tbody > tr'); const rowHeight = row ? row.offsetHeight : 28; const availableHeight = window.innerHeight - grid.getBoundingClientRect().top; const pageSize = Math.floor((availableHeight - theadHeight - (paginationHeight + 16 * 2)) / rowHeight); return { availableHeight, pageSize }; }; handlerPageChange = (page) => { this.setState({ pageCurrent: page }); }; handlerCellChange = (field, id, value, afterAction) => { if (['compX', 'compY', 'compZ'].indexOf(field) !== -1 && value.trim() === '') { value = null; } this.props.stationActions.updateStationValue(id, { [field]: value }, afterAction); }; handlerRowOnContextMenu = (record, index, e) => { if (!e.ctrlKey) { e.preventDefault(); return Menu.buildFromTemplate([ { label: 'Clear values', icon: resourcePath('./assets/icons/eraser.png'), click: () => this.props.stationActions.updateStationValue(record.id, { compX: null, compY: null, compZ: null }) }, { label: 'Delete values', icon: resourcePath('./assets/icons/table-delete-row.png'), click: () => this.props.stationActions.deleteStationValue({ id: record.id }) } ]).popup(remote.getCurrentWindow()); } }; render = () => { const compWidth = 165; const columns = [{ title: 'Time', dataIndex: 'time', hasFilter: true, hasSorter: true, onCell: (record) => ({ onClick: () => this.props.uiActions.setChartCurrentTime(new Date(record.time)) }), }, { title: 'X', dataIndex: 'compX', hasFilter: true, hasSorter: true, render: (text, record, index) => (<Grid.InputCell value={text} onChange={ (value, afterAction) => this.handlerCellChange('compX', record.id, value, afterAction) } />), width: compWidth }, { title: 'Y', dataIndex: 'compY', hasFilter: true, hasSorter: true, render: (text, record, index) => (<Grid.InputCell value={text} onChange={ (value, afterAction) => this.handlerCellChange('compY', record.id, value, afterAction) } />), width: compWidth }, { title: 'Z', dataIndex: 'compZ', hasFilter: true, hasSorter: true, render: (text, record, index) => (<Grid.InputCell value={text} onChange={ (value, afterAction) => this.handlerCellChange('compZ', record.id, value, afterAction) } />), width: compWidth }, { title: '', dataIndex: 'format', hasFilter: true, hasSorter: true, render: (text, record, index) => app.VALUES_CONVERT_FORMAT[text], width: 80 }]; const { values, isLoading, currentTime } = this.props; const currentTimeStr = moment(currentTime).format(app.FORMAT_DATE_SQL); const data = values ? Object.values(values) : []; const rowSelection = { onChange: (selectedRowKeys, selectedRows) => { this.props.uiActions.setGridSelectedRows(selectedRows); }, selections: true }; return ( <div style={{ height: this.state.availableHeight }}> <Grid rowClassName={(record) => (record.time === currentTimeStr ? 'select-row' : '')} ref="grid" rowKey="id" columns={columns} data={data} loading={isLoading} rowSelection={rowSelection} pagination={{ pageSize: this.state.pageSize, showQuickJumper: true, current: this.state.pageCurrent, onChange: this.handlerPageChange }} size="x-small" bordered onRow={(record, index) => ({ onContextMenu: (event) => this.handlerRowOnContextMenu(record, index, event) })} /> </div> ); }; } StationGrid.propTypes = { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), }; StationGrid.defaultProps = { width: '100%', height: '100%', }; function mapStateToProps(state) { return { values: state.station.stationView.values, isLoading: state.station.stationView.isLoading, currentTime: state.ui.chartCurrentTime, }; } function mapDispatchToProps(dispatch) { return { uiActions: bindActionCreators(uiActions, dispatch), stationActions: bindActionCreators(stationActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(StationGrid);
src/components/article/tools/MobileArticleTools.js
hanyulo/twreporter-react
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup' import Link from 'react-router/lib/Link' import { LINK_PREFIX } from '../../../constants/link-prefix' import BackToTopicIcon from '../../../../static/asset/article-back-to-topic-mobile.svg' import BackToTopIcon from '../../../../static/asset/article-back-to-top-mobile.svg' import BookmarkAddedIcon from '../../../../static/asset/added-bookmark-mobile.svg' import BookmarkUnaddedIcon from '../../../../static/asset/add-bookmark-mobile.svg' import PropTypes from 'prop-types' import React from 'react' import soothScroll from 'smoothscroll' import styled from 'styled-components' import styles from './MobileArticleTools.scss' const buttonWidth = 52 const buttonHeight = 52 const IconContainer = styled.div` position: relative; border-radius: 50%; width: ${buttonWidth}px; height: ${buttonHeight}px; background-color: rgba(255, 255, 255, .8); overflow: hidden; img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } cursor: pointer; ` const SubsequentIconContainer = IconContainer.extend` margin-bottom: 20px; ` const BookmarkImg = styled.img` opacity: ${props => (props.showUp ? 1 : 0 )}; transition: opacity 200ms linear; ` const BackToTopBtn = () => ( <IconContainer onClick={() => soothScroll(0)}> <img src={BackToTopIcon} /> </IconContainer> ) const BackToTopicBtn = (props) => ( <Link to={`${LINK_PREFIX.TOPICS}${props.topicSlug}`} title={props.topicTitle}> <SubsequentIconContainer> <img src={BackToTopicIcon} /> </SubsequentIconContainer> </Link> ) BackToTopicBtn.propTypes = { topicSlug: React.PropTypes.string.isRequired, topicTitle: React.PropTypes.string.isRequired } class MobileArticleTools extends React.PureComponent { render() { const { topicTitle, topicSlug, toShow, isBookmarked } = this.props return ( <CSSTransitionGroup transitionName={{ enter: styles['effect-enter'], enterActive: styles['effect-enter-active'], leave: styles['effect-leave'], leaveActive: styles['effect-leave-active'] }} transitionEnterTimeout={500} transitionLeaveTimeout={300} > {!toShow ? null : ( <div className={styles['article-tools-container']}> {!topicSlug ? null : <BackToTopicBtn topicSlug={topicSlug} topicTitle={topicTitle} />} <SubsequentIconContainer onClick={this.props.handleOnClickBookmark}> <BookmarkImg showUp={!isBookmarked} src={BookmarkUnaddedIcon} /> <BookmarkImg showUp={isBookmarked} src={BookmarkAddedIcon} /> </SubsequentIconContainer> <BackToTopBtn /> </div> )} </CSSTransitionGroup> ) } } MobileArticleTools.propTypes = { isBookmarked: PropTypes.bool.isRequired, toShow: PropTypes.bool.isRequired, topicTitle: PropTypes.string, topicSlug: PropTypes.string } MobileArticleTools.defaultProps = { topicTitle: '', topicSlug: '' } export default MobileArticleTools
internals/templates/containers/LanguageProvider/index.js
BartoszBazanski/react-100-pushup-challenge
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
node_modules/react-native-maps/lib/components/MapCallout.js
RahulDesai92/PHR
import PropTypes from 'prop-types'; import React from 'react'; import { StyleSheet, ViewPropTypes, } from 'react-native'; import decorateMapComponent, { SUPPORTED, USES_DEFAULT_IMPLEMENTATION, } from './decorateMapComponent'; const propTypes = { ...ViewPropTypes, tooltip: PropTypes.bool, onPress: PropTypes.func, }; const defaultProps = { tooltip: false, }; class MapCallout extends React.Component { render() { const AIRMapCallout = this.getAirComponent(); return <AIRMapCallout {...this.props} style={[styles.callout, this.props.style]} />; } } MapCallout.propTypes = propTypes; MapCallout.defaultProps = defaultProps; const styles = StyleSheet.create({ callout: { position: 'absolute', }, }); module.exports = decorateMapComponent(MapCallout, { componentType: 'Callout', providers: { google: { ios: SUPPORTED, android: USES_DEFAULT_IMPLEMENTATION, }, }, });
platform/ui/src/contextProviders/LanguageProvider.js
OHIF/Viewers
// Reference > https://reactjs.org/docs/context.html import React from 'react'; import { withTranslation as I18NextWithTranslation, I18nextProvider, } from 'react-i18next'; import i18n from '@ohif/i18n'; const WrapperI18n = Component => { const WrapperComponent = props => ( <I18nextProvider i18n={i18n}> <Component {...props} /> </I18nextProvider> ); return WrapperComponent; }; const withTranslation = namespace => Component => { const TranslatedComponent = props => { return <Component {...props} />; }; return WrapperI18n(I18NextWithTranslation(namespace)(TranslatedComponent)); }; export { withTranslation }; export default withTranslation;
src/esm/components/action/social-button-icon-words/index.js
KissKissBankBank/kitten
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["children"], _excluded2 = ["children"], _excluded3 = ["children"], _excluded4 = ["children"]; import React from 'react'; import { Button } from '../../action/button'; import { FacebookIcon } from '../../graphics/icons/facebook-icon'; import { TwitterIcon } from '../../graphics/icons/twitter-icon'; import { LinkedinIcon } from '../../graphics/icons/linkedin-icon'; import { InstagramIcon } from '../../graphics/icons/instagram-icon'; export var FacebookButtonIconWords = function FacebookButtonIconWords(_ref) { var children = _ref.children, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement(Button, props, /*#__PURE__*/React.createElement(FacebookIcon, { height: "14", width: "7" }), /*#__PURE__*/React.createElement("span", null, children)); }; export var TwitterButtonIconWords = function TwitterButtonIconWords(_ref2) { var children = _ref2.children, props = _objectWithoutPropertiesLoose(_ref2, _excluded2); return /*#__PURE__*/React.createElement(Button, props, /*#__PURE__*/React.createElement(TwitterIcon, { height: "12", width: "15" }), /*#__PURE__*/React.createElement("span", null, children)); }; export var InstagramButtonIconWords = function InstagramButtonIconWords(_ref3) { var children = _ref3.children, props = _objectWithoutPropertiesLoose(_ref3, _excluded3); return /*#__PURE__*/React.createElement(Button, props, /*#__PURE__*/React.createElement(InstagramIcon, { height: "16", width: "16" }), /*#__PURE__*/React.createElement("span", null, children)); }; export var LinkedinButtonIconWords = function LinkedinButtonIconWords(_ref4) { var children = _ref4.children, props = _objectWithoutPropertiesLoose(_ref4, _excluded4); return /*#__PURE__*/React.createElement(Button, props, /*#__PURE__*/React.createElement(LinkedinIcon, { height: "12", width: "12" }), /*#__PURE__*/React.createElement("span", null, children)); }; var defaultProps = { modifier: 'beryllium' }; FacebookButtonIconWords.defaultProps = defaultProps; TwitterButtonIconWords.defaultProps = defaultProps; LinkedinButtonIconWords.defaultProps = defaultProps; InstagramButtonIconWords.defaultProps = defaultProps;
packages/netlify-cms-backend-test/src/AuthenticationPage.js
netlify/netlify-cms
import React from 'react'; import PropTypes from 'prop-types'; import styled from '@emotion/styled'; import { Icon, buttons, shadows, GoBackButton } from 'netlify-cms-ui-default'; const StyledAuthenticationPage = styled.section` display: flex; flex-flow: column nowrap; align-items: center; justify-content: center; height: 100vh; `; const PageLogoIcon = styled(Icon)` color: #c4c6d2; margin-top: -300px; `; const LoginButton = styled.button` ${buttons.button}; ${shadows.dropDeep}; ${buttons.default}; ${buttons.gray}; padding: 0 30px; margin-top: -40px; display: flex; align-items: center; position: relative; ${Icon} { margin-right: 18px; } `; export default class AuthenticationPage extends React.Component { static propTypes = { onLogin: PropTypes.func.isRequired, inProgress: PropTypes.bool, config: PropTypes.object.isRequired, t: PropTypes.func.isRequired, }; componentDidMount() { /** * Allow login screen to be skipped for demo purposes. */ const skipLogin = this.props.config.backend.login === false; if (skipLogin) { this.props.onLogin(this.state); } } handleLogin = e => { e.preventDefault(); this.props.onLogin(this.state); }; render() { const { config, inProgress, t } = this.props; return ( <StyledAuthenticationPage> <PageLogoIcon size="300px" type="netlify-cms" /> <LoginButton disabled={inProgress} onClick={this.handleLogin}> {inProgress ? t('auth.loggingIn') : t('auth.login')} </LoginButton> {config.site_url && <GoBackButton href={config.site_url} t={t}></GoBackButton>} </StyledAuthenticationPage> ); } }
src/components/player-selection.js
RaulEscobarRivas/React-Redux-High-Order-Components
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { updatePlayerSelection } from '../actions'; import { getPositionSelected, getPlayersSelected } from '../reducers'; class PlayerSelection extends Component { constructor(props) { super(props); this.state = { position: this.props.positionSelected, validSelection: false, players: this.props.players, freeSpots: this.props.freeSpots } } unselectAndReturnPlayers() { const unselectedPlayers = {}; for (const player in this.state.players) { Object.assign(unselectedPlayers, this.state.players, this.state.players[player].selected = false) } return unselectedPlayers; } playerSelectedHighlight(player) { if (this.state.players[player].selected === true) return 'selected'; } selectPlayer(player) { if (this.state.freeSpots > 0) { this.setState({ freeSpots: this.state.freeSpots-1 }); return Object.assign({}, this.state.players, this.state.players[player].selected = !this.state.players[player].selected); } else { this.setState({ freeSpots: this.props.freeSpots-1 }); return Object.assign({}, this.unselectAndReturnPlayers(), this.state.players[player].selected = !this.state.players[player].selected); } } clickHandler(player) { this.setState( prevState => { return Object.assign({}, this.state, { players: this.selectPlayer(player) } ); }); this.props.updatePlayerSelection(this.state); } renderPlayers() { const players = Object.keys(this.state.players); return players.map( (player, index) => { const className = this.playerSelectedHighlight(player) ? 'player-selected' : 'player'; return <div key={index} className={className} onClick={() => this.clickHandler(player)}>{this.state.players[player].name}</div>; } ); } render() { return ( <div className="player-selection"> {this.renderPlayers()} </div> ); } } const mapStateToProps = state => { const positionSelected = getPositionSelected(state); return { positionSelected, players: getPlayersSelected(state, positionSelected) } } const mapDispatchToProps = dispatch => { return { updatePlayerSelection: selection => dispatch(updatePlayerSelection(selection)) } } export default connect(mapStateToProps, mapDispatchToProps)(PlayerSelection);
app/components/Header/index.js
Ennovar/clock_it
import React from 'react'; import { FormattedMessage } from 'react-intl'; import { ImgSmall } from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.png'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <ImgSmall src={Banner} alt="Ennovar" /> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/login"> <FormattedMessage {...messages.login} /> </HeaderLink> <HeaderLink to="/dashboard"> <FormattedMessage {...messages.dashboard} /> </HeaderLink> </NavBar> <hr /> </div> ); } } export default Header;
docs/app/Examples/views/Statistic/Variations/StatisticExampleHorizontalGroup.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Statistic } from 'semantic-ui-react' const items = [ { label: 'Views', value: '2,204' }, { label: 'Downloads', value: '3,322' }, { label: 'Tasks', value: '22' }, ] const StatisticExampleHorizontalGroup = () => <Statistic.Group horizontal items={items} /> export default StatisticExampleHorizontalGroup
app/javascript/mastodon/components/admin/Trends.js
ikuradon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import api from 'mastodon/api'; import { FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Hashtag from 'mastodon/components/hashtag'; export default class Trends extends React.PureComponent { static propTypes = { limit: PropTypes.number.isRequired, }; state = { loading: true, data: null, }; componentDidMount () { const { limit } = this.props; api().get('/api/v1/admin/trends/tags', { params: { limit } }).then(res => { this.setState({ loading: false, data: res.data, }); }).catch(err => { console.error(err); }); } render () { const { limit } = this.props; const { loading, data } = this.state; let content; if (loading) { content = ( <div> {Array.from(Array(limit)).map((_, i) => ( <Hashtag key={i} /> ))} </div> ); } else { content = ( <div> {data.map(hashtag => ( <Hashtag key={hashtag.name} name={hashtag.name} href={`/admin/tags/${hashtag.id}`} people={hashtag.history[0].accounts * 1 + hashtag.history[1].accounts * 1} uses={hashtag.history[0].uses * 1 + hashtag.history[1].uses * 1} history={hashtag.history.reverse().map(day => day.uses)} className={classNames(hashtag.requires_review && 'trends__item--requires-review', !hashtag.trendable && !hashtag.requires_review && 'trends__item--disabled')} /> ))} </div> ); } return ( <div className='trends trends--compact'> <h4><FormattedMessage id='trends.trending_now' defaultMessage='Trending now' /></h4> {content} </div> ); } }
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
ge6285790/test
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
src/svg-icons/av/games.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvGames = (props) => ( <SvgIcon {...props}> <path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/> </SvgIcon> ); AvGames = pure(AvGames); AvGames.displayName = 'AvGames'; AvGames.muiName = 'SvgIcon'; export default AvGames;
assets/jqwidgets/demos/react/app/chart/chartprinting/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxChart from '../../../jqwidgets-react/react_jqxchart.js'; import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js'; class App extends React.Component { componentDidMount() { this.refs.printBtn.on('click', () => { let content = window.document.getElementsByClassName('myChart')[0].outerHTML; let newWindow = window.open('', '', 'width=800, height=500'), document = newWindow.document.open(), pageContent = '<!DOCTYPE html>' + '<html>' + '<head>' + '<meta charset="utf-8" />' + '<title>jQWidgets Chart</title>' + '</head>' + '<body>' + content + '</body></html>'; try { document.write(pageContent); document.close(); newWindow.print(); newWindow.close(); } catch (error) { } }); } render() { let source = { datatype: 'csv', datafields: [ { name: 'Country' }, { name: 'GDP' }, { name: 'DebtPercent' }, { name: 'Debt' } ], url: '../sampledata/gdp_dept_2010.txt' }; let dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + source.url + '" : ' + error); } }); let padding = { left: 5, top: 5, right: 5, bottom: 5 }; let titlePadding = { left: 90, top: 0, right: 0, bottom: 10 }; let xAxis = { dataField: 'Country' }; let seriesGroups = [ { type: 'column', columnsGapPercent: 50, valueAxis: { unitInterval: 5000, title: { text: 'GDP & Debt per Capita($)<br>' } }, series: [ { dataField: 'GDP', displayText: 'GDP per Capita' }, { dataField: 'Debt', displayText: 'Debt per Capita' } ] }, { type: 'line', valueAxis: { unitInterval: 10, title: { text: 'Debt (% of GDP)' }, gridLines: { visible: false }, position: 'right' }, series: [ { dataField: 'DebtPercent', displayText: 'Debt (% of GDP)' } ] } ]; return ( <div> <JqxChart className='myChart' style={{ width: 850, height: 500 }} title={'Economic comparison'} description={'GDP and Debt in 2010'} showLegend={true} enableAnimations={true} padding={padding} titlePadding={titlePadding} source={dataAdapter} xAxis={xAxis} colorScheme={'scheme01'} seriesGroups={seriesGroups} /> <JqxButton style={{ float: 'left' }} ref='printBtn' value='Print' width={80} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/_wlk/AboutPage.js
welovekpop/uwave-web-welovekpop.club
import React from 'react'; import FacebookIcon from './icons/Facebook'; import YouTubeIcon from './icons/YouTube'; import InstagramIcon from './icons/Instagram'; import GithubIcon from './icons/Github'; import TwitterIcon from './icons/Twitter'; import SlackIcon from './icons/Slack'; import SocialMediaLink from './SocialMediaLink'; import './AboutPage.css'; export default () => ( <div className="wlk-AboutPage"> <h1 className="wlk-AboutPage-title">WE ♥ KPOP</h1> <p> WLK is a community dedicated to sharing the best South Korean music. Listen to what other people play live from YouTube and SoundCloud, share your opinion by talking to others and contribute to each day&#39;s unique playlist by hand-picking tracks yourself. </p> <p> WLK can also be found on: </p> <ul> <SocialMediaLink label="YouTube" href="https://youtube.com/c/welovekpopclub"> <YouTubeIcon /> </SocialMediaLink> <SocialMediaLink label="Facebook" href="https://facebook.com/wlk.yt"> <FacebookIcon /> </SocialMediaLink> <SocialMediaLink label="Instagram" href="https://instagram.com/wlk_official"> <InstagramIcon /> </SocialMediaLink> <SocialMediaLink label="Twitter" href="https://twitter.com/wlk_official"> <TwitterIcon /> </SocialMediaLink> <SocialMediaLink label="Github" href="https://github.com/welovekpop"> <GithubIcon /> </SocialMediaLink> <SocialMediaLink label="Slack" href="https://slack.wlk.yt"> <SlackIcon /> </SocialMediaLink> </ul> <hr className="wlk-AboutPage-separator" /> <h2>Rules</h2> <div className="wlk-Rules"> <div className="wlk-Rules-left"> <ol start="1" className="wlk-Rules-list"> <li className="wlk-Rules-item">Play only Korean related songs.</li> <li className="wlk-Rules-item">Songs that are over 7:00 minutes long might be skipped.</li> <li className="wlk-Rules-item">Songs that are heavily downvoted might be skipped.</li> <li className="wlk-Rules-item">Songs that are in the history (previous 25 songs) will be skipped.</li> <li className="wlk-Rules-item">Try to play the best quality versions of songs.</li> </ol> </div> <div className="wlk-Rules-right"> <ol start="6" className="wlk-Rules-list"> <li className="wlk-Rules-item">Chat in English!</li> <li className="wlk-Rules-item">Don&#39;t spam the chat.</li> </ol> </div> </div> </div> );
app/containers/Cart/CartPage.js
ryanwashburne/react-skeleton
// React import PropTypes from 'prop-types'; import React from 'react'; import { NavLink } from 'react-router-dom'; // Constants import { subtotal } from 'app/util/env'; // Redux import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as storeActions from 'app/reducers/storeReducer'; import * as global from 'app/reducers/globalReducer'; // UI import { Container, Row, Col, Table, Button } from 'mdbreact'; import { Frame } from 'app/components'; class CartPage extends React.Component { render() { const { cart, total, actions } = this.props; const options = []; for (let i = 1; i <= 10; i++ ) { options.push( <option value={i} key={i} >{i}</option> ); } return ( <Frame footer={false}> <Container> <Row> <Col xs="12"> <h1 className="h1-responsive wow slideInLeft" data-wow-duration="0.6s">Shopping Cart</h1> {Object.keys(cart).length > 0 && <p><NavLink to="/store">Continue shopping</NavLink></p> } {Object.keys(cart).length > 0 && <Table small> <thead> <tr> <th></th> <th>Price</th> <th>Quantity</th> </tr> </thead> <tbody> {Object.keys(cart).map((id, i) => { const item = cart[id]; return ( <tr key={i}> <th scope="row" className="d-flex flex-column-reverse flex-md-row"> <img style={{ maxWidth: 200, maxHeight: 200 }} className="img-fluid w-100 h-100 mr-md-3" src={item.img} /> <div> <h2 className="h2-responsive">{item.name}</h2> <a onTouchTap={() => { actions.Snack(`Removed ${item.name} from the cart.`); actions.removeFromCart(item.id); actions.saveCart(); }} >Delete</a> </div> </th> <td>{`$${item.dollars}.${item.cents}`}</td> <td> <select value={item.count} onChange={(e) => { actions.changeQty(item.id, e.target.value); actions.saveCart(); }}> {options} </select> </td> </tr> ); })} </tbody> </Table> } {Object.keys(cart).length === 0 && <p>Your cart is empty. Visit the <NavLink to="/store">Store</NavLink> to select items.</p> } </Col> </Row> <Row> <Col className="mt-3 text-center text-md-right" xs="12"> <h4 className="font-weight-bold h4-responsive">Subtotal ({total} item{total > 1 ? 's' : ''}): ${subtotal(cart)}</h4> {total > 0 && <NavLink to="/checkout"><Button color="success">Proceed to Checkout</Button></NavLink> } {total === 0 && <Button color="success" outline disabled>Proceed to Checkout</Button> } </Col> </Row> </Container> </Frame> ); } } CartPage.propTypes = { cart: PropTypes.object.isRequired, total: PropTypes.number.isRequired, actions: PropTypes.object.isRequired }; const mapStateToProps = (state) => { return { cart: state.store.cart, total: state.store.total }; }; const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators({...storeActions, ...global}, dispatch) }; }; CartPage = connect( mapStateToProps, mapDispatchToProps )(CartPage); export default CartPage;
src/client/app.js
rvboris/finalytics
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { AppContainer } from 'react-hot-loader'; import { addLocaleData } from 'react-intl'; import { ConnectedRouter } from 'react-router-redux'; import { renderRoutes } from 'react-router-config'; import WebFont from 'webfontloader'; import moment from 'moment'; import routes from '../shared/routes'; import './bootstrap.scss'; import './style.css'; import store, { runSaga, initialLocale, history } from './store'; Promise.config({ warnings: false, longStackTraces: true, cancellation: false, monitoring: false, }); const renderApp = () => { render( <AppContainer> <Provider store={store}> <ConnectedRouter history={history}> {renderRoutes(routes)} </ConnectedRouter> </Provider> </AppContainer>, document.body.childNodes[0] ); }; if (process.env.NODE_ENV === 'development' && module.hot) { module.hot.accept(); module.hot.accept('../shared/routes', renderApp); } runSaga(); import(`react-intl/locale-data/${initialLocale}`).then((localeData) => { addLocaleData(localeData); moment.locale(initialLocale); renderApp(); }); WebFont.load({ google: { families: ['Noto Sans'], }, });
app/routes.js
dfucci/Borrowr
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import HomePage from './containers/HomePage'; import CounterPage from './containers/CounterPage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> </Route> );
components/price/price.js
Travix-International/travix-ui-kit
// Imports import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; import { getClassNamesWithMods, getDataAttributes, warnAboutDeprecatedProp } from '../_helpers'; /** * Adds the thousands separator to a given value. * If either the thousands separator is not set or the value doesn't have thousands, * it will return the original value. * * @function addThousandsSeparator * @param {String} value String to be formatted * @param {String} thousandsSeparator Character to be used to split the thousands unit. * @return {String} Either the original value or the formatted value. */ export function addThousandsSeparator(value, thousandsSeparator) { if (!thousandsSeparator || (value.length <= 3)) { return value; } return value.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator); } /** * Ensures that a decimal value has the right decimal precision (no rounding applied). * * @function ensureDecimalPrecision * @param {String} value String representing the decimal part of a number. * @param {Number} decimalsPrecision Number of decimals to be allowed. * @return {String} The value with a proper precision. */ export function ensureDecimalPrecision(value = '', decimalsPrecision = 2) { if (value.length > decimalsPrecision) { return value.substr(0, decimalsPrecision); } return `${value}${'0'.repeat(decimalsPrecision - value.length)}`; } /** * Price component */ function Price(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { additionalText, className, dataAttrs = {}, decimalsPrecision, decimalsSeparator, discount, showAsterisk, showDecimals, size, symbol, symbolPosition, thousandsSeparator, underlined, unstyled, value, } = props; if (!value && value !== 0) { return null; } const mods = props.mods ? props.mods.slice() : []; const rootClass = 'ui-price'; const [intValue, decValue] = value.toString().split('.'); if (unstyled) { const priceFormatted = [ addThousandsSeparator(intValue, thousandsSeparator), showDecimals && ensureDecimalPrecision(decValue, decimalsPrecision), ].filter(i => i !== false).join(decimalsSeparator); const unstyledValue = [ symbolPosition === 'left' && symbol, priceFormatted, symbolPosition === 'right' && symbol, showAsterisk && '*', ].filter(i => i !== false).join(' '); return ( <span {...getDataAttributes(dataAttrs)}> {unstyledValue} </span> ); } mods.push(`size_${size}`); const priceClasses = classnames(getClassNamesWithMods(rootClass, mods), className); const textBlock = additionalText ? ( <div className={`${rootClass}__additional-text-block`}> {additionalText} </div> ) : null; let discountBlock = null; if (discount) { const [intDiscountValue, decDiscountValue] = discount.toString().split('.'); const discountValue = addThousandsSeparator(intDiscountValue, thousandsSeparator) + decimalsSeparator + ensureDecimalPrecision(decDiscountValue, decimalsPrecision); discountBlock = ( <div className={`${rootClass}__discount`}> {discountValue} </div> ); } const decimalsMarkup = showDecimals ? ( <div className={`${rootClass}__decimals`}> {decimalsSeparator + ensureDecimalPrecision(decValue, decimalsPrecision)} </div> ) : null; const asterisk = showAsterisk ? (<div className={`${rootClass}__asterisk`}>*</div>) : null; const underlineMarkup = underlined ? <div className={`${rootClass}__underline`}/> : null; return ( <div className={priceClasses} {...getDataAttributes(dataAttrs)}> {discountBlock} <div className={`${rootClass}__value-delimiter`}> <div className={`${rootClass}__currency ${rootClass}__currency_${symbolPosition}`}>{symbol}</div> <div className={`${rootClass}__integers`}>{addThousandsSeparator(intValue, thousandsSeparator)}</div> {decimalsMarkup} {asterisk} </div> {underlineMarkup} {textBlock} </div> ); } Price.defaultProps = { additionalText: '', decimalsPrecision: 2, decimalsSeparator: '.', discount: 0, showAsterisk: false, showDecimals: true, size: 'l', symbol: '€', symbolPosition: 'left', thousandsSeparator: ',', underlined: false, unstyled: false, }; Price.propTypes = { /** * Additional text that will be displayed under price and the line. * E.g.: 'per day'. */ additionalText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), /** * Custom className(s) to be concatenated with the default ones on the component's root element */ className: PropTypes.string, /** * Data attribute. You can use it to set up GTM key or any custom data-* attribute */ dataAttrs: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object, ]), /** * Decimals precision. Max number of decimals. */ decimalsPrecision: PropTypes.number, /** * Decimals separator. When formatting the number it will split decimals from integers. */ decimalsSeparator: PropTypes.string, /** * Discount block. Strikethrough text with original price. */ discount: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * You can provide set of custom modifications. */ mods: PropTypes.arrayOf(PropTypes.string), /** * Defines if it should show the asterisk or not. */ showAsterisk: PropTypes.bool, /** * Defines if it should show the decimals or not. */ showDecimals: PropTypes.bool, /** * Price's size */ size: PropTypes.oneOf(['xs', 's', 'm', 'l', 'xl']), /** * Currency symbol. Defines the currency symbol of the Price. */ symbol: PropTypes.string, /** * Currency symbol's position. Defines where the currency symbol is rendered on the Price. */ symbolPosition: PropTypes.oneOf(['left', 'right']), /** * Thousands separator. When formatting the number it will split the thousands digits. */ thousandsSeparator: PropTypes.string, /** * Flag defining if the price should be underlined. */ underlined: PropTypes.bool, /** * Flag defining if the price should be rendered without any styles. */ unstyled: PropTypes.bool, /** * Price to be displayed. */ value: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]).isRequired, }; export default Price;
node_modules/react-router/modules/RouteUtils.js
jameswatkins77/React-Blogger-App
import React from 'react' import warning from './warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) /* istanbul ignore if: error logging */ if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (routes && !Array.isArray(routes)) { routes = [ routes ] } return routes }
src/js/components/icons/base/BrandHpeElementPath.js
odedre/grommet-final
/** * @description BrandHpeElementPath SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-brand-hpe-element-path`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'brand-hpe-element-path'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 40 12" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polygon fill="none" stroke="#01A982" strokeWidth="3" points="1.5 1.5 38.5 1.5 38.5 10.5 1.5 10.5"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'BrandHpeElementPath'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/index.js
brod4910/React-Webpack-Boilerplate
const css = require('./app.css'); import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') );
app/javascript/mastodon/features/followers/index.js
verniy6462/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, fetchFollowers, expandFollowers, } 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', 'followers', Number(props.params.accountId), 'items']), hasMore: !!state.getIn(['user_lists', 'followers', Number(props.params.accountId), 'next']), }); @connect(mapStateToProps) export default class Followers 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(fetchFollowers(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(fetchFollowers(Number(nextProps.params.accountId))); } } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) { this.props.dispatch(expandFollowers(Number(this.props.params.accountId))); } } handleLoadMore = (e) => { e.preventDefault(); this.props.dispatch(expandFollowers(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='followers'> <div className='scrollable' onScroll={this.handleScroll}> <div className='followers'> <HeaderContainer accountId={this.props.params.accountId} /> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} {loadMore} </div> </div> </ScrollContainer> </Column> ); } }
src/components/Navbar/Searchbar.js
nicolas-adamini/littleblue
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { search } from '../../redux/actions/index'; import { withRouter } from 'react-router-dom'; class Searchbar extends Component { constructor(props) { super(props); this.state = { value: '', placeholder: '' } this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); this.updateSearchPlaceholder = this.updateSearchPlaceholder.bind(this); } updateSearchPlaceholder(pathname = '') { let searchType = 'anything'; switch (pathname) { case '/images': searchType = 'images' break; case '/videos': searchType = 'videos' break; case '/maps': searchType = 'places' break; } this.setState({ placeholder: `Search for ${searchType}...` }); } componentWillMount() { const { location } = this.props; this.updateSearchPlaceholder(location.pathname); } componentWillUpdate(nextProps, nextState) { const { location } = this.props; const { placeholder } = this.state; if (location.pathname !== nextProps.location.pathname) { this.updateSearchPlaceholder(nextProps.location.pathname); } } handleSubmit(e) { e.preventDefault(); const { value } = this.state; const { search, history, location } = this.props; if (value) { search(value); if (location.pathname === '/') { history.push('/web'); } } } handleChange(e) { this.setState({ value: e.target.value }); } render() { const { value, placeholder } = this.state; return ( <form onSubmit={this.handleSubmit}> <input value={value} type="text" onChange={this.handleChange} placeholder={placeholder} /> <button type="type"><i className="material-icons">search</i></button> </form> ); } } const mapDispatchToProps = dispatch => { return bindActionCreators({ search: search }, dispatch); } export default withRouter(connect(null, mapDispatchToProps)(Searchbar));
src/views/components/VideoPlayer.js
physiii/open-automation
import React from 'react'; import PropTypes from 'prop-types'; import VideoStream from './VideoStream.js'; import Toolbar from './Toolbar.js'; import PlayButtonIcon from '../icons/PlayButtonIcon.js'; import StopButtonIcon from '../icons/StopButtonIcon.js'; import ExpandIcon from '../icons/ExpandIcon.js'; import fscreen from 'fscreen'; import './VideoPlayer.css'; const controlsHideDelay = 3000; export class VideoPlayer extends React.Component { constructor (props) { super(props); // Copying props to state here because we specifically only care about // the autoplay prop during the first render. this.state = { isPlaying: this.props.autoplay, isFullScreen: false, hasPlayedOnce: false, currentPlayLocation: 0, shouldShowControls: this.props.showControlsWhenStopped || this.props.autoplay }; this.element = React.createRef(); this.handleClick = this.handleClick.bind(this); this.handleFullScreenClick = this.handleFullScreenClick.bind(this); this.updateFullScreenState = this.updateFullScreenState.bind(this); this.showHideControls = this.showHideControls.bind(this); } componentDidMount () { fscreen.addEventListener('fullscreenchange', this.updateFullScreenState); // For autoplay, hide controls after delay. if (this.state.shouldShowControls) { this.showHideControls(); } } componentDidUpdate (previousProps, previousState) { if (!previousState.isPlaying && this.state.isPlaying && typeof this.props.onPlay === 'function') { this.props.onPlay(); } else if (previousState.isPlaying && !this.state.isPlaying && typeof this.props.onStop === 'function') { this.props.onStop(); } if (!previousState.isFullScreen && this.state.isFullScreen) { this.enterFullScreen(); } else if (previousState.isFullScreen && !this.state.isFullScreen) { this.exitFullScreen(); } } componentWillUnmount () { fscreen.removeEventListener('fullscreenchange', this.updateFullScreenState); clearTimeout(this.controlsTimeout); } handleClick () { if (this.state.isPlaying) { this.stop(); } else { this.play(); } } handleFullScreenClick (event) { event.stopPropagation(); this.setState({isFullScreen: !this.state.isFullScreen}); } updateFullScreenState () { this.setState({isFullScreen: this.isFullScreen()}); } isFullScreen () { return this.element.current === fscreen.fullscreenElement; } enterFullScreen () { if (fscreen.fullscreenEnabled) { fscreen.requestFullscreen(this.element.current); } } exitFullScreen () { if (fscreen.fullscreenEnabled) { fscreen.exitFullscreen(); this.showHideControls(); } } showHideControls (forceShow) { this.setState({shouldShowControls: this.state.isPlaying || this.props.showControlsWhenStopped || this.state.isFullScreen || forceShow}); clearTimeout(this.controlsTimeout); this.controlsTimeout = setTimeout(() => { this.setState({shouldShowControls: (!this.state.isPlaying && (this.props.showControlsWhenStopped || this.state.isFullScreen)) || false}); }, controlsHideDelay); } play () { this.setState({ isPlaying: true, hasPlayedOnce: true }); this.showHideControls(); } getVideoWidth () { if (this.element) { if (this.element.current) { return this.element.current.clientWidth; } } return 0; } getVideoHeight () { if (this.element) { if (this.element.current) { return this.element.current.clientHeight; } } return 0; } stop () { this.setState({ isPlaying: false, shouldShowControls: this.props.showControlsWhenStopped || this.state.isFullScreen }); } getAspectRatioPaddingTop () { const aspectRatio = this.props.height / this.props.width; return (aspectRatio * 100) + '%'; } getMotionWidth () { const width1 = this.props.motionArea.p1[0] * this.getVideoWidth(), width2 = this.props.motionArea.p2[0] * this.getVideoWidth(); let width = width2 - width1; if (!this.props.firstPointSet && !this.props.firstLoad) { width = 0; } return width; } getMotionHeight () { const width1 = this.props.motionArea.p1[1] * this.getVideoHeight(), width2 = this.props.motionArea.p2[1] * this.getVideoHeight(); let width = width2 - width1; if (!this.props.firstPointSet && !this.props.firstLoad) { width = 0; } return width; } render () { return ( <div onKeyDown={this.handleKeyPress} styleName={'player' + (this.state.isPlaying ? ' isPlaying' : '') + (this.state.isFullScreen ? ' isFullScreen' : '')} ref={this.element} onClick={this.handleClick} onMouseMove={() => this.showHideControls()}> <div styleName="overlay"> {this.state.isPlaying && this.props.shouldShowControls ? <StopButtonIcon size={64} shadowed={true} /> : null} {!this.state.isPlaying && this.props.shouldShowControls ? <PlayButtonIcon size={64} shadowed={true} /> : null} </div> <div styleName={'toolbar' + (this.props.shouldShowControls ? '' : ' isHidden')}> <Toolbar rightChildren={fscreen.fullscreenEnabled && <ExpandIcon size={22} isExpanded={this.state.isFullScreen} onClick={this.handleFullScreenClick} />} /> </div> {this.state.isPlaying && !this.props.recording && <span styleName="live">Live</span>} <div styleName="video"> <span styleName="aspectRatio" style={{paddingTop: this.getAspectRatioPaddingTop()}} /> {this.props.posterUrl && !this.state.hasPlayedOnce && <img styleName="poster" src={this.props.posterUrl}/>} <div styleName={'motionAreaOverlay'} style={this.props.motionArea ? { left: this.props.motionArea.p1[0] * this.getVideoWidth(), top: this.props.motionArea.p1[1] * this.getVideoHeight(), width: this.getMotionWidth(), height: this.getMotionHeight() } : {display: 'none'}} /> <VideoStream styleName="canvas" {...this.props} shouldStream={this.state.isPlaying} key={(this.props.recording && this.props.recording.id) || this.props.cameraServiceId} /> </div> </div> ); } } VideoPlayer.propTypes = { // NOTE: The VideoPlayer component should always be called with a key // property set to the ID of the recording or camera that is being streamed. cameraServiceId: PropTypes.string.isRequired, motionArea: PropTypes.object, firstLoad: PropTypes.bool, firstPointSet: PropTypes.bool, secondPointSet: PropTypes.bool, recording: PropTypes.object, streamingToken: PropTypes.string, posterUrl: PropTypes.string, autoplay: PropTypes.bool, showControlsWhenStopped: PropTypes.bool, shouldShowControls: PropTypes.bool, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, onPlay: PropTypes.func, onStop: PropTypes.func }; VideoPlayer.defaultProps = { showControlsWhenStopped: true }; export default VideoPlayer;
App/node_modules/react-native/Libraries/Image/Image.ios.js
Dagers/React-Native-Differential-Updater
/** * 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. * * @providesModule Image * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const ImageResizeMode = require('ImageResizeMode'); const ImageSourcePropType = require('ImageSourcePropType'); const ImageStylePropTypes = require('ImageStylePropTypes'); const NativeMethodsMixin = require('NativeMethodsMixin'); const NativeModules = require('NativeModules'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheet = require('StyleSheet'); const StyleSheetPropType = require('StyleSheetPropType'); const createReactClass = require('create-react-class'); const flattenStyle = require('flattenStyle'); const requireNativeComponent = require('requireNativeComponent'); const resolveAssetSource = require('resolveAssetSource'); const ImageViewManager = NativeModules.ImageViewManager; /** * A React component for displaying different types of images, * including network images, static resources, temporary local images, and * images from local disk, such as the camera roll. * * This example shows fetching and displaying an image from local storage * as well as one from network and even from data provided in the `'data:'` uri scheme. * * > Note that for network and data images, you will need to manually specify the dimensions of your image! * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image } from 'react-native'; * * export default class DisplayAnImage extends Component { * render() { * return ( * <View> * <Image * source={require('./img/favicon.png')} * /> * <Image * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} * /> * <Image * style={{width: 66, height: 58}} * source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}} * /> * </View> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage); * ``` * * You can also add `style` to an image: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image, StyleSheet } from 'react-native'; * * const styles = StyleSheet.create({ * stretch: { * width: 50, * height: 200 * } * }); * * export default class DisplayAnImageWithStyle extends Component { * render() { * return ( * <View> * <Image * style={styles.stretch} * source={require('./img/favicon.png')} * /> * </View> * ); * } * } * * // skip these lines if using Create React Native App * AppRegistry.registerComponent( * 'DisplayAnImageWithStyle', * () => DisplayAnImageWithStyle * ); * ``` * * ### GIF and WebP support on Android * * When building your own native code, GIF and WebP are not supported by default on Android. * * You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app. * * ``` * dependencies { * // If your app supports Android versions before Ice Cream Sandwich (API level 14) * compile 'com.facebook.fresco:animated-base-support:1.3.0' * * // For animated GIF support * compile 'com.facebook.fresco:animated-gif:1.3.0' * * // For WebP support, including animated WebP * compile 'com.facebook.fresco:animated-webp:1.3.0' * compile 'com.facebook.fresco:webpsupport:1.3.0' * * // For WebP support, without animations * compile 'com.facebook.fresco:webpsupport:1.3.0' * } * ``` * * Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` : * ``` * -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl { * public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier); * } * ``` * */ // $FlowFixMe(>=0.41.0) const Image = createReactClass({ displayName: 'Image', propTypes: { /** * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`, * > `stretch`, `center`, `repeat`. */ style: StyleSheetPropType(ImageStylePropTypes), /** * The image source (either a remote URL or a local file resource). * * This prop can also contain several remote URLs, specified together with * their width and height and potentially with scale/other URI arguments. * The native side will then choose the best `uri` to display based on the * measured size of the image container. A `cache` property can be added to * control how networked request interacts with the local cache. * * The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`, * `webp` (Android only), `psd` (iOS only). */ source: ImageSourcePropType, /** * A static image to display while loading the image source. * * - `uri` - a string representing the resource identifier for the image, which * should be either a local file path or the name of a static image resource * (which should be wrapped in the `require('./path/to/image.png')` function). * - `width`, `height` - can be specified if known at build time, in which case * these will be used to set the default `<Image/>` component dimensions. * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if * unspecified, meaning that one image pixel equates to one display point / DIP. * - `number` - Opaque type returned by something like `require('./image.jpg')`. * * @platform ios */ defaultSource: PropTypes.oneOfType([ // TODO: Tooling to support documenting these directly and having them display in the docs. PropTypes.shape({ uri: PropTypes.string, width: PropTypes.number, height: PropTypes.number, scale: PropTypes.number, }), PropTypes.number, ]), /** * When true, indicates the image is an accessibility element. * @platform ios */ accessible: PropTypes.bool, /** * The text that's read by the screen reader when the user interacts with * the image. * @platform ios */ accessibilityLabel: PropTypes.node, /** * blurRadius: the blur radius of the blur filter added to the image */ blurRadius: PropTypes.number, /** * When the image is resized, the corners of the size specified * by `capInsets` will stay a fixed size, but the center content and borders * of the image will be stretched. This is useful for creating resizable * rounded buttons, shadows, and other resizable assets. More info in the * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets). * * @platform ios */ capInsets: EdgeInsetsPropType, /** * The mechanism that should be used to resize the image when the image's dimensions * differ from the image view's dimensions. Defaults to `auto`. * * - `auto`: Use heuristics to pick between `resize` and `scale`. * * - `resize`: A software operation which changes the encoded image in memory before it * gets decoded. This should be used instead of `scale` when the image is much larger * than the view. * * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is * faster (usually hardware accelerated) and produces higher quality images. This * should be used if the image is smaller than the view. It should also be used if the * image is slightly bigger than the view. * * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html. * * @platform android */ resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']), /** * Determines how to resize the image when the frame doesn't match the raw * image dimensions. * * - `cover`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view (minus padding). * * - `contain`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal to * or less than the corresponding dimension of the view (minus padding). * * - `stretch`: Scale width and height independently, This may change the * aspect ratio of the src. * * - `repeat`: Repeat the image to cover the frame of the view. The * image will keep it's size and aspect ratio. (iOS only) */ resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']), /** * A unique identifier for this element to be used in UI Automation * testing scripts. */ testID: PropTypes.string, /** * Invoked on mount and layout changes with * `{nativeEvent: {layout: {x, y, width, height}}}`. */ onLayout: PropTypes.func, /** * Invoked on load start. * * e.g., `onLoadStart={(e) => this.setState({loading: true})}` */ onLoadStart: PropTypes.func, /** * Invoked on download progress with `{nativeEvent: {loaded, total}}`. * @platform ios */ onProgress: PropTypes.func, /** * Invoked on load error with `{nativeEvent: {error}}`. */ onError: PropTypes.func, /** * Invoked when a partial load of the image is complete. The definition of * what constitutes a "partial load" is loader specific though this is meant * for progressive JPEG loads. * @platform ios */ onPartialLoad: PropTypes.func, /** * Invoked when load completes successfully. */ onLoad: PropTypes.func, /** * Invoked when load either succeeds or fails. */ onLoadEnd: PropTypes.func, }, statics: { resizeMode: ImageResizeMode, /** * Retrieve the width and height (in pixels) of an image prior to displaying it. * This method can fail if the image cannot be found, or fails to download. * * In order to retrieve the image dimensions, the image may first need to be * loaded or downloaded, after which it will be cached. This means that in * principle you could use this method to preload images, however it is not * optimized for that purpose, and may in future be implemented in a way that * does not fully load/download the image data. A proper, supported way to * preload images will be provided as a separate API. * * Does not work for static image resources. * * @param uri The location of the image. * @param success The function that will be called if the image was successfully found and width * and height retrieved. * @param failure The function that will be called if there was an error, such as failing to * to retrieve the image. * * @returns void * * @platform ios */ getSize: function( uri: string, success: (width: number, height: number) => void, failure?: (error: any) => void, ) { ImageViewManager.getSize(uri, success, failure || function() { console.warn('Failed to get size for image: ' + uri); }); }, /** * Prefetches a remote image for later use by downloading it to the disk * cache * * @param url The remote location of the image. * * @return The prefetched image. */ prefetch(url: string) { return ImageViewManager.prefetchImage(url); }, /** * Resolves an asset reference into an object which has the properties `uri`, `width`, * and `height`. The input may either be a number (opaque type returned by * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' } */ resolveAssetSource: resolveAssetSource, }, mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'UIView', validAttributes: ReactNativeViewAttributes.UIView }, render: function() { const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined }; let sources; let style; if (Array.isArray(source)) { style = flattenStyle([styles.base, this.props.style]) || {}; sources = source; } else { const {width, height, uri} = source; style = flattenStyle([{width, height}, styles.base, this.props.style]) || {}; sources = [source]; if (uri === '') { console.warn('source.uri should not be an empty string'); } } const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108 const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108 if (this.props.src) { console.warn('The <Image> component requires a `source` property rather than `src`.'); } return ( <RCTImageView {...this.props} style={style} resizeMode={resizeMode} tintColor={tintColor} source={sources} /> ); }, }); const styles = StyleSheet.create({ base: { overflow: 'hidden', }, }); const RCTImageView = requireNativeComponent('RCTImageView', Image); module.exports = Image;
example/main.js
tanem/react-salvager
import React from 'react' import ReactDOM from 'react-dom' import Salvager from '../src/Salvager' import Row from './Row' ReactDOM.render( <Salvager bufferSize={25} rowWrapperStyle={{ listStyleType: 'none', marginBottom: 0, marginTop: 0, paddingLeft: 0 }} visibleAreaStyle={{ backgroundColor: '#fff', border: '1px solid #ddd', height: 400, width: 300 }} > {getRows(500000)} </Salvager>, document.querySelector('.Root') ) function getRows(number) { return new Array(number) .fill(0) .map((v, i) => <Row key={`${i + 1}`}>{`Item ${i + 1}`}</Row> ) }
src/svg-icons/device/signal-cellular-4-bar.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular4Bar = (props) => ( <SvgIcon {...props}> <path d="M2 22h20V2z"/> </SvgIcon> ); DeviceSignalCellular4Bar = pure(DeviceSignalCellular4Bar); DeviceSignalCellular4Bar.displayName = 'DeviceSignalCellular4Bar'; export default DeviceSignalCellular4Bar;
test/fixtures/react/nonJSX/expected.js
davesnx/babel-plugin-transform-react-qa-classes
import React, { Component } from 'react'; class TestClass extends Component { test() { return true; } } export default TestClass;
ui/browser/index.js
linclark/tofino
/* Copyright 2016 Mozilla 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 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { ipcRenderer } from 'electron'; import App from './views/app.jsx'; import configureStore from './store/store'; const store = configureStore(); /** * Hot Module Reload */ // if (module.hot) { // module.hot.accept(); // } const container = document.getElementById('browser-container'); const app = React.createElement(App); const chrome = React.createElement(Provider, { store }, app); const onRender = () => ipcRenderer.send('window-ready'); render(chrome, container, onRender);
client/src/Flash.js
panter/mykonote
import React, { Component } from 'react'; import NoticeFlash from './NoticeFlash'; import AlertFlash from './AlertFlash'; import './Flash.css'; class Flash extends Component { render() { return ( <div> <NoticeFlash /> <AlertFlash /> </div> ); } } export default Flash;
native/ChatItem/ChatItem.js
abdurrahmanekr/react-chat-elements
import React, { Component } from 'react'; import styles from './ChatItemStyle.js'; import Avatar from '../Avatar/Avatar'; import { View, Text, Image, } from 'react-native'; export class ChatItem extends Component { render() { return ( <View style={styles.rceContainerCitem} onClick={this.props.onClick} onContextMenu={this.props.onContextMenu}> <View style={styles.rceCitem}> <View style={styles.rceCitemAvatar}> <Avatar src={this.props.avatar} alt={this.props.alt} sideElement={ this.props.statusColor && <View style={[styles.rceCitemStatus, {backgroundColor: this.props.statusColor}]}> <Text> {this.props.statusText} </Text> </View> } type={'circle' && {'flexible': this.props.avatarFlexible}}/> </View> <View style={styles.rceCitemBody}> <View style={styles.rceCitemBodyTop}> <Text ellipsizeMode='tail' numberOfLines={1} style={styles.rceCitemBodyTopTitle}> {this.props.title} </Text> <Text style={styles.rceCitemBodyTopTime} ellipsizeMode='tail' numberOfLines={1}> { this.props.date && !isNaN(this.props.date) && ( this.props.dateString || (this.props.date).toString() ) } </Text> </View> <View style={styles.rceCitemBodyBottom}> <Text ellipsizeMode='tail' numberOfLines={1} style={styles.rceCitemBodyTopTitle}> {this.props.subtitle} </Text> { this.props.unread > 0 && <View style={styles.rceCitemBodyBottomStatus}> <Text style={styles.rceCitemBodyBottomStatusText}> {this.props.unread} </Text> </View> } </View> </View> </View> </View> ); } } ChatItem.defaultProps = { id: '', onClick: null, avatar: '', avatarFlexible: false, alt: '', title: '', subtitle: '', date: new Date(), unread: 0, statusColor: null, statusText: null, dateString: null, } export default ChatItem;
src/render.js
pshrmn/cryptonite
import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloProvider } from 'react-apollo'; import { CuriProvider } from '@curi/react'; import client from './apolloClient'; import Header from './components/Header'; import Footer from './components/Footer'; import 'scss/base.scss'; import 'scss/main.scss'; export default ({ router }) => { ReactDOM.render(( <ApolloProvider client={client}> <CuriProvider router={router}> {({ response }) => { const { body:Body } = response; return ( <div id='app-base'> <Header /> <main> <div className='container'> <Body response={response} /> </div> </main> <Footer /> </div> ); }} </CuriProvider> </ApolloProvider> ), document.querySelector('#app-holder')); };
services/QuillLMS/client/app/bundles/Connect/utils/devTools.js
empirical-org/Empirical-Core
import React from 'react'; // Exported from redux-devtools import { createDevTools } from '@redux-devtools/core'; // Monitors are separate packages, and you can make a custom one import LogMonitor from '@redux-devtools/log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; // createDevTools takes a monitor and produces a DevTools component const DevTools = createDevTools( // Monitors are individually adjustable with props. // Consult their repositories to learn about those props. // Here, we put LogMonitor inside a DockMonitor. <DockMonitor changePositionKey='ctrl-q' defaultIsVisible={false} toggleVisibilityKey='ctrl-h' > <LogMonitor theme='tomorrow' /> </DockMonitor> ); export default DevTools;
lib/components/DevTools.js
emmenko/redux-react-router-async-example
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'> <LogMonitor /> </DockMonitor> )
app/components/GeometryCanvasCifdata/index.js
mhoffman/CatAppBrowser
/** * * GeometryCanvasCifdata * */ import { compose } from 'recompose'; import React from 'react'; import _ from 'lodash'; import PropTypes, { instanceOf } from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { connect } from 'react-redux'; import Paper from 'material-ui/Paper'; /* import Button from 'material-ui/Button';*/ /* import Chip from 'material-ui/Chip';*/ /* import AddIcon from 'material-ui-icons/Add';*/ /* import RemoveIcon from 'material-ui-icons/Remove';*/ import { Md3dRotation } from 'react-icons/lib/md'; import { withCookies, Cookies } from 'react-cookie'; import { isMobile } from 'react-device-detect'; import * as actions from 'components/GeometryCanvasWithOptions/actions'; import { styles } from './styles'; const jQuery = require('jquery'); window.jQuery = jQuery; const { ChemDoodle } = require('utils/ChemDoodleWeb'); // eslint-disable-line no-unused-vars const initialState = { rotationMatrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1.3], }; class GeometryCanvasCifdata extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { ...initialState, orientation: 'test orientation', perspective: (this.props.cookies.get('perspective') === 'true'), tiltToRotate: (this.props.cookies.get('tiltToRotate') === 'true'), }; /* this.downloadStructure = this.downloadStructure.bind(this);*/ } componentDidMount() { const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.innerHTML = ` function _load_lib(url, callback){ id = 'load_' + url; var s = document.createElement('script'); s.src = url; s.id = id; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } // Load Libraries /*var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1.3]*/ /*rotationMatrix = ChemDoodle.lib.mat4.rotate(rotationMatrix, -.8, [1,0,0]);*/ /*rotationMatrix = ChemDoodle.lib.mat4.rotate(rotationMatrix, +.1, [0,0,1]);*/ if(typeof cif_${this.props.uniqueId} === 'undefined' ) { let cif_${this.props.uniqueId} } if(typeof tfcanvas_${this.props.uniqueId} === 'undefined' ) { let tfcanvas_${this.props.uniqueId} } //Code tfcanvas_${this.props.uniqueId} = new ChemDoodle.TransformCanvas3D('${this.props.id}_view'); document.getElementById("${this.props.id}_view").tfcanvas = tfcanvas_${this.props.uniqueId}; cif_${this.props.uniqueId} = ChemDoodle.readCIF(\`${this.props.cifdata}\`, ${this.props.x}, ${this.props.y}, ${this.props.z}); if (typeof alpha_${this.props.uniqueId} === 'undefined') { let alpha_${this.props.uniqueId} = 0.; } if (typeof beta_${this.props.uniqueId} === 'undefined') { let beta_${this.props.uniqueId} = 0.; } if (typeof gamma_${this.props.uniqueId} === 'undefined') { let gamma_${this.props.uniqueId} = 0.; } if(typeof altLabels === 'undefined') { var altLabels } altLabels = ${JSON.stringify(this.props.altLabels)}; cif_${this.props.uniqueId}.molecule.atoms.map(function(atom, i){ if(altLabels.hasOwnProperty(i)) { atom.altLabel = altLabels[i]; } }); /*tfcanvas_${this.props.uniqueId}.specs.set3DRepresentation('Line');*/ /*tfcanvas_${this.props.uniqueId}.specs.set3DRepresentation('Stick');*/ /*tfcanvas_${this.props.uniqueId}.specs.set3DRepresentation('Wireframe');*/ /*tfcanvas_${this.props.uniqueId}.specs.set3DRepresentation('van der Waals Spheres');*/ tfcanvas_${this.props.uniqueId}.specs.set3DRepresentation('Ball and Stick'); tfcanvas_${this.props.uniqueId}.specs.backgroundColor = '${this.props.color}'; tfcanvas_${this.props.uniqueId}.specs.projectionPerspective_3D = ${this.props.perspective}; tfcanvas_${this.props.uniqueId}.specs.compass_display = true; tfcanvas_${this.props.uniqueId}.specs.compass_size_3D = 50; tfcanvas_${this.props.uniqueId}.specs.atoms_displayLabels_3D = true; tfcanvas_${this.props.uniqueId}.specs.crystals_unitCellLineWidth = 5; tfcanvas_${this.props.uniqueId}.specs.shapes_color = 'black'; tfcanvas_${this.props.uniqueId}.specs.shapes_lineWidth = 1; tfcanvas_${this.props.uniqueId}.loadContent([cif_${this.props.uniqueId}.molecule], [cif_${this.props.uniqueId}.unitCell]); tfcanvas_${this.props.uniqueId}.rotationMatrix = [${this.props.rotationMatrix}] || [${this.state.rotationMatrix}] || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1.3]; tfcanvas_${this.props.uniqueId}.updateScene() if(${this.state.tiltToRotate}) { window.addEventListener('deviceorientation', (e) => { /*ALPHA*/ /*if(typeof alpha_${this.props.uniqueId} !== 'undefined') {*/ /*if(.01 < Math.abs(alpha_${this.props.uniqueId} - e.alpha) < 1.5) {*/ /*tfcanvas_${this.props.uniqueId}.rotationMatrix = ChemDoodle.lib.mat4.rotate(tfcanvas_${this.props.uniqueId}.rotationMatrix,(e.alpha - alpha_${this.props.uniqueId}) * 0.015, tfcanvas_${this.props.uniqueId}.rotationMatrix.slice(8, 11));*/ /*}*/ /*}*/ /*GAMMA*/ /*if (typeof gamma_${this.props.uniqueId} !== 'undefined') {*/ /*if(.01 < Math.abs(gamma_${this.props.uniqueId} - e.gamma) < 1.5) {*/ /*tfcanvas_${this.props.uniqueId}.rotationMatrix = ChemDoodle.lib.mat4.rotate(tfcanvas_${this.props.uniqueId}.rotationMatrix,(e.gamma - gamma_${this.props.uniqueId}) * 0.015, tfcanvas_${this.props.uniqueId}.rotationMatrix.slice(8, 11));*/ /*}*/ /*}*/ /*BETA*/ if (typeof beta_${this.props.uniqueId} !== 'undefined') { if(0.01 < Math.abs(beta_${this.props.uniqueId} - e.beta) < 1.5) { tfcanvas_${this.props.uniqueId}.rotationMatrix = ChemDoodle.lib.mat4.rotate(tfcanvas_${this.props.uniqueId}.rotationMatrix, -(e.beta - beta_${this.props.uniqueId}) * 0.015, [1, 0, 0]); } } alpha_${this.props.uniqueId} = e.alpha; beta_${this.props.uniqueId} = e.beta; gamma_${this.props.uniqueId} = e.gamma; tfcanvas_${this.props.uniqueId}.updateScene() }, true) } ; `; const item = document.getElementById(`${this.props.id}_view`); item.appendChild(script); this.props.saveCanvas(item.tfcanvas); document.addEventListener('mouseup', (() => { const nonUnity = !_.isEqual(item.tfcanvas.rotationMatrix, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); const nonOld = !_.isEqual(item.tfcanvas.rotationMatrix, this.props.rotationMatrix); if (nonUnity && nonOld) { this.props.setRotationMatrix( item.tfcanvas.rotationMatrix ); } })); } shouldComponentUpdate(nextProps) { return !_.isEqual(nextProps, this.props); } componentDidUpdate() { this.componentDidMount(); } /* downloadStructure() {*/ /* axios.get(url, params).then((response) => {*/ /* const tempUrl = window.URL.createObjectURL(new Blob([response.data]));*/ /* const link = document.createElement('a');*/ /* link.href = tempUrl;*/ /* link.setAttribute('download', `dft_input_${(new Date()).getTime()}.zip`);*/ /* document.body.appendChild(link);*/ /* link.click();*/ /* }).catch(() => {*/ /* });*/ /* }*/ render() { return ( <div> {(isMobile === false || this.state.tiltToRotate === false) ? null : <div> <Md3dRotation />{'\u00A0\u00A0'} Tilt phone to rotate.</div> } <Paper height={14}> <p id={`${this.props.id}_script`} > <canvas id={`${this.props.id}_view`} height={this.props.height} width={this.props.width} style={{ borderWidth: this.props.borderWidth, borderColor: '#000000', borderStyle: 'solid', }} /> </p> </Paper> {/* <Button raised className={this.props.classes.button} > <MdFullscreen /> Fullscreen </Button> <Button raised color="primary" className={this.props.classes.button} onClick={this.downloadStructure}> <MdFileDownload /> Download </Button> */} </div> ); } } GeometryCanvasCifdata.defaultProps = { height: Math.max(Math.min(window.innerWidth * 0.5, 600), 300), width: Math.max(Math.min(window.innerWidth * 0.5, 600), 300), color: '#fff', cifdata: '', cifurl: '', x: 2, y: 2, z: 1, borderWidth: 0, altLabels: {}, perspective: true, tiltToRotate: true, }; GeometryCanvasCifdata.propTypes = { uniqueId: PropTypes.string.isRequired, cifdata: PropTypes.string.isRequired, id: PropTypes.string.isRequired, height: PropTypes.number, width: PropTypes.number, color: PropTypes.string, x: PropTypes.number, y: PropTypes.number, z: PropTypes.number, rotationMatrix: PropTypes.array, setRotationMatrix: PropTypes.func, saveCanvas: PropTypes.func, borderWidth: PropTypes.number, altLabels: PropTypes.object, perspective: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types tiltToRotate: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types cookies: instanceOf(Cookies).isRequired, }; const mapDispatchToProps = (dispatch) => ({ setRotationMatrix: (x) => { dispatch(actions.setRotationMatrix(x)); }, saveCanvas: (x) => { dispatch(actions.saveCanvas(x)); }, }); const mapStateToProps = (state) => ({ rotationMatrix: state.get('geometryCanvasReducer').rotationMatrix, }); export default compose( withStyles(styles, { withTheme: true }), withCookies, connect(mapStateToProps, mapDispatchToProps) )(GeometryCanvasCifdata);
client/components/reqApproved.js
marhyorh/booktrade
import React from 'react'; export default (props) => { const onRemove = (book, event) => { event.preventDefault(); Meteor.call('book.removeOutstanding', book); Meteor.call('book.unApprove', book); } const reqApproved = () => { return props.books.map(book => { return ( <li className="list-group-item" key={book._id}> {book.title} <i className="glyphicon glyphicon-remove" onClick={onRemove.bind(this, book)} /> </li> ); }); } return ( <div className="reqApproved"> {props.books.length >= 1 && <h3>Requests Approved:</h3>} <ul className="list-group"> { reqApproved() } </ul> </div> ) };
app/view/API/index.js
Juice4213/GZHReactNativeDemo
/** * Created by tompda on 2017/2/5. */ /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View, ScrollView, Navigator, InteractionManager, AlertIOS, Linking, } from 'react-native'; import MainItem from '../../component/mainItem'; import NavitatorBar from '../../component/navigatorBar'; import NetInfo from './NetInfo'; import AppState from './AppState'; import LayoutAnimationDemo from './LayoutAnimation'; import LayoutAnimationPro from './LayoutAnimation2'; import ShareDemos from './ShareDemo'; import AsyncStorageDemo from './AsyncStorage'; import DimensionsDemo from './DimensionsDemo'; import PixelRatioDemo from './PixelRatioDemo'; import AlertIOSDemo from './AlertIOSDemo'; import ActionSheetIOSDemo from './ActionSheetIOSDemo'; import VibrationDemo from './VibrationDemo'; import LinkingDemo from './LinkingDemo'; import NativeModuleDemo1 from './NativeModule1'; export default class GZHReactNativeDemo extends Component { render() { return ( <View style={{flex:1,backgroundColor:'#ffffff'}}> <NavitatorBar title = 'API' leftOnPress = {()=>this._pop()} leftContext = '返回' /> <ScrollView style={{flex:1}} contentContainerStyle={styles.container}> <MainItem itemTitle = 'NetInfo' onPress={()=>this.pushToNetInfo()} /> <MainItem itemTitle = 'AppState' onPress={()=>this.pushToAppState()} /> <MainItem itemTitle = 'LayoutAnimation' onPress={()=>this.pushToLayout()} /> <MainItem itemTitle = 'LayoutAnimation2' onPress={()=>this.pushToLayout2()} /> <MainItem itemTitle = '调用系统分享' onPress={()=>this.pushToShareDemo()} /> <MainItem itemTitle = 'AsyncStorage(持久化存储)' onPress={()=>this.pushToAsyncStorage()} /> <MainItem itemTitle = 'Dimensions的使用' onPress={()=>this.pushToDimensions()} /> <MainItem itemTitle = 'PixelRatio设备像素密度' onPress={()=>this.pushToPixelRatio()} /> <MainItem itemTitle = 'AlertIOS' onPress={()=>this.pushToAlertIOS()} /> <MainItem itemTitle = 'ActionSheetIOS' onPress={()=>this.pushToActionSheetIOS()} /> <MainItem itemTitle = 'Vibration控制设备震动' onPress={()=>this.pushToVibration()} /> <MainItem itemTitle = 'Linking使用实例' onPress={()=>this.pushToLinking()} /> <MainItem itemTitle = '原生模块封装基础' onPress={()=>this.pushToNativeModule1()} /> </ScrollView> </View> ); } _pop = () => { const {navigator} = this.props; if(navigator){ navigator.pop(); } } //NativeModule pushToNativeModule1 = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'NativeModule1', component:NativeModuleDemo1, }) } }); }; //Linking pushToLinking = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'Linking', component:LinkingDemo, }) } }); }; //Vibration pushToVibration = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'Vibration', component:VibrationDemo, }) } }); }; //ActionSheetIOS pushToActionSheetIOS = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'ActionSheetIOS', component:ActionSheetIOSDemo, }) } }); }; //AlertIOS pushToAlertIOS = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'Dimensions', component:AlertIOSDemo, }) } }); }; //PixelRatio设备像素密度 pushToPixelRatio = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'Dimensions', component:PixelRatioDemo, }) } }); }; //Dimensions的使用 pushToDimensions = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'Dimensions', component:DimensionsDemo, }) } }); }; //网络状态 pushToNetInfo = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'netinfo', component:NetInfo, }) } }); }; //APP状态 pushToAppState = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'appState', component:AppState, }) } }); }; //动画 pushToLayout = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'layout', component:LayoutAnimationDemo, }) } }); }; //动画2 pushToLayout2 = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'layout2', component:LayoutAnimationPro, }) } }); }; //系统分享 pushToShareDemo = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'shareDemo', component:ShareDemos, }) } }); }; //持久化存储 pushToAsyncStorage = () => { const {navigator} = this.props; InteractionManager.runAfterInteractions(()=>{ if(navigator){ navigator.push({ name:'AsyncStorage', component: AsyncStorageDemo, }) } }); } } const styles = StyleSheet.create({ container: { //flex: 1, }, });
ui/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
carmine/northshore
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/Tabs/TabBar.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; const propTypes = { activeTab: PropTypes.number, className: PropTypes.string, cssPrefix: PropTypes.string.isRequired, onChange: PropTypes.func, }; const defaultProps = { activeTab: 0 }; class TabBar extends React.Component { constructor(props) { super(props); this.handleClickTab = this.handleClickTab.bind(this); } handleClickTab(tabId) { if (this.props.onChange) { this.props.onChange(tabId); } } render() { const { activeTab, className, cssPrefix, children, ...otherProps } = this.props; const classes = classNames({ [`${cssPrefix}__tab-bar`]: true }, className); return ( <div className={classes} {...otherProps}> {React.Children.map(children, (child, tabId) => React.cloneElement(child, { cssPrefix, tabId, active: tabId === activeTab, onTabClick: this.handleClickTab, }) )} </div> ); } } TabBar.propTypes = propTypes; TabBar.defaultProps = defaultProps; export default TabBar;
rojak-ui-web/src/app/utils/Navbar.js
bobbypriambodo/rojak
import React from 'react'; import { Link } from 'react-router'; import rojakBlack from '../../assets/images/rojak-black.svg'; import styles from './Navbar.css'; const Navbar = () => ( <nav className={`uk-navbar ${styles.navbar}`}> <ul className="uk-navbar-nav"> <li className="uk-active"> <Link className={styles.homeLink} to="/"> <img className={styles.logo} src={rojakBlack} alt="logo" /> </Link> </li> </ul> </nav> ); export default Navbar;
src/index.js
Nexapp/NexappCart
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './cart/reducers/configureStore'; import ShoppingCart from './cart/containers/ShoppingCart'; import './index.css'; const store = configureStore(); ReactDOM.render( <Provider store={store}> <ShoppingCart /> </Provider>, document.getElementById('root') );
packages/react-tv/modules/renderOnAppLoaded.js
raphamorim/react-tv
/** * Copyright (c) 2017-present, Célio Latorraca. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import Plaform from './Platform'; export default Component => class extends React.Component { constructor() { super(); this.state = {loaded: false}; } componentDidMount() { if (Plaform('webos')) { this.bindWebOSLaunchEvent(); } else { this.setState({loaded: true}); } } bindWebOSLaunchEvent() { document.addEventListener( 'webOSLaunch', () => { this.setState({loaded: true}); }, true ); } render() { const {loaded} = this.state; let component = null; if (loaded) { component = <Component {...this.props} />; } return component; } };
techCurriculum/ui/solutions/7.1/src/components/TextInput.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; class TextInput extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(event) { const value = event.target.value; this.props.onChange(value); } render() { return ( <div className='form-group'> <label className='control-label'>{this.props.label}</label> <input type='text' className='form-control' name={this.props.name} value={this.props.value} onChange={this.handleChange} /> </div> ) } } export default TextInput;
App/Client/node_modules/react-router/modules/Redirect.js
qianyuchang/React-Chat
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { formatPattern } from './PatternUtils' import { falsy } from './PropTypes' const { string, object } = React.PropTypes /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ const Redirect = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.from) route.path = route.from route.onEnter = function (nextState, replace) { const { location, params } = nextState let pathname if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params) } else if (!route.to) { pathname = location.pathname } else { let routeIndex = nextState.routes.indexOf(route) let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1) let pattern = parentPattern.replace(/\/*$/, '/') + route.to pathname = formatPattern(pattern, params) } replace({ pathname, query: route.query || location.query, state: route.state || location.state }) } return route }, getRoutePattern(routes, routeIndex) { let parentPattern = '' for (let i = routeIndex; i >= 0; i--) { const route = routes[i] const pattern = route.path || '' parentPattern = pattern.replace(/\/*$/, '/') + parentPattern if (pattern.indexOf('/') === 0) break } return '/' + parentPattern } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Redirect> elements are for router configuration only and should not be rendered' ) } }) export default Redirect
src/svg-icons/av/av-timer.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAvTimer = (props) => ( <SvgIcon {...props}> <path d="M11 17c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1zm0-14v4h2V5.08c3.39.49 6 3.39 6 6.92 0 3.87-3.13 7-7 7s-7-3.13-7-7c0-1.68.59-3.22 1.58-4.42L12 13l1.41-1.41-6.8-6.8v.02C4.42 6.45 3 9.05 3 12c0 4.97 4.02 9 9 9 4.97 0 9-4.03 9-9s-4.03-9-9-9h-1zm7 9c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zM6 12c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1z"/> </SvgIcon> ); AvAvTimer = pure(AvAvTimer); AvAvTimer.displayName = 'AvAvTimer'; AvAvTimer.muiName = 'SvgIcon'; export default AvAvTimer;
src/containers/Bookcase.js
claclacla/_Udacity_-Organize-your-bookshelves-using-ReactJS
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import Data from '../Data'; import BookShelf from '../components/BookShelf'; const ListBooks = function (props) { const { books } = props; return ( <div className="list-books"> <div className="list-books-title"> <h1>MyReads</h1> </div> <div className="list-books-content"> <div> <BookShelf title="Currently reading" books={books.filter(book => book.shelf === Data.currentlyReading.value)} /> <BookShelf title="Want to read" books={books.filter(book => book.shelf === Data.wantToRead.value)} /> <BookShelf title="Read" books={books.filter(book => book.shelf === Data.read.value)} /> </div> </div> <div className="open-search"> <Link to="/search">Add a book</Link> </div> </div> ); } ListBooks.propTypes = { books: PropTypes.array.isRequired } export default ListBooks
ReactApp/LastChance/src/app.js
Mastenka/josefina
import React, { Component } from 'react'; import { AppRegistry, Dimensions, StyleSheet, Text, TouchableHighlight, View } from 'react-native'; export default class LastChance extends Component { render() { return ( <View style={styles.container}> <Text> Neco </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', }, preview: { flex: 1, width: 50, height: 300, }, capture: { flex: 0, backgroundColor: '#fff', borderRadius: 5, color: '#000', padding: 10, margin: 40 } }); AppRegistry.registerComponent('LastChance', () => LastChance);
frontend/src/components/partners/profile/buttons/addNewVerificationButton.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import VerifiedUser from 'material-ui-icons/VerifiedUser'; import IconWithTextButton from '../../../common/iconWithTextButton'; const messages = { text: 'Verify Profile', }; const AddNewVerificationButton = (props) => { const { handleClick } = props; return ( <IconWithTextButton icon={<VerifiedUser />} text={messages.text} onClick={handleClick} /> ); }; AddNewVerificationButton.propTypes = { handleClick: PropTypes.func, }; export default AddNewVerificationButton;
frontend/myblog/src/apps/articles/component/articlePagination.js
shady831213/myBlog
import React from 'react'; import {createUltimatePagination, ITEM_TYPES} from 'react-ultimate-pagination'; import NavigationFirstPage from 'material-ui-icons/FirstPage'; import NavigationLastPage from 'material-ui-icons/LastPage'; import NavigationChevronLeft from 'material-ui-icons/ChevronLeft'; import NavigationChevronRight from 'material-ui-icons/ChevronRight'; import {ListItem, ListItemIcon, ListItemText} from 'material-ui/List'; import {GridList} from 'material-ui/GridList'; const Page = ({value, isActive, onClick}) => ( <ListItem disableGutters button mini dense={!isActive} onClick={onClick} divider={isActive}> < ListItemText primary={isActive?value.toString():null} secondary={isActive?null:value.toString()} /> </ListItem> ); const Ellipsis = ({onClick}) => ( <ListItem disableGutters button mini dense onClick={onClick}> < ListItemText secondary={"..."} /> </ListItem> ); const FirstPageLink = ({isActive, onClick}) => ( <ListItem disableGutters button mini dense onClick={onClick}> <ListItemIcon> <NavigationFirstPage/> </ListItemIcon> </ListItem> ); const PreviousPageLink = ({isActive, onClick}) => ( <ListItem disableGutters button mini dense onClick={onClick}> <ListItemIcon> <NavigationChevronLeft/> </ListItemIcon> </ListItem> ); const NextPageLink = ({isActive, onClick}) => ( <ListItem disableGutters button mini dense onClick={onClick}> <ListItemIcon> <NavigationChevronRight/> </ListItemIcon> </ListItem> ); const LastPageLink = ({isActive, onClick}) => ( <ListItem disableGutters button mini dense onClick={onClick}> <ListItemIcon> <NavigationLastPage/> </ListItemIcon> </ListItem> ); const Wrapper = (props) => { return <GridList >{props.children}</GridList> }; const itemTypeToComponent = { [ITEM_TYPES.PAGE]: Page, [ITEM_TYPES.ELLIPSIS]: Ellipsis, [ITEM_TYPES.FIRST_PAGE_LINK]: FirstPageLink, [ITEM_TYPES.PREVIOUS_PAGE_LINK]: PreviousPageLink, [ITEM_TYPES.NEXT_PAGE_LINK]: NextPageLink, [ITEM_TYPES.LAST_PAGE_LINK]: LastPageLink }; const AritclePagination = createUltimatePagination({ itemTypeToComponent: itemTypeToComponent, WrapperComponent: Wrapper }); export default AritclePagination;
packages/material-ui-icons/src/Reply.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z" /></g> , 'Reply');
src/components/artifacts.js
cosmowiki/cosmowiki
import React from 'react'; const ArtifactsComponent = ({appUrl}) => { return ( <main role="main" className="pure-u-1"> <div id="siteTitle" className="pure-u-1 places center"> <div id="siteTitleContainer"> <h1>Orte</h1> <h3>der Blick zu den Sternen</h3> </div> </div> <div id="pageSubMenuContainer"> </div> </main> ) }; export default ArtifactsComponent;
src/pages/blog.js
Oluwasetemi/Oluwasetemi.github.io
/* eslint-disable react/jsx-props-no-spreading */ /* eslint-disable react/no-danger */ import { animated, useSpring } from '@react-spring/web' import Bio from 'components/Bio' import SEO from 'components/seo' import { graphql, Link } from 'gatsby' import React from 'react' import { useDrag } from 'react-use-gesture' import styled from 'styled-components' import { formatReadingTime } from 'utils/helpers' const OnePostSummaryStyles = styled(animated.article)` margin-top: 1.5rem; margin-bottom: 3.5rem; padding: 1.55rem 1.25em; cursor: grabbing; box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.06) 0px 1px 2px 0px; h2 { font-size: 2.25rem; } p.excerpt { margin-bottom: 2rem; } ` function OnePostSummary({node, title}) { const [{x, y}, api] = useSpring(() => ({x: 0, y: 0})) // Set the drag hook and define component movement based on gesture data const bind = useDrag(({down, movement: [mx, my]}) => { api.start({x: down ? mx : 0, y: down ? my : 0}) }) return ( <OnePostSummaryStyles data-tip="Please Drag Me 👌" {...bind()} style={{x, y}} key={node.fields.slug} > <h2> <Link style={{boxShadow: 'none', color: '#800080'}} to={`/blog${node.fields.slug}`} > {title} </Link> </h2> <small> {node.frontmatter.date} {` • ${formatReadingTime(node.timeToRead)}`} {node.frontmatter.tags.map(tag => ( <Link to={`/tags/${tag}`} key={tag}> • 🏷 <span>{`${tag}`}</span> </Link> ))} </small> <p className="excerpt" dangerouslySetInnerHTML={{__html: node.excerpt}} /> <span> <Link style={{boxShadow: 'none', color: '#800080'}} to={`blog${node.fields.slug}`} > read more </Link> </span> </OnePostSummaryStyles> ) } function BlogIndex({data: {allMdx}}) { const posts = allMdx.edges return ( <> <SEO title="Home" /> <Bio /> {posts.map(({node}) => { const title = node.frontmatter.title || node.fields.slug return ( <OnePostSummary key={node.fields.slug} node={node} title={title} /> ) })} </> ) } export default BlogIndex export const pageQuery = graphql` query { allMdx( sort: {fields: [frontmatter___date], order: DESC} filter: { frontmatter: {isPublished: {eq: true}} fileAbsolutePath: {regex: "//content/blog//"} } ) { edges { node { excerpt(pruneLength: 280) fields { slug } timeToRead frontmatter { date(formatString: "dddd DD MMMM YYYY") title tags } } } } } `