path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/js/components/icons/base/Up.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-up`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'up'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polyline fill="none" stroke="#000" strokeWidth="2" points="7.086 1.174 17.086 11.174 7.086 21.174" transform="rotate(-89 12.086 11.174)"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Up'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
frontend/src/idPortal/appBar.js
unicef/un-partner-portal
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Grid from 'material-ui/Grid'; import Popover from 'material-ui/Popover'; import AppBar from 'material-ui/AppBar'; import Typography from 'material-ui/Typography'; import IconButton from 'material-ui/IconButton'; import AccountIcon from 'material-ui-icons/AccountCircle'; import Logout from '../components/layout/logout'; import logo from '../img/logo.png'; const styleSheet = theme => ({ leftHeader: { [theme.breakpoints.down('xs')]: { width: '100%', }, width: theme.spacing.unit * 28, justifyContent: 'center', zIndex: 1, backgroundColor: theme.palette.secondary[500], }, rightHeader: { flexShrink: 1, // dark blue color added as extra to regular palette backgroundColor: theme.palette.primary.strong, '-ms-grid-column': 2, }, iconBox: { width: 48, height: 48, }, headerIcon: { fill: theme.palette.primary[400], }, noPrint: { '@media print': { display: 'none', }, }, logo: { maxWidth: '170px', }, }); class MainAppBar extends Component { constructor() { super(); this.state = { notifAnchor: null, profileAnchor: null, profileOpen: false, }; this.handleProfileClick = this.handleProfileClick.bind(this); this.handleProfileOnClose = this.handleProfileOnClose.bind(this); } handleProfileClick(event) { this.setState({ profileOpen: true, profileAnchor: event.currentTarget }); } handleProfileOnClose() { this.setState({ profileOpen: false }); } render() { const { classes } = this.props; return ( <React.Fragment> <AppBar className={`${classes.header} ${classes.leftHeader} ${classes.noPrint}`} position="static" color="accent" > <Typography type="display1" color="inherit"> <img className={classes.logo} src={logo} alt="logo" /> </Typography> </AppBar> <AppBar className={`${classes.header} ${classes.rightHeader} ${classes.noPrint}`} position="static" color="primary" > <Grid container direction="row" justify="flex-end" spacing={0} > <Grid item> <IconButton color="contrast" onClick={this.handleProfileClick}> <AccountIcon className={`${classes.iconBox} ${classes.headerIcon}`} /> </IconButton> </Grid> </Grid> </AppBar> <Popover id="partnerProfile" anchorEl={this.state.profileAnchor} open={this.state.profileOpen} anchorOrigin={{ vertical: 'bottom', horizontal: 'right', }} transformOrigin={{ vertical: 'top', horizontal: 'right', }} onClose={this.handleProfileOnClose} > <Logout onClose={this.handleProfileOnClose} /> </Popover> </React.Fragment> ); } } MainAppBar.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styleSheet, { name: 'MainAppBar' })(MainAppBar);
src/routes/contact/index.js
zmj1316/InfomationVisualizationCourseWork
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Contact from './Contact'; const title = 'Contact Us'; export default { path: '/contact', action() { return { title, component: <Layout><Contact title={title} /></Layout>, }; }, };
examples/huge-apps/components/GlobalNav.js
levjj/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); export default GlobalNav;
src/svg-icons/hardware/keyboard-voice.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardVoice = (props) => ( <SvgIcon {...props}> <path d="M12 15c1.66 0 2.99-1.34 2.99-3L15 6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 15 6.7 12H5c0 3.42 2.72 6.23 6 6.72V22h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/> </SvgIcon> ); HardwareKeyboardVoice = pure(HardwareKeyboardVoice); HardwareKeyboardVoice.displayName = 'HardwareKeyboardVoice'; HardwareKeyboardVoice.muiName = 'SvgIcon'; export default HardwareKeyboardVoice;
src/svg-icons/action/swap-vert.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVert = (props) => ( <SvgIcon {...props}> <path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/> </SvgIcon> ); ActionSwapVert = pure(ActionSwapVert); ActionSwapVert.displayName = 'ActionSwapVert'; ActionSwapVert.muiName = 'SvgIcon'; export default ActionSwapVert;
server/sonar-web/src/main/js/apps/about/components/AboutLeakPeriod.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info 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 ReadMore from './ReadMore'; import { translate } from '../../../helpers/l10n'; const link = 'https://redirect.sonarsource.com/doc/fix-the-leak.html'; export default class AboutLeakPeriod extends React.Component { render() { return ( <div className="boxed-group"> <h2>{translate('about_page.fix_the_leak')}</h2> <div className="boxed-group-inner"> <p className="about-page-text">{translate('about_page.fix_the_leak.text')}</p> <ReadMore link={link} /> </div> </div> ); } }
client/src/components/InfoPage.js
Pairboard/Pairboard
import React from 'react'; export default function InfoPage() { return ( <div> <p>This pair noticeboard in intended only for use by FCC Forum participants - it doesn't work without a valid forum account.</p> <p>This was made in response to the week long <a href="https://forum.freecodecamp.com/t/computer-frontend-web-development-challenge-november-16-to-26/55986">front end challenge</a> organised by @P1xt.</p> <h1>Technology used</h1> <p>The front end is built with <b>React</b>, in firm defiance of best practices, and uses an unholy mix of <b>react-bootstrap</b>, and regular <b>Bootstrap</b>.</p> <p>The back end is built with <b>NodeJS</b>, <b>Express</b> and <b>MongoDB</b>, with free, sandbox/hobby tier hosting from <b>Heroku</b> and <b>mLab</b>.</p> <h1>Repos</h1> <p>The front end repo is here: <a href="https://github.com/jacksonbates/pair-frontend">Front end</a>.</p> <p>The back end repo is here: <a href="https://github.com/jacksonbates/pair-backend">Back end</a>.</p> <p>Neither have been refactored or tidied, yet...</p> <h1>Notes</h1> <p>I suspect I am using React all wrong - especially with the way I am dealing with form submissions, forcing redirects an refreshes all over the place. Doesn't seem very Reacty to me...</p> <h1>Further Development</h1> <p>I am open to further development of this idea. Now that the project is finished in the eyes of the 'contest', I am open to working with any collaborators. PM me on the forum: <a href="https://forum.freecodecamp.com/users/jacksonbates">JacksonBates</a></p> </div> ); }
src/components/DayHours.js
NataGrankina/surprise-calendar
require('normalize.css'); require('styles/App.scss'); import React from 'react'; class DayHoursComponent extends React.Component { render() { var events = []; var hours = []; for (var i = 0; i < 24; i++) { hours.push(<div key={i} className="hour-box">{i}:00</div>); } return ( <div>{hours}</div> ); } } export default DayHoursComponent;
app/components/ErrorLine.js
dikalikatao/fil
import React from 'react'; export default class ErrorLine extends React.Component { render() { let block = "console__error-line", error = this.props.error; return ( <div className={block}> <pre className={block + "__description"}> {error} </pre> </div> ); } }
src/components/Nav/Nav.js
moxun33/react-mobx-antd-boilerplate
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { Menu, Icon } from 'antd'; const SubMenu = Menu.SubMenu; const MenuItemGroup = Menu.ItemGroup; export default class Nav extends Component { state = { current: 'index' }; handleClick = e => { console.log('click ', e); this.setState({ current: e.key }); }; render() { return ( <Menu onClick={this.handleClick} selectedKeys={[this.state.current]} mode='horizontal'> <Menu.Item key='index'> <Link to='/'>首页</Link> </Menu.Item> <Menu.Item key='user'> <Link to='/user'>用户</Link> </Menu.Item> <Menu.Item key='antd'> <Link to='/antd'>Antd</Link> </Menu.Item> </Menu> ); } }
src/app/components/portalSignup.js
nazar/soapee-ui
import React from 'react'; import Portal from 'react-portal'; import AnimatedModal from 'components/animatedModal'; export default React.createClass({ render() { return ( <Portal isOpened={this.props.isOpened} closeOnEsc={true} closeOnOutsideClick={true} onClose={this.signalClosed} > <AnimatedModal> Think of the children </AnimatedModal> </Portal> ); } });
src/containers/TrustPublish.js
iris-dni/iris-frontend
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { fetchPetition } from 'actions/PetitionActions'; import settings from 'settings'; import Trust from 'components/Trust'; import getPetitionForm from 'selectors/petitionForm'; const TrustPublishContainer = (props) => ( <div> <Helmet title={settings.trustPage.publish.title} /> <Trust {...props} action={'publish'} /> </div> ); TrustPublishContainer.fetchData = ({ store, params }) => { return store.dispatch(fetchPetition(params.id)); }; export const mapStateToProps = ({ petition, trust, me }) => ({ petition: getPetitionForm(petition), isLoggedIn: me && !!me.id }); TrustPublishContainer.propTypes = { location: React.PropTypes.object.isRequired, petition: React.PropTypes.object.isRequired, isLoggedIn: React.PropTypes.bool.isRequired }; export default connect( mapStateToProps )(TrustPublishContainer);
src/containers/Forms/Slider/index.js
EncontrAR/backoffice
import React, { Component } from 'react'; import Slider from '../../../components/uielements/slider'; import PageHeader from '../../../components/utility/pageHeader'; import Box from '../../../components/utility/box'; import LayoutWrapper from '../../../components/utility/layoutWrapper'; import ContentHolder from '../../../components/utility/contentHolder'; export default class AntdSlider extends Component { onChange = value => { console.log('onChange: ', value); }; onAfterChange = value => { console.log('onAfterChange: ', value); }; render() { return ( <LayoutWrapper> <PageHeader>Slider</PageHeader> <Box title="Event" subtitle="The onChange callback function will fire when the user changes the slider's value. The onAfterChange callback function will fire when onmouseup fired." > <ContentHolder> <Slider defaultValue={30} onChange={this.onChange} onAfterChange={this.onAfterChange} /> <Slider range step={10} defaultValue={[20, 50]} onChange={this.onChange} onAfterChange={this.onAfterChange} /> </ContentHolder> </Box> </LayoutWrapper> ); } }
src/Creatable.js
mmpro/react-select
import PropTypes from 'prop-types'; import React from 'react'; import defaultFilterOptions from './utils/defaultFilterOptions'; import defaultMenuRenderer from './utils/defaultMenuRenderer'; import Select from './Select'; class CreatableSelect extends React.Component { constructor (props, context) { super(props, context); this.filterOptions = this.filterOptions.bind(this); this.menuRenderer = this.menuRenderer.bind(this); this.onInputKeyDown = this.onInputKeyDown.bind(this); this.onInputChange = this.onInputChange.bind(this); this.onOptionSelect = this.onOptionSelect.bind(this); } createNewOption () { const { isValidNewOption, newOptionCreator, onNewOptionClick, options = [], } = this.props; if (isValidNewOption({ label: this.inputValue })) { const option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); const isOptionUnique = this.isOptionUnique({ option, options }); // Don't add the same option twice. if (isOptionUnique) { if (onNewOptionClick) { onNewOptionClick(option); } else { options.unshift(option); this.select.selectValue(option); } } } } filterOptions (...params) { const { filterOptions, isValidNewOption, promptTextCreator, showNewOptionAtTop } = this.props; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. const excludeOptions = params[2] || []; const filteredOptions = filterOptions(...params) || []; if (isValidNewOption({ label: this.inputValue })) { const { newOptionCreator } = this.props; const option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. const isOptionUnique = this.isOptionUnique({ option, options: excludeOptions.concat(filteredOptions) }); if (isOptionUnique) { const prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = newOptionCreator({ label: prompt, labelKey: this.labelKey, valueKey: this.valueKey }); if (showNewOptionAtTop) { filteredOptions.unshift(this._createPlaceholderOption); } else { filteredOptions.push(this._createPlaceholderOption); } } } return filteredOptions; } isOptionUnique ({ option, options }) { const { isOptionUnique } = this.props; options = options || this.props.options; return isOptionUnique({ labelKey: this.labelKey, option, options, valueKey: this.valueKey }); } menuRenderer (params) { const { menuRenderer } = this.props; return menuRenderer({ ...params, onSelect: this.onOptionSelect, selectValue: this.onOptionSelect }); } onInputChange (input) { const { onInputChange } = this.props; // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; if (onInputChange) { this.inputValue = onInputChange(input); } return this.inputValue; } onInputKeyDown (event) { const { shouldKeyDownEventCreateNewOption, onInputKeyDown } = this.props; const focusedOption = this.select.getFocusedOption(); if ( focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption(event) ) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } else if (onInputKeyDown) { onInputKeyDown(event); } } onOptionSelect (option) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } } focus () { this.select.focus(); } render () { const { ref: refProp, ...restProps } = this.props; let { children } = this.props; // We can't use destructuring default values to set the children, // because it won't apply work if `children` is null. A falsy check is // more reliable in real world use-cases. if (!children) { children = defaultChildren; } const props = { ...restProps, allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: (ref) => { this.select = ref; // These values may be needed in between Select mounts (when this.select is null) if (ref) { this.labelKey = ref.props.labelKey; this.valueKey = ref.props.valueKey; } if (refProp) { refProp(ref); } } }; return children(props); } } const defaultChildren = props => <Select {...props} />; const isOptionUnique = ({ option, options, labelKey, valueKey }) => { if (!options || !options.length) { return true; } return options .filter((existingOption) => existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey] ) .length === 0; }; const isValidNewOption = ({ label }) => !!label; const newOptionCreator = ({ label, labelKey, valueKey }) => { const option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; }; const promptTextCreator = label => `Create option "${label}"`; const shouldKeyDownEventCreateNewOption = ({ keyCode }) => { switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; default: return false; } }; // Default prop methods CreatableSelect.isOptionUnique = isOptionUnique; CreatableSelect.isValidNewOption = isValidNewOption; CreatableSelect.newOptionCreator = newOptionCreator; CreatableSelect.promptTextCreator = promptTextCreator; CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption; CreatableSelect.defaultProps = { filterOptions: defaultFilterOptions, isOptionUnique, isValidNewOption, menuRenderer: defaultMenuRenderer, newOptionCreator, promptTextCreator, shouldKeyDownEventCreateNewOption, showNewOptionAtTop: true }; CreatableSelect.propTypes = { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: PropTypes.func, // See Select.propTypes.filterOptions filterOptions: PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: PropTypes.func, // input change handler: function (inputValue) {} onInputChange: PropTypes.func, // input keyDown handler: function (event) {} onInputKeyDown: PropTypes.func, // new option click handler: function (option) {} onNewOptionClick: PropTypes.func, // See Select.propTypes.options options: PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: PropTypes.func, ref: PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: PropTypes.func, // Where to show prompt/placeholder option text. // true: new option prompt at top of list (default) // false: new option prompt at bottom of list showNewOptionAtTop: PropTypes.bool, }; export default CreatableSelect;
src/common/Dialog/DialogStandardButtons.js
Syncano/syncano-dashboard
import React from 'react'; import _ from 'lodash'; import { FlatButton, RaisedButton } from 'material-ui'; const DialogStandardButtons = ({ handleCancel, handleConfirm, submitLabel = 'Confirm', cancelLabel = 'Cancel', inverted, disabled, submitDisabled, cancelDisabled, ...other }) => { const styles = { rootInverted: { display: 'flex', flexDirection: 'row-reverse', justifyContent: 'flex-end', marginLeft: -10 }, button: { marginLeft: 10, borderRadius: '4px' } }; return ( <div style={inverted && styles.rootInverted}> <FlatButton key="cancel" label={cancelLabel} labelStyle={{ textTransform: 'none' }} buttonStyle={{ borderRadius: '4px' }} style={styles.button} disabled={disabled || cancelDisabled} onTouchTap={_.debounce(handleCancel, 500, { leading: true })} data-e2e={other['data-e2e-cancel']} /> <RaisedButton key="confirm" label={submitLabel} labelStyle={{ textTransform: 'none', color: '#436E1D' }} buttonStyle={{ borderRadius: '4px' }} backgroundColor="#B8E986" style={styles.button} disabled={disabled || submitDisabled} onTouchTap={_.debounce(handleConfirm, 500, { leading: true })} data-e2e={other['data-e2e-submit']} /> </div> ); }; export default DialogStandardButtons;
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
sc4599/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import TypingActionCreators from 'actions/TypingActionCreators'; import DraftActionCreators from 'actions/DraftActionCreators'; import GroupStore from 'stores/GroupStore'; import DraftStore from 'stores/DraftStore'; import AvatarItem from 'components/common/AvatarItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { text: DraftStore.getDraft(), profile: ActorClient.getUser(ActorClient.getUid()) }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); GroupStore.addChangeListener(getStateFromStores); DraftStore.addLoadDraftListener(this.onDraftLoad); } componentWillUnmount() { DraftStore.removeLoadDraftListener(this.onDraftLoad); GroupStore.removeChangeListener(getStateFromStores); } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } onDraftLoad = () => { this.setState(getStateFromStores()); }; onChange = event => { TypingActionCreators.onTyping(this.props.peer); this.setState({text: event.target.value}); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } else if (event.keyCode === 50 && event.shiftKey) { console.warn('Mention should show now.'); } }; onKeyUp = () => { DraftActionCreators.saveDraft(this.state.text); }; sendTextMessage = () => { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } this.setState({text: ''}); DraftActionCreators.saveDraft('', true); }; onSendFileClick = () => { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }; onPhotoInputChange = () => { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; render() { const text = this.state.text; const profile = this.state.profile; return ( <section className="compose" onPaste={this.onPaste}> <AvatarItem image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onChange} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp} value={text}> </textarea> <footer className="compose__footer row"> <button className="button" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </div> </section> ); } } export default ComposeSection;
src/lib/reactors/Showcase/ItemThumbnail.js
ynunokawa/react-webmap
// Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import { Thumbnail } from 'react-bootstrap'; class ItemThumbnail extends React.Component { constructor (props) { super(props); this._onClickThumbnail = this._onClickThumbnail.bind(this); this._onMouseoverThumbnail = this._onMouseoverThumbnail.bind(this); this._onMouseoutThumbnail = this._onMouseoutThumbnail.bind(this); } _onClickThumbnail () { const coordinates = [this.props.feature.geometry.coordinates[1], this.props.feature.geometry.coordinates[0]]; this.props.onClickThumbnail(coordinates, 15); } _onMouseoverThumbnail () { const feature = this.props.feature; this.props.onMouseoverThumbnail(feature); } _onMouseoutThumbnail () { this.props.onMouseoutThumbnail(null); } render () { const feature = this.props.feature; const layoutFields = this.props.layoutFields; let imageUrl = feature.properties[layoutFields.image]; const name = feature.properties[layoutFields.name]; const description = feature.properties[layoutFields.description]; if (layoutFields.imageUrlPrefix !== undefined && layoutFields.imageUrlPrefix !== '') { imageUrl = layoutFields.imageUrlPrefix + imageUrl; } return ( <Thumbnail src={imageUrl} onClick={this._onClickThumbnail} onMouseOver={this._onMouseoverThumbnail} onMouseOut={this._onMouseoutThumbnail} className="react-webmap-item-thumbnail" > <h3>{name}</h3> <p>{description}</p> </Thumbnail> ); } } ItemThumbnail.propTypes = { feature: React.PropTypes.any, layoutFields: React.PropTypes.object, onClickThumbnail: React.PropTypes.func, onMouseoverThumbnail: React.PropTypes.func, onMouseoutThumbnail: React.PropTypes.func }; ItemThumbnail.displayName = 'ItemThumbnail'; export default ItemThumbnail;
docs/src/app/components/pages/components/DatePicker/ExampleInline.js
rscnt/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; const DatePickerExampleInline = () => ( <div> <DatePicker hintText="Portrait Inline Dialog" container="inline" /> <DatePicker hintText="Landscape Inline Dialog" container="inline" mode="landscape" /> </div> ); export default DatePickerExampleInline;
src/Menu/SimpleMenu.js
dimik/react-material-web-components
import React from 'react' import PropTypes from 'prop-types' import {MDCComponent} from '../MDCComponent' import {List} from '../List' import {MDCSimpleMenu} from '@material/menu/dist/mdc.menu' import classNames from 'classnames' class SimpleMenu extends MDCComponent { static displayName = 'SimpleMenu' static propTypes = { children: PropTypes.node, className: PropTypes.string, onCancel: PropTypes.func, onChange: PropTypes.func, open: PropTypes.bool, openFrom: PropTypes.shape({ horizontal: PropTypes.oneOf(['left', 'right']), vertical: PropTypes.oneOf(['top', 'bottom']), }), style: PropTypes.object, // eslint-disable-line react/forbid-prop-types tabIndex: PropTypes.number, } static defaultProps = { onCancel: () => {}, onChange: () => {}, tabIndex: -1, } componentDidMount() { super.componentDidMount() this._setupListeners() } componentWillReceiveProps(nextProps) { if (nextProps.open !== this.component_.open) { this.component_.open = nextProps.open } } componentWillUnmount() { this._clearListeners() super.componentWillUnmount() } attachTo(el) { return new MDCSimpleMenu(el) } _setupListeners() { this.listen( 'MDCSimpleMenu:selected', this.changeListener_ = e => this.props.onChange( e, e.detail, ) ) this.listen( 'MDCSimpleMenu:cancel', this.cancelListener_ = () => this.props.onCancel() ) } _clearListeners() { this.unlisten( 'MDCSimpleMenu:selected', this.changeListener_ ) this.unlisten( 'MDCSimpleMenu:cancel', this.cancelListener_ ) } render() { const { children, className, open, openFrom, onCancel, onChange, style, ...otherProps, } = this.props const cssClasses = classNames({ 'mdc-simple-menu': true, 'mdc-simple-menu--open': open, [`mdc-simple-menu--open-from-${openFrom && openFrom.vertical}-${openFrom && openFrom.horizontal}`]: openFrom, }, className) return ( <div {...otherProps} className={cssClasses} ref={el => this.root_ = el} style={{transform: 'scale(0)', ...style}} > <List aria-hidden="true" className="mdc-simple-menu__items" role="menu" > {children} </List> </div> ) } } export default SimpleMenu
components/ImpactLeague/ImpactLeagueCode.js
akashnautiyal013/ImpactRun01
'use strict'; import React, { Component } from 'react'; import{ StyleSheet, View, Image, ScrollView, TextInput, Dimensions, TouchableOpacity, Text, AlertIOS, Platform, ActivityIndicatorIOS, AsyncStorage } from 'react-native'; import commonStyles from '../styles'; import apis from '../apis'; import styleConfig from '../styleConfig'; import dismissKeyboard from 'react-native/Libraries/Utilities/dismissKeyboard'; import Icon from 'react-native-vector-icons/Ionicons'; var deviceWidth = Dimensions.get('window').width; var deviceHeight = Dimensions.get('window').height; var ApiUtils = { checkStatus: function(response) { if (response.status >= 200 && response.status < 300) { return response; } else { let error = new Error(response.status); error.response = response; return response; } } }; class ImpactLeagueCode extends Component { constructor() { super(); this.state = { moreText:'', codenotextist:'', loading:false, }; this.codeDoesnotExistCheck = this.codeDoesnotExistCheck.bind(this); } SubmitCode(){ this.setState({ loading:true, }) var http = new XMLHttpRequest(); var user_id = this.props.user.user_id; var token = this.props.user.auth_token; var auth_token = (token); let formData = new FormData(); formData.append('user', user_id); formData.append('team', this.state.moreText); http.open("POST", apis.ImpactLeagueCodeApi, true); fetch(apis.ImpactLeagueCodeApi, { method: "POST", datatype:'json', headers: { 'Authorization':'Bearer '+token, 'Accept':'application/json', 'Content-Type':'application/x-www-form-urlencoded', }, body: formData }) .then((response) => { return response.json(); }) .then((responseJson) => { this.setState({ loading:false, }) console.log('responseJson',responseJson); this.codeDoesnotExistCheck(responseJson); }) .catch((err) => { console.log('error',err); this.setState({ codenotextist:'Sorry, this team is full.', loading:false, }) }) .done(); dismissKeyboard(); this._textInput.setNativeProps({text: ''}); } checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } else { let error = new Error(response.statusText); error.response = response; throw error; } } goBack(){ this.props.navigator.pop(); } Navigate_To_nextpage(responseJson){ var team_code = responseJson.team_code; console.log(responseJson.company_attribute); var cities = responseJson.company_attribute; var city = []; var i; for (i = 0; i < cities.length; i++) { if (cities[i].city != null ) { city.push(cities[i].city); } } console.log('text',city); var departments = responseJson.company_attribute; var department = []; var i; for (i = 0; i < departments.length; i++) { if (departments[i].department != null) { department.push(departments[i].department); } } console.log('text',department); this.props.navigator.replace({ id:'impactleagueform2', passProps:{ cities:city, departments:department, user:this.props.user, data:responseJson, getUserData:this.props.getUserData, }, navigator: this.props.navigator, }) } codeDoesnotExistCheck(responseJson){ console.log('responcedatacode',responseJson); var valueReturn = "Object with team_code="+this.state.moreText+" does not exist."; var valueReturn2 = "The fields user, team must make a unique set"; if (responseJson) { if (responseJson.team[0] === valueReturn) { this.setState({ codenotextist:'Sorry, that’s not the code.', }) }else{ this.Navigate_To_nextpage(responseJson); } } } isloading(){ if (this.state.loading) { return( <View style={{position:'absolute',top:0,backgroundColor:'rgba(4, 4, 4, 0.56)',height:deviceHeight,width:deviceWidth,justifyContent: 'center',alignItems: 'center',}}> <ActivityIndicatorIOS style={{height: 80}} size="large" > </ActivityIndicatorIOS> </View> ) }else{ return; } } render() { return ( <View style={{height:deviceHeight,width:deviceWidth,backgroundColor:'white'}}> <View style={commonStyles.Navbar}> <TouchableOpacity style={{top:10,left:0,position:'absolute',height:70,width:70,backgroundColor:'transparent',justifyContent: 'center',alignItems: 'center',}} onPress={()=>this.goBack()} > <Icon style={{color:'white',fontSize:30,fontWeight:'bold'}}name={'ios-arrow-back'}></Icon> </TouchableOpacity> <Text style={commonStyles.menuTitle}>Impact League</Text> </View> <View style={styles.container}> <View style={styles.ContentWrap}> <Text style={{marginTop:10,color:styleConfig.purplish_brown,fontSize:styleConfig.FontSizeDisc,fontFamily:styleConfig.FontFamily,}}>Enter the secret code here.</Text> <View style ={ styles.InputUnderLine}> <TextInput ref={component => this._textInput = component} style={styles.textEdit} onChangeText={(moreText) => this.setState({moreText})} placeholder="DFG3456" /> </View> <View style={{marginBottom:20}}><Text style={styles.Errtext}>{this.state.codenotextist}</Text></View> <View style={styles.BtnWrap}> <TouchableOpacity onPress={() => this.SubmitCode()} style={styles.submitbtn}> <Text style={{color:'white'}}>SUBMIT</Text> </TouchableOpacity> </View> </View> </View> {this.isloading()} </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', flex:1, justifyContent: 'center', alignItems: 'center', padding:10, }, ContentWrap:{ flex:1, }, BtnWrap:{ justifyContent: 'center', alignItems: 'center', }, InputUnderLine:{ height:50, borderBottomColor: '#e1e1e8', backgroundColor: 'white', borderBottomWidth:1 , width:deviceWidth-50, marginTop:20, marginBottom:20, }, textEdit: { height:48, borderBottomColor: '#e1e1e8', backgroundColor: 'white', borderBottomWidth:1 , borderRadius:8, width:deviceWidth-50, color:'#4a4a4a', }, submitbtn:{ justifyContent: 'center', alignItems: 'center', width:deviceWidth-70, height:45, borderRadius:2, shadowColor: '#000000', shadowOpacity: 0.2, shadowRadius: 2, shadowOffset: { height: 2, }, backgroundColor:styleConfig.light_gold, }, Errtext:{ color:'red', fontFamily:styleConfig.FontFamily3, fontSize:styleConfig.FontSize3, } }); export default ImpactLeagueCode;
tests/components/icons/status/Blank-test.js
abzfarah/Pearson.NAPLAN.GnomeH
import {test} from 'tape'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Blank from '../../../src/components/icons/status/Blank'; import CSSClassnames from '../../../src/utils/CSSClassnames'; const STATUS_ICON = CSSClassnames.STATUS_ICON; test('loads a blank icon', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(Blank)); const blankIcon = shallowRenderer.getRenderOutput(); if (blankIcon.props.className.indexOf(`${STATUS_ICON}-blank`) > -1) { t.pass('Icon has blank class'); } else { t.fail('Icon does not have blank class'); } }); test('loads a blank icon with custom class applied', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(Blank, { className:'custom-class' })); const blankIcon = shallowRenderer.getRenderOutput(); if (blankIcon.props.className.indexOf('custom-class') > -1) { t.pass('Blank icon has custom class applied'); } else { t.fail('Blank icon does not have custom class applied'); } });
web/client/configdev/src/config/Usage.js
project-owner/Peppy
/* Copyright 2019-2020 Peppy Player peppy.player@gmail.com This file is part of Peppy Player. Peppy Player 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. Peppy Player 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 Peppy Player. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import {FormControl, FormGroup} from '@material-ui/core'; import Factory from "../Factory"; export default class Usage extends React.Component { render() { const { classes, params, updateState, labels } = this.props; return ( <div> <FormControl component="fieldset"> <FormGroup column="true"> {Factory.createCheckbox("touchscreen", params, updateState, labels)} {Factory.createCheckbox("mouse", params, updateState, labels)} {Factory.createCheckbox("lirc", params, updateState, labels)} {Factory.createCheckbox("web", params, updateState, labels)} {Factory.createCheckbox("stream.server", params, updateState, labels)} {Factory.createCheckbox("browser.stream.player", params, updateState, labels)} {Factory.createCheckbox("voice.assistant", params, updateState, labels)} </FormGroup> {Factory.createNumberTextField("long.press.time.ms", params, updateState, "ms", {width: "10rem", marginTop: "1rem"}, classes, labels )} </FormControl> <FormControl component="fieldset"> <FormGroup column="true"> {Factory.createCheckbox("headless", params, updateState, labels)} {Factory.createCheckbox("vu.meter", params, updateState, labels)} {Factory.createCheckbox("album.art", params, updateState, labels)} {Factory.createCheckbox("auto.play", params, updateState, labels)} {Factory.createCheckbox("desktop", params, updateState, labels)} {Factory.createCheckbox("check.for.updates", params, updateState, labels)} {Factory.createCheckbox("bluetooth", params, updateState, labels)} {Factory.createCheckbox("samba", params, updateState, labels)} </FormGroup> </FormControl> </div> ); } }
client/src/components/dashboard/profile/utils/header.js
mikelearning91/seeme-starter
import React, { Component } from 'react'; import { Link } from 'react-router'; import mui from 'material-ui'; import MdIconPack from 'react-icons/lib/md'; import MdPeople from 'react-icons/lib/md/people'; import MdTouchApp from 'react-icons/lib/md/touch-app'; import MdExitApp from 'react-icons/lib/md/exit-to-app'; const HeaderLogin = require('../auth/header-login') const cookie = require('react-cookie'); class Header extends React.Component { renderLinks() { const user = cookie.load('user') console.log(user); if (user !== undefined) { return [ <li key={`${1}header`}> <Link to="my-profile"><MdPeople className="nav-size" /></Link> </li>, <li key={`${2}header`}> <Link to="sas"><MdTouchApp className="nav-size" /></Link> </li>, <li key={`${3}header`}> <Link to="logout"><MdExitApp className="nav-size" /></Link> </li> ]; } else { return [ // Unauthenticated navigation <li> <HeaderLogin /> </li> ]; } } render () { return ( <div> <nav className="navbar navbar-default navbar-fixed-top"> <div className="nav-container"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav-collapse"> <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> <span className="navbar-brand">{this.props.logo}</span> </div> <div className="collapse navbar-collapse" id="nav-collapse"> <ul className="nav navbar-nav navbar-right"> {this.renderLinks()} </ul> </div> </div> </nav> </div> ); } }; export default Header;
examples/react/src/players/NoPreload.js
andfk/react-howler
import React from 'react' import ReactHowler from 'ReactHowler' import Button from '../components/Button' class NoPreload extends React.Component { constructor (props) { super(props) this.state = { preload: false, loaded: false, playing: false } this.handleLoad = this.handleLoad.bind(this) this.handlePlay = this.handlePlay.bind(this) this.handlePause = this.handlePause.bind(this) } // This isn't required but you can use it if you want to // If you don't call load(), the audio will be automatically // loaded when you set the playing prop to true handleLoad () { this.setState({ preload: true }) } handlePlay () { this.setState({ playing: true }) } handlePause () { this.setState({ playing: false }) } render () { return ( <div> <ReactHowler src={['sound2.ogg', 'sound2.mp3']} preload={this.state.preload} playing={this.state.playing} onLoad={() => this.setState({loaded: true})} /> {!this.state.loaded && <Button className='full' onClick={this.handleLoad}>Load (Optional)</Button> } <br /> <Button onClick={this.handlePlay}>Play</Button> <Button onClick={this.handlePause}>Pause</Button> </div> ) } } export default NoPreload
src/index.js
eperiou/DeGreenFields
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root'));
app/app.js
lizhaogai/lyda-dada-v
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; /* eslint-disable import/no-unresolved, import/extensions */ // Load the favicon, the manifest.json file and the .htaccess file import 'file?name=[name].[ext]!./favicon.ico'; import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import ContextProvider from 'react-with-context'; import {applyRouterMiddleware, Router, browserHistory} from 'react-router'; import {syncHistoryWithStore} from 'react-router-redux'; import FontFaceObserver from 'fontfaceobserver'; import {useScroll} from 'react-router-scroll'; import configureStore from './store'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Import CSS reset and Global Styles import 'sanitize.css/sanitize.css'; import './global-styles'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Import i18n messages import {translationMessages} from './i18n'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import {selectLocationState} from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); import LocalStorage from './LocalStorage'; // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <ContextProvider context={{client: LocalStorage}}> <MuiThemeProvider> <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider> </MuiThemeProvider> </ContextProvider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/en.js'), System.import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
admin/client/App/shared/Popout/PopoutHeader.js
ONode/keystone
/** * Render a header for a popout */ import React from 'react'; import Transition from 'react-addons-css-transition-group'; const PopoutHeader = React.createClass({ displayName: 'PopoutHeader', propTypes: { leftAction: React.PropTypes.func, leftIcon: React.PropTypes.string, title: React.PropTypes.string.isRequired, transitionDirection: React.PropTypes.oneOf(['next', 'prev']), }, render () { // If we have a left action and a left icon, render a header button var headerButton = (this.props.leftAction && this.props.leftIcon) ? ( <button key={'button_' + this.props.transitionDirection} type="button" className={'Popout__header__button octicon octicon-' + this.props.leftIcon} onClick={this.props.leftAction} /> ) : null; // If we have a title, render it var headerTitle = this.props.title ? ( <span key={'title_' + this.props.transitionDirection} className="Popout__header__label" > {this.props.title} </span> ) : null; return ( <div className="Popout__header"> <Transition transitionName="Popout__header__button" transitionEnterTimeout={200} transitionLeaveTimeout={200} > {headerButton} </Transition> <Transition transitionName={'Popout__pane-' + this.props.transitionDirection} transitionEnterTimeout={360} transitionLeaveTimeout={360} > {headerTitle} </Transition> </div> ); }, }); module.exports = PopoutHeader;
src/components/Champion/index.js
dragoncodes/dragon-lol
import React from 'react' import { RiotApi } from 'riot-api' import { RiotActions } from 'store/riot' import { connect } from 'react-redux' import './champion.scss' class Champion extends React.Component { static propTypes = { championId: React.PropTypes.number, champions: React.PropTypes.any, customRender: React.PropTypes.func, loadChampion: React.PropTypes.func.isRequired, showName: React.PropTypes.bool }; shouldComponentUpdate (nextProps, nextState) { // Update only when the champion for this component has arrived return !!(nextProps.champions && nextProps.champions[ nextProps.championId ]) } componentDidMount () { const props = this.props if (props.championId) { this.props.loadChampion(props.championId) } } render () { const { customRender, champions, championId } = this.props let championLoading = !champions || !champions[ championId ] if (championLoading) { return ( <div>Loading champion</div> ) } if (customRender) { return customRender(champions, championId) } return this.renderChampion(champions[ championId ]) } renderChampion (champion) { const { showName = true } = this.props return ( <div className='champion-card'> <img crossOrigin='' className='champion-image' src={champion.image}/> {showName ? ( <div className='champion-title'> { champion.name + ' ' + champion.title } </div> ) : null } </div> ) } } // +=============== Actions ============== const championLoaded = (champion) => { return { type: RiotActions.ChampionLoaded, champion } } // ======================================= const mapDispatchToProps = (dispatch) => { return { loadChampion: (championId) => { return RiotApi.Instance.Champions.ById(championId).then( (champion) => { dispatch(championLoaded(champion)) } ) } } } const mapStateToProps = (state) => ({ champions: state.riot.champions }) export default connect(mapStateToProps, mapDispatchToProps)(Champion)
src/containers/recipes/Card/CardView.js
banovotz/WatchBug2
/** * Recipe View Screen * - The individual recipe screen * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, StyleSheet, TouchableOpacity, } from 'react-native'; import { Icon } from 'react-native-elements'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Card, Text } from '@ui/'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ favourite: { position: 'absolute', top: -45, right: 0, }, }); /* Component ==================================================================== */ class RecipeCard extends Component { static componentName = 'RecipeCard'; static propTypes = { image: PropTypes.string.isRequired, title: PropTypes.string.isRequired, body: PropTypes.string.isRequired, onPress: PropTypes.func, onPressFavourite: PropTypes.func, isFavourite: PropTypes.bool, } static defaultProps = { onPress: null, onPressFavourite: null, isFavourite: null, } render = () => { const { title, body, image, onPress, onPressFavourite, isFavourite } = this.props; return ( <TouchableOpacity activeOpacity={0.8} onPress={onPress}> <Card image={image && { uri: image }}> <View style={[AppStyles.paddingBottomSml]}> <Text h3>{title}</Text> <Text>{body}</Text> {!!onPressFavourite && <TouchableOpacity activeOpacity={0.8} onPress={onPressFavourite} style={[styles.favourite]} > <Icon raised name={'star-border'} color={isFavourite ? '#FFFFFF' : '#FDC12D'} containerStyle={{ backgroundColor: isFavourite ? '#FDC12D' : '#FFFFFF', }} /> </TouchableOpacity> } </View> </Card> </TouchableOpacity> ); } } /* Export Component ==================================================================== */ export default RecipeCard;
dev/react-subjects/subjects/Flux/solution.js
AlanWarren/dotfiles
import React from 'react' import { render } from 'react-dom' import ContactList from './solution/components/ContactList' /* The goal of this exercise is to add a button beside each contact in the list that can be used to delete that contact. To do this, you'll need to perform the following steps: * Hint: Open up Flux.png and make your way around the Flux diagram as you go * - Make the <ContactList> component listen for changes to the ContactStore and updates its state when the store changes - Add a "delete" button next to each contact (components/ContactList.js) - The delete button should create an action (actions/ViewActionCreators.js) that does two things: - Sends a "delete contact" action through the dispatcher - Sends a request to the server to actually delete the contact - The server creates an action that sends a "contact was deleted" action through the dispatcher - The ContactStore (stores/ContactStore.js) picks up the "delete contact" event, removes the corresponding contact, and fires a change event */ render(<ContactList/>, document.getElementById('app'))
app/index.js
CKrawczyk/electron-subject-uploader
import React from 'react'; import ReactDom from 'react-dom'; import '../css/main.styl'; import apiClient from 'panoptes-client'; import routes from './routes'; import { Router, hashHistory } from 'react-router'; const App = () => ( <Router history={hashHistory} routes={routes} /> ); // For console access: if (window) { window.zooAPI = apiClient; } ReactDom.render(<App />, document.getElementById('root'));
codes/chapter05/react-router-v4/basic/demo05/app/components/App.js
atlantis1024/react-step-by-step
import React from 'react'; import { Link } from 'react-router-dom'; class App extends React.PureComponent { render() { return ( <div> <h1>React Router Tutorial</h1> <ul role="nav"> <li><Link to="/about">关于</Link></li> <li><Link to="/topics">主题</Link></li> <li><Link to="/redirect">重定向到关于页面</Link></li> <li><Link to="/nomatch">无法匹配的页面</Link></li> </ul> </div> ) } } export default App;
src/Parser/Warrior/Protection/Modules/Spells/ShieldBlock.js
enragednuke/WoWAnalyzer
import React from 'react'; import { formatPercentage, formatThousands } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; const debug = false; class Shield_Block extends Analyzer { static dependencies = { combatants: Combatants, }; lastShield_BlockBuffApplied = 0; physicalHitsWithShield_Block = 0; physicalDamageWithShield_Block = 0; physicalHitsWithoutShield_Block = 0; physicalDamageWithoutShield_Block = 0; on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (SPELLS.SHIELD_BLOCK_BUFF.id === spellId) { this.lastShield_BlockBuffApplied = event.timestamp; } } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (SPELLS.SHIELD_BLOCK_BUFF.id === spellId) { this.lastShield_BlockBuffApplied = 0; } } on_toPlayer_damage(event) { // Physical if (event.ability.type === 1) { if (this.lastShield_BlockBuffApplied > 0) { this.physicalHitsWithShield_Block += 1; this.physicalDamageWithShield_Block += event.amount + (event.absorbed || 0) + (event.overkill || 0); } else { this.physicalHitsWithoutShield_Block += 1; this.physicalDamageWithoutShield_Block += event.amount + (event.absorbed || 0) + (event.overkill || 0); } } } on_finished() { if (debug) { console.log(`Hits with Shield Block ${this.physicalHitsWithShield_Block}`); console.log(`Damage with Shield Block ${this.physicalDamageWithShield_Block}`); console.log(`Hits without Shield Block ${this.physicalHitsWithoutShield_Block}`); console.log(`Damage without Shield Block ${this.physicalDamageWithoutShield_Block}`); console.log(`Total physical ${this.physicalDamageWithoutShield_Block}${this.physicalDamageWithShield_Block}`); } } suggestions(when) { const physicalDamageMitigatedPercent = this.physicalDamageWithShield_Block / (this.physicalDamageWithShield_Block + this.physicalDamageWithoutShield_Block); when(physicalDamageMitigatedPercent).isLessThan(0.90) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You only had the <SpellLink id={SPELLS.SHIELD_BLOCK_BUFF.id} /> buff for {formatPercentage(actual)}% of physical damage taken. You should have the Shield Block buff up to mitigate as much physical damage as possible.</span>) .icon(SPELLS.SHIELD_BLOCK_BUFF.icon) .actual(`${formatPercentage(actual)}% was mitigated by Shield Block`) .recommended(`${Math.round(formatPercentage(recommended))}% or more is recommended`) .regular(recommended - 0.10).major(recommended - 0.2); }); } statistic() { const physicalHitsMitigatedPercent = this.physicalHitsWithShield_Block / (this.physicalHitsWithShield_Block + this.physicalHitsWithoutShield_Block); const physicalDamageMitigatedPercent = this.physicalDamageWithShield_Block / (this.physicalDamageWithShield_Block + this.physicalDamageWithoutShield_Block); return ( <StatisticBox icon={<SpellIcon id={SPELLS.SHIELD_BLOCK_BUFF.id} />} value={`${formatPercentage (physicalHitsMitigatedPercent)}%`} label="Physical Hits Mitigated" tooltip={`Shield Block usage breakdown: <ul> <li>You were hit <b>${this.physicalHitsWithShield_Block}</b> times with your Shield Block buff (<b>${formatThousands(this.physicalDamageWithShield_Block)}</b> damage).</li> <li>You were hit <b>${this.physicalHitsWithoutShield_Block}</b> times <b><i>without</i></b> your Shield Block buff (<b>${formatThousands(this.physicalDamageWithoutShield_Block)}</b> damage).</li> </ul> <b>${formatPercentage(physicalHitsMitigatedPercent)}%</b> of physical attacks were mitigated with Shield Block (<b>${formatPercentage(physicalDamageMitigatedPercent)}%</b> of physical damage taken).`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(10); } export default Shield_Block;
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
odapplications/WebView-with-Lower-Tab-Menu
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
docs/app/src/components/LanguageSelector.js
tercenya/compendium
import React from 'react'; import ReactDOM from 'react-dom'; import MFizzIcon from './MFizzIcon'; import _ from 'lodash'; export const Language = (props, context) => { const changeLanguage = (lang, event) => { console.log(`changing language to ${lang}`); if (props.onClick) { props.onClick(lang); }; } const icon = props.icon || props.lang return( <button className={`language-bar language-${props.lang}`} onClick={(e) => changeLanguage(props.lang, e)}> <MFizzIcon icon={icon}/>&nbsp;{props.children} </button> ) } function renderChildren(props, state) { return React.Children.map(props.children, child => { return React.cloneElement(child, { lang: state.lang }) }) } export default class LanguageSelector extends React.Component { constructor(props) { super(props); this.state = {lang: 'ruby'} } componentDidMount() { if (typeof window !== "undefined") { lang = window.localStorage.getItem('compendium-language'); if (lang) { this.setState({lang: lang}); } } } update(l) { this.setState({lang: l}); if (typeof window != "undefined") { window.localStorage.setItem('compendium-language', l); } this.forceUpdate(); } render() { return( <div> <div> <Language lang='ruby' onClick={(l) => { this.update(l) }}>ruby</Language> <Language lang='php' onClick={(l) => { this.update(l) }}>php</Language> <Language lang='node' icon='nodejs' onClick={(l) => { this.update(l) }}>nodejs</Language> </div> {renderChildren(this.props, this.state)} </div> ); } } // <Language lang='python'>python</Language> // <Language lang='java'>java</Language> // <Language lang='cli' icon='shell'>cURL</Language>
packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js
romaindso/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; async function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-async-await"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/layouts/Field/FieldGroup.js
Bandwidth/shared-components
import React from 'react'; import PropTypes from 'prop-types'; import { withPulseGroup } from 'skeletons/PulseGroup'; import * as styles from './styles'; /** * A component that renders a collection of Field components into a grid, making space for * labels, help text, etc. Simply pass the number of columns into this component and render * Field components as its children. * @visibleName Field.Group */ class FieldGroup extends React.Component { static propTypes = { /** * The number of columns to divide the fieldset into when rendering. Field.Group can span multiple columns if provided * with a columnSpan prop. Field.Group which overflow the column limit will be added to new rows. If a Field's * columnSpan is too large to fit in the current row, it will be wrapped to the next one. */ columns: PropTypes.number, /** * A component prop to override the component used to render the outer container which renders field rows. * Defaults to Field.Group.styles.FieldRowContainer. */ RowContainer: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), /** * A component prop to override the component which is injected to wrap Field elements into discrete rows. * Row receives the same `columns` prop provided to this component. Defaults to Field.Group.styles.FieldRow. */ Row: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), }; static defaultProps = { className: "scl-field-group", RowContainer: styles.FieldRowContainer, Row: styles.FieldRow, columns: 2, }; static styles = styles; partitionFields = () => { const { columns, children, Row } = this.props; const childArray = React.Children.toArray(children); const rows = childArray.reduce( (rows, child) => { const childColumnSpan = child.props.columnSpan || 1; if (childColumnSpan > columns) { throw new Error( `A Field has a columnSpan of ${childColumnSpan}, but the containing Field.Group only has ${columns} columns`, ); } const currentRow = rows[rows.length - 1]; if (currentRow.columnWidth + childColumnSpan <= columns) { // add to current row return [ ...rows.slice(0, rows.length - 1), { children: [ ...currentRow.children, { column: currentRow.columnWidth, element: child, }, ], columnWidth: currentRow.columnWidth + childColumnSpan, }, ]; } else { // create new row return [ ...rows, { children: [{ column: 0, element: child }], columnWidth: childColumnSpan, }, ]; } }, [{ children: [], columnWidth: 0 }], ); return rows.map((row, rowIdx) => ( <Row key={rowIdx} columns={columns}> {row.children.map(({ element, column }) => React.cloneElement(element, { column }), )} </Row> )); }; render() { const { RowContainer, Row, columns, ...rest } = this.props; return <RowContainer {...rest}>{this.partitionFields()}</RowContainer>; } } const PulseFieldRow = withPulseGroup(styles.FieldRow); FieldGroup.Skeleton = ({ ...rest }) => ( <FieldGroup Row={props => <PulseFieldRow {...props} />} {...rest} /> ); export default FieldGroup;
app/javascript/mastodon/features/compose/components/text_icon_button.js
musashino205/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const iconStyle = { height: null, lineHeight: '27px', width: `${18 * 1.28571429}px`, }; export default class TextIconButton extends React.PureComponent { static propTypes = { label: PropTypes.string.isRequired, title: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func.isRequired, ariaControls: PropTypes.string, }; handleClick = (e) => { e.preventDefault(); this.props.onClick(); } render () { const { label, title, active, ariaControls } = this.props; return ( <button title={title} aria-label={title} className={`text-icon-button ${active ? 'active' : ''}`} aria-expanded={active} onClick={this.handleClick} aria-controls={ariaControls} style={iconStyle} > {label} </button> ); } }
docs/src/app/components/pages/components/CircularProgress/ExampleDeterminate.js
matthewoates/material-ui
import React from 'react'; import CircularProgress from 'material-ui/CircularProgress'; export default class CircularProgressExampleDeterminate extends React.Component { constructor(props) { super(props); this.state = { completed: 0, }; } componentDidMount() { this.timer = setTimeout(() => this.progress(5), 1000); } componentWillUnmount() { clearTimeout(this.timer); } progress(completed) { if (completed > 100) { this.setState({completed: 100}); } else { this.setState({completed}); const diff = Math.random() * 10; this.timer = setTimeout(() => this.progress(completed + diff), 1000); } } render() { return ( <div> <CircularProgress mode="determinate" value={this.state.completed} /> <CircularProgress mode="determinate" value={this.state.completed} size={60} thickness={7} /> <CircularProgress mode="determinate" value={this.state.completed} size={80} thickness={5} /> </div> ); } }
src/html.js
gopalshackergarage/gopalshackergarage.github.io
import React from 'react'; import PropTypes from 'prop-types'; export default class HTML extends React.Component { render() { return ( <html {...this.props.htmlAttributes}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> {this.props.headComponents} </head> <body {...this.props.bodyAttributes}> <script dangerouslySetInnerHTML={{ __html: ` (function() { window.__onThemeChange = function() {}; function setTheme(newTheme) { window.__theme = newTheme; preferredTheme = newTheme; document.body.className = newTheme; window.__onThemeChange(newTheme); } var preferredTheme; try { preferredTheme = localStorage.getItem('theme'); } catch (err) { } window.__setPreferredTheme = function(newTheme) { setTheme(newTheme); try { localStorage.setItem('theme', newTheme); } catch (err) {} } var darkQuery = window.matchMedia('(prefers-color-scheme: dark)'); darkQuery.addListener(function(e) { window.__setPreferredTheme(e.matches ? 'dark' : 'light') }); setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light')); })(); `, }} /> {this.props.preBodyComponents} <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ); } } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, };
client/app/ihome/index/index.js
jl-/r-
import React, { Component } from 'react'; import Card from '../../partials/card'; import styles from './style.scss'; class Index extends Component { render() { return ( <div className={styles.home}> <Card> 1 </Card> <Card> 1 </Card> <Card> 1 </Card> <Card> 1 </Card> </div> ); } } export default Index;
examples/async/containers/Root.js
aphillipo/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import configureStore from '../store/configureStore'; import AsyncApp from './AsyncApp'; const store = configureStore(); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <AsyncApp />} </Provider> ); } }
indico/web/client/js/react/components/principals/imperative.js
pferreir/indico
// This file is part of Indico. // Copyright (C) 2002 - 2021 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import _ from 'lodash'; import React from 'react'; import ReactDOM from 'react-dom'; import {FavoritesProvider} from 'indico/react/hooks'; import {UserSearch} from './Search'; /** * Open a user/group/etc. search prompt imperatively. * * This mounts the UserSearch component in a temporary location * and returns a promise that will be resolved once something is * selected or the dialog is closed (in that case it will be resolved * with an empty list of principals) */ export function showUserSearch(searchProps = {}) { const container = document.createElement('div'); document.body.appendChild(container); const cleanup = () => _.defer(() => { ReactDOM.unmountComponentAtNode(container); document.body.removeChild(container); }); return new Promise(resolve => { ReactDOM.render( <FavoritesProvider> {([favorites]) => ( <UserSearch favorites={favorites} existing={[]} onAddItems={users => { resolve(searchProps.single ? users?.identifier : users.map(u => u.identifier)); cleanup(); }} onClose={() => { resolve(searchProps.single ? null : []); cleanup(); }} defaultOpen {...searchProps} /> )} </FavoritesProvider>, container ); }); }
src/App.js
erlanglab/erlangpl-ui
// @flow import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import './App.css'; import core from './core'; const { Navigation, Footer } = core.components; // plugins import eplDashboard from './plugins/epl-dashboard'; import eplSupTree from './plugins/epl-sup-tree'; import eplVizceral from './plugins/epl-vizceral'; import about from './about'; import plugins from './plugins'; const App = ({ store, history }: { store: mixed, history: mixed }) => { const tabs = [ { path: '/dashboard', icon: 'television' }, { path: '/sup-tree', icon: 'sitemap' }, { path: '/traffic', icon: 'share-alt' }, { path: '/about', icon: 'question' } ].concat( plugins.reduce( (acc, plugin) => { if (plugin.name && plugin.icon) { const name = plugin.name.replace('epl-', ''); return acc.concat({ path: `/${name}`, icon: plugin.icon }); } console.warn(`Could not register navigation for ${plugin.name}`); return acc; }, [] ) ); const routes = plugins.reduce( (acc, plugin) => { if (plugin.name && plugin.Component) { const name = plugin.name.replace('epl-', ''); return acc.concat( <Route key={acc.length} path={`/${name}`} component={plugin.Component} /> ); } console.warn(`Could not add route for ${plugin.name}`); return acc; }, [] ); return ( <Provider store={store}> <ConnectedRouter history={history}> <div className="App"> <Navigation tabs={tabs} /> <div className="App-container"> <Route exact path="/" render={() => <Redirect to="/dashboard" />} /> <Route path="/dashboard/:subRoute*" component={eplDashboard.Dashboard} /> <Route path="/sup-tree" component={eplSupTree.SupTree} /> <Route path="/traffic/:view*" component={eplVizceral.Vizceral} /> <Route path="/about" component={about.components.About} /> {routes} </div> <Footer /> </div> </ConnectedRouter> </Provider> ); }; export default App;
src/client/assets/js/nodes/outputs/notify/node.js
me-box/platform-sdk
import React from 'react'; //import composeNode from 'utils/composeNode'; import Textfield from 'components/form/Textfield'; import Textarea from 'components/form/Textarea'; import Select from 'components/form/Select'; import Cell from 'components/Cell'; import Cells from 'components/Cells'; class Node extends React.Component { render() { const {selected,values,updateNode} = this.props; const nameprops = { id: "name", value: values.name || "", onChange: (property, event)=>{ updateNode(property, event.target.value); }, selected: selected, } const nameinput = <div className="centered"> <Textfield {...nameprops}/> </div> const messageprops = { id: "message", value: values.message || "", onChange: (property, event)=>{ updateNode(property, event.target.value); }, selected: selected, } const messageinput = <div className="centered"> <Textarea {...messageprops}/> </div> const toprops = { id: "to", value: values.to || "", onChange: (property, event)=>{ updateNode(property, event.target.value); }, selected: selected, } const toinput = <div className="centered"> <Textfield {...toprops}/> </div> const typeprops = { options: [{name: 'twitter', value: 'twitter'}, {name: 'sms', value: 'sms'}], onSelect: (event)=>{ this.props.updateNode("subtype", event.target.value); this.props.updateOutputSchema(event.target.value); }, style: {width: '100%'}, value: this.props.values.subtype || "", } const typeinput = <div className="centered"> <Select {...typeprops}/> </div> return <div> <Cells> <Cell title={"name"} content={nameinput}/> <Cell title={"message"} content={messageinput}/> <Cell title={"to"} content={toinput}/> <Cell title={"type"} content={typeinput}/> </Cells> </div> } } /*export default composeNode(Node, 'notify', { category: 'outputs', color: '#d45500', defaults: { name: {value:""}, subtype: {value:"twitter"}, message: {value:""}, to:{value:""}, }, inputs:1, outputs:0, icon: "fa-envelope-o", unicode: '\uf003', label: function() { return this.name||this.topic||"notify"; }, schema: ()=>{ return { input:{ type: "object", description: "the container object", properties:{ channel: {type:'string', description: '<i>sms</i> or <i>twitter</i>', enum:["sms", "twitter"]}, payload: { type: 'object', description: 'the message payload', properties: { to: {type:'string', description: 'phone number or twitter handle'}, message: {type:'string', description: 'message to send'}, }, required: ["to", "message"] } }, required: ["channel", "payload"] } } }, description: ()=>"<p> This will send a notification to a communication endpoint such as an email address, sms, twitter, growl or push. Note that <strong> currently only twitter and sms are supported </strong></p>", labelStyle: function() { return this.name?"node_label_italic":""; } } );*/
app/.plop/stories.js
atralice/reactDockerizeBoilerplate
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import {{ properCase name }} from 'Components/{{properCase folder}}/{{ properCase name }}'; import s from 'Components/{{properCase folder}}/{{ properCase name }}.styl'; storiesOf('{{ properCase name }}', module) .add('default', () => <{{ properCase name }}/>);
src/components/employee/EmployeeList.js
GHImplementationTeam/FrontEnd
import { List, ListItem } from 'material-ui/List'; import Paper from 'material-ui/Paper'; import RaisedButton from 'material-ui/RaisedButton'; import Subheader from 'material-ui/Subheader'; import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../../actions/employeeActions'; class EmployeeList extends React.Component { componentWillMount() { this.props.actions.loadEmployees(); } render() { const employees = this.props.employees; return ( <Paper> <List> <Subheader>Employees</Subheader> {employees.map(employee => (<ListItem key={employee.id} primaryText={`${employee.firstName} ${employee.lastName}`} secondaryText="Awaiting response" rightToggle={ <RaisedButton label="ReSend" primary /> } />), )} </List> </Paper> ); } } EmployeeList.propTypes = { employees: PropTypes.array.isRequired, }; function mapStateToProps(state, ownProps) { if (state.employees.length > 0) { return { employees: state.employees, }; } return { employees: [{ id: '', nickName: '', firstName: '', lastName: '', email: '', ssn: '' }], }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(EmployeeList);
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
luoxiaoshenghustedu/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import Inputs from 'utils/Inputs'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import ComposeActionCreators from 'actions/ComposeActionCreators'; import GroupStore from 'stores/GroupStore'; import PreferencesStore from 'stores/PreferencesStore'; import ComposeStore from 'stores/ComposeStore'; import AvatarItem from 'components/common/AvatarItem.react'; import MentionDropdown from 'components/common/MentionDropdown.react'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = () => { return { text: ComposeStore.getText(), profile: ActorClient.getUser(ActorClient.getUid()), sendByEnter: PreferencesStore.sendByEnter, mentions: ComposeStore.getMentions() }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); GroupStore.addChangeListener(this.onChange); ComposeStore.addChangeListener(this.onChange); PreferencesStore.addChangeListener(this.onChange); } componentWillUnmount() { GroupStore.removeChangeListener(this.onChange); ComposeStore.removeChangeListener(this.onChange); PreferencesStore.removeChangeListener(this.onChange); } onChange = () => { this.setState(getStateFromStores()); }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } onMessageChange = event => { let text = event.target.value; ComposeActionCreators.onTyping(this.props.peer, text, this.getCaretPosition()); }; onKeyDown = event => { if (this.state.mentions === null) { if (this.state.sendByEnter === 'true') { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } } else { if (event.keyCode === KeyCodes.ENTER && event.metaKey) { event.preventDefault(); this.sendTextMessage(); } } } }; sendTextMessage = () => { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } ComposeActionCreators.cleanText(); }; onSendFileClick = () => { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }; onPhotoInputChange = () => { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; onMentionSelect = (mention) => { ComposeActionCreators.insertMention(this.props.peer, this.state.text, this.getCaretPosition(), mention); this.refs.area.getDOMNode().focus(); }; onMentionClose = () => { ComposeActionCreators.closeMention(); }; getCaretPosition = () => { let el = this.refs.area.getDOMNode(); let selection = Inputs.getInputSelection(el); return selection.start; }; render() { const { text, profile, mentions } = this.state; return ( <section className="compose" onPaste={this.onPaste}> <MentionDropdown mentions={mentions} onSelect={this.onMentionSelect} onClose={this.onMentionClose}/> <AvatarItem className="my-avatar" image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onMessageChange} onKeyDown={this.onKeyDown} value={text} ref="area"/> <footer className="compose__footer row"> <button className="button" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </div> </section> ); } } export default ComposeSection;
admin/client/views/list.js
Ftonso/keystone
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import CurrentListStore from '../stores/CurrentListStore'; import Columns from '../columns'; import ConfirmationDialog from '../components/ConfirmationDialog'; import CreateForm from '../components/CreateForm'; import FlashMessages from '../components/FlashMessages'; import Footer from '../components/Footer'; import ItemsTable from '../components/ItemsTable'; import ListColumnsForm from '../components/ListColumnsForm'; import ListControl from '../components/ListControl'; import ListDownloadForm from '../components/ListDownloadForm'; import ListFilters from '../components/ListFilters'; import ListFiltersAdd from '../components/ListFiltersAdd'; import ListSort from '../components/ListSort'; import MobileNavigation from '../components/MobileNavigation'; import PrimaryNavigation from '../components/PrimaryNavigation'; import SecondaryNavigation from '../components/SecondaryNavigation'; import UpdateForm from '../components/UpdateForm'; import { BlankState, Button, Container, FormInput, InputGroup, Pagination, Spinner } from 'elemental'; import { plural } from '../utils'; const TABLE_CONTROL_COLUMN_WIDTH = 26; // icon + padding const ListView = React.createClass({ getInitialState () { return { confirmationDialog: { isOpen: false }, checkedItems: {}, constrainTableWidth: true, manageMode: false, searchString: '', showCreateForm: window.location.search === '?create' || Keystone.createFormErrors, showUpdateForm: false, ...this.getStateFromStore(), }; }, componentDidMount () { CurrentListStore.addChangeListener(this.updateStateFromStore); }, componentWillUnmount () { CurrentListStore.removeChangeListener(this.updateStateFromStore); }, updateStateFromStore () { this.setState(this.getStateFromStore()); }, getStateFromStore () { var state = { columns: CurrentListStore.getActiveColumns(), currentPage: CurrentListStore.getCurrentPage(), filters: CurrentListStore.getActiveFilters(), items: CurrentListStore.getItems(), list: CurrentListStore.getList(), loading: CurrentListStore.isLoading(), pageSize: CurrentListStore.getPageSize(), ready: CurrentListStore.isReady(), search: CurrentListStore.getActiveSearch(), rowAlert: CurrentListStore.rowAlert() }; if (!this._searchTimeout) { state.searchString = state.search; } state.showBlankState = (state.ready && !state.loading && !state.items.results.length && !state.search && !state.filters.length); return state; }, // ============================== // HEADER // ============================== updateSearch (e) { clearTimeout(this._searchTimeout); this.setState({ searchString: e.target.value }); var delay = e.target.value.length > 1 ? 150 : 0; this._searchTimeout = setTimeout(() => { delete this._searchTimeout; CurrentListStore.setActiveSearch(this.state.searchString); }, delay); }, handleSearchClear () { CurrentListStore.setActiveSearch(''); this.setState({ searchString: '' }); ReactDOM.findDOMNode(this.refs.listSearchInput).focus(); }, handleSearchKey (e) { // clear on esc if (e.which === 27) { this.handleSearchClear(); } }, handlePageSelect (i) { CurrentListStore.setCurrentPage(i); }, toggleManageMode (filter = !this.state.manageMode) { this.setState({ manageMode: filter, checkedItems: {}, }); }, toggleUpdateModal (filter = !this.state.showUpdateForm) { this.setState({ showUpdateForm: filter, }); }, massUpdate () { // TODO: Implement update multi-item console.log('Update ALL the things!'); }, massDelete () { let { checkedItems, list } = this.state; let itemCount = plural(checkedItems, ('* ' + list.singular.toLowerCase()), ('* ' + list.plural.toLowerCase())); let itemIds = Object.keys(checkedItems); this.setState({ confirmationDialog: { isOpen: true, label: 'Delete', body: `Are you sure you want to delete ${itemCount}?<br /><br />This cannot be undone.`, onConfirmation: () => { CurrentListStore.deleteItems(itemIds); this.toggleManageMode(); this.removeConfirmationDialog(); } } }); }, handleManagementSelect (selection) { if (selection === 'all') this.checkAllTableItems(); if (selection === 'none') this.uncheckAllTableItems(); if (selection === 'visible') this.checkAllTableItems(); return false; }, renderSearch () { var searchClearIcon = classnames('ListHeader__search__icon octicon', { 'is-search octicon-search': !this.state.searchString.length, 'is-clear octicon-x': this.state.searchString.length, }); return ( <InputGroup.Section grow className="ListHeader__search"> <FormInput ref="listSearchInput" value={this.state.searchString} onChange={this.updateSearch} onKeyUp={this.handleSearchKey} placeholder="Search" className="ListHeader__searchbar-input" /> <button ref="listSearchClear" type="button" title="Clear search query" onClick={this.handleSearchClear} disabled={!this.state.searchString.length} className={searchClearIcon} /> </InputGroup.Section> ); }, renderCreateButton () { if (this.state.list.nocreate) return null; var props = { type: 'success' }; if (this.state.list.autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => this.toggleCreateModal(true); } return ( <InputGroup.Section className="ListHeader__create"> <Button {...props} title={'Create ' + this.state.list.singular}> <span className="ListHeader__create__icon octicon octicon-plus" /> <span className="ListHeader__create__label"> Create </span> <span className="ListHeader__create__label--lg"> Create {this.state.list.singular} </span> </Button> </InputGroup.Section> ); }, renderConfirmationDialog () { const props = this.state.confirmationDialog; return ( <ConfirmationDialog isOpen={props.isOpen} body={props.body} confirmationLabel={props.label} onCancel={this.removeConfirmationDialog} onConfirmation={props.onConfirmation} /> ); }, renderManagement () { // WIP: Management mode currently under development, so the UI is disabled // unless the KEYSTONE_DEV environment variable is set if (!Keystone.devMode) return; let { checkedItems, items, list, manageMode, pageSize } = this.state; if (!items.count || (list.nodelete && list.noedit)) return; let checkedItemCount = Object.keys(checkedItems).length; let buttonNoteStyles = { color: '#999', fontWeight: 'normal' }; // action buttons let actionUpdateButton = !list.noedit ? ( <InputGroup.Section> <Button onClick={this.toggleUpdateModal} disabled={!checkedItemCount}>Update</Button> </InputGroup.Section> ) : null; let actionDeleteButton = !list.nodelete ? ( <InputGroup.Section> <Button onClick={this.massDelete} disabled={!checkedItemCount}>Delete</Button> </InputGroup.Section> ) : null; let actionButtons = manageMode ? ( <InputGroup.Section> <InputGroup contiguous> {actionUpdateButton} {actionDeleteButton} </InputGroup> </InputGroup.Section> ) : null; // select buttons let selectAllButton = items.count > pageSize ? ( <InputGroup.Section> <Button onClick={() => this.handleManagementSelect('all')} title="Select all rows (including those not visible)">All <small style={buttonNoteStyles}>({items.count})</small></Button> </InputGroup.Section> ) : null; let selectButtons = manageMode ? ( <InputGroup.Section> <InputGroup contiguous> {selectAllButton} <InputGroup.Section> <Button onClick={() => this.handleManagementSelect('visible')} title="Select all rows">{items.count > pageSize ? 'Page' : 'All'} <small style={buttonNoteStyles}>({items.results.length})</small></Button> </InputGroup.Section> <InputGroup.Section> <Button onClick={() => this.handleManagementSelect('none')} title="Deselect all rows">None</Button> </InputGroup.Section> </InputGroup> </InputGroup.Section> ) : null; // selected count text let selectedCountText = manageMode ? ( <InputGroup.Section grow> <span style={{ color: '#666', display: 'inline-block', lineHeight: '2.4em', margin: 1 }}>{checkedItemCount} selected</span> </InputGroup.Section> ) : null; // put it all together return ( <InputGroup style={{ float: 'left', marginRight: '.75em' }}> <InputGroup.Section> <Button isActive={manageMode} onClick={() => this.toggleManageMode(!manageMode)}>Manage</Button> </InputGroup.Section> {selectButtons} {actionButtons} {selectedCountText} </InputGroup> ); }, renderPagination () { let { currentPage, items, list, manageMode, pageSize } = this.state; if (manageMode || !items.count) return; return ( <Pagination className="ListHeader__pagination" currentPage={currentPage} onPageSelect={this.handlePageSelect} pageSize={pageSize} plural={list.plural} singular={list.singular} style={{ marginBottom: 0 }} total={items.count} limit={10} /> ); }, renderHeader () { let { items, list } = this.state; return ( <div className="ListHeader"> <Container> <h2 className="ListHeader__title"> {plural(items.count, ('* ' + list.singular), ('* ' + list.plural))} <ListSort /> </h2> <InputGroup className="ListHeader__bar"> {this.renderSearch()} <ListFiltersAdd className="ListHeader__filter" /> <ListColumnsForm className="ListHeader__columns" /> <ListDownloadForm className="ListHeader__download" /> <InputGroup.Section className="ListHeader__expand"> <Button isActive={!this.state.constrainTableWidth} onClick={this.toggleTableWidth} title="Expand table width"> <span className="octicon octicon-mirror" /> </Button> </InputGroup.Section> {this.renderCreateButton()} </InputGroup> <ListFilters /> <div style={{ height: 34, marginBottom: '2em' }}> {this.renderManagement()} {this.renderPagination()} <span style={{ clear: 'both', display: 'table' }} /> </div> </Container> </div> ); }, // ============================== // TABLE // ============================== checkTableItem (item, e) { e.preventDefault(); let newCheckedItems = { ...this.state.checkedItems }; let itemId = item.id; if (this.state.checkedItems[itemId]) { delete newCheckedItems[itemId]; } else { newCheckedItems[itemId] = true; } this.setState({ checkedItems: newCheckedItems, }); }, checkAllTableItems () { let checkedItems = {}; this.state.items.results.forEach(item => { checkedItems[item.id] = true; }); this.setState({ checkedItems: checkedItems, }); }, uncheckAllTableItems () { this.setState({ checkedItems: {}, }); }, deleteTableItem (item, e) { if (e.altKey) { return CurrentListStore.deleteItem(item.id); } e.preventDefault(); this.setState({ confirmationDialog: { isOpen: true, label: 'Delete', body: `Are you sure you want to delete <strong>${item.name}</strong>?<br /><br />This cannot be undone.`, onConfirmation: () => { CurrentListStore.deleteItem(item.id); this.removeConfirmationDialog(); } } }); }, removeConfirmationDialog () { this.setState({ confirmationDialog: { isOpen: false } }); }, toggleTableWidth () { this.setState({ constrainTableWidth: !this.state.constrainTableWidth, }); }, // ============================== // COMMON // ============================== toggleCreateModal (visible) { this.setState({ showCreateForm: visible, }); }, renderBlankStateCreateButton () { var props = { type: 'success' }; if (this.state.list.nocreate) return null; if (this.state.list.autocreate) { props.href = '?new' + this.props.csrfQuery; } else { props.onClick = () => this.toggleCreateModal(true); } return ( <Button {...props}> <span className="octicon octicon-plus" /> Create {this.state.list.singular} </Button> ); }, renderBlankState () { if (!this.state.showBlankState) return null; return ( <Container> <FlashMessages messages={this.props.messages} /> <BlankState style={{ marginTop: 40 }}> <BlankState.Heading>No {this.state.list.plural.toLowerCase()} found&hellip;</BlankState.Heading> {this.renderBlankStateCreateButton()} </BlankState> </Container> ); }, renderActiveState () { if (this.state.showBlankState) return null; let containerStyle = { transition: 'max-width 160ms ease-out', msTransition: 'max-width 160ms ease-out', MozTransition: 'max-width 160ms ease-out', WebkitTransition: 'max-width 160ms ease-out', }; if (!this.state.constrainTableWidth) containerStyle['maxWidth'] = '100%'; return ( <div> {this.renderHeader()} <Container style={containerStyle}> <FlashMessages messages={this.props.messages} /> <ItemsTable deleteTableItem={this.deleteTableItem} list={this.state.list} columns={this.state.columns} items={this.state.items} manageMode={this.state.manageMode} checkedItems={this.state.checkedItems} rowAlert={this.state.rowAlert} checkTableItem={this.checkTableItem} /> {this.renderNoSearchResults()} </Container> </div> ); }, renderNoSearchResults () { if (this.state.items.results.length) return null; let matching = this.state.search; if (this.state.filters.length) { matching += (matching ? ' and ' : '') + plural(this.state.filters.length, '* filter', '* filters'); } matching = matching ? ' found matching ' + matching : '.'; return ( <BlankState style={{ marginTop: 20, marginBottom: 20 }}> <span className="octicon octicon-search" style={{ fontSize: 32, marginBottom: 20 }} /> <BlankState.Heading>No {this.state.list.plural.toLowerCase()}{matching}</BlankState.Heading> </BlankState> ); }, render () { return !this.state.ready ? ( <div className="view-loading-indicator"><Spinner size="md" /></div> ) : ( <div className="keystone-wrapper"> <header className="keystone-header"> <MobileNavigation brand={this.props.brand} currentListKey={this.state.list.path} currentSectionKey={this.props.nav.currentSection.key} sections={this.props.nav.sections} signoutUrl={this.props.signoutUrl} /> <PrimaryNavigation brand={this.props.brand} currentSectionKey={this.props.nav.currentSection.key} sections={this.props.nav.sections} signoutUrl={this.props.signoutUrl} /> <SecondaryNavigation currentListKey={this.state.list.path} lists={this.props.nav.currentSection.lists} /> </header> <div className="keystone-body"> {this.renderBlankState()} {this.renderActiveState()} </div> <Footer appversion={this.props.appversion} backUrl={this.props.backUrl} brand={this.props.brand} User={this.props.User} user={this.props.user} version={this.props.version} /> <CreateForm err={this.props.createFormErrors} isOpen={this.state.showCreateForm} list={this.state.list} onCancel={() => this.toggleCreateModal(false)} values={this.props.createFormData} /> <UpdateForm isOpen={this.state.showUpdateForm} itemIds={Object.keys(this.state.checkedItems)} list={this.state.list} onCancel={() => this.toggleUpdateModal(false)} /> {this.renderConfirmationDialog()} </div> ); } }); ReactDOM.render( <ListView appversion={Keystone.appversion} backUrl={Keystone.backUrl} brand={Keystone.brand} createFormData={Keystone.createFormData} createFormErrors={Keystone.createFormErrors} csrfQuery={Keystone.csrf.query} messages={Keystone.messages} nav={Keystone.nav} signoutUrl={Keystone.signoutUrl} user={Keystone.user} User={Keystone.User} version={Keystone.version} />, document.getElementById('list-view') );
lib/src/linesofcode.js
SerendpityZOEY/Solr-Search-React-UI
/** * Created by yue on 2/13/17. */ import React from 'react'; import {List, ListItem, NestedList} from 'material-ui/List'; import FontIcon from 'material-ui/FontIcon'; const styles = { codeSnippet: { fontFamily: "Fira Mono", fontSize: 14 }, } class Lines extends React.Component{ constructor(props){ super(props); this.state={ openMenu: false } } handleClick(val) { console.log(val); //if the prev editor is empty, remove the empty line in the next editor if(this.props.newCode.length==0){ this.props.onAddBtnClick('// =>'+val.substr(1).trim()); }else{ this.props.onAddBtnClick(this.props.newCode+'\n'+'// =>'+val.substr(1).trim()); } this.setState({ openMenu: true, }); } render(){ var diffcontent = this.props.diffcontent; var contents = this.props.content; var callsiteEntered = this.props.callsiteEntered; var importEntered = this.props.importEntered; var res = diffcontent.split("\n").map(function(i, index) { //method highlighting if(callsiteEntered!=''){ for(var item=0;item<callsiteEntered.length;item++){ var customizeMethod = '.'+callsiteEntered[item]+'('; if(i.indexOf(customizeMethod) > -1){ //extract the method form line var start = i.indexOf(callsiteEntered[item]); var end = start+callsiteEntered[item].length; var word = i.substring(start, end); //this is exactly what highlight function above does i = i.substring(0,i.indexOf(word))+'<mark>'+i.substring(i.indexOf(word), i.indexOf(word)+word.length)+'</mark>'+ i.substring(i.indexOf(word)+word.length); //if line has color if(i.match(/^\+/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor:'#c8e6c9',marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: i}}></code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> if(i.match(/^\-/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor:'#ffcdd2',marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: i}}></code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> return <ListItem key={index} primaryText={ <pre style={{marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: i}}></code></pre>} innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> } } } //import highlighting if(importEntered!=''){ for(item=0;item<importEntered.length;item++){ if(i.indexOf(importEntered[item]) > -1){ start = i.indexOf(importEntered[item]); end = start+importEntered[item].length; word = i.substring(start, end); i = i.substring(0,i.indexOf(word))+'<mark>'+i.substring(i.indexOf(word), i.indexOf(word)+word.length)+'</mark>'+ i.substring(i.indexOf(word)+word.length); //if line has color if(i.match(/^\+/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor: '#c8e6c9', marginTop: 0, marginBottom: 0}}> <code dangerouslySetInnerHTML={{__html: i}}></code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> if(i.match(/^\-/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor:'#ffcdd2',marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: i}}></code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> return <ListItem key={index} primaryText={ <pre style={{marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: i}}></code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> } } } if(i.match(/^\+/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor:'#c8e6c9',marginTop:0,marginBottom:0}}><code>{i}</code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> if(i.match(/^\-/)) return <ListItem key={index} primaryText={ <pre style={{backgroundColor:'#ffcdd2',marginTop:0,marginBottom:0}}><code>{i}</code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> if(i.includes('@@')){ var part2 = i.split('@@')[1]; var expand = '@@'+part2+'@@'; var endLine = part2.substr(part2.indexOf('+')+1,part2.indexOf(',')-2); var beginLine = diffcontent.split("\n")[index-3]; if(beginLine === ' ') beginLine = diffcontent.split("\n")[index-2]; var token = contents.split('\n').indexOf(beginLine.substr(1)); var res = [] for(var ind=token+3;ind<endLine-1;ind++){ res.push(contents.split('\n')[ind]) } var nestedRes = res.join('\n'); return <ListItem key={index} primaryText={ <pre style={{color:'#9e9e9e',marginTop:0,marginBottom:0}}><code> <FontIcon className="fa fa-expand" style={{fontSize:14}} />{expand} </code></pre> } nestedItems={[ <pre style={{marginTop:0,marginBottom:0,color:'#9e9e9e'}}><code> {nestedRes}</code></pre> ]} innerDivStyle={{padding:0}} style={styles.codeSnippet} /> } else return <ListItem key={index} primaryText={ <pre style={{marginTop:0,marginBottom:0}}><code>{i}</code></pre> } innerDivStyle={{padding:0}} style={styles.codeSnippet} onClick={() => this.handleClick(i)} /> }, this); return <div>{res}</div> } } export default Lines;
frontend/jest_mocks/createComponentWithIntl.js
RyanNoelk/OpenEats
import React from 'react'; import renderer from 'react-test-renderer'; import { IntlProvider } from 'react-intl'; // See: https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#jest const createComponentWithIntl = (children, props = { locale: 'en' }) => { return renderer.create( <IntlProvider {...props}> {children} </IntlProvider> ); }; export default createComponentWithIntl;
client/src/components/StepByStep.js
codefordenver/Circular
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import { Row, Col, Grid } from 'react-bootstrap'; import Steps from './HowItWorks/Steps'; import HowItWorksStepHeaderContent from './HowItWorks/HowItWorksStepHeaderContent'; import HowItWorksStepContent from './HowItWorks/HowItWorksStepContent'; const shortStepsData = [ { title: 'Create or Join a Campaign', icon: <i className="fa fa-bullhorn how-icon" />, content: [ { div: ( <p> Look up your address{' '} <Link className="more-step-details-link" to={{ pathname: 'how-does-this-work', state: { currentStep: 0 } }} > {' '} here{' '} </Link>{' '} to create a new recycling campaign for your building or join an existing one! </p> ) } ] }, { title: 'Recruit Your Neighbors', icon: <i className="fa fa-users how-icon" />, content: [ { p: 'We provide you with the resources to gather the support of your building community.' } ] }, { title: 'Request Recyling From Your Landlord', icon: <i className="fa fa-comment how-icon" />, content: [ { p: 'Submit your petition for recycling to your landlord and hope for the best!' } ] }, { title: 'Recycle!', icon: <i className="fa fa-recycle how-icon" />, content: [ { p: "That's it! Hopefully your landlord agrees to provide recycling services for you and " + 'your community. Enjoy your convenient recycling!' } ] } ]; const HowItWorksVerticalStep = ({ title, icon, content, stepIndex }) => ( <div className="inner-content-container"> <div> <HowItWorksStepHeaderContent title={title} icon={icon} stepIndex={stepIndex} priority={3} stacked={false} /> <HowItWorksStepContent content={content} /> </div> <Link className="more-step-details-link" to={{ pathname: 'how-does-this-work', state: { currentStep: stepIndex } }} > More Details </Link> </div> ); HowItWorksVerticalStep.defaultProps = { icon: null }; HowItWorksVerticalStep.propTypes = { title: PropTypes.string.isRequired, icon: PropTypes.node, content: PropTypes.arrayOf(PropTypes.shape({})).isRequired, stepIndex: PropTypes.number.isRequired }; const StepByStep = () => { const steps = shortStepsData.map((stepData, index) => { const data = { ...stepData, stepIndex: index }; return { content: <HowItWorksVerticalStep {...data} /> }; }); return ( <Grid fluid className="step-by-step-container"> <Row className="tinted"> <Col xs={12} lg={10} lgOffset={1}> <h2 className="home-section-title">HOW DOES THIS WORK?</h2> </Col> </Row> <Row className="tinted"> <Col xs={12} lg={10} lgOffset={1} className="pad-bottom"> <Steps vertical pulseNextStep autoSlide height={400} steps={steps} /> </Col> </Row> </Grid> ); }; export default StepByStep;
docs/src/app/components/pages/components/Tabs/Page.js
lawrence-yu/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 tabsReadmeText from './README'; import tabsExampleSimpleCode from '!raw!./ExampleSimple'; import TabsExampleSimple from './ExampleSimple'; import tabsExampleControlledCode from '!raw!./ExampleControlled'; import TabsExampleControlled from './ExampleControlled'; import tabsExampleSwipeableCode from '!raw!./ExampleSwipeable'; import TabsExampleSwipeable from './ExampleSwipeable'; import tabsExampleIconCode from '!raw!./ExampleIcon'; import TabsExampleIcon from './ExampleIcon'; import tabsExampleIconTextCode from '!raw!./ExampleIconText'; import TabsExampleIconText from './ExampleIconText'; import tabsCode from '!raw!material-ui/Tabs/Tabs'; import tabCode from '!raw!material-ui/Tabs/Tab'; const descriptions = { simple: 'A simple example of Tabs. The third tab demonstrates the `onActive` property of `Tab`.', controlled: 'An example of controlled tabs. The selected tab is handled through state and callbacks in the parent ' + '(example) component.', swipeable: 'This example integrates the [react-swipeable-views]' + '(https://github.com/oliviertassinari/react-swipeable-views) component with Tabs, animating the Tab transition, ' + 'and allowing tabs to be swiped on touch devices.', icon: 'An example of tabs with icon.', iconText: 'An example of tabs with icon and text.', }; const TabsPage = () => ( <div> <Title render={(previousTitle) => `Tabs - ${previousTitle}`} /> <MarkdownElement text={tabsReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={tabsExampleSimpleCode} > <TabsExampleSimple /> </CodeExample> <CodeExample title="Controlled example" description={descriptions.controlled} code={tabsExampleControlledCode} > <TabsExampleControlled /> </CodeExample> <CodeExample title="Swipeable example" description={descriptions.swipeable} code={tabsExampleSwipeableCode} > <TabsExampleSwipeable /> </CodeExample> <CodeExample title="Icon example" description={descriptions.icon} code={tabsExampleIconCode} > <TabsExampleIcon /> </CodeExample> <CodeExample title="Icon and text example" description={descriptions.iconText} code={tabsExampleIconTextCode} > <TabsExampleIconText /> </CodeExample> <PropTypeDescription code={tabsCode} header="### Tabs Properties" /> <PropTypeDescription code={tabCode} header="### Tab Properties" /> </div> ); export default TabsPage;
blueprints/smart/files/__root__/containers/__name__/__name__.js
murrayjbrown/react-redux-rxjs-stampit-babylon-universal
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' type Props = { } export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return {} } export default connect( mapStateToProps, mapDispatchToProps )(<%= pascalEntityName %>)
src/app/components/tooltipQuestion.js
benigeri/soapee-ui
import React from 'react'; import { Tooltip, OverlayTrigger } from 'react-bootstrap'; export default React.createClass( { getDefaultProps() { return { placement: 'left' }; }, render() { const tooltip = ( <Tooltip>{ this.props.children }</Tooltip> ); return ( <span className="tooltip-question"> <OverlayTrigger placement={ this.props.placement } overlay={ tooltip }> <i className="fa fa-question-circle"></i> </OverlayTrigger> </span> ); } } );
graphwalker-studio/src/main/js/components/configpanel/element-group.js
GraphWalker/graphwalker-project
import React, { Component } from 'react'; import { connect } from "react-redux"; import { FormGroup, InputGroup, Switch, TextArea } from "@blueprintjs/core"; import { updateElement, setStartElement } from "../../redux/actions"; import Group from "./group"; class ElementGroup extends Component { render() { const { id, name, sharedState, guard, weight, actions, requirements, updateElement, isStartElement, setStartElement, isVertex, disabled } = this.props; return ( <Group name="Element" isOpen={true}> <FormGroup label="Name" disabled={disabled}> <InputGroup disabled={disabled} value={name} onChange={({ target: { value }}) => updateElement('name', value ? value : undefined)}/> </FormGroup> <FormGroup label="Shared Name" disabled={disabled || !isVertex}> <InputGroup disabled={disabled || !isVertex} value={sharedState} onChange={({ target: { value }}) => updateElement('sharedState', value ? value : undefined)}/> </FormGroup> <FormGroup label="Guard" disabled={disabled || isVertex}> <InputGroup disabled={disabled || isVertex} value={guard} onChange={({ target: { value }}) => updateElement('guard', value ? value : undefined)}/> </FormGroup> <FormGroup label="Weight" disabled={disabled || isVertex}> <InputGroup disabled={disabled || isVertex} value={weight} onChange={({ target: { value }}) => updateElement('weight', value ? value : undefined)}/> </FormGroup> <FormGroup label="Actions" disabled={disabled}> <div className="bp3-input-group"> <TextArea disabled={disabled} value={actions.join("\n")} onChange={({ target: { value }}) => updateElement('actions', value ? value.split("\n") : undefined)}/> </div> </FormGroup> <FormGroup label="Requirements" disabled={disabled}> <div className="bp3-input-group"> <TextArea disabled={disabled} value={requirements.join("\n")} onChange={({ target: { value }}) => updateElement('requirements', value ? value.split("\n") : undefin)}/> </div> </FormGroup> <Switch disabled={disabled} label="Start element" checked={isStartElement} onChange={({ target: { checked }}) => setStartElement(id)}/> </Group> ) } } const mapStateToProps = ({ test: { models, selectedModelIndex, selectedElementId }}) => { const model = models[selectedModelIndex]; const elements = [...model.vertices, ...model.edges]; const isVertex = model.vertices.filter( e => e.id == selectedElementId).length == 1; const element = elements.filter(element => element.id === selectedElementId)[0] || {}; const { id = "", name = "", sharedState = "", guard = "", weight = "", actions = [], requirements = [] } = element; return { id, name, sharedState, guard, weight, actions, requirements, isStartElement: model.startElementId === selectedElementId, isVertex, disabled: selectedElementId === null } }; export default connect(mapStateToProps, { updateElement, setStartElement })(ElementGroup);
lib/components/App.js
LeooRamalho/react-advanced
import React from 'react'; import ArticleList from './ArticleList'; class App extends React.Component { state = this.props.store.getState(); render() { return ( <ArticleList articles={this.state.articles} store={this.props.store} /> ); } } export default App;
app/src/components/character.js
bhayden1/savageReact
import {Component} from 'react'; import React from 'react'; export class Character extends Component { render() { return( <div className="row item"> <div className="col col-33">{this.props.name}</div> <div className="col">{this.props.toughness}</div> <div className="col">{this.props.armor}</div> <div className="col">{this.props.overflow}</div> <div className="col">{this.props.wounds}</div> </div> ); } }
html.js
Bubblbu/this-and-that
import React from 'react' import Helmet from 'react-helmet' import { prefixLink } from 'gatsby-helpers' const BUILD_TIME = new Date().getTime() module.exports = React.createClass({ displayName: 'HTML', propTypes: { body: React.PropTypes.string, }, render() { const {body, route} = this.props const {title} = Helmet.rewind() const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' /> let css if (process.env.NODE_ENV === 'production') { css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } /> } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" /> { title.toComponent() } { font } { css } </head> <body> <div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } /> <script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } /> </body> </html> ) }, })
src/index.js
Darmody/DoubanFMac
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; require('electron-cookies'); const store = configureStore(); render( <Provider store={store}> <Router history={hashHistory}> {routes(store)} </Router> </Provider>, document.getElementById('root') ); if (process.env.NODE_ENV !== 'production') { // Use require because imports can't be conditional. // In production, you should ensure process.env.NODE_ENV // is envified so that Uglify can eliminate this // module and its dependencies as dead code. // require('./createDevToolsWindow')(store); }
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Files/js/components/redundancystatus.js
patel344/Mr.Miner
import PropTypes from 'prop-types' import React from 'react' const colorNotAvailable = '#FF8080' const colorGoodRedundancy = '#00CBA0' const RedundancyStatus = ({available, redundancy, uploadprogress}) => { const indicatorStyle = { opacity: (() => { if (!available || redundancy < 1.0) { return 1 } if (uploadprogress > 100) { return 1 } return uploadprogress/100 })(), color: (() => { if (!available || redundancy < 1.0) { return colorNotAvailable } return colorGoodRedundancy })(), } return ( <div className="redundancy-status"> <i className="fa fa-cubes" style={indicatorStyle} /> <span className="redundancy-text">{redundancy > 0 ? redundancy + 'x' : '--'}</span> </div> ) } RedundancyStatus.propTypes = { available: PropTypes.bool.isRequired, redundancy: PropTypes.number.isRequired, uploadprogress: PropTypes.number.isRequired, } export default RedundancyStatus
client/js/components/Layout/Resolution.js
akamaurizio/new-year-resos
import React from 'react'; export default class Resolution extends React.Component{ render(){ const {title, desc} = this.props return( <div className="col-md-4"> <div className="resolution card"> <h2 className="resolution-title">{title}</h2> <p>{desc}</p> </div> </div> ) } }
src/components/big_timer.js
adamakers/Scoreboard
import React from 'react'; import styles from './../styles/big_timer.css'; const GameClock = (props) => { return ( <div className="timer-container"> <h1 className="timer-time">{props.gameClock}</h1> {/* Enter game time here. Needs to be updated with a timer*/} <h3 className="timer-quarter">QTR <span>4</span></h3> </div> ); } export default GameClock;
Ch04/04_01/start/src/index.js
Raziyehbazargan/React.js_Essential_Training
import React from 'react' import { render } from 'react-dom' import { SkiDayList } from './components/ski-day-list' // import { SkiDayCount } from './components/SkiDayCount-createClass' // import { SkiDayCount } from './components/SkiDayCount-ES6' //import { SkiDayCount } from './components/SkiDayCount' import { App } from './components/app' window.React = React // render( // <SkiDayCount />, // document.getElementById('react-container') // ) render( <App />, document.getElementById('react-container') )
src/stories/index.js
danialm/backgammon
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import fetchMock from 'fetch-mock'; import { Button, Welcome } from '@storybook/react/demo'; import Dice from '../components/Dice'; import Profile from '../components/Profile'; import '../css/index.css'; import '../css/App.css'; storiesOf('Dice', module) .add('6 6', () => <Dice die1={6} die2={6} />) .add('1 2', () => <Dice die1={1} die2={2} />) .add('4 7', () => <Dice die1={4} die2={7} />) .add('0 0', () => <Dice die1={0} die2={0} />); class ProfileWrapper extends React.Component { constructor(props) { super(props); this.state = { user: {} }; } render() { return ( <Profile user={this.state.user} fetchSelf={ () => this.setState({ user: { name: "dan", email: "dan@email.com" } }) } onChange={ (user) => this.setState({ user: user }) } {...this.props} />); } } storiesOf('Profile', module) .add( 'Dan Profile', () => { fetchMock .mock( (url, { method }) => { return url === 'http://localhost:3000/api/v1/users/me' && method === 'PATCH'; }, { id: 1, name: "updated name", email: "updated email", created_at: "2017-08-30T19:09:16.428Z" }, ); return ( <ProfileWrapper changePasswordHandler={action("changePassword")} store={{ getState: () => {}, dispatch: () => console.log("dispatch") }} /> ); });
src/Icon.js
15lyfromsaturn/react-materialize
import React from 'react'; import constants from './constants'; import cx from 'classnames'; class Icon extends React.Component { render() { let classes = { 'material-icons': true }; constants.PLACEMENTS.forEach(p => { classes[p] = this.props[p]; }); constants.ICON_SIZES.forEach(s => { classes[s] = this.props[s]; }); return <i className={cx(classes, this.props.className)}>{this.props.children}</i>; } } Icon.propTypes = { tiny: React.PropTypes.bool, small: React.PropTypes.bool, medium: React.PropTypes.bool, large: React.PropTypes.bool }; export default Icon;
packages/component/src/text-field-macro.js
Pinecast/encoder
import React from 'react'; export default (inputProps) => <label> <span>{inputProps.title}</span> <input {...inputProps} type='text' /> </label>;
actor-apps/app-web/src/app/components/dialog/messages/Text.react.js
jamesbond12/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import _ from 'lodash'; import React from 'react'; import memoize from 'memoizee'; import emojify from 'emojify.js'; import emojiCharacters from 'emoji-named-characters'; import { Path } from 'constants/ActorAppConstants'; import ActorClient from 'utils/ActorClient'; const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character)); emojify.setConfig({ mode: 'img', img_dir: Path.toEmoji // eslint-disable-line }); const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), (name) => name.replace(/\+/g, '\\+')); const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi'); const processText = function (text) { const markedText = ActorClient.renderMarkdown(text); // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127 const noPTag = markedText.replace(/<p>/g, '<p> '); let emojifiedText = emojify .replace(noPTag.replace(emojiRegexp, (match) => `:${inversedEmojiCharacters[match]}:`)); return emojifiedText; }; const memoizedProcessText = memoize(processText, { length: 1000, maxAge: 60 * 60 * 1000, max: 10000 }); class Text extends React.Component { static propTypes = { content: React.PropTypes.object.isRequired, className: React.PropTypes.string }; constructor(props) { super(props); } render() { const { content, className } = this.props; const renderedContent = ( <div className={className} dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}> </div> ); return renderedContent; } } export default Text;
src/svg-icons/image/picture-as-pdf.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePictureAsPdf = (props) => ( <SvgIcon {...props}> <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5v3zm4-3H19v1h1.5V11H19v2h-1.5V7h3v1.5zM9 9.5h1v-1H9v1zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm10 5.5h1v-3h-1v3z"/> </SvgIcon> ); ImagePictureAsPdf = pure(ImagePictureAsPdf); ImagePictureAsPdf.displayName = 'ImagePictureAsPdf'; ImagePictureAsPdf.muiName = 'SvgIcon'; export default ImagePictureAsPdf;
src/Breadcrumbs/Breadcrumbs.component.js
Talend/react-talend-components
import React from 'react'; import { Button } from 'react-bootstrap'; import classNames from 'classnames'; import uuid from 'uuid'; import theme from './Breadcrumbs.scss'; import { ActionDropdown } from '../Actions'; /** * Default max items to display without starting by ellipsis */ const DEFAULT_MAX_ITEMS = 3; /** * Indicate the current page's location within a navigational hierarchy. * @param {object} props react props * @example <Breadcrumbs maxItems={3} items={items} /> */ function Breadcrumbs(props) { const items = props.items || []; const nbItems = items.length; const maxItemsToDisplay = props.maxItems || DEFAULT_MAX_ITEMS; const maxItemsReached = nbItems > maxItemsToDisplay; const ellipsisIndex = (nbItems - 1) - maxItemsToDisplay; const hiddenItems = items.slice(0, ellipsisIndex + 1) .map((hiddenItem, index) => ( { id: `${props.id}-item-${index}`, label: hiddenItem.text, title: hiddenItem.title, onClick: event => hiddenItem.onClick(event, hiddenItem), }) ); /** * Render breadcrumb item * @param item Plain object representative of breadcrumb item * @param index Item position * @returns {*} Breadcrumb item rendering depending of its position */ const renderBreadcrumbItem = (item, index) => { const { text, title, onClick } = item; const isActive = index === (nbItems - 1); const id = `${props.id}-item-${index}`; /** * Wrapper for onClick in order to return item * @param args Arguments of default onClick callback * @returns {Function} New callback with the item */ let wrappedOnClick; if (onClick) { wrappedOnClick = event => onClick(event, item); } if (maxItemsReached && index < ellipsisIndex) { return ( <li className="sr-only" key={index}> {onClick ? <Button id={id} bsStyle="link" role="link" title={title} onClick={wrappedOnClick} >{text}</Button> : <span>{text}</span> } </li> ); } if (maxItemsReached && index === ellipsisIndex) { return ( <li className={classNames(theme.dots)} key={index} aria-hidden="true"> <ActionDropdown id={`${props.id}-ellipsis`} items={hiddenItems} label="&hellip;" link noCaret /> </li> ); } return ( <li className={isActive ? 'active' : ''} key={index}> {(!isActive && onClick) ? <Button id={id} bsStyle="link" role="link" title={title} onClick={wrappedOnClick} >{text}</Button> : <span id={id}>{text}</span> } </li> ); }; return ( <ol id={props.id} className={classNames('breadcrumb', theme['tc-breadcrumb'], 'tc-breadcrumb')}> {items.map(renderBreadcrumbItem)} </ol> ); } Breadcrumbs.propTypes = { id: React.PropTypes.string, items: React.PropTypes.arrayOf( React.PropTypes.shape({ text: React.PropTypes.string.isRequired, title: React.PropTypes.string, onClick: React.PropTypes.func, }) ), maxItems: React.PropTypes.number, }; Breadcrumbs.defaultProps = { id: `${uuid.v4()}`, }; export default Breadcrumbs;
fields/types/date/DateFilter.js
Redmart/keystone
import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import moment from 'moment'; import DayPicker from 'react-day-picker'; import { FormField, FormInput, FormRow, FormSelect, SegmentedControl } from 'elemental'; const TOGGLE_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true } ]; const MODE_OPTIONS = [ { label: 'On', value: 'on' }, { label: 'After', value: 'after' }, { label: 'Before', value: 'before' }, { label: 'Between', value: 'between' } ]; var DayPickerIndicator = React.createClass({ render () { return ( <span className="DayPicker-Indicator"> <span className="DayPicker-Indicator__border" /> <span className="DayPicker-Indicator__bg" /> </span> ); } }); function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, inverted: TOGGLE_OPTIONS[0].value, value: moment(0, 'HH').format(), before: moment(0, 'HH').format(), after: moment(0, 'HH').format() }; } var DateFilter = React.createClass({ displayName: 'DateFilter', statics: { getDefaultValue: getDefaultValue, }, propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), inverted: React.PropTypes.boolean }) }, getInitialState () { return { activeInputField: 'after', month: new Date() // The month to display in the calendar }; }, getDefaultProps () { return { format: 'DD-MM-YYYY', filter: getDefaultValue(), value: moment().startOf('day').toDate() }; }, componentDidMount () { // focus the text input if (this.props.filter.mode === 'between') { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, toggleInverted (value) { this.updateFilter({ inverted: value }); ReactDOM.findDOMNode(this.refs.input).focus(); }, selectMode (mode) { this.updateFilter({ mode }); if (mode === 'between') { setTimeout(() => { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); },200); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, handleInputChange(e) { const { value } = e.target; let { month } = this.state; // Change the current month only if the value entered by the user is a valid // date, according to the `L` format if (moment(value, 'L', true).isValid()) { month = moment(value, 'L').toDate(); } this.updateFilter({ value: value }); this.setState({ month }, this.showCurrentDate); }, setActiveField (field) { this.setState({ activeInputField: field }); }, switchBetweenActiveInputFields (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; const { activeInputField } = this.state; let send = {}; send[activeInputField] = day; this.updateFilter(send); const newActiveField = ( activeInputField === 'before' ) ? 'after' : 'before'; this.setState( { activeInputField: newActiveField }, () => { ReactDOM.findDOMNode(this.refs[newActiveField]).focus(); } ); }, selectDay (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; this.updateFilter({ value: day }); }, showCurrentDate() { this.refs.daypicker.showMonth(this.state.month); }, renderToggle () { const { filter } = this.props; return ( <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={filter.inverted} onChange={this.toggleInverted} /> </FormField> ); }, renderControls () { let controls; const { field, filter } = this.props; const mode = MODE_OPTIONS.filter((i => i.value === filter.mode))[0]; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; // DayPicker stuff const modifiers = { 'selected': (day) => moment(filter.value).isSame(day) }; if (mode.value === 'between') { controls = ( <div> <FormRow> <FormField width="one-half"> <FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} /> </FormField> <FormField width="one-half"> <FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} /> </FormField> </FormRow> <div style={{ position: 'relative' }}> <DayPicker modifiers={ modifiers } className="DayPicker--chrome" onDayClick={ this.switchBetweenActiveInputFields } /> <DayPickerIndicator /> </div> </div> ); } else { controls = ( <div> <FormField> <FormInput ref="input" placeholder={placeholder} value={moment(filter.value).format(this.props.format)} onChange={this.handleInputChange} onFocus={this.showCurrentDate} /> </FormField> <div style={{ position: 'relative' }}> <DayPicker ref="daypicker" modifiers={ modifiers } className="DayPicker--chrome" onDayClick={this.selectDay} /> <DayPickerIndicator /> </div> </div> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter((i => i.value === filter.mode))[0]; return ( <div> {this.renderToggle()} <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} /> {this.renderControls()} </div> ); } }); module.exports = DateFilter;
examples/shopping-cart/src/components/App.js
usirin/nuclear-js
'use strict'; import React from 'react' import CartContainer from './CartContainer' import ProductsContainer from './ProductsContainer' export default React.createClass({ render() { return ( <div> <ProductsContainer /> <CartContainer /> </div> ); } });
docs/app/Examples/views/Item/Types/Items.js
ben174/Semantic-UI-React
import React from 'react' import { Image, Item } from 'semantic-ui-react' const Items = () => ( <Item.Group> <Item> <Item.Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' /> <Item.Content> <Item.Header as='a'>Header</Item.Header> <Item.Meta>Description</Item.Meta> <Item.Description> <Image src='http://semantic-ui.com/images/wireframe/short-paragraph.png' /> </Item.Description> <Item.Extra>Additional Details</Item.Extra> </Item.Content> </Item> <Item> <Item.Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' /> <Item.Content> <Item.Header as='a'>Header</Item.Header> <Item.Meta>Description</Item.Meta> <Item.Description> <Image src='http://semantic-ui.com/images/wireframe/short-paragraph.png' /> </Item.Description> <Item.Extra>Additional Details</Item.Extra> </Item.Content> </Item> </Item.Group> ) export default Items
src/routes/Timetable/components/Emoji/Emoji.js
BloomerWD/timetable
import React, { Component } from 'react'; const Emojies = [ <span className="icon-emoji-cool"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="path4"></span><span className="path5"></span><span className="path6"></span><span className="path7"></span><span className="path8"></span><span className="path9"></span></span>, <span className="icon-emoji-smile"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="path4"></span><span className="path5"></span><span className="path6"></span><span className="path7"></span><span className="path8"></span><span className="path9"></span><span className="path10"></span></span>, <span className="icon-emoji-smile-1"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="path4"></span><span className="path5"></span><span className="path6"></span><span className="path7"></span><span className="path8"></span></span>, <span className="icon-emoji-vomiting"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="path4"></span><span className="path5"></span><span className="path6"></span><span className="path7"></span><span className="path8"></span><span className="path9"></span><span className="path10"></span><span className="path11"></span><span className="path12"></span><span className="path13"></span><span className="path14"></span><span className="path15"></span><span className="path16"></span><span className="path17"></span><span className="path18"></span><span className="path19"></span></span>, <span className="icon-emoji-wink"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="path4"></span><span className="path5"></span><span className="path6"></span><span className="path7"></span><span className="path8"></span></span> ]; const randomInteger = (min, max) => { return Math.floor(min + Math.random() * (max + 1 - min)); } export default () => { return (Emojies[randomInteger(0, 4)]); }
app/jsx/new_user_tutorial/trays/HomeTray.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import I18n from 'i18n!new_user_tutorial' import TutorialTrayContent from './TutorialTrayContent' const HomeTray = () => ( <TutorialTrayContent name="Home" heading={I18n.t('Home')} subheading={I18n.t('Welcome your students')} image="/images/tutorial-tray-images/Panda_Home.svg" seeAllLink={{ label: I18n.t('See more in Canvas Guides'), href: `https://community.canvaslms.com/docs/DOC-10460- canvas-instructor-guide-table-of-contents#jive_content_id_Course_Navigation` }} links={[ { label: I18n.t('How do I use the Course Home Page as an instructor?'), href: 'https://community.canvaslms.com/docs/DOC-12947-4152724144' }, { label: I18n.t( 'What layout options are available in the Course Home Page as an instructor?' ), href: 'https://community.canvaslms.com/docs/DOC-12816-4152719700' }, { label: I18n.t('How do I change the Course Home Page?'), href: 'https://community.canvaslms.com/docs/DOC-13012-4152724499' } ]} > {I18n.t(`The Course Home Page is the first page students see when they open your course. The Home Page can display the course participation activity stream, the Course Modules page, the Course Assignments list, Syllabus, or a page you design as the front page.`)} </TutorialTrayContent> ) export default HomeTray
client/app/components/CalendarNavigation/index.js
puja1234/DTA
import React from 'react'; class CalendarNavigation extends React.Component{ constructor(props){ super(props); } backClick = () => { this.props.previousEvents(); }; nextClick = () => { this.props.nextEvents(); }; todayClick = () => { this.props.todayEvents(); }; render(){ return( <div> { this.props.month === new Date().getMonth() && this.props.title === 'next'? <button disabled={true}>{`>`}</button>: this.props.title === 'next' ? <button onClick={this.nextClick}>{`>`}</button> : <div> {this.props.title === 'back' ? <button onClick={this.backClick}>{`<`}</button> : <button onClick={this.todayClick}>Today</button> } </div> } </div> ) } }; export default CalendarNavigation;
src/client/index.js
brettsnaidero/bsd
/* eslint-disable global-require */ import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { CodeSplitProvider, rehydrateState } from 'code-split-component'; import ReactHotLoader from './components/ReactHotLoader'; import App from '../shared/components/App'; // Get the DOM Element that will host our React application. const container = document.querySelector('#app'); function renderApp(TheApp) { // We use the code-split-component library to provide us with code splitting // within our application. This library supports server rendered applications, // but for server rendered applications it requires that we rehydrate any // code split modules that may have been rendered for a request. We use // the provided helper and then pass the result to the CodeSplitProvider // instance which takes care of the rest for us. This is really important // to do as it will ensure that our React checksum for the client will match // the content returned by the server. // @see https://github.com/ctrlplusb/code-split-component rehydrateState().then(codeSplitState => render( <ReactHotLoader> <CodeSplitProvider state={codeSplitState}> <BrowserRouter> <TheApp /> </BrowserRouter> </CodeSplitProvider> </ReactHotLoader>, container, ), ); } // The following is needed so that we can support hot reloading our application. if (process.env.NODE_ENV === 'development' && module.hot) { // Accept changes to this file for hot reloading. module.hot.accept('./index.js'); // Any changes to our App will cause a hotload re-render. module.hot.accept( '../shared/components/App', () => renderApp(require('../shared/components/App').default), ); } // Execute the first render of our app. renderApp(App); // This registers our service worker for asset caching and offline support. // Keep this as the last item, just in case the code execution failed (thanks // to react-boilerplate for that tip.) require('./registerServiceWorker');
src/parser/priest/holy/modules/checklist/Component.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPELLS from 'common/SPELLS'; // import ITEMS from 'common/ITEMS'; import SpellLink from 'common/SpellLink'; // import ItemLink from 'common/ItemLink'; import ResourceLink from 'common/ResourceLink'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; import { TooltipElement } from 'common/Tooltip'; 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'; const HolyPriestChecklist = ({ combatant, castEfficiency, thresholds }) => { const AbilityRequirement = props => ( <GenericCastEfficiencyRequirement castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)} {...props} /> ); AbilityRequirement.propTypes = { spell: PropTypes.number.isRequired, }; return ( <Checklist> <Rule name="Use core abilities as often as possible" description={( <> Using your core abilities as often as possible will typically result in better performance, remember to <SpellLink id={SPELLS.SMITE.id} /> as often as you can! </> )} > <AbilityRequirement spell={SPELLS.HOLY_WORD_SERENITY.id} /> <AbilityRequirement spell={SPELLS.HOLY_WORD_SANCTIFY.id} /> <AbilityRequirement spell={SPELLS.PRAYER_OF_MENDING_CAST.id} /> {combatant.hasTalent(SPELLS.DIVINE_STAR_TALENT.id) && ( <AbilityRequirement spell={SPELLS.DIVINE_STAR_TALENT.id} /> )} {combatant.hasTalent(SPELLS.HALO_TALENT.id) && ( <AbilityRequirement spell={SPELLS.HALO_TALENT.id} /> )} {combatant.hasTalent(SPELLS.CIRCLE_OF_HEALING_TALENT.id) && ( <AbilityRequirement spell={SPELLS.CIRCLE_OF_HEALING_TALENT.id} /> )} </Rule> <Rule name="Use cooldowns effectively" description={( <> Cooldowns are an important part of healing, try to use them to counter fight mechanics. For example if a boss has burst damage every 3 minutes, <SpellLink id={SPELLS.DIVINE_HYMN_CAST.id} /> should be used to counter it. </> )} > <AbilityRequirement spell={SPELLS.GUARDIAN_SPIRIT.id} /> <AbilityRequirement spell={SPELLS.DIVINE_HYMN_CAST.id} /> <AbilityRequirement spell={SPELLS.DESPERATE_PRAYER.id} /> <AbilityRequirement spell={SPELLS.SYMBOL_OF_HOPE.id} /> {combatant.hasTalent(SPELLS.HOLY_WORD_SALVATION_TALENT.id) && ( <AbilityRequirement spell={SPELLS.HOLY_WORD_SALVATION_TALENT.id} /> )} {combatant.hasTalent(SPELLS.APOTHEOSIS_TALENT.id) && ( <AbilityRequirement spell={SPELLS.APOTHEOSIS_TALENT.id} /> )} {/* We can't detect race, so disable this when it has never been cast. */} {castEfficiency.getCastEfficiencyForSpellId(SPELLS.ARCANE_TORRENT_MANA1.id) && ( <AbilityRequirement spell={SPELLS.ARCANE_TORRENT_MANA1.id} /> )} </Rule> <Rule name="Try to avoid being inactive for a large portion of the fight" description={( <> High downtime is inexcusable, while it may be tempting to not cast and save mana, Holy's damage filler <SpellLink id={SPELLS.SMITE.id} /> is free. You can reduce your downtime by reducing the delay between casting spells, anticipating movement, moving during the GCD, and <TooltipElement content="You can ignore this while learning Holy, but contributing DPS whilst healing is a major part of becoming a better than average player.">when you're not healing try to contribute some damage.*</TooltipElement>. </> )} > <Requirement name="Non healing time" thresholds={thresholds.nonHealingTimeSuggestionThresholds} /> <Requirement name="Downtime" thresholds={thresholds.downtimeSuggestionThresholds} /> </Rule> <Rule name={<>Use all of your <ResourceLink id={RESOURCE_TYPES.MANA.id} /> effectively</>} description="If you have a large amount of mana left at the end of the fight that's mana you could have turned into healing. Try to use all your mana during a fight. A good rule of thumb is to try to match your mana level with the boss's health." > <Requirement name="Mana left" thresholds={thresholds.manaLeft} /> </Rule> <PreparationRule thresholds={thresholds} /> </Checklist> ); }; HolyPriestChecklist.propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; export default HolyPriestChecklist;
docs/server.js
chrishoage/react-bootstrap
/* eslint no-console: 0 */ import 'colors'; import React from 'react'; import express from 'express'; import path from 'path'; import Router from 'react-router'; import routes from './src/Routes'; import httpProxy from 'http-proxy'; import metadata from './generate-metadata'; import ip from 'ip'; const development = process.env.NODE_ENV !== 'production'; const port = process.env.PORT || 4000; let app = express(); if (development) { let proxy = httpProxy.createProxyServer(); let webpackPort = process.env.WEBPACK_DEV_PORT; let target = `http://${ip.address()}:${webpackPort}`; app.get('/assets/*', function(req, res) { proxy.web(req, res, { target }); }); proxy.on('error', function(e) { console.log('Could not connect to webpack proxy'.red); console.log(e.toString().red); }); console.log('Prop data generation started:'.green); metadata().then( props => { console.log('Prop data generation finished:'.green); app.use(function renderApp(req, res) { res.header('Access-Control-Allow-Origin', target); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); Router.run(routes, req.url, Handler => { let html = React.renderToString(<Handler assetBaseUrl={target} propData={props}/>); res.send('<!doctype html>' + html); }); }); }); } else { app.use(express.static(path.join(__dirname, '../docs-built'))); } app.listen(port, function() { console.log(`Server started at:`); console.log(`- http://localhost:${port}`); console.log(`- http://${ip.address()}:${port}`); });
node_modules/react-bootstrap/es/Collapse.js
NickingMeSpace/questionnaire
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import css from 'dom-helpers/style'; import React from 'react'; import PropTypes from 'prop-types'; import Transition from 'react-overlays/lib/Transition'; import capitalize from './utils/capitalize'; import createChainedFunction from './utils/createChainedFunction'; var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { node.offsetHeight; // eslint-disable-line no-unused-expressions } function getDimensionValue(dimension, elem) { var value = elem['offset' + capitalize(dimension)]; var margins = MARGINS[dimension]; return value + parseInt(css(elem, margins[0]), 10) + parseInt(css(elem, margins[1]), 10); } var propTypes = { /** * Show the component; triggers the expand or collapse animation */ 'in': PropTypes.bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: PropTypes.bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ transitionAppear: PropTypes.bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: PropTypes.number, /** * Callback fired before the component expands */ onEnter: PropTypes.func, /** * Callback fired after the component starts to expand */ onEntering: PropTypes.func, /** * Callback fired after the component has expanded */ onEntered: PropTypes.func, /** * Callback fired before the component collapses */ onExit: PropTypes.func, /** * Callback fired after the component starts to collapse */ onExiting: PropTypes.func, /** * Callback fired after the component has collapsed */ onExited: PropTypes.func, /** * The dimension used when collapsing, or a function that returns the * dimension * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own CSS animation for the `.width` CSS class._ */ dimension: PropTypes.oneOfType([PropTypes.oneOf(['height', 'width']), PropTypes.func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. */ getDimensionValue: PropTypes.func, /** * ARIA role of collapsible element */ role: PropTypes.string }; var defaultProps = { 'in': false, timeout: 300, mountOnEnter: false, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; var Collapse = function (_React$Component) { _inherits(Collapse, _React$Component); function Collapse(props, context) { _classCallCheck(this, Collapse); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleEnter = _this.handleEnter.bind(_this); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleEntered = _this.handleEntered.bind(_this); _this.handleExit = _this.handleExit.bind(_this); _this.handleExiting = _this.handleExiting.bind(_this); return _this; } /* -- Expanding -- */ Collapse.prototype.handleEnter = function handleEnter(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype.handleEntering = function handleEntering(elem) { var dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); }; Collapse.prototype.handleEntered = function handleEntered(elem) { var dimension = this._dimension(); elem.style[dimension] = null; }; /* -- Collapsing -- */ Collapse.prototype.handleExit = function handleExit(elem) { var dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; triggerBrowserReflow(elem); }; Collapse.prototype.handleExiting = function handleExiting(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype._dimension = function _dimension() { return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; }; // for testing Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) { return elem['scroll' + capitalize(dimension)] + 'px'; }; Collapse.prototype.render = function render() { var _props = this.props, onEnter = _props.onEnter, onEntering = _props.onEntering, onEntered = _props.onEntered, onExit = _props.onExit, onExiting = _props.onExiting, className = _props.className, props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']); delete props.dimension; delete props.getDimensionValue; var handleEnter = createChainedFunction(this.handleEnter, onEnter); var handleEntering = createChainedFunction(this.handleEntering, onEntering); var handleEntered = createChainedFunction(this.handleEntered, onEntered); var handleExit = createChainedFunction(this.handleExit, onExit); var handleExiting = createChainedFunction(this.handleExiting, onExiting); var classes = { width: this._dimension() === 'width' }; return React.createElement(Transition, _extends({}, props, { 'aria-expanded': props.role ? props['in'] : null, className: classNames(className, classes), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting })); }; return Collapse; }(React.Component); Collapse.propTypes = propTypes; Collapse.defaultProps = defaultProps; export default Collapse;
src/routes/Invoicer/PaymentDetails/index.js
joshhunt/money
import React, { Component } from 'react'; import styles from './styles.styl'; import Remarkable from 'remarkable'; const md = new Remarkable(); export default class PaymentDetails extends Component { constructor(props) { super(props); this.state = this.renderMarkdown(props, true) } componentWillReceiveProps(nextProps, force) { this.setState(this.renderMarkdown(nextProps)); } renderMarkdown(nextProps, force) { const state = {} if (force || nextProps.left !== this.props.left) { state.mdLeft = md.render(nextProps.left); } if (force || nextProps.right !== this.props.right) { state.mdRight = md.render(nextProps.right); } return state } render () { return ( <div className={styles.root}> <div className={styles.paymentInstructions} dangerouslySetInnerHTML={{__html: this.state.mdLeft}}></div> <div className={styles.paymentBank} dangerouslySetInnerHTML={{__html: this.state.mdRight}}></div> </div> ); } }
www/imports/mapPage/shortlist/ShortEntryPres_forBarCharts.js
terraswat/hexagram
// Presentational component for the short list entry. import React from 'react'; import PropTypes from 'prop-types'; //import Slider, { Range } from 'rc-slider'; // We can just import Slider or Range to reduce bundle size // import Slider from 'rc-slider/lib/Slider'; // import Range from 'rc-slider/lib/Range'; //import 'rc-slider/assets/index.css'; import BarChart from '/imports/mapPage/shortlist/BarChart' import Icon, { icons } from '/imports/component/Icon' import './shortEntry.css'; const filterIcon = (able) => { // Render the filter icon. if (able.indexOf('filtering') < 0) { return null } let widget = <Icon icon = 'filter' title = "Map is being filtered by this attribute's values" className = 'hot filter circle' /> return widget; } const renderMetadata = (able, metadata) => { // Render the metadata. if (able.indexOf('metadata') < 0) { return null } // TODO remove extra classes let widget = <table className = 'layer-metadata' > <tbody> { metadata.map((row, i) => <tr key = { i } > <td className = 'rightAlign' > { row[0] + ':' } </td> <td> { row[1] } </td> </tr> )} </tbody> </table> return widget } const barChart = (able) => { // Render a bar chart for discrete values. if (!able.includes('barChart')) { return null } let widget = <BarChart /> return widget } const histogram = (able) => { // Render a histogram for continuous values. if (!able.includes('historgram')) { return null } let widget = <Histogram /> return widget } const zeroTick = (able) => { // Render the zero tickmark. if (able.indexOf('zeroTick') < 0) { return null } let widget = <div className = 'zero_tick' > </div> return widget } const zero = (able) => { // Render the zero. if (able.indexOf('zero') < 0) { return null } let widget = <div className = 'zero' > 0 </div> return widget } const rangeValues = (able, low, high) => { // Render the range values for a continuous attr. if (able.indexOf('rangeValues') < 0) { return null } let widget = <div className = 'range_values' > { zeroTick(able) } { zero(able) } <div> <div className = 'range_low' > { low } </div> <div className = 'range_high' > { high } </div> </div> </div> return widget; } const filterContents = (able, range) => { // Render the filter content. if (able.indexOf('filterContents') < 0) { return null } let widget = <div className = 'filter_contents' > <div className = 'range_slider' value = { range } data = {{ layer: 'TODO' }} > <div className = 'low_mask mask' > </div> <div className = 'high_mask mask' > </div> </div> </div> return widget; } const ShortEntryPres = ({ able, dynamic, floatControl, high, id, low, metadata, range, zero, onMouseEnter, onMouseLeave }) => ( <div className = { 'shortEntryRoot layer-entry ' + dynamic } data = {{ layer: id }} onMouseEnter = { onMouseEnter } onMouseLeave = { onMouseLeave } > { filterIcon(able) } <div className = 'attrLabel' > { id } </div> { renderMetadata(able, metadata) } <div> { barChart(able) } { histogram(able) } { rangeValues(able, low, high) } { filterContents(able) } </div> <div className = 'controls' > </div> </div> ) ShortEntryPres.propTypes = { able: PropTypes.array, // capabilities to determine displayables dynamic: PropTypes.string, // 'dynamic' indicates this is a dynamic attr floatControl: PropTypes.string, // controls displayed on hover high: PropTypes.number, // high range value id: PropTypes.string, // attribute name low: PropTypes.number, // low range value metadata: PropTypes.array, // metadata rows range: PropTypes.array, // range of ? zero: PropTypes.bool, // show the zero tick mark onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, } export default ShortEntryPres;
client/src/research/EmailLinkLoginPage.story.js
mit-teaching-systems-lab/swipe-right-for-cs
import React from 'react'; import { storiesOf } from '@storybook/react'; import EmailLinkLoginPage from './EmailLinkLoginPage.js'; storiesOf('Research/EmailLinkLoginPage', module) //eslint-disable-line no-undef .add('normal', () => { return <EmailLinkLoginPage />; });
src/Image.js
bvasko/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const Image = React.createClass({ propTypes: { /** * Sets image as responsive image */ responsive: React.PropTypes.bool, /** * Sets image shape as rounded */ rounded: React.PropTypes.bool, /** * Sets image shape as circle */ circle: React.PropTypes.bool, /** * Sets image shape as thumbnail */ thumbnail: React.PropTypes.bool }, getDefaultProps() { return { responsive: false, rounded: false, circle: false, thumbnail: false }; }, render() { const classes = { 'img-responsive': this.props.responsive, 'img-rounded': this.props.rounded, 'img-circle': this.props.circle, 'img-thumbnail': this.props.thumbnail }; return ( <img {...this.props} className={classNames(this.props.className, classes)} /> ); } }); export default Image;
node_modules/react-native/Libraries/Text/Text.js
Helena-High/school-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactNativeComponentClass = require('react/lib/createReactNativeComponentClass'); const merge = require('merge'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, ellipsizeMode: true, allowFontScaling: true, selectable: true, adjustsFontSizeToFit: true, minimumFontScale: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the `fontFamily` from *`styles.baseText`, but the title provides its own additional styles. The title and body will * stack on top of each other on account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}<br /><br /> * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // App registration and rendering * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` */ const Text = React.createClass({ propTypes: { /** * This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * `numberOfLines` must be set in conjunction with this prop. * * > `clip` is working only for iOS */ ellipsizeMode: React.PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `ellipsizeMode`. */ numberOfLines: React.PropTypes.number, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}`` */ onPress: React.PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>`` */ onLongPress: React.PropTypes.func, /** * Lets the user select text, to use the native copy and paste functionality. * * @platform android */ selectable: React.PropTypes.bool, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * * @platform ios */ suppressHighlighting: React.PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: React.PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility setting on iOS. The * default is `true`. * * @platform ios */ allowFontScaling: React.PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](/react-native/docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: React.PropTypes.bool, /** * Specifies whether font should be scaled down automatically to fit given style constraints. * @platform ios */ adjustsFontSizeToFit: React.PropTypes.bool, /** * Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0). * @platform ios */ minimumFontScale: React.PropTypes.number, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, ellipsizeMode: 'tail', }; }, getInitialState: function(): Object { return merge(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, contextTypes: { isInAParentText: React.PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): ReactElement<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = () => { this.props.onPress && this.props.onPress(); }; this.touchableHandleLongPress = () => { this.props.onLongPress && this.props.onLongPress(); }; this.touchableGetPressRectOffset = function(): RectOffset { return PRESS_RECT_OFFSET; }; } return setResponder; }, onResponderGrant: function(e: SyntheticEvent, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number, left: number, right: number, bottom: number, } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass(viewConfig); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass({ validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', }); } module.exports = Text;
examples/simple-todos/index.js
rayshih/fun-react
// @flow import React from 'react' import ReactDOM from 'react-dom' import { createTypes, caseOf, createView, createProgram, fromSimpleInit, fromSimpleUpdate, trace, } from '../../src' // 1. define your init model const init = { currentInputText: '', // input state seq: 0, // sequential id todos: [] // no todo item initially } // 2. define Msg, which is basically a wrapper of ui event // createTypes help us to annotate the data const Msg = createTypes( 'InputChange', 'Add', 'Delete', 'Check', 'ChangeVisibility' ) // 3. define update function (the reducer) const update = caseOf({ InputChange: (event: Object, model) => ({ ...model, currentInputText: trace(event.target.value, event.target.value) }), Add: (_, model) => ({ ...model, currentInputText: '', seq: model.seq + 1, todos: [...model.todos, { id: model.seq + 1, title: model.currentInputText }] }) }) // 4. define view const SimpleTodoList = createView('SimpleTodoList', ({model}, {event}) => ( <div> { trace(model, model).todos.map(item => ( <div key={item.id}> {item.id}: {item.title} </div> )) } <input value={model.currentInputText} onChange={event(Msg.InputChange)} /> <button onClick={event(Msg.Add)}>Add</button> </div> )) const rootEl = document.getElementById('app') const Program = createProgram({ init: fromSimpleInit(init), update: fromSimpleUpdate(update), view: SimpleTodoList, inputs: () => [] }) ReactDOM.render(<Program />, rootEl)
lib/containers/PreviewContainer.js
sgleung/autumn
import React from 'react' import {connect} from 'react-redux' import Preview from '../components/Preview' const PreviewContainer = React.createClass({ render() { const {html} = this.props return ( <Preview htmlText={html} /> ) } }); const mapStateToProps = (state) => { return { html: state.html } } export default connect(mapStateToProps)(PreviewContainer)
src/screens/users/Login.js
kevingatera/Eseness
import React, { Component } from 'react'; import { StyleSheet, View, KeyboardAvoidingView, Image, Text, StatusBar } from 'react-native'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import SplashScreen from 'react-native-splash-screen'; import LoginForm from './loginForm'; export default class Login extends Component { componentDidMount() { SplashScreen.hide(); } static navigationOptions = { header: { visible: false, } } render() { return( <KeyboardAwareScrollView style={styles.container}> <StatusBar backgroundColor="rgba(8, 135, 198, 0.9)" /> <View style={styles.logoContainer}> <Image style={styles.logo} source={require('../../assets/SplashCenter.png')} /> <Text style={styles.logoSubtitle}> This app is brought to you by Esseness </Text> </View> <View style={styles.loginForm}> <LoginForm /> </View> </KeyboardAwareScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'skyblue', }, logoSubtitle: { marginTop: 280, textAlign: 'center', opacity: 0.65, }, logo: { // backgroundColor: 'red', // flex: 1, top: 150, // top: 421, width: 412, height: 152, alignItems: 'center', justifyContent: 'center', // backgroundColor: 'red', position: 'absolute', } })
packages/mineral-ui-icons/src/IconLabel.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconLabel(props: IconProps) { const iconProps = { rtl: true, ...props }; return ( <Icon {...iconProps}> <g> <path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12l-4.37-6.16z"/> </g> </Icon> ); } IconLabel.displayName = 'IconLabel'; IconLabel.category = 'action';
mine-data/src/common/withTracking.js
BerlingskeMedia/nyhedsbreveprofil
import React, { Component } from 'react'; import { pageview } from 'react-ga'; export const withTracking = WrapperComponent => { if (window.location.host.includes('profil.berlingskemedia.dk')) { return class WithTracking extends Component { componentDidMount() { pageview(window.location.pathname + window.location.search); } render() { return <WrapperComponent {...this.props}/>; } } } return class WithNoTracking extends Component { componentDidMount() { console.log('[React GA] FAKE pageview (non-prod env):', window.location.pathname + window.location.search); } render() { return <WrapperComponent {...this.props}/>; } } };
app/containers/NotFoundPage/index.js
oliverox/react99
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1>Page Not Found</h1> ); } }
assets/jqwidgets/demos/react/app/calendar/disabled/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxCalendar from '../../../jqwidgets-react/react_jqxcalendar.js'; class App extends React.Component { render() { return ( <JqxCalendar width={220} height={220} disabled={true}/> ) } } ReactDOM.render(<App />, document.getElementById('app'));
{{cookiecutter.repo_name}}/app/src/views/RestrictedView.js
thorgate/django-project-template
import React from 'react'; import { Helmet } from 'react-helmet-async'; import { Row, Col } from 'reactstrap'; import withView from 'decorators/withView'; import { loginRequired } from 'decorators/permissions'; const Restricted = () => ( <div className="page-container"> <Helmet title="Example" /> <Row> <Col md={12}> Hi, I require logged in permissions <br /> </Col> </Row> </div> ); const RestrictedView = withView()(loginRequired()(Restricted)); export default RestrictedView;
app/components/EditDish.js
rondobley/meal-planner
import React from 'react'; class EditDish extends React.Component { constructor(props) { super(props); this.handleNameInputChange = this.handleNameInputChange.bind(this); this.handleReferenceInputChange = this.handleReferenceInputChange.bind(this); } handleNameInputChange(e) { this.props.onNameInputChange(e.target.value); } handleReferenceInputChange(e) { this.props.onReferenceInputChange(e.target.value); } render() { let button = <button type='submit' className='btn btn-primary' data-dish-id={this.props.dishId} onClick={this.props.handleEdit}>Save</button>; return ( <form> <div className={'form-group ' + this.props.modalFormValidationState}> <label className='control-label'>Dish</label> <input type='text' className='form-control' ref='nameInputField' value={this.props.dishName} onChange={this.handleNameInputChange} autoFocus/> <span className='help-block'>{this.props.helpBlock}</span> <label className='control-label'>Recipe</label> <input type='text' className='form-control' ref='referenceInputField' value={this.props.dishReference} onChange={this.handleReferenceInputChange} /> </div> {button} </form> ); } } export default EditDish;
fields/components/columns/IdColumn.js
belafontestudio/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; var IdColumn = React.createClass({ displayName: 'IdColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, list: React.PropTypes.object, }, renderValue () { let value = this.props.data.id; if (!value) return null; return ( <ItemsTableValue padded interior title={value} href={'/keystone/' + this.props.list.path + '/' + value} field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = IdColumn;
old-or-not-typescript/React-RxJS/src/__test__/router.spec.js
janaagaard75/framework-investigations
import React from 'react';
src/parser/hunter/survival/modules/talents/AlphaPredator.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import { ALPHA_DAMAGE_KC_MODIFIER } from 'parser/hunter/survival/constants'; /** * Kill Command now has 2 charges, and deals 30% increased damage. * * Example log: https://www.warcraftlogs.com/reports/yNwk89Rt1HprGdXJ#fight=2&type=damage-done */ class AlphaPredator extends Analyzer { damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.ALPHA_PREDATOR_TALENT.id); } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.KILL_COMMAND_DAMAGE_SV.id) { return; } this.damage += calculateEffectiveDamage(event, ALPHA_DAMAGE_KC_MODIFIER); } statistic() { return ( <TalentStatisticBox talent={SPELLS.ALPHA_PREDATOR_TALENT.id} value={<ItemDamageDone amount={this.damage} />} tooltip="This statistic shows the damage gained from the increased Kill Command damage. It does not reflect the potential damage gain from having 2 charges of Kill Command or from the focus gain from Kill Command overall." /> ); } } export default AlphaPredator;
test/integration/app-document-import-order/pages/_app.js
azukaru/next.js
import React from 'react' import RequiredByApp from '../requiredByApp' import sideEffect from '../sideEffectModule' sideEffect('_app') function MyApp({ Component, pageProps }) { return ( <React.Fragment> <RequiredByApp /> <Component {...pageProps} /> </React.Fragment> ) } export default MyApp
packages/material-ui-icons/src/Tab.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><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 16H3V5h10v4h8v10z" /></g> , 'Tab');