path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/javascript/mastodon/features/compose/components/search.js
3846masa/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleClear = (e) => { e.preventDefault(); if (this.props.value.length > 0 || this.props.submitted) { this.props.onClear(); } } handleKeyDown = (e) => { if (e.key === 'Enter') { e.preventDefault(); this.props.onSubmit(); } } noop () { } handleFocus = () => { this.props.onShow(); } render () { const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} onChange={this.handleChange} onKeyUp={this.handleKeyDown} onFocus={this.handleFocus} /> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={`fa fa-search ${hasValue ? '' : 'active'}`} /> <i aria-label={intl.formatMessage(messages.placeholder)} className={`fa fa-times-circle ${hasValue ? 'active' : ''}`} /> </div> </div> ); } } export default injectIntl(Search);
src/routes/withTracker.js
wearepush/redux-starter
import React, { Component } from 'react'; import { object } from 'prop-types'; import GoogleAnalytics from 'react-ga'; const googleAnaliticsId = process.env?.GOOGLE_ANALITICS_ID; if (googleAnaliticsId) { GoogleAnalytics.initialize(googleAnaliticsId); } export default function withTracker(WrappedComponent, options = {}) { const trackPage = (page) => { GoogleAnalytics.set({ page, ...options, }); GoogleAnalytics.pageview(page); }; const HOC = class extends Component { componentDidMount() { if (googleAnaliticsId) { const { location } = this.props; const page = location.pathname; trackPage(page); } } componentDidUpdate(nextProps) { if (googleAnaliticsId) { const { location } = this.props; const currentPage = location.pathname; const nextPage = nextProps.location.pathname; if (currentPage !== nextPage) { trackPage(nextPage); } } } render() { return <WrappedComponent {...this.props} />; } }; if (typeof WrappedComponent.fetchData !== 'undefined') { HOC.fetchData = WrappedComponent.fetchData; } HOC.propTypes = { location: object.isRequired, }; return HOC; }
src/components/MyMainMenu.js
fredrikku/rikku-grommet-react-sample
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import MenuIcon from 'grommet/components/icons/base/Menu'; import Anchor from 'grommet/components/Anchor'; import Menu from 'grommet/components/Menu'; import Box from 'grommet/components/Box'; const MainMenu = (props) => { const { myTableStore } = props; const menuItems = props.menuItems || []; return ( <Box flex={true} justify='end' direction='row' responsive={false}> <Menu pad={{ vertical: 'medium', between: 'small'}} icon={<MenuIcon size="medium" colorIndex="neutral-4"/>} dropAlign={{"right": "right"}} > { menuItems.map( (item, index) => <Anchor key={item.key} onClick={ () => props.selectTable( myTableStore[item.key]) }> {item.title} </Anchor> )} </Menu> </Box> ); }; MainMenu.propTypes = { menuItems: PropTypes.arrayOf(PropTypes.shape({key: PropTypes.number.isRequired, title: PropTypes.string.isRequired})), selectTable: PropTypes.func.isRequired, myTableStore: PropTypes.array.isRequired }; const mapStateToProps = state => ( { myTableStore: state.myTableStore } ); //subscribe MainMenu to redux-store, meaning state will appear as props instead export default connect(mapStateToProps)(MainMenu);
node_modules/@material-ui/core/esm/Link/Link.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { capitalize } from '../utils/helpers'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; export var styles = { /* Styles applied to the root element. */ root: {}, /* Styles applied to the root element if `underline="none"`. */ underlineNone: { textDecoration: 'none' }, /* Styles applied to the root element if `underline="hover"`. */ underlineHover: { textDecoration: 'none', '&:hover': { textDecoration: 'underline' } }, /* Styles applied to the root element if `underline="always"`. */ underlineAlways: { textDecoration: 'underline' }, // Same reset as ButtonBase.root /* Styles applied to the root element if `component="button"`. */ button: { position: 'relative', // Remove grey highlight WebkitTapHighlightColor: 'transparent', backgroundColor: 'transparent', // Reset default value // We disable the focus ring for mouse, touch and keyboard users. outline: 'none', border: 0, margin: 0, // Remove the margin in Safari borderRadius: 0, padding: 0, // Remove the padding in Firefox cursor: 'pointer', userSelect: 'none', verticalAlign: 'middle', '-moz-appearance': 'none', // Reset '-webkit-appearance': 'none', // Reset '&::-moz-focus-inner': { borderStyle: 'none' // Remove Firefox dotted outline. } } }; var Link = React.forwardRef(function Link(props, ref) { var classes = props.classes, className = props.className, _props$component = props.component, component = _props$component === void 0 ? 'a' : _props$component, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, TypographyClasses = props.TypographyClasses, _props$underline = props.underline, underline = _props$underline === void 0 ? 'hover' : _props$underline, _props$variant = props.variant, variant = _props$variant === void 0 ? 'inherit' : _props$variant, other = _objectWithoutProperties(props, ["classes", "className", "component", "color", "TypographyClasses", "underline", "variant"]); return React.createElement(Typography, _extends({ className: clsx(classes.root, component === 'button' && classes.button, classes["underline".concat(capitalize(underline))], className), classes: TypographyClasses, color: color, component: component, ref: ref, variant: variant }, other)); }); process.env.NODE_ENV !== "production" ? Link.propTypes = { /** * The content of the link. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the link. */ color: PropTypes.oneOf(['default', 'error', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary']), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * `classes` property applied to the [`Typography`](/api/typography/) element. */ TypographyClasses: PropTypes.object, /** * Controls when the link should have an underline. */ underline: PropTypes.oneOf(['none', 'hover', 'always']), /** * Applies the theme typography styles. */ variant: PropTypes.string } : void 0; export default withStyles(styles, { name: 'MuiLink' })(Link);
src/svg-icons/image/colorize.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageColorize = (props) => ( <SvgIcon {...props}> <path d="M20.71 5.63l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z"/> </SvgIcon> ); ImageColorize = pure(ImageColorize); ImageColorize.displayName = 'ImageColorize'; ImageColorize.muiName = 'SvgIcon'; export default ImageColorize;
src/components/login/LoginForm.js
hugofrely/chat-react-redux
import React from 'react'; import TextInput from '../common/TextInput'; const LoginForm = ({user, onSave, onChange, saving}) => { return ( <form> <h1>Login</h1> <TextInput name="email" label="Email" onChange={onChange} value={user.email} /> <TextInput name="password" label="Password" onChange={onChange} value={user.password} /> <input type="submit" disabled={saving} value={saving ? 'Logining in...' : 'Login'} className="btn btn-primary" onClick={onSave}/> </form> ); }; LoginForm.propTypes = { onSave: React.PropTypes.func.isRequired, saving: React.PropTypes.bool, user: React.PropTypes.object.isRequired, onChange: React.PropTypes.func.isRequired }; export default LoginForm;
frontend/src/Settings/MediaManagement/RootFolder/EditRootFolderModal.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import EditRootFolderModalContentConnector from './EditRootFolderModalContentConnector'; function EditRootFolderModal({ isOpen, onModalClose, ...otherProps }) { return ( <Modal isOpen={isOpen} onModalClose={onModalClose} > <EditRootFolderModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } EditRootFolderModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default EditRootFolderModal;
src/buttons/Button.js
kosiakMD/react-native-elements
import PropTypes from 'prop-types'; import React from 'react'; import { TouchableNativeFeedback, TouchableHighlight, StyleSheet, View, Platform, ActivityIndicator, Text as NativeText, } from 'react-native'; import colors from '../config/colors'; import Text from '../text/Text'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import getIconType from '../helpers/getIconType'; import normalize from '../helpers/normalizeText'; import ViewPropTypes from '../config/ViewPropTypes'; const log = () => { console.log('please attach method to this component'); //eslint-disable-line no-console }; const Button = props => { const { disabled, loading, loadingRight, activityIndicatorStyle, buttonStyle, borderRadius, title, onPress, icon, iconComponent, secondary, secondary2, secondary3, primary1, primary2, backgroundColor, color, fontSize, underlayColor, raised, textStyle, large, iconRight, fontWeight, disabledStyle, fontFamily, containerViewStyle, rounded, outline, transparent, textNumberOfLines, textEllipsizeMode, allowFontScaling, ...attributes } = props; let { Component, rightIcon, leftIcon } = props; let leftIconElement; if (!leftIcon && icon) { leftIcon = icon; } if (leftIcon) { let Icon; if (iconComponent) { Icon = iconComponent; } else if (!leftIcon.type) { Icon = MaterialIcon; } else { Icon = getIconType(leftIcon.type); } leftIconElement = ( <Icon {...leftIcon} color={leftIcon.color || 'white'} size={leftIcon.size || (large ? 26 : 18)} style={[styles.icon, leftIcon.style && leftIcon.style]} /> ); } let rightIconElement; if (iconRight || rightIcon) { if (!rightIcon) { rightIcon = iconRight; } let Icon; if (iconComponent) { Icon = iconComponent; } else if (!rightIcon.type) { Icon = MaterialIcon; } else { Icon = getIconType(rightIcon.type); } rightIconElement = ( <Icon {...rightIcon} color={rightIcon.color || 'white'} size={rightIcon.size || (large ? 26 : 18)} style={[styles.iconRight, rightIcon.style && rightIcon.style]} /> ); } let loadingElement; if (loading) { loadingElement = ( <ActivityIndicator animating={true} style={[styles.activityIndicatorStyle, activityIndicatorStyle]} color={color || 'white'} size={(large && 'large') || 'small'} /> ); } if (!Component && Platform.OS === 'ios') { Component = TouchableHighlight; } if (!Component && Platform.OS === 'android') { Component = TouchableNativeFeedback; } if (!Component) { Component = TouchableHighlight; } if (Platform.OS === 'android' && (borderRadius && !attributes.background)) { attributes.background = TouchableNativeFeedback.Ripple( 'ThemeAttrAndroid', true ); } const baseFont = { color: (textStyle && textStyle.color) || color || stylesObject.text.color, size: (textStyle && textStyle.fontSize) || fontSize || (!large && stylesObject.smallFont.fontSize) || stylesObject.text.fontSize, }; let textOptions = {}; if (textNumberOfLines) { textOptions.numberOfLines = textNumberOfLines; if (textEllipsizeMode) { textOptions.ellipsizeMode = textEllipsizeMode; } } return ( <View style={[ styles.container, raised && styles.raised, containerViewStyle, borderRadius && { borderRadius }, ]} > <Component underlayColor={underlayColor || 'transparent'} onPress={onPress || log} disabled={disabled || false} {...attributes} > <View style={[ styles.button, secondary && { backgroundColor: colors.secondary }, secondary2 && { backgroundColor: colors.secondary2 }, secondary3 && { backgroundColor: colors.secondary3 }, primary1 && { backgroundColor: colors.primary1 }, primary2 && { backgroundColor: colors.primary2 }, backgroundColor && { backgroundColor: backgroundColor }, borderRadius && { borderRadius }, !large && styles.small, rounded && { borderRadius: baseFont.size * 3.8, paddingHorizontal: !large ? stylesObject.small.padding * 1.5 : stylesObject.button.padding * 1.5, }, outline && { borderWidth: 1, backgroundColor: 'transparent', borderColor: baseFont.color, }, transparent && { borderWidth: 0, backgroundColor: 'transparent', }, buttonStyle && buttonStyle, disabled && { backgroundColor: colors.disabled }, disabled && disabledStyle && disabledStyle, ]} > {(icon && !iconRight) || leftIconElement ? leftIconElement : null} {loading && !loadingRight && loadingElement} <Text style={[ styles.text, color && { color }, !large && styles.smallFont, fontSize && { fontSize }, textStyle && textStyle, fontWeight && { fontWeight }, fontFamily && { fontFamily }, ]} {...textOptions} allowFontScaling={allowFontScaling} > {title} </Text> {loading && loadingRight && loadingElement} {(icon && iconRight) || rightIconElement ? rightIconElement : null} </View> </Component> </View> ); }; Button.propTypes = { buttonStyle: ViewPropTypes.style, title: PropTypes.string, onPress: PropTypes.any, icon: PropTypes.object, leftIcon: PropTypes.object, rightIcon: PropTypes.object, iconRight: PropTypes.object, iconComponent: PropTypes.any, secondary: PropTypes.bool, secondary2: PropTypes.bool, secondary3: PropTypes.bool, primary1: PropTypes.bool, primary2: PropTypes.bool, backgroundColor: PropTypes.string, color: PropTypes.string, fontSize: PropTypes.any, underlayColor: PropTypes.string, raised: PropTypes.bool, textStyle: NativeText.propTypes.style, disabled: PropTypes.bool, loading: PropTypes.bool, activityIndicatorStyle: ViewPropTypes.style, loadingRight: PropTypes.bool, Component: PropTypes.any, borderRadius: PropTypes.number, large: PropTypes.bool, fontWeight: PropTypes.string, disabledStyle: ViewPropTypes.style, fontFamily: PropTypes.string, containerViewStyle: ViewPropTypes.style, rounded: PropTypes.bool, outline: PropTypes.bool, transparent: PropTypes.bool, allowFontScaling: PropTypes.bool, textNumberOfLines: PropTypes.number, textEllipsizeMode: PropTypes.string, }; const stylesObject = { container: { backgroundColor: 'transparent', marginLeft: 15, marginRight: 15, }, button: { padding: 19, backgroundColor: colors.primary, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', }, text: { color: 'white', fontSize: normalize(16), }, icon: { marginRight: 10, }, iconRight: { marginLeft: 10, }, small: { padding: 12, }, smallFont: { fontSize: normalize(14), }, activityIndicatorStyle: { marginHorizontal: 10, height: 0, }, raised: { ...Platform.select({ ios: { shadowColor: 'rgba(0,0,0, .4)', shadowOffset: { height: 1, width: 1 }, shadowOpacity: 1, shadowRadius: 1, }, android: { backgroundColor: '#fff', elevation: 2, }, }), }, }; const styles = StyleSheet.create(stylesObject); export default Button;
src/routes/index.js
cmosguy/react-redux-auth0
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import App from '../components/App'; // Child routes import home from './home'; import contact from './contact'; import login from './login'; import register from './register'; import content from './content'; import error from './error'; export default { path: '/', children: [ home, contact, login, register, content, error, ], async action({ next, render, context }) { const component = await next(); if (component === undefined) return component; return render( <App context={context}>{component}</App> ); }, };
src/js/components/tool-header.js
pfb3cn/react_bootcamp_exercise
import React from 'react'; export class ToolHeader extends React.Component { static propTypes = { header: React.PropTypes.string }; render() { return <h1>Color Tool</h1>; } }
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
kibousoft/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components'; import Overlay from 'react-overlays/lib/Overlay'; import classNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import detectPassiveEvents from 'detect-passive-events'; import { buildCustomEmojis } from '../../emoji/emoji'; const messages = defineMessages({ emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' }, emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' }, emoji_not_found: { id: 'emoji_button.not_found', defaultMessage: 'No emojos!! (╯°□°)╯︵ ┻━┻' }, custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' }, recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' }, search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' }, people: { id: 'emoji_button.people', defaultMessage: 'People' }, nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' }, food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' }, activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' }, travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' }, objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' }, symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' }, flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' }, }); const assetHost = process.env.CDN_HOST || ''; let EmojiPicker, Emoji; // load asynchronously const backgroundImageFn = () => `${assetHost}/emoji/sheet.png`; const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; const categoriesSort = [ 'recent', 'custom', 'people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols', 'flags', ]; class ModifierPickerMenu extends React.PureComponent { static propTypes = { active: PropTypes.bool, onSelect: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; handleClick = e => { this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1); } componentWillReceiveProps (nextProps) { if (nextProps.active) { this.attachListeners(); } else { this.removeListeners(); } } componentWillUnmount () { this.removeListeners(); } handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } attachListeners () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } removeListeners () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } render () { const { active } = this.props; return ( <div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}> <button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button> </div> ); } } class ModifierPicker extends React.PureComponent { static propTypes = { active: PropTypes.bool, modifier: PropTypes.number, onChange: PropTypes.func, onClose: PropTypes.func, onOpen: PropTypes.func, }; handleClick = () => { if (this.props.active) { this.props.onClose(); } else { this.props.onOpen(); } } handleSelect = modifier => { this.props.onChange(modifier); this.props.onClose(); } render () { const { active, modifier } = this.props; return ( <div className='emoji-picker-dropdown__modifiers'> <Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} /> <ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} /> </div> ); } } @injectIntl class EmojiPickerMenu extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), loading: PropTypes.bool, onClose: PropTypes.func.isRequired, onPick: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, intl: PropTypes.object.isRequired, skinTone: PropTypes.number.isRequired, onSkinTone: PropTypes.func.isRequired, }; static defaultProps = { style: {}, loading: true, placement: 'bottom', frequentlyUsedEmojis: [], }; state = { modifierOpen: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } getI18n = () => { const { intl } = this.props; return { search: intl.formatMessage(messages.emoji_search), notfound: intl.formatMessage(messages.emoji_not_found), categories: { search: intl.formatMessage(messages.search_results), recent: intl.formatMessage(messages.recent), people: intl.formatMessage(messages.people), nature: intl.formatMessage(messages.nature), foods: intl.formatMessage(messages.food), activity: intl.formatMessage(messages.activity), places: intl.formatMessage(messages.travel), objects: intl.formatMessage(messages.objects), symbols: intl.formatMessage(messages.symbols), flags: intl.formatMessage(messages.flags), custom: intl.formatMessage(messages.custom), }, }; } handleClick = emoji => { if (!emoji.native) { emoji.native = emoji.colons; } this.props.onClose(); this.props.onPick(emoji); } handleModifierOpen = () => { this.setState({ modifierOpen: true }); } handleModifierClose = () => { this.setState({ modifierOpen: false }); } handleModifierChange = modifier => { this.props.onSkinTone(modifier); } render () { const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props; if (loading) { return <div style={{ width: 299 }} />; } const title = intl.formatMessage(messages.emoji); const { modifierOpen } = this.state; return ( <div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}> <EmojiPicker perLine={8} emojiSize={22} sheetSize={32} custom={buildCustomEmojis(custom_emojis)} color='' emoji='' set='twitter' title={title} i18n={this.getI18n()} onClick={this.handleClick} include={categoriesSort} recent={frequentlyUsedEmojis} skin={skinTone} showPreview={false} backgroundImageFn={backgroundImageFn} emojiTooltip /> <ModifierPicker active={modifierOpen} modifier={skinTone} onOpen={this.handleModifierOpen} onClose={this.handleModifierClose} onChange={this.handleModifierChange} /> </div> ); } } @injectIntl export default class EmojiPickerDropdown extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), intl: PropTypes.object.isRequired, onPickEmoji: PropTypes.func.isRequired, onSkinTone: PropTypes.func.isRequired, skinTone: PropTypes.number.isRequired, }; state = { active: false, loading: false, }; setRef = (c) => { this.dropdown = c; } onShowDropdown = () => { this.setState({ active: true }); if (!EmojiPicker) { this.setState({ loading: true }); EmojiPickerAsync().then(EmojiMart => { EmojiPicker = EmojiMart.Picker; Emoji = EmojiMart.Emoji; this.setState({ loading: false }); }).catch(() => { this.setState({ loading: false }); }); } } onHideDropdown = () => { this.setState({ active: false }); } onToggle = (e) => { if (!this.state.loading && (!e.key || e.key === 'Enter')) { if (this.state.active) { this.onHideDropdown(); } else { this.onShowDropdown(); } } } handleKeyDown = e => { if (e.key === 'Escape') { this.onHideDropdown(); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } render () { const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis } = this.props; const title = intl.formatMessage(messages.emoji); const { active, loading } = this.state; return ( <div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}> <div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}> <img className={classNames('emojione', { 'pulse-loading': active && loading })} alt='🙂' src={`${assetHost}/emoji/1f602.svg`} /> </div> <Overlay show={active} placement='bottom' target={this.findTarget}> <EmojiPickerMenu custom_emojis={this.props.custom_emojis} loading={loading} onClose={this.onHideDropdown} onPick={onPickEmoji} onSkinTone={onSkinTone} skinTone={skinTone} frequentlyUsedEmojis={frequentlyUsedEmojis} /> </Overlay> </div> ); } }
code/frontend/src/components/Dashboard/index.js
CPSC319-2017w1/coast.the-terminal
import React from 'react'; import PropTypes, { instanceOf } from 'prop-types'; import { connect } from 'react-redux'; import { withCookies, Cookies } from 'react-cookie'; import DashboardComponent from './Dashboard.jsx'; import { switchView } from '../../actions/main-actions.js'; const mapStateToProps = state => { return { user: state.user, tables: state.tables }; }; const mapDispatchToProps = dispatch => { return { switchTab: tab => { dispatch(switchView(tab)); } }; }; /** * Class that represents Dashboard Container */ class DashboardContainer extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } /** * Redirects to the page based on the button clicked * @param event */ onClick(event) { event.preventDefault(); const tab = event.target.getAttribute('name'); this.props.cookies.set('tab', tab); this.props.switchTab(tab); } /** * renders the react component to the screen * @return {XML} */ render() { return <DashboardComponent onClick={this.onClick} />; } } DashboardContainer.propTypes = { user: PropTypes.object.isRequired, tables: PropTypes.object.isRequired, switchTab: PropTypes.func.isRequired, cookies: instanceOf(Cookies).isRequired }; const Dashboard = connect( mapStateToProps, mapDispatchToProps )(DashboardContainer); export default withCookies(Dashboard);
src/js/view/LoginForm.js
marqusm/react-client-template
import React from 'react'; import {Field, reduxForm} from 'redux-form'; import {RaisedButton} from "material-ui"; import {TextField} from "redux-form-material-ui"; class LoginForm extends React.Component { componentDidMount() { this.ref // the Field .getRenderedComponent() // on Field, returns ReduxFormMaterialUITextField .getRenderedComponent() // on ReduxFormMaterialUITextField, returns TextField .focus(); } saveRef = ref => (this.ref = ref) render() { const {handleSubmit} = this.props; return ( <div className="login"> <form ref="form"> <Field name="username" component={TextField} hintText="Enter your Username" // floatingLabelText="Username" ref={this.saveRef} withRef /> <br/> <Field name="password" type="password" component={TextField} hintText="Enter your Password" // floatingLabelText="Password" ref={this.saveRef} withRef /> <br/> <RaisedButton label="Submit" primary={true} onClick={(event) => { handleSubmit() }}/> </form> </div> ); }; } LoginForm = reduxForm({ form: 'login', })(LoginForm); export default LoginForm;
src/Xword.js
bcopeland/xwordjs
// @flow import React, { Component } from 'react'; import Modal from 'react-modal'; import FileInput from './FileInput.js'; import Server from './Server.js'; import Cell from './Cell.js'; import Clues from './Clues.js'; import Loading from './Loading.js'; import {TimerState, Timer} from './Timer.js'; import { Route, Switch, Link } from 'react-router-dom'; import { ButtonGroup, ButtonToolbar, DropdownButton, MenuItem, ProgressBar, Button } from 'react-bootstrap'; import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'; import { TextDecoder } from 'text-encoding'; import './Xword.css'; // TODO // . clue-only entry // . auto-pause // . port nav enhancements (no auto next, skip to first blank) var Xd = require("./xd.js"); var Puz = require("./puz.js"); var Xpf = require("./xpf.js"); class XwordClue { state: { index: number, direction: string, number: number, clue: string, answer: string, active: boolean, crossActive: boolean }; constructor(options) { this.state = { 'index': 0, 'direction': 'A', 'number': 0, 'clue': '', 'answer': '', 'active': false, 'crossActive': false, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } } class XwordCell { state: { fill: string, entry: string, active: boolean, focus: boolean, circled: boolean, incorrect: boolean, number: number, version: number, }; constructor(options) { this.state = { fill: '.', entry: ' ', active: false, focus: false, circled: false, incorrect: false, version: 0, number: 0, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } isBlack() : boolean { return this.state.fill === '#'; } } function Title(props) { var title = props.title; var author = props.author ? " by " + props.author : ""; return ( <div className={"xwordjs-title"}> <span className={"xwordjs-title-text"}>{title}</span> <span className={"xwordjs-author-text"}>{author}</span> </div> ); } function ClueBar(props) { var text = ''; for (var i=0; i < props.value.length; i++) { var clue = props.value[i]; if (clue.get('active')) { text = clue.get('number') + ". " + clue.get('clue'); } } return <div className={"xwordjs-clue-bar"}>{text}</div>; } class Grid extends Component { render() { var rows = []; for (var i=0; i < this.props.height; i++) { var row_cells = []; for (var j=0; j < this.props.width; j++) { var ind = i * this.props.width + j; var fill = this.props.cells[ind].get('fill'); var entry = this.props.cells[ind].get('entry'); var active = this.props.cells[ind].get('active'); var focus = this.props.cells[ind].get('focus'); var circled = this.props.cells[ind].get('circled'); var incorrect = this.props.cells[ind].get('incorrect'); var number = this.props.cells[ind].get('number') || ''; var black = fill === '#'; if (fill === '#' || fill === '.') { fill = ' '; } var cell = <Cell id={"cell_" + ind} value={entry} key={"cell_" + ind} isBlack={black} isActive={active} isFocus={focus} isCircled={circled} isIncorrect={incorrect} isTop={i===0} isLeft={j===0} number={number} onClick={(x)=>this.props.handleClick(parseInt(x.substring(5), 10))}/>; row_cells.push(cell); } rows[i] = <div className="xwordjs-grid-row" key={"row_" + i}>{row_cells}</div>; } return ( <div id="xwordjs-grid-inner">{rows}</div> ); } } function MobileKeyboardKey(props) { return <div className="xwordjs-keyboard-key" onClick={() => props.onClick(props.code)}>{props.value}</div>; } function MobileKeyboard(props) { var keys = ["qwertyuiop", "asdfghjkl", "␣zxcvbnm⌫"]; var rows = []; for (var i=0; i < keys.length; i++) { var rowstr = keys[i]; var row_keys = []; for (var j=0; j < rowstr.length; j++) { var ch = rowstr.charAt(j); var code; if (ch === '␣') { code = 0x20; } else if (ch === '⌫') { code = 0x8; } else { code = ch.charCodeAt(0); } var key = <MobileKeyboardKey key={ch} onClick={props.onClick} code={code} value={ch}/>; row_keys.push(key); } rows[i] = <div className="xwordjs-keyboard-row" key={i}>{row_keys}</div>; } return ( <div className="xwordjs-keyboard">{rows}</div> ); } class XwordSolver extends Component { state: { height: number, width: number, cells: Array<XwordCell>, clues: Array<XwordClue>, title: string, author: string, timer: TimerState, activecell: number, direction: string, cell_to_clue_table: Array<Array<number>>, clue_to_cell_table: Array<number>, version: number, solutionId: ?string, dismissed_modal: boolean, modified: boolean, rebus: boolean, server: ?Server }; closeModal: Function; revealAll: Function; serverUpdate: Function; constructor() { super(); this.state = { 'height': 15, 'width': 15, 'cells': [], 'clues': [], 'title': '', 'author': '', 'timer': new TimerState(), 'activecell': 0, 'direction': 'A', 'cell_to_clue_table': [], 'clue_to_cell_table': [], 'dismissed_modal': false, 'version': 1, 'modified': false, 'solutionId': null, rebus: false, 'server': null, } this.closeModal = this.closeModal.bind(this); this.revealAll = this.revealAll.bind(this); this.serverUpdate = this.serverUpdate.bind(this); } loadServerPuzzle(id: string) { if (!process.env.REACT_APP_HAS_SERVER) return; var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server .getSolution(id) .then(function(obj) { return server.getPuzzle(obj.PuzzleId) }) .then(function(data) { var decoder = new TextDecoder('utf-8'); var puz = new Xpf(decoder.decode(data)); self.setState({solutionId: id, server: server}); self.puzzleLoaded(id, puz); server.connect(id, self.serverUpdate); var entries = []; for (var i=0; i < self.state.cells.length; i++) { entries.push({'Version': -1, 'Value': ''}); } server.sendSolution(id, -1, entries); }); } loadPuzzle(file: File, filename : ?string) { var self = this; if (process.env.REACT_APP_HAS_SERVER) { var server = new Server({base_url: process.env.PUBLIC_URL}) server.uploadPuzzle(file) .then(function(obj) { var id = obj.Id; return server.startSolution(id); }) .then(function(obj) { var solutionId = obj.Id; document.location.hash = "/s/" + solutionId; self.loadServerPuzzle(solutionId); }); } else { this.loadPuzzleURL(window.URL.createObjectURL(file), filename); } } loadPuzzleURL(url: string, filename : ?string) { var self = this; var request = new Request(url); fetch(request).then(function(response) { return response.arrayBuffer(); }).then(function(data) { var puz; var fn = filename || url; var decoder; if (fn.endsWith("xd")) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xd(decoder.decode(data)); self.puzzleLoaded(url, puz); } else if (fn.endsWith("xml") || url.match(/^http/)) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xpf(decoder.decode(data)); self.puzzleLoaded(url, puz); } else { puz = new Puz(data); self.puzzleLoaded(url, puz); } }); } cellPos(clue_id: number) { var y = Math.floor(clue_id / this.state.width); var x = clue_id % this.state.width; return [x, y]; } navRight() { var [x, y] = this.cellPos(this.state.activecell); while (x < this.state.width) { x += 1; if (x < this.state.width && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x === this.state.width) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navLeft() { var [x, y] = this.cellPos(this.state.activecell); while (x >= 0) { x -= 1; if (x >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navUp() { var [x, y] = this.cellPos(this.state.activecell); while (y >= 0) { y -= 1; if (y >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navDown() { var [x, y] = this.cellPos(this.state.activecell); while (y < this.state.height) { y += 1; if (y < this.state.height && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y === this.state.height) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navNextClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id + 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } navPrevClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id - 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } findNextEmptyCell(direction: string, start_x: number, start_y: number, end_x: ?number, end_y: ?number): ?number { var dind = (direction === 'A') ? 0 : 1; var [x_incr, y_incr] = [1 - dind, dind]; var [x, y] = [start_x, start_y]; if (end_x === null || end_x === undefined) end_x = this.state.width; if (end_y === null || end_y === undefined) end_y = this.state.height; var len = (!dind) ? end_x - start_x : end_y - start_y; for (let i = 0; i < len; i++) { var cell_id = y * this.state.width + x; var cell = this.state.cells[cell_id]; if (cell.isBlack()) break; if (cell.get('entry') === ' ') return cell_id; x += x_incr; y += y_incr; } return null; } navNext() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var clue = this.state.clues[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); var alen = clue.get('answer').length; var empty_cell_id = this.findNextEmptyCell(this.state.direction, x, y); // wrap if (empty_cell_id === null || empty_cell_id === undefined) { empty_cell_id = this.findNextEmptyCell(this.state.direction, start_x, start_y, x, y); } if (empty_cell_id === null || empty_cell_id === undefined) { // no empty square. [x, y] = this.cellPos(cur_cell_id); // if end of word, go to next word if ((this.state.direction === 'A' && x === start_x + alen - 1) || (this.state.direction === 'D' && y === start_y + alen - 1)) { this.navNextClue(); return; } // go to next word if (this.state.direction === 'A') x += 1; else y += 1; empty_cell_id = y * this.state.width + x; } this.selectCell(empty_cell_id, this.state.direction); } navPrev() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); if (this.state.direction === 'A') x -= 1; else y -= 1; if (x < start_x) x = start_x; if (y < start_y) y = start_y; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } switchDir() { var dir = this.state.direction === 'A' ? 'D' : 'A'; this.selectCell(this.state.activecell, dir); } type(ch: string) { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); cell.setState({entry: text + ch}); this.setState({modified: true}) } else { cell.setState({'entry': ch, 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navNext(); } } del() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.selectCell(this.state.activecell, this.state.direction); } } backspace() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navPrev(); } } isCorrect() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; var fill = cell.get('fill'); var entry = cell.get('entry'); if (fill !== '#' && (entry !== fill && entry !== fill.charAt(0))) return false; } return true; } processKeyCode(keyCode: number, shift: boolean) { // A-Z if ((keyCode >= 0x41 && keyCode <= 0x5a) || (keyCode >= 0x61 && keyCode <= 0x7a)) { var ch = String.fromCharCode(keyCode) this.type(ch.toUpperCase()); return true; } switch (keyCode) { case 0x8: this.backspace(); return true; case 0x9: if (!shift) this.navNextClue(); else this.navPrevClue(); return true; case 0x20: this.switchDir(); return true; case 0x25: this.navLeft(); return true; case 0x26: this.navUp(); return true; case 0x27: this.navRight(); return true; case 0x28: this.navDown(); return true; case 0x2e: this.del(); return true; default: return false; } } handleKeyDown(e: KeyboardEvent) { if (e.ctrlKey || e.altKey) return; if (this.state.direction === 'A' && (e.keyCode === 0x26 || e.keyCode === 0x28)) { this.selectCell(this.state.activecell, 'D'); e.preventDefault(); return; } if (this.state.direction === 'D' && (e.keyCode === 0x25 || e.keyCode === 0x27)) { this.selectCell(this.state.activecell, 'A'); e.preventDefault(); return; } if (this.processKeyCode(e.keyCode, e.shiftKey)) { e.preventDefault(); } } handleClick(i: number) { if (this.state.activecell === i) { this.switchDir(); } else { this.selectCell(i, this.state.direction); } } puzzleLoaded(url: string, puz: Object) { var grid = puz.grid; var flags = puz.flags; var maxx = grid[0].length; var maxy = grid.length; var i; var title = 'Untitled'; var author = 'Unknown'; for (i=0; i < puz.headers.length; i++) { var [header, value] = puz.headers[i]; if (header === 'Title') { title = value; } else if (header === 'Creator' || header === 'Author') { author = value; } } var cells = Array(maxx * maxy).fill(null); var cell_to_clue_table = Array(maxx * maxy).fill(null); var number_index = []; for (var y = 0; y < maxy; y++) { for (var x = 0; x < maxx; x++) { var fill = grid[y][x]; var is_black = fill === '#'; var number = 0; var start_of_xslot = (!is_black && (x === 0 || grid[y][x-1] === '#') && (x + 1 < maxx && grid[y][x+1] !== '#')); var start_of_yslot = (!is_black && (y === 0 || grid[y-1][x] === '#') && (y + 1 < maxy && grid[y+1][x] !== '#')); if (start_of_xslot || start_of_yslot) { number_index.push([x,y]); number = number_index.length; } var circled = false; if (flags) { circled = !!(flags[y][x] & puz.FLAGS.CIRCLED); } cells[y * maxx + x] = new XwordCell({ 'fill': fill, 'number': number, 'active': false, 'circled': circled }); cell_to_clue_table[y * maxx + x] = [null, null]; } } var clues = []; var clue_to_cell_table = []; for (i=0; i < puz.clues.length; i++) { var [type, cluestr, answer] = puz.clues[i]; var [dir, num] = type; var clue = new XwordClue({ 'index': i, 'direction': dir, 'number': num, 'clue': cluestr, 'answer': answer}); clues.push(clue); // clue_to_cell table: index into clues[] has the corresponding // cell id var xy = number_index[num - 1]; clue_to_cell_table[i] = xy[1] * maxx + xy[0]; // set up cell_to_clue_table: indexed by cell id, each entry // has a two element array (across, down) which contains the // index into clues[]. Iterate over answer in the direction // of the clue to set all cells making up the answer var ind = 0, xincr = 0, yincr = 0; if (dir === 'A') { xincr = 1; } else { ind = 1; yincr = 1; } [x, y] = xy; for (var j = 0; y < maxy && x < maxx; j++) { var cell = y * maxx + x; if (grid[y][x] === '#') break; cell_to_clue_table[cell][ind] = i; x += xincr; y += yincr; } } this.setState({ 'title': title, 'author': author, 'width': maxx, 'height': maxy, 'cells': cells, 'clues': clues, 'clue_to_cell_table': clue_to_cell_table, 'cell_to_clue_table': cell_to_clue_table }); this.loadStoredData(); this.selectCell(0, 'A', true); // set cluelist to match grid height var gridelem = document.getElementById("xwordjs-grid-inner"); var cluediv = document.getElementById("xwordjs-cluelist-container"); var cluelist = document.getElementsByClassName("xwordjs-cluelist"); var gridHeight = window.getComputedStyle(gridelem).getPropertyValue("height"); if (cluediv) cluediv.style.height = gridHeight; for (i = 0; i < cluelist.length; i++) { var e = cluelist[i]; var newheight = String(parseInt(gridHeight, 10) - 60) + "px"; e.style.height = newheight; } } saveStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = { entries: this.state.cells.map((x) => x.state.entry), elapsed: this.state.timer.get('elapsed') }; // avoid a race condition when first starting up if (!data.elapsed) return; localStorage.setItem(key, JSON.stringify(data)); } readStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = localStorage.getItem(key); if (!data) return null; return JSON.parse(data); } loadStoredData() { var data = this.readStoredData() if (!data) return; var entries = data.entries; var elapsed = data.elapsed; for (var i=0; i < entries.length; i++) { this.state.cells[i].setState({entry: entries[i]}); } this.setState({modified: true}) this.state.timer.setState({elapsed: elapsed}); this.setState({cells: this.state.cells, timer: this.state.timer}); } highlightClue(clue: XwordClue, active: boolean) { var cluenum = clue.get('index'); var cind = this.state.clue_to_cell_table[cluenum]; var [x, y] = this.cellPos(cind); var x_incr = clue.get('direction') === 'A' ? 1 : 0; var y_incr = !x_incr; for (; x < this.state.width && y < this.state.height; ) { var cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"active": active}); x += x_incr; y += y_incr; } } selectCell(cell_id: number, direction: string, initial: ?boolean) { var cell = this.state.cells[cell_id]; if (cell.isBlack()) return; var newclues = this.state.clues.slice(); var newcells = this.state.cells.slice(); // unselect existing selected cell and crosses var oldcell_id = this.state.activecell; var old_dind = (this.state.direction === 'A') ? 0 : 1; var oldclue = this.state.clues[this.state.cell_to_clue_table[oldcell_id][old_dind]]; var oldcross = this.state.clues[this.state.cell_to_clue_table[oldcell_id][1 - old_dind]]; var oldcell = this.state.cells[oldcell_id]; var dind = (direction === 'A') ? 0 : 1; var clue = this.state.clues[this.state.cell_to_clue_table[cell_id][dind]]; var cross = this.state.clues[this.state.cell_to_clue_table[cell_id][1 - dind]]; var e; var cluediv = document.getElementById("xwordjs-cluelist-container"); var display = window.getComputedStyle(cluediv).getPropertyValue("display"); var hasClues = display !== "none"; if (initial || oldcross !== cross) { if (oldcross) oldcross.setState({"crossActive": false}); if (cross) { cross.setState({"crossActive": true}); e = document.getElementById("clue_" + cross.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldclue !== clue) { if (oldclue) { oldclue.setState({"active": false}); this.highlightClue(oldclue, false); } if (clue) { clue.setState({"active": true}); this.highlightClue(clue, true); e = document.getElementById("clue_" + clue.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldcell_id !== cell_id) { oldcell.setState({focus: false}); cell.setState({focus: true}); } e = document.getElementById("cell_" + cell_id); if (e) { var rect = e.getBoundingClientRect(); var container = document.getElementById("xwordjs-container"); var prect = container.getBoundingClientRect(); if (prect.left > rect.left || prect.right < rect.right || prect.top > rect.top || prect.bottom < rect.bottom) { scrollIntoViewIfNeeded(e); } } this.setState({'clues': newclues, 'cells': newcells, 'activecell': cell_id, 'direction': direction, rebus: false}); } revealCell() { var cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } revealClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var cind = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cind); var x_incr = !dind; var y_incr = !x_incr; var cell; for (; x < this.state.width && y < this.state.height; ) { cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"entry": cell.get('fill')}); x += x_incr; y += y_incr; } cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } selectClue(clue: XwordClue) { var cluenum = clue.get('index'); // set first empty cell in this clue as active var cell = this.state.clue_to_cell_table[cluenum]; var [start_x, start_y] = this.cellPos(cell); var empty_cell = this.findNextEmptyCell(clue.get('direction'), start_x, start_y); if (empty_cell != null) cell = empty_cell; this.selectCell(cell, clue.get('direction')); } closeModal() { this.setState({'dismissed_modal': true}); } showErrors() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) { if (cell.get('entry') !== ' ' && cell.get('entry') !== cell.get('fill')) { cell.setState({incorrect: true}); } else { cell.setState({incorrect: false}); } } } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } revealAll() { this.setState({'dismissed_modal': true}); for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) cell.setState({'entry': cell.get('fill')}); } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } serverUpdate(json: Object) { console.log("a server update happened..."); for (var i = 0; i < json.Entries.length; i++) { var ch = json.Entries[i].Value; var version = json.Entries[i].Version; var cell = this.state.cells[i]; if (cell && !cell.isBlack() && version > cell.get('version')) { cell.setState({entry: ch, version: version}); } } this.setState({version: json.Version}); } updateTimer(state: Object) { if (state.stopped) return; if (this.isCorrect()) { state.stopped = true; } this.saveStoredData(); this.state.timer.setState(state); this.setState({'timer': this.state.timer}); if (!this.state.solutionId) return; var entries = []; for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; entries.push({'Version': cell.get('version'), 'Value': cell.get('entry')}); } if (this.state.modified) { // $FlowFixMe this.state.server.sendSolution(this.state.solutionId, this.state.version, entries); this.setState({modified: false}); } } startRebus() { this.setState({rebus: true}); } componentDidMount() { var self = this; window.addEventListener("keydown", (e) => self.handleKeyDown(e)); if (this.props.filename) { self.loadPuzzleURL(process.env.PUBLIC_URL + this.props.filename); return; } if (this.props.serverId) { self.loadServerPuzzle(this.props.serverId); return; } // TODO move to XwordMain ? // old-style URLs: // #[^/][hash] -> /s/hash var puzzle = window.location.hash.substring(1); if (puzzle.length && puzzle[0] !== '/' && this.props.history) { this.props.history.push("/s/" + puzzle); return; } // ?filename -> /load/filename puzzle = window.location.search.substring(1); if (puzzle.length && this.props.history) { this.props.history.push("/file/" + puzzle); return; } } componentWillUnmount() { var self = this; window.removeEventListener("keydown", (e) => self.handleKeyDown(e)); } render() { if (this.state.cells.length === 0) { if (this.props.filename || this.props.serverId) { return <Loading/>; } if (process.env.REACT_APP_HAS_SERVER) { return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>Collaborative XwordJS</h1> <p> Upload a crossword puzzle here (.puz or .xpf format). Once loaded, you can copy the random URL string and share with someone else to play together. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>XwordJS</h1> <p> Select a crossword puzzle here (.puz or .xpf format) and then you can solve it in your browser. The file will remain local and not uploaded anywhere else. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <Modal isOpen={this.isCorrect() && !this.state.dismissed_modal}> <h1>Nice job!</h1> <p>You solved it. Sorry for the anticlimactic dialog.</p> <p>It took {this.state.timer.elapsedStr(true)}.</p> <button onClick={this.closeModal}>OK</button> </Modal> <div className="xwordjs-vertical-container"> <div className="xwordjs-topbar"> <Title title={this.state.title} author={this.state.author}/> </div> <div className="xwordjs-timer-bar"> <Timer value={this.state.timer} onChange={(x) => this.updateTimer(x)}/> <DropdownButton title="Reveal"> <MenuItem eventKey="1" onClick={() => this.showErrors()}>Show Errors</MenuItem> <MenuItem divider/> <MenuItem eventKey="2" onClick={() => this.revealCell()}>Reveal Cell</MenuItem> <MenuItem eventKey="3" onClick={() => this.revealClue()}>Reveal Clue</MenuItem> <MenuItem divider/> <MenuItem eventKey="4" onClick={() => this.revealAll()}>Reveal All</MenuItem> </DropdownButton> <ButtonSpacer/> <Button onClick={() => this.setState({rebus: !this.state.rebus})} active={this.state.rebus} bsSize="xsmall">Rebus</Button> </div> <ClueBar value={this.state.clues}/> <div className="xwordjs-container" id="xwordjs-container"> <div className="xwordjs-grid" id="xwordjs-grid"> <Grid height={this.state.height} width={this.state.width} cells={this.state.cells} handleClick={(x) => this.handleClick(x)}/> </div> <Clues selectClue={(i) => this.selectClue(i)} value={this.state.clues}/> </div> <BabyLink filename={this.props.filename}/> <MobileKeyboard onClick={(code) => this.processKeyCode(code, false)}/> </div> </div> ); } } function BabyLink(props) { var link = []; if (props.filename === "2017-11-13.xd") { link.push(<a href="/images/syc.jpg">55-Across: healthy 7 lbs, 1 oz</a>) } return ( <div>{link}</div> ); } function XwordLoadFile(props) { return ( <XwordSolver filename={props.match.params.name}/> ); } function XwordLoadServer(props) { return ( <XwordSolver serverId={props.match.params.hash}/> ); } class XwordPuzzleListLoader extends Component { state: { items: ?array }; constructor(options) { super(); this.state = { items: null } Object.assign(this.state, options); }; componentDidMount() { var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server.listSolutions().then(function (data) { self.setState({items: data}); }); } render() { if (!this.state.items) { return <Loading/>; } return <XwordPuzzleList puzzles={this.state.items}/>; } } const ButtonSpacer = (props) => ( <ButtonGroup><span className="xwordjs-button-spacer"/></ButtonGroup> ); function XwordPuzzleList(props) { var items = []; for (var i = 0; i < props.puzzles.length; i++) { var p = props.puzzles[i]; items.push(<li key={i}><Link to={"/s/" + p.Id}>{p.Title + " " + p.Author}<ProgressBar now={p.Progress} label={`${p.Progress}%`}/></Link></li>); } return <ul>{items}</ul>; } function XwordMainPanel() { return ( <Switch> <Route exact path="/" component={XwordSolver}/> <Route path="/file/:name" component={XwordLoadFile}/> <Route path="/s/:hash" component={XwordLoadServer}/> <Route path="/list" component={XwordPuzzleListLoader}/> </Switch> ); } function XwordMain() { return ( <div> <XwordMainPanel /> </div> ); } export default XwordMain;
app/containers/Home.js
sandim27/ReduxApp
import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; import UploadBlock from '../components/UploadBlock'; export default class Home extends Component { constructor(props){ super(props); this.state = { newNamePhoto: '', newPhoto: {}, activeName: true, }; this.uploadPhoto = this.uploadPhoto.bind(this); this.addNewPhoto = this.addNewPhoto.bind(this); this.addPhotoName = this.addPhotoName.bind(this); } uploadPhoto(event){ this.props.uploadPhoto(event.target.files[0]); this.setState({newPhoto: event.target.files[0]}); if(this.state.newNamePhoto) this.setState({activeName: true}) else this.setState({activeName: false}) } addPhotoName(event) { this.setState({newNamePhoto: event.target.value}); this.setState({activeName: true}) } addNewPhoto() { const { photos, uploadedImage, addNewPhoto } = this.props; const newPhoto = this.state.newPhoto; const newName = this.state.newNamePhoto; const newUrl = uploadedImage.url; const newId = photos[0].id; addNewPhoto(newPhoto, newName, newUrl, newId); } render() { const { uploadedImage } = this.props; return ( <div> <div className="upload-form"> <UploadBlock addPhotoName={this.addPhotoName} uploadPhoto={this.uploadPhoto} uploadedImage={uploadedImage} newPhoto={this.state.newPhoto} activeName={this.state.activeName} /> <Button bsStyle="primary" className="add-photo" bsSize="small" disabled={!this.state.newNamePhoto || !uploadedImage.url} onClick={this.addNewPhoto}> Add new photo </Button> <p hidden={!uploadedImage.name}><strong>{uploadedImage.name }</strong> the photo was successfully uploaded!</p> </div> </div> ); } }
src/components/title/Title.js
jshack3r/ws-redux-counters-router
import React from 'react' class Title extends React.Component { constructor(props) { super(props) } componentDidMount() { this.props.onLoad() } render() { let { onClick } = this.props return <h2 className="text-muted" onClick={onClick} style={{cursor:'pointer'}}>Redux Counters</h2> } } Title.propTypes = { onClick: React.PropTypes.func.isRequired, onLoad: React.PropTypes.func.isRequired } export default Title
client/components/App.js
Kamill90/Dental
import React from 'react'; import NavigationBar from './client/NavigationBar'; export default ({ children }) => { return( <div> <NavigationBar/> <div className="container">{children}</div> </div> ) };
packages/react-error-overlay/src/containers/StackFrame.js
appier/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. */ /* @flow */ import React, { Component } from 'react'; import CodeBlock from './StackFrameCodeBlock'; import { getPrettyURL } from '../utils/getPrettyURL'; import { darkGray } from '../styles'; import type { StackFrame as StackFrameType } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const linkStyle = { fontSize: '0.9em', marginBottom: '0.9em', }; const anchorStyle = { textDecoration: 'none', color: darkGray, cursor: 'pointer', }; const codeAnchorStyle = { cursor: 'pointer', }; const toggleStyle = { marginBottom: '1.5em', color: darkGray, cursor: 'pointer', border: 'none', display: 'block', width: '100%', textAlign: 'left', background: '#fff', fontFamily: 'Consolas, Menlo, monospace', fontSize: '1em', padding: '0px', lineHeight: '1.5', }; type Props = {| frame: StackFrameType, contextSize: number, critical: boolean, showCode: boolean, editorHandler: (errorLoc: ErrorLocation) => void, |}; type State = {| compiled: boolean, |}; class StackFrame extends Component<Props, State> { state = { compiled: false, }; toggleCompiled = () => { this.setState(state => ({ compiled: !state.compiled, })); }; getErrorLocation(): ErrorLocation | null { const { _originalFileName: fileName, _originalLineNumber: lineNumber, } = this.props.frame; // Unknown file if (!fileName) { return null; } // e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1" const isInternalWebpackBootstrapCode = fileName.trim().indexOf(' ') !== -1; if (isInternalWebpackBootstrapCode) { return null; } // Code is in a real file return { fileName, lineNumber: lineNumber || 1 }; } editorHandler = () => { const errorLoc = this.getErrorLocation(); if (!errorLoc) { return; } this.props.editorHandler(errorLoc); }; onKeyDown = (e: SyntheticKeyboardEvent<>) => { if (e.key === 'Enter') { this.editorHandler(); } }; render() { const { frame, contextSize, critical, showCode } = this.props; const { fileName, lineNumber, columnNumber, _scriptCode: scriptLines, _originalFileName: sourceFileName, _originalLineNumber: sourceLineNumber, _originalColumnNumber: sourceColumnNumber, _originalScriptCode: sourceLines, } = frame; const functionName = frame.getFunctionName(); const compiled = this.state.compiled; const url = getPrettyURL( sourceFileName, sourceLineNumber, sourceColumnNumber, fileName, lineNumber, columnNumber, compiled ); let codeBlockProps = null; if (showCode) { if ( compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null ) { codeBlockProps = { lines: scriptLines, lineNum: lineNumber, columnNum: columnNumber, contextSize, main: critical, }; } else if ( !compiled && sourceLines && sourceLines.length !== 0 && sourceLineNumber != null ) { codeBlockProps = { lines: sourceLines, lineNum: sourceLineNumber, columnNum: sourceColumnNumber, contextSize, main: critical, }; } } const canOpenInEditor = this.getErrorLocation() !== null && this.props.editorHandler !== null; return ( <div> <div>{functionName}</div> <div style={linkStyle}> <a style={canOpenInEditor ? anchorStyle : null} onClick={canOpenInEditor ? this.editorHandler : null} onKeyDown={canOpenInEditor ? this.onKeyDown : null} tabIndex={canOpenInEditor ? '0' : null} > {url} </a> </div> {codeBlockProps && ( <span> <a onClick={canOpenInEditor ? this.editorHandler : null} style={canOpenInEditor ? codeAnchorStyle : null} > <CodeBlock {...codeBlockProps} /> </a> <button style={toggleStyle} onClick={this.toggleCompiled}> {'View ' + (compiled ? 'source' : 'compiled')} </button> </span> )} </div> ); } } export default StackFrame;
resources/assets/js/components/AppComponent.js
jrm2k6/i-heart-reading
import React, { Component } from 'react'; import { fetchUser } from '../actions/userProfileActions'; import { hideModal } from '../actions/modals/modalActions'; import { connect } from 'react-redux'; import Modal from 'react-modal'; import LateralMenu from './LateralMenu'; import AlertsComponent from './AlertsComponent'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const mapStateToProps = (state) => { return { user: state.userProfileReducer.user, currentTypeAlert: state.alertsReducer.currentTypeAlert, currentContentAlert: state.alertsReducer.currentContentAlert, modalComponent: state.modalReducer.component, modalData: state.modalReducer.data, showingModal: state.modalReducer.showingModal }; }; const overrideModalDefaultStyles = () => { Modal.defaultStyles.overlay.backgroundColor = "rgba(0, 0, 0, 0.85)"; Modal.defaultStyles.content.width = "60%"; Modal.defaultStyles.content.height = "60%"; Modal.defaultStyles.content.top = "0"; Modal.defaultStyles.content.bottom = "0"; Modal.defaultStyles.content.left = "0"; Modal.defaultStyles.content.right = "0"; Modal.defaultStyles.content.margin = "auto"; Modal.defaultStyles.content.padding = "0"; Modal.defaultStyles.content.borderRadius = "1px"; Modal.defaultStyles.content.border = "none"; } overrideModalDefaultStyles(); const mapDispatchToProps = (dispatch) => { return { fetchUser: () => { dispatch(fetchUser()); }, hideModal: () => { dispatch(hideModal()); } }; }; class AppComponent extends Component { componentDidMount() { this.props.fetchUser(); } render() { const { currentTypeAlert, currentContentAlert, showingModal, modalComponent, modalData } = this.props; const alert = (currentTypeAlert && currentContentAlert) ? <AlertsComponent type={currentTypeAlert} content={currentContentAlert} /> : null; const element = (showingModal && modalComponent) ? React.createElement(modalComponent, modalData) : null; return ( <div className='root-component'> {alert} <LateralMenu history={this.props.history} user={this.props.user} /> <div className='interactive-panel'> {this.props.children} </div> <Modal contentLabel={'Application Modal'} isOpen={showingModal} onRequestClose={this.props.hideModal} > {element} </Modal> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(AppComponent);
app/javascript/mastodon/components/admin/ReportReasonSelector.js
musashino205/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import api from 'mastodon/api'; import { injectIntl, defineMessages } from 'react-intl'; import classNames from 'classnames'; const messages = defineMessages({ other: { id: 'report.categories.other', defaultMessage: 'Other' }, spam: { id: 'report.categories.spam', defaultMessage: 'Spam' }, violation: { id: 'report.categories.violation', defaultMessage: 'Content violates one or more server rules' }, }); class Category extends React.PureComponent { static propTypes = { id: PropTypes.string.isRequired, text: PropTypes.string.isRequired, selected: PropTypes.bool, disabled: PropTypes.bool, onSelect: PropTypes.func, children: PropTypes.node, }; handleClick = () => { const { id, disabled, onSelect } = this.props; if (!disabled) { onSelect(id); } }; render () { const { id, text, disabled, selected, children } = this.props; return ( <div tabIndex='0' role='button' className={classNames('report-reason-selector__category', { selected, disabled })} onClick={this.handleClick}> {selected && <input type='hidden' name='report[category]' value={id} />} <div className='report-reason-selector__category__label'> <span className={classNames('poll__input', { active: selected, disabled })} /> {text} </div> {(selected && children) && ( <div className='report-reason-selector__category__rules'> {children} </div> )} </div> ); } } class Rule extends React.PureComponent { static propTypes = { id: PropTypes.string.isRequired, text: PropTypes.string.isRequired, selected: PropTypes.bool, disabled: PropTypes.bool, onToggle: PropTypes.func, }; handleClick = () => { const { id, disabled, onToggle } = this.props; if (!disabled) { onToggle(id); } }; render () { const { id, text, disabled, selected } = this.props; return ( <div tabIndex='0' role='button' className={classNames('report-reason-selector__rule', { selected, disabled })} onClick={this.handleClick}> <span className={classNames('poll__input', { checkbox: true, active: selected, disabled })} /> {selected && <input type='hidden' name='report[rule_ids][]' value={id} />} {text} </div> ); } } export default @injectIntl class ReportReasonSelector extends React.PureComponent { static propTypes = { id: PropTypes.string.isRequired, category: PropTypes.string.isRequired, rule_ids: PropTypes.arrayOf(PropTypes.string), disabled: PropTypes.bool, intl: PropTypes.object.isRequired, }; state = { category: this.props.category, rule_ids: this.props.rule_ids || [], rules: [], }; componentDidMount() { api().get('/api/v1/instance').then(res => { this.setState({ rules: res.data.rules, }); }).catch(err => { console.error(err); }); } _save = () => { const { id, disabled } = this.props; const { category, rule_ids } = this.state; if (disabled) { return; } api().put(`/api/v1/admin/reports/${id}`, { category, rule_ids, }).catch(err => { console.error(err); }); }; handleSelect = id => { this.setState({ category: id }, () => this._save()); }; handleToggle = id => { const { rule_ids } = this.state; if (rule_ids.includes(id)) { this.setState({ rule_ids: rule_ids.filter(x => x !== id ) }, () => this._save()); } else { this.setState({ rule_ids: [...rule_ids, id] }, () => this._save()); } }; render () { const { disabled, intl } = this.props; const { rules, category, rule_ids } = this.state; return ( <div className='report-reason-selector'> <Category id='other' text={intl.formatMessage(messages.other)} selected={category === 'other'} onSelect={this.handleSelect} disabled={disabled} /> <Category id='spam' text={intl.formatMessage(messages.spam)} selected={category === 'spam'} onSelect={this.handleSelect} disabled={disabled} /> <Category id='violation' text={intl.formatMessage(messages.violation)} selected={category === 'violation'} onSelect={this.handleSelect} disabled={disabled}> {rules.map(rule => <Rule key={rule.id} id={rule.id} text={rule.text} selected={rule_ids.includes(rule.id)} onToggle={this.handleToggle} disabled={disabled} />)} </Category> </div> ); } }
app/javascript/mastodon/features/list_adder/components/list.js
gol-cha/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import { removeFromListAdder, addToListAdder } from '../../../actions/lists'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, }); const MapStateToProps = (state, { listId, added }) => ({ list: state.get('lists').get(listId), added: typeof added === 'undefined' ? state.getIn(['listAdder', 'lists', 'items']).includes(listId) : added, }); const mapDispatchToProps = (dispatch, { listId }) => ({ onRemove: () => dispatch(removeFromListAdder(listId)), onAdd: () => dispatch(addToListAdder(listId)), }); export default @connect(MapStateToProps, mapDispatchToProps) @injectIntl class List extends ImmutablePureComponent { static propTypes = { list: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onRemove: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, added: PropTypes.bool, }; static defaultProps = { added: false, }; render () { const { list, intl, onRemove, onAdd, added } = this.props; let button; if (added) { button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />; } else { button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />; } return ( <div className='list'> <div className='list__wrapper'> <div className='list__display-name'> <Icon id='list-ul' className='column-link__icon' fixedWidth /> {list.get('title')} </div> <div className='account__relationship'> {button} </div> </div> </div> ); } }
client/src/app/components/voice-control/components/SpeechButton.js
zraees/sms-project
import React from 'react' import {Popover, OverlayTrigger} from 'react-bootstrap' import {bindActionCreators} from 'redux' import * as VoiceActions from '../VoiceActions' import {connect} from 'react-redux'; import SpeechHelp from './SpeechHelp' class SpeechButton extends React.Component { hidePopover = ()=> { this.refs.vpOverlay.hide() }; render() { const popover = ( <Popover ref="popover" id="popover-basic" placement="bottom" title={null} >{ !this.props.hasError ? <h4 className="vc-title">Voice command activated <br /> <small>Please speak clearly into the mic</small> </h4> : <h4 className="vc-title-error text-center"> <i className="fa fa-microphone-slash"/> Voice command failed <br /> <small className="txt-color-red">Must <strong>"Allow"</strong> Microphone</small> <br /> <small className="txt-color-red">Must have <strong>Internet Connection</strong> </small> </h4> } <div> <a className="btn btn-success" id="speech-help-btn" onClick={this.props.voiceControlShowHelp}>See Commands</a> <a className="btn bg-color-purple txt-color-white" onClick={this.hidePopover}>Close Popup</a> </div> </Popover> ) return ( <div id="speech-btn" className={this.props.className}> <div> <OverlayTrigger trigger={this.props.started ? null : "click" } placement="bottom" ref="vpOverlay" overlay={popover}> <a onClick={this.voiceControlToggle} title="Voice Command" id="voice-command-btn"><i className="fa fa-microphone"/></a> </OverlayTrigger> </div> <SpeechHelp showHelp={this.props.showHelp} onHide={this.props.voiceControlHideHelp}/> </div> ) } voiceControlToggle = (e)=> { if (this.props.started) { this.hidePopover(); this.props.voiceControlOff() } else { this.props.voiceControlOn() } } } export default connect( (state)=> { return state.voice }, (dispatch)=> { return bindActionCreators(VoiceActions, dispatch) } )(SpeechButton)
hit-the-road-react/src/components/RentalsMap.prev.js
buckmelton/hit-the-road
import React, { Component } from 'react'; // import GoogleApiComponent from 'google-maps-react'; import '../css/App.css'; import '../css/normalize.css'; import '../css/skeleton.css'; // Google Maps API key: AIzaSyCFwE9ezzuQGddycwRrZ1K3BvRzFVQGvvg const __GAPI_KEY__ = "AIzaSyCFwE9ezzuQGddycwRrZ1K3BvRzFVQGvvg"; class RentalsMap extends Component { render() { if (!this.props.loaded) { return <div>Loading...</div> } return ( <div>Map will go here</div> ); } } export default RentalsMap; // export default GoogleApiComponent({ // apiKey: __GAPI_KEY__ // })(RentalsMap)
client/src/components/layouts/Sidebar.js
banderson/reactive-stock-ticker-demo
import React from 'react'; export default ({children}) => ( <aside className="col-xs-3"> {children} </aside> );
modules/dreamview/frontend/src/components/DefaultRouting/CycleNumberInput.js
ApolloAuto/apollo
import React from 'react'; import _ from 'lodash'; import CheckboxItem from 'components/common/CheckboxItem'; export default class CycleNumberInput extends React.Component { constructor(props) { super(props); this.state = { cycleNumber: 1, isCycling: false, }; this.sendCycleDefaultRouting = this.sendCycleDefaultRouting.bind(this); this.cancelSendDefaultRouting = this.cancelSendDefaultRouting.bind(this); this.toggleCycle = this.toggleCycle.bind(this); this.handleInput = (event) => { this.setState({ cycleNumber: event.target.value }); }; } toggleCycle() { this.setState((prevState) => { return { isCycling: !prevState.isCycling }; }); } sendCycleDefaultRouting() { const { routeEditingManager, options } = this.props; if (this.state.isCycling) { const cycleNumber = parseInt(this.state.cycleNumber, 10); if (isNaN(cycleNumber) || cycleNumber < 1) { alert('please input a valid cycle number'); } else if (!routeEditingManager.checkCycleRoutingAvailable()) { alert(`Please set the default routing reasonably,the distance from the car position to the end point should exceed ${routeEditingManager.defaultRoutingDistanceThreshold}, otherwise it will not be able to form a closed loop.`); } else { routeEditingManager.sendCycleRoutingRequest(cycleNumber); } } else { routeEditingManager.sendRoutingRequest(false, routeEditingManager.currentDefaultRouting); } options.showCycleNumberInput = false; } cancelSendDefaultRouting() { const { options } = this.props; options.showCycleNumberInput = false; } render() { return ( <React.Fragment> <div className="default-routing-input"> <div> <div> <label className="name-label">Start Cycling</label> <CheckboxItem extraClasses="start-cycle-checkbox" id="isReportableData" isChecked={this.state.isCycling} disabled={false} onClick={this.toggleCycle} /> </div> {this.state.isCycling && <div> <label className="name-label">Cycle Number:</label> <input className="name-input" value={this.state.cycleNumber} onChange={this.handleInput} type="number" ></input> </div>} </div> <div className="default-routing-input-btn"> <button className="input-button submit-button" onClick={this.sendCycleDefaultRouting}>Send</button> <button className="input-button" onClick={this.cancelSendDefaultRouting}>Cancel</button> </div> </div> </React.Fragment> ); } }
src/svg-icons/action/theaters.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTheaters = (props) => ( <SvgIcon {...props}> <path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/> </SvgIcon> ); ActionTheaters = pure(ActionTheaters); ActionTheaters.displayName = 'ActionTheaters'; ActionTheaters.muiName = 'SvgIcon'; export default ActionTheaters;
react/JobCard/components/SellingPoint/SellingPoint.js
seekinternational/seek-asia-style-guide
import React from 'react'; import PropTypes from 'prop-types'; import styles from './SellingPoint.less'; import Text from '../../../Text/Text'; const SellingPoint = ({ sellingPoints, showSellingPoint }) => { if (!showSellingPoint || !sellingPoints) { return null; } return ( <ul className={styles.sellingPoints}> {sellingPoints.map((sellingPoint, i) => ( <li key={i} className={styles.sellingPoint}> <Text whispering baseline={false} className={styles.text}> {sellingPoint} </Text> </li> ))} </ul> ); }; SellingPoint.propTypes = { sellingPoints: PropTypes.arrayOf(PropTypes.string), showSellingPoint: PropTypes.bool }; export default SellingPoint;
src/main.js
warcraftlfg/warcrafthub-client
import React from 'react' import ReactDOM from 'react-dom' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' // ======================================================== // Store Instantiation // ======================================================== const initialState = window.___INITIAL_STATE__ const store = createStore(initialState) // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = () => { const routes = require('./routes/index').default(store) ReactDOM.render( <AppContainer store={store} routes={routes} />, MOUNT_NODE ) } // This code is excluded from production bundle if (__DEV__) { if (module.hot) { // Development render functions const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react').default ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } // Wrap render in try/catch render = () => { try { renderApp() } catch (error) { console.error(error) renderError(error) } } // Setup hot module replacement module.hot.accept('./routes/index', () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE) render() }) ) } } // ======================================================== // Go! // ======================================================== render()
fields/types/text/TextColumn.js
dvdcastro/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var TextColumn = React.createClass({ displayName: 'TextColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, getValue () { // cropping text is important for textarea, which uses this column const value = this.props.data.fields[this.props.col.path]; return value ? value.substr(0, 100) : null; }, render () { const value = this.getValue(); const empty = !value && this.props.linkTo ? true : false; const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined; return ( <ItemsTableCell> <ItemsTableValue className={className} href={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}> {value} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = TextColumn;
client/components/FlassCommon/Video/VideoTimePanel/VideoTimePanelComponent.js
Nexters/flass
import React from 'react'; import PropTypes from 'prop-types'; import VideoDurationComponent from '../VideoDurationComponent'; import './VideoTimePanelComponentStyles.scss'; const propTypes = { duration: PropTypes.number.isRequired, elapsed: PropTypes.number.isRequired }; const defaultProps = { }; const VideoTimePanelComponent = ({ duration, elapsed }) => ( <span className="video-timepanel"> <VideoDurationComponent seconds={ elapsed } /> { ' / ' } <VideoDurationComponent seconds={ duration } /> </span> ); VideoTimePanelComponent.propTypes = propTypes; VideoTimePanelComponent.defaultProps = defaultProps; export { VideoTimePanelComponent };
src/svg-icons/action/view-stream.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewStream = (props) => ( <SvgIcon {...props}> <path d="M4 18h17v-6H4v6zM4 5v6h17V5H4z"/> </SvgIcon> ); ActionViewStream = pure(ActionViewStream); ActionViewStream.displayName = 'ActionViewStream'; ActionViewStream.muiName = 'SvgIcon'; export default ActionViewStream;
src/docs/components/LabelDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Label from 'grommet/components/Label'; import Anchor from 'grommet/components/Anchor'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; Label.displayName = 'Label'; export default class LabelDoc extends Component { render () { return ( <DocsArticle title='Label'> <section> <p>A simple text label. This could be used to annotate a <Anchor path='/docs/value'>Value</Anchor> to indicate what the value refers to. Or, it can annotate a <Anchor path='/docs/card'>Card</Anchor> to indicate a category.</p> <Label>Sample Label</Label> </section> <section> <h2>Properties</h2> <dl> <dt><code>labelFor {"{string}"}</code></dt> <dd>ID of the form element that the label is for. Optional.</dd> <dt><code>truncate true|false</code></dt> <dd>Restrict the text to a single line and truncate with ellipsis if it is too long to all fit. Defaults to <code>false</code>.</dd> <dt><code>uppercase true|false</code></dt> <dd>Convert the label to uppercase. Defaults to <code>false</code>.</dd> </dl> </section> <section> <h2>Usage</h2> <Code preamble={`import Label from 'grommet/components/Label';`}> <Label> {'{contents}'} </Label> </Code> </section> </DocsArticle> ); } };
src/components/TabContent/TabContent.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; const TabContent = props => { const { selected, children, ...other } = props; return ( <div {...other} selected={selected} hidden={!selected}> {children} </div> ); }; TabContent.propTypes = { /** * Specify whether the TabContent is selected */ selected: PropTypes.bool, /** * Pass in content to render inside of the TabContent */ children: PropTypes.node, }; TabContent.defaultProps = { selected: false, }; export default TabContent;
frontend/src/components/SearchBar.js
OwenRay/Remote-MediaServer
/* eslint-disable no-underscore-dangle */ /** * Created by owenray on 19/07/2017. */ import React, { Component } from 'react'; import { Button, Icon, Input, Row } from 'react-materialize'; import { deserialize } from 'redux-jsonapi'; import store from '../helpers/stores/settingsStore'; class SearchBar extends Component { constructor() { super(); this.toggleGrouped = this.toggleGrouped.bind(this); this.state = { filters: { title: '' }, settings: { libraries: [] } }; } componentWillMount() { this.onChange = this.onChange.bind(this); store.subscribe(this.onSettingsChange.bind(this)); this.onSettingsChange(); } /** * triggered when the settings model changes */ onSettingsChange() { const { api } = store.getState(); if (!api.setting) { return; } this.setState({ settings: deserialize(api.setting[1], store), }); } /** * @param e * called when user types in field, applies typed value to state */ onChange(e) { e.stopPropagation(); e.preventDefault(); const o = this.state; o.filters[e.target.name] = e.target.value; this.setState(o); if (this.props.onChange) { this.props.onChange(o.filters); } } toggleGrouped() { const f = this.props.filters; f.distinct = f.distinct ? '' : 'external-id'; if (this.props.onChange) { this.props.onChange(f); } } render() { if (this.state === null) { return null; } const { props } = this; const { filters } = props; return ( <div className={props.className}> <Row> <Input s={3} name="libraryId" type="select" label="Library:" value={filters.libraryId} onChange={this.onChange}> <option value="">All libraries</option> {this.state.settings.libraries.map((lib) => { let { uuid } = lib; if (lib.type === 'shared') [uuid] = uuid.split('-'); return <option key={uuid} value={uuid}>{lib.name}</option>; })} </Input> <div className="col search s6"> <Input s={12} name="title" type="text" label="" value={filters.title || ''} onChange={this.onChange} /> <Button className="mdi-action-search"><Icon>search</Icon></Button> </div> <Input s={3} name="sort" type="select" label="Sort by:" value={filters.sort} onChange={this.onChange}> <option value="title">Title</option> <option value="date_added:DESC">Date added</option> <option value="release-date:DESC">Date released</option> </Input> <Button className="toggleGroup" data-tip={filters.distinct ? 'Disable grouping' : 'Enable grouping'} floating onClick={this.toggleGrouped} icon={filters.distinct ? 'layers_clear' : 'layers'} /> </Row> </div> ); } } export default SearchBar;
src/components/Input.js
abdulhannanali/github-organization-repos
import React from 'react'; import classnames from 'classnames'; import '../styles/Input.css'; const Input = (props) => { const classNames = classnames(['form-control', 'Input']); return ( <div className="form-group"> <input type="text" className={classNames} maxLength="39" {...props} /> </div> ); }; export default Input;
Agenda/src/components/esqueciSenha.js
interlegis/agenda-evento
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import _ from 'lodash'; import { recuperarSenha } from '../actions'; import { FIELD_ESQUECI_SENHA } from './forms/fields_types'; class EsqueciSenha extends Component{ handleSubmitForm({ email }){ this.props.recuperarSenha({ email }); } renderAlert(){ if (this.props.errorMessage) { return( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } } renderField(fieldConfig, field){ const fieldHelper = this.props.fields[field]; return( <fieldset className={(fieldHelper.touched && fieldHelper.invalid) ? "form-group has-error has-feedback" : "form-group"} key={`${fieldConfig.type}\_${fieldConfig.label}`}> <label className="control-label center">{fieldConfig.titulo}</label> <input className="form-control" {...fieldHelper} type={fieldConfig.type} placeholder={`Coloque ${fieldConfig.label}`}/> {fieldHelper.touched && fieldHelper.error && <div className="help-block">{fieldHelper.error}</div>} </fieldset> ); } render(){ const { handleSubmit, submitting, fields: { email }} = this.props; return( <div> <div> <h2 className="title">Agenda de Eventos Interlegis</h2> <h3>Sistema para agendamento de eventos a serem realizados no prédio Interlegis</h3> </div> <div className="center-div-flex"> <div className="panel panel-primary col-md-5 center"> <div className="panel-heading text-center">Esqueci minha Senha</div> <div className="panel-body center col-md-12"> <form onSubmit={handleSubmit(this.handleSubmitForm.bind(this))} className="center col-md-12" style={{paddingBottom: 10}}> {_.map(FIELD_ESQUECI_SENHA, this.renderField.bind(this))} {this.renderAlert()} <div className="login-button"> <button type="submit" disabled={submitting} className={(email.touched && email.invalid)? "btn btn-primary btn-md disabled" : "btn btn-primary btn-md"}> Recuperar Senha </button> </div> </form> </div> </div> </div> </div> ); } } function validate(values) { const errors = {}; var re_email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; _.each(FIELD_ESQUECI_SENHA, (fieldConfig, field) => { if (!values[field]) { errors[field] = `Por favor, insira ${fieldConfig.label}...`; } if (values[field] && fieldConfig.type == 'email' && !re_email.test(values[field])) { errors[field] = `Por favor, insira um email em formato valido!`; } }); return errors; } function mapStateToProps(state){ return { errorMessage: state.authentication.error }; } export default reduxForm({ form: 'login', fields: _.keys(FIELD_ESQUECI_SENHA), validate }, mapStateToProps, { recuperarSenha })(EsqueciSenha);
shopping-cart-app/src/components/routes/AddNewStore/AddNewStore.js
JCFlores/shoppingCart
import React, { Component } from 'react'; import Header from '../../Header'; import AddNewStoreAction from './AddNewStoreAction' import './AddNewStore.css'; class Signup extends Component { constructor(props) { super(props); console.log(props); this.state = { storeName: '', description: '', image: '' }; // use post function from AddNewUserAction.js this.AddNewStoreAction = new AddNewStoreAction(); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); } handleSubmit(event) { event.preventDefault(); this.AddNewStoreAction.addNewStore(this.state.storeName, this.state.description, this.state.image, this.props.match.params.id); } render () { return ( <div> <Header /> <section className="hero"> <div className="hero-body"> <div className="container store-name"> <h1 className="title">Tell Us About Your Store</h1> </div> </div> </section> <section> <div className="container form-container"> <form onSubmit={this.handleSubmit}> <div className="field"> <label className="label"> Store Name: </label> <input type="text" className="input" placeholder="Store Name" name="storeName" value={this.state.value} onChange={this.handleChange} /> </div> <div className="field"> <label className="label"> Description of Your Store: </label> <input type="text" className="input" placeholder="Description of Your Store" name="description" value={this.state.value} onChange={this.handleChange} /> </div> <div className="field"> <label className="label"> Image of Your Store: </label> <input type="password" className="input" placeholder="Paste a Link to an Image of Your Store" name="image" value={this.state.value} onChange={this.handleChange} /> </div> <button className="button signup-button"type="submit">Submit</button> </form> </div> </section> </div> ); } } export default Signup;
js/jqwidgets/demos/react/app/grid/foreignkeycolumn/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { render() { let employeesSource = { datatype: 'xml', datafields: [ { name: 'FirstName', type: 'string' }, { name: 'LastName', type: 'string' } ], root: 'Employees', record: 'Employee', id: 'EmployeeID', url: '../sampledata/employees.xml', async: false }; let employeesAdapter = new $.jqx.dataAdapter(employeesSource, { autoBind: true, beforeLoadComplete: (records) => { let data = new Array(); // update the loaded records. Dynamically add EmployeeName and EmployeeID fields. for (let i = 0; i < records.length; i++) { let employee = records[i]; employee.EmployeeName = employee.FirstName + ' ' + employee.LastName; employee.EmployeeID = employee.uid; data.push(employee); } return data; } }); // prepare the data let ordersSource = { datatype: 'xml', datafields: [ // name - determines the field's name. // values - specifies the field's values. // values.source - specifies the foreign source. The expected value is an array. // values.name - specifies the field's name in the foreign source. // When the ordersAdapter is loaded, each record will have a field called 'EmployeeID'. The 'EmployeeID' for each record will come from the employeesAdapter where the record's 'EmployeeID' from orders.xml matches to the 'EmployeeID' from employees.xml. { name: 'EmployeeID', map: 'm\\:properties>d\\:EmployeeID', values: { source: employeesAdapter.records, name: 'EmployeeName' } }, { name: 'ShippedDate', map: 'm\\:properties>d\\:ShippedDate', type: 'date' }, { name: 'Freight', map: 'm\\:properties>d\\:Freight', type: 'float' }, { name: 'ShipName', map: 'm\\:properties>d\\:ShipName' }, { name: 'ShipAddress', map: 'm\\:properties>d\\:ShipAddress' }, { name: 'ShipCity', map: 'm\\:properties>d\\:ShipCity' }, { name: 'ShipCountry', map: 'm\\:properties>d\\:ShipCountry' } ], root: 'entry', record: 'content', id: 'm\\:properties>d\\:OrderID', url: '../sampledata/orders.xml', pager: (pagenum, pagesize, oldpagenum) => { // callback called when a page or page size is changed. } }; let ordersAdapter = new $.jqx.dataAdapter(ordersSource); let columns = [ { text: 'Employee Name', datafield: 'EmployeeID', width: 150 }, { text: 'Ship City', datafield: 'ShipCity', width: 150 }, { text: 'Ship Country', datafield: 'ShipCountry', width: 150 }, { text: 'Ship Name', datafield: 'ShipName' } ]; return ( <JqxGrid width={850} source={ordersAdapter} pageable={true} autoheight={true} columns={columns} selectionmode={'multiplecellsadvanced'} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/components/DropdownButton/DropdownButton.stories.js
InsideSalesOfficial/insidesales-components
import React from 'react'; import { storiesOf } from '@storybook/react'; import DropdownButton from './DropdownButton'; import Icons from '../icons'; import { wrapComponentWithContainerAndTheme, colors } from "../styles"; const SFIcon = Icons.ColoredSalesforceIcon; const buttonAction = (selectedOption) => { alert(`Clicked ${selectedOption.label}!`) }; const dropdownOptions = [ { value: '1', label: 'Option 1', }, { value: '2', label: 'Option 2', } ]; function renderChapterWithTheme(theme) { return { info: ` Usage ~~~ import React from 'react'; import { DropdownButton } from 'insidesales-components'; ~~~ `, chapters: [ { sections: [ { title: 'Default', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton options={dropdownOptions} onClick={buttonAction} /> ) }, { title: 'Disabled', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton disabled options={dropdownOptions} onClick={buttonAction} /> ) }, { title: 'Danger', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton danger options={dropdownOptions} onClick={buttonAction} /> ) }, { title: 'Gray', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton options={dropdownOptions} onClick={buttonAction} theme={{gray: true}} /> ) }, { title: 'With Icon', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton options={dropdownOptions} onClick={buttonAction} icon={ <SFIcon size={{ width: 24, height: 16.45 }} />} /> ) }, { title: 'Gray with Icon', sectionFn: () => wrapComponentWithContainerAndTheme(theme, <DropdownButton options={dropdownOptions} onClick={buttonAction} theme={{gray: true}} icon={ <SFIcon size={{ width: 24, height: 16.45 }} />} /> ) }, ] } ] }; } storiesOf('Base', module) .addWithChapters("Default DropdownButton", renderChapterWithTheme({})) .addWithChapters( "DropdownButton w/ BlueYellow Theme", renderChapterWithTheme(colors.blueYellowTheme) );
src/components/routeToTab1.js
dfw-chris-diaz/react-demo
import React from 'react'; import MainPage from './mainPage'; const defaultTab = 1; export default function RouteToTab1(){ return( <MainPage defaultTab={defaultTab} /> ); }
node_modules/react-bootstrap/es/Grid.js
ASIX-ALS/asix-final-project-frontend
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: PropTypes.bool, /** * You can use a custom element for this component */ componentClass: elementType }; var defaultProps = { componentClass: 'div', fluid: false }; var Grid = function (_React$Component) { _inherits(Grid, _React$Component); function Grid() { _classCallCheck(this, Grid); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Grid.prototype.render = function render() { var _props = this.props, fluid = _props.fluid, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = prefix(bsProps, fluid && 'fluid'); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Grid; }(React.Component); Grid.propTypes = propTypes; Grid.defaultProps = defaultProps; export default bsClass('container', Grid);
examples/cra/src/components/Placeholder.js
bluetidepro/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './Placeholder.css'; /** * Image placeholders. */ export default class Placeholder extends Component { static propTypes = { type: PropTypes.oneOf([ 'animal', 'bacon', 'beard', 'bear', 'cat', 'food', 'city', 'nature', 'people', ]), width: PropTypes.number, height: PropTypes.number, }; static defaultProps = { type: 'animal', width: 150, height: 150, }; getImageUrl() { const { type, width, height } = this.props; const types = { animal: `http://placeimg.com/${width}/${height}/animals`, bacon: `http://baconmockup.com/${width}/${height}`, bear: `http://www.placebear.com/${width}/${height}`, beard: `http://placebeard.it/${width}/${height}`, cat: `http://lorempixel.com/${width}/${height}/cats`, city: `http://lorempixel.com/${width}/${height}/city`, food: `http://lorempixel.com/${width}/${height}/food`, nature: `http://lorempixel.com/${width}/${height}/nature`, people: `http://lorempixel.com/${width}/${height}/people`, }; return types[type]; } render() { const { type, width, height } = this.props; return ( <img className="placeholder" src={this.getImageUrl()} alt={type} width={width} height={height} /> ); } }
src/components/footer.js
ninalouw/portfolio
import React, { Component } from 'react'; import { Link } from 'react-router'; import FontAwesome from 'react-fontawesome'; import FontIcon from 'material-ui/FontIcon'; import {red500, yellow500, blue500} from 'material-ui/styles/colors'; import {Row, Col} from 'react-materialize'; class Footer extends Component { render () { const iconStyles = { marginRight: 24, }; return ( <footer className="footer"> <Row> <Col s={3} m={2} l={2} className="footer-elem"> <FontIcon className="material-icons" style={iconStyles}>home</FontIcon><p>Get in Touch</p> </Col> <Col s={3} m={2} l={2} className="footer-elem"> <FontIcon className="material-icons" style={iconStyles} color={red500}>phone</FontIcon><p>604 405 6789</p> </Col> <Col s={3} m={2} l={2} className="footer-elem"> <a className="footer-a" href="mailto:[email protected]"><FontIcon className="material-icons" style={iconStyles} color={yellow500}>email</FontIcon><p>[email protected]</p></a> </Col> <Col s={3} m={2} l={2} className="footer-elem"> <a href="https://www.linkedin.com/in/ninamaelouw/"> <FontAwesome className="fa-icon-footer" name='linkedin' size='2x'/> </a> </Col> <Col s={3} m={2} l={2} className="footer-elem"> <a href="https://twitter.com/ninamaelouw"> <FontAwesome className="fa-icon-footer" name='twitter' size='2x'/> </a> </Col> <Col s={3} m={2} l={2} className="footer-elem"> <a href="https://github.com/ninalouw"> <FontAwesome className="fa-icon-footer" name='github' size='2x'/> </a> </Col> </Row> </footer> ); } } export default Footer;
src/modules/Input/components/SocketSettings/index.js
ruebel/synth-react-redux
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import styled from 'styled-components'; import Button from '../../../components/Button'; import ButtonGroup from '../../../components/ButtonGroup'; import Close from '../../../components/icons/Close'; import Gear from '../../../components/icons/Gear'; import H1 from '../../../components/typography/H1'; import InputGroup from '../../../components/InputGroup'; import JsonViewer from './JsonViewer'; import MinMax from '../../../components/MinMax'; import Modal from '../../../components/Modal'; import Refresh from '../../../components/icons/Refresh'; import Scale from './Scale'; import Select from '../../../components/Select'; import TextInput from '../../../components/TextInput'; import { getSocketPrevious, getSocketSettings } from '../../selectors'; const Actions = styled.div` position: absolute; top: 5px; right: 5px; `; const Wrapper = styled.div` width: 60vw; flex: 1; `; class SocketSettings extends React.Component { constructor(props) { super(props); this.state = { hasChange: false, options: [], previous: props.settings, raw: props.previous.raw, settings: props.settings, showRaw: false }; this.handleChange = this.handleChange.bind(this); this.handleClose = this.handleClose.bind(this); this.handleSave = this.handleSave.bind(this); this.hideRaw = this.hideRaw.bind(this); this.refreshMessage = this.refreshMessage.bind(this); } componentWillReceiveProps(next) { if (next.previous.raw && !this.state.raw) { this.refreshMessage(); } } handleClose() { if (this.state.hasChange) { this.props.save(this.state.previous); } this.setState({ hasChange: false, settings: this.state.previous }); this.props.close(); } handleChange(e, prop) { this.setState({ hasChange: true, settings: Object.assign(this.state.settings, { [prop]: e.target ? e.target.value : e }), raw: prop === 'url' ? this.props.previous.raw : this.state.raw }); } handleSave() { this.props.save(this.state.settings); this.setState({ previous: this.state.settings }); } hideRaw() { this.setState({ showRaw: false }); } refreshMessage() { this.setState({ raw: this.props.previous.raw, showRaw: true }); } render() { const icon = ( <Gear fill="rgba(0, 0, 0, 0.3)" height="100vw" width="100vw" /> ); return this.props.show ? ( <Modal close={this.handleClose} icon={icon}> <Wrapper> <H1>Event Source Settings</H1> <InputGroup label="Url" required require={this.state.url}> <TextInput change={e => this.handleChange(e, 'url')} placeholder="Url" required value={this.state.settings.url} /> </InputGroup> <JsonViewer data={this.state.raw} minimized={!this.state.showRaw}> <Actions> <Refresh click={this.refreshMessage} /> {this.state.showRaw && <Close click={this.hideRaw} />} </Actions> </JsonViewer> <InputGroup label="Velocity Trigger"> <Select labelKey="name" onChange={e => this.handleChange(e.id, 'velocityScalar')} options={Object.keys(this.state.raw || {}).map(k => ({ id: k, name: k }))} searchable={false} value={this.state.settings.velocityScalar} valueKey="id" /> </InputGroup> <InputGroup label="Scale"> <Scale keys={this.state.settings.scale} onChange={e => this.handleChange(e, 'scale')} /> </InputGroup> <InputGroup label="Note Length"> <MinMax max={5000} min={0} step={10} onSet={e => this.handleChange(e, 'noteLength')} value={this.state.settings.noteLength} /> </InputGroup> <ButtonGroup> <Button active click={this.handleClose} text="Cancel" type="danger" /> <Button active={Boolean(this.state.hasChange)} click={this.handleSave} text="Save" /> </ButtonGroup> </Wrapper> </Modal> ) : null; } } SocketSettings.propTypes = { close: PropTypes.func.isRequired, previous: PropTypes.object, save: PropTypes.func.isRequired, settings: PropTypes.object, show: PropTypes.bool }; const mapStateToProps = state => ({ previous: getSocketPrevious(state), settings: getSocketSettings(state) }); export default connect(mapStateToProps, null)(SocketSettings);
src/components/AppContent/index.js
currency-cop/currency-cop
import React from 'react' class AppContent extends React.Component { componentDidMount() { this.screen = this.props.screenAction } componentDidUpdate() { if (this.props.screenAction != this.screen) { this._div.scrollTop = 0 this.screen = this.props.screenAction } } render () { let screen = this.props.screen return ( <div className="layout-item content" ref={(ref) => this._div = ref}> { screen } </div> ) } } export default AppContent
src/components/layout/Layout.js
gribnoysup/diy-dog-search
import React from 'react' import styled from 'styled-components' import {fontFamilyMonospace} from '../common/Typography' export const Container = styled.div` width: 100%; height: 100%; display: flex; flex-direction: column; ` Container.displayName = 'Container' const HeaderDiv = styled.div` color: #ffffff; background-color: #000000; display: flex; align-items: center; width: 100%; min-height: 56px; padding: 0 20px; box-sizing: border-box; justify-content: space-between; & > *:first-child { margin-left: 0; } & > *:last-child { margin-right: 0; } ${(props) => props.sticky ? ` position: fixed; z-index: 999; left: 0; top: 0; ` : ''} @media screen and (min-width: 48em) { justify-content: flex-start; } ` export class Header extends React.Component { static propTypes = { sticky: React.PropTypes.bool } fixBody(node) { document.body.style.paddingTop = this.getHeight(node) + 'px' } unfixBody() { document.body.style.paddingTop = '' } getHeight(node) { return node ? node.getBoundingClientRect().height : 0 } handleRef(ref) { if (this.props.sticky) { ref ? this.fixBody(ref) : this.unfixBody() } } render() { const {children, sticky} = this.props return ( <HeaderDiv sticky={sticky} innerRef={(ref) => this.handleRef(ref)} > {children} </HeaderDiv> ) } } export const Content = styled.div` flex: 1 0 auto; display: flex; flex-direction: column; padding: 0 20px; margin: 20px auto; width: 100%; max-width: 760px; box-sizing: border-box; ` Content.displayName = 'Content' export const Body = styled.div` display: flex; flex-direction: column; width: 100%; min-height: 100%; ` Body.displayName = 'Body' export const Footer = styled.div` width: 100%; box-sizing: border-box; background-color: #000000; color: #ffffff; font-family: ${fontFamilyMonospace}; font-size: 12px; font-weight: bold; display: flex; flex-direction: column; align-items: center; padding: 0 20px; padding-bottom: 10px; & a { color: #ffffff; &:visited { color: #afafaf; } } & p { margin-top: 10px; margin-bottom: 0; text-align: center; max-width: 410px; } @media screen and (min-width: 35.5em) { padding-bottom: 20px; & p { margin-top: 20px; } } ` Footer.displayName = 'Footer'
app/src/App.js
sfelderman/inverted-index
import React, { Component } from 'react'; import DragSubmit from './DragSubmit'; import SearchBar from './search/SearchBar'; import DisplaySearch from './display/DisplaySearch'; import styles from './App.css'; class App extends Component { render() { return ( <div style={styles}> <DragSubmit /> <SearchBar /> <DisplaySearch /> </div> ); } } export default App;
example/story.js
yangshun/react-storybook-addon-chapters
import { storiesOf } from '@storybook/react'; import React from 'react'; import Button from './Button'; storiesOf('Addon Chapters', module) .addWithChapters( 'Story With Chapters', { useTheme: false, subtitle: 'Display multiple components within one story!', info: ` React Storybook Chapters addon allows showcasing of multiple components within a story by breaking it down into smaller categories (**Chapters**) and subcategories (**Sections**) for more organizational goodness. This section is called **Story Info** and you can provide an abstract of your story here. A story consists of multiple chapters and a chapter consists of multiple sections. Each section can render a block of code, which typically used to showcase one component or a particular state of a component. Yes, all info sections support markdown formatting! `, chapters: [ // List of chapters. { title: 'This is a Chapter\'s Title', subtitle: 'And this is a chapter\'s subtitle', info: ` Chapters can be used to group related components together, or show varying states of a component. Each chapter comes with a **Chapter Title**, **Chapter Subtitle**, **Chapter Info** and a list of **Sections**. Simply omit any of them to hide them from rendering. `, sections: [ // List of sections. { title: 'This is a Section\'s Title', subtitle: 'Each section can be used to render a component', info: ` Provide additional information about your section here. Each section comes with a **Section Title**, **Section Subtitle**, **Section Info**. Simply omit any of them to hide them from rendering. The section below does not have a subtitle nor info. There's also the option of showing the source code and propTypes of the component. `, sectionFn: () => (<Button label="My Button" onClick={() => { alert('Hello World!'); }} />), options: { showSource: false, allowSourceToggling: true, showPropTables: true, allowPropTablesToggling: true, }, }, { title: 'Here\'s another section, but without subtitle and info', sectionFn: () => (<Button label="My Disabled Button" disabled onClick={() => { }} />), }, ], }, { title: 'Usage', info: ` Install the following npm module: ~~~ npm install --save-dev react-storybook-addon-chapters ~~~ Then set the addon in the place you configure storybook like this: ~~~ import React from 'react'; import { configure, setAddon } from '@storybook/react'; import chaptersAddon from 'react-storybook-addon-chapters'; setAddon(chaptersAddon); configure(function () { ... }, module); ~~~ Then create your stories with the **.addWithChapters** API. ~~~ import React from 'react'; import Button from './Button'; import { storiesOf } from '@storybook/react'; storiesOf('Addon Chapters') .addWithChapters( 'Story With Chapters', { subtitle: <Optional story subtitle>, info: <Optional story info>, chapters: [ // List of chapters. { title: <Optional chapter title>, subtitle: <Optional chapter subtitle>, info: <Optional chapter info>, sections: [ // List of sections. { title: <Optional section title>, subtitle: <Optional section subtitle>, info: <Optional section info>, sectionFn: () => (<Button>My Button</Button>), options: { showSource: true, allowSourceToggling: true, showPropTables: true, allowPropTablesToggling: true, }, }, ... ], }, ... ] } ); ~~~ `, }, ], } ) .addWithChapters( 'Story Without Chapters', { info: ` If you don't require displaying of the chapter information, simply use only one chapter with your list of sections and omit the chapter-related parameters. You'll end up with just a list of rendered sections. Refer to the example in **example/story.js**. `, chapters: [ { sections: [ { title: 'Section Title', subtitle: 'Section Subtitle', info: ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. `, sectionFn: () => (<Button label="My Button" onClick={() => { }} />), }, { title: 'Section Title Again', subtitle: 'Section Subtitle Again', sectionFn: () => (<Button label="My Button Again" onClick={() => { }} />), }, ], }, ], } ); const decorator = story => ( <div style={{ backgroundColor: 'rgba(0, 0, 0, 0.1)', display: 'inline-block', padding: '10px', }} > {story()} </div> ); storiesOf('Addon Chapters', module) .addWithChapters( 'Story With Decorators', { info: ` If you don't require displaying of the chapter information, simply use only one chapter with your list of sections and omit the chapter-related parameters. You'll end up with just a list of rendered sections. Refer to the example in **example/story.js**. `, chapters: [ { sections: [ { title: 'Section Title', subtitle: 'Section Subtitle', info: ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. `, sectionFn: () => (<Button label="My Button" onClick={() => { }} />), options: { decorator, }, }, { title: 'Section Title Again', subtitle: 'Section Subtitle Again', sectionFn: () => (<Button label="My Button Again" onClick={() => { }} />), options: { decorator, }, }, ], }, ], } );
source/components/DataHandler/DataHandler.js
cloud-walker/react-inspect
import React from 'react' import is from 'ramda/src/is' import pipe from 'ramda/src/pipe' import addIndex from 'ramda/src/addIndex' import map from 'ramda/src/map' import keys from 'ramda/src/keys' import stripFunction from '../../utils/stripFunction' import Level from '../Level' import Punctuation from '../Punctuation' import Key from '../Key' import Value from '../Value' import CollapseHandler from '../CollapseHandler' const Component = class extends React.Component { static displayName = 'ReactInspectDataHandler' static defaultProps = { outer: false, } render() { const {data, outer, theme} = this.props if (is(String)(data)) { return <Value type="string" theme={theme}>{`"${data}"`}</Value> } if (is(Number)(data)) { return <Value type="number" theme={theme}>{`${data}`}</Value> } if (is(Function)(data)) { const value = ( <Value type="function" theme={theme}> {stripFunction(String(data))} </Value> ) if (outer) { return value } return ( <CollapseHandler> {show => show ? value : {...value, props: {...value.props, children: 'fn'}}} </CollapseHandler> ) } if (is(Array)(data)) { const value = addIndex(map)((x, i) => ( <Level key={i}> <Component data={x} theme={theme} /> </Level> ))(data) return ( <span> <Punctuation theme={theme}>{'['}</Punctuation> {outer ? ( value ) : ( <CollapseHandler> {show => show ? ( value ) : ( <Punctuation theme={theme}>...</Punctuation> )} </CollapseHandler> )} <Punctuation theme={theme}>{']'}</Punctuation> </span> ) } if (is(Object)(data)) { const value = pipe( keys, map(x => ( <Level key={x}> <Key theme={theme}>{x}</Key> <Punctuation theme={theme}>:</Punctuation>{' '} <Component data={data[x]} theme={theme} /> </Level> )), )(data) return ( <span> <Punctuation theme={theme}>{'{'}</Punctuation> {outer ? ( value ) : ( <CollapseHandler> {show => show ? ( value ) : ( <Punctuation theme={theme}>...</Punctuation> )} </CollapseHandler> )} <Punctuation theme={theme}>{'}'}</Punctuation> </span> ) } return <Value type="keyword" theme={theme}>{`${data}`}</Value> } } export default Component
fluent-react/examples/async-messages/src/index.js
zbraniecki/fluent.js
import React from 'react'; import ReactDOM from 'react-dom'; import { AppLocalizationProvider } from './l10n'; import App from './App'; ReactDOM.render( <AppLocalizationProvider userLocales={navigator.languages}> <App /> </AppLocalizationProvider>, document.getElementById('root') );
src/svg-icons/hardware/keyboard-tab.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardTab = (props) => ( <SvgIcon {...props}> <path d="M11.59 7.41L15.17 11H1v2h14.17l-3.59 3.59L13 18l6-6-6-6-1.41 1.41zM20 6v12h2V6h-2z"/> </SvgIcon> ); HardwareKeyboardTab = pure(HardwareKeyboardTab); HardwareKeyboardTab.displayName = 'HardwareKeyboardTab'; HardwareKeyboardTab.muiName = 'SvgIcon'; export default HardwareKeyboardTab;
src/components/Svg/Expand.js
bibleexchange/be-front-new
import React from 'react'; class Expand extends React.Component { render() { return ( <svg className='expand' x='0' y='0' viewBox='0, 0,250, 250'> <g transform="translate(1.05932,1.0593224)"> <path d="M 15.217893,234.60694 12.5,231.71388 l 0,-82.10694 C 12.5,69.166666 12.550746,67.449254 15,65 c 2.303515,-2.303515 4.166666,-2.5 23.70602,-2.5 19.686451,0 21.298744,-0.173255 22.5,-2.417824 C 61.943967,58.70331 62.5,49.034899 62.5,37.582176 62.5,19.166666 62.707481,17.292519 65,15 c 2.449439,-2.449439 4.166666,-2.5 84.90927,-2.5 l 82.40928,0 2.59072,3.293574 c 2.56095,3.255722 2.59073,4.232552 2.59073,84.999996 0,80.03977 -0.051,81.75743 -2.5,84.20643 -2.30159,2.30159 -4.16666,2.5 -23.5,2.5 -14.66666,0 -21.45238,0.45237 -22.5,1.5 -1.04763,1.04762 -1.5,7.83334 -1.5,22.5 0,19.33334 -0.19841,21.19841 -2.5,23.5 -2.44936,2.44936 -4.16666,2.5 -84.78211,2.5 l -82.282105,0 -2.717893,-2.89306 z M 170.49126,218.02276 C 171.92861,214.2771 171.3232,190.5732 169.75,189 c -1.11725,-1.11725 -14.40869,-1.5 -52.08907,-1.5 -45.319516,0 -50.82719,-0.21549 -52.875004,-2.06874 C 62.644097,183.49294 62.5,180.21771 62.5,133.47409 62.5,101.47516 62.035991,82.718639 61.20602,81.167824 60.054249,79.015717 58.48568,78.75 46.933255,78.75 39.794922,78.75 33.064714,79.091431 31.977234,79.508736 30.206889,80.188081 30,87.577954 30,150.13374 L 30,220 l 69.866264,0 c 62.555786,0 69.945646,-0.20689 70.624996,-1.97724 z m 47.5315,-47.5315 C 219.79311,169.81191 220,162.42205 220,99.866264 L 220,30 150.13374,30 C 87.577954,30 80.188081,30.206889 79.508736,31.977234 79.091431,33.064714 78.75,64.170964 78.75,101.10223 c 0,50.55938 0.370565,67.51833 1.5,68.64777 1.129435,1.12944 18.088392,1.5 68.64776,1.5 36.93128,0 68.03753,-0.34143 69.125,-0.75874 z M 103.31874,146.46407 c -1.13781,-1.25726 -2.06874,-3.92522 -2.06874,-5.92881 0,-3.09746 4.90752,-8.55305 32.77684,-36.43724 21.62741,-21.638971 32.35593,-33.215242 31.5395,-34.031677 -0.68053,-0.68053 -8.47999,-1.39573 -17.33213,-1.589335 -15.83146,-0.346248 -16.13577,-0.406949 -18.59914,-3.709898 -2.20335,-2.954322 -2.31408,-3.817156 -0.92147,-7.179232 2.38151,-5.749469 7.47775,-6.579084 37.55899,-6.114219 23.45461,0.36246 26.22522,0.63203 28.599,2.782576 2.53362,2.295364 2.62841,3.475408 2.62841,32.723214 0,25.356991 -0.30926,30.651251 -1.8824,32.224381 -3.35229,3.35228 -6.93699,3.7323 -10.45531,1.10838 -3.2153,-2.39793 -3.295,-2.80407 -3.6393,-18.54642 -0.1936,-8.852144 -0.9088,-16.651602 -1.58933,-17.332132 -0.81644,-0.816435 -12.39271,9.912095 -34.03167,31.539512 -28.72864,28.71328 -33.27291,32.77683 -36.65444,32.77683 -2.15209,0 -4.77544,-1.01146 -5.92881,-2.28593 z" id="path3359" /> </g> </svg> ); } } module.exports = Expand;
app/components/FunctionTestForm/requestBodyBuilder.js
fission/fission-ui
/** * * RequestBodyBuilder * */ import React from 'react'; import AceEditor from 'react-ace'; import 'brace/mode/json'; import 'brace/mode/xml'; import 'brace/mode/plain_text'; import 'brace/theme/monokai'; class RequestBodyBuilder extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const { bodytype, content, onSelectType, onContentChange } = this.props; return ( <div> <select className="form-control" name="bodytype" value={bodytype} onChange={onSelectType}> <option value="plain_text">Text</option> <option value="json">Json</option> <option value="xml">Xml</option> </select> <AceEditor mode={bodytype} theme="monokai" name="RequestBodyForm" value={content} editorProps={{ $blockScrolling: true }} onChange={onContentChange} height="150px" width="100%" /> </div> ); } } RequestBodyBuilder.propTypes = { bodytype: React.PropTypes.string.isRequired, content: React.PropTypes.string.isRequired, onSelectType: React.PropTypes.func.isRequired, onContentChange: React.PropTypes.func.isRequired, }; export default RequestBodyBuilder;
src/views/AboutView.js
dapplab/babel-client
import React from 'react'; import { Link } from 'react-router'; const AboutView = () => ( <div className='container text-center'> <h1>This is the about view!</h1> <hr /> <Link to='/'>Back To Home View</Link> </div> ); export default AboutView;
src/LearnWordsFast/Client/js/components/ChangeLanguages.js
drussilla/LearnWordsFast
import React from 'react'; import Reflux from 'reflux'; import _ from 'lodash'; import {Input, Button, Panel} from 'react-bootstrap'; import {UserSettingsStore, UserSettingsActions} from '../stores/UserSettingsStore'; import {LanguagesStore, LanguagesActions} from '../stores/LanguagesStore'; const ChangeLanguages = React.createClass({ mixins: [ Reflux.listenTo(UserSettingsStore, 'onUserSettingsLoad'), Reflux.listenTo(LanguagesStore, 'onLanguagesLoad') ], getInitialState() { let {userInfo} = UserSettingsStore; let {mainLanguage, trainingLanguage, additionalLanguages} = userInfo || {}; let {languages} = LanguagesStore; return { userInfo, languages, mainLanguage, trainingLanguage, additionalLanguages } }, componentDidMount() { UserSettingsActions.getInfo(); LanguagesActions.getAll(); }, onUserSettingsLoad(data) { let {userInfo} = data; let {mainLanguage, trainingLanguage, additionalLanguages} = userInfo || {}; this.setState({ userInfo, mainLanguage, trainingLanguage, additionalLanguages }); }, onLanguagesLoad(languages) { this.setState({ languages }); }, createLanguagesOptions(type) { if (this.state.languages) { return this.state.languages.filter(language => { if (type === 'main') { return !_.contains(this.state.additionalLanguages, language.id) && language.id !== this.state.trainingLanguage; } else { return !_.contains(this.state.additionalLanguages, language.id) && language.id !== this.state.mainLanguage; } }).map(language => { return <option value={language.id} key={language.id}>{language.name}</option>; }); } }, selectTrainingLanguage(e) { var value = e.target.value; this.setState({ errors: null, trainingLanguage: value }); }, selectMainLanguage(e) { var value = e.target.value; this.setState({ errors: null, mainLanguage: value }) }, selectAdditionalLanguage(id, e) { var additionalLanguages = _.clone(this.state.additionalLanguages); var errors = null; if (e.target.checked) { if (additionalLanguages.length < 5) { additionalLanguages.push(id); } else { errors = ["Don't select more than 5 languages as additional"] } } else { additionalLanguages = additionalLanguages.filter(language => language !== id); } this.setState({ errors: errors, additionalLanguages: additionalLanguages }); }, createCheckboxesForAdditionalLanguages() { if (this.state.languages) { return this.state.languages.filter(language => { return language.id !== this.state.mainLanguage && language.id !== this.state.trainingLanguage; }).map(language => { return <Input type="checkbox" label={language.name} key={language.id} checked={_.contains(this.state.additionalLanguages, language.id)} onChange={this.selectAdditionalLanguage.bind(null, language.id)}/> }); } }, changeLanguages() { let {trainingLanguage, mainLanguage, additionalLanguages} = this.state; UserSettingsActions.changeLanguages({trainingLanguage, mainLanguage, additionalLanguages}) }, render() { if(!this.state.languages) { return (<div>Loading...</div>); } let errors = this.state.errors && this.state.errors.map((error, i) => <div bsStySle="error" key={'error-' + i}> {error} </div>); return ( <div> <Input type="select" label="Training language" placeholder="select" value={this.state.trainingLanguage} onChange={this.selectTrainingLanguage}> {this.createLanguagesOptions.call(null, 'training')} </Input> <Input type="select" label="Main language" placeholder="select" value={this.state.mainLanguage} onChange={this.selectMainLanguage}> {this.createLanguagesOptions.call(null, 'main')} </Input> <label>Additional Languages</label> {this.createCheckboxesForAdditionalLanguages()} <Button bsStyle="primary" onClick={this.changeLanguages}>Change Languages</Button> {errors ? <Panel header="Errors" className="validation-errors" bsStyle="danger"> {errors} </Panel> : null} </div> ); } }); export default ChangeLanguages;
app/components/TemplateItemComponent.js
okmttdhr/pull-request-templates
import React from 'react'; import { Link } from 'react-router' import classNames from 'classnames' import TemplateActions from '../actions/TemplateActions' class TemplateItemComponent extends React.Component { static propTypes = { template: React.PropTypes.object.isRequired }; static defaultProps = {}; constructor(props) { super(props); this.state = {}; } componentDidMount() { // ... } componentWillUnmount() { // ... } shouldComponentUpdate() { return true; } updateTemplate() { TemplateActions.updateSelected(this.props.template.id); } render() { var template = this.props.template; var classes = classNames({ 'active': template.selected }); return ( <li className={classes}> <p onClick={this.updateTemplate.bind(this)}>{template.name}</p> </li> ); } } export default TemplateItemComponent;
examples/05 Customize/Handles and Previews/Container.js
arnif/react-dnd
import React, { Component } from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd/modules/backends/HTML5'; import BoxWithImage from './BoxWithImage'; import BoxWithHandle from './BoxWithHandle'; @DragDropContext(HTML5Backend) export default class Container extends Component { render() { return ( <div> <div style={{ marginTop: '1.5rem' }}> <BoxWithHandle /> <BoxWithImage /> </div> </div> ); } }
app/javascript/mastodon/features/compose/components/warning.js
theoria24/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; export default class Warning extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, }; render () { const { message } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='compose-form__warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> {message} </div> )} </Motion> ); } }
src/parser/deathknight/blood/modules/core/DeathsCaress.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import SpellUsable from 'parser/shared/modules/SpellUsable'; const RANGE_WHERE_YOU_SHOULDNT_DC = 12; // yrd class DeathsCaress extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; dcCasts = 0; cast = []; spellsThatShouldBeUsedFirst = [ SPELLS.DEATH_AND_DECAY.id, ]; constructor(...args) { super(...args); if(this.selectedCombatant.hasTalent(SPELLS.BLOODDRINKER_TALENT.id)) { this.spellsThatShouldBeUsedFirst.push(SPELLS.BLOODDRINKER_TALENT.id); } } on_byPlayer_cast(event) { if (event.ability.guid !== SPELLS.DEATHS_CARESS.id) { return; } const hadAnotherRangedSpell = this.spellsThatShouldBeUsedFirst.some(e => this.spellUsable.isAvailable(e)); this.dcCasts += 1; this.cast.push({ timestamp: event.timestamp, hadAnotherRangedSpell: hadAnotherRangedSpell, playerPosition: { x: event.x, y: event.y, }, enemyPosition: { x: 0, y: 0, }, }); } on_byPlayer_damage(event) { if (event.ability.guid !== SPELLS.DEATHS_CARESS.id || this.cast.length === 0) { return; } this.cast[this.cast.length - 1].enemyPosition = { x: event.x, y: event.y, }; } calculateDistance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / 100; } get badDcCasts() { let badCasts = 0; this.cast.forEach(e => { //only happens when the target died before the damage event occurs if (e.enemyPosition.x === 0 && e.enemyPosition.y === 0) { return; } const distance = this.calculateDistance(e.enemyPosition.x, e.enemyPosition.y, e.playerPosition.x, e.playerPosition.y); if (distance <= RANGE_WHERE_YOU_SHOULDNT_DC || e.hadAnotherRangedSpell) { // close to melee-range => bad || when another ranged spell was available badCasts += 1; } }); return badCasts; } get averageCastSuggestionThresholds() { return { actual: 1 - (this.badDcCasts / this.dcCasts), isLessThan: { minor: 1, average: .95, major: .9, }, style: 'percentage', }; } suggestions(when) { when(this.averageCastSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Avoid casting <SpellLink id={SPELLS.DEATHS_CARESS.id} /> unless you're out of melee range and about to cap your runes while <SpellLink id={SPELLS.DEATH_AND_DECAY.id} /> and <SpellLink id={SPELLS.BLOODDRINKER_TALENT.id} /> are on cooldown. Dump runes primarily with <SpellLink id={SPELLS.HEART_STRIKE.id} />.</>) .icon(SPELLS.DEATHS_CARESS.icon) .actual(`${formatPercentage(this.badDcCasts / this.dcCasts)}% bad ${SPELLS.DEATHS_CARESS.name} casts`) .recommended(`0% are recommended`); }); } } export default DeathsCaress;
frontend/app/index.js
briancappello/flask-react-spa
import 'babel-polyfill' // this must come before everything else otherwise style cascading doesn't work as expected import 'main.scss' import { AppContainer as HotReloadContainer } from 'react-hot-loader' import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/createBrowserHistory' import configureStore from 'configureStore' import App from 'components/App' import { login } from 'security/actions' import { flashInfo } from 'site/actions' import SecurityApi from 'security/api' import { storage } from 'utils' const APP_MOUNT_POINT = document.getElementById('app') const initialState = {} const history = createBrowserHistory() const store = configureStore(initialState, history) const renderRootComponent = (Component) => { ReactDOM.render( <HotReloadContainer> <Component store={store} history={history} /> </HotReloadContainer>, APP_MOUNT_POINT ) } const token = storage.getToken() store.dispatch(login.request()) SecurityApi.checkAuthToken(token) .then(({ user }) => { store.dispatch(login.success({ token, user })) }) .catch(() => { store.dispatch(login.failure()) }) .then(() => { store.dispatch(login.fulfill()) renderRootComponent(App) const isAuthenticated = store.getState().security.isAuthenticated const alreadyHasFlash = store.getState().flash.visible if (isAuthenticated && !alreadyHasFlash) { store.dispatch(flashInfo('Welcome back!')) } }) if (module.hot) { module.hot.accept('./components/App', () => { ReactDOM.unmountComponentAtNode(APP_MOUNT_POINT) const NextApp = require('./components/App').default renderRootComponent(NextApp) }) }
examples/js/column/column-align-table.js
neelvadgama-hailo/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class ColumnAlignTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true } dataAlign='center'>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' headerAlign='right'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' headerAlign='center' dataAlign='right'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/components/header/Palette.js
numb86/image-editor
// @flow import React from 'react'; import {DRAW_LINE} from '../actionLayer/ActionLayer'; import type {ActionLayerName} from '../actionLayer/ActionLayer'; import type {ChangeableActionLayerSettings} from '../../state/generateActionLayerSettings'; const COLOR_LIST = [ '#000', // 黒 '#fff', // 白 '#f00', // 赤 '#f90', // オレンジ '#ff3', // 黄色 '#60f', // 青 '#9ff', // 水色 '#f0f', // 紫 '#6f0', // 緑 '#960', // 茶色 ]; export default function Palette({ updateActionLayerSettings, }: { updateActionLayerSettings: ( target: ActionLayerName, data: ChangeableActionLayerSettings ) => void, }) { function update(color) { updateActionLayerSettings(DRAW_LINE, {strokeStyle: color}); } // TODO: Fragments を使う return ( <span className="palette"> {COLOR_LIST.map(color => ( <button key={color} style={{backgroundColor: color}} onClick={() => { update(color); }} /> ))} </span> ); }
frontend/src/components/submitcast/CastRoleInput.js
tdv-casts/website
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardHeader, CardText, CardActions } from 'material-ui/Card'; import Chip from 'material-ui/Chip'; import FlatButton from 'material-ui/FlatButton'; import FastForward from 'material-ui/svg-icons/av/fast-forward'; import Done from 'material-ui/svg-icons/action/done'; import CastRoleAutoComplete from './CastRoleAutoComplete'; const rolesWithMultipleActors = [ 'Tanzsolisten', 'Gesangssolisten', 'Tanzensemble', 'Gesangsensemble', ]; const maleRoles = [ 'Graf von Krolock', 'Professor Abronsius', 'Alfred', 'Chagal', 'Herbert', 'Koukol', ]; class CastRoleInput extends React.Component { static propTypes = { role: PropTypes.string.isRequired, dataSource: PropTypes.array.isRequired, onFinish: PropTypes.func.isRequired, cardStyle: PropTypes.object, }; static defaultProps = { cardStyle: {}, }; state = { actors: [], }; componentWillReceiveProps(nextProps) { if (this.props.role !== nextProps.role) { this.setState({ actors: [] }); } }; doesAllowMultipleActors() { const { role } = this.props; return rolesWithMultipleActors.includes(role); }; getFilteredDataSource() { const { dataSource } = this.props; const { actors } = this.state; const alreadyListedNames = actors.map(person => person.name); return dataSource.filter(person => !alreadyListedNames.includes(person.name)); }; toChipKey(person) { const { role } = this.props; return `chip-${role}-${person.id}`; }; fireOnFinish = () => { const { actors } = this.state; this.props.onFinish(actors); }; handleAutoCompletion = person => { if (this.doesAllowMultipleActors()) { this.setState({actors: this.state.actors.concat(person)}); } else { this.setState({actors: [person]}, this.fireOnFinish); } }; handleUpdate = (searchText, dataSource, params) => { if (!this.doesAllowMultipleActors()) { this.setState({ actors: [] }); } }; handleRemoveChip = key => { const {actors} = this.state; const filtered = actors.filter(actor => this.toChipKey(actor) !== key); this.setState({ actors: filtered }); this.focus(); }; focus() { if (this.input) { this.input.focus(); } }; getHeaderSubtitle() { if (this.doesAllowMultipleActors()) { return 'Welche DarstellerInnen haben diese Rolle gespielt?'; } if (maleRoles.includes(this.props.role)) { return 'Welcher Darsteller hat diese Rolle gespielt?'; } return 'Welche Darstellerin hat diese Rolle gespielt?'; }; renderHeader() { const { role } = this.props; return ( <CardHeader title={role} subtitle={this.getHeaderSubtitle()} expandable={false} /> ); }; renderInput() { const { role } = this.props; if (!this.doesAllowMultipleActors() && this.state.actors.length > 0) { return null; } return ( <CastRoleAutoComplete role={role} allowsMultipleEntries={this.doesAllowMultipleActors()} dataSource={this.getFilteredDataSource()} onSubmit={this.handleAutoCompletion} onUpdate={this.handleUpdate} ref={element => this.input = element} /> ); }; renderChips() { const { actors } = this.state; if (actors.length === 0 || !this.doesAllowMultipleActors()) { return null; } const chips = actors.map(actor => { const key = this.toChipKey(actor); return ( <Chip key={key} onRequestDelete={() => this.handleRemoveChip(key)} > {actor.name} </Chip> ); }); const style = { display: 'flex', flexWrap: 'wrap', marginTop: '1em', }; return ( <div style={style}> {chips} </div> ); }; renderActions() { const isSkip = this.state.actors.length === 0; const label = isSkip ? 'Überspringen' : 'Weiter'; const icon = isSkip ? (<FastForward />) : (<Done />); return ( <CardActions> <FlatButton label={label} onTouchTap={this.fireOnFinish} icon={icon} /> </CardActions> ); }; // TODO FIXME Display green / icon when name is entered and "Next" can be clicked. render() { const { cardStyle } = this.props; return ( <Card style={cardStyle}> {this.renderHeader()} <CardText> {this.renderInput()} {this.renderChips()} </CardText> {this.renderActions()} </Card> ); }; } export default CastRoleInput;
packages/veritone-widgets/src/widgets/EngineSelection/EngineListView/EngineListContainer/EngineSelectionRow/index.js
veritone/veritone-sdk
import React from 'react'; import { connect } from 'react-redux'; import { bool, object, func, string, shape, any } from 'prop-types'; import { get } from 'lodash'; import { Lozenge, Truncate } from 'veritone-react-common'; import { modules } from 'veritone-redux-common'; const { engine: engineModule } = modules; import Checkbox from '@material-ui/core/Checkbox'; import { withStyles } from '@material-ui/styles'; import networkIsolatedLogo from '../../../images/networkisolated_logo.png'; import externalAccessLogo from '../../../images/externalaccess_logo.png'; import externalProcessingLogo from '../../../images/externalprocessing_logo.png'; import humanReviewLogo from '../../../images/humanreview_logo.png'; import * as engineSelectionModule from '../../../../../redux/modules/engineSelection'; import ToggleButton from '../../../ToggleButton/'; import styles from './styles'; @withStyles(styles) @connect( (state, ownProps) => ({ isSelected: engineSelectionModule.engineIsSelected( state, ownProps.engineId, ownProps.id ), engine: engineModule.getEngine(state, ownProps.engineId), isChecked: engineSelectionModule.engineIsChecked( state, ownProps.engineId, ownProps.id ) }), { selectEngines: engineSelectionModule.selectEngines, deselectEngines: engineSelectionModule.deselectEngines, checkEngine: engineSelectionModule.checkEngine, uncheckEngine: engineSelectionModule.uncheckEngine } ) export default class EngineSelectionRow extends React.Component { static propTypes = { id: string.isRequired, engine: shape({ id: string.isRequired, name: string.isRequired, category: object, description: string, iconPath: string, ownerOrganization: object }).isRequired, isSelected: bool.isRequired, isChecked: bool.isRequired, onViewDetail: func.isRequired, selectEngines: func.isRequired, deselectEngines: func.isRequired, checkEngine: func.isRequired, uncheckEngine: func.isRequired, classes: shape({ any }), }; handleChange = () => { this.props.isChecked ? this.props.uncheckEngine(this.props.id, this.props.engine.id) : this.props.checkEngine(this.props.id, this.props.engine.id); }; handleClick = () => { this.props.onViewDetail(this.props.engine); }; render() { const { classes } = this.props; const { name, iconClass, color } = this.props.engine.category || {}; const deploymentModelLogo = { FullyNetworkIsolated: networkIsolatedLogo, MostlyNetworkIsolated: externalAccessLogo, NonNetworkIsolated: externalProcessingLogo, HumanReview: humanReviewLogo }; return ( <div className={classes.row}> <div className={classes.avatar}> {this.props.engine.iconPath ? ( <img className={classes.icon} src={this.props.engine.iconPath} /> ) : ( <i className="icon-engines" /> )} <div className={classes.engineSelect}> <Checkbox color="primary" onChange={this.handleChange} checked={this.props.isChecked} /> </div> </div> <div className={classes.container}> <div className={classes.primary}> <div className={classes.main}> <div className={classes.headings}> <div className={classes.title} onClick={this.handleClick}> {this.props.engine.name} </div> <div className={classes.orgName}> {get(this.props, 'engine.ownerOrganization.name')} </div> </div> </div> <div className={classes.info}> {name && ( <Lozenge iconClassName={iconClass} backgroundColor={color}> {name} </Lozenge> )} </div> <div className={classes.description}> {this.props.engine.description && ( <Truncate clamp={3}>{this.props.engine.description}</Truncate> )} </div> </div> <div className={classes.secondary}> <div className={classes.logos}> <div className={classes.logo}> <img className={classes.icon} src={deploymentModelLogo[this.props.engine.deploymentModel]} /> </div> </div> <div> <ToggleButton id={this.props.id} onAdd={this.props.selectEngines} onRemove={this.props.deselectEngines} engineId={this.props.engine.id} isSelected={this.props.isSelected} /> </div> </div> </div> </div> ); } }
packages/cockpit/ui/src/components/Layout.js
iurimatias/embark-framework
import React from 'react'; import {NavLink as RNavLink} from 'react-router-dom'; import {Link, withRouter} from 'react-router-dom'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import { UncontrolledTooltip, DropdownItem, DropdownMenu, DropdownToggle, Nav, NavItem, NavLink, Container, Alert } from 'reactstrap'; import {explorerSearch} from "../actions"; import {LIGHT_THEME, DARK_THEME} from '../constants'; import FontAwesome from 'react-fontawesome'; import "./Layout.css"; import { AppHeader, AppSidebar, AppSidebarFooter, AppSidebarForm, AppSidebarHeader, AppSidebarMinimizer, AppSidebarNav, AppNavbarBrand, AppHeaderDropdown } from '@coreui/react'; import {searchResult} from "../reducers/selectors"; import SearchBar from './SearchBar'; import logo from '../images/logo-brand-new.png'; import './Layout.css'; const HEADER_NAV_ITEMS = [ {name: "Dashboard", to: "/", icon: 'tachometer'}, {name: "Deployment", to: "/deployment", icon: "arrow-up"}, {name: "Explorer", to: "/explorer/overview", base: "explorer/", icon: "compass"}, {name: "Editor", to: "/editor", icon: "codepen"}, {name: "Utils", to: "/utilities/converter", base: "utilities/", icon: "cog"} ]; const SIDEBAR_NAV_ITEMS = { "/explorer" : {items: [ {url: "/explorer/overview", icon: "fa fa-signal", name: "Overview"}, {url: "/explorer/accounts", icon: "fa fa-users", name: "Accounts"}, {url: "/explorer/blocks", icon: "fa fa-stop", name: "Blocks"}, {url: "/explorer/contracts", icon: "fa fa-file-code-o", name: "Contracts"}, {url: "/explorer/transactions", icon: "fa fa-exchange", name: "Transactions"} ]}, "/utilities/": {items: [ {url: "/utilities/converter", icon: "fa fa-plug", name: "Converter"}, {url: "/utilities/communication", icon: "fa fa-phone", name: "Communication"}, {url: "/utilities/ens", icon: "fa fa-circle", name: "ENS"}, {url: "/utilities/sign-and-verify", icon: "fa fa-edit", name: "Sign & Verify"}, {url: "/utilities/transaction-decoder", icon: "fa fa-edit", name: "Transaction Decoder"} ]} }; const removeCssClasses = () => { document.body.classList.remove('sidebar-fixed'); document.body.classList.remove('sidebar-lg-show'); }; const getSidebar = (location) => { const currentItem = Object.keys(SIDEBAR_NAV_ITEMS).find(path => location.pathname.startsWith(path)); return currentItem && SIDEBAR_NAV_ITEMS[currentItem]; }; class Layout extends React.Component { constructor(props) { super(props); this.state = { searchLoading: false, searchError: false }; } shouldComponentUpdate(nextProps) { if (nextProps.searchResult && Object.keys(nextProps.searchResult).length && nextProps.searchResult !== this.props.searchResult) { this.setState({searchLoading: false}); if (nextProps.searchResult.error) { this.setState({searchError: true}); return true; } else { this.setState({searchError: false}); } if (nextProps.searchResult.className) { this.props.history.push(`/explorer/contracts/${nextProps.searchResult.className}`); return false; } if (nextProps.searchResult.address) { this.props.history.push(`/explorer/accounts/${nextProps.searchResult.address}`); return false; } if (nextProps.searchResult.hasOwnProperty('transactionIndex')) { this.props.history.push(`/explorer/transactions/${nextProps.searchResult.hash}`); return false; } if (nextProps.searchResult.hasOwnProperty('number')) { this.props.history.push(`/explorer/blocks/${nextProps.searchResult.number}`); return false; } // Returned something we didn't know existed } return true; } searchTheExplorer(value) { this.props.explorerSearch(value); this.setState({searchLoading: true}); } dismissSearchError() { this.setState({searchError: false}); } isActive = (itemUrl, baseUrl, match, location) => { if (itemUrl === location.pathname) { return true; } if (!baseUrl) { return false; } return location.pathname.indexOf(baseUrl) > -1; }; renderNav() { return ( <React.Fragment> <Nav className="header-nav d-lg-down-none" navbar> {HEADER_NAV_ITEMS.map((item) => { return ( <NavItem className="px-3" key={item.to}> <NavLink exact activeClassName="active" tag={RNavLink} to={item.to} isActive={this.isActive.bind(this, item.to, item.base)}> <FontAwesome className="mr-2" name={item.icon}/> {item.name} </NavLink> </NavItem> ); })} </Nav> <AppHeaderDropdown className="list-unstyled d-xl-none" direction="down"> <DropdownToggle nav> <FontAwesome name="bars"/> </DropdownToggle> <DropdownMenu> {HEADER_NAV_ITEMS.map((item) => ( <DropdownItem key={item.to} to={item.to} tag={Link}> <FontAwesome className="mr-2" name={item.icon} /> {item.name} </DropdownItem> ))} </DropdownMenu> </AppHeaderDropdown> </React.Fragment> ); } renderRightNav() { return ( <Nav className="ml-auto" navbar> <NavItem> <SearchBar loading={this.state.searchLoading} searchSubmit={searchValue => this.searchTheExplorer(searchValue)}/> </NavItem> {this.renderTool()} {this.renderSettings()} </Nav> ); } renderSettings() { const {logout, toggleTheme, currentTheme} = this.props; return ( <AppHeaderDropdown direction="down"> <DropdownToggle nav> <i className="icon-settings" /> </DropdownToggle> <DropdownMenu right style={{ right: 'auto' }}> <DropdownItem className="text-capitalize" onClick={() => toggleTheme()}> <FontAwesome name={currentTheme === DARK_THEME ? 'sun-o' : 'moon-o'} /> {currentTheme === DARK_THEME ? LIGHT_THEME : DARK_THEME} Mode </DropdownItem> <DropdownItem onClick={logout}><FontAwesome name="lock" /> Logout</DropdownItem> </DropdownMenu> </AppHeaderDropdown> ); } renderTool() { return ( <React.Fragment> <NavItem> <NavLink id="open-documentation" href="https://framework.embarklabs.io" title="Documentation" rel="noopener noreferrer" target="_blank"> <FontAwesome name="book" /> </NavLink> </NavItem> <NavItem> <NavLink id="open-github" href="https://github.com/embarklabs" title="Github" rel="noopener noreferrer" target="_blank"> <FontAwesome name="github" /> </NavLink> </NavItem> <UncontrolledTooltip target="open-documentation"> Open Embark documentation </UncontrolledTooltip> <UncontrolledTooltip target="open-github"> Open Github of Embark </UncontrolledTooltip> </React.Fragment> ); } render() { const {children, searchResult, location} = this.props; const sidebar = getSidebar(location); if (!sidebar) { removeCssClasses(); } return ( <div className="app animated fadeIn"> <AppHeader fixed> <AppNavbarBrand full={{src: logo, width: 50, height: 50, alt: 'Embark Logo'}} minimized={{src: logo, width: 50, height: 50, alt: 'Embark Logo'}} /> {this.renderNav()} {this.renderRightNav()} </AppHeader> <div className="app-body"> {sidebar && <AppSidebar fixed display="sm"> <AppSidebarHeader /> <AppSidebarForm /> <AppSidebarNav navConfig={sidebar} location={location} /> <AppSidebarFooter /> <AppSidebarMinimizer /> </AppSidebar> } <main className="main"> <Container fluid className="h-100 pt-4"> <Alert color="danger" isOpen={(this.state.searchError && Boolean(searchResult.error))} className="search-error no-gutters" toggle={() => this.dismissSearchError()}> {searchResult.error} </Alert> {children} </Container> </main> </div> </div> ); } } Layout.propTypes = { children: PropTypes.element, tabs: PropTypes.arrayOf(PropTypes.object), location: PropTypes.object, logout: PropTypes.func, toggleTheme: PropTypes.func, currentTheme: PropTypes.string, explorerSearch: PropTypes.func, searchResult: PropTypes.object, history: PropTypes.object }; function mapStateToProps(state) { return {searchResult: searchResult(state)}; } export default withRouter(connect( mapStateToProps, { explorerSearch: explorerSearch.request }, )(Layout));
app/components/Home.js
mswiszcz/pagebuilder
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Home.css'; import Card from './Home/Card'; import Header from './common/Header'; import moment from 'moment'; import { PROJECT_DATE_FORMAT } from '../model/project'; import { STATUS } from '../reducers/gatsby'; export default class Home extends Component { props: { projects: Object }; constructor(props) { super(props); if (Object.keys(this.props.projects).length == 0) { this.props.loadProjects(); } } componentDidMount() { if (this.props.gatsbyStatus.develop != STATUS.IDLE) this.props.gatsbyDevelopStop(); this.props.closeProject(); } openProject = (project) => { this.props.openProject(project); this.props.router.push('/editor'); } render() { const { openProject, deleteProject, deleteServer, projects, servers } = this.props; let sortedProjects = Object.keys(projects).sort((a, b) => { return projects[a].updatedAt > projects[b].updatedAt ? -1 : 1; }); return ( <main className='dashboard'> <div className='main-container'> <div className={styles.wrapper}> <Header backButtonVisible={false} title='Dashboard' subtitle={ moment().format('dddd[,] D MMMM') } actionsVisible={true} /> <div className={styles.container}> { sortedProjects.map((key, i) => { let project = projects[key]; return ( <Card key={`project-card-${project.id}`} title={project.name} subtitle={ `Updated ${moment(project.updatedAt, PROJECT_DATE_FORMAT).fromNow()}` } icon={project.icon} color={project.color} onClick={() => { this.openProject(project) }} deleteAction={(e) => { deleteProject(project) }} disabled={project.setupInProgress} />); }, this)} </div> </div> </div> </main> ); } }
resources/assets/js/components/SearchBookComponent.js
jrm2k6/i-heart-reading
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { runSearch } from '../actions/searchActions'; import { createAssignment } from '../actions/crudActions'; import { showModal } from '../actions/modals/modalActions'; import BookDetailsModal from './modals/BookDetailsModal'; const mapStateToProps = (state) => { return { suggestions: state.searchReducer.suggestions, noSuggestions: state.searchReducer.noSuggestions, isSearching: state.searchReducer.isSearching, currentQuery: state.searchReducer.currentQuery, user: state.userProfileReducer.user }; }; const mapDispatchToProps = (dispatch) => { return { onSearch: (query, type) => { dispatch(runSearch(query, type)); }, onClickAssign: (bookId, userId) => dispatch(createAssignment(bookId, userId)), showModal: (component, data) => { dispatch(showModal(component, data)); }, }; }; class SearchBookComponent extends Component { constructor(props) { super(props); this.state = { currentQuery: null, selectedOption: 'title' }; } render() { const { onSearch, onClickAssign, currentQuery, suggestions, noSuggestions, isSearching, user } = this.props let results = null; if (currentQuery === null || currentQuery.length === 0) { results = <div className='search-hint'>Please enter a query</div>; } else if (isSearching) { results = <div className='search-hint'>Searching</div>; } else if (noSuggestions) { results = <div className='search-hint'>No books found!</div>; } else { results = ( <SearchBookSuggestions suggestions={suggestions} showModal={(component, data) => { this.props.showModal(component, data); }} onClick={(bookId) => { onClickAssign(bookId, user.id).finally( function() { browserHistory.push('/app/books'); } ); }} /> ); } return ( <div className='search-book-container'> <div className='search-book-input-btn'> <input className='search-book-input' onChange={(e) => { this.setState({currentQuery: e.target.value}); }} placeholder='Enter a title or an author' > </input> <button className='search-books-btn' onClick={() => { onSearch(this.state.currentQuery, this.state.selectedOption); }} > Search </button> </div> <div className='search-input-options right-margin'> <span className='search-option-title'>Select a filter:</span> <div className='ihr-radio-wrapper' onClick={() => { this.setState({ selectedOption: 'author' }); }} > <input className='ihr-radio' type='radio' name='author' id='author' value='author' readOnly={true} checked={'author' == this.state.selectedOption} onClick={() => { this.setState({ selectedOption: 'author' }); }} /> <div className='ihr-check'></div> <label className='label-ihr' forName='author'> Book Authors </label> </div> <div className='ihr-radio-wrapper' onClick={() => { this.setState({ selectedOption: 'title' }); }} > <input className='ihr-radio' type='radio' name='title' id='title' value='title' checked={'title' == this.state.selectedOption} readOnly={true} onClick={() => { this.setState({ selectedOption: 'title' }); }} /> <div className='ihr-check'></div> <label className='label-ihr' forName='title'> Book Titles </label> </div> </div> {results} </div> ); } }; const SearchBookSuggestions = ({ suggestions, onClick, showModal }) => ( <div className='search-book-suggestions-container'> <div className='search-book-suggestions-header'> <span className='book-properties'>Title</span> <span className='book-properties'>Author</span> <span className='book-properties'># Pages</span> <span className='book-properties'>Details</span> <span className='book-actions'></span> </div> <div> {suggestions.map(suggestion => { return ( <div key={suggestion.google_book_id} className='search-book-suggestion'> <span className='book-properties'>{suggestion.title}</span> <span className='book-properties'>{suggestion.authors}</span> <span className='book-properties'>{suggestion.num_pages}</span> <span className='book-properties' onClick={() => { showModal(BookDetailsModal, {suggestion, onClick})}} > View more </span> <span className='book-actions assign' onClick={() => {onClick(suggestion.google_book_id);}} > Assign </span> </div> )} )} </div> </div> ); export default connect(mapStateToProps, mapDispatchToProps)(SearchBookComponent);
frontend/src/components/partners/profile/modals/addVerificationModal/verificationQuestion.js
unicef/un-partner-portal
import React from 'react'; import { withStyles } from 'material-ui/styles'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import SpreadContent from '../../../../common/spreadContent'; import PolarRadio from '../../../../forms/fields/PolarRadio'; import TextForm from '../../../../forms/textFieldForm'; import GridColumn from '../../../../common/grid/gridColumn'; const messages = { comment: 'Comment', }; const styleSheet = (theme) => { const spacing = theme.spacing.unit; return { padding: { padding: `0px ${spacing}px ${spacing}px ${spacing}px`, alignItems: 'center', }, background: { backgroundColor: theme.palette.common.lightGreyBackground, }, questionMargin: { marginRight: spacing, }, }; }; const VerificationQuestion = (props) => { const { classes, question, questionFieldName, commentFieldName, readOnly, warn } = props; return ( <GridColumn spacing={8}> <SpreadContent className={`${classes.padding} ${classes.background}`}> <Typography type="body2" className={classes.questionMargin}> {question} </Typography> <PolarRadio warn={warn} fieldName={questionFieldName} readOnly={readOnly} /> </SpreadContent> <div className={classes.padding}> <TextForm label={messages.comment} fieldName={commentFieldName} warn={warn} textFieldProps={{ multiline: true, InputProps: { inputProps: { maxLength: '300', }, }, }} readOnly={readOnly} /> </div> </GridColumn> ); }; VerificationQuestion.propTypes = { classes: PropTypes.object, question: PropTypes.string, questionFieldName: PropTypes.string, commentFieldName: PropTypes.string, readOnly: PropTypes.bool, warn: PropTypes.bool, }; export default withStyles(styleSheet, { name: 'VerificationQuestion' })(VerificationQuestion);
modules/Common/SearchBox.js
cloudytimemachine/frontend
import React from 'react' import { Link } from 'react-router' import { browserHistory } from 'react-router' export default React.createClass({ getInitialState: function() { return { url: '' }; }, handleURLChange: function(e) { this.setState({ url: e.target.value }); }, contextTypes: { router: React.PropTypes.object }, handleSubmit: function(e) { e.preventDefault(); var url = this.state.url.trim(); if (!url) { return; } this.setState({ url: '' }); browserHistory.push({ pathname: '/search/', search: '?host='+this.refs.q.value }); }, render() { return ( <form className="navbar-form" role="search" onSubmit={this.handleSubmit}> <div className="input-group"> <input type="text" className="form-control" placeholder="Search" ref="q" value={this.state.url} onChange={this.handleURLChange} /> <div className="input-group-btn"> <button className="btn btn-default" type="submit"><i className="glyphicon glyphicon-search"></i></button> </div> {/*input-group-btn*/} </div> {/*input-group*/} </form> ) } });
src/index.js
miraks/react-autolink-text
import React from 'react'; import shouldPureComponentUpdate from 'react-pure-render/function'; import matchParser from './match_parser'; export default class AutoLinkText extends React.Component { shouldComponentUpdate = shouldPureComponentUpdate render() { const text = this.props.text; const target = this.props.target; return ( <span>{matchParser(text)::prepareElements(text, target)::truncate(this.props.maxLength)::keyElements()}</span> ); } } function prepareElements(text, target) { let elements = []; let lastIndex = 0; this.forEach((match) => { if (match.position.start !== 0) { elements.push(<span>{text.slice(lastIndex, match.position.start)}</span>); } elements.push(<a target={target} href={match.getAnchorHref()} >{match.getAnchorText()}</a>); lastIndex = match.position.end; }); if (lastIndex < text.length) { elements.push(<span>{text.slice(lastIndex)}</span>); } return elements; } function truncate(maxLength) { if (!maxLength) return this; let elements = []; let length = 0; this.some((el) => { length += el.props.children.length; if (length > maxLength) { const truncatedText = el.props.children.slice(0, -(length - maxLength)); elements.push( React.cloneElement(el, {}, truncatedText) ); return true; // stop iterating through the elements } elements.push(el); }); return elements; } /* * Generate unique keys for each of the elements. * The key will be based on the index of the element. */ function keyElements() { return this.map((el, index) => { return React.cloneElement(el, {key: index}); }); } AutoLinkText.propTypes = { text: React.PropTypes.string, target: React.PropTypes.string, maxLength: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]) }; AutoLinkText.defaultProps = { text: '', target: '_self' }
packages/web/src/components/Account/Forgot.js
hengkx/note
import React from 'react'; import PropTypes from 'prop-types'; import { Form, Input, message, Button } from 'antd'; import { Link } from 'react-router-dom'; import './less/account.less'; const FormItem = Form.Item; class Forgot extends React.Component { static propTypes = { form: PropTypes.object.isRequired, forgot: PropTypes.func.isRequired, forgotResult: PropTypes.object } componentWillReceiveProps(nextProps) { const { forgotResult } = nextProps; if (forgotResult !== this.props.forgotResult) { if (forgotResult.code !== 0) { message.error(forgotResult.message); } else { message.success('密码已发送到您的邮箱请注意查收!'); } } } handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { this.props.forgot({ email: values.email }); } }); } render() { const { getFieldDecorator } = this.props.form; return ( <Form className="account" onSubmit={this.handleSubmit}> <h1>云笔记</h1> <FormItem hasFeedback > {getFieldDecorator('email', { rules: [ { type: 'email', message: '请输入正确的邮箱!' }, { required: true, message: '请输入邮箱!' } ] })(<Input placeholder="邮箱" />)} </FormItem> <FormItem> <Button type="primary" htmlType="submit" size="large">找回密码</Button> </FormItem> <FormItem> <Link to="/signin">点击返回登录</Link> </FormItem> </Form> ); } } export default Form.create()(Forgot);
src/svg-icons/image/gradient.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGradient = (props) => ( <SvgIcon {...props}> <path d="M11 9h2v2h-2zm-2 2h2v2H9zm4 0h2v2h-2zm2-2h2v2h-2zM7 9h2v2H7zm12-6H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z"/> </SvgIcon> ); ImageGradient = pure(ImageGradient); ImageGradient.displayName = 'ImageGradient'; export default ImageGradient;
node_modules/react-router/es/Prompt.js
lousanna/sinatrademo
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for prompting the user before navigating away * from a screen with a component. */ var Prompt = function (_React$Component) { _inherits(Prompt, _React$Component); function Prompt() { _classCallCheck(this, Prompt); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Prompt.prototype.enable = function enable(message) { if (this.unblock) this.unblock(); this.unblock = this.context.router.history.block(message); }; Prompt.prototype.disable = function disable() { if (this.unblock) { this.unblock(); this.unblock = null; } }; Prompt.prototype.componentWillMount = function componentWillMount() { if (this.props.when) this.enable(this.props.message); }; Prompt.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.when) { if (!this.props.when || this.props.message !== nextProps.message) this.enable(nextProps.message); } else { this.disable(); } }; Prompt.prototype.componentWillUnmount = function componentWillUnmount() { this.disable(); }; Prompt.prototype.render = function render() { return null; }; return Prompt; }(React.Component); Prompt.propTypes = { when: PropTypes.bool, message: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired }; Prompt.defaultProps = { when: true }; Prompt.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ block: PropTypes.func.isRequired }).isRequired }).isRequired }; export default Prompt;
src/components/ResetPasswordForm.js
react-auth/react-auth
import React from 'react'; import { Link } from 'react-router'; import utils from '../utils'; import LoginLink from '../components/LoginLink'; import { forgotPassword } from '../actions'; class DefaultResetPasswordForm extends React.Component { render() { return ( <ResetPasswordForm {...this.props}> <div className='sp-reset-password-form'> <div className="row"> <div className="col-sm-offset-4 col-xs-12 col-sm-4" spIf="form.sent"> <p className="alert alert-success"> We have sent a password reset link to the email address of the account that you specified. Please check your email for this message, then click on the link. </p> <p className="pull-right"> <LoginLink>Back to Login</LoginLink> </p> </div> <div className="col-xs-12" spIf="!form.sent"> <div className="form-horizontal"> <div className="form-group"> <label htmlFor="spEmail" className="col-xs-12 col-sm-4 control-label">Email or Username</label> <div className="col-xs-12 col-sm-4"> <input className="form-control" id="spEmail" name="email" placeholder="Your Email Address" /> </div> </div> <div className="form-group"> <div className="col-sm-offset-4 col-xs-12"> <p spIf="form.error"><span spBind="form.errorMessage" /></p> <button type="submit" className="btn btn-primary">Request Password Reset</button> </div> </div> </div> </div> </div> </div> </ResetPasswordForm> ); } } export default class ResetPasswordForm extends React.Component { state = { fields: { email: '' }, errorMessage: null, isFormProcessing: false, isFormSent: false }; onFormSubmit(e) { e.preventDefault(); e.persist(); var next = (err, data) => { if (err) { return this.setState({ isFormProcessing: false, errorMessage: err.message }); } // If the user didn't specify any data, // then simply default to what we have in state. data = data || this.state.fields; forgotPassword(this.state.fields).then(() => { this.setState({ isFormSent: true, isFormProcessing: false, errorMessage: null }); }).catch((err) => { this.setState({ isFormProcessing: false, errorMessage: err.message }); }); }; this.setState({ isFormProcessing: true }); if (this.props.onSubmit) { e.data = this.state.fields; this.props.onSubmit(e, next); } else { next(null, this.state.fields); } } _mapFormFieldHandler(element, tryMapField) { if (element.type === 'input' || element.type === 'textarea') { if (element.props.type !== 'submit') { switch(element.props.name) { case 'email': tryMapField('email'); break; } } } } _spIfHandler(action, element) { var test = null; switch (action) { case 'form.processing': test = this.state.isFormProcessing; break; case 'form.sent': test = this.state.isFormSent; break; case 'form.error': test = this.state.errorMessage !== null; break; } return test; } _spBindHandler(bind, element) { var result = false; switch (bind) { case 'form.errorMessage': let className = element.props ? element.props.className : undefined; result = <span className={className}>{this.state.errorMessage}</span>; break; } return result; } render() { if (this.props.children) { return ( <form onSubmit={this.onFormSubmit.bind(this)}> {utils.makeForm(this, this._mapFormFieldHandler.bind(this), this._spIfHandler.bind(this), this._spBindHandler.bind(this))} </form> ); } else { return <DefaultResetPasswordForm {...this.props} />; } } }
client/containers/SignUpContainer.js
axax/lunuc
import React from 'react' import PropTypes from 'prop-types' import config from 'gen/config-client' import BlankLayout from 'client/components/layout/BlankLayout' import {Link} from 'client/util/route' import {Card, SimpleButton, TextField, Row, Col, Typography} from 'ui/admin' import {client} from '../middleware/graphql' class SignUpContainer extends React.Component { state = { loading: false, usernameError: null, passwordError: null, emailError: null, username: '', password: '', email: '', signupFinished: false } handleInputChange = (e) => { const target = e.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name this.setState({ [target.name]: value }) } signup = (e) => { e.preventDefault() this.setState({usernameError: null, passwordError: null, emailError: null}) let hasError = false const {email, username, password} = this.state if (email.trim() === '') { this.setState({emailError: 'Please enter a valid email address'}) hasError = true } if (username.trim() === '') { this.setState({usernameError: 'Please enter a username'}) hasError = true } if (password.trim() === '') { this.setState({passwordError: 'Please enter a password'}) hasError = true } if (hasError) { return } this.setState({loading: true}) client.mutate({ mutation: ` mutation createUser($email: String!, $username: String!, $password: String!) { createUser(email: $email, username: $username, password: $password) { email password username _id } } `, variables: { email, username, password } }).then((res) => { console.log(res) if (res.errors && res.errors.length) { res.errors.forEach(e => { console.log(e) if (e.state) { this.setState(e.state) } }) this.setState({loading: false}) } else { this.setState({loading: false, signupFinished: true}) } }) } render() { const {signupFinished, email, username, password, loading, usernameError, passwordError, emailError} = this.state return ( <BlankLayout style={{marginTop: '5rem'}}> <Row> <Col xs={1} sm={2} md={4}></Col> <Col xs={10} sm={8} md={4}> <Card> <Typography variant="h3" gutterBottom>Sign up</Typography> {signupFinished ? <Typography gutterBottom>Thanks for your registration! <Link to={config.ADMIN_BASE_URL + '/login'}>Login</Link></Typography> : <form> <TextField label="Username" error={!!usernameError} helperText={usernameError} disabled={!!loading} autoComplete="username" fullWidth autoFocus value={username} onChange={this.handleInputChange} type="text" placeholder="Enter username" name="username" required/> <TextField label="Email" error={!!emailError} helperText={emailError} disabled={!!loading} autoComplete="email" fullWidth value={email} onChange={this.handleInputChange} type="text" placeholder="Enter email" name="email" required/> <TextField label="Password" error={!!passwordError} helperText={passwordError} disabled={!!loading} fullWidth autoComplete="new-password" value={password} onChange={this.handleInputChange} type="password" placeholder="Enter Password" name="password" required/> <div style={{textAlign: 'right'}}> <SimpleButton variant="contained" color="primary" showProgress={loading} onClick={this.signup.bind(this)}>Sign up</SimpleButton> </div> <Typography gutterBottom> Already have an account? <Link to={config.ADMIN_BASE_URL + '/login'}>Login</Link></Typography> </form> } </Card> </Col> <Col xs={1} sm={2} md={4}></Col> </Row> </BlankLayout> ) } } SignUpContainer.propTypes = { mutate: PropTypes.func, } export default SignUpContainer
src/index.js
Aleczhang1992/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
demo/components/TodosList.js
bradparks/cerebral__web_app_state_with_debugger
import React from 'react'; import Todo from './Todo.js'; import {Decorator as Cerebral} from 'cerebral-react'; @Cerebral({ todos: ['visibleTodos'], isAllChecked: ['isAllChecked'] }) class TodosList extends React.Component { renderTodo(todo, index) { return <Todo key={index} index={index} todo={todo}/> } render() { return ( <section id="main"> <input id="toggle-all" type="checkbox" checked={this.props.isAllChecked} onChange={() => this.props.signals.toggleAllChanged()} /> <label htmlFor="toggle-all">Mark all as complete</label> <ul id="todo-list"> {this.props.todos.map(this.renderTodo.bind(this))} </ul> </section> ); } } export default TodosList;
actor-apps/app-web/src/app/components/modals/Preferences.react.js
hmoraes/actor-platform
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import PreferencesStore from 'stores/PreferencesStore'; const appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); const ThemeManager = new Styles.ThemeManager(); const menuItems = [ { payload: '1', text: 'English', value: 'en'}, { payload: '2', text: 'Russian', value: 'ru'} ]; const getStateFromStores = () => { const language = PreferencesStore.language; return { isOpen: PreferencesStore.isModalOpen, preferences: PreferencesStore.preferences, language: language, selectedLanguage: _.findIndex(menuItems, {value: language}) }; }; @ReactMixin.decorate(IntlMixin) class PreferencesModal extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); PreferencesStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { PreferencesStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { PreferencesActionCreators.hide(); }; onDone = () => { PreferencesActionCreators.save({ language: this.state.language, sendByEnter: this.refs.sendByEnter.getSelectedValue() }); this.onClose(); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onLanguageChange = (event, selectedIndex, menuItem) => { this.setState({ language: menuItem.value, selectedLanguage: _.findIndex(menuItems, {value: menuItem.value}) }); }; render() { const preferences = this.state.preferences; if (this.state.isOpen === true) { return ( <Modal className="modal-new modal-new--preferences" closeTimeoutMS={150} isOpen={this.state.isOpen} style={{width: 760}}> <div className="modal-new__header"> <i className="modal-new__header__icon material-icons">settings</i> <h3 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/> </h3> <div className="pull-right"> <FlatButton hoverColor="rgba(81,145,219,.17)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onDone} secondary={true} style={{marginTop: -6}}/> </div> </div> <div className="modal-new__body"> <div className="preferences"> <aside className="preferences__tabs"> <a className="preferences__tabs__tab preferences__tabs__tab--active">General</a> <a className="preferences__tabs__tab hide">Notifications</a> <a className="preferences__tabs__tab hide">Sidebar colors</a> <a className="preferences__tabs__tab hide">Security</a> <a className="preferences__tabs__tab hide">Other Options</a> </aside> <div className="preferences__body"> <div className="preferences__list"> <div className="preferences__list__item preferences__list__item--general"> <ul> <li> <i className="icon material-icons">keyboard</i> <RadioButtonGroup defaultSelected={preferences.sendByEnter} name="send" ref="sendByEnter"> <RadioButton label="Enter – send message, Shift + Enter – new line" style={{marginBottom: 12}} value="true"/> <RadioButton label="Cmd + Enter – send message, Enter – new line" value="false"/> </RadioButtonGroup> </li> <li className="language hide"> <i className="icon material-icons">menu</i> Language: <DropDownMenu labelStyle={{color: '#5191db'}} menuItemStyle={{height: '40px', lineHeight: '40px'}} menuItems={menuItems} onChange={this.onLanguageChange} selectedIndex={this.state.selectedLanguage} style={{verticalAlign: 'top', height: 52}} underlineStyle={{display: 'none'}}/> </li> </ul> </div> <div className="preferences__list__item preferences__list__item--notifications hide"> <ul> <li> <i className="icon material-icons">notifications</i> <RadioButtonGroup defaultSelected="all" name="notifications"> <RadioButton label="Notifications for activity of any kind" style={{marginBottom: 12}} value="all"/> <RadioButton label="Notifications for Highlight Words and direct messages" style={{marginBottom: 12}} value="quiet"/> <RadioButton label="Never send me notifications" style={{marginBottom: 12}} value="disable"/> </RadioButtonGroup> <p className="hint"> You can override your desktop notification preference on a case-by-case basis for channels and groups from the channel or group menu. </p> </li> </ul> </div> </div> </div> </div> </div> </Modal> ); } else { return null; } } } export default PreferencesModal;
src/components/build_panel.js
RexSkz/drone-ui
import Humanize from './humanize'; import React from 'react'; import TimeAgo from 'react-timeago'; import zhStrings from 'react-timeago/lib/language-strings/zh-CN' import buildFormatter from 'react-timeago/lib/formatters/buildFormatter' import './build_panel.less'; export default class BuildPanel extends React.Component { renderParentLink(parent) { const {repo} = this.props; if (parent > 0) { return ( <div> <em>上级:</em> #{parent} <a href={`/${repo.owner}/${repo.name}/${parent}`} className="parent-link"> <i className="material-icons">insert_link</i> </a> </div> ); } } render() { const { build, job } = this.props; const formatter = buildFormatter(zhStrings); let classes = ['build-panel', job.state || job.status]; let environs = []; if (job && job.environ) { Object.keys(job.environ).map((key) => { environs.push( <code key={key}>{key}={job.environ[key]}</code> ); }); } let branch = (build.refspec != '' && build.event == 'pull_request') ? build.refspec : build.branch; return ( <div className={classes.join(' ')}> <h1>#{build.number} <span>{build.message}</span></h1> <div className="build-panel-detail"> <div> <div><em>分支:</em><span>{branch}</span></div> <div> <em>提交记录:</em><span>{build.commit.substr(0,8)}</span> <a href={build.link_url} target="_blank" className="commit-link"> <i className="material-icons">insert_link</i> </a> </div> <div><em>作者:</em><span>{build.author}</span></div> {this.renderParentLink(build.parent)} <p>{environs}</p> </div> <div> <div> <i className="material-icons">access_time</i> {job.started_at ? <TimeAgo date={(job.started_at || build.created_at) * 1000} formatter={formatter} /> : <span>--</span> } </div> <div> <i className="material-icons">timelapse</i> {job.finished_at ? <Humanize finished={job.finished_at} start={job.started_at} /> : <TimeAgo date={(job.started_at || build.created_at) * 1000} formatter={formatter} /> } </div> </div> </div> <div>{this.props.children}</div> </div> ); } }
admin/client/App/elemental/ScreenReaderOnly/index.js
rafmsou/keystone
import React from 'react'; import { css, StyleSheet } from 'aphrodite/no-important'; function ScreenReaderOnly ({ className, ...props }) { props.className = css(classes.srOnly, className); return <span {...props} />; }; const classes = StyleSheet.create({ srOnly: { border: 0, clip: 'rect(0,0,0,0)', height: 1, margin: -1, overflow: 'hidden', padding: 0, position: 'absolute', width: 1, }, }); module.exports = ScreenReaderOnly;
src/pages/404.js
EricSSartorius/homepage
import React from 'react' const NotFoundPage = () => ( <div className="not-found"> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </div> ) export default NotFoundPage
packages/mcs-lite-mobile-web/src/containers/DeviceDetailInfo/DeviceDetailInfo.js
MCS-Lite/mcs-lite
import PropTypes from 'prop-types'; import React from 'react'; import Helmet from 'react-helmet'; import B from 'mcs-lite-ui/lib/B'; import P from 'mcs-lite-ui/lib/P'; import MobileHeader from 'mcs-lite-ui/lib/MobileHeader'; import { updatePathname } from 'mcs-lite-ui/lib/utils/routerHelper'; import IconArrowLeft from 'mcs-lite-icon/lib/IconArrowLeft'; import { Link } from 'react-router'; import { Container } from './styled-components'; class DeviceDetailInfo extends React.Component { static propTypes = { // React-router Params deviceId: PropTypes.string.isRequired, // Redux State device: PropTypes.object, // Redux Action fetchDeviceDetail: PropTypes.func.isRequired, // React-intl I18n getMessages: PropTypes.func.isRequired, }; componentWillMount = () => this.props.fetchDeviceDetail(this.props.deviceId); render() { const { deviceId, device, getMessages: t } = this.props; return ( <div> <Helmet> <title>{t('deviceIntro')}</title> </Helmet> <MobileHeader.MobileHeader title={t('deviceIntro')} leftChildren={ <MobileHeader.MobileHeaderIcon component={Link} to={updatePathname(`/devices/${deviceId}`)} > <IconArrowLeft /> </MobileHeader.MobileHeaderIcon> } /> <main> {device && ( <Container> <div> <B>{t('deviceName')}</B> <P>{device.deviceName}</P> </div> <div> <B>{t('creator')}</B> <P>{device.user.userName}</P> </div> <div> <B>{t('version')}</B> <P>{device.prototype.version}</P> </div> <div> <B>{t('description')}</B> <P>{device.deviceDescription}</P> </div> <div> <B>DeviceId</B> <P>{device.deviceId}</P> </div> <div> <B>DeviceKey</B> <P>{device.deviceKey}</P> </div> </Container> )} </main> </div> ); } } export default DeviceDetailInfo;
app/src/index.js
NomadGraphix/csc-final-project-2017
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; function main() { const app = document.createElement('div'); document.body.appendChild(app); ReactDOM.render(<App />, app); } main();
packages/mineral-ui-icons/src/IconNaturePeople.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 IconNaturePeople(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M22.17 9.17c0-3.87-3.13-7-7-7s-7 3.13-7 7A6.98 6.98 0 0 0 14 16.06V20H6v-3h1v-4c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v4h1v5h16v-2h-3v-3.88a7 7 0 0 0 6.17-6.95zM4.5 11c.83 0 1.5-.67 1.5-1.5S5.33 8 4.5 8 3 8.67 3 9.5 3.67 11 4.5 11z"/> </g> </Icon> ); } IconNaturePeople.displayName = 'IconNaturePeople'; IconNaturePeople.category = 'image';
stories/Pagination.stories.js
react-materialize/react-materialize
import React from 'react'; import { storiesOf } from '@storybook/react'; import Pagination from '../src/Pagination'; const stories = storiesOf('Components/Pagination', module); stories.addParameters({ info: { text: `Add pagination links to help split up your long content into shorter, easier to understand blocks. You just have to provide the items and onSelect attribute, when clicked, the onSelect function will be called with the page number. Otherwise you can customize the page button with PaginationButton component.` } }); stories.add('Default', () => <Pagination items={10} maxButtons={8} />); stories.add('with activePage', () => <Pagination items={5} activePage={3} />);
modules/experiences/client/components/create-experience/SubmittedInfo.js
Trustroots/trustroots
// External dependencies import { useTranslation, Trans } from 'react-i18next'; import PropTypes from 'prop-types'; import React from 'react'; // Internal dependencies import '@/config/client/i18n'; import { DAYS_TO_REPLY } from '../../utils/constants'; import SuccessMessage from '@/modules/core/client/components/SuccessMessage'; /** * Info after successful submitting of a new experience. */ export default function SubmittedInfo({ isPublic, isReported, name, username, }) { const { t } = useTranslation('experiences'); return ( <SuccessMessage title={t('Thank you for sharing your experience!')} cta={ <a className="btn btn-primary" href={`/profile/${username}/experiences`} > {t('See their experiences')} </a> } > <p> {isPublic ? t('Your experience with {{name}} is public now.', { name }) : t( 'Your experience will become public when {{name}} shares their experience, or at most in {{count}} days.', { name, count: DAYS_TO_REPLY }, )} </p> {isReported && ( <p> {/* @TODO remove ns (issue #1368) */} <Trans t={t} ns="experiences"> You also reported them to us. Please do{' '} <a href="/support">get in touch with us</a> if you have any further info to add. </Trans> </p> )} </SuccessMessage> ); } SubmittedInfo.propTypes = { isPublic: PropTypes.bool.isRequired, isReported: PropTypes.bool.isRequired, name: PropTypes.string.isRequired, username: PropTypes.string.isRequired, };
js/components/App.js
sogko/todomvc-relay-go
import React from 'react'; import Relay from 'react-relay'; class App extends React.Component { render() { return ( <div> <h1>Widget list</h1> <ul> {this.props.viewer.widgets.edges.map(edge => <li>{edge.node.name} (ID: {edge.node.id})</li> )} </ul> </div> ); } } export default Relay.createContainer(App, { fragments: { viewer: () => Relay.QL` fragment on User { widgets(first: 10) { edges { node { id, name, }, }, }, } `, }, });
docs/src/PageFooter.js
mcraiganthony/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className='bs-docs-footer' role='contentinfo'> <div className='container'> <div className='bs-docs-social'> <ul className='bs-docs-social-buttons'> <li> <iframe className='github-btn' src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true' width={95} height={20} title='Star on GitHub' /> </li> <li> <iframe className='github-btn' src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true' width={92} height={20} title='Fork on GitHub' /> </li> <li> <iframe src="http://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder='0' scrolling='no'> </iframe> </li> </ul> </div> <p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p> <ul className='bs-docs-footer-links muted'> <li>Currently v{version}</li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
src/inputs/components/input-types/select-input.js
juttle/juttle-client-library
import React, { Component } from 'react'; import Select from 'react-select'; class SelectInput extends Component { handleChange(chosenOption) { this.props.inputUpdate(chosenOption.value); } render() { let { value, options } = this.props.input; return ( <div className="form-group"> <Select name="form-field-name" value={value} options={options.items} clearable={false} onChange={this.handleChange.bind(this)} /> </div> ); } } export default SelectInput;
fields/types/email/EmailColumn.js
codevlabs/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; var EmailColumn = React.createClass({ displayName: 'EmailColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { let value = this.props.data.fields[this.props.col.path]; if (!value) return; return ( <ItemsTableValue href={'mailto:'+ value} padded exterior field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { let value = this.props.data.fields[this.props.col.path]; return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = EmailColumn;
examples/sidebar/app.js
okcoker/react-router
import React from 'react'; import { Router, Route, Link } from 'react-router'; import data from './data'; var Category = React.createClass({ render() { var category = data.lookupCategory(this.props.params.category); return ( <div> <h1>{category.name}</h1> {this.props.children || ( <p>{category.description}</p> )} </div> ); } }); var CategorySidebar = React.createClass({ render() { var category = data.lookupCategory(this.props.params.category); return ( <div> <Link to="/">◀︎ Back</Link> <h2>{category.name} Items</h2> <ul> {category.items.map((item, index) => ( <li key={index}> <Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link> </li> ))} </ul> </div> ); } }); var Item = React.createClass({ render() { var { category, item } = this.props.params; var menuItem = data.lookupItem(category, item); return ( <div> <h1>{menuItem.name}</h1> <p>${menuItem.price}</p> </div> ); } }); var Index = React.createClass({ render() { return ( <div> <h1>Sidebar</h1> <p> Routes can have multiple components, so that all portions of your UI can participate in the routing. </p> </div> ); } }); var IndexSidebar = React.createClass({ render() { return ( <div> <h2>Categories</h2> <ul> {data.getAll().map((category, index) => ( <li key={index}> <Link to={`/category/${category.name}`}>{category.name}</Link> </li> ))} </ul> </div> ); } }); var App = React.createClass({ render() { var { children } = this.props; return ( <div> <div className="Sidebar"> {children ? children.sidebar : <IndexSidebar />} </div> <div className="Content"> {children ? children.content : <Index />} </div> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}> <Route path=":item" component={Item} /> </Route> </Route> </Router> ), document.getElementById('example'));
src/CheckboxGroup.js
jsummer/react-ui
"use strict" import React from 'react' import classnames from 'classnames' import Checkbox from './Checkbox' import { toArray } from './utils/strings' import { toTextValue } from './utils/objects' class CheckboxGroup extends React.Component { static displayName = "CheckboxGroup" static propTypes = { className: React.PropTypes.string, data: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.func ]).isRequired, inline: React.PropTypes.bool, onChange: React.PropTypes.func, readOnly: React.PropTypes.bool, sep: React.PropTypes.string, style: React.PropTypes.object, textTpl: React.PropTypes.string, value: React.PropTypes.any, valueTpl: React.PropTypes.string } static defaultProps = { sep: ',', textTpl: '{text}', valueTpl: '{id}' } componentWillReceiveProps (nextProps) { if (nextProps.value !== this.props.value) { this.setValue(nextProps.value) } if (nextProps.data !== this.props.data) { this.setState({ data: this.formatData(nextProps.data) }) } } state = { value: this.formatValue(this.props.value), data: this.formatData(this.props.data) } formatValue (value) { return toArray(value, this.props.sep) } getValue (sep) { let value = this.state.value if (sep === undefined) { sep = this.props.sep } if (sep) { value = value.join(sep) } return value } setValue (value) { this.setState({ value: this.formatValue(value) }) } formatData (data) { if (typeof data === 'function') { data.then(res => { this.setState({ data: this.formatData(res) }) })() return [] } else { return toTextValue(data, this.props.textTpl, this.props.valueTpl) } } handleChange (checked, value) { if (typeof value !== 'string') { value = value.toString() } let values = this.state.value if (checked) { values.push(value) } else { let i = values.indexOf(value) if (i >= 0) { values.splice(i, 1) } } if (this.props.onChange) { this.props.onChange(this.props.sep ? values.join(this.props.sep) : values) } this.setState({ value: values }) } render () { let className = classnames( this.props.className, 'rct-checkbox-group', { 'rct-inline': this.props.inline } ) let values = this.state.value let items = this.state.data.map((item, i) => { let value = this.props.sep ? item.$value.toString() : item.$value let checked = values.indexOf(value) >= 0 return ( <Checkbox key={i} index={i} readOnly={this.props.readOnly} checked={checked} onChange={this.handleChange.bind(this)} text={item.$text} value={item.$value} /> ) }) return ( <div style={this.props.style} className={className}>{this.state.msg || items}</div> ) } } export default CheckboxGroup require('./FormControl').register( 'checkbox-group', function (props) { return <CheckboxGroup {...props} /> }, CheckboxGroup, 'array' )
docs/app/Examples/collections/Form/Variations/FormExampleInverted.js
shengnian/shengnian-ui-react
import React from 'react' import { Button, Form, Segment } from 'shengnian-ui-react' const FormExampleInverted = () => ( <Segment inverted> <Form inverted> <Form.Group widths='equal'> <Form.Input label='First name' placeholder='First name' /> <Form.Input label='Last name' placeholder='Last name' /> </Form.Group> <Form.Checkbox label='I agree to the Terms and Conditions' /> <Button type='submit'>Submit</Button> </Form> </Segment> ) export default FormExampleInverted
src/App/App.js
mdboop/francis
import React from 'react'; import Nav from '../Nav/Nav'; class App extends React.Component { constructor(props) { super(props); this.state = {}; } render() { return ( <div> <Nav /> {this.props.children} </div> ); } } App.propTypes = { children: React.PropTypes.element, }; export default App;
src/components/Portal.js
neontribe/gbptm
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; const Portal = (props) => { // https://github.com/facebook/react/issues/13097#issuecomment-405658104 const [isMounted, setIsMounted] = React.useState(false); const element = document.querySelector(props.selector); React.useEffect(() => { setIsMounted(true); }, []); if (element && isMounted) { return ReactDOM.createPortal(props.children, element); } return null; }; Portal.propTypes = { /** query selector to determine where to mount the Portal */ selector: PropTypes.string, children: PropTypes.node, }; Portal.defaultProps = { selector: 'body', }; export default Portal;
packages/examples/regithub/pages/home.js
siddharthkp/reaqt
import React from 'react' import Nav from '../components/presentation/common/nav' import ProfileInput from '../components/presentation/profile/profile-input' export default () => ( <div> <Nav /> <ProfileInput /> </div> )
docs/src/PageHeader.js
collinwu/react-bootstrap
import React from 'react'; const PageHeader = React.createClass({ render() { return ( <div className='bs-docs-header' id='content'> <div className='container'> <h1>{this.props.title}</h1> <p>{this.props.subTitle}</p> </div> </div> ); } }); export default PageHeader;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Promises.js
GreenGremlin/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'; function load() { return Promise.resolve([ { 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: [] }; } componentDidMount() { load().then(users => { this.setState({ users }); }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-promises"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
actor-apps/app-web/src/app/components/JoinGroup.react.js
lstNull/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import DialogActionCreators from 'actions/DialogActionCreators'; import JoinGroupActions from 'actions/JoinGroupActions'; import JoinGroupStore from 'stores/JoinGroupStore'; // eslint-disable-line class JoinGroup extends React.Component { static propTypes = { params: React.PropTypes.object }; static contextTypes = { router: React.PropTypes.func }; constructor(props) { super(props); JoinGroupActions.joinGroup(props.params.token) .then((peer) => { this.context.router.replaceWith('/'); DialogActionCreators.selectDialogPeer(peer); }).catch((e) => { console.warn(e, 'User is already a group member'); this.context.router.replaceWith('/'); }); } render() { return null; } } export default requireAuth(JoinGroup);
docs/app/Examples/collections/Form/Shorthand/FormExampleFieldControlId.js
shengnian/shengnian-ui-react
import React from 'react' import { Form, Input, TextArea, Button } from 'shengnian-ui-react' const FormExampleFieldControlId = () => ( <Form> <Form.Group widths='equal'> <Form.Field id='form-input-control-first-name' control={Input} label='First name' placeholder='First name' /> <Form.Field id='form-input-control-last-name' control={Input} label='Last name' placeholder='Last name' /> </Form.Group> <Form.Field id='form-textarea-control-opinion' control={TextArea} label='Opinion' placeholder='Opinion' /> <Form.Field id='form-button-control-public' control={Button} content='Confirm' label='Label with htmlFor' /> </Form> ) export default FormExampleFieldControlId