path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/hocs/withoutProps.js
hbibkrim/neon-wallet
// @flow import { omit } from 'lodash-es' import React from 'react' import { compose, setDisplayName, wrapDisplayName } from 'recompose' export default function withoutProps(...propNames: Array<string>): Function { return (Component: Class<React.Component<*>>): Class<React.Component<*>> => { const ComponentWithoutProps = (props: Object) => { const passDownProps = omit(props, ...propNames) return <Component {...passDownProps} /> } return compose(setDisplayName(wrapDisplayName(Component, 'withoutProps')))( ComponentWithoutProps, ) } }
client/src/components/group_dialog/GroupDialog.js
thewizardplusplus/vk-group-stats
import React from 'react' import Dialog from 'material-ui/Dialog' import IconButton from '../icon_button/IconButton' import TextField from 'material-ui/TextField' import IconicButton from '../iconic_button/IconicButton' import './group_dialog.css' export default class GroupDialog extends React.Component { static propTypes = { open: React.PropTypes.bool.isRequired, onClose: React.PropTypes.func.isRequired, onAccept: React.PropTypes.func.isRequired, } state = { screenName: '', } handleScreenNameChange = (event, newValue) => { this.setState({ screenName: newValue, }) } handleScreenNameReset = () => { this.setState({ screenName: '', }) } handleClose = () => { this.handleScreenNameReset() this.props.onClose() } handleAccept = () => { const screenName = this.state.screenName this.handleClose() if (screenName.length > 0) { this.props.onAccept(screenName) } } render() { return <Dialog title="Добавить группу" open={this.props.open} onRequestClose={this.handleClose} actions={[ <IconButton icon="close" text="Отмена" onClick={this.handleClose} />, <IconButton icon="add" text="Добавить" onClick={this.handleAccept} />, ]}> <TextField className="GroupDialog-text-field" floatingLabelText="Адрес" floatingLabelFixed={true} hintText="Например, https://vk.com/team или просто team" value={this.state.screenName} fullWidth={true} onChange={this.handleScreenNameChange} /> <IconicButton icon="close" onTouchTap={this.handleScreenNameReset} /> </Dialog> } }
static/src/js/pages/Diagnostic.js
enginyoyen/blackcrystal
import React from 'react'; import NavMain from '../components/navigation/NavMain'; import PageFooter from '../components/PageFooter'; import PageHeader from '../components/PageHeader'; import { Row, Col, Grid } from 'react-bootstrap'; const Overview = React.createClass({ getInitialState() { return {}; }, componentDidMount(){ }, render() { return ( <div> <NavMain activePage="diagnostic"/> <PageHeader title="Diagnostic"/> <Grid> <Row> <div className="box box-success"> <div className="box-header with-border"> <h3 className="box-title"></h3> </div> <div className="box-body"> To be implemented.... </div> </div> </Row> </Grid> <PageFooter /> </div> ); } }); export default Overview;
src/components/Trust/index.js
iris-dni/iris-frontend
import React from 'react'; import settings from 'settings'; import styles from './trust.scss'; import Heading2 from 'components/Heading2'; import Container from 'components/Container'; import Section from 'components/Section'; import TextCenter from 'components/TextCenter'; import FormWrapper from 'components/FormWrapper'; import FormHeader from 'components/FormHeader'; import TrustSupportForm from 'components/TrustSupportForm'; import TrustPublishForm from 'components/TrustPublishForm'; import SsoProviders from 'components/SsoProviders'; import generateSsoProviders from 'helpers/generateSsoProviders'; import getReturnUrlFromLocation from 'helpers/getReturnUrlFromLocation'; import TrustFlow from 'components/TrustFlow'; const getPageIntro = (loggedIn, action) => ({ title: settings.trustPage[action][loggedIn ? 'trustedTitle' : 'title'], intro: settings.trustPage[action][loggedIn ? 'trustedIntro' : 'intro'] }); const Trust = ({ isLoggedIn, location, action }) => ( <div> <Container> <TextCenter> <FormHeader {...getPageIntro(isLoggedIn, action)}> <div className={styles.sso}> {!isLoggedIn && <SsoProviders providers={generateSsoProviders( settings.ssoProviders, getReturnUrlFromLocation(location) )} /> } </div> </FormHeader> </TextCenter> </Container> <div className={styles.form}> <Section theme={'light'} padding margin> <Container> <FormWrapper> {!isLoggedIn && <div className={styles['form-title']}> <Heading2 text={settings.trustPage[action].formTitle} /> </div> } {action === 'support' && <TrustSupportForm /> } {action === 'publish' && <TrustPublishForm /> } </FormWrapper> </Container> </Section> </div> <Container> <FormWrapper> <TrustFlow action={action} /> </FormWrapper> </Container> </div> ); Trust.propTypes = { location: React.PropTypes.object.isRequired, action: React.PropTypes.oneOf([ 'support', 'publish' ]) }; export default Trust;
node_modules/react-error-overlay/lib/components/Collapsible.js
kishigo/recipes-react-redux
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 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; } /** * 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 { black } from '../styles'; var _collapsibleStyle = { color: black, cursor: 'pointer', border: 'none', display: 'block', width: '100%', textAlign: 'left', background: '#fff', fontFamily: 'Consolas, Menlo, monospace', fontSize: '1em', padding: '0px', lineHeight: '1.5' }; var collapsibleCollapsedStyle = Object.assign({}, _collapsibleStyle, { marginBottom: '1.5em' }); var collapsibleExpandedStyle = Object.assign({}, _collapsibleStyle, { marginBottom: '0.6em' }); var Collapsible = function (_Component) { _inherits(Collapsible, _Component); function Collapsible() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Collapsible); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Collapsible.__proto__ || Object.getPrototypeOf(Collapsible)).call.apply(_ref, [this].concat(args))), _this), _this.state = { collapsed: true }, _this.toggleCollaped = function () { _this.setState(function (state) { return { collapsed: !state.collapsed }; }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Collapsible, [{ key: 'render', value: function render() { var count = this.props.children.length; var collapsed = this.state.collapsed; return React.createElement( 'div', null, React.createElement( 'button', { onClick: this.toggleCollaped, style: collapsed ? collapsibleCollapsedStyle : collapsibleExpandedStyle }, (collapsed ? '▶' : '▼') + (' ' + count + ' stack frames were ') + (collapsed ? 'collapsed.' : 'expanded.') ), React.createElement( 'div', { style: { display: collapsed ? 'none' : 'block' } }, this.props.children, React.createElement( 'button', { onClick: this.toggleCollaped, style: collapsibleExpandedStyle }, '\u25B2 ' + count + ' stack frames were expanded.' ) ) ); } }]); return Collapsible; }(Component); export default Collapsible;
examples/shopping-cart/src/main.js
adrianleb/nuclear-js
'use strict'; import React from 'react' import App from './components/App' import reactor from './reactor' import actions from './actions' import CartStore from './stores/CartStore' import ProductStore from './stores/ProductStore' reactor.registerStores({ cart: CartStore, products: ProductStore, }) actions.fetchProducts() React.render( React.createElement(App, null), document.getElementById('flux-app') );
app/clients/next/pages/about.js
koapi/koapp
import React from 'react' import { compose } from 'recompose' import page from '../components/page' import Link from 'next/link' import provider from '../redux' export default compose(provider(), page({ title: 'About' }))(props => ( <div> <div> Next App </div> <p> <Link prefetch href='/'><a>Index</a></Link> </p> </div> ))
src/app/Routes.js
lpan/htn-challenge
import React from 'react'; import { Router, Route, Redirect } from 'react-router'; import { history } from './store'; import App from './App'; import Applicants from './views/Applicants'; import Details from './views/Details'; const Routes = () => ( <Router history={history}> <Redirect from="/" to="applicants" /> <Route path="/" component={App}> <Route path="/applicants" component={Applicants} /> <Route path="/details" component={Details} /> </Route> </Router> ); export default Routes;
src/components/SideNav/SideNav.js
franciscopreller/outflow-client
import React from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import AppBar from 'material-ui/AppBar'; import AddConnectionIcon from 'material-ui/svg-icons/content/add-circle'; import PreferencesIcon from 'material-ui/svg-icons/action/settings'; import { addSession } from '../../modules/session/actions'; import AddConnectionDialog from './AddConnectionDialog'; export class SideNav extends React.Component { static contextTypes = { store: React.PropTypes.object, }; constructor(props, context) { super(props, context); this.state = { open: false, addConnectionDialogOpen: false, }; // Bindings this.handleRequestChange = this.handleRequestChange.bind(this); this.handleOpenDialog = this.handleOpenDialog.bind(this); this.handleCloseDialog = this.handleCloseDialog.bind(this); this.handleAddNewConnection = this.handleAddNewConnection.bind(this); } getStyles() { return { headerTitleStyle: { fontSize: '20px', height: '128px', }, }; } handleRequestChange(open) { this.setState({open}); } handleCloseDialog() { this.setState({ addConnectionDialogOpen: false, }); } handleOpenDialog() { this.setState({ open: false, addConnectionDialogOpen: true, }); } handleAddNewConnection({ host, port, name }) { this.context.store.dispatch(addSession({ host, port, name })); // Close the dialog this.handleCloseDialog(); } render() { const navigationItems = [{ primaryText: 'New Connection', leftIcon: <AddConnectionIcon />, onTouchTap: this.handleOpenDialog, }, { primaryText: 'Preferences', leftIcon: <PreferencesIcon />, onTouchTap: () => alert('clicked preferences'), }]; return ( <div> <AddConnectionDialog handleCloseDialog={this.handleCloseDialog} handleOpenDialog={this.handleOpenDialog} handleAddNewConnection={this.handleAddNewConnection} open={this.state.addConnectionDialogOpen} /> <Drawer open={this.state.open} docked={false} onRequestChange={this.handleRequestChange}> <AppBar title="OutFlow" showMenuIconButton={false} titleStyle={this.getStyles().headerTitleStyle}/> {navigationItems.map((item, key) => <MenuItem key={`snav__${key}`} {...item} />)} </Drawer> </div> ); } } export default SideNav;
src/components/Schedule/Schedule.js
hack-duke/hackduke-ideate-website
import React from 'react' import classes from './Schedule.scss' const title = 'Schedule' export const Schedule = (props) => ( <div className={classes.schedule}> <h1 className={classes.header}>{title}</h1> <div className={classes.schedule}> <img className={classes.image} src={'schedule.png'} alt={'placeholder'} /> </div> </div> ) Schedule.proptypes = { pdf: React.PropTypes.string.isRequired } export default Schedule
src/svg-icons/file/attachment.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileAttachment = (props) => ( <SvgIcon {...props}> <path d="M2 12.5C2 9.46 4.46 7 7.5 7H18c2.21 0 4 1.79 4 4s-1.79 4-4 4H9.5C8.12 15 7 13.88 7 12.5S8.12 10 9.5 10H17v2H9.41c-.55 0-.55 1 0 1H18c1.1 0 2-.9 2-2s-.9-2-2-2H7.5C5.57 9 4 10.57 4 12.5S5.57 16 7.5 16H17v2H7.5C4.46 18 2 15.54 2 12.5z"/> </SvgIcon> ); FileAttachment = pure(FileAttachment); FileAttachment.displayName = 'FileAttachment'; FileAttachment.muiName = 'SvgIcon'; export default FileAttachment;
common/components/ide/TabBar.js
ebertmi/webbox
import React from 'react'; import screenfull from 'screenfull'; import Icon from '../Icon'; import {Nav, NavItem} from '../bootstrap'; import Menu from './Menu'; import SendToTeacherModal from './SendToTeacherModal'; import Tab from './tabs/Tab'; import FileTab from './tabs/FileTab'; import ProcessTab from './tabs/ProcessTab'; import OptionsTab from './tabs/OptionsTab'; import InsightsTab from './tabs/InsightsTab'; import AttributesTab from './tabs/AttributesTab'; import MatplotlibTab from './tabs/MatplotlibTab'; import TurtleTab from './tabs/TurtleTab'; import TestAuthoringTab from './tabs/TestAuthoringTab'; import TestResultTab from './tabs/TestResultTab'; import { MODES } from '../../constants/Embed'; import ScrollableElement from '../scrollable/ScrollableElement'; const TAB_TYPES = { file: FileTab, options: OptionsTab, process: ProcessTab, insights: InsightsTab, attributes: AttributesTab, matplotlib: MatplotlibTab, turtle: TurtleTab, tests: TestAuthoringTab, testresult: TestResultTab }; export default class TabBar extends React.Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); this.onStartStop = this.onStartStop.bind(this); this.onTest= this.onTest.bind(this); this.onShareWithTeacher = this.onShareWithTeacher.bind(this); this.onSave = this.onSave.bind(this); this.onToggleFullscreen = this.onToggleFullscreen.bind(this); this.onScreenfullChange = this.onScreenfullChange.bind(this); this.onTabListScroll = this.onTabListScroll.bind(this); this.onToggleSendToTeacherModal = this.onToggleSendToTeacherModal.bind(this); this.onCloseSendToTeacherModal = this.onCloseSendToTeacherModal.bind(this); this.state = { showSendToTeacherModal: false, tabs: [] }; } componentDidMount() { // Add screenfull listener if (screenfull.isEnabled) { document.addEventListener(screenfull.raw.fullscreenchange, this.onScreenfullChange); } this.props.project.on('change', this.onChange); this.props.project.tabManager.on('change', this.onChange); this.onChange(); } componentWillUnmount() { this.props.project.removeListener('change', this.onChange); this.props.project.tabManager.removeListener('change', this.onChange); if (screenfull.isEnabled) { // Remove listener (cleanup) document.removeEventListener(screenfull.raw.fullscreenchange, this.onScreenfullChange); } } onToggleSendToTeacherModal() { this.setState({ showSendToTeacherModal: !this.state.showSendToTeacherModal }); } onCloseSendToTeacherModal() { this.setState({ showSendToTeacherModal: false }); } onShareWithTeacher(message) { this.props.project.shareWithTeacher(message); } onScreenfullChange() { this.forceUpdate(); } onChange() { this.setState({ tabs: this.props.project.tabManager.getTabs() }); this.forceUpdate(); } /** * Toggles between fullscreen and normal, if supported */ onToggleFullscreen(e) { if (screenfull.isEnabled) { screenfull.toggle(e.currentTarget.closest('.ide')); } } onTabClick(index, e) { e.preventDefault(); if (e.button === 1) { this.props.project.tabManager.closeTab(index); } else if (e.ctrlKey || e.shiftKey) { // toggle tab should display it on a split view this.props.project.tabManager.toggleTab(index); } else { this.props.project.tabManager.switchTab(index); } } onTabClose(index, e) { e.preventDefault(); this.props.project.tabManager.closeTab(index); } onStartStop(e) { e.preventDefault(); let project = this.props.project; if (project.isRunning()) { project.stop(); } else { project.run(); } } onTest(e) { e.preventDefault(); let project = this.props.project; if (project.isRunning()) { project.stop(); } else { project.test(); } } onSave(e) { e.preventDefault(); this.props.project.saveEmbed(); } onTabListScroll(offset) { if (this.tabList != null) { if (offset.scrollLeft != null) { this.tabList.scrollLeft = offset.scrollLeft; } } } renderTabs() { let project = this.props.project; return project.tabManager.getTabs().map(({active, item, type, uniqueId}, index) => { let TabType = TAB_TYPES[type] || Tab; return ( <TabType className="tab-item" key={uniqueId} active={active} item={item} onClick={this.onTabClick.bind(this, index)} onClose={this.onTabClose.bind(this, index)} /> ); }); } render() { let project = this.props.project; let startStop; let tester; let shareWithTeacher; const isRunning = project.isRunning(); const fullScreenIcon = screenfull.isFullscreen ? 'compress' : 'expand'; if (project.run) { startStop = ( <NavItem className="unselectable" onClick={this.onStartStop} title="Ausführen/Stoppen (Strg+B)" useHref={false}> {isRunning ? <Icon name="stop" className="danger"/> : <Icon name="play" className="success"/>} </NavItem> ); } if (project.test && project.hasTestCode()) { tester = ( <NavItem className="unselectable" onClick={this.onTest} useHref={false}> <Icon name="check-square-o" /> </NavItem> ); } if (this.props.project.mode === MODES.Default) { shareWithTeacher = ( <NavItem className="unselectable" onClick={this.onToggleSendToTeacherModal} useHref={false} title="An Dozenten schicken" > <Icon className="unselectable" name="paper-plane" title="An Dozenten schicken" /> </NavItem> ); } return ( <div className="control-bar"> <ScrollableElement scrollYToX={true} className="tabs-scroll-wrapper" onScroll={this.onTabListScroll}> <nav className="tabs-container" ref={ref => { this.tabList = ref; }}> {this.renderTabs()} </nav> </ScrollableElement> <span className="embed-title">{project.name}</span> <Nav className="controls" bsStyle="pills"> {startStop} {tester} <NavItem className="unselectable" onClick={this.onSave} useHref={false} title="Speichern (Strg+S)"> <Icon name="save" /> </NavItem> { shareWithTeacher } <SendToTeacherModal isOpen={this.state.showSendToTeacherModal} toggle={this.onCloseSendToTeacherModal} callback={this.onShareWithTeacher} /> <NavItem className="unselectable" onClick={this.onToggleFullscreen} title="Vollbildmodus" disabled={!screenfull.isEnabled}> <Icon name={fullScreenIcon} title="Vollbildmodus"/> </NavItem> <Menu project={project}/> </Nav> </div> ); } }
node_modules/native-base/Components/Widgets/List.js
paulunits/tiptap
/* @flow */ 'use strict'; import React from 'react'; import {View, ListView} from 'react-native'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import _ from 'lodash'; export default class ListNB extends NativeBaseComponent { getInitialStyle() { return { list: { }, insetList: { borderWidth: 1, borderColor: this.getTheme().listBorderColor, margin: 15, borderBottomWidth: 0 } } } prepareRootProps() { var defaultProps = { style: this.props.inset ? this.getInitialStyle().insetList : this.getInitialStyle().list }; return computeProps(this.props, defaultProps); } renderChildren() { var childrenArray = React.Children.toArray(this.props.children); var keyIndex = 0; childrenArray = childrenArray.map((child) => { keyIndex++; return React.cloneElement(child, {...child.props, key: keyIndex}); }); var lastElement = _.last(childrenArray); // var modLastElement = React.cloneElement(lastElement, computeProps(lastElement.props, {last: true})); return _.concat(_.slice(childrenArray, 0, childrenArray.length - 1), lastElement); } render() { if(this.props.dataArray && this.props.renderRow) { const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var dataSource = ds.cloneWithRows(this.props.dataArray); return ( <ListView {...this.prepareRootProps()} enableEmptySections={true} dataSource={dataSource} renderRow={this.props.renderRow} /> ); } else return( <View {...this.prepareRootProps()} > {this.renderChildren()} </View> ); } }
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js
rekyyang/ArtificalLiverCloud
import _transformLib from 'transform-lib'; const _components = { Foo: { displayName: 'Foo' } }; const _transformLib2 = _transformLib({ filename: '%FIXTURE_PATH%', components: _components, locals: [], imports: [] }); function _wrapComponent(id) { return function (Component) { return _transformLib2(Component, id); }; } import React, { Component } from 'react'; const Foo = _wrapComponent('Foo')(class Foo extends Component { render() {} });
js/components/utility/export-modal.js
NullVoxPopuli/tanqueReact
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { connect } from 'react-redux'; import { Button, Tooltip } from 'reactstrap'; import CopyToClipboard from 'react-copy-to-clipboard'; import { objectToDataURL, convertObjectToQRCodeDataURL } from 'utility'; import SimpleModal from 'components/-components/simple-modal'; const mapStateToProps = state => ({ config: state.identity.config }); @connect(mapStateToProps, {}) export default class ExportModal extends React.Component { static propTypes = { config: PropTypes.object, tagName: PropTypes.string } constructor(props) { super(props); this.state = { showModal: false, copied: false, Tag: props.tagName || 'li' }; this.didClickDownload = this.didClickDownload.bind(this); this.didCopy = this.didCopy.bind(this); } componentWillMount() { this.renderQrCode(); } identity() { const { config } = this.props; const { alias, publicKey: publickey, uid } = (config || {}); return { alias, publickey, uid }; } didClickDownload() { this.refs.downloadIdentity.click(); } didCopy() { this.setState({ copied: true }); setTimeout(() => { this.setState({ copied: false }); }, 1000); } async renderQrCode() { const identity = this.identity(); const dataUrl = await convertObjectToQRCodeDataURL(identity); this.setState({ qrCode: dataUrl }); } render() { const { config } = this.props; const { copied, Tag, qrCode } = this.state; // don't show the export functionality when // we haven't set ourselves up yet. if (_.isEmpty(config)) return null; const identity = this.identity(); const formattedJson = JSON.stringify(identity, null, 2); const dataUrl = objectToDataURL(identity); const filename = `${config.alias}.json`; const tooltipId = 'export-tooltip-copy'; return ( <Tag> <a style={{ display: 'none' }} ref='downloadIdentity' href={dataUrl} download={filename} target='_blank'></a> <SimpleModal title='Export Identity' buttonText='Export Identity' confirmText='Download' cancelText='Close' additionalFooterButtons={ <CopyToClipboard text={formattedJson} onCopy={this.didCopy}> <Button id={tooltipId}> Copy <Tooltip placement="bottom" isOpen={copied} autohide={true} target={tooltipId}> Copied! </Tooltip> </Button> </CopyToClipboard> } onConfirm={this.didClickDownload}> <div className="d-flex flex-row align-items-stretch"> <img src={qrCode} /> <pre style={{ marginBottom: 0 }}> {formattedJson} </pre> </div> </SimpleModal> </Tag> ); } }
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
tateisu/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages } from 'react-intl'; import IconButton from '../../../components/icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import detectPassiveEvents from 'detect-passive-events'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ public_short: { id: 'privacy.public.short', defaultMessage: 'Public' }, public_long: { id: 'privacy.public.long', defaultMessage: 'Post to public timelines' }, unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' }, unlisted_long: { id: 'privacy.unlisted.long', defaultMessage: 'Do not show in public timelines' }, private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' }, private_long: { id: 'privacy.private.long', defaultMessage: 'Post to followers only' }, direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' }, direct_long: { id: 'privacy.direct.long', defaultMessage: 'Post to mentioned users only' }, change_privacy: { id: 'privacy.change', defaultMessage: 'Adjust status privacy' }, }); const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; class PrivacyDropdownMenu extends React.PureComponent { static propTypes = { style: PropTypes.object, items: PropTypes.array.isRequired, value: PropTypes.string.isRequired, placement: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } handleKeyDown = e => { const { items } = this.props; const value = e.currentTarget.getAttribute('data-index'); const index = items.findIndex(item => { return (item.value === value); }); let element; switch(e.key) { case 'Escape': this.props.onClose(); break; case 'Enter': this.handleClick(e); break; case 'ArrowDown': element = this.node.childNodes[index + 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'ArrowUp': element = this.node.childNodes[index - 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'Tab': if (e.shiftKey) { element = this.node.childNodes[index - 1] || this.node.lastChild; } else { element = this.node.childNodes[index + 1] || this.node.firstChild; } if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); e.preventDefault(); e.stopPropagation(); } break; case 'Home': element = this.node.firstChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'End': element = this.node.lastChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; } } handleClick = e => { const value = e.currentTarget.getAttribute('data-index'); e.preventDefault(); this.props.onClose(); this.props.onChange(value); } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem) this.focusedItem.focus(); this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } render () { const { mounted } = this.state; const { style, items, placement, value } = 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 }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`privacy-dropdown__dropdown ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null, zIndex: 2 }} role='listbox' ref={this.setRef}> {items.map(item => ( <div role='option' tabIndex='0' key={item.value} data-index={item.value} onKeyDown={this.handleKeyDown} onClick={this.handleClick} className={classNames('privacy-dropdown__option', { active: item.value === value })} aria-selected={item.value === value} ref={item.value === value ? this.setFocusRef : null}> <div className='privacy-dropdown__option__icon'> <Icon id={item.icon} fixedWidth /> </div> <div className='privacy-dropdown__option__content'> <strong>{item.text}</strong> {item.meta} </div> </div> ))} </div> )} </Motion> ); } } export default @injectIntl class PrivacyDropdown extends React.PureComponent { static propTypes = { isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onModalOpen: PropTypes.func, onModalClose: PropTypes.func, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: false, placement: 'bottom', }; handleToggle = ({ target }) => { if (this.props.isUserTouching()) { if (this.state.open) { this.props.onModalClose(); } else { this.props.onModalOpen({ actions: this.options.map(option => ({ ...option, active: option.value === this.props.value })), onClick: this.handleModalActionClick, }); } } else { const { top } = target.getBoundingClientRect(); if (this.state.open && this.activeElement) { this.activeElement.focus(); } this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); this.setState({ open: !this.state.open }); } } handleModalActionClick = (e) => { e.preventDefault(); const { value } = this.options[e.currentTarget.getAttribute('data-index')]; this.props.onModalClose(); this.props.onChange(value); } handleKeyDown = e => { switch(e.key) { case 'Escape': this.handleClose(); break; } } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleClose = () => { if (this.state.open && this.activeElement) { this.activeElement.focus(); } this.setState({ open: false }); } handleChange = value => { this.props.onChange(value); } componentWillMount () { const { intl: { formatMessage } } = this.props; this.options = [ { icon: 'globe', value: 'public', text: formatMessage(messages.public_short), meta: formatMessage(messages.public_long) }, { icon: 'unlock', value: 'unlisted', text: formatMessage(messages.unlisted_short), meta: formatMessage(messages.unlisted_long) }, { icon: 'lock', value: 'private', text: formatMessage(messages.private_short), meta: formatMessage(messages.private_long) }, { icon: 'envelope', value: 'direct', text: formatMessage(messages.direct_short), meta: formatMessage(messages.direct_long) }, ]; } render () { const { value, intl } = this.props; const { open, placement } = this.state; const valueOption = this.options.find(item => item.value === value); return ( <div className={classNames('privacy-dropdown', placement, { active: open })} onKeyDown={this.handleKeyDown}> <div className={classNames('privacy-dropdown__value', { active: this.options.indexOf(valueOption) === (placement === 'bottom' ? 0 : (this.options.length - 1)) })}> <IconButton className='privacy-dropdown__value-icon' icon={valueOption.icon} title={intl.formatMessage(messages.change_privacy)} size={18} expanded={open} active={open} inverted onClick={this.handleToggle} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} style={{ height: null, lineHeight: '27px' }} /> </div> <Overlay show={open} placement={placement} target={this}> <PrivacyDropdownMenu items={this.options} value={value} onClose={this.handleClose} onChange={this.handleChange} placement={placement} /> </Overlay> </div> ); } }
source/containers/SearchPage/TopFilter.js
mikey1384/twin-kle
import React from 'react'; import PropTypes from 'prop-types'; import FilterBar from 'components/FilterBar'; TopFilter.propTypes = { applyFilter: PropTypes.func.isRequired, style: PropTypes.object, selectedFilter: PropTypes.string.isRequired }; export default function TopFilter({ applyFilter, selectedFilter, style }) { return ( <FilterBar style={style} bordered> <nav className={selectedFilter === 'video' ? 'active' : ''} onClick={() => applyFilter('video')} > Videos </nav> <nav className={selectedFilter === 'url' ? 'active' : ''} onClick={() => applyFilter('url')} > Links </nav> <nav className={selectedFilter === 'subject' ? 'active' : ''} onClick={() => applyFilter('subject')} > Subjects </nav> </FilterBar> ); }
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js
jamiehill/react-router
import React from 'react'; class Announcements extends React.Component { render () { return ( <div> <h3>Announcements</h3> {this.props.children || <p>Choose an announcement from the sidebar.</p>} </div> ); } } export default Announcements;
src/app/components/App.js
Dynamit/healthcare-microsite
/** * Top-level component for the app */ import React from 'react'; import { RouteHandler, Navigation } from 'react-router'; import Helmet from 'react-helmet'; import Symbol from './Symbol'; import Button from './Button'; import Menu from './Menu'; import mixin from 'react-mixin'; import classNames from 'classnames'; import api from '../api'; import PrevNext from './PrevNext'; import ImageLoader from 'react-imageloader'; // conditionally load `scroll` module // its dependencies call `window` and break gulpfile.babel let scroll; if (typeof window !== 'undefined') { scroll = require('scroll'); } class App extends React.Component { constructor(props) { super(props); /** * Default state * @type {Object} */ this.state = { /** * The `slug` of the currently selected article * @type {String} */ selectedArticle: (this.props.data.article) ? this.props.data.article.slug : 'introduction', /** * Whether or not the user is in reading mode * @type {Boolean} */ isReading: this.props.isReading || false, /** * Whether or not the (mobile) menu is open * @type {Boolean} */ isNavigating: false, /** * Whether or not the user has engaged the menu. Used to add animation classes. * @type {Boolean} */ hasEngaged: false, /** * Whether or not the poster image is loading * @type {Boolean} */ posterLoading: false, /** * Style breakpoint, captured from body:before content */ breakpoint: '' }; /** * List of placeholder values "all" articles * @type {Array} */ this.articleList = [ 'Introduction', '2015 August 26', '2015 September 9', '2015 September 23', '2015 October 7' ] } /** * Async call for data * @return {Promise} */ static fetchData() { return api.get('/article.json'); } componentDidMount() { // add breakpoint listener window.addEventListener('resize', this._refreshBreakpoint.bind(this)); this._refreshBreakpoint(); } /** * Get breakpoint value from styles */ _refreshBreakpoint() { let bp = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, ''); this.setState({ breakpoint: bp }); } /** * Set an article as "selected". * Article can be "selected", but not "reading"; user can previewing article. * @param {String} key Id (same as slug) of the article * @param {Object} e Event */ _selectArticle(key, e, animate) { if (e) { e.preventDefault() } // if user selected article is already select, close nav and return if (this.state.selectedArticle === key) { this.setState({ isNavigating: false }); return; } let state = { isLoading: animate, posterLoading: true }; if (this.state.isNavigating) { state.selectedArticle = key; } // trigger loading this.setState(state, () => { // if should animate and menu is closed, delay, else, no delay let delay = (animate) ? this.props.duration : 0; setTimeout(() => { this.setState({ selectedArticle: key, isNavigating: false }, () => { if (this.state.isReading) { this._gotoArticle(); } if (animate) { setTimeout(() => { this.setState({ isLoading: false }) }, delay); } if (!this.state.isNavigating && !this.state.isReading) { React.findDOMNode(this.refs.ArticleLeadHeading).focus(); } }); }, delay); }); } /** * Stop reading. Return to "Home". * @param {Object} e Event */ _stopReading(e) { if (e) { e.preventDefault() } this.setState({ isReading: false }, () => { this.transitionTo('/'); }); } /** * Go into "reading" mode. * Start reading selected article. */ _startReading() { this.setState({ isReading: true }); } /** * Route to the selected article (read from state) * @param {Object} e Event */ _gotoArticle(e) { if (e) { e.preventDefault() } this._scrollToTop().then(() => { this.transitionTo(`/article/${this.props.data.meta[this.state.selectedArticle].slug}`); React.findDOMNode(this.refs.ArticleLeadHeading).focus(); }); } /** * Smooth scroll both container and Handler component to top * @return {Promise} */ _scrollToTop() { let scrollApp = new Promise((resolve, reject) => { scroll.top(React.findDOMNode(this.refs.App), 0, resolve); }); let scrollHandler = new Promise((resolve, reject) => { scroll.top(React.findDOMNode(this.refs.Handler), 0, resolve); }); return new Promise((resolve, reject) => { Promise.all([scrollApp, scrollHandler]).then(resolve); }); } /** * Toggle open/close the menu. * Indicate that the app has been engaged (used to apply animations) * @param {Object} e Event */ _toggleMenu(e) { if (e) { e.preventDefault() } this.setState({ isNavigating: !this.state.isNavigating, hasEngaged: true }, () => { if (this.state.isNavigating) { React.findDOMNode(this.refs.Menu).focus(); } }); } /** * When poster image loads, update state */ _handlePosterLoad() { this.setState({ posterLoading: false }); } render() { // data for selected article let selectedArticleData = this.props.data.meta[this.state.selectedArticle]; // conditional classes let containerClassNames = classNames('app', { 'is-navigating': this.state.isNavigating, 'is-reading': this.state.isReading || this.props.data.article }); let bodyClassNames = classNames('body', { 'animate-bodyIn': !this.state.isNavigating && this.state.hasEngaged, 'animate-bodyOut': this.state.isNavigating, 'animate-articleIn': this.state.isReading || this.props.data.article, 'animate-articleOut': !this.state.isReading, 'is-loading': this.state.isLoading }); let menuClassNames = classNames({ 'animate-menuIn': this.state.isNavigating, 'animate-menuOut': !this.state.isNavigating && this.state.hasEngaged }); let posterClassNames = classNames('poster', { 'is-loading': this.state.posterLoading }); // if menu is open, make a click/touch on the `body` close the menu let bodyCloseHandler = (this.state.isNavigating) ? this._toggleMenu.bind(this) : ''; return ( <div ref="App" className={containerClassNames} role="main"> <Helmet title={this.props.title} meta={[ { name: 'description', content: this.props.description }, { name: 'og:description', content: this.props.description }, { property: 'og:title', content: this.props.title }, { property: 'og:type', content: 'article' }, { property: 'og:image', content: `${this.props.baseurl}/assets/images/${selectedArticleData.image}` }, { property: 'twitter:card', content: 'summary_large_image' }, { property: 'twitter:site', content: '@dynamit' }, { property: 'twitter:title', content: this.props.title }, { property: 'twitter:description', content: this.props.description }, { property: 'twitter:image', content: `${this.props.baseurl}/assets/images/${selectedArticleData.image}` } ]} /> <div className={bodyClassNames} onTouchStart={bodyCloseHandler} onClick={bodyCloseHandler}> <div className="header" role="banner"> <div className="lockup" onClick={this._stopReading.bind(this)} > <Symbol href="/" aria-label="Home" id="dynamit-logo" /> </div> <a href="/" tabIndex="0" className="menu-toggle" onClick={this._toggleMenu.bind(this)}> <span className="menu-toggle-label">More Articles</span> <Symbol id="menu-icon" containerNodeType="div" /> </a> </div> <div className={posterClassNames}> <ImageLoader src={`/assets/images/${selectedArticleData.image}`} onLoad={this._handlePosterLoad.bind(this)} imgProps={{ alt: ' ' }} wrapper={React.DOM.div} /> <div className="article-lead"> <h1 key={selectedArticleData.slug}> <a href={`/article/${selectedArticleData.slug}/`} ref="ArticleLeadHeading" onClick={this._gotoArticle.bind(this)}>{selectedArticleData.title}</a> </h1> <div className="article-lead-extras"> <p>{selectedArticleData.abstract}</p> <Button href={`/article/${selectedArticleData.slug}/`} onClick={this._gotoArticle.bind(this)}>Continue Reading</Button> </div> <PrevNext {...this.props} items={this.articleList} selectedArticle={this.state.selectedArticle} handleSelectArticle={this._selectArticle.bind(this)} /> </div> </div> <div ref="Handler" className="handler"> <RouteHandler {...this.props} breakpoint={this.state.breakpoint} selectedArticle={this.state.selectedArticle} isReading={this.state.isReading} handleSelectArticle={this._selectArticle.bind(this)} handleGotoArticle={this._gotoArticle.bind(this)} handleStartReading={this._startReading.bind(this)} handleStopReading={this._stopReading.bind(this)} /> </div> </div> <Menu ref="Menu" className={menuClassNames} items={this.articleList} selectedArticle={this.state.selectedArticle} articles={this.props.data.meta} handleSelectArticle={this._selectArticle.bind(this)} /> </div> ); } }; // mixin Navigation from react-router mixin.onClass(App, Navigation); // default props App.defaultProps = { title: 'Healthcare | Dynamit', description: 'Digital ideas for shaping the healthcare consumer experience in the areas of relationships, access, communication, and adoption.', baseurl: 'http://healthcare.dynamit.com', duration: 300 } export default App;
src/svg-icons/content/remove-circle-outline.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentRemoveCircleOutline = (props) => ( <SvgIcon {...props}> <path d="M7 11v2h10v-2H7zm5-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ContentRemoveCircleOutline = pure(ContentRemoveCircleOutline); ContentRemoveCircleOutline.displayName = 'ContentRemoveCircleOutline'; ContentRemoveCircleOutline.muiName = 'SvgIcon'; export default ContentRemoveCircleOutline;
src/main/scripts/modules/sea-siege/react/views/card/mana-cost.js
twuni/sea-siege
import React from 'react'; import _ from 'lodash'; import Component from '../../components/component'; import Icon from '../../components/icon'; const {number} = React.PropTypes; class ManaCost extends Component { static get propTypes() { return Component.withPropTypes({ red: number, blue: number, black: number, white: number, green: number, any: number }); } static get defaultProps() { return Component.withDefaultProps({ red: 0, blue: 0, black: 0, white: 0, green: 0, any: 0 }); } renderEachManaType() { return _.compact(_.map(['red', 'blue', 'black', 'white', 'green', 'any'], (manaType) => { let cost = this.props[manaType]; if(cost == 0) { return undefined; } if(cost == -1) { cost = '*'; } if(manaType !== 'any') { return _.times(cost, function(n) { return <span key={`${manaType}-${n}`} className={manaType}/> }); } return <span key={manaType} className={manaType}>{cost}</span> })); } render() { return <span className={this.classNames}>{this.renderEachManaType()}</span> } } export default ManaCost;
src/components/Logout.js
DmitriWolf/atm-challenge
import React, { Component } from 'react'; import { Link } from 'react-router' class Logout extends Component { render() { return ( <div className="dashboard logout"> <h2>Thank you for using this Bank of Dmitri ATM.</h2> <ul className="menu"> <Link to="/login"><li>Login</li></Link> </ul> </div> ); } } export default Logout;
frontend/node_modules/recharts/src/component/DefaultTooltipContent.js
justdotJS/rowboat
/** * @fileOverview Default Tooltip Content */ import _ from 'lodash'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import pureRender from '../util/PureRender'; import { isNumOrStr } from '../util/DataUtils'; const defaultFormatter = value => ( (_.isArray(value) && isNumOrStr(value[0]) && isNumOrStr(value[1])) ? value.join(' ~ ') : value ); @pureRender class DefaultTooltipContent extends Component { static displayName = 'DefaultTooltipContent'; static propTypes = { separator: PropTypes.string, formatter: PropTypes.func, wrapperStyle: PropTypes.object, itemStyle: PropTypes.object, labelStyle: PropTypes.object, labelFormatter: PropTypes.func, label: PropTypes.any, payload: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.any, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.array]), unit: PropTypes.any, })), itemSorter: PropTypes.func, }; static defaultProps = { separator: ' : ', itemStyle: {}, labelStyle: {}, }; renderContent() { const { payload, separator, formatter, itemStyle, itemSorter } = this.props; if (payload && payload.length) { const listStyle = { padding: 0, margin: 0 }; const items = payload.sort(itemSorter) .map((entry, i) => { const finalItemStyle = { display: 'block', paddingTop: 4, paddingBottom: 4, color: entry.color || '#000', ...itemStyle, }; const hasName = isNumOrStr(entry.name); const finalFormatter = entry.formatter || formatter || defaultFormatter; return ( <li className="recharts-tooltip-item" key={`tooltip-item-${i}`} style={finalItemStyle}> {hasName ? <span className="recharts-tooltip-item-name">{entry.name}</span> : null} { hasName ? <span className="recharts-tooltip-item-separator">{separator}</span> : null } <span className="recharts-tooltip-item-value"> {finalFormatter ? finalFormatter(entry.value, entry.name, entry, i) : entry.value} </span> <span className="recharts-tooltip-item-unit">{entry.unit || ''}</span> </li> ); }); return <ul className="recharts-tooltip-item-list" style={listStyle}>{items}</ul>; } return null; } render() { const { labelStyle, label, labelFormatter, wrapperStyle } = this.props; const finalStyle = { margin: 0, padding: 10, backgroundColor: '#fff', border: '1px solid #ccc', whiteSpace: 'nowrap', ...wrapperStyle, }; const finalLabelStyle = { margin: 0, ...labelStyle, }; const hasLabel = isNumOrStr(label); let finalLabel = hasLabel ? label : ''; if (hasLabel && labelFormatter) { finalLabel = labelFormatter(label); } return ( <div className="recharts-default-tooltip" style={finalStyle}> <p className="recharts-tooltip-label" style={finalLabelStyle}>{finalLabel}</p> {this.renderContent()} </div> ); } } export default DefaultTooltipContent;
src/admin/client/apps/facebook-sdk.js
cezerin/cezerin
import React from 'react'; import messages from 'lib/text'; import api from 'lib/api'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; export const Description = { key: 'facebook-sdk', name: 'Facebook SDK', coverUrl: '/admin-assets/images/apps/facebook.png', description: `The Facebook SDK for JavaScript provides a rich set of client-side functionality that: <ol> <li>Enables you to use the Like Button and other Social Plugins on your site.</li> <li>Enables you to use Facebook Login to lower the barrier for people to sign up on your site.</li> <li>Makes it easy to call into Facebook's Graph API.</li> <li>Launch Dialogs that let people perform various actions like sharing stories.</li> <li>Facilitates communication when you're building a game or an app tab on Facebook.</li> </ol> <p>The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.</p>` }; const FACEBOOK_CODE = `<script> window.fbAsyncInit = function() { FB.init({ appId : 'YOUR_APP_ID', autoLogAppEvents : true, xfbml : true, version : 'v2.11' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/YOUR_LOCALE/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script>`; export class App extends React.Component { constructor(props) { super(props); this.state = { appId: '', locale: 'en_US' }; } handleAppIdChange = event => { this.setState({ appId: event.target.value }); }; handleLocaleChange = event => { this.setState({ locale: event.target.value }); }; fetchSettings = () => { api.apps.settings .retrieve('facebook-sdk') .then(({ status, json }) => { const appSettings = json; if (appSettings) { this.setState({ appId: appSettings.appId, locale: appSettings.locale }); } }) .catch(error => { console.log(error); }); }; updateSettings = () => { const { appId, locale } = this.state; const htmlCode = appId && appId.length > 0 ? FACEBOOK_CODE.replace(/YOUR_APP_ID/g, appId).replace( /YOUR_LOCALE/g, locale ) : ''; api.apps.settings.update('facebook-sdk', { appId: appId, locale: locale }); api.theme.placeholders.update('facebook-sdk', { place: 'body_start', value: htmlCode }); }; componentDidMount() { this.fetchSettings(); } render() { return ( <div> <div>You can find App ID using the Facebook App Dashboard.</div> <TextField type="text" fullWidth={true} value={this.state.appId} onChange={this.handleAppIdChange} floatingLabelText="App ID" /> <TextField type="text" fullWidth={true} value={this.state.locale} onChange={this.handleLocaleChange} floatingLabelText="Locale" hintText="en_US" /> <div style={{ textAlign: 'right' }}> <RaisedButton label={messages.save} primary={true} disabled={false} onClick={this.updateSettings} /> </div> </div> ); } }
client/src/components/utils/FieldGroup.js
DjLeChuck/recalbox-manager
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Col from 'react-bootstrap/lib/Col'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import { cloneObject } from '../../utils'; class FieldGroup extends Component { static propTypes = { id: PropTypes.string.isRequired, label: PropTypes.node, labelColMd: PropTypes.number, componentColMd: PropTypes.number, }; render() { let controlProps = cloneObject(this.props); delete controlProps.componentColMd; delete controlProps.labelColMd; delete controlProps.label; return ( <FormGroup controlId={this.props.id}> {this.props.label && <Col componentClass={ControlLabel} md={this.props.labelColMd || 4}> {this.props.label} </Col> } <Col md={this.props.componentColMd || 6}> <FormControl {...controlProps} /> </Col> </FormGroup> ); } } export default FieldGroup;
app/javascript/mastodon/features/following/index.js
tateisu/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import ScrollableList from '../../components/scrollable_list'; import MissingIndicator from 'mastodon/components/missing_indicator'; const mapStateToProps = (state, props) => ({ isAccount: !!state.getIn(['accounts', props.params.accountId]), accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']), hasMore: !!state.getIn(['user_lists', 'following', props.params.accountId, 'next']), blockedBy: state.getIn(['relationships', props.params.accountId, 'blocked_by'], false), }); export default @connect(mapStateToProps) class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, blockedBy: PropTypes.bool, isAccount: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchAccount(this.props.params.accountId)); this.props.dispatch(fetchFollowing(this.props.params.accountId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(nextProps.params.accountId)); this.props.dispatch(fetchFollowing(nextProps.params.accountId)); } } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowing(this.props.params.accountId)); }, 300, { leading: true }); render () { const { shouldUpdateScroll, accountIds, hasMore, blockedBy, isAccount } = this.props; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = blockedBy ? <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' /> : <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />; return ( <Column> <ColumnBackButton /> <ScrollableList scrollKey='following' hasMore={hasMore} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} prepend={<HeaderContainer accountId={this.props.params.accountId} hideTabs />} alwaysPrepend emptyMessage={emptyMessage} > {blockedBy ? [] : accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} /> )} </ScrollableList> </Column> ); } }
packages/material-ui-icons/src/LaptopChromebook.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let LaptopChromebook = props => <SvgIcon {...props}> <path d="M22 18V3H2v15H0v2h24v-2h-2zm-8 0h-4v-1h4v1zm6-3H4V5h16v10z" /> </SvgIcon>; LaptopChromebook = pure(LaptopChromebook); LaptopChromebook.muiName = 'SvgIcon'; export default LaptopChromebook;
todomvc/client/index.js
bigsassy/drf-react-redux
import 'todomvc-app-css/index.css'; import React from 'react'; import { render } from 'react-dom'; import configureStore from './store/configureStore'; import Root from './containers/Root'; const store = configureStore(); render( <Root store={store} />, document.getElementById('root') );
docs/app/Examples/collections/Message/Types/MessageExampleMessage.js
clemensw/stardust
import React from 'react' import { Message } from 'semantic-ui-react' const MessageExampleMessage = () => ( <Message> <Message.Header> Changes in Service </Message.Header> <p> We updated our privacy policy here to better service our customers. We recommend reviewing the changes. </p> </Message> ) export default MessageExampleMessage
src/CostSymbols.js
PAK90/mtg-hunter
import React from 'react' export default class CostSymbols extends React.Component { render(){ const { cost } = this.props if (!cost) return null return ( <span> {cost.toLowerCase().match(/([0-z]\/[0-z])|hw|[0-z,½,∞]/g).map(function (basename, i) { var src = './src/img/' + basename.replace("/", "").toLowerCase() + '.png'; return <img key={i} src={src} height='15px' style={{marginBottom: -2}}/>; })} </span> ) } }
services/ui/src/components/AddTask/components/Error.js
amazeeio/lagoon
import React from 'react'; export default () => <div>Error.</div>;
pootle/static/js/admin/components/Project/ProjectController.js
Finntack/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import Search from '../Search'; import ProjectAdd from './ProjectAdd'; import ProjectEdit from './ProjectEdit'; const ProjectController = React.createClass({ propTypes: { items: React.PropTypes.object.isRequired, model: React.PropTypes.func.isRequired, onAdd: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, onSearch: React.PropTypes.func.isRequired, onSelectItem: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, searchQuery: React.PropTypes.string.isRequired, selectedItem: React.PropTypes.object, view: React.PropTypes.string.isRequired, }, render() { const viewsMap = { add: ( <ProjectAdd model={this.props.model} collection={this.props.items} onSuccess={this.props.onSuccess} onCancel={this.props.onCancel} /> ), edit: ( <ProjectEdit model={this.props.selectedItem} collection={this.props.items} onAdd={this.props.onAdd} onSuccess={this.props.onSuccess} onDelete={this.props.onDelete} /> ), }; const args = { count: this.props.items.count, }; let msg; if (this.props.searchQuery) { msg = ngettext('%(count)s project matches your query.', '%(count)s projects match your query.', args.count); } else { msg = ngettext( 'There is %(count)s project.', 'There are %(count)s projects. Below are the most recently added ones.', args.count ); } const resultsCaption = interpolate(msg, args, true); return ( <div className="admin-app-projects"> <div className="module first"> <Search fields={['index', 'code', 'fullname', 'disabled']} onSearch={this.props.onSearch} onSelectItem={this.props.onSelectItem} items={this.props.items} selectedItem={this.props.selectedItem} searchLabel={gettext('Search Projects')} searchPlaceholder={gettext('Find project by name, code')} resultsCaption={resultsCaption} searchQuery={this.props.searchQuery} /> </div> <div className="module admin-content"> {viewsMap[this.props.view]} </div> </div> ); }, }); export default ProjectController;
react/gameday2/utils/layoutUtils.js
jaredhasenklein/the-blue-alliance
/* eslint-disable import/prefer-default-export */ import React from 'react' import SvgIcon from 'material-ui/SvgIcon' import { NUM_VIEWS_FOR_LAYOUT, LAYOUT_SVG_PATHS } from '../constants/LayoutConstants' // Convenience wrapper around NUM_VIEWS_FOR_LAYOUT that has bounds checking and // a sensible default. export function getNumViewsForLayout(layoutId) { if (layoutId >= 0 && layoutId < NUM_VIEWS_FOR_LAYOUT.length) { return NUM_VIEWS_FOR_LAYOUT[layoutId] } return 1 } export function getLayoutSvgIcon(layoutId, color = '#757575') { const pathData = LAYOUT_SVG_PATHS[layoutId] return ( <SvgIcon color={color} viewBox="0 0 23 15"> <path d={pathData} /> </SvgIcon> ) } export { getNumViewsForLayout as default }
src/routes.js
lanceharper/react-redux-universal-hot-example
import React from 'react'; import {Route} from 'react-router'; import { App, Home, Widgets, About, Login, RequireLogin, LoginSuccess, Survey, NotFound, } from 'containers'; export default function(store) { return ( <Route component={App}> <Route path="/" component={Home}/> <Route path="/widgets" component={Widgets}/> <Route path="/about" component={About}/> <Route path="/login" component={Login}/> <Route component={RequireLogin} onEnter={RequireLogin.onEnter(store)}> <Route path="/loginSuccess" component={LoginSuccess}/> </Route> <Route path="/survey" component={Survey}/> <Route path="*" component={NotFound}/> </Route> ); }
app/javascript/mastodon/components/dropdown_menu.js
mhffdq/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from './icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import detectPassiveEvents from 'detect-passive-events'; const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; let id = 0; class DropdownMenu extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { items: PropTypes.array.isRequired, onClose: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, }; static defaultProps = { style: {}, placement: 'bottom', }; state = { mounted: 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); this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } handleClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.props.onClose(); if (typeof action === 'function') { e.preventDefault(); action(); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } renderItem (option, i) { if (option === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { text, href = '#' } = option; return ( <li className='dropdown-menu__item' key={`${text}-${i}`}> <a href={href} target='_blank' rel='noopener' role='button' tabIndex='0' autoFocus={i === 0} onClick={this.handleClick} data-index={i}> {text} </a> </li> ); } render () { const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props; const { mounted } = this.state; 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 }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className='dropdown-menu' style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}> <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} /> <ul> {items.map((option, i) => this.renderItem(option, i))} </ul> </div> )} </Motion> ); } } export default class Dropdown extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { icon: PropTypes.string.isRequired, items: PropTypes.array.isRequired, size: PropTypes.number.isRequired, title: PropTypes.string, disabled: PropTypes.bool, status: ImmutablePropTypes.map, isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, dropdownPlacement: PropTypes.string, openDropdownId: PropTypes.number, }; static defaultProps = { title: 'Menu', }; state = { id: id++, }; handleClick = ({ target }) => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } else { const { top } = target.getBoundingClientRect(); const placement = top * 2 < innerHeight ? 'bottom' : 'top'; this.props.onOpen(this.state.id, this.handleItemClick, placement); } } handleClose = () => { this.props.onClose(this.state.id); } handleKeyDown = e => { switch(e.key) { case 'Enter': this.handleClick(e); break; case 'Escape': this.handleClose(); break; } } handleItemClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.handleClose(); if (typeof action === 'function') { e.preventDefault(); action(); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } render () { const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId } = this.props; const open = this.state.id === openDropdownId; return ( <div onKeyDown={this.handleKeyDown}> <IconButton icon={icon} title={title} active={open} disabled={disabled} size={size} ref={this.setTargetRef} onClick={this.handleClick} /> <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}> <DropdownMenu items={items} onClose={this.handleClose} /> </Overlay> </div> ); } }
src/app/components/activities/components/Task.js
backpackcoder/world-in-flames
import React from 'react' import classnames from 'classnames' import Moment from '../../utils/Moment' let Task = React.createClass({ render: function () { let item = this.props.item; return ( <span> <div className="bar-holder no-padding"> <p className="margin-bottom-5"> { item.status == 'PRIMARY' ? <i className="fa fa-warning text-warning"/> : null } <strong>{item.status}:</strong> <i>{item.title}</i> <span className={classnames(['pull-right', 'semi-bold', ( item.status == 'CRITICAL' ? 'text-danger' : 'text-muted' )])}>{ item.width == 100 ? <span> <i className="fa fa-check text-success"/> Complete </span> : <span>{item.width + '%'}</span> }</span> </p> <div className={classnames(['progress', item.progressClass])}> <div className={classnames(['progress-bar', { 'progress-bar-success': item.status == 'MINOR' || item.status == 'NORMAL', 'bg-color-teal': item.status == 'PRIMARY' || item.status == 'URGENT', 'progress-bar-danger': item.status == 'CRITICAL' }])} style={{width: item.width + '%'}}></div> </div> <em className="note no-margin">last updated on <Moment data={this.props.lastUpdate} format="MMMM Do, h:mm a"/></em> </div> </span> ) } }); export default Task
app/javascript/mastodon/features/list_editor/components/search.js
Craftodon/Craftodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists'; import classNames from 'classnames'; const messages = defineMessages({ search: { id: 'lists.search', defaultMessage: 'Search among people you follow' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'suggestions', 'value']), }); const mapDispatchToProps = dispatch => ({ onSubmit: value => dispatch(fetchListSuggestions(value)), onClear: () => dispatch(clearListSuggestions()), onChange: value => dispatch(changeListSuggestions(value)), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class Search extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleKeyUp = e => { if (e.keyCode === 13) { this.props.onSubmit(this.props.value); } } handleClear = () => { this.props.onClear(); } render () { const { value, intl } = this.props; const hasValue = value.length > 0; return ( <div className='list-editor__search search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span> <input className='search__input' type='text' value={value} onChange={this.handleChange} onKeyUp={this.handleKeyUp} placeholder={intl.formatMessage(messages.search)} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={classNames('fa fa-search', { active: !hasValue })} /> <i aria-label={intl.formatMessage(messages.search)} className={classNames('fa fa-times-circle', { active: hasValue })} /> </div> </div> ); } }
src/main.js
virtoolswebplayer/react-redux-starter-kit-chinese
/* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import { useRouterHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; // Configure history for react-router const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }); // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState, browserHistory); const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store); // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={history} routes={routes} store={store}/>, document.getElementById('root') );
src/applications/static-pages/coe-access/createCOEAccess.js
department-of-veterans-affairs/vets-website
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; export default function createCOEAccess(store, widgetType) { const root = document.querySelector(`[data-widget-type="${widgetType}"]`); if (root) { import(/* webpackChunkName: "chapter-31-cta" */ './COEAccess').then( module => { const COEAccess = module.default; ReactDOM.render( <Provider store={store}> <COEAccess /> </Provider>, root, ); }, ); } }
Router/router-demo/src/router/Sidebar.js
imuntil/React
import React from 'react' import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom' const routes = [ { path: '/', exact: true, sidebar () { return <div>home!</div> }, main: () => <h2>Home</h2> }, { path: '/bubblegum', sidebar: () => <div>bubblegum!</div>, main: () => <h2>Bubblegum</h2> }, { path: '/shoelaces', sidebar: () => <div>shoelaces!</div>, main: () => <h2>Shoelaces</h2> } ] const SidebarDemo = ({match}) => ( <Router basename={match.url}> <div style={{display: 'flex'}}> <div style={{ padding: '10px', width: '40%', background: '#f0f0f0' }}> <Route exact path='/' render={() => ( <Redirect to='/' /> )} /> <ul style={{listStyleType: 'none', padding: 0}}> <li><Link to="/">Home</Link></li> <li><Link to="/bubblegum">Bubblegum</Link></li> <li><Link to="/shoelaces">Shoelaces</Link></li> </ul> <hr/> { routes.map((route, index) => ( <Route key={index} path={route.path} exact={route.exact} component={route.sidebar} /> )) } </div> <div style={{flex: 1, padding: '10px'}}> { routes.map((route, index) => ( <Route key={index} path={route.path} exact={route.exact} component={route.main} /> )) } </div> </div> </Router> ) export default SidebarDemo
src/src/pages/Charts/PerformanceChart.js
chaitanya1375/Myprojects
import React from 'react'; import ReactChartist from 'react-chartist'; import Chartist from 'chartist'; const dataPerformance = { labels: ['6pm','9pm','11pm', '2am', '4am', '8am', '2pm', '5pm', '8pm', '11pm', '4am'], series: [ [1, 6, 8, 7, 4, 7, 8, 12, 16, 17, 14, 13] ] }; const optionsPerformance = { showPoint: false, lineSmooth: true, height: "260px", axisX: { showGrid: false, showLabel: true }, axisY: { offset: 40, }, low: 0, high: 16 }; const PerformanceChart = () => ( <div className="card"> <div className="header"> <h4>24 Hours Performance</h4> <p className="category">Line Chart</p> </div> <div className="content"> <ReactChartist data={dataPerformance} options={optionsPerformance} type="Line" className="ct-chart" /> </div> </div> ); export default PerformanceChart;
src/components/Input.js
aastein/crypto-trader
import React from 'react'; import PropTypes from 'prop-types'; const Input = props => ( ( <div> <input className={`${props.className} ${props.invalid ? 'invalid' : ''}`} maxLength={props.maxLength} name={props.name} onChange={e => props.onChange(props.name, e)} placeholder={props.placeholder} type={props.type} value={props.value} /> </div> ) ); Input.propTypes = { className: PropTypes.string.isRequired, invalid: PropTypes.bool, maxLength: PropTypes.number, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, placeholder: PropTypes.string, value: PropTypes.string, }; Input.defaultProps = { invalid: false, maxLength: Number.MAX_SAFE_INTEGER, placeholder: '', value: '', type: 'text', }; export default Input;
packages/material-ui-icons/src/ShowChart.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ShowChart = props => <SvgIcon {...props}> <path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z" /> </SvgIcon>; ShowChart = pure(ShowChart); ShowChart.muiName = 'SvgIcon'; export default ShowChart;
src/svg-icons/action/account-balance-wallet.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBalanceWallet = (props) => ( <SvgIcon {...props}> <path d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); ActionAccountBalanceWallet = pure(ActionAccountBalanceWallet); ActionAccountBalanceWallet.displayName = 'ActionAccountBalanceWallet'; ActionAccountBalanceWallet.muiName = 'SvgIcon'; export default ActionAccountBalanceWallet;
client/components/SearchResults.js
rompingstalactite/rompingstalactite
import React from 'react'; import { connect } from 'react-redux'; import RecipeContainer from '../../client/components/RecipeContainer.js'; import '../scss/_search.scss'; const SearchResults = (props) => ( <div className="search-results container"> <div className="row"> <div className="col-xs-12"> <RecipeContainer className="recipes-searched" type="Search Results" recipes={props.recipesSearched} /> </div> </div> </div> ); const mapStateToProps = (state) => { return { recipesSearched: state.recipesSearched, }; }; export default connect(mapStateToProps)(SearchResults);
src/components/Root.js
git-okuzenko/react-redux
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import routes from '../routes'; import { Router } from 'react-router'; export default class Root extends Component { render() { const { store, history } = this.props; return ( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ); } } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired };
src/packages/@ncigdc/modern_components/CancerDistributionTable/CancerDistributionTable.relay.js
NCI-GDC/portal-ui
/* @flow */ import React from 'react'; import { graphql } from 'react-relay'; import { compose, withPropsOnChange } from 'recompose'; import { makeFilter, replaceFilters } from '@ncigdc/utils/filters'; import Query from '@ncigdc/modern_components/Query'; export default (Component: ReactClass<*>) => compose( withPropsOnChange(['filters'], ({ filters = null }) => { const cnvAvailableVariationDataFilter = { field: 'cases.available_variation_data', value: ['cnv'], }; const ssmAvailableVariationDataFilter = { field: 'cases.available_variation_data', value: ['ssm'], }; return { variables: { ssmTested: makeFilter([ssmAvailableVariationDataFilter]), cnvTested: makeFilter([cnvAvailableVariationDataFilter]), cnvGainFilter: replaceFilters( makeFilter([ cnvAvailableVariationDataFilter, { field: 'cnvs.cnv_change', value: ['Gain'], }, ]), filters, ), cnvLossFilter: replaceFilters( makeFilter([ cnvAvailableVariationDataFilter, { field: 'cnvs.cnv_change', value: ['Loss'], }, ]), filters, ), caseAggsFilter: replaceFilters( { op: 'and', content: [ { op: 'NOT', content: { field: 'cases.gene.ssm.observation.observation_id', value: 'MISSING', }, }, { op: 'in', content: ssmAvailableVariationDataFilter, }, ], }, filters, ), ssmCountsFilters: replaceFilters( makeFilter([ssmAvailableVariationDataFilter]), filters, ), }, }; }), )((props: Object) => { return ( <Query parentProps={props} minHeight={50} variables={props.variables} Component={Component} query={graphql` query CancerDistributionTable_relayQuery( $ssmTested: FiltersArgument $ssmCountsFilters: FiltersArgument $caseAggsFilter: FiltersArgument $cnvGainFilter: FiltersArgument $cnvLossFilter: FiltersArgument $cnvTested: FiltersArgument ) { viewer { explore { ssms { aggregations(filters: $ssmCountsFilters) { occurrence__case__project__project_id { buckets { key doc_count } } } } cases { filtered: aggregations(filters: $caseAggsFilter) { project__project_id { buckets { doc_count key } } } cnvGain: aggregations(filters: $cnvGainFilter) { project__project_id { buckets { doc_count key } } } cnvLoss: aggregations(filters: $cnvLossFilter) { project__project_id { buckets { doc_count key } } } cnvTotal: aggregations(filters: $cnvTested) { project__project_id { buckets { doc_count key } } } total: aggregations(filters: $ssmTested) { project__project_id { buckets { doc_count key } } } } } } } `} /> ); });
[2]. Demo_RN/[21]. tabBar_demo/index.ios.js
knightsj/RN_Demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TabBarIOS } from 'react-native'; var TabBarDemo = React.createClass({ // 设置初始值 getInitialState(){ return{ // 默认被选中的tabBarItem selectedTabBarItem: 'home' } }, render() { return ( <View style={styles.container}> {/*头部*/} <View style={styles.headerViewStyle}> <Text style={styles.navTitleStyle}>我是导航栏</Text> </View> {/*选项卡*/} <TabBarIOS barTintColor='white' tintColor = 'purple' > {/*homepage tab*/} <TabBarIOS.Item systemIcon="downloads" title="张三" badge="3" selected={this.state.selectedTabBarItem == 'home'} onPress = {()=>{this.setState({selectedTabBarItem: 'home'})}} > {/*中间这个view是属于这个tab的view*/} <View style={[styles.commonViewStyle,{backgroundColor:'red'}]}> <Text>home page</Text> </View> </TabBarIOS.Item> {/*bookmarks tab*/} <TabBarIOS.Item systemIcon="bookmarks" selected={this.state.selectedTabBarItem == 'second'} onPress = {()=>{this.setState({selectedTabBarItem: 'second'})}} > <View style={[styles.commonViewStyle,{backgroundColor:'green'}]}> <Text>bookmarks page</Text> </View> </TabBarIOS.Item> {/*dowloads tab*/} <TabBarIOS.Item systemIcon="downloads" badge="1" selected={this.state.selectedTabBarItem == 'three'} onPress = {()=>{this.setState({selectedTabBarItem: 'three'})}} > <View style={[styles.commonViewStyle,{backgroundColor:'blue'}]}> <Text>downloads page</Text> </View> </TabBarIOS.Item> {/*search tab*/} <TabBarIOS.Item systemIcon="search" selected={this.state.selectedTabBarItem == 'four'} onPress = {()=>{this.setState({selectedTabBarItem: 'four'})}} > <View style={[styles.commonViewStyle,{backgroundColor:'orange'}]}> <Text>search page</Text> </View> </TabBarIOS.Item> </TabBarIOS> </View> ); } }); const styles = StyleSheet.create({ container: { flex:1, backgroundColor: '#F5FCFF', }, headerViewStyle:{ height:64, backgroundColor:'white', justifyContent:'center', alignItems:'center', }, navTitleStyle:{ color:'blue' }, commonViewStyle:{ flex:1, justifyContent:'center', alignItems:'center' } }); AppRegistry.registerComponent('component_demo', () => TabBarDemo);
packages/recon-engine/src/parse/__tests__/__fixtures__/real-world-lystable/src.js
recon-js/recon
/* eslint-disable */ import React from 'react'; import PropTypes from 'utils/prop-types'; import {compose, withReducer, branch} from 'recompose'; import {identity} from 'lodash'; import {isRecruitmentManager} from 'utils/talent'; import {TALENT_REQUEST_STATES} from 'constants/talent'; import {TalentRequest, Agency, AgencyTalentRequest} from 'api/records'; import {createContainer, query as q} from 'api/recall'; import DateRange from 'moment-range'; import {PRIVACY_MODES} from 'constants/notes'; import {matchRecord} from 'utils/record'; import {Record} from 'immutable'; import withStaticProperties from 'decorators/with-static-properties'; import notFound from 'decorators/not-found'; import {Box, Flex} from 'components/layout'; import Paper from 'components/paper'; import LoadingSpinner from 'components/loading-spinner'; import SectionHeader from 'components/section-header'; import CardHeader from 'components/card-header'; import Link from 'components/link'; import Text from 'components/text'; import Icon from 'components/icon'; import CandidateList from 'components/candidate-list'; import MenuChecklist from 'components/menu-checklist'; import ContextualMenuButton from 'components/contextual-menu-button'; import MenuItemWithConfirm from 'components/menu-item-with-confirm'; import TalentRequestInformation from 'components/talent-request-information'; import NotesCard from 'components/notes-card'; import Avatar from 'components/avatar'; import Button from 'components/button'; import Modal from 'components/modal'; import TalentRequestForm from 'hera/components/talent-request-form'; import withViewer from 'decorators/with-viewer'; import withActions from 'decorators/with-actions'; import { updateTalentRequest, cancelTalentRequest, setFinalCandidate, removeCandidate, createAgencyTalentRequest, saveTalentRequest, } from 'actions/talent-request-actions'; // State export const State = new Record({ editing: false, }); // Actions const TOGGLE_EDIT_FORM = 'TOGGLE_EDIT_FORM'; const CLOSE_EDIT_FORM = 'CLOSE_EDIT_FORM'; export const reducer = (state, action) => { switch (action.type) { case TOGGLE_EDIT_FORM: return state.merge({editing: !state.editing}); case CLOSE_EDIT_FORM: return state.merge({editing: false}); default: return state; } }; // View /* Render talent reqiest updates */ export function UpdatesCard( { talentRequest, ...otherProps } ) { return ( <Box {...otherProps}> <CardHeader locked={true} title="Updates" justify="flex-start" /> <Paper padded={true}> <Flex flexDirection="column"> {!!talentRequest.final_candidate ? <Flex flexDirection="row" marginBottom={20}> <Flex marginRight={15}> <Avatar size="medium" record={talentRequest.final_candidate.supplier} /> </Flex> <Flex flexDirection="column"> <Text weight="semi-bold">Selected Candidate</Text> <Text>{talentRequest.final_candidate.supplier.name}</Text> </Flex> </Flex> : null} <Flex flexDirection="row" alignItems="center"> <Flex width="45px" marginRight={15} justifyContent="center"> <Text size="extra-large" weight="extra-light"> {talentRequest.candidates.size} </Text> </Flex> <Text weight="semi-bold">Candidates</Text> </Flex> </Flex> <Flex flexDirection="row" alignItems="center"> <Flex width="45px" marginRight={15} justifyContent="center"> <Text size="extra-large" weight="extra-light"> {talentRequest.agencies.size} </Text> </Flex> <Text weight="semi-bold">Agencies</Text> </Flex> </Paper> </Box> ); } export function AgencyChecklist( { talentRequest, agencies, onCreated, createAgencyTalentRequestAction, } ) { const items = agencies.map(agency => { // Check if the agency is already attached const existingAgency = talentRequest.agencies.find( _agency => !!_agency && matchRecord(agency, _agency) ); return { checked: !!existingAgency, label: agency.name, checkAction: () => { createAgencyTalentRequestAction( new AgencyTalentRequest({ talent_request: talentRequest, agency, }) ).then(() => { onCreated(); }); }, }; }); return ( <MenuChecklist items={items} placeholderContent="No agencies in this team" key={null} > <Box width={220}> Add to Talent Request </Box> </MenuChecklist> ); } const Z_INDEX = { MODAL: 200, }; /** * Display a talent request in detail */ export const TalentRequestsDetailPage = withStaticProperties({ propTypes: { talentRequest: PropTypes.record(TalentRequest), agencies: PropTypes.iterableOf(PropTypes.record(Agency)), recall: PropTypes.shape({ markAsStale: PropTypes.func, }).isRequired, queries: PropTypes.shape({ agencies: PropTypes.shape({ id: PropTypes.string, ready: PropTypes.bool, }), talentRequest: PropTypes.shape({ id: PropTypes.string, ready: PropTypes.bool, }), }).isRequired, viewer: PropTypes.viewer.isRequired, updateTalentRequest: PropTypes.func.isRequired, cancelTalentRequest: PropTypes.func.isRequired, setFinalCandidate: PropTypes.func.isRequired, removeCandidate: PropTypes.func.isRequired, createAgencyTalentRequest: PropTypes.func.isRequired, saveTalentRequest: PropTypes.func.isRequired, state: PropTypes.shape({ editing: PropTypes.bool.isRequired, }).isRequired, dispatch: PropTypes.func.isRequired, }, })(function TalentRequestsDetailPage(props) { const { talentRequest, agencies, queries, viewer, // withReducer state: {editing}, dispatch, } = props; const handleContainerRefresh = () => { props.recall.markAsStale([ props.queries.agencies.id, props.queries.talentRequest.id, ]); }; const fire = action => () => dispatch(action); const status = !!talentRequest ? TALENT_REQUEST_STATES[talentRequest.status] : null; const searchRange = !!talentRequest && !!talentRequest.start_date && !!talentRequest.end_date ? new DateRange(talentRequest.start_date, talentRequest.end_date) : null; const heading = ( <div> {isRecruitmentManager(viewer) ? <Link to="@requests"> Talent Requests </Link> : <Link to="@myrequests"> My Requests </Link>} <Icon>chevron_right</Icon> {!!talentRequest ? talentRequest.job_title : 'Loading'} </div> ); const menu = ( <ContextualMenuButton iconColor="grey" origin="top right"> <AgencyChecklist talentRequest={talentRequest} agencies={agencies} createAgencyTalentRequestAction={props.createAgencyTalentRequest} onCreated={handleContainerRefresh} /> <MenuItemWithConfirm icon="remove_circle_outline" confirm="Are you sure?" onClick={() => props.cancelTalentRequest(talentRequest)} key="cancel" > Cancel Request </MenuItemWithConfirm> </ContextualMenuButton> ); const editTalentRequest = [ <Button key={0} square={true} icon="edit" theme="light" size="small" onClick={fire({type: TOGGLE_EDIT_FORM})} />, <Modal key={1} open={editing} onCloseRequest={fire({type: CLOSE_EDIT_FORM})} zIndex={Z_INDEX.MODAL} > <TalentRequestForm saveTalentRequest={props.saveTalentRequest} exitForm={fire({type: CLOSE_EDIT_FORM})} team={viewer.team} baseZIndex={Z_INDEX.MODAL} talentRequest={talentRequest} /> </Modal>, ]; return ( <Box margin="50px auto 20px" maxWidth={1180} width="100%"> {queries.talentRequest.ready ? <div> <SectionHeader marginBottom={20} heading={heading} /> <Flex flexDirection="row"> <Flex flex={2} flexDirection="column" marginRight={20}> <CardHeader locked={true} title="Request Details" justify="flex-start" primaryActions={ status !== TALENT_REQUEST_STATES.cancelled && status !== TALENT_REQUEST_STATES.placed ? editTalentRequest : undefined } /> <Paper padded={true}> <TalentRequestInformation talentRequest={talentRequest} menu={menu} /> </Paper> </Flex> <Flex flex={1} flexDirection="column" marginLeft={20}> <UpdatesCard talentRequest={talentRequest} marginBottom={30} /> <NotesCard title="Hiring Notes" parent={talentRequest} privacyMode={PRIVACY_MODES.PRIVATE} /> </Flex> </Flex> <Flex marginTop={40} flexDirection="column"> <SectionHeader icon="lock" marginBottom={20} heading="Candidates" /> <CandidateList finalCandidate={talentRequest.final_candidate} candidates={talentRequest.candidates} team={viewer.team} searchRange={searchRange} setFinalCandidate={props.setFinalCandidate} removeCandidate={props.removeCandidate} viewer={viewer} /> </Flex> </div> : <LoadingSpinner size="medium" />} </Box> ); }); const candidateFragment = { id: true, removed_at: true, removed_by: { id: true, }, talent_request: { id: true, }, supplier: { id: true, name: true, email: true, city: true, next_available: true, show_availability: true, supplier_type: true, picture: { id: true, type: true, remote_id: true, filename: true, url: true, }, profile: { id: true, contact_email: true, accepted: true, invited_by: { id: true, name: true, }, created_at: true, created_by: { id: true, name: true, }, approved_at: true, contact_name: true, team: { id: true, }, agency: { id: true, name: true, contact_name: true, email: true, }, }, }, }; export const container = createContainer({ queries: { agencies: q.many(Agency, { params: () => ({ filter: { archived: false, }, }), fields: { name: true, contact_name: true, }, }), talentRequest: q.single(TalentRequest, { params: vars => ({ id: vars.params.requestId, }), fields: { id: true, created_at: true, status: true, submitted_by: { id: true, name: true, picture: { id: true, type: true, remote_id: true, filename: true, url: true, }, }, job_title: true, job_description: true, position_type: true, start_date: true, end_date: true, location: true, team_name: true, urgency: true, skills: { edges: { id: true, type: true, name: true, }, }, final_candidate: { ...candidateFragment, }, candidates: { edges: { ...candidateFragment, }, }, agencies: { edges: { id: true, name: true, contact_name: true, email: true, }, }, }, }), }, }); const talentRequestOrNotFound = branch( ({queries, talentRequest}) => !queries.talentRequest.ready || !!talentRequest, identity, notFound() ); export default compose( withViewer(), withActions({ updateTalentRequest, cancelTalentRequest, setFinalCandidate, removeCandidate, createAgencyTalentRequest, saveTalentRequest, }), container, talentRequestOrNotFound, withReducer('state', 'dispatch', reducer, new State()) )(TalentRequestsDetailPage);
app/javascript/mastodon/components/status_content.js
corzntin/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import escapeTextContentForBrowser from 'escape-html'; import PropTypes from 'prop-types'; import emojify from '../emoji'; import { isRtl } from '../rtl'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, '').toLowerCase(); if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) { return; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const content = { __html: emojify(status.get('content')) }; const spoilerContent = { __html: emojify(escapeTextContentForBrowser(status.get('spoiler_text', ''))) }; const directionStyle = { direction: 'ltr' }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, }); if (isRtl(status.get('search_index'))) { directionStyle.direction = 'rtl'; } if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' aria-label={status.get('search_index')} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} /> {' '} <button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden && 0} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} /> </div> ); } else if (this.props.onClick) { return ( <div ref={this.setRef} tabIndex='0' aria-label={status.get('search_index')} className={classNames} style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} dangerouslySetInnerHTML={content} /> ); } else { return ( <div tabIndex='0' aria-label={status.get('search_index')} ref={this.setRef} className='status__content' style={directionStyle} dangerouslySetInnerHTML={content} /> ); } } }
example/src/screens/NavigationTypes.js
eeynard/react-native-navigation
import React from 'react'; import {StyleSheet, ScrollView} from 'react-native'; import Row from '../components/Row'; class NavigationTypes extends React.Component { constructor(props) { super(props); this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this)); } onNavigatorEvent(event) { if (event.type === 'DeepLink') { const parts = event.link.split('/'); if (parts[0] === 'tab1') { this.props.navigator.push({ screen: parts[1] }); } } } toggleDrawer = () => { this.props.navigator.toggleDrawer({ side: 'left', animated: true }); }; pushScreen = () => { this.props.navigator.push({ screen: 'example.Types.Push', title: 'New Screen', }); }; pushListScreen = () => { console.log('RANG', 'pushListScreen'); this.props.navigator.push({ screen: 'example.Types.ListScreen', title: 'List Screen', }); }; pushCustomTopBarScreen = () => { this.props.navigator.push({ screen: 'example.Types.CustomTopBarScreen' }); }; pushCustomButtonScreen = () => { this.props.navigator.push({ screen: 'example.Types.CustomButtonScreen', title: 'Custom Buttons' }); }; pushTopTabsScreen = () => { this.props.navigator.push({ screen: 'example.Types.TopTabs', title: 'Top Tabs', topTabs: [{ screenId: 'example.Types.TopTabs.TabOne', title: 'Tab One', }, { screenId: 'example.Types.TopTabs.TabTwo', title: 'Tab Two', }], }); }; showModal = () => { this.props.navigator.showModal({ screen: 'example.Types.Modal', title: 'Modal', }); }; showLightBox = () => { this.props.navigator.showLightBox({ screen: "example.Types.LightBox", passProps: { title: 'LightBox', content: 'Hey there, I\'m a light box screen :D', onClose: this.dismissLightBox, }, style: { backgroundBlur: 'dark', backgroundColor: 'rgba(0, 0, 0, 0.7)', tapBackgroundToDismiss: true } }); }; dismissLightBox = () => { this.props.navigator.dismissLightBox(); }; showInAppNotification = () => { this.props.navigator.showInAppNotification({ screen: 'example.Types.Notification', }); }; render() { return ( <ScrollView style={styles.container}> <Row title={'Toggle Drawer'} onPress={this.toggleDrawer}/> <Row title={'Push Screen'} testID={'pushScreen'} onPress={this.pushScreen}/> {/*<Row title={'Push List Screen'} testID={'pushListScreen'} onPress={this.pushListScreen}/>*/} <Row title={'Custom TopBar'} onPress={this.pushCustomTopBarScreen}/> <Row title={'Custom Button'} onPress={this.pushCustomButtonScreen}/> <Row title={'Top Tabs Screen'} onPress={this.pushTopTabsScreen} platform={'android'}/> <Row title={'Show Modal'} onPress={this.showModal}/> <Row title={'Show Lightbox'} onPress={this.showLightBox}/> <Row title={'Show In-App Notification'} onPress={this.showInAppNotification}/> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, row: { height: 48, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'rgba(0, 0, 0, 0.054)', }, text: { fontSize: 16, }, }); export default NavigationTypes;
demo/src/components/navigators/layout-toptap-navigator.js
tuantle/hypertoxin
'use strict'; // eslint-disable-line import { Ht } from 'hypertoxin'; import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import { createMaterialTopTabNavigator } from 'react-navigation'; import RowLayoutView from '../layout-views/row-layout-view'; import ColumnLayoutView from '../layout-views/column-layout-view'; import DefaultTheme from '../../themes/default-theme'; const { Dimensions } = ReactNative; const { BodyScreen, HeaderScreen, FlatButton, IconImage } = Ht; const DEVICE_WIDTH = Dimensions.get(`window`).width; const LayoutTopTabNavigator = createMaterialTopTabNavigator({ rowLayout: { screen: ({ screenProps }) => { const { component } = screenProps; const { Theme, shade } = component.state; return ( <RowLayoutView Theme = { Theme } shade = { shade } /> ); }, navigationOptions: () => { return { tabBarVisible: true, tabBarLabel: `ROW LAYOUT` }; } }, columnLayout: { screen: ({ screenProps }) => { const { component } = screenProps; const { Theme, shade } = component.state; return ( <ColumnLayoutView Theme = { Theme } shade = { shade } /> ); }, navigationOptions: () => { return { tabBarVisible: true, tabBarLabel: `COLUMN LAYOUT` }; } } }, { swipeEnabled: true, animationEnabled: true, lazy: true, initialRouteName: `rowLayout`, tabBarPosition: `top`, tabBarOptions: { scrollEnabled: true, activeTintColor: DefaultTheme.color.palette.red, inactiveTintColor: DefaultTheme.color.palette.blue, activeBackgroundColor: `transparent`, inactiveBackgroundColor: `transparent`, labelStyle: { ...DefaultTheme.font.smaller, flexWrap: `nowrap` }, tabStyle: { justifyContent: `center`, alignItems: `center`, width: DEVICE_WIDTH / 2 }, indicatorStyle: { borderBottomColor: DefaultTheme.color.palette.red, borderBottomWidth: 2 }, style: { flexShrink: 1, flexDirection: `column`, justifyContent: `flex-start`, alignItems: `flex-start`, width: DEVICE_WIDTH, height: 50, backgroundColor: `transparent` } } }); export default class LayoutTopTabNavigatorWrapper extends React.Component { static router = LayoutTopTabNavigator.router; constructor (props) { super(props); } render () { const component = this; const { navigation, screenProps } = component.props; const { shade } = screenProps.component.state; return ([ <HeaderScreen key = 'header-screen' shade = { shade } label = 'LAYOUTS' > <FlatButton room = 'content-left' overlay = 'transparent' corner = 'circular' onPress = {() => navigation.toggleDrawer()} > <IconImage room = 'content-middle' source = 'menu' /> </FlatButton> </HeaderScreen>, <BodyScreen key = 'body-screen' shade = { shade } style = {{ container: { paddingTop: 90 } }} > <LayoutTopTabNavigator key = 'text-top-tab-navigator' room = 'content-top' { ...component.props } /> </BodyScreen> ]); } }
src/mui/form/FormField.js
RestUI/rest-ui
import React from 'react'; import { Field } from 'redux-form'; import Labeled from '../input/Labeled'; const FormField = ({ input, ...rest }) => input.props.addField ? (input.props.addLabel ? <Field {...rest} {...input.props} name={input.props.source} component={Labeled} label={input.props.label}>{ input }</Field> : <Field {...rest} {...input.props} name={input.props.source} component={input.type} /> ) : (input.props.addLabel ? <Labeled {...rest} label={input.props.label} source={input.props.source}>{input}</Labeled> : (typeof input.type === 'string' ? input : React.cloneElement(input, rest) ) ); export default FormField;
resources/apps/frontend/src/components/Form/Select/LoginTypeSelect.js
johndavedecano/PHPLaravelGymManagementSystem
import React from 'react'; import Select from 'react-select'; const options = [ { value: 'login', label: 'Login', }, { value: 'logout', label: 'Logout', }, ]; export default props => { return ( <Select options={options} {...props} defaultValue={options.find(option => option.value === props.defaultValue)} value={options.find(option => option.value === props.value)} getOptionLabel={option => option.label} getOptionValue={option => option.value} /> ); };
examples/universal/client.js
taylorhakes/redux
import 'babel-core/polyfill'; import React from 'react'; import configureStore from './store/configureStore'; import { Provider } from 'react-redux'; import App from './containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
src/scene/Ceshi/index.js
Mrlyjoutlook/cnode-native
import React, { Component } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import Modal from 'react-native-modalbox'; const styles = StyleSheet.create({ wrapper: { paddingTop: 50, flex: 1 }, modal: { justifyContent: 'center', alignItems: 'center' }, modal2: { height: 230, backgroundColor: "#3B5998" }, modal3: { height: 300, width: 300 }, modal4: { height: 300 }, btn: { margin: 10, backgroundColor: "#3B5998", color: "white", padding: 10 }, btnModal: { position: "absolute", top: 0, right: 0, width: 50, height: 50, backgroundColor: "transparent" }, text: { color: "black", fontSize: 22 } }); class Ceshi extends Component { static navigationOptions = { header: null } state = { } render() { return ( <View style={styles.wrapper}> <Modal isOpen={true} style={[styles.modal, styles.modal1]} ref={"modal1"} swipeToClose={true} onClosed={()=>{}} onOpened={()=>{}} onClosingState={()=>{}}> <Text style={styles.text}>Basic modal</Text> </Modal> </View> ); } } export default Ceshi;
src/components/pagination/number-link.js
adrienlozano/stephaniewebsite
import React from 'react'; import Link from "~/components/link"; import styled, { css } from "styled-components"; import { darken } from "polished"; const disabledCss = css` cursor:default; pointer-events: none; background-color: ${ ({theme}) => darken(0.1, theme.colors.light)}; ` export default styled(Link).attrs({ activeClassName : props => props.activeClassName || "active", exact: props => props.exact || true, disabled: props => props.disabled || false })` background-color: ${ ({theme}) => darken(0.4, theme.colors.light) }; text-decoration:none !important; &:hover{ background-color: ${({theme}) => theme.colors.secondaryAccent }; } margin: 0 5px 30px; border-radius: 3px; line-height: 25px; height:25px; width: 20px; color: #FFF; padding: 3px 6px; &.active{ background-color: ${ ({theme}) => theme.colors.primaryAccent }; cursor:default; } ${ ({disabled}) => disabled ? disabledCss : null }; `
client/src/Components/DownloadableResumeGenerator.js
teamcrux/EmploymentOptions
//import React, { Component } from 'react'; //const moment = require('moment'); export default function createDownloadableResume (data) { console.log("HELLO") fetch(`/api/pdf`, { headers: { 'Accept': 'application/pdf', 'Content-Type': 'application/pdf', 'Authorization': 'JWT '+localStorage.getItem("token") }, method: 'GET' }) .then((response) => response.json()) .then((responseJson) => { //console.log(responseJson); }); }
backend/routes/react-server.js
moyuyc/isomorphic-blog
/** * Created by moyu on 2017/2/8. */ import express from 'express' import path from 'path' import fs from 'fs' import url from 'url' import React from 'react'; import {renderToString} from 'react-dom/server' // import createMemoryHistory from 'history/createMemoryHistory' import reactRouter, {match, RouterContext} from 'react-router' import {Provider} from 'react-redux' import DocumentTitle from 'react-document-title' import DocumentMeta from 'react-document-meta' import {pathUpdateEntry, fetchConfig} from '../../frontend/src/reducers/actions' import {initState} from '../../frontend/src/reducers/appReducers' import {routerForSiteMap, routes} from '../../frontend/src/router' import {configureStore} from '../../frontend/src/main' const server = express(); import {fePath, spacePath} from '../server' server.use(handleRender); // This is fired every time the server side receives a request function handleRender(req, res, next) { // console.log(req.url, req.originalUrl); match({ routes: routes, location: req.url }, function(error, redirectLocation, renderProps) { if (error) { res.status(500).send(error.stack); } else if (redirectLocation) { const pathname = decodeURIComponent(url.parse(req.originalUrl).pathname) if( fs.existsSync(path.join(fePath, pathname)) || fs.existsSync(path.join(spacePath, pathname)) ) { next(); } else { res.redirect(302, redirectLocation.pathname + redirectLocation.search); } } else if (renderProps) { var store = configureStore(initState); // we can invoke some async operation(eg. fetchAction or getDataFromDatabase) // call store.dispatch(Action(data)) to update state. // console.log('renderProps', renderProps) store.dispatch(fetchConfig()).then(f => store.dispatch(pathUpdateEntry(renderProps.location.pathname, renderProps.params))) .then(() => res.renderStore(store, renderProps)) } else { res.status(404).send('Not found') } }) } express.response.renderStore = function (store, renderProps) { const html = renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); const title = DocumentTitle.rewind(); const meta = DocumentMeta.renderAsHTML(); this.header('content-type', 'text/html; charset=utf-8') this.send(renderFullPage(title, html, store.getState(), meta)) } const htmlPath = path.join(fePath, 'index.html'); var html = fs.readFileSync(htmlPath).toString(); fs.watch(htmlPath, () => { console.log('html changed') html = fs.readFileSync(htmlPath).toString(); }) function renderFullPage(title, partHtml, initialState, headerInsertHTML) { // <!--HTML--> var allHtml = html; if (initialState) { allHtml = allHtml.replace(/\/\*\s*?INITIAL_STATE\s*?\*\//, `window.__INITIAL_STATE__=${JSON.stringify(initialState)}`) } if (title) { allHtml = allHtml.replace(/<title>[\s\S]*?<\/title>/, `<title>${title}</title>`); } if (headerInsertHTML) { allHtml = allHtml.replace(/<!--\s*?HEAD_INSERT\s*?-->/, headerInsertHTML); } return allHtml.replace(/<!--\s*?HTML\s*?-->/, partHtml); } export default server;
src/trials-layout.js
buildkite/trial-pipeline-visualizer
import React from 'react'; import PropTypes from 'prop-types'; import Trial from './trial'; import colors from './colors'; import 'babel-polyfill'; class TrialsLayout extends React.Component { static propTypes = { accountsUrl: PropTypes.string.isRequired, pollSeconds: PropTypes.number.isRequired }; constructor(props) { super(props); this.state = { accounts: [], fetched: false }; } componentWillMount() { this.fetchStats(); this.fetchInterval = setInterval((() => this.fetchStats()), this.props.pollSeconds * 1000); } componentWillUnmount() { clearInterval(this.fetchInterval); } fetchStats() { fetch(this.props.accountsUrl).then((response) => { response.json().then((json) => { this.setState({ // Filter out accounts that haven't done anything accounts: json.accounts.filter((a) => a.agents_count > 0), fetched: true }); }) }) } render() { return ( <div className="TrialsLayout"> <h1 className="TrialsLayout"> {this._heading()} </h1> <div className="Trials__legend"> <p style={{color: colors.agents}}><span className="Trials__legend-dot" style={{backgroundColor: colors.agents}}></span> Connected an Agent</p> <p style={{color: colors.builds}}><span className="Trials__legend-dot" style={{backgroundColor: colors.builds}}></span> Ran a Passing Build</p> <p style={{color: colors.members}}><span className="Trials__legend-dot" style={{backgroundColor: colors.members}}></span> Invited a Team Member</p> </div> <div className="Trials"> {this.state.accounts.map(function(account) { return <Trial key={account.slug} trial={account} /> })} </div> </div> ) } _heading() { if (this.state.fetched) { return ( <span> {`${this._trialCount()} Trialling`} <span style={{ color:'#666' }}>{" / "}</span> {`${this._upgradeCount()} Upgraded`} <span style={{ color:'#666' }}>{" / "}</span> {`${this._expiredCount()} Expired`} </span> ) } else { return ( <span>Loading…</span> ) } } _trialCount() { return this.state.accounts.filter((a) => a.state == "trial").length } _upgradeCount() { return this.state.accounts.filter((a) => a.state == "active").length } _expiredCount() { return this.state.accounts.filter((a) => a.state == "trial_expired").length } }; export default TrialsLayout;
examples/counter/src/main.js
PhilipGarnero/react-redux-reliever
import 'babel-polyfill' import React from 'react' import {render} from 'react-dom' import {Provider} from 'react-redux' import {createStore, applyMiddleware} from 'redux' import {createLogger} from 'redux-logger' import RelieverRegistry from 'react-redux-reliever' import RxRelieverPlugin from 'react-redux-reliever/plugins/rx' import SagaRelieverPlugin from 'react-redux-reliever/plugins/saga' import CounterReliever from './relievers/CounterReliever' import Counter from './components/Counter' RelieverRegistry.use(RxRelieverPlugin) RelieverRegistry.use(SagaRelieverPlugin) RelieverRegistry.register(CounterReliever, 'counter') const logger = createLogger() const store = createStore(RelieverRegistry.buildRootReducer(), applyMiddleware(...RelieverRegistry.middlewares(), logger)) RelieverRegistry.setupStore(store) render( <Provider store={store}> <Counter /> </Provider>, document.getElementById('root') )
app/App.js
krisburtoft/contacts-keeper
import React from 'react'; import styles from './App.css'; export default class App extends React.Component { constructor(props) { super(props); this.state = {test: 'foo'}; } render() { return ( <div> <div className={styles.app}> < </div> } }
src/app/component/provider-image/provider-image.js
all3dp/printing-engine-client
import PropTypes from 'prop-types' import React from 'react' import propTypes from '../../prop-types' import cn from '../../lib/class-names' const ProviderImage = ({ classNames, src, alt, size = 'default', inline = false, minor = false, onClick = null }) => React.createElement( onClick ? 'a' : 'div', { className: cn('ProviderImage', {inline, minor, link: !!onClick, [size]: true}, classNames), onClick, href: onClick && '#' }, <img className="ProviderImage__image" alt={alt} src={src} /> ) ProviderImage.propTypes = { ...propTypes.component, src: PropTypes.string.isRequired, alt: PropTypes.string, inline: PropTypes.bool, minor: PropTypes.bool, onClick: PropTypes.func, size: PropTypes.oneOf(['default', 's']) } export default ProviderImage
node_modules/react-bootstrap/es/Glyphicon.js
WatkinsSoftwareDevelopment/HowardsBarberShop
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 { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An icon name. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: React.PropTypes.string.isRequired }; var Glyphicon = function (_React$Component) { _inherits(Glyphicon, _React$Component); function Glyphicon() { _classCallCheck(this, Glyphicon); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Glyphicon.prototype.render = function render() { var _extends2; var _props = this.props, glyph = _props.glyph, className = _props.className, props = _objectWithoutProperties(_props, ['glyph', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, glyph)] = true, _extends2)); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Glyphicon; }(React.Component); Glyphicon.propTypes = propTypes; export default bsClass('glyphicon', Glyphicon);
src/svg-icons/content/reply-all.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentReplyAll = (props) => ( <SvgIcon {...props}> <path d="M7 8V5l-7 7 7 7v-3l-4-4 4-4zm6 1V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/> </SvgIcon> ); ContentReplyAll = pure(ContentReplyAll); ContentReplyAll.displayName = 'ContentReplyAll'; ContentReplyAll.muiName = 'SvgIcon'; export default ContentReplyAll;
local-cli/generator/templates/index.android.js
catalinmiron/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class <%= name %> extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
docs/app/Examples/elements/Segment/States/SegmentExampleDisabled.js
ben174/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleDisabled = () => ( <Segment disabled> Disabled content </Segment> ) export default SegmentExampleDisabled
src/components.js
ieugen/tcomb-form
'use strict'; import React from 'react'; import t from 'tcomb-validation'; import { compile } from 'uvdom/react'; import { humanize, merge, getTypeInfo, getOptionsOfEnum, move, UIDGenerator } from './util'; import classnames from 'classnames'; const Nil = t.Nil; const assert = t.assert; const SOURCE = 'tcomb-form'; const noobj = Object.freeze({}); const noarr = Object.freeze([]); const noop = () => {}; export function getComponent(type, options) { if (options.factory) { return options.factory; } const name = t.getTypeName(type); switch (type.meta.kind) { case 'irreducible' : return ( type === t.Bool ? Checkbox : type === t.Dat ? Datetime : Textbox ); case 'struct' : return Struct; case 'list' : return List; case 'enums' : return Select; case 'maybe' : case 'subtype' : return getComponent(type.meta.type, options); default : t.fail(`[${SOURCE}] unsupported type ${name}`); } } function sortByText(a, b) { return ( a.text < b.text ? -1 : a.text > b.text ? 1 : 0 ); } function getComparator(order) { return { asc: sortByText, desc: (a, b) => -sortByText(a, b) }[order]; } export const decorators = { template(name) { return (Component) => { Component.prototype.getTemplate = function getTemplate() { return this.props.options.template || this.props.ctx.templates[name]; }; }; }, attrs(Component) { Component.prototype.getAttrs = function getAttrs() { const attrs = t.mixin({}, this.props.options.attrs); attrs.id = this.getId(); attrs.name = this.getName(); if (attrs.className) { attrs.className = { [classnames(attrs.className)]: true }; } return attrs; }; }, placeholder(Component) { Component.prototype.getPlaceholder = function getPlaceholder() { const attrs = this.props.options.attrs || noobj; let placeholder = attrs.placeholder; if (Nil.is(placeholder) && this.getAuto() === 'placeholders') { placeholder = this.getDefaultLabel(); } return placeholder; }; }, templates(Component) { Component.prototype.getTemplates = function getTemplates() { return merge(this.props.ctx.templates, this.props.options.templates); }; } }; export class Component extends React.Component { static transformer = { format: value => Nil.is(value) ? null : value, parse: value => value }; constructor(props) { super(props); this.typeInfo = getTypeInfo(props.type); this.state = { hasError: false, value: this.getTransformer().format(props.value) }; } getTransformer() { return this.props.options.transformer || this.constructor.transformer; } shouldComponentUpdate(nextProps, nextState) { const should = ( nextState.value !== this.state.value || nextState.hasError !== this.state.hasError || nextProps.options !== this.props.options || nextProps.type !== this.props.type ); return should; } componentWillReceiveProps(props) { if (props.type !== this.props.type) { this.typeInfo = getTypeInfo(props.type); } this.setState({value: this.getTransformer().format(props.value)}); } onChange(value) { this.setState({value}, () => { this.props.onChange(value, this.props.ctx.path); }); } getValidationOptions() { return { path: this.props.ctx.path, context: this.props.context || this.props.ctx.context }; } validate() { const value = this.getTransformer().parse(this.state.value); const result = t.validate(value, this.props.type, this.getValidationOptions()); this.setState({hasError: !result.isValid()}); return result; } getAuto() { return this.props.options.auto || this.props.ctx.auto; } getI18n() { return this.props.options.i18n || this.props.ctx.i18n; } getDefaultLabel() { const ctx = this.props.ctx; if (ctx.label) { return ctx.label + (this.typeInfo.isMaybe ? this.getI18n().optional : this.getI18n().required); } } getLabel() { const ctx = this.props.ctx; const legend = this.props.options.legend; let label = this.props.options.label; label = label || legend; if (Nil.is(label) && ctx.auto === 'labels') { label = this.getDefaultLabel(); } return label; } getError() { const error = this.props.options.error || this.props.type.getValidationErrorMessage; if (t.Func.is(error)) { const validationContext = this.getValidationOptions(); return error(this.state.value, validationContext.path, validationContext.context); } return error; } hasError() { return this.props.options.hasError || this.state.hasError; } getConfig() { return merge(this.props.ctx.config, this.props.options.config); } getId() { const attrs = this.props.options.attrs || noobj; if (attrs.id) { return attrs.id; } if (!this.uid) { this.uid = this.props.ctx.uidGenerator.next(); } return this.uid; } getName() { return this.props.options.name || this.props.ctx.name || this.getId(); } getLocals() { const options = this.props.options; const value = this.state.value; return { path: this.props.ctx.path, error: this.getError(), hasError: this.hasError(), label: this.getLabel(), onChange: this.onChange.bind(this), config: this.getConfig(), value, disabled: options.disabled, help: options.help }; } render() { const locals = this.getLocals(); // getTemplate is the only required implementation when extending Component assert(t.Func.is(this.getTemplate), `[${SOURCE}] missing getTemplate method of component ${this.constructor.name}`); const template = this.getTemplate(); return compile(template(locals)); } } function toNull(value) { return (t.Str.is(value) && value.trim() === '') || Nil.is(value) ? null : value; } function parseNumber(value) { var n = parseFloat(value); var isNumeric = (value - n + 1) >= 0; return isNumeric ? n : toNull(value); } @decorators.attrs @decorators.placeholder @decorators.template('textbox') export class Textbox extends Component { static transformer = { format: value => Nil.is(value) ? null : value, parse: toNull }; static numberTransformer = { format: value => Nil.is(value) ? null : String(value), parse: parseNumber }; getTransformer() { const options = this.props.options; return options.transformer ? options.transformer : this.typeInfo.innerType === t.Num ? Textbox.numberTransformer : Textbox.transformer; } getLocals() { const locals = super.getLocals(); locals.attrs = this.getAttrs(); locals.attrs.placeholder = this.getPlaceholder(); locals.type = this.props.options.type || 'text'; return locals; } } @decorators.attrs @decorators.template('checkbox') export class Checkbox extends Component { static transformer = { format: value => Nil.is(value) ? false : value, parse: value => value }; getLocals() { const locals = super.getLocals(); locals.attrs = this.getAttrs(); // checkboxes must always have a label locals.label = locals.label || this.getDefaultLabel(); return locals; } } @decorators.attrs @decorators.template('select') export class Select extends Component { static transformer = (nullOption) => { return { format: value => Nil.is(value) && nullOption ? nullOption.value : value, parse: value => nullOption && nullOption.value === value ? null : value }; }; static multipleTransformer = { format: value => Nil.is(value) ? noarr : value, parse: value => value }; getTransformer() { const options = this.props.options; if (options.transformer) { return options.transformer; } if (this.isMultiple()) { return Select.multipleTransformer; } return Select.transformer(this.getNullOption()); } getNullOption() { return this.props.options.nullOption || {value: '', text: '-'}; } isMultiple() { return this.typeInfo.innerType.meta.kind === 'list'; } getEnum() { return this.isMultiple() ? getTypeInfo(this.typeInfo.innerType.meta.type).innerType : this.typeInfo.innerType; } getOptions() { const options = this.props.options; const items = options.options ? options.options.slice() : getOptionsOfEnum(this.getEnum()); if (options.order) { items.sort(getComparator(options.order)); } const nullOption = this.getNullOption(); if (!this.isMultiple() && options.nullOption !== false) { items.unshift(nullOption); } return items; } getLocals() { const locals = super.getLocals(); locals.attrs = this.getAttrs(); locals.options = this.getOptions(); locals.isMultiple = this.isMultiple(); return locals; } } @decorators.attrs @decorators.template('radio') export class Radio extends Component { getOptions() { const options = this.props.options; const items = options.options ? options.options.slice() : getOptionsOfEnum(this.typeInfo.innerType); if (options.order) { items.sort(getComparator(options.order)); } return items; } getLocals() { const locals = super.getLocals(); locals.attrs = this.getAttrs(); locals.options = this.getOptions(); return locals; } } @decorators.attrs @decorators.template('date') export class Datetime extends Component { static transformer = { format: (value) => { return t.Arr.is(value) ? value : t.Dat.is(value) ? [value.getFullYear(), value.getMonth(), value.getDate()].map(String) : [null, null, null]; }, parse: (value) => { value = value.map(parseNumber); return value.every(t.Num.is) ? new Date(value[0], value[1], value[2]) : value.every(Nil.is) ? null : value; } }; getOrder() { return this.props.options.order || ['M', 'D', 'YY']; } getLocals() { const locals = super.getLocals(); locals.attrs = this.getAttrs(); locals.order = this.getOrder(); return locals; } } @decorators.templates export class Struct extends Component { static transformer = { format: value => Nil.is(value) ? noobj : value, parse: value => value }; validate() { let value = {}; let errors = []; let hasError = false; let result; for (let ref in this.refs) { if (this.refs.hasOwnProperty(ref)) { result = this.refs[ref].validate(); errors = errors.concat(result.errors); value[ref] = result.value; } } if (errors.length === 0) { const InnerType = this.typeInfo.innerType; value = new InnerType(value); if (this.typeInfo.isSubtype && errors.length === 0) { result = t.validate(value, this.props.type, this.getValidationOptions()); hasError = !result.isValid(); errors = errors.concat(result.errors); } } this.setState({hasError: hasError}); return new t.ValidationResult({errors, value}); } onChange(fieldName, fieldValue, path, kind) { const value = t.mixin({}, this.state.value); value[fieldName] = fieldValue; this.state.value = value; this.props.onChange(value, path, kind); } getTemplate() { return this.props.options.template || this.getTemplates().struct; } getTypeProps() { return this.typeInfo.innerType.meta.props; } getOrder() { return this.props.options.order || Object.keys(this.getTypeProps()); } getInputs() { const { options, ctx } = this.props; const props = this.getTypeProps(); const auto = this.getAuto(); const i18n = this.getI18n(); const config = this.getConfig(); const templates = this.getTemplates(); const value = this.state.value; const inputs = {}; for (let prop in props) { if (props.hasOwnProperty(prop)) { const propType = props[prop]; const propOptions = options.fields && options.fields[prop] ? options.fields[prop] : noobj; inputs[prop] = React.createElement(getComponent(propType, propOptions), { key: prop, ref: prop, type: propType, options: propOptions, value: value[prop], onChange: this.onChange.bind(this, prop), ctx: { context: ctx.context, uidGenerator: ctx.uidGenerator, auto, config, name: ctx.name ? `${ctx.name}[${prop}]` : prop, label: humanize(prop), i18n, templates, path: ctx.path.concat(prop) } }); } } return inputs; } getLocals() { const options = this.props.options; const locals = super.getLocals(); locals.order = this.getOrder(); locals.inputs = this.getInputs(); locals.className = options.className; return locals; } } function toSameLength(value, keys, uidGenerator) { if (value.length === keys.length) { return keys; } const ret = []; for (let i = 0, len = value.length; i < len; i++ ) { ret[i] = keys[i] || uidGenerator.next(); } return ret; } @decorators.templates export class List extends Component { static transformer = { format: value => Nil.is(value) ? noarr : value, parse: value => value }; constructor(props) { super(props); this.state.keys = this.state.value.map(() => props.ctx.uidGenerator.next()); } componentWillReceiveProps(props) { if (props.type !== this.props.type) { this.typeInfo = getTypeInfo(props.type); } const value = this.getTransformer().format(props.value); this.setState({ value, keys: toSameLength(value, this.state.keys, props.ctx.uidGenerator) }); } validate() { const value = []; let errors = []; let hasError = false; let result; for (let i = 0, len = this.state.value.length; i < len; i++ ) { result = this.refs[i].validate(); errors = errors.concat(result.errors); value.push(result.value); } // handle subtype if (this.typeInfo.isSubtype && errors.length === 0) { result = t.validate(value, this.props.type, this.getValidationOptions()); hasError = !result.isValid(); errors = errors.concat(result.errors); } this.setState({hasError: hasError}); return new t.ValidationResult({errors: errors, value: value}); } onChange(value, keys, path, kind) { keys = toSameLength(value, keys, this.props.ctx.uidGenerator); if (!kind) { // optimise re-rendering this.state.value = value; this.state.keys = keys; this.props.onChange(value, path, kind); } else { this.setState({value, keys}, () => { this.props.onChange(value, path, kind); }); } } addItem(evt) { evt.preventDefault(); const value = this.state.value.concat(undefined); const keys = this.state.keys.concat(this.props.ctx.uidGenerator.next()); this.onChange(value, keys, this.props.ctx.path.concat(value.length - 1), 'add'); } onItemChange(itemIndex, itemValue, path) { const value = this.state.value.slice(); value[itemIndex] = itemValue; this.onChange(value, this.state.keys, path); } removeItem(i, evt) { evt.preventDefault(); const value = this.state.value.slice(); value.splice(i, 1); const keys = this.state.keys.slice(); keys.splice(i, 1); this.onChange(value, keys, this.props.ctx.path.concat(i), 'remove'); } moveUpItem(i, evt) { evt.preventDefault(); if (i > 0) { this.onChange( move(this.state.value.slice(), i, i - 1), move(this.state.keys.slice(), i, i - 1), this.props.ctx.path.concat(i), 'moveUp' ); } } moveDownItem(i, evt) { evt.preventDefault(); if (i < this.state.value.length - 1) { this.onChange( move(this.state.value.slice(), i, i + 1), move(this.state.keys.slice(), i, i + 1), this.props.ctx.path.concat(i), 'moveDown' ); } } getTemplate() { return this.props.options.template || this.getTemplates().list; } getItems() { const { options, ctx } = this.props; const auto = this.getAuto(); const i18n = this.getI18n(); const config = this.getConfig(); const templates = this.getTemplates(); const value = this.state.value; const type = this.typeInfo.innerType.meta.type; const Component = getComponent(type, options.item || noobj); return value.map((value, i) => { const buttons = []; if (!options.disableRemove) { buttons.push({ label: i18n.remove, click: this.removeItem.bind(this, i) }); } if (!options.disableOrder) { buttons.push({ label: i18n.up, click: this.moveUpItem.bind(this, i) }); } if (!options.disableOrder) { buttons.push({ label: i18n.down, click: this.moveDownItem.bind(this, i) }); } return { input: React.createElement(Component, { ref: i, type, options: options.item || noobj, value, onChange: this.onItemChange.bind(this, i), ctx: { context: ctx.context, uidGenerator: ctx.uidGenerator, auto, config, i18n, name: ctx.name ? `${ctx.name}[${i}]` : String(i), templates, path: ctx.path.concat(i) } }), key: this.state.keys[i], buttons: buttons }; }); } getLocals() { const options = this.props.options; const i18n = this.getI18n(); const locals = super.getLocals(); locals.add = options.disableAdd ? null : { label: i18n.add, click: this.addItem.bind(this) }; locals.items = this.getItems(); locals.className = options.className; return locals; } } export class Form extends React.Component { validate() { return this.refs.input.validate(); } getValue(raw) { const result = this.validate(); return raw === true ? result : result.isValid() ? result.value : null; } getComponent(path) { path = t.Str.is(path) ? path.split('.') : path; return path.reduce((input, name) => input.refs[name], this.refs.input); } render() { const type = this.props.type; const options = this.props.options || noobj; const { i18n, templates } = Form; assert(t.isType(type), `[${SOURCE}] missing required prop type`); assert(t.Obj.is(options), `[${SOURCE}] prop options must be an object`); assert(t.Obj.is(templates), `[${SOURCE}] missing templates config`); assert(t.Obj.is(i18n), `[${SOURCE}] missing i18n config`); // this is in the render method because I need this._reactInternalInstance this.uidGenerator = this.uidGenerator || new UIDGenerator(this._reactInternalInstance ? this._reactInternalInstance._rootNodeID : ''); const Component = getComponent(type, options); return React.createElement(Component, { ref: 'input', type: type, options, value: this.props.value, onChange: this.props.onChange || noop, ctx: this.props.ctx || { context: this.props.context, uidGenerator: this.uidGenerator, auto: 'labels', templates, i18n, path: [] } }); } }
src/svg-icons/places/casino.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesCasino = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.5 18c-.83 0-1.5-.67-1.5-1.5S6.67 15 7.5 15s1.5.67 1.5 1.5S8.33 18 7.5 18zm0-9C6.67 9 6 8.33 6 7.5S6.67 6 7.5 6 9 6.67 9 7.5 8.33 9 7.5 9zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm0-9c-.83 0-1.5-.67-1.5-1.5S15.67 6 16.5 6s1.5.67 1.5 1.5S17.33 9 16.5 9z"/> </SvgIcon> ); PlacesCasino = pure(PlacesCasino); PlacesCasino.displayName = 'PlacesCasino'; PlacesCasino.muiName = 'SvgIcon'; export default PlacesCasino;
src/App.js
VicJuice/vicjuice.com
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
src/infra/component/Table.js
hellowin/kanca
// @flow import React from 'react'; import Pagination from 'infra/component/Pagination'; class Table extends React.Component { props: { data: { [string]: any }[], columns: { key: string, label: any }[], } render() { const { data, columns } = { data: [], columns: [], ...this.props, }; const Row = dt => ( <tr> {columns.map((col, key) => <td key={key}>{dt[col.key]}</td> )} </tr> ); const Wrapper = props => ( <table className="table table-striped"> <thead><tr> {columns.map((col, key) => <th key={key}>{col.label}</th>)} </tr></thead> <tbody> {props.children} </tbody> </table> ); return ( <Pagination list={data} ChildNode={Row} Wrapper={Wrapper} /> ); } } export default Table;
ui/src/js/team/EditTeamDetails.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import React, { Component } from 'react'; import IconButton from '../common/components/IconButton'; import Notification from '../common/components/Notification'; import FileChooseAndUploadButton from './FileChooseAndUploadButton'; export default class EditTeamDetails extends Component { constructor(props) { super(props); } uploadImage(file) { var data = new FormData(); data.append('teamId', this.props.team.teamId); data.append('file', file); var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt') } }; axios .post('http://localhost:8081/team/image/upload', data, config) .then(function(response) { that.refs.notification.addNotification(counterpart.translate('EDIT_SUCCES_TITLE'), counterpart.translate('EDIT_SUCCES_MESSAGE'), 'success'); }) .catch(function(error) { that.refs.notification.handleError(error); }); } leaveEditMode() { this.props.editTeam(false); } editTeam(toEdit, event) { var that = this; var toEditGlobal = toEdit; var newEntry = event.target.value; var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt') } }; axios .post('http://localhost:8081/team/edit?teamId=' + this.props.team.teamId + '&toEdit=' + toEditGlobal + '&newEntry=' + newEntry, {}, config) .then(function(response) { // that.refs.notification.addNotification(counterpart.translate('EDIT_SUCCES_TITLE'), counterpart.translate('EDIT_SUCCES_MESSAGE'), 'success'); if (toEditGlobal === 'name') { that.props.teamNameChangedAction(newEntry); } else { that.props.loadTeamDetails(); } }) .catch(function(error) { that.refs.notification.handleError(error); }); } updateImageName(imageName) { // this.props.updateImageName(imageName); } render() { return ( <div> <div className="row"> <div className="col-md-12"> <h1>{counterpart.translate('TEAM_EDIT')}</h1> </div> </div> <div className="row"> <div className="col-md-12 form-group"> <label htmlFor="team_name">{counterpart.translate('TEAM_NAME')}:</label> <input type="text" className="form-control" id="team_name" placeholder="" defaultValue={this.props.team.teamName} onBlur={e => this.editTeam('name', e)} /> </div> <div className="col-md-12"> <FileChooseAndUploadButton imageId="edit-team-img" imageFileName={this.props.team.teamId} updateImageName={this.updateImageName.bind(this)} teamId={this.props.team.teamId} /> </div> <div className="col-md-12 form-group"> <label htmlFor="team_description">{counterpart.translate('TEAM_DESCRIPTION')}:</label> <textarea className="form-control" rows="10" id="team_description" onBlur={e => this.editTeam('description', e)} defaultValue={this.props.team.description} /> </div> <div className="col-md-12"></div> </div> <div className="row align-center bottomButton"> <IconButton text="Anschauen" glyphIcon="glyphicon-eye-open" onClick={this.leaveEditMode.bind(this)} /> </div> <Notification ref="notification" /> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
_src/src/components/About/About.js
YannickDot/yannickdot.github.io
import React from 'react' import { rhythm } from 'utils/typography' const emojiStyle = { display: 'inline-block', margin: '0 4px 0 2px', height: '22px', position: 'relative', top: '5px' } const EmojiIsland = () => { return ( <img style={emojiStyle} src="https://twemoji.maxcdn.com/2/72x72/1f3dd.png" alt="🏝" /> ) } const EmojiFr = () => { return ( <img style={emojiStyle} src="https://twemoji.maxcdn.com/2/72x72/1f1eb-1f1f7.png" alt="🇫🇷" /> ) } class About extends React.Component { render() { return ( <div className="about" style={{ marginBottom: rhythm(2.5), fontFamily: 'Roboto' }}> <div className="personal-intro-content"> <p className="first"> Hi I'm Yannick, I am a french <EmojiFr /> software engineer raised in Martinique <EmojiIsland /> {' '} and passionnate about <strong>Front-end</strong> stuff and{' '} <strong>building products</strong>. <br /> </p> <p className="first"> I'm currently working <strong>remotely</strong> as a{' '} <strong>Lead Front-end engineer</strong> at{' '} <a href="https://www.teacupanalytics.com" target="_blank"> Teacup Analytics </a>. </p> {/* <p style={{ textAlign: 'justify' }}> I consider this blog to be a playground where I can share some of my experiments, discoveries, maybe a few tips and tricks, and projects I work on. </p> */} <p> My toolset is composed of : <br />{' '} <span className="toolset"> JavaScript · React · React Native · ReasonML · AngularJS · Node · CSS </span> </p> </div> </div> ) } } export default About
src/shell/server.js
jeffhandley/redux-playground
import React from 'react'; import ReactDOMServer from 'react-dom/server' export default function server(store) { return { renderPage(page) { // Rendering the page body will populate the store's state const body = ReactDOMServer.renderToString(page); // Once the body has been rendered, we grab a copy of the state const state = store.getState(); const props = {...state, body}; // Respect the page template specified in state; default to FullPage const template = React.createElement( state.layout.template || require('./templates/FullPage').default, props ); return ReactDOMServer.renderToStaticMarkup(template); } } }
react/tic-tac-toe/src/App.js
ripter/Workshops
import React from 'react'; import { Board } from './Board'; import { useWASMState } from './useWASMState'; import './App.css'; export function App() { const { state, hasLoaded, dispatch } = useWASMState(); if (!hasLoaded) { return <div className="tic-tac-toe"> <p>Loading...</p> </div>; } return <Game {...state} jumpTo={stepNumber => dispatch({type: 'rewind', stepNumber})} click={index => dispatch({type: 'click', index})} />; } // Game is a copy from the tutorial: https://reactjs.org/tutorial/tutorial.html // Codepen: https://codepen.io/gaearon/pen/gWWZgR?editors=0110 // Modified to handle the change in state. function Game(props) { const { board, stepNumber, isXNext, winner } = props; let moves = []; for (let move=0; move < stepNumber; move++) { const desc = move ? 'Go to move #' + move : 'Go to game start'; moves.push( <li key={move}> <button onClick={() => props.jumpTo(move)}>{desc}</button> </li> ); } let status; if (winner) { status = "Winner: " + winner; } else { status = "Next player: " + (isXNext ? "X" : "O"); } return ( <div className="game"> <div className="game-board"> <Board squares={board} onClick={i => props.click(i)} /> </div> <div className="game-info"> <div>{status}</div> <ol>{moves}</ol> </div> </div> ); }
src/js/shared/containers/Blog/BlogList.js
suranartnc/js-starter-kit
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as BlogActions from '../../actions/BlogActions'; class BlogList extends Component { constructor(props) { super(props); } static prefetchData = [BlogActions.getPosts]; componentDidMount() { // fetch API only if the content is not in the state yet if (this.props.blogs.length == 0) { this.props.getPosts(); } } renderBlogs() { return this.props.blogs.map((blog) => { return ( <li key={blog.question_id}> <Link to={`blog/${blog.question_id}/`}>{ blog.title }</Link> </li> ); }); } render() { return ( <div> <ul>{ this.renderBlogs() }</ul> </div> ); } } function mapStateToProps({ blogs }) { return { blogs }; } function mapDispatchToProps(dispatch) { return bindActionCreators(BlogActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(BlogList);
src/features/ViewMenuPopups/Views/Title.js
erhathaway/cellular_automata
import React from 'react'; import styled from 'react-emotion'; const Container = styled('div')` height: 30px; color: gray; text-align: center; padding: 10px; letter-spacing: 3px; font-size: 12px; `; export default ({ children }) => ( <Container> { children } </Container> );
src/components/badges/demos/NumberOverIcon.js
isogon/material-components
import React from 'react' import { Badge, Icon } from '../../../' export default () => ( <Badge overlap text="4"> <Icon lg name="account_box" /> </Badge> )
modules/Captures.js
cloudytimemachine/frontend
import React from 'react' import CaptureListContainer from './Captures/CaptureListContainer' class Captures extends React.Component { render() { console.log(this.props.params); return ( <div> {/*<RequestCaptureForm />*/} {/*<QueueStatus />*/} <CaptureListContainer /> </div> ) } } export default Captures;
src/components/SearchMetadata/stories.js
envisioning/tdb-storybook
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import SearchMetadata from './'; storiesOf('SearchMetadata', module) .add('default', () => ( <SearchMetadata took={100} total={150} showing={125} /> ))
actor-apps/app-web/src/app/components/common/AvatarItem.react.js
gale320/actor-platform
import React from 'react'; import classNames from 'classnames'; class AvatarItem extends React.Component { static propTypes = { image: React.PropTypes.string, placeholder: React.PropTypes.string.isRequired, size: React.PropTypes.string, title: React.PropTypes.string.isRequired }; constructor(props) { super(props); } render() { const title = this.props.title; const image = this.props.image; const size = this.props.size; let placeholder, avatar; let placeholderClassName = classNames('avatar__placeholder', `avatar__placeholder--${this.props.placeholder}`); let avatarClassName = classNames('avatar', { 'avatar--tiny': size === 'tiny', 'avatar--small': size === 'small', 'avatar--medium': size === 'medium', 'avatar--big': size === 'big', 'avatar--huge': size === 'huge', 'avatar--square': size === 'square' }); placeholder = <span className={placeholderClassName}>{title[0]}</span>; if (image) { avatar = <img alt={title} className="avatar__image" src={image}/>; } return ( <div className={avatarClassName}> {avatar} {placeholder} </div> ); } } export default AvatarItem;
packages/material-ui-icons/src/SignalCellular1Bar.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SignalCellular1Bar = props => <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z" /><path d="M12 12L2 22h10z" /> </SvgIcon>; SignalCellular1Bar = pure(SignalCellular1Bar); SignalCellular1Bar.muiName = 'SvgIcon'; export default SignalCellular1Bar;
node_modules/react-navigation/lib-rn/views/Card.js
gunaangs/Feedonymous
import React from 'react'; import { Animated, StyleSheet } from 'react-native'; import createPointerEventsContainer from './PointerEventsContainer'; var babelPluginFlowReactPropTypes_proptype_NavigationSceneRendererProps = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationSceneRendererProps || require('prop-types').any; /** * Component that renders the scene as card for the <NavigationCardStack />. */ class Card extends React.Component { render() { const { children, pointerEvents, style } = this.props; return <Animated.View pointerEvents={pointerEvents} ref={this.props.onComponentRef} style={[styles.main, style]}> {children} </Animated.View>; } } const styles = StyleSheet.create({ main: { backgroundColor: '#E9E9EF', bottom: 0, left: 0, position: 'absolute', right: 0, shadowColor: 'black', shadowOffset: { width: 0, height: 0 }, shadowOpacity: 0.4, shadowRadius: 10, top: 0 } }); Card = createPointerEventsContainer(Card); export default Card;
app/javascript/mastodon/features/directory/index.js
lynlynlynx/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from 'mastodon/components/column'; import ColumnHeader from 'mastodon/components/column_header'; import { addColumn, removeColumn, moveColumn, changeColumnParams } from 'mastodon/actions/columns'; import { fetchDirectory, expandDirectory } from 'mastodon/actions/directory'; import { List as ImmutableList } from 'immutable'; import AccountCard from './components/account_card'; import RadioButton from 'mastodon/components/radio_button'; import classNames from 'classnames'; import LoadMore from 'mastodon/components/load_more'; import { ScrollContainer } from 'react-router-scroll-4'; const messages = defineMessages({ title: { id: 'column.directory', defaultMessage: 'Browse profiles' }, recentlyActive: { id: 'directory.recently_active', defaultMessage: 'Recently active' }, newArrivals: { id: 'directory.new_arrivals', defaultMessage: 'New arrivals' }, local: { id: 'directory.local', defaultMessage: 'From {domain} only' }, federated: { id: 'directory.federated', defaultMessage: 'From known fediverse' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'directory', 'items'], ImmutableList()), isLoading: state.getIn(['user_lists', 'directory', 'isLoading'], true), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class Directory extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, columnId: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, domain: PropTypes.string.isRequired, params: PropTypes.shape({ order: PropTypes.string, local: PropTypes.bool, }), }; state = { order: null, local: null, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('DIRECTORY', this.getParams(this.props, this.state))); } } getParams = (props, state) => ({ order: state.order === null ? (props.params.order || 'active') : state.order, local: state.local === null ? (props.params.local || false) : state.local, }); handleMove = dir => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch } = this.props; dispatch(fetchDirectory(this.getParams(this.props, this.state))); } componentDidUpdate (prevProps, prevState) { const { dispatch } = this.props; const paramsOld = this.getParams(prevProps, prevState); const paramsNew = this.getParams(this.props, this.state); if (paramsOld.order !== paramsNew.order || paramsOld.local !== paramsNew.local) { dispatch(fetchDirectory(paramsNew)); } } setRef = c => { this.column = c; } handleChangeOrder = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['order'], e.target.value)); } else { this.setState({ order: e.target.value }); } } handleChangeLocal = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['local'], e.target.value === '1')); } else { this.setState({ local: e.target.value === '1' }); } } handleLoadMore = () => { const { dispatch } = this.props; dispatch(expandDirectory(this.getParams(this.props, this.state))); } render () { const { isLoading, accountIds, intl, columnId, multiColumn, domain, shouldUpdateScroll } = this.props; const { order, local } = this.getParams(this.props, this.state); const pinned = !!columnId; const scrollableArea = ( <div className='scrollable' style={{ background: 'transparent' }}> <div className='filter-form'> <div className='filter-form__column' role='group'> <RadioButton name='order' value='active' label={intl.formatMessage(messages.recentlyActive)} checked={order === 'active'} onChange={this.handleChangeOrder} /> <RadioButton name='order' value='new' label={intl.formatMessage(messages.newArrivals)} checked={order === 'new'} onChange={this.handleChangeOrder} /> </div> <div className='filter-form__column' role='group'> <RadioButton name='local' value='1' label={intl.formatMessage(messages.local, { domain })} checked={local} onChange={this.handleChangeLocal} /> <RadioButton name='local' value='0' label={intl.formatMessage(messages.federated)} checked={!local} onChange={this.handleChangeLocal} /> </div> </div> <div className={classNames('directory__list', { loading: isLoading })}> {accountIds.map(accountId => <AccountCard id={accountId} key={accountId} />)} </div> <LoadMore onClick={this.handleLoadMore} visible={!isLoading} /> </div> ); return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='address-book-o' title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} /> {multiColumn && !pinned ? <ScrollContainer scrollKey='directory' shouldUpdateScroll={shouldUpdateScroll}>{scrollableArea}</ScrollContainer> : scrollableArea} </Column> ); } }
src/svg-icons/action/perm-camera-mic.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermCameraMic = (props) => ( <SvgIcon {...props}> <path d="M20 5h-3.17L15 3H9L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v-2.09c-2.83-.48-5-2.94-5-5.91h2c0 2.21 1.79 4 4 4s4-1.79 4-4h2c0 2.97-2.17 5.43-5 5.91V21h7c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-6 8c0 1.1-.9 2-2 2s-2-.9-2-2V9c0-1.1.9-2 2-2s2 .9 2 2v4z"/> </SvgIcon> ); ActionPermCameraMic = pure(ActionPermCameraMic); ActionPermCameraMic.displayName = 'ActionPermCameraMic'; ActionPermCameraMic.muiName = 'SvgIcon'; export default ActionPermCameraMic;
src/component/ProfileItemEdit.js
im-js/im.js
/** * <plusmancn@gmail.com> created at 2017 * * Copyright (c) 2017 plusmancn, all rights * reserved. * * @flow * * 单条目编辑页 */ import React, { Component } from 'react'; import { StyleSheet, ScrollView, View } from 'react-native'; import { Color, FontSize, Button, TextInput } from '../../UiLibrary'; import { profileStore } from '../storeSingleton.js'; // 为了动态改变 SAVE 按钮的可点击状态 class LeftComponent extends React.Component { state: Object; constructor(props) { super(props); this.state = { isSaveDisabled: props.isSaveDisabled }; } render() { return ( <View style={styles.leftComponent} > <Button isWithOutLine={false} onPress={this.props.handleSave} disabled={this.state.isSaveDisabled} textStyle={styles.saveButton} > 保存 </Button> </View> ); } } export default class ProfileItemEdit extends Component { state: Object; _leftComponent: Object; constructor() { super(); this.state = { value: profileStore.userInfo.name }; } componentWillMount () { this.props.navigator.setRenderRightCompoent((sceneProps) => { return ( <LeftComponent ref={(ref) => { this._leftComponent = ref; }} handleSave={this._handleSave} isSaveDisabled={!this.state.value} /> ); }); } _handleSave = async () => { let result = await profileStore.modifyUserInfo('name', this.state.value); if (result.success) { this.props.navigator.pop(); } } _onChangeText = (text) => { this.setState({ value: text }); if (!this._leftComponent) { return; } if (text) { this._leftComponent.setState({ isSaveDisabled: false }); } else { this._leftComponent.setState({ isSaveDisabled: true }); } } render() { return ( <ScrollView style={styles.container} > <TextInput.Line value={this.state.value} onChangeText={this._onChangeText} /> </ScrollView> ); } } const styles = StyleSheet.create({ leftComponent: { flex: 1, justifyContent: 'center' }, container: { flex: 1, backgroundColor: Color.BackgroundGrey, paddingTop: 20 }, saveButton: { fontSize: FontSize.Content, color: Color.WechatGreen } });
src/photos/lib/confirm.js
goldoraf/cozy-drive
import React from 'react' import ReactDOM from 'react-dom' const confirm = (component, saga) => { const wrapper = document.body.appendChild(document.createElement('div')) const abort = () => { ReactDOM.unmountComponentAtNode(wrapper) } const confirm = () => { saga().then(() => { ReactDOM.unmountComponentAtNode(wrapper) }) } ReactDOM.render(React.cloneElement(component, { confirm, abort }), wrapper) } export default confirm
src/Calendar.js
trueanthem/react-date-range
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import parseInput from './utils/parseInput.js'; import DayCell from './DayCell.js'; import getTheme, { defaultClasses } from './styles.js'; function checkRange(dayMoment, range) { return ( dayMoment.isBetween(range['startDate'], range['endDate']) || dayMoment.isBetween(range['endDate'], range['startDate']) ); } function checkStartEdge(dayMoment, range) { const { startDate } = range; return dayMoment.isSame(startDate); } function checkEndEdge(dayMoment, range) { const { endDate } = range; return dayMoment.isSame(endDate); } function isOutsideMinMax(dayMoment, minDate, maxDate, format) { return ( (minDate && dayMoment.isBefore(parseInput(minDate, format))) || (maxDate && dayMoment.isAfter(parseInput(maxDate, format))) ); } function getMonthRange(dayMoment) { const startOfMonth = dayMoment.clone().startOf('month'); const endOfMonth = dayMoment.clone().endOf('month'); return { startOfMonth, endOfMonth, }; } function isSameDate(date1, date2) { return ( date1.isSame(date2, 'year') && date1.isSame(date2, 'month') && date1.isSame(date2, 'day') ); } function isStartOfWeekMonth(dayMoment) { const { startOfMonth } = getMonthRange(dayMoment); return dayMoment.day() === 0 || isSameDate(dayMoment, startOfMonth); } function isEndOfWeekMonth(dayMoment) { const { endOfMonth } = getMonthRange(dayMoment); return dayMoment.day() === 6 || isSameDate(dayMoment, endOfMonth); } class Calendar extends Component { constructor(props, context) { super(props, context); const { format, range, theme, offset, firstDayOfWeek } = props; const date = parseInput(props.date, format); const state = { date, shownDate: ((range && range['endDate']) || date) .clone() .add(offset, 'days'), firstDayOfWeek: firstDayOfWeek || moment.localeData().firstDayOfWeek(), }; this.state = state; this.styles = getTheme(theme); } componentDidMount() { const { onInit } = this.props; onInit && onInit(this.state.date); } componentWillReceiveProps(newProps) { const { format, range, offset } = newProps; const { startDate, endDate } = range || {}; const newDate = parseInput(newProps.date, format); const oldDate = parseInput(this.props.date, format); if (startDate && endDate && startDate.isSame(endDate)) { return; } if (newProps.date && this.props.date && newDate.isSame(oldDate)) { return; } this.setState({ date: newDate, shownDate: ((range && endDate) || newDate).clone().add(offset, 'days'), }); } getShownDate() { const { link, offset } = this.props; const shownDate = link ? link.clone().add(offset, 'days') : this.state.shownDate; return shownDate; } handleSelect(newDate) { const { link, onChange } = this.props; const { date } = this.state; onChange && onChange(newDate, Calendar); if (!link) { this.setState({ date: newDate }); } } changeMonth(direction, event) { event.preventDefault(); const { link, linkCB } = this.props; if (link && linkCB) { return linkCB(direction); } const current = this.state.shownDate.month(); const newMonth = this.state.shownDate.clone().add(direction, 'months'); this.setState({ shownDate: newMonth, }); } renderMonthButton(onlyClasses, styles, defaultButton, customButton) { const btn = styles[customButton]; if (btn) { return btn; } return ( <i style={ onlyClasses ? undefined : { ...styles['MonthArrow'], ...styles[defaultButton] } } ></i> ); } renderMonthAndYear(classes) { const shownDate = this.getShownDate(); const month = shownDate.format('MMM.'); const year = shownDate.year(); const { styles } = this; const { onlyClasses, minDate, disablePrevMonths } = this.props; const disableMonthButtonPrev = disablePrevMonths && shownDate.isSameOrBefore(minDate || moment(), 'month'); return ( <div style={onlyClasses ? undefined : styles['MonthAndYear']} className={classes.monthAndYearWrapper} > <button style={ onlyClasses ? undefined : { ...styles['MonthButton'], float: 'left', ...(disableMonthButtonPrev ? { opacity: 0.5, cursor: 'not-allowed' } : null), } } className={classes.prevButton} disabled={disableMonthButtonPrev} onClick={this.changeMonth.bind(this, -1)} > {this.renderMonthButton( onlyClasses, styles, 'MonthArrowPrev', 'MonthButtonPrev' )} </button> <span> <span className={classes.month}>{month}</span> <span className={classes.monthAndYearDivider}>&nbsp;</span> <span className={classes.year}>{year}</span> </span> <button style={ onlyClasses ? undefined : { ...styles['MonthButton'], float: 'right' } } className={classes.nextButton} onClick={this.changeMonth.bind(this, +1)} > {this.renderMonthButton( onlyClasses, styles, 'MonthArrowNext', 'MonthButtonNext' )} </button> </div> ); } renderWeekdays(classes) { const dow = this.state.firstDayOfWeek; const weekdays = []; const { styles } = this; const { onlyClasses } = this.props; for (let i = dow; i < 7 + dow; i++) { const day = moment.weekdaysMin(i); weekdays.push( <span style={onlyClasses ? undefined : styles['Weekday']} className={classes.weekDay} key={day} > {day} </span> ); } return weekdays; } renderDays(classes) { // TODO: Split this logic into smaller chunks const { styles } = this; const { range, minDate, maxDate, format, onlyClasses } = this.props; const shownDate = this.getShownDate(); const { date, firstDayOfWeek } = this.state; const dateUnix = date.unix(); const monthNumber = shownDate.month(); const dayCount = shownDate.daysInMonth(); const startOfMonth = shownDate.clone().startOf('month').isoWeekday(); const lastMonth = shownDate.clone().month(monthNumber - 1); const lastMonthNumber = lastMonth.month(); const lastMonthDayCount = lastMonth.daysInMonth(); const nextMonth = shownDate.clone().month(monthNumber + 1); const nextMonthNumber = nextMonth.month(); const days = []; // Previous month's days const diff = Math.abs(firstDayOfWeek - (startOfMonth + 7)) % 7; for (let i = diff - 1; i >= 0; i--) { const dayMoment = lastMonth.clone().date(lastMonthDayCount - i); days.push({ dayMoment, isPassive: true }); } // Current month's days for (let i = 1; i <= dayCount; i++) { const dayMoment = shownDate.clone().date(i); days.push({ dayMoment }); } // Next month's days const remainingCells = 42 - days.length; // 42cells = 7days * 6rows for (let i = 1; i <= remainingCells; i++) { const dayMoment = nextMonth.clone().date(i); days.push({ dayMoment, isPassive: true }); } const today = moment().startOf('day'); return days.map((data, index) => { const { dayMoment, isPassive } = data; const isSelected = !range && dayMoment.unix() === dateUnix; const isInRange = range && checkRange(dayMoment, range); const isStartEdge = range && checkStartEdge(dayMoment, range); const isEndEdge = range && checkEndEdge(dayMoment, range); const isEdge = isStartEdge || isEndEdge; const isToday = today.isSame(dayMoment); const isInRangeFirstOfRow = (isStartOfWeekMonth(dayMoment) && (isInRange || isEndEdge)) || isStartEdge; const isInRangeLastOfRow = (isEndOfWeekMonth(dayMoment) && (isInRange || isStartEdge)) || isEndEdge; const isVisible = dayMoment.month() === monthNumber; return ( <DayCell onSelect={this.handleSelect.bind(this)} {...data} theme={styles} isStartEdge={isStartEdge} isEndEdge={isEndEdge} isSelected={isSelected || isEdge} isInRange={isInRange} isInRangeFirstOfRow={isInRangeFirstOfRow} isInRangeLastOfRow={isInRangeLastOfRow} isToday={isToday} key={index} isPassive={ isPassive || isOutsideMinMax(dayMoment, minDate, maxDate, format) } isVisible={isVisible} onlyClasses={onlyClasses} classNames={classes} /> ); }); } render() { const { styles } = this; const { onlyClasses, classNames } = this.props; const classes = { ...defaultClasses, ...classNames }; return ( <div style={ onlyClasses ? undefined : { ...styles['Calendar'], ...this.props.style } } className={classes.calendar} > <div className={classes.monthAndYear}> {this.renderMonthAndYear(classes)} </div> <div className={classes.weekDays}>{this.renderWeekdays(classes)}</div> <div className={classes.days}>{this.renderDays(classes)}</div> </div> ); } } Calendar.defaultProps = { format: 'DD/MM/YYYY', theme: {}, onlyClasses: false, classNames: {}, }; Calendar.propTypes = { sets: PropTypes.string, range: PropTypes.shape({ startDate: PropTypes.object, endDate: PropTypes.object, }), minDate: PropTypes.oneOfType([ PropTypes.object, PropTypes.func, PropTypes.string, ]), maxDate: PropTypes.oneOfType([ PropTypes.object, PropTypes.func, PropTypes.string, ]), date: PropTypes.oneOfType([ PropTypes.object, PropTypes.string, PropTypes.func, ]), format: PropTypes.string.isRequired, firstDayOfWeek: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), onChange: PropTypes.func, onInit: PropTypes.func, link: PropTypes.oneOfType([ PropTypes.shape({ startDate: PropTypes.object, endDate: PropTypes.object, }), PropTypes.bool, ]), linkCB: PropTypes.func, theme: PropTypes.object, disablePrevMonths: PropTypes.bool, onlyClasses: PropTypes.bool, classNames: PropTypes.object, }; export default Calendar;
src/routes/News/routes/Archive/index.js
weedz/reactcms
import React from 'react'; import { Link } from 'react-router-dom'; import {ReduxWrapper} from '../../../../wrappers'; import News from '../../components/News'; import { fetchNewsGraphQL } from '../../../../actions/newsActions'; class Archive extends React.Component { constructor(props) { super(); this.state = { page: Number(props.match.params.page) || 1 }; } componentWillMount() { this.updateArchive(); } componentDidUpdate() { const currentPage = Number(this.props.match.params.page); if (isNaN(currentPage) && this.props.children) { } else if (isNaN(currentPage) && this.state.page !== 1) { this.state.page = 1; this.updateArchive(); } else if (!isNaN(currentPage) && this.state.page !== currentPage) { this.state.page = currentPage; this.updateArchive(); } } updateArchive() { //this.props.fetchNews(this.state.page); this.props.fetchNewsGraphQL(); } render() { const currentPage = Number(this.state.page); const links = []; if (this.props.match.params.page > 1 && this.props.articles.length > 0) { links.push(<Link key="prev" to={`/news/archive/${currentPage-1}`}>Previous</Link>) } if (this.props.numberOfArticles > this.props.match.params.page * 10) { links.push(<Link key="next" to={`/news/archive/${currentPage+1}`}>Next</Link>) } if (this.props.articles.length === 0) { links.push(<Link key="news" to={`${this.props.match.url}`}>News</Link>); } else if (this.props.match.params.page === undefined) { links.push(<Link key="archive" to={`${this.props.match.url}/archive/2`}>Archive</Link>); } return ( <div> <News articles={this.props.articles}/> {links} </div> ); } } export default ReduxWrapper(Archive, (state) => ({ articles: state.news.articles, numberOfArticles: state.news.numberOfArticles, lastFetch: state.news.lastFetch, fetching: state.news.fetching, }), { fetchNewsGraphQL });
public/src/components/feed-search-input_es6.js
alannesta/redux-rss
import React from 'react'; var FeedActions = require('../actions/feed-actions'); class FeedSearchInput extends React.Component { constructor() { super(); } searchFeed = () => { FeedActions.searchFeed(this.refs.inputField.value); } render() { return ( <section className = "toolbar"> <input ref = "inputField" type = "text" /> <button onClick = {this.searchFeed}>Submit</button> </section> ) } } export default FeedSearchInput;
react-flux-mui/js/material-ui/src/svg-icons/action/card-giftcard.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCardGiftcard = (props) => ( <SvgIcon {...props}> <path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/> </SvgIcon> ); ActionCardGiftcard = pure(ActionCardGiftcard); ActionCardGiftcard.displayName = 'ActionCardGiftcard'; ActionCardGiftcard.muiName = 'SvgIcon'; export default ActionCardGiftcard;
examples/async/index.js
batmanimal/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
src/Specifications.js
jma921/auto-specs-app
import React, { Component } from 'react'; import base from './utils/base'; import Clipboard from 'clipboard'; import './Specifications.css'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Tooltip } from 'reactstrap'; class Specifications extends Component { constructor() { super() this.state = { tooltipOpen: null, modal: false, showSuccess: false, showError: false } } printWindow = (e) => { window.print(); }; reportError = (e) => { e.preventDefault(); // this.props.handleClick(); alert('This will do something one day.'); }; toggleTooltip = (ms) => { // ms = length of timeout this.setState({ tooltipOpen: true }); setTimeout(() => { this.setState({ tooltipOpen: null }) }, ms) }; toggleModal = () => { this.setState({ modal: !this.state.modal }) }; submitErrorForm = (e) => { console.log(e); e.preventDefault(); const name = this.refs.name.value; const errorReported = `${this.props.year} ${this.props.make} ${this.props.model} ${this.props.engine} ${this.refs.errorReported.value}`; if (!name && !errorReported) { this.setState({ showError: "Please enter your name and the error." }) return; } if (!name) { this.setState({ showError: "Please enter your name." }) return; } if (!errorReported) { this.setState({ showError: "Please enter your error." }) return; } console.log(name, errorReported); this.refs.name.value = ''; this.refs.errorReported.value = ''; const timestamp = Date.now(); const key = -Math.abs(Date.now()); base.push('messages', { data: { name: name, error: errorReported, timestamp: timestamp, key: key} }).then(newLocation => { const generatedKey = newLocation.key; this.setState({ showSuccess: 'Thanks for your input. This box will close in 3 seconds.' }) }).catch(err => { console.log(err); }) setTimeout(() => { this.setState({ modal: false, showSuccess: null, showError: null }) }, 3000) }; copyToClipboard = (e) => { e.preventDefault(); const cap = `${this.props.year} ${this.props.make} ${this.props.model} ${this.props.engine} L\n Oil Cap: ${this.props.data.oilCap}\n Qts. Weight:${this.props.data.recWeight || '5W30'}\n Oil Filter: ${this.props.data.oilFilter}\n Air Filter: ${this.props.data.airFilter}\n Cabin Filter: ${this.props.data.cabinFilter}\n Wipers: ${this.props.data.wipers}\n Rear Wiper: ${this.props.data.rearWiper || 'None'}\n`; }; componentDidMount() { const clipboard = new Clipboard('#copyButton'); clipboard.on('success', function(e) { this.toggleTooltip(2000); console.info('Action:', e.action); console.info('Text:', e.text); console.info('Trigger:', e.trigger); e.clearSelection(); }.bind(this)); clipboard.on('error', function(e) { console.error('Action:', e.action); console.error('Trigger:', e.trigger); }); } render() { const specs = this.props.data; let oilCap, recWeight, oilFilter, airFilter, cabinFilter, wipers, rearWiper, battery; if (specs !== null) { oilCap = specs.oilCap ? `Oil Capacity: ${specs.oilCap}\n` : ''; recWeight = specs.recWeight ? `Oil Weight: ${specs.recWeight}\n` : ''; oilFilter = specs.oilFilter ? `Oil Filter: ${specs.oilFilter}\n` : ''; airFilter = specs.airFilter ? `Air Filter: ${specs.airFilter}\n` : ''; cabinFilter = specs.cabinFilter ? `Cabin Filter: ${specs.cabinFilter}\n` : ''; wipers = specs.wipers ? `Wipers: ${specs.wipers}\n` : ''; rearWiper = specs.rearWiper ? `Rear Wiper: ${specs.rearWiper}\n` : ''; battery = specs.battery ? `Battery: ${specs.battery}\n` : ''; } const copiedText = `${this.props.year} ${this.props.make} ${this.props.model} ${this.props.engine} L\n${oilCap}${oilFilter}${recWeight}${airFilter}${cabinFilter}${wipers}${rearWiper}${battery}`; let oilFilterCrossLink, airFilterCrossLink; if (specs.oilFilter !== undefined) { if (specs.oilFilter.substr(0,1) === 'P') { oilFilterCrossLink = `http://www.oilfilter-crossreference.com/convert/AC-Delco/${specs.oilFilter}`; } else { oilFilterCrossLink = 'none'; } } if (specs.airFilter !== undefined) { if (specs.airFilter.substr(0,1) === 'A') { airFilterCrossLink = `http://www.airfilter-crossreference.com/convert/AC-DELCO/${specs.airFilter}` } } return ( <div className="col-xs-12"> <div className="jumbotron mt-2"> <div className=""> <h2 id="model" >{this.props.year} {this.props.make} {this.props.model} {this.props.engine} L</h2> <p className="crossReferenceInfo">Click on air filter or oil filter for cross reference info if available.</p> <h4 id="oilCap" className="lead"><em>Oil Capacity:</em> <strong>{specs.oilCap} Quarts</strong></h4> <h4 id="recWeight" className="lead"><em>Oil Specification:</em> <strong>{specs.recWeight}</strong></h4> <h4 id="oilFilter" className="lead"><em>Oil Filter:</em> <strong><a href={oilFilterCrossLink} target="_blank">{specs.oilFilter}</a></strong></h4> {specs.airFilter ? <h4 id="airFilter" className="lead"><em>Air Filter:</em> <strong><a href={airFilterCrossLink} target="_blank">{specs.airFilter}</a></strong></h4> : null} {specs.cabinFilter ? <h4 id="cabinFilter" className="lead"><em>Cabin Filter:</em> <strong>{specs.cabinFilter}</strong></h4> : null} {specs.wipers ? <h4 id="wipers" className="lead"><em>Front Wipers:</em> <strong>{specs.wipers}</strong></h4> : null} {specs.rearWiper ? <h4 id="" className="lead"><em>Rear Wiper:</em> <strong>{specs.rearWiper}</strong></h4> : null} {specs.battery ? <h4 className="lead" id="battery"><em>Battery:</em> <strong>{specs.battery}</strong></h4> : null} {specs.oilReset ? <h4 className="lead" id="oilReset"><em>Oil Reset: </em><small>{specs.oilReset}</small></h4> : null} </div> <button id="printSpecs" className="btn btn-success mr-1 hidden-print" onClick={this.printWindow}><i className="fa fa-print"></i> Print</button> <button id="copyButton" className="btn btn-info hidden-print" onClick={this.copyToClipboard} data-clipboard-text={copiedText}><i className="fa fa-clipboard"></i> Copy To Clipboard</button> <div className="col-xs"> <button className="btn btn-link hidden-print" onClick={this.toggleModal}>Report An Error</button> </div> <Tooltip placement="top" isOpen={this.state.tooltipOpen} target="copyButton" > Copied! </Tooltip> </div> <Modal isOpen={this.state.modal} toggle={this.toggleModal} className={this.props.className}> <ModalHeader toggle={this.toggle}>Report An Error</ModalHeader> <ModalBody> <p>Please enter your name and describe the error.</p> <form onSubmit={this.submitErrorForm}> <div className="form-group"> <label htmlFor="name" className="control-label">Name</label> <input className="form-control" type="text" name="name" ref="name" /> </div> <div className="form-group"> <label htmlFor="errorReported">Error</label> <textarea rows="3" className="form-control" type="text" name="errorReported" ref="errorReported" /> </div> </form> { this.state.showSuccess ? <div className="alert alert-success"><p><strong>Success!</strong> {this.state.showSuccess}</p></div> : null } { this.state.showError ? <div className="alert alert-danger"><p><strong>Error!</strong> {this.state.showError}</p></div> : null } </ModalBody> <ModalFooter> <Button color="primary" onClick={this.submitErrorForm}>Submit</Button>{' '} <Button color="secondary" onClick={this.toggleModal}>Cancel</Button> </ModalFooter> </Modal> </div> ); } } export default Specifications;
app/components/kanban/EditForm.js
alanbo/devy-issue-tracker
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as kanbanActions from '../../actions/kanban'; import styles from './EditForm.scss'; // import { Link } from 'react-router-dom'; // import styles from './Counter.css'; const issueTypes = ['feature', 'bug', 'update']; function showIssueTypes() { return issueTypes.map(issueType => ( <option key={issueType} value={issueType}>{issueType}</option> )); } class EditForm extends Component { state = { heading: '', desc: '', branch: '', issue_type: 'feature', open: false } componentWillRender() { if (this.props.editedIssue) { } } componentWillMount() { if (!this.state.branch) { this.setState({ branch: `${this.state.issue_type}-` }); } if (this.props.issue_id) { let { heading, desc, branch, issue_type } = this.props.issues.filter(i => i.id === this.props.issue_id)[0]; this.setState({ heading, desc, branch, issue_type }); } } setValue(e) { this.setState({ [e.target.name]: e.target.value }); if (e.target.name === 'issue_type' && issueTypes.includes(this.state.branch.slice(0, -1))) { this.setState({ branch: `${e.target.value}-` }); } } componentDidMount() { const that = this; this.editScreen.addEventListener('click', function(e) { if (this.isEqualNode(e.target)) { that.props.clickOut(); } }); } render() { const { issues, addIssue, editIssue } = this.props; return ( <div className={styles.editScreen} ref={editScreen => { this.editScreen = editScreen; }} > <div className={styles.editContainer}> <form> <input value={this.state.heading} type="text" name="heading" onChange={this.setValue.bind(this)} placeholder="Heading" /> <textarea value={this.state.desc} type="text" name="desc" onChange={this.setValue.bind(this)} placeholder="Describe the issue..." >{this.state.desc}</textarea> <input value={this.state.branch} type="text" name="branch" onChange={this.setValue.bind(this)} /> <select name="issue_type" value={this.state.issue_type} onChange={this.setValue.bind(this)} > { showIssueTypes() } </select> <button onClick={e => { e.preventDefault(); if (this.props.issue_id) { editIssue({ id: this.props.issue_id, ...this.state }); } else { addIssue({ id: Math.random() * 10000, ...this.state }); } this.props.onSave(); }} > Save </button> </form> </div> </div> ); } } function mapStateToProps(state) { return { issues: state.kanban }; } export default connect(mapStateToProps, kanbanActions)(EditForm);
client/analytics/components/pages/alerts/alertsSetting/ConditionItems.js
Haaarp/geo
import React from 'react'; import TresholdItem from './TresholdItem'; const ConditionItems = (props) =>{ return( <div> { props.selectedTreshold.conditions ? props.selectedTreshold.conditions.map((conditon,i) => { return <TresholdItem item={conditon} onInit={props.onInit} itemsNames={props.itemsNames} itemsComparison={props.itemsComparison} length={conditon.length} handleSelect={props.handleSelect} deleteDropDownList={props.deleteDropDownList} deleteDropDownItem={props.deleteDropDownItem} addTresholdItem={props.addTresholdItem} selectTresholdID={props.selectTresholdID} selectAlertID={i} addDropDownList={props.addDropDownList} key={"treshold-item=" + i} treshloadItemId={i} id={i} onKeyUp={props.onKeyUp} value={props.value} />; }) : null } </div> ); }; export default ConditionItems;
src/components/Twitter/TwitterLoader.js
Rico75/ricardoswebconsulting-react-php
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Twitter.scss'; //console.log('TwitterLoader s: ', s); class TwitterLoader extends Component { render() { return ( <div className={s.root}> <div className={"loader " + (this.props.paging ? "active" : "")}> <img src="svg/loader.svg" /> </div> </div> ); } } export default withStyles(TwitterLoader, s);
app/app.js
ryanau/doc_now_client
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; import Raven from 'raven-js'; // Import Mixpanel import initializeMixpanel from 'utils/mixpanel'; // Import React AB Test import mixpanelHelper from 'react-ab-test/lib/helpers/mixpanel'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Import global sagas import { injectGlobalSagas } from './sagas'; // Initializations initializeMixpanel(document, window, process.env.NODE_ENV); mixpanelHelper.enable(); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Inject global sagas injectGlobalSagas(store); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/zh.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require Raven .config('https://bbf6a82ad8684075bb457301bf4176e7@sentry.io/191999') .install(); }
src/svg-icons/av/repeat.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRepeat = (props) => ( <SvgIcon {...props}> <path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/> </SvgIcon> ); AvRepeat = pure(AvRepeat); AvRepeat.displayName = 'AvRepeat'; AvRepeat.muiName = 'SvgIcon'; export default AvRepeat;
src/svg-icons/image/crop-landscape.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropLandscape = (props) => ( <SvgIcon {...props}> <path d="M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 12H5V7h14v10z"/> </SvgIcon> ); ImageCropLandscape = pure(ImageCropLandscape); ImageCropLandscape.displayName = 'ImageCropLandscape'; ImageCropLandscape.muiName = 'SvgIcon'; export default ImageCropLandscape;
client/src/components/AuthButton.js
wapjude/labify
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Button } from 'react-native'; import { NavigationActions } from 'react-navigation'; const AuthButton = ({ logout, loginScreen, isLoggedIn }) => ( <Button title={isLoggedIn ? 'Log Out' : 'Open Login Screen'} onPress={isLoggedIn ? logout : loginScreen} /> ); AuthButton.propTypes = { isLoggedIn: PropTypes.bool.isRequired, logout: PropTypes.func.isRequired, loginScreen: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ isLoggedIn: state.auth.isLoggedIn, }); const mapDispatchToProps = dispatch => ({ logout: () => dispatch({ type: 'Logout' }), loginScreen: () => dispatch(NavigationActions.navigate({ routeName: 'Login' })), }); export default connect(mapStateToProps, mapDispatchToProps)(AuthButton);