path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
website/core/WebPlayer.js
alin23/react-native
/** * 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 WebPlayer */ 'use strict'; var Prism = require('Prism'); var React = require('React'); var WEB_PLAYER_VERSION = '1.2.6'; /** * Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown. * * Optionally, include url parameters directly after the block's language. For * the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player * * E.g. * ```ReactNativeWebPlayer?platform=android * import React from 'react'; * import { AppRegistry, Text } from 'react-native'; * * const App = () => <Text>Hello World!</Text>; * * AppRegistry.registerComponent('MyApp', () => App); * ``` */ var WebPlayer = React.createClass({ parseParams: function(paramString) { var params = {}; if (paramString) { var pairs = paramString.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); params[pair[0]] = pair[1]; } } return params; }, render: function() { var hash = `#code=${encodeURIComponent(this.props.children)}`; if (this.props.params) { hash += `&${this.props.params}`; } return ( <div className={'web-player'}> <Prism>{this.props.children}</Prism> <iframe style={{marginTop: 4}} width="880" height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'} data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`} frameBorder="0" /> </div> ); }, }); module.exports = WebPlayer;
envkey-react/src/components/forms/user/org_role_select.js
envkey/envkey-app
import React from 'react' import h from "lib/ui/hyperscript_with_helpers" import {orgRoleLabel} from 'lib/ui' export default function({ value, onChange, orgRolesAssignable, isSubmitting }){ const renderRoleOption = (orgRole, i)=> { return h.option({key: i, value: orgRole}, orgRoleLabel(orgRole)) } return h.fieldset(".org-role-select", [ h.label("Organization Role"), h.select( ".org-role", {value, onChange, disabled: isSubmitting}, orgRolesAssignable.map(renderRoleOption) ) ]) }
assets/javascripts/kitten/components/form/radio-set/stories.js
KissKissBankBank/kitten
import React from 'react' import { RadioSet } from './index' import { DocsPage } from 'storybook/docs-page' export default { component: RadioSet, title: 'Form/RadioSet', parameters: { docs: { page: () => <DocsPage filepath={__filename} importString="RadioSet" />, }, }, decorators: [ story => ( <div className="story-Container story-Grid story-Grid--large"> {story()} </div> ), ], args: defaultArgs, argTypes: { id: { name: 'id', control: 'text', }, label: { name: 'label', control: 'text', }, items: { name: 'items', control: 'object', }, error: { name: 'error', control: 'boolean', }, disabled: { name: 'disabled', control: 'boolean', }, design: { name: 'design', options: ['disc', 'check'], control: 'inline-radio', }, fontWeight: { name: 'fontWeight', options: ['light', 'normal', 'bold'], control: 'inline-radio', }, }, } const defaultArgs = { id: 'story-radio-set', error: false, disabled: false, design: 'disc', fontWeight: 'normal', } export const Default = args => <RadioSet {...args} /> Default.args = { ...defaultArgs, items: [ { text: 'Option A', id: 'option-a', defaultChecked: true, }, { text: 'Option B', id: 'option-b', }, ], }
src/svg/ciamSVG.js
auth0/web-header
import React from 'react'; const ciamStyle = { backgroundColor: '#C879B2', width: 46, height: 30, display: 'inline-block', color: '#F5F7F9', borderRadius: 3, textAlign: 'center', fontSize: 12, fontWeight: 500, textTransform: 'uppercase', padding: 7 }; const ciamSVG = () => <span style={ciamStyle}> ciam </span>; export default ciamSVG;
src/view-header.js
mateim24/react-input-calendar
import React from 'react' class ViewHeader extends React.Component { static propTypes = { next: React.PropTypes.func, prev: React.PropTypes.func, titleAction: React.PropTypes.func, data: React.PropTypes.string } render() { let prop = this.props return ( <div className="navigation-wrapper"> <span className="icon" onClick={prop.prev} ><i className="fa fa-angle-left"></i></span> <span className="navigation-title" onClick={prop.titleAction} >{prop.data}</span> <span className="icon" onClick={prop.next} ><i className="fa fa-angle-right"></i></span> </div> ) } } export default ViewHeader
src/components/Modal/Modal.js
IanChuckYin/IanChuckYin.github.io
import React, { Component } from 'react'; import styles from './Modal.module.scss'; class Modal extends Component { modalDomElement = null; render() { const { component, onCloseClick } = this.props; return ( <div className={styles.Modal} ref={element => this.modalDomElement = element}> <div className={styles.ModalContainer}> <button className={styles.CloseButton} onClick={() => onCloseClick()}> <i className="fas fa-times" /> </button> {component} </div> </div> ); } } export default Modal;
SocialStarter/app/FeedView.js
Monte9/react-native-social-starter
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Alert, Image, Dimensions, ScrollView, TouchableOpacity } from 'react-native'; import { Card, Text, Button } from 'react-native-elements' import Icon from 'react-native-vector-icons/MaterialIcons' const { width, height } = Dimensions.get("window"); import posts from './sample_posts' class FeedView extends Component { render() { return ( <View style={{flex: 1}}> <View style={styles.header}> <Text style={styles.headerTitle}>Social Feed</Text> </View> <ScrollView style={{backgroundColor: '#e1e8ee', paddingBottom: 100}}> <View style={styles.container}> { posts.map((post, index) => { return ( <TouchableOpacity onPress={() => console.log("pressed")} activeOpacity={1} key={index}> <Card title={post.title} image={{uri: post.post_uri}} containerStyle={{backgroundColor: '#bdc6cf'}} onPress={() => console.log("pressed")}> <Text style={{marginBottom: 10}}> {post.post_text} </Text> <Button icon={{name: 'eye', type: 'font-awesome', color:'white'}} backgroundColor={'#6296f9'} buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}} title='Explore' onPress={() => console.log("pressed")}/> </Card> </TouchableOpacity> ) }) } </View> </ScrollView> </View> ); } } const styles = { user: { flexDirection: 'row', marginBottom: 6 }, image: { width: 30, height: 30, marginRight: 10 }, name: { fontSize: 16, marginTop: 5 }, header: { flex: 0.1, backgroundColor: 'white', width: width, height: 64 }, headerTitle: { alignItems: 'center', alignSelf: 'center', justifyContent: 'center', color: '#6296f9', fontWeight: 'bold', paddingTop: 20, fontSize: 18 } } export default FeedView
src/containers/ChannelDropdown/index.js
badT/twitchBot
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Link } from 'react-router'; import TweenMax from 'gsap/src/minified/TweenMax.min'; import { getChannels, setChannel, unsetChannel } from '../../actions/index'; import Logo from '../../components/Logo/index'; import { styles } from './styles.scss'; class ChannelDropdown extends Component { constructor(props) { super(props); this.state = { drawerOpen: false, animating: false, }; } componentWillMount() { this.props.getChannels(); this.channelInt = setInterval(this.props.getChannels, 300000); } componentWillUnmount() { clearInterval(this.channelInt); } toggleDrawer() { if (this.state.animating) return; this.setState({ animating: true }); if (this.state.drawerOpen) { this.drawerAnim().close(); setTimeout(() => { this.setState({ animating: false, drawerOpen: false }); }, 600); } else { this.setState({ drawerOpen: true }); this.drawerAnim().open(); setTimeout(() => { this.setState({ animating: false }); }, 600); } } drawerAnim() { const open = () => { TweenMax.to('#drawer_overlay', 0.6, { css: { 'background-color': 'rgba(0,0,0,0.6)' } }); TweenMax.to('#drawer', 0.6, { x: '0%' }); /* animate hamburger icon */ TweenMax.to('#brg_top', 0.5, { rotation: 150, y: 4, x: 12 }); TweenMax.to('#brg_btm', 0.5, { rotation: -150, y: -4, x: 12 }); TweenMax.to('#brg_mid', 0.5, { rotation: 90, y: -7, x: 0 }); }; const close = () => { TweenMax.to('#drawer_overlay', 0.6, { css: { 'background-color': 'rgba(0,0,0,0)' } }); TweenMax.to('#drawer', 0.6, { x: '101%' }); /* animate hamburger icon */ TweenMax.to('#brg_top', 0.5, { rotation: 0, y: 0, x: 0 }); TweenMax.to('#brg_btm', 0.5, { rotation: 0, y: 0, x: 0 }); TweenMax.to('#brg_mid', 0.5, { rotation: 0, y: 0, x: 0 }); }; return { open, close }; } linkClickHandler(name) { if (this.props.channels.selected !== name) { this.props.setChannel(name); this.toggleDrawer(); } } logoClickHandler() { if (this.state.drawerOpen) this.toggleDrawer(); this.props.unsetChannel(); } renderChannels(channelData) { const name = channelData.channel.name; return ( <Link key={name} className={`drawer-link ${this.props.channels.selected === name ? 'drawer-link-active' : ''}`} to="/chat" onClick={() => this.linkClickHandler(name)} > {name} </Link> ); } render() { return ( <div className={`${styles}`}> {/* Hamburger Icon */} <span className="burger-holder" onClick={() => this.toggleDrawer()}> <svg className="burger" width="14" height="8" viewBox="-2 -2 18 12"> <line className="burger-line" id="brg_top" x1="0" y1="0" x2="14" y2="0" /> <line className="burger-line" id="brg_mid" x1="0" y1="4" x2="14" y2="4" /> <line className="burger-line" id="brg_btm" x1="0" y1="8" x2="14" y2="8" /> </svg> </span> {/* Logo Link */} <Link to="/" className="logo" onClick={() => this.logoClickHandler()}> {/* Logo component */} <Logo /> </Link> {/* Dropdown Menu Overlay BG */} <div className={`drawer-overlay ${this.state.drawerOpen ? 'drawer-open' : ''}`} id="drawer_overlay" onClick={() => this.toggleDrawer()} ></div> {/* Dropdown Menu */} <div className="drawer" id="drawer"> <h4 className="about-link"> <Link to="/about" onClick={() => this.toggleDrawer()}>About Chatson</Link> </h4> <h4 className="channel-list-header">Active Chat Streams</h4> <div className="finger-point text-center closing-copy">&#9759;</div> {this.props.channels.list.map(this.renderChannels, this)} </div> </div> ); } } ChannelDropdown.propTypes = { getChannels: React.PropTypes.func, setChannel: React.PropTypes.func, unsetChannel: React.PropTypes.func, channels: React.PropTypes.object, }; function mapDispatchToProps(dispatch) { return bindActionCreators({ getChannels, setChannel, unsetChannel }, dispatch); } function mapStateToProps({ channels }) { return { channels }; } export default connect(mapStateToProps, mapDispatchToProps)(ChannelDropdown);
src/svg-icons/social/notifications.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialNotifications = (props) => ( <SvgIcon {...props}> <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/> </SvgIcon> ); SocialNotifications = pure(SocialNotifications); SocialNotifications.displayName = 'SocialNotifications'; SocialNotifications.muiName = 'SvgIcon'; export default SocialNotifications;
packages/ringcentral-widgets/containers/ConferenceCallDialerPage/index.js
ringcentral/ringcentral-js-widget
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connectModule } from '../../lib/phoneContext'; import BackButton from '../../components/BackButton'; import BackHeader from '../../components/BackHeader'; import DialerPanel from '../../components/DialerPanel'; import i18n from './i18n'; class ConferenceCallDialerPanel extends Component { componentWillMount() { this.props.setLastSessionId(); } render() { const { onBack, ...baseProps } = this.props; return [ <BackHeader key="header" onBackClick={onBack} backButton={<BackButton label={i18n.getString('activeCall')} />} />, <DialerPanel key="dialer" {...baseProps} />, ]; } } ConferenceCallDialerPanel.propTypes = { ...DialerPanel.propTypes, onBack: PropTypes.func.isRequired, setLastSessionId: PropTypes.func.isRequired, }; ConferenceCallDialerPanel.defaultProps = { ...DialerPanel.defaultProps, }; export default connectModule((phone) => phone.conferenceDialerUI)( ConferenceCallDialerPanel, );
examples/Explorer/components/RightCorner.js
react-native-simple-router-community/react-native-simple-router
import React from 'react'; import { Alert, Image, StyleSheet, TouchableHighlight, View, } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, }, button: { padding: 5, marginRight: 5, }, }); export default class RightCorner extends React.Component { constructor(props) { super(props); this.onPress = this.onPress.bind(this); } onPress() { Alert.alert( 'Alert Title', 'My Alert Msg', [ { text: 'OK', onPress: () => {} }, ] ); } render() { return ( <View style={styles.container}> <TouchableHighlight style={styles.button} onPress={this.onPress} underlayColor={'transparent'} > <Image source={require('../images/ic_account_circle_white.png')} /> </TouchableHighlight> </View> ); } }
packages/react-instantsearch-dom/src/widgets/HitsPerPage.js
algolia/react-instantsearch
import { connectHitsPerPage } from 'react-instantsearch-core'; import HitsPerPage from '../components/HitsPerPage'; /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure />` documentation](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {string} id - The id of the select input * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage - the root div of the widget * @themeKey ais-HitsPerPage-select - the select * @themeKey ais-HitsPerPage-option - the select option * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <HitsPerPage * defaultRefinement={5} * items={[ * { value: 5, label: 'Show 5 hits' }, * { value: 10, label: 'Show 10 hits' }, * ]} * /> * <Hits /> * </InstantSearch> * ); */ export default connectHitsPerPage(HitsPerPage);
tests/react_modules/es6class-proptypes-callsite.js
mroch/flow
/* @flow */ import React from 'react'; import Hello from './es6class-proptypes-module'; import type {Node} from 'react'; class HelloLocal extends React.Component<{name: string}> { defaultProps = {}; propTypes = { name: React.PropTypes.string.isRequired, }; render(): Node { return <div>{this.props.name}</div>; } } class Callsite extends React.Component<{}> { render(): Node { return ( <div> <Hello /> <HelloLocal /> </div> ); } } module.exports = Callsite;
lib/component-library-slides/Styling.js
RallySoftware/rally-present
import React from 'react'; import CodeBlock from '../components/CodeBlock'; const wtfSrc = require('./images/wtf.gif'); const cssCode = `render() { return ( <div> <span className="label">Name</span> <input /> </div> ); }`; export default class Slide extends React.Component { render() { return ( <div> <h1>CSS: here be dragons</h1> <img src={ wtfSrc } /> <CodeBlock> { cssCode } </CodeBlock> </div> ); } }
src/svg-icons/action/reorder.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionReorder = (props) => ( <SvgIcon {...props}> <path d="M3 15h18v-2H3v2zm0 4h18v-2H3v2zm0-8h18V9H3v2zm0-6v2h18V5H3z"/> </SvgIcon> ); ActionReorder = pure(ActionReorder); ActionReorder.displayName = 'ActionReorder'; ActionReorder.muiName = 'SvgIcon'; export default ActionReorder;
js/src/dapps/registry/ui/record-type-select.js
kushti/mpt
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default (value, onSelect, className = '') => ( <DropDownMenu className={ className } value={ value } onChange={ onSelect }> <MenuItem value='A' primaryText='A – Ethereum address' /> <MenuItem value='IMG' primaryText='IMG – hash of a picture in the blockchain' /> <MenuItem value='CONTENT' primaryText='CONTENT – hash of a data in the blockchain' /> </DropDownMenu> );
src/components/SetupAssistant/SetupAssistantItem.js
propertybase/react-lds
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { Button } from '../Button'; import { ProgressRing } from '../Progress'; import { MediaObject } from '../MediaObject'; import { SummaryDetail } from '../SummaryDetail'; const SetupAssistantItem = ({ children, className, isOpen, title, stepProgress, step, renderProgress, renderAddon, renderOpenContent, onOpen, ...rest }) => { const renderTitle = _title => ( <div className="slds-setup-assistant__step-summary"> <MediaObject figureLeft={renderProgress({ stepProgress, step })} bodyClassName="slds-m-top_x-small" center={false} > <MediaObject figureRight={renderAddon()} bodyClassName="slds-setup-assistant__step-summary-content" center={false} > <h3 className="slds-setup-assistant__step-summary-title slds-text-heading_small"> {onOpen ? ( <Button flavor={null} className="slds-button_reset" onClick={onOpen}> {_title} </Button> ) : _title} </h3> <p>{children}</p> </MediaObject> </MediaObject> </div> ); return ( <li className={cx('slds-setup-assistant__item', className)} {...rest}> <article className="slds-setup-assistant__step"> {onOpen ? ( <SummaryDetail containerClassName="slds-container_fluid" iconButtonClassName="slds-m-top_x-small" isOpen={isOpen} onOpen={onOpen} renderTitle={renderTitle} title={title} > {renderOpenContent && (() => ( <div className="slds-setup-assistant__step-detail"> {renderOpenContent({ isOpen })} </div> ))} </SummaryDetail> ) : renderTitle(title) } </article> </li> ); }; SetupAssistantItem.defaultProps = { children: null, className: null, stepProgress: null, step: null, isOpen: false, onOpen: null, renderAddon: () => null, renderOpenContent: () => null, // eslint-disable-next-line react/prop-types renderProgress: ({ stepProgress, step }) => (step || stepProgress) && ( <ProgressRing progress={stepProgress} status="active-step" size="large" > {step} </ProgressRing> ) }; SetupAssistantItem.propTypes = { /** * Item content */ children: PropTypes.node, /** * Additional className */ className: PropTypes.string, /** * Defines the expanded state */ isOpen: PropTypes.bool, /** * Triggered on expand icon and title click */ onOpen: PropTypes.func, /** * Function that renders the expanded content. Called when isOpen is true */ renderAddon: PropTypes.func, /** * Renders the expanded content */ renderOpenContent: PropTypes.func, /** * Renders the progress ring */ renderProgress: PropTypes.func, /** * Passed to renderProgress */ step: PropTypes.element, /** * Passed to renderProgress */ stepProgress: PropTypes.number, /** * Step title */ title: PropTypes.string.isRequired, }; export default SetupAssistantItem;
components/Deck/DeckLanguageMenu.js
slidewiki/slidewiki-platform
import React from 'react'; import PropTypes from 'prop-types'; import {defineMessages} from 'react-intl'; import {navigateAction} from 'fluxible-router'; import {connectToStores} from 'fluxible-addons-react'; import {flagForLocale} from '../../configs/locales'; import {getLanguageName} from '../../common'; import Util from '../common/Util'; import {Dropdown, Button, Icon, Flag} from 'semantic-ui-react'; import DeckTreeStore from '../../stores/DeckTreeStore'; import DeckPageStore from '../../stores/DeckPageStore'; import PermissionsStore from '../../stores/PermissionsStore'; import TranslationStore from '../../stores/TranslationStore'; class DeckLanguageMenu extends React.Component { constructor(props) { super(props); this.messages = defineMessages({ selectLanguage:{ id: 'InfoPanelInfoView.selectLanguage', defaultMessage:'Select language' }, }); } changeCurrentLanguage(e, { value: language }) { // exclude keyboard events except Enter if (!(e.code && e.code === 'Enter' || !e.code)) { return; } if (language === 'addNew') { $('#DeckTranslationsModalOpenButton').click(); return; } if (language === 'translateSlide') { $('#SlideTranslationsModalOpenButton').click(); return; } // we need to create the href to navigate to let selector = this.props.DeckTreeStore.selector.toJS(); // first, check selector type if (selector.stype === 'slide') { // for slides, we need to find the proper slide variant let variant = this.props.TranslationStore.nodeVariants.find((v) => v.language === language); if (!variant) { // try to find a variant for the primary tree language to provide as fallback variant = this.props.TranslationStore.nodeVariants.find((v) => v.language === this.props.TranslationStore.treeLanguage); if (!variant) { // if still no variant, get the variant for the primary language of the slide as saved variant = this.props.TranslationStore.nodeVariants.find((v) => v.language === this.props.TranslationStore.originLanguage); } } if (variant) { let oldSlideId = selector.sid; selector.sid = `${variant.id}-${variant.revision}`; // replace current slide id with translation slide id in spath as well selector.spath = selector.spath.replace(new RegExp(oldSlideId, 'g'), selector.sid); } // else change nothing and hope for the best :) } // else it's a deck, no spath replacing needed let href = Util.makeNodeURL(selector, 'deck', '', this.props.DeckTreeStore.slug, language); this.context.executeAction(navigateAction, { url: href }); } render() { let canEdit = this.props.PermissionsStore.permissions && this.props.PermissionsStore.permissions.edit && !this.props.PermissionsStore.permissions.readOnly; let primaryLanguage = this.props.TranslationStore.treeLanguage; let languages = [primaryLanguage, ...this.props.TranslationStore.treeTranslations]; if (this.props.TranslationStore.currentLang && languages.indexOf(this.props.TranslationStore.currentLang) < 0) { // put the current (but unavailable) language first languages.unshift(this.props.TranslationStore.currentLang); } // remove duplicates languages = languages.filter((elem, pos) => { return languages.indexOf(elem) === pos; }); let languageOptions = languages.map((t) => ({ text: getLanguageName(t) + (t === primaryLanguage ? ' (primary)' : ''), value: t, flag: flagForLocale(t), icon: !flagForLocale(t) && 'flag', })); if (canEdit) { languageOptions.push({ text: 'Add a new translation', value: 'addNew', icon: 'translate', key: 'placeholderForAddANewTranslation' }); // we need to create the href to navigate to let selector = this.props.DeckTreeStore.selector.toJS(); if (selector.stype === 'slide' && (this.props.DeckPageStore.mode === 'markdownEdit' || this.props.DeckPageStore.mode === 'edit')) { languageOptions.push({ text: 'Translate Slide', value: 'translateSlide', icon: 'translate', key: 'placeholderForTranslateSlide' }); } } // the user selected language (defaults to the primary deck tree language) let selectedLanguage = this.props.TranslationStore.currentLang || primaryLanguage; let selectedLanguageIcon = (flagForLocale(selectedLanguage) || 'icon'); let selectedLanguageName = getLanguageName(selectedLanguage); let selectLanguageMessage = this.context.intl.formatMessage(this.messages.selectLanguage); let translatebtn = { padding: '16px', fontWeight: 'bold' }; let dropdownTrigger = ( <div className="text" data-tooltip={selectLanguageMessage}> <i className={selectedLanguageIcon + ' flag'} />{selectedLanguageName} </div> ); let ariaLabel = `The selected language of the slide is ${selectedLanguageName}`; return ( <Dropdown style={translatebtn} fluid trigger={dropdownTrigger} aria-label={selectLanguageMessage} aria-label={ariaLabel} disabled={languageOptions.length < 2 && !canEdit} defaultValue={selectedLanguage} options={languageOptions} selectOnNavigation={false} onChange={this.changeCurrentLanguage.bind(this)} className={`${this.props.lastAttached ? 'bottom' : ''} attached medium basic button`} /> ); } } DeckLanguageMenu.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; DeckLanguageMenu = connectToStores(DeckLanguageMenu, [DeckTreeStore, DeckPageStore, PermissionsStore, TranslationStore], (context, props) => { return { DeckPageStore: context.getStore(DeckPageStore).getState(), DeckTreeStore: context.getStore(DeckTreeStore).getState(), PermissionsStore: context.getStore(PermissionsStore).getState(), TranslationStore: context.getStore(TranslationStore).getState(), }; }); export default DeckLanguageMenu;
app/components/System.js
elct9620/TLM-Website
/** * System Component */ import React from 'react' export default class System extends React.Component { render() { return( <section id="system" className="container section"> <h1 className="section-title small">遊戲系統</h1> <div className="alert text-center"> 詳細介紹將陸續登場 </div> </section> ) } }
fields/types/geopoint/GeoPointField.js
vokal/keystone
import Field from '../Field'; import React from 'react'; import { FormInput, Grid, } from '../../../admin/client/App/elemental'; module.exports = Field.create({ displayName: 'GeopointField', statics: { type: 'Geopoint', }, focusTargetRef: 'lat', handleLat (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [value[0], newVal], }); }, handleLong (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [newVal, value[1]], }); }, renderValue () { const { value } = this.props; if (value && value[1] && value[0]) { return <FormInput noedit>{value[1]}, {value[0]}</FormInput>; // eslint-disable-line comma-spacing } return <FormInput noedit>(not set)</FormInput>; }, renderField () { const { value = [], path } = this.props; return ( <Grid.Row xsmall="one-half" gutter={10}> <Grid.Col> <FormInput autoComplete="off" name={this.getInputName(path + '[1]')} onChange={this.handleLat} placeholder="Latitude" ref="lat" value={value[1]} /> </Grid.Col> <Grid.Col width="one-half"> <FormInput autoComplete="off" name={this.getInputName(path + '[0]')} onChange={this.handleLong} placeholder="Longitude" ref="lng" value={value[0]} /> </Grid.Col> </Grid.Row> ); }, });
src/parser/mage/fire/modules/Checklist/Component.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Checklist from 'parser/shared/modules/features/Checklist'; import Rule from 'parser/shared/modules/features/Checklist/Rule'; import Requirement from 'parser/shared/modules/features/Checklist/Requirement'; import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule'; import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement'; class FireMageChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; const AbilityRequirement = props => ( <GenericCastEfficiencyRequirement castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)} {...props} /> ); return ( <Checklist> <Rule name="Use your cooldowns" description={( <> Using your cooldown abilities as often as possible can help raise your dps significantly. Some help more than others, but as a general rule of thumb you should be looking to use most of your damaging abilities and damage cooldowns as often as possible unless you need to save them for a priority burst phase that is coming up soon. </> )} > <AbilityRequirement spell={SPELLS.COMBUSTION.id} /> <AbilityRequirement spell={SPELLS.FIRE_BLAST.id} /> {combatant.hasTalent(SPELLS.BLAST_WAVE_TALENT.id) && <AbilityRequirement spell={SPELLS.BLAST_WAVE_TALENT.id} />} {combatant.hasTalent(SPELLS.PHOENIX_FLAMES_TALENT.id) && <AbilityRequirement spell={SPELLS.PHOENIX_FLAMES_TALENT.id} />} {combatant.hasTalent(SPELLS.MIRROR_IMAGE_TALENT.id) && <AbilityRequirement spell={SPELLS.MIRROR_IMAGE_TALENT.id} />} {combatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id) && <AbilityRequirement spell={SPELLS.RUNE_OF_POWER_TALENT.id} />} {combatant.hasTalent(SPELLS.LIVING_BOMB_TALENT.id) && <AbilityRequirement spell={SPELLS.LIVING_BOMB_TALENT.id} />} {combatant.hasTalent(SPELLS.METEOR_TALENT.id) && <AbilityRequirement spell={SPELLS.METEOR_TALENT.id} />} </Rule> <Rule name="Use Combustion effectively" description={( <> Using <SpellLink id={SPELLS.COMBUSTION.id} /> properly is one of the most important aspects of playing Fire well. Therefore it is critical that you make the most of the time that you have while Combustion is active. This include things such as not wasting time or GCDs while Combustion is active and ensuring that you properly setup for your "Combustion Window". </> )} > <Requirement name="Fire Blast Charges" thresholds={thresholds.fireBlastCombustionCharges} tooltip="When Combustion is getting close to becomming available, it is important to save a couple Fire Blast charges to be used during the Combustion Window. This will help ensure that you can get as many Hot Streak procs as possible during Combustion." /> {combatant.hasTalent(SPELLS.PHOENIX_FLAMES_TALENT.id) && ( <Requirement name="Phoenix Flames Charges" thresholds={thresholds.phoenixFlamesCombustionCharges} tooltip="When outside of Combustion, you should avoid using your Phoenix Flames charges so that they have time to come off cooldown before Combustion is available again. This will ensure that you have a couple charges so you can get as many Hot Streak procs as possible before Combustion ends. If you are about to cap on Phoenix Flames charges, then it is acceptable to use one." /> )} {combatant.hasTalent(SPELLS.FIRESTARTER_TALENT.id) && ( <Requirement name="Combustion during Firestarter" thresholds={thresholds.firestarterCombustionUsage} tooltip="If you are talented into Firestarter, you should ensure that you do not cast Combustion while the boss is above 90% Health. This would be a waste considering every spell is guaranteed to crit while the boss is above 90% Health, which defeats the purpose of using Combustion. Instead, you should use Combustion when the boss gets to 89% so you can continue the streak of guaranteed crits once Firestarter finishes." /> )} {combatant.hasTalent(SPELLS.FIRESTARTER_TALENT.id) && ( <Requirement name="Pyroclasm Usage" thresholds={thresholds.pyroclasmCombustionUsage} tooltip="If you have enough time to complete the cast before Combustion ends, then you should always use your Pyroclasm procs to hard cast Pyroblast during Combustion. This is primarily because Combustion will guarantee that the spell crits, resulting in more damage on top of the 225% that the Pyroclasm buff gives." /> )} <Requirement name="Bad Scorch Uses" thresholds={thresholds.scorchSpellUsageDuringCombustion} tooltip="It is very important to use your time during Combustion wisely to get as many Hot Streak procs as possible before Combustion ends. To accomplish this, you should be stringing your guaranteed crit spells (Fireblast and Phoenix Flames) together to perpetually convert Heating Up to Hot Streak as many times as possible. If you run out of instant spells, cast Scorch instead." /> <Requirement name="Bad Fireball Uses" thresholds={thresholds.fireballSpellUsageDuringCombustion} tooltip="Due to Combustion's short duration, you should never cast Fireball during Combustion. Instead, you should use your instant cast abilities like Fireblast and Phoenix Flames. If you run out of instant abilities, cast Scorch instead since it's cast time is shorter." /> </Rule> <Rule name="Use your procs effectively" description={( <> Fire Mage revolves almost entirely around utilizing your procs effectively. Therefore it is very important that you manage your procs correctly to ensure that you get the most out of them. </> )} > <Requirement name="Hot Streak Proc Utilization" thresholds={thresholds.hotStreakUtilization} tooltip="Your Hot Streak Utilization. The bulk of your rotation revolves around successfully converting Heating Up procs into Hot Streak and using those Hot Streak procs effectively. Unless it is unavoidable, you should never let your Hot Streak procs expire without using them." /> <Requirement name="Wasted Crits Per Minute" thresholds={thresholds.hotStreakWastedCrits} tooltip="In addition to converting Heating Up to Hot Streak, it is also very important to use your Hot Streak procs as quickly as possible. This is primarily because you are unable to get a Heating Up proc if you already have Hot Streak. Therefore, casting abilities that can give you Heating Up while you have Hot Streak would be a big waste." /> <Requirement name="Hardcast into Hot Streak" thresholds={thresholds.hotStreakPreCasts} tooltip="Unless you are in Combustion and have Fire Blast/Phoenix Flames charges, you should always cast an ability that can generate Heating Up before using your Hot Streak proc. As an example, if you have Hot Streak and you cast Fireball > Pyroblast to use your Hot Streak, and one of those spells crit, then you will get Heating Up. If both spells crit, then you will instantly get a new Hot Streak proc." /> {combatant.hasTalent(SPELLS.PHOENIX_FLAMES_TALENT.id) && ( <Requirement name="Phoenix Flames Usage" thresholds={thresholds.phoenixFlamesHeatingUpUsage} tooltip="Because Phoenix Flames is guaranteed to crit, you should only use it to convert Heating Up into Hot Streak." /> )} <Requirement name="Fire Blast Usage" thresholds={thresholds.fireBlastHeatingUpUsage} tooltip="Because Fire Blast is guaranteed to crit, you should only use it to convert Heating Up into Hot Streak." /> </Rule> <Rule name="Use your talents effectively" description="Regardless of which talents you select, you should ensure that you are utilizing them properly. If you are having trouble effectively using a particular talent, you should consider taking a different talent that you can utilize properly or focus on effectively using the talents that you have selected." > {combatant.hasTalent(SPELLS.PYROCLASM_TALENT.id) && ( <Requirement name="Pyroclasm Utilization" thresholds={thresholds.pyroclasmUtilization} tooltip="Pyroclasm has a chance to give you a buff that makes your next non instant Pyroblast deal 225% additional damage. You should ensure that you are using these procs (especially during Combustion) somewhat quickly to ensure you dont waste or overwrite any of these procs." /> )} {combatant.hasTalent(SPELLS.SEARING_TOUCH_TALENT.id) && ( <Requirement name="Searing Touch Utilization" thresholds={thresholds.searingTouchUtilization} tooltip="Searing Touch causes your Scorch ability to deal 150% additional damage and be guaranteed to crit when the target is under 30% health. Therefore it is important that when the target is under 30% health, you cast Scorch instead of Fireball." /> )} {combatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id) && ( <Requirement name="Rune of Power Uptime" thresholds={thresholds.runeOfPowerBuffUptime} tooltip="Using Rune of Power effectively means being able to stay within the range of it for it's entire duration. If you are unable to do so or if you frequently have to move out of the range of the buff, consider taking a different talent instead." /> )} </Rule> <Rule name="Avoid downtime" description={( <> As a DPS, it is important to spend as much time casting as possible as if you are not casting then you are not doing damage. Therefore it is important to minimize your movements, stay within range of the target, and cancelling casts .. if you can avoid it. While some fights will have an amount of time that is unavoidable downtime; the more you can minimize that downtime, the better. </> )} > <Requirement name="Downtime" thresholds={thresholds.downtimeSuggestionThresholds} /> <Requirement name="Cancelled Casts" thresholds={thresholds.cancelledCasts} /> </Rule> <PreparationRule thresholds={thresholds}> <Requirement name="Arcane Intellect active" thresholds={thresholds.arcaneIntellectUptime} /> </PreparationRule> </Checklist> ); } } export default FireMageChecklist;
fields/types/markdown/MarkdownColumn.js
mikaoelitiana/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; var MarkdownColumn = React.createClass({ displayName: 'MarkdownColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { let value = this.props.data.fields[this.props.col.path]; return (value && Object.keys(value).length) ? value.md.substr(0, 100) : null; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); } }); module.exports = MarkdownColumn;
js/components/Navbar/Navbar.react.js
ryantang333/dashboard-prototype
import React, { Component } from 'react'; import { connect } from 'react-redux'; const Sidebar = () => { return ( <div id="navbar"> Hello. </div> ); }; // Which props do we want to inject, given the global state? const select = (state) => ({ data: state }); // Wrap the component to inject dispatch and state into it export default connect(select)(Sidebar);
src/components/common/ErrorMessage.js
brianyamasaki/rideshare
import React from 'react'; import { Text, View } from 'react-native'; const ErrorMessage = (props) => { const { containerStyleDft, textStyleDft } = styles; if (!props.children) { return null; } return ( <View style={containerStyleDft}> <Text style={textStyleDft}> {props.children} </Text> </View> ); } const styles = { containerStyleDft: { minHeight: 40, padding: 10, alignItems: 'center' }, textStyleDft: { fontSize: 18, lineHeight: 23, color: 'darkred' } }; export { ErrorMessage };
blueocean-material-icons/src/js/components/svg-icons/maps/ev-station.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsEvStation = (props) => ( <SvgIcon {...props}> <path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z"/> </SvgIcon> ); MapsEvStation.displayName = 'MapsEvStation'; MapsEvStation.muiName = 'SvgIcon'; export default MapsEvStation;
src/components/itemRow.js
antholord/poe-livesearch
/** * Created by Anthony Lord on 2017-04-21. */ import React from 'react'; import CopyToClipboard from 'react-copy-to-clipboard'; import Mods from './mods' import Image from "./image"; class ItemRow extends React.Component { constructor(props){ super(props); this.state = { copied : false}; this.displayRequirements = this.displayRequirements.bind(this); this.displayLinks = this.displayLinks.bind(this); this.buildMessage = this.buildMessage.bind(this); this.findProp = this.findProp.bind(this); /* this.armour = this.findProp("Armour"); this.evasion = this.findProp("Evasion Rating"); this.es = this.findProp("Energy Shield"); this.block = this.findProp("Block"); this.crit = this.findProp("Critical Strike Chance"); this.quality = this.findProp("Quality"); this.aps = Number(this.findProp("Attacks per Second")); this.phys = this.findProp("Physical Damage"); this.ele = this.findProp("Elemental Damage"); this.chaos = this.findProp("Chaos Damage"); this.cdps = (this.chaos) ? Math.round(this.chaos * this.aps) : ''; this.pdps = (this.phys) ? Math.round(this.phys * this.aps) : ''; this.edps = (this.ele) ? Math.round(this.ele * this.aps) : ''; this.dps = ((this.phys) ? this.pdps : 0) + ((this.ele) ? this.edps : 0) + ((this.chaos) ? this.cdps : 0); */ } displayRequirements(){ if (!this.props.item.Item.requirements){ return ( <div className="smallInfo flexBottom"> <span>ilvl : {this.props.item.Item.ilvl}</span> </div> ); } return ( <div className="smallInfo flexBottom"> <span>ilvl : {this.props.item.Item.ilvl}</span> {(this.props.item.Item.requirements[0] && this.props.item.Item.requirements[0].name === "Level") ? <span>Req : Lvl {this.props.item.Item.requirements[0].values[0][0]}</span> : null} {(this.props.item.Item.requirements[1] && this.props.item.Item.requirements[1].name) ? <span>{this.props.item.Item.requirements[1].name}{' : '}{this.props.item.Item.requirements[1].values[0][0]}</span> : null} {(this.props.item.Item.requirements[2] && this.props.item.Item.requirements[2].name) ? <span>{this.props.item.Item.requirements[2].name}{' : '}{this.props.item.Item.requirements[2].values[0][0]}</span> : null} {(this.props.item.Item.requirements[3] && this.props.item.Item.requirements[3].name) ? <span>{this.props.item.Item.requirements[3].name}{' : '}{this.props.item.Item.requirements[3].values[0][0]}</span> : null} <span>{(!this.props.item.Item.identified) ? 'Unidentified' : null}</span> </div> ); } displayLinks() { let s = ''; if (this.props.item.Item.links) { Object.values(this.props.item.Item.links).map((item) => { s += (item>1) ? item + 'L ' : ''; }) } return s } buildMessage() { const r = this.props.item; let s= '@' + r.lastCharacterName + ' Hi, I would like to purchase your ' + ((r.Item.stackSize>1) ? r.Item.stackSize : '') + r.Item.name + ' ' + r.Item.typeLine; if (r.Item.note.length>0){ if (r.Item.note.substring(0,6) === "~price"){ s+= ' listed for ' + r.Item.note.substring(6,r.Item.note.length); }else if (r.Item.note.substring(0,4) === "~b/o"){ s+= ' listed for ' + r.Item.note.substring(4,r.Item.note.length); } } s+=' in tab "' + r.stash + '"'; return s; } findProp(s) { if (!this.props.item.Item.properties) return null; let f = this.props.item.Item.properties.find(function(o) {return o.name === s;}); if (!f) return null; let r=0; if (s.includes("Damage") && f.values[0][0] && f.values[0][0].includes("-")){ for (let i = 0;i<f.values.length;i++){ let arr = f.values[i][0].split("-"); if (arr.length>0){ r+= ((Number(arr[0]) + Number(arr[1])) / 2); } } }else{ return f.values[0][0]; } return r; } render() { const r = this.props.item; const cp = this.props.item.Item.customProperties; return ( <li className="media container-fluid"> <div className="panel itemPanel panel-default"> <div className="panel-body"> <div className="media-left"> <Image key={this.props.index+'-img'} item={r} index={this.props.index+'-img'}/> {(r.Item.stackSize) ? '# : ' + r.Item.stackSize : null} </div> <div className="media-body"> <div className="media-top"> <div className="media-heading"> <span className={"item itemframe" + r.Item.frameType}> <h5 className={"item itemframe" + r.Item.frameType}> {r.Item.name} </h5> </span> <h6> {' ' + r.Item.typeLine} </h6> <span className="corrupted"> {(r.Item.corrupted) ? 'Corrupted' : null} </span> </div> {this.displayRequirements()} </div> <div className="media-middle"> <div className=""> <Mods item={r.Item}/> </div> </div> </div> <div className="media-body tableBody"> <table className="table table-condensed"> <thead> <tr className="center text-center"> <th className="text-center">Armour</th> <th className="text-center">Evasion</th> <th className="text-center">Shield</th> <th className="text-center">Block</th> <th className="text-center">Crit</th> <th className="text-center">Qual</th> </tr> </thead> <tbody className="text-center"> <tr> <td>{(cp.armour === 0) ? '' : cp.armour}</td> <td>{(cp.evasion === 0) ? '' : cp.evasion}</td> <td>{(cp.es === 0) ? '' : cp.es}</td> <td>{(cp.block === 0) ? '' : cp.block}</td> <td>{(cp.crit === 0) ? '' : cp.crit}</td> <td>{(cp.quality === 0) ? '' : cp.quality}</td> </tr> </tbody> </table> <table className="table table-condensed"> <thead> <tr className="center text-center"> <th className="text-center">pDPS</th> <th className="text-center">eDPS</th> <th className="text-center">DPS</th> <th className="text-center">APS</th> <th className="text-center">Phys</th> <th className="text-center">Ele</th> </tr> </thead> <tbody className="text-center"> <tr> <td>{(cp.pdps === 0) ? '' : Math.round(cp.pdps)}</td> <td>{(cp.edps === 0) ? '' : Math.round(cp.edps)}</td> <td>{(cp.dps === 0) ? '' : Math.round(cp.dps)}</td> <td>{(cp.aps === 0) ? '' : cp.aps.toFixed(2)}</td> <td>{(cp.phys === 0) ? '' : Math.round(cp.phys)}</td> <td>{(cp.ele === 0) ? '' : Math.round(cp.ele)}</td> </tr> </tbody> </table> </div> <div className="media-right"> </div> <div className="media-bottom flexBottom col-md-12 top10"> <div className="col-md-9"> <span>Name : {r.lastCharacterName}</span><span> Account : {r.accountName}</span> <span className=""> Note : {r.Item.note}</span> </div> <div className="col-md-3"> <CopyToClipboard text={this.buildMessage()}> <button type='text' className="btnToLink media-bottom pull-right media-right"> ~Message seller~ </button> </CopyToClipboard> <CopyToClipboard text={JSON.stringify(r)}> <button type='text' className="btnToLink media-bottom media-right pull-right"> d </button> </CopyToClipboard> </div> </div> </div> </div> </li> ); } } export default ItemRow;
views/components/FormTextAreaUi.js
gvaldambrini/madam
import React from 'react'; // A form textarea presentational component. export default React.createClass({ propTypes: { handleChange: React.PropTypes.func.isRequired, name: React.PropTypes.string.isRequired, label: React.PropTypes.string.isRequired, value: React.PropTypes.string, formHorizontal: React.PropTypes.bool }, getDefaultProps: function() { return { formHorizontal: true }; }, getInitialState: function() { return {value: ''}; }, componentWillMount: function() { this.setState({value: this.props.value}); }, componentWillReceiveProps: function(nextProps) { this.setState({value: nextProps.value}); }, handleChange: function(event) { this.props.handleChange(this.props.name, event.currentTarget.value); }, render: function() { const textarea = ( <textarea name={this.props.name} className="form-control" rows="5" value={this.state.value} onChange={this.handleChange}> </textarea> ); if (this.props.formHorizontal) { return ( <div className="form-group"> <label className="control-label col-sm-2">{this.props.label}</label> <div className="col-sm-10"> {textarea} </div> </div> ); } return ( <div className="form-group"> <div className="col-sm-12"> <label className="control-label">{this.props.label}</label> {textarea} </div> </div> ); } });
docs/app/Examples/modules/Popup/Usage/PopupExampleClick.js
aabustamante/Semantic-UI-React
import React from 'react' import { Button, Popup } from 'semantic-ui-react' const PopupExampleClick = () => ( <Popup trigger={<Button color='red' icon='flask' content='Activate doomsday device' />} content={<Button color='green' content='Confirm the launch' />} on='click' position='top right' /> ) export default PopupExampleClick
src/svg-icons/av/music-video.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMusicVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/> </SvgIcon> ); AvMusicVideo = pure(AvMusicVideo); AvMusicVideo.displayName = 'AvMusicVideo'; AvMusicVideo.muiName = 'SvgIcon'; export default AvMusicVideo;
website/src/components/edit-link.js
netlify/netlify-cms
import React from 'react'; import { css } from '@emotion/core'; function EditLink({ collection, filename }) { return ( <div css={css` float: right; a { font-weight: 700; } #pencil { fill: #7ca511; } `} > <a href={`/admin/#/edit/${collection}/${filename}`} target="_blank" rel="noopener noreferrer"> <svg version="1.1" id="pencil" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="14px" height="14px" viewBox="0 0 512 512" enableBackground="new 0 0 512 512" xmlSpace="preserve" > <path d="M398.875,248.875L172.578,475.187l-22.625-22.625L376.25,226.265L398.875,248.875z M308.375,158.39L82.063,384.687 l45.266,45.25L353.625,203.64L308.375,158.39z M263.094,113.125L36.828,339.437l22.625,22.625L285.75,135.765L263.094,113.125z M308.375,67.875L285.719,90.5L421.5,226.265l22.625-22.625L308.375,67.875z M376.25,0L331,45.25l135.75,135.766L512,135.781 L376.25,0z M32,453.5V480h26.5L32,453.5 M0,376.25L135.766,512H0V376.25L0,376.25z" /> </svg>{' '} Edit this page </a> </div> ); } export default EditLink;
src/class/options/OptionsUtils.js
MrMamen/traktflix
import React from 'react'; import BrowserStorage from '../BrowserStorage'; import OptionsActionsCreators from './OptionsActionCreators'; class OptionsUtils { constructor() { this.options = [{ id: `disableScrobbling`, name: ``, description: ``, value: false }, { id: `allowGoogleAnalytics`, name: ``, description: ``, value: false, origins: [`*://google-analytics.com/*`] }, { id: `allowRollbar`, name: ``, description: ``, value: false, origins: [`*://api.rollbar.com/*`] }, { id: `showNotifications`, name: ``, description: ``, value: false, permissions: [`notifications`] }, { id: `sendReceiveSuggestions`, name: ``, description: ``, value: false, origins: [`*://script.google.com/*`, `*://script.googleusercontent.com/*`], additionalElements: ( <React.Fragment> <br></br> <a href="https://docs.google.com/spreadsheets/d/1Yq9rnpszwh2XFVllLkNelaFeu8FY0lldd91ce7JVZPk/edit?usp=sharing" target="_blank">Database</a> </React.Fragment> ) }]; } async getOptions() { try { const storage = await BrowserStorage.get(`options`); for (const option of this.options) { option.name = browser.i18n.getMessage(`${option.id}Name`); option.description = browser.i18n.getMessage(`${option.id}Description`); if (storage.options) { option.add = storage.options[option.id]; } } OptionsActionsCreators.receiveOptions(this.options); } catch (error) { OptionsActionsCreators.receiveOptionsFailed(error); } } } const optionsUtils = new OptionsUtils(); export default optionsUtils;
frontend/src/Components/Loading/LoadingIndicator.js
lidarr/Lidarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import styles from './LoadingIndicator.css'; function LoadingIndicator({ className, rippleClassName, size }) { const sizeInPx = `${size}px`; const width = sizeInPx; const height = sizeInPx; return ( <div className={className} style={{ height }} > <div className={classNames(styles.rippleContainer, 'followingBalls')} style={{ width, height }} > <div className={rippleClassName} style={{ width, height }} /> <div className={rippleClassName} style={{ width, height }} /> <div className={rippleClassName} style={{ width, height }} /> </div> </div> ); } LoadingIndicator.propTypes = { className: PropTypes.string, rippleClassName: PropTypes.string, size: PropTypes.number }; LoadingIndicator.defaultProps = { className: styles.loading, rippleClassName: styles.ripple, size: 50 }; export default LoadingIndicator;
app/viewControllers/components/unused/CountdownTicker.js
Evyy/cffs-ui
'use strict'; import React from 'react'; import countdown from 'countdown'; class CountdownTicker extends React.Component { constructor (props) { super(props); } static propTypes = { to: React.PropTypes.instanceOf(Date).isRequired }; state = { timeLeft: countdown(this.props.to) } componentDidMount () { let blah = this; this.countdownInterval = setInterval(function() { blah.updateTimeLeft() }, 1000); } componentWillUnmount () { clearInterval(this.countdownInterval); } updateTimeLeft () { this.setState({ timeLeft: countdown(this.props.to) }) } render () { let tl = this.state.timeLeft; return ( <div className="countdown-ticker"> <ul> <li> {tl.days} <em>d</em> </li> <li> {tl.hours} <em>h</em> </li> <li> {tl.minutes} <em>m</em> </li> <li> {tl.seconds} <em>s</em> </li> </ul> </div> ); } } export default CountdownTicker;
src/routes/MyResource/components/MyResource.js
TheModevShop/craft-app
import React from 'react'; import {Link} from 'react-router'; import _ from 'lodash'; import AddResource from './AddResource/AddResource'; import ResourceContent from './ResourceContent/ResourceContent'; import AddConfig from './AddConfig/AddConfig'; import Dashboard from './Dashboard/Dashboard'; import ConfigContent from './ConfigContent/ConfigContent'; import moment from 'moment' import './my-resource.less'; class MyResource extends React.Component { constructor(...args) { super(...args); this.state = { }; } componentDidMount() { const resourceId = _.get(this.props.membership, 'membership_id'); if (resourceId && _.get(this.props.membership, 'membership_type') === 'resource') { this.props.getConfigsForResource(resourceId); this.props.getAnalyticsForResource(resourceId) } } componentWillReceiveProps(nextProps) { const resourceId = _.get(this.props.membership, 'membership_id'); const nextResourceId = _.get(nextProps.membership, 'membership_id'); if (!resourceId && nextResourceId && _.get(nextProps.membership, 'membership_type') === 'resource') { this.props.getConfigsForResource(resourceId); this.props.getAnalyticsForResource(resourceId); } } render() { const {membership, configs} = this.props; const hasConfigs = _.get(configs, 'items.length'); const hasAnalytics = _.get(this.props.analytics, 'ui.data.rows.length') const daysLeft = membership ? 7 - moment().diff(moment(membership.resource_created_at), 'days') : 100; return ( <div className="my-resource-wrapper page-wrapper"> { membership && !membership.premium ? <div style={{marginBottom: 30}}> <div className="banner card"> <span> { daysLeft > 0 ? <h2 className="bold" style={{color: '#9c4610', marginBottom: '5px'}}>You currently have {daysLeft} {daysLeft === 1 ? 'day' : 'days'} left on your free trial</h2> : <h2 className="bold" style={{color: 'red', marginBottom: '5px'}}>Your free trial has expired.</h2> } <h5><Link className="secondary-link text-link" to={'/admin/settings?premium=true'}>Upgrade to Premium</Link></h5> </span> </div> </div> : null } { membership ? <div> { hasConfigs && !hasAnalytics ? <div className="banner card"> <span> <h2 className="bold" style={{marginBottom: '5px'}}>You currently have no analytics. In the mean time you can add more products.</h2> <h5><Link className="secondary-link text-link" to={'/admin/products'}>Add Products Now</Link></h5> </span> </div> : null } </div> : <div> <div className="banner card"> <span> <h2 className="bold" style={{marginBottom: '5px'}}>Add Information About your Business</h2> <h5>We will use information about your business to allow us to easily contact you letting you know when there have been changes to the sytem or your account.</h5> </span> </div> <AddResource {...this.props} /> </div> } <br /> <br /> { hasConfigs || !membership ? null: <div> <div className="banner card"> <span> <h2 className="bold" style={{marginTop: '5px'}}>Linking Your First Report.</h2> <h5>Linking a report configuration to your current distribution data allows us to automatically map where your products can be found. After you link the report, you will then setup the fields.</h5> <h5 style={{margin: '20px 0 0 0'}}><a className="secondary-link" target="_blank" href="https://docs.google.com/document/d/1c_ltkjJCpVcaCVIaJFY7GtETHGg2ZvxLnJtI4nkJlGM/edit?usp=sharing">HOW TO SETUP YOUR REPORT (ENCOMPASS ONLY)</a></h5> </span> </div> <AddConfig redirect={true} {...this.props} membership={membership} /> </div> } { hasAnalytics ? <Dashboard analytics={_.get(this.props.analytics, 'ui')} /> : null } </div> ); } } MyResource.propTypes = { membership: React.PropTypes.object.isRequired, configs: React.PropTypes.object, getConfigsForResource: React.PropTypes.func.isRequired, getAnalyticsForResource: React.PropTypes.func.isRequired, }; export default MyResource;
src/client.js
mudetroit/rivalry
import React from 'react'; import ReactDOM from 'react-dom'; import {App} from './ui/app'; ReactDOM.render(<App />, document.getElementById('app'));
react/features/reactions/components/web/ReactionButton.js
gpolitis/jitsi-meet
/* @flow */ import React from 'react'; import { Tooltip } from '../../../base/tooltip'; import AbstractToolbarButton from '../../../toolbox/components/AbstractToolbarButton'; import type { Props as AbstractToolbarButtonProps } from '../../../toolbox/components/AbstractToolbarButton'; /** * The type of the React {@code Component} props of {@link ReactionButton}. */ type Props = AbstractToolbarButtonProps & { /** * Optional text to display in the tooltip. */ tooltip?: string, /** * From which direction the tooltip should appear, relative to the * button. */ tooltipPosition: string, /** * Optional label for the button. */ label?: string }; /** * The type of the React {@code Component} state of {@link ReactionButton}. */ type State = { /** * Used to determine zoom level on reaction burst. */ increaseLevel: number, /** * Timeout ID to reset reaction burst. */ increaseTimeout: TimeoutID | null } /** * Represents a button in the reactions menu. * * @augments AbstractToolbarButton */ class ReactionButton extends AbstractToolbarButton<Props, State> { /** * Default values for {@code ReactionButton} component's properties. * * @static */ static defaultProps = { tooltipPosition: 'top' }; /** * Initializes a new {@code ReactionButton} instance. * * @inheritdoc */ constructor(props: Props) { super(props); this._onKeyDown = this._onKeyDown.bind(this); this._onClickHandler = this._onClickHandler.bind(this); this.state = { increaseLevel: 0, increaseTimeout: null }; } _onKeyDown: (Object) => void; _onClickHandler: () => void; /** * Handles 'Enter' key on the button to trigger onClick for accessibility. * We should be handling Space onKeyUp but it conflicts with PTT. * * @param {Object} event - The key event. * @private * @returns {void} */ _onKeyDown(event) { // If the event coming to the dialog has been subject to preventDefault // we don't handle it here. if (event.defaultPrevented) { return; } if (event.key === 'Enter') { event.preventDefault(); event.stopPropagation(); this.props.onClick(); } } /** * Handles reaction button click. * * @returns {void} */ _onClickHandler() { this.props.onClick(); clearTimeout(this.state.increaseTimeout); const timeout = setTimeout(() => { this.setState({ increaseLevel: 0 }); }, 500); this.setState(state => { return { increaseLevel: state.increaseLevel + 1, increaseTimeout: timeout }; }); } /** * Renders the button of this {@code ReactionButton}. * * @param {Object} children - The children, if any, to be rendered inside * the button. Presumably, contains the emoji of this {@code ReactionButton}. * @protected * @returns {ReactElement} The button of this {@code ReactionButton}. */ _renderButton(children) { return ( <div aria-label = { this.props.accessibilityLabel } aria-pressed = { this.props.toggled } className = 'toolbox-button' onClick = { this._onClickHandler } onKeyDown = { this._onKeyDown } role = 'button' tabIndex = { 0 }> { this.props.tooltip ? <Tooltip content = { this.props.tooltip } position = { this.props.tooltipPosition }> { children } </Tooltip> : children } </div> ); } /** * Renders the icon (emoji) of this {@code reactionButton}. * * @inheritdoc */ _renderIcon() { const { toggled, icon, label } = this.props; const { increaseLevel } = this.state; return ( <div className = { `toolbox-icon ${toggled ? 'toggled' : ''}` }> <span className = { `emoji increase-${increaseLevel > 12 ? 12 : increaseLevel}` }>{icon}</span> {label && <span className = 'text'>{label}</span>} </div> ); } } export default ReactionButton;
app/javascript/mastodon/features/list_editor/components/search.js
PlantsNetwork/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists'; import classNames from 'classnames'; const messages = defineMessages({ search: { id: 'lists.search', defaultMessage: 'Search among people you follow' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'suggestions', 'value']), }); const mapDispatchToProps = dispatch => ({ onSubmit: value => dispatch(fetchListSuggestions(value)), onClear: () => dispatch(clearListSuggestions()), onChange: value => dispatch(changeListSuggestions(value)), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class Search extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleKeyUp = e => { if (e.keyCode === 13) { this.props.onSubmit(this.props.value); } } handleClear = () => { this.props.onClear(); } render () { const { value, intl } = this.props; const hasValue = value.length > 0; return ( <div className='list-editor__search search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span> <input className='search__input' type='text' value={value} onChange={this.handleChange} onKeyUp={this.handleKeyUp} placeholder={intl.formatMessage(messages.search)} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={classNames('fa fa-search', { active: !hasValue })} /> <i aria-label={intl.formatMessage(messages.search)} className={classNames('fa fa-times-circle', { active: hasValue })} /> </div> </div> ); } }
app/javascript/mastodon/features/compose/containers/warning_container.js
kagucho/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import Warning from '../components/warning'; import { createSelector } from 'reselect'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { OrderedSet } from 'immutable'; const getMentionedUsernames = createSelector(state => state.getIn(['compose', 'text']), text => text.match(/(?:^|[^\/\w])@([a-z0-9_]+@[a-z0-9\.\-]+)/ig)); const getMentionedDomains = createSelector(getMentionedUsernames, mentionedUsernamesWithDomains => { return OrderedSet(mentionedUsernamesWithDomains !== null ? mentionedUsernamesWithDomains.map(item => item.split('@')[2]) : []); }); const mapStateToProps = state => { const mentionedUsernames = getMentionedUsernames(state); const mentionedUsernamesWithDomains = getMentionedDomains(state); return { needsLeakWarning: (state.getIn(['compose', 'privacy']) === 'private' || state.getIn(['compose', 'privacy']) === 'direct') && mentionedUsernames !== null, mentionedDomains: mentionedUsernamesWithDomains, needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', state.getIn(['meta', 'me']), 'locked']), }; }; const WarningWrapper = ({ needsLeakWarning, needsLockWarning, mentionedDomains }) => { if (needsLockWarning) { return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />; } else if (needsLeakWarning) { return ( <Warning message={<FormattedMessage id='compose_form.privacy_disclaimer' defaultMessage='Your private status will be delivered to mentioned users on {domains}. Do you trust {domainsCount, plural, one {that server} other {those servers}}? Post privacy only works on Mastodon instances. If {domains} {domainsCount, plural, one {is not a Mastodon instance} other {are not Mastodon instances}}, there will be no indication that your post is private, and others may pay a blue rupee for the post or otherwise it may be made visible to unintended recipients.' values={{ domains: <strong>{mentionedDomains.join(', ')}</strong>, domainsCount: mentionedDomains.size }} />} /> ); } return null; }; WarningWrapper.propTypes = { needsLeakWarning: PropTypes.bool, needsLockWarning: PropTypes.bool, mentionedDomains: ImmutablePropTypes.orderedSet.isRequired, }; export default connect(mapStateToProps)(WarningWrapper);
app/components/calendar/Month.js
adrilo/headek
import React, { Component } from 'react'; import { Table } from 'react-bootstrap'; import Weekdays from './Weekdays'; import Week from './Week'; export default class Month extends Component { render() { let splittedWeeks = this.getSplittedWeeksData(); let tableStyle = { backgroundColor: '#FFFFFF' }; return ( <Table bordered style={tableStyle}> <Weekdays /> <tbody> {splittedWeeks.map((week) => { return ( <Week weekDates={week} headaches={this.props.headaches} key={week[0].date} /> ); })} </tbody> </Table> ); } getSplittedWeeksData() { const NUM_DAYS_PER_WEEK = 7; let year = this.props.year, month = this.props.month, startDayIndexCurrentMonth = this.getStartDayIndexCurrentMonth(year, month), lastDayIndexCurrentMonth = this.getLastDayIndexCurrentMonth(year, month), numDaysCurrentMonth = this.getNumDaysCurrentMonth(year, month), numDaysPreviousMonth = this.getNumDaysPreviousMonth(year, month), weeks = [], currentWeek = [], splittedWeeks = [], i; // first week for (i = startDayIndexCurrentMonth - 1; i >= 0; i--) { weeks.push({ date: new Date(year, month - 1, numDaysPreviousMonth - i), isFromCurrentMonth: false }); } for (i = 1; i <= numDaysCurrentMonth; i++) { weeks.push({ date: new Date(year, month, i), isFromCurrentMonth: true }); } for (i = 1; i <= (NUM_DAYS_PER_WEEK - lastDayIndexCurrentMonth); i++) { weeks.push({ date: new Date(year, month + 1, i), isFromCurrentMonth: false }); } // split by week for (i = 1; i <= weeks.length; i++) { currentWeek.push(weeks[i]); if (i % NUM_DAYS_PER_WEEK === 0) { splittedWeeks.push(currentWeek); currentWeek = []; } } return splittedWeeks; } getStartDayIndexCurrentMonth(year, month) { var startDayIndex = new Date(year, month, 1).getDay(); return (startDayIndex === 0) ? 7 : startDayIndex; } getLastDayIndexCurrentMonth(year, month) { var lastDayIndex = new Date(year, month + 1, 0).getDay(); return (lastDayIndex === 0) ? 7 : lastDayIndex; } getNumDaysCurrentMonth(year, month) { return new Date(year, month + 1, 0).getDate(); } getNumDaysPreviousMonth(year, month) { return new Date(year, month, 0).getDate(); } }
src/react/LogMonitorButton.js
hetony/redux-devtools
import React from 'react'; import brighten from '../utils/brighten'; const styles = { base: { cursor: 'pointer', fontWeight: 'bold', borderRadius: 3, padding: 4, marginLeft: 3, marginRight: 3, marginTop: 5, marginBottom: 5, flexGrow: 1, display: 'inline-block', fontSize: '0.8em', color: 'white', textDecoration: 'none' } }; export default class LogMonitorButton extends React.Component { constructor(props) { super(props); this.state = { hovered: false, active: false }; } handleMouseEnter() { this.setState({ hovered: true }); } handleMouseLeave() { this.setState({ hovered: false }); } handleMouseDown() { this.setState({ active: true }); } handleMouseUp() { this.setState({ active: false }); } onClick() { if (!this.props.enabled) { return; } if (this.props.onClick) { this.props.onClick(); } } render() { let style = { ...styles.base, backgroundColor: this.props.theme.base02 }; if (this.props.enabled && this.state.hovered) { style = { ...style, backgroundColor: brighten(this.props.theme.base02, 0.2) }; } if (!this.props.enabled) { style = { ...style, opacity: 0.2, cursor: 'text', backgroundColor: 'transparent' }; } return ( <a onMouseEnter={::this.handleMouseEnter} onMouseLeave={::this.handleMouseLeave} onMouseDown={::this.handleMouseDown} onMouseUp={::this.handleMouseUp} style={style} onClick={::this.onClick}> {this.props.children} </a> ); } }
src/ui/components/views/Page/PageLoading.js
belng/pure
/* @flow */ import React, { Component } from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import LoadingItem from '../Core/LoadingItem'; import Page from './Page'; export default class PageLoading extends Component<void, any, void> { shouldComponentUpdate(nextProps: any, nextState: any): boolean { return shallowCompare(this, nextProps, nextState); } render() { return ( <Page {...this.props}> <LoadingItem /> </Page> ); } }
src/server/modules/send-html.js
Noviel/osnova-react-environment
// Created by snov on 10.02.2017. // // Generates HTML based on Webpack bundle // //========================================================================= import React from 'react'; import reactDOM from 'react-dom/server'; import App from '../../components/App'; import Html from '../../components/Html'; import { getAssets } from '../../../dev/webpack-utils'; const sendHtml = (/*opts*/) => osnova => { const app = osnova.express; app.get('*', (req, res) => { res.send('<!doctype html>\n' + reactDOM.renderToString(<Html assets={ getAssets() } component={<App/>}/>)); }); osnova.next(); }; export default sendHtml;
src/client/index.js
MrCheater/demo-counter
import React from 'react'; import App from './components/container/App'; import './styles.css'; export default function () { return <App />; }
tests/lib/rules/vars-on-top.js
ipanasenko/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/vars-on-top"), EslintTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new EslintTester(); ruleTester.run("vars-on-top", rule, { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 }, errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
src/components/Helper/RandomAvatar.js
steem/qwp-antd
import React from 'react' import styles from './avatar.less' import _ from 'lodash' class Avatar extends React.Component { render() { let c1 = _.random(0, 255) let c2 = _.random(0, 255) let c3 = _.random(0, 255) let b1 = 255 - c1 let b2 = 255 - c2 let b3 = 255 - c3 let br1 = parseInt(c1 * 2 / 3) let br2 = parseInt(c2 * 2 / 3) let br3 = parseInt(c3 * 2 / 3) let square = this.props.square || 24 let props = { width: square, height: square, backgroundColor: `rgb(${b1},${b2},${b3})`, color: `rgb(${c1},${c2},${c3})`, border: `1px solid rgb(${br1},${br2},${br3})`, } let textProps = { fontSize: this.props.fontSize || '12px', } return ( <div className={styles.avatar} style={{ ...props }}> <span style={{ ...textProps }} >{this.props.text.toUpperCase()}</span> </div> ) } } export default Avatar
app/clients/next/components/pagination.js
garbin/koapp
import React from 'react' import Paginate from 'react-paginate' import { translate } from 'react-i18next' export default translate(['common'])(class Pagination extends React.Component { render () { const { t } = this.props return ( <Paginate containerClassName='pagination' pageClassName='page-item' pageLinkClassName='page-link' activeClassName='active' previousLabel={t('prev_page')} previousClassName='page-item' previousLinkClassName='page-link' breakClassName='page-item' breakLabel={<a className='page-link'>...</a>} nextLabel={t('next_page')} nextClassName='page-item' disableInitialCallback nextLinkClassName='page-link' {...this.props} /> ) } })
website/scripts/generate-headings.js
rofrischmann/fela
import { outputFileSync, readFileSync } from 'fs-extra' import { join } from 'path' import recursive from 'recursive-readdir' import React from 'react' import TestRenderer from 'react-test-renderer' import MDX from '@mdx-js/runtime' import { getFixedId, getId } from '../components/Heading' function Heading({ level, children, addHeading }) { const [text, fixedId] = getFixedId(children) const id = getId(children, level, fixedId) addHeading([text, id, level]) return null } function generateHeadings(file) { const headings = [] const components = { h2: ({ children }) => ( <Heading level={2} addHeading={(h) => headings.push(h)}> {children} </Heading> ), h3: ({ children }) => ( <Heading level={3} addHeading={(h) => headings.push(h)}> {children} </Heading> ), h4: ({ children }) => ( <Heading level={4} addHeading={(h) => headings.push(h)}> {children} </Heading> ), h5: ({ children }) => ( <Heading level={5} addHeading={(h) => headings.push(h)}> {children} </Heading> ), h6: ({ children }) => ( <Heading level={6} addHeading={(h) => headings.push(h)}> {children} </Heading> ), } const content = readFileSync(file, 'utf-8') TestRenderer.create(<MDX components={components}>{content}</MDX>) return headings } recursive(join(__dirname, '../pages/docs'), (err, files) => { if (err) { throw err } // `files` is an array of file paths files.forEach((file) => { const headings = generateHeadings(file) const dataPath = file.replace('/pages/docs/', '/data/headings/') outputFileSync( dataPath.replace('.mdx', '.json'), JSON.stringify(headings, null, 2) ) }) })
node_modules/recompose/renderComponent.js
SerendpityZOEY/Fixr-RelevantCodeSearch
'use strict'; exports.__esModule = true; var _createHelper = require('./createHelper'); var _createHelper2 = _interopRequireDefault(_createHelper); var _createEagerFactory = require('./createEagerFactory'); var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // import React from 'react' var renderComponent = function renderComponent(Component) { return function (_) { var factory = (0, _createEagerFactory2.default)(Component); var RenderComponent = function RenderComponent(props) { return factory(props); }; // const RenderComponent = props => <Component {...props} /> if (process.env.NODE_ENV !== 'production') { /* eslint-disable global-require */ var wrapDisplayName = require('./wrapDisplayName').default; /* eslint-enable global-require */ RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent'); } return RenderComponent; }; }; exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false);
app/components/Resume.js
jayteesanchez/website-v1
import React from 'react'; import {Link} from 'react-router'; import ResumeStore from '../stores/ResumeStore' import ResumeActions from '../actions/ResumeActions'; class Resume extends React.Component { constructor(props) { super(props); this.state = ResumeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { ResumeStore.listen(this.onChange); document.getElementById('name-brand').style.opacity = ''; document.getElementById('resume').className = 'current-state'; document.getElementById('technologies').className = 'nav-links'; document.getElementById('projects').className = 'nav-links'; } componentWillUnmount() { ResumeStore.unlisten(this.onChange); } onChange(state) { document.getElementByClassName('container').classList.remove('fadeIn animated'); document.getElementByClassName('container').classList.add('fadeOut animated'); this.setState(state); } render() { return ( <div className='container fadeIn animated'> <div className='col-xs-10 col-sm-10 col-md-8 col-md-offset-2' style={{paddingBottom: '200px;'}}> <div className="panel panel-default text-center"> <br></br> <text className='project-title'>Under Construction, Please Check out my <a href="https://www.linkedin.com/in/jayteesanchez">Linked-In!</a></text> <br></br> <br></br> </div> </div> </div> ) } } export default Resume;
app/components/Offline.js
lotgd/client-graphql-www
import React from 'react'; import Message from './parts/Message'; import ThreeColumnLayout from './parts/ThreeColumnLayout'; import Form from './../../src/Form'; class Offline extends React.Component { onSubmit(type, state) { state["type"] = type; this.props.loginCallback(state); } render() { const form = [ {type: "email", label: "email address", fieldName: "email", defaultValue: "admin"}, {type: "password", label: "password", fieldName: "password", defaultValue: "12345"}, ]; const middle = <div className="d-loginPrompt"> <h2>Login Form</h2> {this.props.message && <Message isError={this.props.error} message={this.props.message} />} <Form fields={form} submitButton="Log In" onSubmit={this.onSubmit.bind(this, "classic")} /> </div>; return <ThreeColumnLayout middle={middle} /> } } export default Offline;
src/components/views/delegateProfile/components/RightBar.js
LiskHunt/LiskHunt
import React from 'react'; import SocialBar from './SocialBar'; import DonationBar from './DonationBar'; const RightBar = ({ social, donations }) => { return ( <div className="right-bar column"> <SocialBar social={social} /> <DonationBar donations={donations} /> </div> ); }; export default RightBar;
app_learn/src/containers/Tab1/cameraRollDemo.js
liuboshuo/react-native
/** * Created by ls-mac on 2017/5/10. */ import React, { Component } from 'react'; import { View, StyleSheet, TouchableOpacity, Text } from 'react-native'; import NavigationBar from '../../component/navBarCommon' import back from './../../source/images/icon_back.png' import * as Constants from '../../constants/constant' import CameraRollPicker from 'react-native-camera-roll-picker' export default class cameraRollDemo extends Component { getSelectedImages(images,current){ } render() { const {title} = this.props.data; return ( <View style={styles.container}> <NavigationBar title={title} leftImage={ back } leftAction={()=>this.props.navigator.pop()}/> <CameraRollPicker callback={this.getSelectedImages.bind(this)} /> </View> ); } } const styles = StyleSheet.create({ container:{ flex:1, backgroundColor:Constants.viewBgColor }, buttonStyle:{ height:40, backgroundColor:'red', justifyContent:'center', alignItems:'center', borderRadius:6, margin:10 } });
js/app/categories/store.js
monetario/web
'use strict'; import React from 'react'; import Reflux from 'reflux'; import API from '../../api'; import Actions from './actions'; import DEFAULT_PAGE_SIZE from '../../constants'; var Store = Reflux.createStore({ listenables: [ Actions ], init() { this.categories = []; this.meta = { "first_url": null, "last_url": null, "next_url": null, "page": 1, "pages": 1, "per_page": 5, "prev_url": null, "total": 0 }; }, getDefaultData() { return { meta: this.meta, categories: this.categories }; }, getAll() { return this.categories; }, _loadUrl(url) { API.get(url).then((data) => { this.categories = data.objects; this.meta = data.meta; this.trigger({categories: this.categories, meta: this.meta}); }); }, onLoadUrl(url) { this._loadUrl(url); }, onLoad() { this._loadUrl( `/API/v1/group_categories/?expand=1&per_page=${DEFAULT_PAGE_SIZE}&page=1&sort=date,desc` ) }, }); export default Store;
components/BookDetailApp/BookDetail.react.js
react-douban/douban-book-web
import '../../semantic-ui/components/item.min.css'; import React from 'react' import { render } from 'react-dom' import { Items, Item, Content, Link, Image, Loader, List } from '../react-semantify' const BookDetail = React.createClass({ render() { const book = this.props.book; return ( <div> <Loader msg='正在加载中...' active={this.props.loading} /> <Items > <Item> <Image className='small' src={book.image} /> <Content> <Link className='header'>{book.title}</Link> <div className='description'> <List> <Item> 作者:&nbsp;{book.author} </Item> <Item> 出版社:&nbsp;{book.publisher} </Item> <Item> 出版年:&nbsp;{book.pubdate} </Item> <Item> 页数:&nbsp;{book.pubdate} </Item> <Item> 定价:&nbsp;{book.price} </Item> <Item> 装帧:&nbsp;{book.binding} </Item> <Item> ISBN:&nbsp;{book.isbn13} </Item> </List> </div> </Content> </Item> <Item> <Content>内容简介 · · · · · ·<br/>{book.summary}</Content> </Item> <Item> <Content>作者简介 · · · · · ·<br/>{book.author_intro}</Content> </Item> <Item> <Content>目录 · · · · · ·<br/>{book.catalog}</Content> </Item> </Items> </div> ); } }); export default BookDetail
server/sonar-web/src/main/js/apps/projects-admin/main.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import debounce from 'lodash/debounce'; import uniq from 'lodash/uniq'; import without from 'lodash/without'; import Header from './header'; import Search from './search'; import Projects from './projects'; import { PAGE_SIZE, TYPE } from './constants'; import { getComponents, getProvisioned, getGhosts, deleteComponents } from '../../api/components'; import ListFooter from '../../components/controls/ListFooter'; export default React.createClass({ propTypes: { hasProvisionPermission: React.PropTypes.bool.isRequired }, getInitialState () { return { ready: false, projects: [], total: 0, page: 1, query: '', qualifiers: 'TRK', type: TYPE.ALL, selection: [] }; }, componentWillMount () { this.requestProjects = debounce(this.requestProjects, 250); }, componentDidMount () { this.requestProjects(); }, getFilters () { const filters = { ps: PAGE_SIZE }; if (this.state.page !== 1) { filters.p = this.state.page; } if (this.state.query) { filters.q = this.state.query; } return filters; }, requestProjects () { switch (this.state.type) { case TYPE.ALL: this.requestAllProjects(); break; case TYPE.PROVISIONED: this.requestProvisioned(); break; case TYPE.GHOSTS: this.requestGhosts(); break; default: // should never happen } }, requestGhosts () { const data = this.getFilters(); getGhosts(data).then(r => { let projects = r.projects.map(project => ({ ...project, id: project.uuid, qualifier: 'TRK' })); if (this.state.page > 1) { projects = [].concat(this.state.projects, projects); } this.setState({ ready: true, projects, total: r.total }); }); }, requestProvisioned () { const data = this.getFilters(); getProvisioned(data).then(r => { let projects = r.projects.map(project => ({ ...project, id: project.uuid, qualifier: 'TRK' })); if (this.state.page > 1) { projects = [].concat(this.state.projects, projects); } this.setState({ ready: true, projects, total: r.total }); }); }, requestAllProjects () { const data = this.getFilters(); data.qualifiers = this.state.qualifiers; getComponents(data).then(r => { let projects = r.components; if (this.state.page > 1) { projects = [].concat(this.state.projects, projects); } this.setState({ ready: true, projects, total: r.paging.total }); }); }, loadMore () { this.setState({ ready: false, page: this.state.page + 1 }, this.requestProjects); }, onSearch (query) { this.setState({ ready: false, page: 1, query, selection: [] }, this.requestProjects); }, onTypeChanged (newType) { this.setState({ ready: false, page: 1, query: '', type: newType, qualifiers: 'TRK', selection: [] }, this.requestProjects); }, onQualifierChanged (newQualifier) { this.setState({ ready: false, page: 1, query: '', type: TYPE.ALL, qualifiers: newQualifier, selection: [] }, this.requestProjects); }, onProjectSelected (project) { const newSelection = uniq([].concat(this.state.selection, project.id)); this.setState({ selection: newSelection }); }, onProjectDeselected (project) { const newSelection = without(this.state.selection, project.id); this.setState({ selection: newSelection }); }, onAllSelected () { const newSelection = this.state.projects.map(project => project.id); this.setState({ selection: newSelection }); }, onAllDeselected () { this.setState({ selection: [] }); }, deleteProjects () { this.setState({ ready: false }); const ids = this.state.selection.join(','); deleteComponents({ ids }).then(() => { this.setState({ page: 1, selection: [] }, this.requestProjects); }); }, render () { return ( <div className="page page-limited"> <Header hasProvisionPermission={this.props.hasProvisionPermission} selection={this.state.selection} total={this.state.total} query={this.state.query} qualifier={this.state.qualifiers} refresh={this.requestProjects}/> <Search {...this.props} {...this.state} onSearch={this.onSearch} onTypeChanged={this.onTypeChanged} onQualifierChanged={this.onQualifierChanged} onAllSelected={this.onAllSelected} onAllDeselected={this.onAllDeselected} deleteProjects={this.deleteProjects}/> <Projects ready={this.state.ready} projects={this.state.projects} refresh={this.requestProjects} selection={this.state.selection} onProjectSelected={this.onProjectSelected} onProjectDeselected={this.onProjectDeselected}/> <ListFooter ready={this.state.ready} count={this.state.projects.length} total={this.state.total} loadMore={this.loadMore}/> </div> ); } });
examples/huge-apps/routes/Calendar/components/Calendar.js
nhunzaker/react-router
import React from 'react' class Calendar extends React.Component { render() { const events = [ { id: 0, title: 'essay due' } ] return ( <div> <h2>Calendar</h2> <ul> {events.map(event => ( <li key={event.id}>{event.title}</li> ))} </ul> </div> ) } } export default Calendar
src/components/actionIssueList/actionIssueRow.js
SwimmyApp/project-swimmy-mockup
import React from 'react'; import {observer} from 'mobx-react'; import DevTool from 'mobx-react-devtools'; @observer export default class ActionIssueRow extends React.Component { render() { const { item } = this.props; return ( <li>{ item.getName() }</li> ); } }
src/components/controls/stateful/TapAnimator.js
mm-taigarevolution/tas_web_app
import React from 'react'; import PropTypes from 'prop-types'; import {Motion, spring} from 'react-motion'; const WithTapAnimated = (Child, callback) => { return class TapAnimator extends React.Component { constructor(props) { super(props); this.state = { isTapped: false }; this.onMouseDown = this.onMouseDown.bind(this); this.onMouseUp = this.onMouseUp.bind(this); } onMouseDown(e) { this.setState({isTapped: true}); } onMouseUp(e) { this.setState({isTapped: false}); if(callback) { // add small delay for better UX setTimeout(() => { callback(); }, 250); } } render() { let isTapped = this.state.isTapped; return ( <Motion defaultStyle={{ scale: 1}} style={{ scale: spring(isTapped ? 0.97 : 1)}}> {style => ( <div style={{ transform: `scale(${style.scale})`}} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp}> <Child {...this.props}/> </div> )} </Motion> ); } } } WithTapAnimated.propTypes = { Child: PropTypes.object.isRequired, callback: PropTypes.object.isRequired }; export default WithTapAnimated;
app/shared/resource-list/ResourceList.js
fastmonkeys/respa-ui
import PropTypes from 'prop-types'; import React from 'react'; import ResourceCard from '../resource-card/ResourceCard'; function ResourceList({ date, emptyMessage, location, resourceIds, history, }) { function renderResourceListItem(resourceId) { return ( <ResourceCard date={date} history={history} key={resourceId} location={location} resourceId={resourceId} /> ); } if (!resourceIds.length) { return emptyMessage ? <p>{emptyMessage}</p> : <div />; } return <div className="resource-list">{resourceIds.map(renderResourceListItem)}</div>; } ResourceList.propTypes = { date: PropTypes.string.isRequired, history: PropTypes.object.isRequired, emptyMessage: PropTypes.string, location: PropTypes.object.isRequired, resourceIds: PropTypes.array.isRequired, }; export default ResourceList;
app/components/CorporatePartnershipsSites/components/HeavyLightUsersStackedBar/index.js
tblazina/analytics_project
import React, { Component } from 'react'; import * as d3 from 'd3'; import _ from 'lodash' import styles from './styles.css'; // import Axis from './Axis'; // import Legend from './Legend.jsx' class Bars extends Component{ render(){ let translate = `translate(${this.props.x}, ${this.props.y})` return( <g transform={translate} className='bar'> <rect width={this.props.width} height={this.props.height} stroke='black' transform="translate(0,1)"> </rect> </g> ) } } export default class HeavyLightUsersStackedBarPlot extends Component{ constructor(props){ super(); // Scales for plot this.xScale = d3.scaleBand() this.yScale = d3.scaleLinear() this.color = d3.scaleOrdinal(d3.schemeCategory10) this.stack = d3.stack() // Update_d3 method which is called with original props this.update_d3(props) } // This will make sure the plot updates when it recieves new properties from // parent (Chart) componentWillReceiveProps(newProps){ this.update_d3(newProps); } update_d3(props) { // Give xScale the domain and range for our data this.xScale .range([0, props.chartWidth/1.25], 0.1) .domain(props.data.map(d => { return d[props.xName];})) ; //Give yScale the domain and range for our data this.yScale .range([props.chartHeight/1.5, 0]) .domain([0, d3.max(props.data, d => { return d[props.yName]; })]) ; } // This takes each of the groups defined by getColors() sets some properties which is // passed the <Bars /> component makeBar(groups){ let props = { x: this.xScale(groups.data[this.props.xName]), y: this.yScale(groups[1]), height: this.yScale(groups[0]) - this.yScale(groups[1]), width: 50 + 'px', key: ("histogram-bar-"+ Math.random()), } return( <Bars {...props}/> ) } // this defines groups from stacked data getColor(groups){ let props = { fill: this.color(groups.key), key: groups.key, } let number = (groups[0][1] - groups[0][0]) let label=(groups.key.split('Users')[0] + '-' + number) return( <g {...props}> {groups.map(this.makeBar.bind(this))} <text x={this.yScale(groups[0][1]) + 10} y={-5} fontSize={10} fill='black' transform='rotate(90)'> {label} </text> </g>) } render() { let translate = `translate(${this.props.margins.left}, ${this.props.margins.top * 1.5})rotate(-90)`, datastack = this.stack.keys(this.props.stacks), groups = datastack(this.props.data) return ( <g className="barplot" transform={translate}> {/* <Legend {...this.props} groups={groups} color={this.color}/> */} <g className='bars'> {groups.map(this.getColor.bind(this))} </g> {/* <Axis {...this.props} yscale={this.yScale} xscale={this.xScale}/> */} </g> ); } }
src/components/field-container.js
zapier/formatic
import React from 'react'; import fieldMixin from '@/src/mixins/field'; // A better way to add new field types vs the old mixins approach. This // component abstracts away our ugly old mixins into a component with a render // callback. That way, we can eventually deprecate the mixins and do a much // grander refactor. class FieldContainer extends React.Component { onChangeValue = fieldMixin.onChangeValue.bind(this); onBubbleValue = fieldMixin.onBubbleValue.bind(this); onStartAction = fieldMixin.onStartAction.bind(this); onFocusAction = fieldMixin.onFocusAction.bind(this); onBlurAction = fieldMixin.onBlurAction.bind(this); onBubbleAction = fieldMixin.onBubbleAction.bind(this); isReadOnly = fieldMixin.isReadOnly.bind(this); constructor() { super(); this.methods = { onChangeValue: this.onChangeValue, onBubbleValue: this.onBubbleValue, onStartAction: this.onStartAction, onFocus: this.onFocusAction, onBlur: this.onBlurAction, onBubbleAction: this.onBubbleAction, isReadOnly: this.onReadOnly, }; } render() { return this.props.children({ ...this.methods, ...this.props, }); } } export default FieldContainer;
src/index.js
PickaxeCMS/pickaxecms
import React from 'react'; import ReactDOM from 'react-dom'; // import { BrowserRouter as Router } from 'react-router-dom'; import {Routes} from './Routes'; import './index.css'; require('dotenv').config(); ReactDOM.render( <div> <Routes /> </div> , document.getElementById('root') );
react-ui/src/containers/Intro.js
MaGuangChen/resume-maguangchen
import React from 'react'; const Intro = () => { const paperPlane = { position: 'relative', left: '0.2rem', } return ( <div> <header className="front"> <div className="front_logo"> <h1>Hi, my name is Paul Ma</h1> <p>你好,我叫馬廣辰,我正在尋找f2e的工作</p> <p>此履歷專案使用以下技術:<br/> react、router、redux、graphQL、webpack、express、mongoose</p> <br/> <p>電子信箱: kwn791122@gmail.com</p> <p>手機: 0915791122</p> <br/> <a href="#to-contact" className="main-button">與我聯絡<i style={paperPlane} className="fa fa-paper-plane-o" aria-hidden="true"></i></a> <a href="#to-about" className="sub-button">或是繼續看履歷</a> <div className="scroll-down"><i className="fa fa-angle-down" aria-hidden="true"></i></div> </div> </header> </div> ) } export default Intro;
node_modules/react-router-dom/es/Link.js
charmainetham/charmainetham.github.io
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 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 React from 'react'; import PropTypes from 'prop-types'; import invariant from 'invariant'; var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); }; /** * The public API for rendering a history-aware <a>. */ var Link = function (_React$Component) { _inherits(Link, _React$Component); function Link() { var _temp, _this, _ret; _classCallCheck(this, Link); 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.handleClick = function (event) { if (_this.props.onClick) _this.props.onClick(event); if (!event.defaultPrevented && // onClick prevented default event.button === 0 && // ignore right clicks !_this.props.target && // let browser handle "target=_blank" etc. !isModifiedEvent(event) // ignore clicks with modifier keys ) { event.preventDefault(); var history = _this.context.router.history; var _this$props = _this.props, replace = _this$props.replace, to = _this$props.to; if (replace) { history.replace(to); } else { history.push(to); } } }, _temp), _possibleConstructorReturn(_this, _ret); } Link.prototype.render = function render() { var _props = this.props, replace = _props.replace, to = _props.to, innerRef = _props.innerRef, props = _objectWithoutProperties(_props, ['replace', 'to', 'innerRef']); // eslint-disable-line no-unused-vars invariant(this.context.router, 'You should not use <Link> outside a <Router>'); var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to); return React.createElement('a', _extends({}, props, { onClick: this.handleClick, href: href, ref: innerRef })); }; return Link; }(React.Component); Link.propTypes = { onClick: PropTypes.func, target: PropTypes.string, replace: PropTypes.bool, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired, innerRef: PropTypes.oneOfType([PropTypes.string, PropTypes.func]) }; Link.defaultProps = { replace: false }; Link.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired, createHref: PropTypes.func.isRequired }).isRequired }).isRequired }; export default Link;
src/routes.js
luanau/react-slingshot-pdps
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/HomePage'; import FuelSavingsPage from './containers/FuelSavingsPage'; // eslint-disable-line import/no-named-as-default import PdpsPage from './containers/PdpsPage.js'; // eslint-disable-line import/no-named-as-default import AboutPage from './components/AboutPage.js'; import NotFoundPage from './components/NotFoundPage.js'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage}/> <Route path="fuel-savings" component={FuelSavingsPage}/> <Route path="pdps" component={PdpsPage}/> <Route path="about" component={AboutPage}/> <Route path="*" component={NotFoundPage}/> </Route> );
assets/javascripts/kitten/components/navigation/floating-menu/stories.js
KissKissBankBank/kitten
import React from 'react' import { FloatingMenu } from './index' import { DocsPage } from 'storybook/docs-page' export default { title: 'Navigation/FloatingMenu', component: FloatingMenu, parameters: { docs: { page: () => ( <DocsPage filepath={__filename} importString="FloatingMenu" /> ), }, }, decorators: [ story => ( <div className="story-Container story-Grid story-Grid">{story()}</div> ), ], } export const Default = () => ( <FloatingMenu> <FloatingMenu.Item isActive href="#"> Mon profil </FloatingMenu.Item> <FloatingMenu.Item href="#">Vérification d’identité</FloatingMenu.Item> <FloatingMenu.Item href="#">Mes contributions</FloatingMenu.Item> <FloatingMenu.Item href="#">Mes projets</FloatingMenu.Item> <FloatingMenu.Item href="https://www.kisskissbankbank.com"> Mes favoris </FloatingMenu.Item> </FloatingMenu> )
src/svg-icons/navigation/arrow-back.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowBack = (props) => ( <SvgIcon {...props}> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/> </SvgIcon> ); NavigationArrowBack = pure(NavigationArrowBack); NavigationArrowBack.displayName = 'NavigationArrowBack'; NavigationArrowBack.muiName = 'SvgIcon'; export default NavigationArrowBack;
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
Jeremy-Meng/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class GroupProfileMembers extends React.Component { static propTypes = { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }; constructor(props) { super(props); } onClick(id) { DialogActionCreators.selectDialogPeerUser(id); } onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); } render() { const groupId = this.props.groupId; const members = this.props.members; const myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="group_profile__members__list__item" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} title={member.peerInfo.title}/> </a> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> {member.peerInfo.title} </a> {controls} </li> ); }, this); return ( <ul className="group_profile__members__list"> {membersList} </ul> ); } } export default GroupProfileMembers;
examples/CardSimple.js
react-materialize/react-materialize
import React from 'react'; import Card from '../src/Card'; import Col from '../src/Col'; export default <Col m={6} s={12}> <Card className='blue-grey darken-1' textClassName='white-text' title='Card title' actions={[<a href='#'>This is a link</a>]}> I am a very simple card. </Card> </Col>;
src/icons/SocialFoursquareOutline.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class SocialFoursquareOutline extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M398.484,164.452l-27.399,137.185C372.848,294.486,386.545,224.793,398.484,164.452z"></path> <path d="M376.764,32c0,0-205.353,0-238.223,0C105.666,32,96,56.798,96,72.414c0,15.627,0,379.64,0,379.64 c0,17.591,9.425,24.117,14.718,26.267c5.299,2.155,19.916,3.971,28.673-6.168c0,0,112.469-131.09,114.4-133.027 c2.921-2.931,2.921-3.125,5.844-3.125c5.843,0,49.192,0,72.766,0c30.575,0,35.49-21.676,38.684-34.559l27.399-137.087 c6.074-30.702,11.693-58.938,15.053-75.325C421.143,51.944,411.744,32,376.764,32z M376.426,96c0,0-31.575,156.209-36.034,176.834 C335,297.771,332.75,304,307,304c-17.605,0-62.375,0-62.375,0c-2.747,0-3.868-0.147-6.049,2.041 c-1.443,1.447-78.168,89.562-78.168,89.562c-19.034,23.396-26.909,31.795-29.033,31.795s-3.375,0-3.375-38.408V91.708 C128,67.034,128.3,64,157.198,64C181.748,64,352,64,352,64C382,64,382.834,64.833,376.426,96z"></path> <path d="M398.484,164.452l15.053-75.374C410.178,105.466,404.559,133.75,398.484,164.452z"></path> <path d="M328.573,96c-5.571,0-157.995,0-157.995,0C164.091,96,160,101.594,160,106.586v231.255c0,0.67,0.402,0.975,0.935,0.36 c0,0,48.202-55.725,54.056-63.021c5.848-7.289,8.491-8.182,17.233-8.182c0,0,56.695,0,62.212,0c6.549,0,10.24-5.75,10.913-8.982 c0.671-3.228,10.536-48.213,11.732-54.119c1.191-5.897-4.214-11.898-9.722-11.898c-5.5,0-64.805,0-64.805,0 c-7.803,0-7.554-5.653-7.554-13.476v-5.512c0-7.815-0.282-13.012,7.516-13.012c0,0,70.403,0,75.313,0 c4.911,0,10.208-4.442,11.102-8.662l8.468-44.042C338.739,100.823,333.828,96,328.573,96z"></path> </g> </g>; } return <IconBase> <g> <path d="M398.484,164.452l-27.399,137.185C372.848,294.486,386.545,224.793,398.484,164.452z"></path> <path d="M376.764,32c0,0-205.353,0-238.223,0C105.666,32,96,56.798,96,72.414c0,15.627,0,379.64,0,379.64 c0,17.591,9.425,24.117,14.718,26.267c5.299,2.155,19.916,3.971,28.673-6.168c0,0,112.469-131.09,114.4-133.027 c2.921-2.931,2.921-3.125,5.844-3.125c5.843,0,49.192,0,72.766,0c30.575,0,35.49-21.676,38.684-34.559l27.399-137.087 c6.074-30.702,11.693-58.938,15.053-75.325C421.143,51.944,411.744,32,376.764,32z M376.426,96c0,0-31.575,156.209-36.034,176.834 C335,297.771,332.75,304,307,304c-17.605,0-62.375,0-62.375,0c-2.747,0-3.868-0.147-6.049,2.041 c-1.443,1.447-78.168,89.562-78.168,89.562c-19.034,23.396-26.909,31.795-29.033,31.795s-3.375,0-3.375-38.408V91.708 C128,67.034,128.3,64,157.198,64C181.748,64,352,64,352,64C382,64,382.834,64.833,376.426,96z"></path> <path d="M398.484,164.452l15.053-75.374C410.178,105.466,404.559,133.75,398.484,164.452z"></path> <path d="M328.573,96c-5.571,0-157.995,0-157.995,0C164.091,96,160,101.594,160,106.586v231.255c0,0.67,0.402,0.975,0.935,0.36 c0,0,48.202-55.725,54.056-63.021c5.848-7.289,8.491-8.182,17.233-8.182c0,0,56.695,0,62.212,0c6.549,0,10.24-5.75,10.913-8.982 c0.671-3.228,10.536-48.213,11.732-54.119c1.191-5.897-4.214-11.898-9.722-11.898c-5.5,0-64.805,0-64.805,0 c-7.803,0-7.554-5.653-7.554-13.476v-5.512c0-7.815-0.282-13.012,7.516-13.012c0,0,70.403,0,75.313,0 c4.911,0,10.208-4.442,11.102-8.662l8.468-44.042C338.739,100.823,333.828,96,328.573,96z"></path> </g> </IconBase>; } };SocialFoursquareOutline.defaultProps = {bare: false}
pootle/static/js/admin/app.js
Finntack/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import 'imports?Backbone=>require("backbone")!backbone-move'; import React from 'react'; import ReactDOM from 'react-dom'; import AdminController from './components/AdminController'; import User from './components/User'; import Language from './components/Language'; import Project from './components/Project'; import AdminRouter from './AdminRouter'; window.PTL = window.PTL || {}; const itemTypes = { user: User, language: Language, project: Project, }; PTL.admin = { init(opts) { if (!itemTypes.hasOwnProperty(opts.itemType)) { throw new Error('Invalid `itemType`.'); } ReactDOM.render( <AdminController adminModule={itemTypes[opts.itemType]} appRoot={opts.appRoot} formChoices={opts.formChoices || {}} router={new AdminRouter()} />, document.querySelector('.js-admin-app') ); }, };
app/main.js
mario2904/ICOM5016-Project
import React from 'react'; import { render } from 'react-dom'; import App from './App.js'; render(<App />, document.getElementById('app'));
src/client/components/AboutAsync/About.js
EdgeJay/web-starterkit
import React from 'react'; import PageHeader from '../PageHeader'; const About = () => ( <div> <PageHeader>About This Repo</PageHeader> <p>{`I created this repository to serve as a starter kit to assist me in kickstarting new web app projects without the need of building from scratch or depend on various plugins/projects that use CLI commands. Feel free to post issues or raise PRs if you found any bugs or areas that require improvement.`}</p> <h2>Pre-requisites</h2> <ul> <li>Node.js v8.9.3 and above must be installed.</li> <li> Recommended to use{' '} <a href="https://yarnpkg.com" rel="noopener noreferrer" target="_blank"> yarn </a>{' '} as package manager </li> </ul> <h2>Getting Started</h2> <ol> <li> Copy dotenv file from <code>/deploy/local</code> folder into project root folder and rename to <code>.env</code> </li> <li> <code>yarn install</code> or <code>npm install</code> </li> <li> <code>npm run dev:server</code> </li> <li> Open{' '} <a href="http://localhost:6150" rel="noopener noreferrer" target="_blank"> http://localhost:6150 </a>{' '} in web browser </li> </ol> </div> ); export default About;
modules/RouteContext.js
ArmendGashi/react-router
import React from 'react' const { object } = React.PropTypes /** * The RouteContext mixin provides a convenient way for route * components to set the route in context. This is needed for * routes that render elements that want to use the Lifecycle * mixin to prevent transitions. */ const RouteContext = { propTypes: { route: object.isRequired }, childContextTypes: { route: object.isRequired }, getChildContext() { return { route: this.props.route } } } export default RouteContext
packages/cf-component-pagination/example/basic/component.js
manatarms/cf-ui
import React from 'react'; import { Pagination, PaginationItem } from 'cf-component-pagination'; import Icon from 'cf-component-icon'; class PaginationComponent extends React.Component { constructor(props) { super(props); this.state = { pages: 4, active: 1 }; } handleClickItem(page) { if (page >= 1 && page <= this.state.pages) { this.setState({ active: page }); } } handleClickPrev() { if (this.state.active > 1) { this.handleClickItem(this.state.active - 1); } } handleClickNext() { if (this.state.active < this.state.pages) { this.handleClickItem(this.state.active + 1); } } render() { const items = []; for (let i = 1; i <= this.state.pages; i++) { items.push( <PaginationItem key={i} type="number" label={'Page ' + i} active={this.state.active === i} onClick={this.handleClickItem.bind(this, i)} > {i} </PaginationItem> ); } return ( <Pagination> <PaginationItem type="prev" label="Previous Page" disabled={this.state.active === 1} onClick={this.handleClickPrev.bind(this)} > <Icon type="caret-left" label={false} /> </PaginationItem> {items} <PaginationItem type="next" label="Next Page" disabled={this.state.active === this.state.pages} onClick={this.handleClickNext} > <Icon type="caret-right" label={false} /> </PaginationItem> </Pagination> ); } } export default PaginationComponent;
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
aimanaiman/supernomadfriendsquad
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
examples/simple/index.js
ganarajpr/react-node-tree
import React from 'react'; import App from './components/App'; React.render( <App />, document.getElementById('root') );
docs/src/app/components/pages/components/Drawer/Page.js
pomerantsev/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import drawerReadmeText from './README'; import DrawerSimpleExample from './ExampleSimple'; import drawerSimpleExampleCode from '!raw!./ExampleSimple'; import DrawerUndockedExample from './ExampleUndocked'; import drawerUndockedExampleCode from '!raw!./ExampleUndocked'; import DrawerOpenSecondaryExample from './ExampleOpenSecondary'; import drawerOpenSecondaryExampleCode from '!raw!./ExampleOpenSecondary'; import drawerCode from '!raw!material-ui/Drawer/Drawer'; const descriptions = { simple: 'A simple controlled `Drawer`. The Drawer is `docked` by default, ' + 'remaining open unless closed through the `open` prop.', undocked: 'An undocked controlled `Drawer` with custom width. ' + 'The Drawer can be cancelled by clicking the overlay or pressing the Esc key. ' + 'It closes when an item is selected, handled by controlling the `open` prop.', right: 'The `openSecondary` prop allows the Drawer to open on the opposite side.', }; const DrawerPage = () => ( <div> <Title render={(previousTitle) => `Drawer - ${previousTitle}`} /> <MarkdownElement text={drawerReadmeText} /> <CodeExample title="Docked example" description={descriptions.simple} code={drawerSimpleExampleCode} > <DrawerSimpleExample /> </CodeExample> <CodeExample title="Undocked example" description={descriptions.undocked} code={drawerUndockedExampleCode} > <DrawerUndockedExample /> </CodeExample> <CodeExample title="Open secondary example" description={descriptions.right} code={drawerOpenSecondaryExampleCode} > <DrawerOpenSecondaryExample /> </CodeExample> <PropTypeDescription code={drawerCode} /> </div> ); export default DrawerPage;
app/javascript/mastodon/features/ui/components/column_header.js
yi0713/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <Icon id={icon} fixedWidth className='column-header__icon' />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/svg-icons/image/grid-off.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGridOff = (props) => ( <SvgIcon {...props}> <path d="M8 4v1.45l2 2V4h4v4h-3.45l2 2H14v1.45l2 2V10h4v4h-3.45l2 2H20v1.45l2 2V4c0-1.1-.9-2-2-2H4.55l2 2H8zm8 0h4v4h-4V4zM1.27 1.27L0 2.55l2 2V20c0 1.1.9 2 2 2h15.46l2 2 1.27-1.27L1.27 1.27zM10 12.55L11.45 14H10v-1.45zm-6-6L5.45 8H4V6.55zM8 20H4v-4h4v4zm0-6H4v-4h3.45l.55.55V14zm6 6h-4v-4h3.45l.55.54V20zm2 0v-1.46L17.46 20H16z"/> </SvgIcon> ); ImageGridOff = pure(ImageGridOff); ImageGridOff.displayName = 'ImageGridOff'; ImageGridOff.muiName = 'SvgIcon'; export default ImageGridOff;
src/screens/authorized/home/contact/Conversation.js
anhtuank7c/simple-chat
import React, { Component } from 'react'; import { View, Text, ListView, Image, ActivityIndicator } from 'react-native'; import { connect } from 'react-redux'; import { GiftedChat } from 'react-native-gifted-chat'; import { findRoomByUser, sendMessage } from '../../../../actions'; class Conversation extends Component { static navigationOptions = { title: ({ state }) => state.params.friend.displayName, tabBar: { visible: false } } componentWillMount() { const { me } = this.props; const { friend } = this.props.navigation.state.params; this.props.findRoomByUser(me, friend); } onSend = (messages = []) => { console.log('onSend', messages); const { me, roomKey } = this.props; const { friend } = this.props.navigation.state.params; this.props.sendMessage(me, friend, messages[0].text, roomKey); } render() { if (this.props.loading) { return ( <View style={styles.containerIndicator}> <ActivityIndicator size="large" color="purple" animating /> </View> ); } return ( <View style={styles.container}> <GiftedChat messages={this.props.messages} user={{ _id: this.props.me.uid }} onSend={this.onSend.bind(this)} /> </View> ); } } const styles = { containerIndicator: { flex: 1, justifyContent: 'center', alignItems: 'center' }, container: { flex: 1 } }; export default connect(state => ({ me: state.authentication.user, loading: state.chat.loading, messages: state.chat.messages, roomKey: state.chat.roomKey }), { findRoomByUser, sendMessage })(Conversation);
src/index.js
ShaoYiwei/React-gallery
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/components/Content.js
Kamyhin/organizer
import React from 'react'; import { Button } from "@blueprintjs/core"; import { getNewID } from '../utils' const style = { 'width': { width: '30%' }, 'padding': { marginLeft: '10px' } }; const Content = ({ events, addEvent, clearEventsList, readAll, popoverOpen }) => { let EventTitle = ''; let isUnread = events.filter((obj) => obj.get('unread') === true).size; const onSubmit = () => { let value = EventTitle.value; if (value) { let id = getNewID(events); addEvent(id, value); EventTitle.value = ""; } else { EventTitle.focus() } }; return ( <div className="pt-card pt-elevation-0"> <p> <input className="pt-input" style={style.width} type="text" placeholder="Введите название события..." dir="auto" ref={(input) => EventTitle = input}/> <Button onClick={onSubmit} style={style.padding} text='Отправить'/> </p> <p> <Button onClick={readAll} style={style.width} text='Пометить все события прочитанными'/> </p> <p> <Button onClick={clearEventsList} style={style.width} text='Удалить все события'/> </p> <p> <Button onClick={ isUnread ? popoverOpen : false } style={style.width} text='Скрыть/показать попап нотификаций'/> </p> </div> ) }; export default Content;
src/svg-icons/hardware/tv.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareTv = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/> </SvgIcon> ); HardwareTv = pure(HardwareTv); HardwareTv.displayName = 'HardwareTv'; export default HardwareTv;
lib/Components/HourlyWeather.js
Kalikoze/weatherly
import React from 'react'; export const HourlyWeather = props => { const weatherImage = props.weatherData.icon; const image = `./lib/Assets/weather-condition-icons/${weatherImage}.svg`; const temperature = props.weatherData.temp.english; const hour = props.weatherData.FCTTIME.civil; return ( <div className="hourly-card"> <p className="hour"> {hour} </p> <img src={image} className="hourly-image" /> <p className="hourly-temperature"> {temperature}° </p> </div> ); };
src/components/PostList.js
chee/blogs
import React from 'react' import {Link} from 'react-router' import Time from './Time' const PostList = ({posts, unpublishedShown}) => ( <div> {posts.map((post, index) => { const { slug, title, date, published } = post if (!published && !unpublishedShown) return null return ( <div key={index}> <Link to={`/posts/${slug}`}> <span> {title} </span> {' '} <Time date={date} /> </Link> </div> ) }) } </div> ) export default PostList
src/index.js
victorditadi/IQApp
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoLista from './components/video_list'; import VideoDetail from './components/video_detail'; const API_KEY = 'AIzaSyBO-z8CQ8jz7I92JxAI-mwyIljz-Y_P7Zs'; class App extends Component { constructor(props){ super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('hermes e renato'); } videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { return ( <div className="row" style={{marginTop: 20}}> <div className="row"> <div className="col s12 m12 l12"> <SearchBar onSearchTermChange={term => this.videoSearch(term)} /> </div> </div> <div className="row"> <div className="col s12 m6 l6"> <VideoDetail video={this.state.selectedVideo}/> </div> <div className="col s12 m6 l6"> <div className="col s12 m12 l11 offset-l1 center-align"> <span style={{fontSize: 28, opacity: 0.5}}>Videos Relacionados</span> </div> <VideoLista onVideoSelect ={(selectedVideo) => this.setState({selectedVideo})} videos={this.state.videos}/> </div> </div> </div> ); } } ReactDOM.render(<App/>, document.querySelector('.container'));
src/app.js
asommer70/thehoick-notes-server
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link, browserHistory } from 'react-router' import cookie from 'react-cookie'; import Notes from './components/notes'; import Note from './components/note'; import NoteForm from './components/note_form'; import Login from './components/login'; import Signup from './components/signup'; import Logout from './components/logout'; const Base = React.createClass({ render() { return ( <div className="columns"> <div className="column is-2"> <h1 className="title">The Hoick Notes</h1> <p> {cookie.load('username') ? `Welcome ${cookie.load('username')}`: ''} </p> </div> <div className="column is-8"> <Link to="/notes" className="button is-primary">Notes</Link> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <Link to="/notes/new" className="button">New Note</Link> <Link to="/logout" className="button is-info is-outlined is-pulled-right">Log Out</Link> <hr/> {this.props.children} </div> </div> ) } }) class App extends Component { // static contextTypes = { // router: React.PropTypes.object.isRequired // } constructor() { super(); } render() { return ( <Router history={browserHistory}> <Route path="/" component={Base}> <Route path="/notes" component={Notes}/> <Route path="/notes/new" component={NoteForm}/> <Route path="/notes/:id" component={Note}/> <Route path="/notes/:id/edit" component={NoteForm}/> <Route path="/login" component={Login}/> <Route path="/signup" component={Signup}/> <Route path="/logout" component={Logout}/> <Route path="*" component={Notes}/> </Route> </Router> ) } } ReactDOM.render( <App />, document.getElementById('main') );
packages/react/src/components/forms/FeedbackForm/index.js
massgov/mayflower
/* eslint jsx-a11y/label-has-associated-control: 0 */ /** * FeedbackForm module. * @module @massds/mayflower-react/FeedbackForm */ import React from 'react'; import PropTypes from 'prop-types'; import CharacterCounter from 'react-character-counter'; import classNames from 'classnames'; import is from 'is'; import Paragraph from 'MayflowerReactText/Paragraph'; // These components exist to make it clear in FeedbackForm's render what's going on. const RefererField = (props) => <input type="hidden" {...props} />; const NodeIdField = (props) => <input type="hidden" {...props} />; // Required for jsonp responses to work. const JsonPField = () => <input type="hidden" name="jsonp" value={1} />; // A hidden input field that prevents FormStack from looking for a required field that wasn't filled in. const HiddenFields = (props) => { const { formId, ...rest } = props; return(<input type="hidden" name="hidden_fields" id={`hidden_fields${formId}`} {...rest} />); }; HiddenFields.propTypes = { /** The form id that the hidden input will be rendered within. */ formId: PropTypes.number }; export default class FeedbackForm extends React.Component { static propTypes = { /** A ref object as created by React.createRef(). Will be applied to the form element. */ formRef: PropTypes.oneOfType([ PropTypes.func, PropTypes.shape({ current: PropTypes.any }) ]), /** A function whose return value is displayed after a successful form submission. */ successMessage: PropTypes.func.isRequired, /** The field id number for the yes textarea. */ yesFeedbackId: PropTypes.number, /** The field id number for the no textarea. */ noFeedbackId: PropTypes.number, /** The field id number for the referer. */ refererId: PropTypes.number, /** The id number for the form from FormStack. */ formId: PropTypes.number, /** The field id number for the yes/no radio buttons. */ radioId: PropTypes.number, /** A drupal node id number for the referer. */ nodeId: PropTypes.number, /** A function whose return value is rendered under the yes textarea. */ yesDisclaimer: PropTypes.func, /** A function whose return value is rendered under the no textarea. */ noDisclaimer: PropTypes.func } static defaultProps = { formId: 2521317, radioId: 47054416, yesFeedbackId: 52940022, noFeedbackId: 47054414, refererId: 47056299 }; state = { yesText: '', noText: '', errorMessage: <Paragraph className="error">Please go back and fill in any required fields (marked with an *)</Paragraph>, feedbackChoice: null, hasError: [], success: false, formSubmitted: false }; yesRadio = React.createRef(); yesTextArea = React.createRef(); noRadio = React.createRef(); noTextArea = React.createRef(); submitButton = React.createRef(); componentDidMount() { if (window) { // We don't have the FormStack class available, but we can fake like we do: window[`form${this.props.formId}`] = { onSubmitError: (err) => { if (err) { this.setState((state, props) => { const hasError = [...state.hasError]; hasError.push(props.radioId); hasError.push(props.noFeedbackId); const errorMessage = <Paragraph className="error">{err.error}</Paragraph>; return{ hasError, errorMessage }; }); } }, onPostSubmit: () => { this.setState({ success: true }); } }; } } defaultDisclaimer = () => ( <div id="feedback-note" className="ma__disclaimer"> We use your feedback to help us improve this site but we are not able to respond directly. <strong>Please do not include personal or contact information.</strong> {' '} If you need a response, please locate the contact information elsewhere on this page or in the footer. </div> ); prefixLabel = (id) => `label${id}`; prefixField = (id) => `field${id}`; handleRadioChange = (e) => { if (e.currentTarget === this.yesRadio.current) { return{ feedbackChoice: true }; } if (e.currentTarget === this.noRadio.current) { return{ feedbackChoice: false }; } return{}; } // Handles the onChange event for the yes/no radio buttons as well as the yes/no textareas. handleChange = (e) => { let newState = {}; e.persist(); if (e.currentTarget === this.yesRadio.current || e.currentTarget === this.noRadio.current) { newState = Object.assign(newState, this.handleRadioChange(e)); } if (e.currentTarget === this.yesTextArea.current) { newState = Object.assign(newState, { yesText: e.currentTarget.value }); } if (e.currentTarget === this.noTextArea.current) { newState = Object.assign(newState, { noText: e.currentTarget.value }); } // If the form was previously submitted but the user made a new change, reset the form submitted status. if (this.state.formSubmitted && Object.keys(newState).length > 0) { newState.formSubmitted = false; newState.success = false; newState.successMessage = ''; } this.setState(newState, this.checkForErrors); } removeError = (errors, idToRemove) => errors.filter((fieldId) => !is.equal(fieldId, idToRemove)); checkForErrors = () => { let hasError = [...this.state.hasError]; const { radioId, noFeedbackId } = this.props; const { feedbackChoice, formSubmitted } = this.state; // The user has not selected yes or no. if (!hasError.includes(radioId) && feedbackChoice === null) { hasError.push(radioId); } if (hasError.includes(radioId) && !is.nil(feedbackChoice)) { hasError = this.removeError(hasError, radioId); } // The user has selected no but has not typed any feedback. if (!hasError.includes(noFeedbackId) && feedbackChoice === false && formSubmitted && is.empty(this.noTextArea.current.value)) { hasError.push(noFeedbackId); } else if (hasError.includes(noFeedbackId) && feedbackChoice === false && !is.empty(this.noTextArea.current.value)) { hasError = this.removeError(hasError, noFeedbackId); } // If the user changed choices from no to yes, remove the error for no if there was one. if (feedbackChoice === true && hasError.includes(noFeedbackId)) { hasError = this.removeError(hasError, noFeedbackId); } // Prevent calling setState too often while typing in textareas. if (!is.equal(hasError, this.state.hasError)) { this.setState({ hasError }); } return hasError; }; handleSubmit = (e) => { e.preventDefault(); // Update the component state to know that the form was just submitted, // then check the form for any errors based on this new state. this.setState({ formSubmitted: true }, () => { // checkForErrors doesn't immediately update state, so it returns what this.state.hasError is being set to. const errors = this.checkForErrors(); // If no remaining errors, submit form. // Since we have to use jsonp and this component could be used with server side rendering, ensure that window exists. if (window && is.array.empty(errors)) { import('b-jsonp').then((module) => { const jsonp = module.default; const form = document.getElementById(`fsForm${this.props.formId}`); const data = new FormData(form); const body = {}; new Map(data.entries()).forEach((value, key) => { body[key] = value; }); // This library leaves behind the script added by formstack in the head of the document. // Any errors are handled by onSubmitError and the response is handled through onPostSubmit. // jsonp requires you to pass a function for the last param though. jsonp('https://www.formstack.com/forms/index.php', body, { prefix: `form${this.props.formId}`, name: 'onPostSubmit' }, () => {}); }); } }); }; render() { const { yesFeedbackId, yesDisclaimer, noFeedbackId, noDisclaimer, refererId, formId, formRef, radioId, nodeId, successMessage } = this.props; const { hasError, success, feedbackChoice, formSubmitted, noText, yesText, errorMessage } = this.state; const yesId = this.prefixField(yesFeedbackId); const noId = this.prefixField(noFeedbackId); const formProps = { id: `fsForm${formId}`, method: 'post', className: 'formForm', onSubmit: this.handleSubmit, action: 'https://www.formstack.com/forms/index.php', encType: 'multipart/form-data' }; // Allows other components to have direct access to the form element. if (formRef) { formProps.ref = formRef; } const refererProps = { id: this.prefixField(refererId), name: this.prefixField(refererId), size: '50', value: window.location.href, className: 'fsField' }; const yesFieldSetClassNames = classNames({ 'radio-yes': true, error: (hasError.includes(yesFeedbackId)) }); const noFieldSetClassNames = classNames({ 'radio-no': true, error: (hasError.includes(noFeedbackId)) }); const noTextAreaClassNames = classNames({ 'fsField required': true, error: (hasError.includes(noFeedbackId)) }); const radiosClassNames = (hasError.includes(radioId)) ? 'error' : null; const messsageClassNames = classNames({ messages: true, hide: success === false && is.array.empty(hasError) }); const messageStyle = { fontWeight: 'bold' }; if (!is.array.empty(hasError)) { messageStyle.color = 'red'; } const characterCounterProps = { maxLength: 10000, wrapperStyle: { display: 'block', fontSize: '17px', lineHeight: '1.625rem', textAlign: 'right' }, characterCounterStyle: { position: 'relative', display: 'block', bottom: '32px', right: '5px', top: 'auto', fontSize: '1rem', fontWeight: 400, lineHeight: '1.625rem' }, overrideStyle: true }; return(success && formSubmitted) ? ( <div className="ma__feedback-form" data-mass-feedback-form> <h2 className="visually-hidden">Feedback</h2> <form noValidate {...formProps}> <fieldset> <div className={messsageClassNames} style={messageStyle}> {is.fn(successMessage) && successMessage()} </div> </fieldset> </form> </div> ) : ( <div className="ma__feedback-form" data-mass-feedback-form> <h2 className="visually-hidden">Feedback</h2> <form noValidate {...formProps}> <input type="hidden" name="form" value={formId} /> <JsonPField /> <input type="hidden" name="viewkey" value="vx39GBYJhi" /> { feedbackChoice === true && <HiddenFields formId={formId} value={noId} />} { feedbackChoice === false && <HiddenFields formId={formId} value={yesId} />} <input type="hidden" name="_submit" value="1" /> <input type="hidden" name="style_version" value="3" /> <input type="hidden" id="viewparam" name="viewparam" value="524744" /> <RefererField {...refererProps} /> <NodeIdField id="field58154059" name="field58154059" value={nodeId} /> <NodeIdField id="field57432673" name="field57432673" value={nodeId} /> <fieldset className={radiosClassNames}> <legend className="fsLabel requiredLabel fsLabelVertical"> Did you find what you were looking for on this webpage? <span> {' '} * <span className="visually-hidden">required</span> </span> </legend> <div className="ma__input-group__items ma__input-group__items--inline"> <div className="ma__input-group__item"> <span className="ma__input-radio"> <input className="fsField required" id={`${this.prefixField(radioId)}_1`} onChange={this.handleChange} ref={this.yesRadio} name={this.prefixField(radioId)} type="radio" value="Yes" /> <label className="fsOptionLabel ma__input-radio__label" htmlFor={`${this.prefixField(radioId)}_1`}>Yes</label> </span> </div> <div className="ma__input-group__item"> <span className="ma__input-radio"> <input className="fsField required" id={`${this.prefixField(radioId)}_2`} onChange={this.handleChange} ref={this.noRadio} name={this.prefixField(radioId)} type="radio" value="No" /> <label className="fsOptionLabel ma__input-radio__label" htmlFor={`${this.prefixField(radioId)}_2`}>No</label> </span> </div> </div> </fieldset> {(feedbackChoice === false) && ( <fieldset className={noFieldSetClassNames}> <label htmlFor={noId}> If &#34;No,&#34; please tell us what you were looking for: <span> {' '} * <span className="visually-hidden">required</span> </span> </label> <div className="ma__textarea__wrapper"> <CharacterCounter value={noText} {...characterCounterProps}> <textarea id={noId} ref={this.noTextArea} onChange={this.handleChange} className={noTextAreaClassNames} name={noId} aria-required="true" maxLength="10000" disabled={feedbackChoice === false ? null : 'disabled'} aria-describedby="feedback-note" /> </CharacterCounter> </div> <input type="hidden" id={yesId} name={yesId} value="" /> <span>{(is.fn(noDisclaimer)) ? noDisclaimer() : this.defaultDisclaimer()}</span> </fieldset> )} {(feedbackChoice === true) && ( <fieldset className={yesFieldSetClassNames}> <label htmlFor={yesId}>Is there anything else you would like to tell us?</label> <div className="ma__textarea__wrapper"> <CharacterCounter value={yesText} {...characterCounterProps}> <textarea ref={this.yesTextArea} onChange={this.handleChange} id={yesId} name={yesId} maxLength="10000" disabled={feedbackChoice === true ? null : 'disabled'} aria-describedby="feedback-note2" /> </CharacterCounter> </div> <input type="hidden" id={noId} name={noId} value="" /> <span>{is.fn(yesDisclaimer) ? yesDisclaimer() : this.defaultDisclaimer()}</span> </fieldset> )} <fieldset className="ma_feedback-fieldset ma__mass-feedback-form__form--submit-wrapper"> <div className={messsageClassNames} style={messageStyle}> {success === false && errorMessage} </div> <input id="submitButton2521317" ref={this.submitButton} className="submitButton ma__button ma__button--small" style={{ display: 'block' }} type="submit" value="Send Feedback" /> </fieldset> </form> </div> ); } }
src/routes/app.js
zhangjingge/sse-antd-admin
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Layout } from '../components' import { classnames, config, menu } from '../utils' import { Helmet } from 'react-helmet' import '../themes/index.less' import moment from 'moment'; import 'moment/locale/zh-cn'; moment.locale('zh-cn'); const { prefix } = config const { Header, Bread, Footer, Sider, styles } = Layout const App = ({ children, location, dispatch, app }) => { const { user, siderFold, darkTheme, isNavbar, menuPopoverVisible, navOpenKeys } = app const headerProps = { menu, user, siderFold, location, isNavbar, menuPopoverVisible, navOpenKeys, switchMenuPopover () { dispatch({ type: 'app/switchMenuPopver' }) }, logout () { dispatch({ type: 'app/logout' }) }, switchSider () { dispatch({ type: 'app/switchSider' }) }, changeOpenKeys (openKeys) { dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } }) }, } const siderProps = { menu, siderFold, darkTheme, location, navOpenKeys, changeTheme () { dispatch({ type: 'app/changeTheme' }) }, changeOpenKeys (openKeys) { localStorage.setItem(`${prefix}navOpenKeys`, JSON.stringify(openKeys)) dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } }) }, } const breadProps = { menu, } if (config.openPages && config.openPages.indexOf(location.pathname) > -1) { /*console.log('login');*/ /*判断是否是登录页面,登录页面的只加载登录信息*/ return <div>{children}</div> } /*console.log('not login');*/ /*加载出登录页面的其他页面*/ return ( <div> <Helmet> <title>ANTD ADMIN</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href={config.logoSrc} type="image/x-icon" /> {config.iconFontUrl ? <script src={config.iconFontUrl}></script> : ''} </Helmet> <div className={classnames(styles.layout, { [styles.fold]: isNavbar ? false : siderFold }, { [styles.withnavbar]: isNavbar })}> {!isNavbar ? <aside className={classnames(styles.sider, { [styles.light]: !darkTheme })}> <Sider {...siderProps} /> </aside> : ''} <div className={styles.main}> <Header {...headerProps} /> <Bread {...breadProps} location={location} /> <div className={styles.container}> <div className={styles.content}> {children} </div> </div> <Footer /> </div> </div> </div> ) } App.propTypes = { children: PropTypes.element.isRequired, location: PropTypes.object, dispatch: PropTypes.func, app: PropTypes.object, } export default connect(({ app, loading }) => ({ app, loading }))(App)
App/config/Drawer/Drawer.js
araneforseti/caretaker-app
import React from 'react'; import { DrawerItems } from 'react-navigation'; import { ThemeProvider, Drawer as MuiDrawer, Avatar } from 'react-native-material-ui'; import theme from '../theme'; import styles from './styles'; export default function Drawer( { navigation, items, screenProps } ) { const drawerItems = items.map((item) => { return { icon: screenProps.routes[item.key].navigationOptions.drawerIcon, value: screenProps.routes[item.key].navigationOptions.drawerLabel, onPress: () => navigation.navigate(item.routeName) }; }); drawerItems[navigation.state.index].active = true; const logoutItems = [{ icon: 'keyboard-arrow-left', value: 'Logout', onPress: screenProps.logout }]; return <ThemeProvider uiTheme={theme}> <MuiDrawer> <MuiDrawer.Header style={styles.header}> <MuiDrawer.Header.Account avatar={<Avatar text={screenProps.userName[0].toUpperCase()} />} footer={{ dense: true, centerElement: { primaryText: screenProps.userName, secondaryText: screenProps.userEmail, } }} /> </MuiDrawer.Header> <MuiDrawer.Section divider items={drawerItems} /> <MuiDrawer.Section items={logoutItems} /> </MuiDrawer> </ThemeProvider>; }
src/components/Workflow/WorkflowCard.js
Aloomaio/netlify-cms
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import c from 'classnames'; import { Link } from 'react-router-dom'; const WorkflowCard = ({ collectionName, title, author, authorLastChange, body, isModification, editLink, stagingURL, timestamp, onDelete, canPublish, onPublish, }) => ( <div className="nc-workflow-card"> <Link to={editLink} className="nc-workflow-link"> <div className="nc-workflow-card-collection">{collectionName}</div> <h2 className="nc-workflow-card-title">{title}</h2> <div className="nc-workflow-card-date">{timestamp} by {authorLastChange}</div> <p className="nc-workflow-card-body">{body}</p> <div> <iframe src={stagingURL} class="ifrm"></iframe> </div> </Link> <div className="nc-workflow-card-button-container"> <button className="nc-workflow-card-buttonDelete" onClick={onDelete}> {isModification ? 'Delete changes' : 'Delete new entry'} </button> <button className='nc-workflow-card-buttonPublish'> <a href={stagingURL} style={{color: '#ffffff'}} target="_blank"> Staging </a> </button> <button className={c('nc-workflow-card-buttonPublish', { 'nc-workflow-card-buttonPublishDisabled': !canPublish, })} onClick={onPublish} > {isModification ? 'Publish changes' : 'Publish new entry'} </button> </div> </div> ); export default WorkflowCard;
src/routes.js
lianwangtao/shanelian.com
import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import Ivenues from './Ivenues'; import Home from './components/Home'; const rootPath = '/'; const onRouteUpdate = function () { let docElements = document.querySelectorAll('.article'); if (docElements.length > 0 && window.location.hash === '') { docElements[0].scrollTop = 0; } }; class IvenuesSection extends React.Component { constructor(props) { super(props); this.constructor.childContextTypes = { routePrefix: React.PropTypes.string.isRequired }; } getChildContext() { return { routePrefix: rootPath }; } render() { return ( <Ivenues {...this.props} /> ); } }; const routes = ( <Router onUpdate={onRouteUpdate} history={browserHistory} > <Route path={rootPath} component={IvenuesSection}> <IndexRoute component={Home} /> </Route> </Router> ); export default routes;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
zhy32008/webCMS
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'));
examples/server/store.js
reactjs/react-router-redux
import React from 'react' import { createStore, combineReducers, compose, applyMiddleware } from 'redux' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' import { routerReducer, routerMiddleware } from 'react-router-redux' export const DevTools = createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor theme="tomorrow" preserveScrollTop={false} /> </DockMonitor> ) export function configureStore(history, initialState) { const reducer = combineReducers({ routing: routerReducer }) let devTools = [] if (typeof document !== 'undefined') { devTools = [ DevTools.instrument() ] } const store = createStore( reducer, initialState, compose( applyMiddleware( routerMiddleware(history) ), ...devTools ) ) return store }
react-graphql-webpack/src/components/withViewport.js
josedab/react-examples
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport} />; } handleResize(value) { this.setState({ viewport: value }); // eslint-disable-line react/no-set-state } }; } export default withViewport;
server/node_modules/react-router/es/StaticRouter.js
Atanasov86/Car-System
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 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 invariant from 'invariant'; import React from 'react'; import PropTypes from 'prop-types'; import { addLeadingSlash, createPath, parsePath } from 'history/PathUtils'; import Router from './Router'; var normalizeLocation = function normalizeLocation(object) { var _object$pathname = object.pathname, pathname = _object$pathname === undefined ? '/' : _object$pathname, _object$search = object.search, search = _object$search === undefined ? '' : _object$search, _object$hash = object.hash, hash = _object$hash === undefined ? '' : _object$hash; return { pathname: pathname, search: search === '?' ? '' : search, hash: hash === '#' ? '' : hash }; }; var addBasename = function addBasename(basename, location) { if (!basename) return location; return _extends({}, location, { pathname: addLeadingSlash(basename) + location.pathname }); }; var stripBasename = function stripBasename(basename, location) { if (!basename) return location; var base = addLeadingSlash(basename); if (location.pathname.indexOf(base) !== 0) return location; return _extends({}, location, { pathname: location.pathname.substr(base.length) }); }; var createLocation = function createLocation(location) { return typeof location === 'string' ? parsePath(location) : normalizeLocation(location); }; var createURL = function createURL(location) { return typeof location === 'string' ? location : createPath(location); }; var staticHandler = function staticHandler(methodName) { return function () { invariant(false, 'You cannot %s with <StaticRouter>', methodName); }; }; var noop = function noop() {}; /** * The public top-level API for a "static" <Router>, so-called because it * can't actually change the current location. Instead, it just records * location changes in a context object. Useful mainly in testing and * server-rendering scenarios. */ var StaticRouter = function (_React$Component) { _inherits(StaticRouter, _React$Component); function StaticRouter() { var _temp, _this, _ret; _classCallCheck(this, StaticRouter); 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.createHref = function (path) { return addLeadingSlash(_this.props.basename + createURL(path)); }, _this.handlePush = function (location) { var _this$props = _this.props, basename = _this$props.basename, context = _this$props.context; context.action = 'PUSH'; context.location = addBasename(basename, createLocation(location)); context.url = createURL(context.location); }, _this.handleReplace = function (location) { var _this$props2 = _this.props, basename = _this$props2.basename, context = _this$props2.context; context.action = 'REPLACE'; context.location = addBasename(basename, createLocation(location)); context.url = createURL(context.location); }, _this.handleListen = function () { return noop; }, _this.handleBlock = function () { return noop; }, _temp), _possibleConstructorReturn(_this, _ret); } StaticRouter.prototype.getChildContext = function getChildContext() { return { router: { staticContext: this.props.context } }; }; StaticRouter.prototype.render = function render() { var _props = this.props, basename = _props.basename, context = _props.context, location = _props.location, props = _objectWithoutProperties(_props, ['basename', 'context', 'location']); var history = { createHref: this.createHref, action: 'POP', location: stripBasename(basename, createLocation(location)), push: this.handlePush, replace: this.handleReplace, go: staticHandler('go'), goBack: staticHandler('goBack'), goForward: staticHandler('goForward'), listen: this.handleListen, block: this.handleBlock }; return React.createElement(Router, _extends({}, props, { history: history })); }; return StaticRouter; }(React.Component); StaticRouter.propTypes = { basename: PropTypes.string, context: PropTypes.object.isRequired, location: PropTypes.oneOfType([PropTypes.string, PropTypes.object]) }; StaticRouter.defaultProps = { basename: '', location: '/' }; StaticRouter.childContextTypes = { router: PropTypes.object.isRequired }; export default StaticRouter;
frontend/eyeballing/src/components/Footer.js
linea-it/dri
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import { Typography, CardMedia } from '@material-ui/core'; import logo from '../assets/img/linea-logo-mini.png'; const styles = () => ({ appBar: { top: 'auto', bottom: 0, }, media: { marginLeft: 5, height: 10, width: 30, }, toolbar: { alignItems: 'center', justifyContent: 'space-between', }, grow: { flexGrow: 1, }, }); function Footer(props) { const { classes } = props; return ( <React.Fragment> <AppBar position="fixed" color="primary" className={classes.appBar}> <Toolbar className={classes.toolbar}> <Typography className={classes.grow} color="inherit"> {/* Developer Portal Instance */} </Typography> <Typography color="inherit">Powered by </Typography> <a href="http://www.linea.gov.br/" rel="noopener noreferrer"> <CardMedia className={classes.media} image={logo} title="LIneA" /> </a> </Toolbar> </AppBar> </React.Fragment> ); } Footer.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Footer);
docs/src/PageHeader.js
HPate-Riptide/react-bootstrap
import React from 'react'; const PageHeader = React.createClass({ render() { return ( <div className="bs-docs-header" id="content"> <div className="container"> <h1>{this.props.title}</h1> <p>{this.props.subTitle}</p> </div> </div> ); } }); export default PageHeader;
src/containers/RoomListPage.js
Destinia/Splendor
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import RoomList from '../components/RoomList.js'; import * as LobbyActions from '../actions/LobbyActions'; const RoomListPage = (props) => ( <div> <RoomList {...props} /> </div> ); const mapStateToProps = (state) => ({ ...state, }); const mapDispatchToProps = (dispatch) => bindActionCreators(LobbyActions, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(RoomListPage);