path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
packages/@lyra/google-maps-input/src/GeopointInput.js
VegaPublish/vega-studio
import PropTypes from 'prop-types' import React from 'react' import config from 'config:@lyra/google-maps-input' import Button from 'part:@lyra/components/buttons/default' import Dialog from 'part:@lyra/components/dialogs/default' import Fieldset from 'part:@lyra/components/fieldsets/default' import { PatchEvent, set, setIfMissing, unset } from 'part:@lyra/form-builder/patch-event' import styles from '../styles/GeopointInput.css' import GeopointSelect from './GeopointSelect' import GoogleMapsLoadProxy from './GoogleMapsLoadProxy' const getLocale = context => { const intl = context.intl || {} return ( intl.locale || (typeof window !== 'undefined' && window.navigator.language) || 'en' ) } const getStaticImageUrl = value => { const loc = `${value.lat},${value.lng}` const params = { key: config.apiKey, center: loc, markers: loc, zoom: 13, scale: 2, size: '640x300' } const qs = Object.keys(params).reduce((res, param) => { return res.concat(`${param}=${encodeURIComponent(params[param])}`) }, []) return `https://maps.googleapis.com/maps/api/staticmap?${qs.join('&')}` } class GeopointInput extends React.Component { static propTypes = { onChange: PropTypes.func.isRequired, markers: PropTypes.arrayOf( PropTypes.shape({ type: PropTypes.string }) ), value: PropTypes.shape({ lat: PropTypes.number, lng: PropTypes.number }), type: PropTypes.shape({ title: PropTypes.string.isRequired, description: PropTypes.string }) } static defaultProps = { markers: [] } static contextTypes = { intl: PropTypes.shape({ locale: PropTypes.string }) } constructor() { super() this.handleToggleModal = this.handleToggleModal.bind(this) this.handleCloseModal = this.handleCloseModal.bind(this) this.state = { modalOpen: false } } handleToggleModal() { this.setState(prevState => ({modalOpen: !prevState.modalOpen})) } handleChange = latLng => { const {type, onChange} = this.props onChange( PatchEvent.from([ setIfMissing({ _type: type.name }), set(latLng.lat(), ['lat']), set(latLng.lng(), ['lng']) ]) ) } handleClear = () => { const {onChange} = this.props onChange(PatchEvent.from(unset())) } handleCloseModal() { this.setState({modalOpen: false}) } render() { const {value, type, markers} = this.props if (!config || !config.apiKey) { return ( <div> <p> The{' '} <a href="https://vegapublish.com/docs/schema-types/geopoint-type"> Geopoint type </a>{' '} needs a Google Maps API key with access to: </p> <ul> <li>Google Maps JavaScript API</li> <li>Google Places API Web Service</li> <li>Google Static Maps API</li> </ul> <p> Please enter the API key with access to these services in <code style={{whitespace: 'nowrap'}}> `&lt;project-root&gt;/config/@lyra/google-maps-input.json` </code> </p> </div> ) } return ( <Fieldset legend={type.title} description={type.description} className={styles.root} markers={markers} > {value && ( <div> <img className={styles.previewImage} src={getStaticImageUrl(value)} /> </div> )} <div className={styles.functions}> <Button onClick={this.handleToggleModal}> {value ? 'Edit' : 'Set location'} </Button> {value && ( <Button type="button" onClick={this.handleClear}> Remove </Button> )} </div> {this.state.modalOpen && ( <Dialog title="Place on map" onClose={this.handleCloseModal} onCloseClick={this.handleCloseModal} onOpen={this.handleOpenModal} message="Select location by dragging the marker or search for a place" isOpen={this.state.modalOpen} > <div className={styles.dialogInner}> <GoogleMapsLoadProxy value={value} apiKey={config.apiKey} onChange={this.handleChange} defaultLocation={config.defaultLocation} defaultZoom={config.defaultZoom} locale={getLocale(this.context)} component={GeopointSelect} /> </div> </Dialog> )} </Fieldset> ) } } export default GeopointInput
src/components/Header/index.js
jefflau/jefflau.net
import React from 'react' import Link from 'gatsby-link' const Header = ({ pages }) => <header className="site-header"> <h1 className="logo"> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > Jeff Lau </Link> </h1> <ul> {pages.map(({node: page}) => <li key={page.id}><Link to={page.frontmatter.slug}>{page.frontmatter.title}</Link></li> )} <li key="mentorship"><Link to="/mentorship">Mentorship</Link></li> </ul> </header> export default Header
client/components/users/email-enrollment-form.js
ShannChiang/meteor-react-redux-base
import React from 'react'; export default class extends React.Component { constructor(props) { super(props); this.state = {uiState: 'INIT'}; this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); this.setState({uiState: 'SENDING'}); this.props.enrollWithEmail(this._input.value, (err) => { if (err) { console.log(err); this.setState({uiState: 'FAIL'}); } else { this.setState({uiState: 'SUCCESS'}); } }); } render() { if (this.state.uiState === 'SENDING') return <div>正在发送邮件...</div>; if (this.state.uiState === 'SUCCESS') return <div>邮件已发送,请查看您的邮箱</div>; return ( <div className="row"> <div className="col-sm-12"> {this.state.uiState === 'FAIL' && <p>邮件发送失败,请重试</p>} <p>请填写登录用的邮箱地址,我们将发送一个链接到你邮箱,通过该链接设置登录密码</p> <form onSubmit={this.onSubmit}> <div className="input-group"> <input className="form-control" type="text" ref={(c) => this._input = c}/> <span className="input-group-btn"> <button className="btn btn-default" type="submit">提交</button> </span> </div> </form> </div> </div> ); } }
es/components/sidebar/panel-element-editor/attributes-editor/attributes-editor.js
dearkaran/react-planner
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ItemAttributesEditor from './item-attributes-editor'; import LineAttributesEditor from './line-attributes-editor'; import HoleAttributesEditor from './hole-attributes-editor'; export default function AttributesEditor(_ref) { var element = _ref.element, onUpdate = _ref.onUpdate, attributeFormData = _ref.attributeFormData, state = _ref.state; switch (element.prototype) { case 'items': return React.createElement(ItemAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData, state: state }); case 'lines': return React.createElement(LineAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData, state: state }); case 'holes': return React.createElement(HoleAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData, state: state }); case 'areas': return null; } return null; } AttributesEditor.propTypes = { element: PropTypes.object.isRequired, onUpdate: PropTypes.func.isRequired, attributeFormData: PropTypes.object.isRequired, state: PropTypes.object.isRequired };
examples/todos-with-undo/src/index.js
heyesther/redux
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import App from './components/App' import reducer from './reducers' const store = createStore(reducer) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
docs/src/components/Playground/Atoms/TextLink/TextLink.js
seekinternational/seek-asia-style-guide
import styles from './TextLink.less'; import React from 'react'; import PropTypes from 'prop-types'; import ChevronIcon from 'seek-asia-style-guide/react/ChevronIcon/ChevronIcon'; import classnames from 'classnames'; const renderChevron = chevron => { if (!chevron) { return null; } return ( <ChevronIcon className={styles.chevron} direction={chevron} svgClassName={styles.chevronSvg} /> ); }; export default function TextLink({ component: Root, className, shouting, yelling, screaming, children, chevron, ...restProps }) { const allProps = { ...restProps, className: classnames(styles.link, { [className]: className, [styles.shouting]: shouting, [styles.yelling]: yelling, [styles.screaming]: screaming, [styles.touchable]: !shouting && !yelling && !screaming }) }; return ( <Root {...allProps}> {children} {renderChevron(chevron)} </Root> ); } TextLink.displayName = 'TextLink'; TextLink.propTypes = { component: PropTypes.any, className: PropTypes.string, children: PropTypes.node, chevron: PropTypes.oneOf(['up', 'down', 'right', 'left']), shouting: PropTypes.bool, yelling: PropTypes.bool, screaming: PropTypes.bool }; TextLink.defaultProps = { component: 'a' };
examples/BackgroundImage/__tests__/index.ios.js
thekevinscott/Hero-test
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/AccordionItem/test.js
daviferreira/react-sanfona
'use strict'; import expect from 'unexpected'; import sd from 'skin-deep'; import React from 'react'; import AccordionItem from './index'; describe('AccordionItem Test Case', () => { let vdom, instance; it('should render', () => { const tree = sd.shallowRender(<AccordionItem />); instance = tree.getMountedInstance(); vdom = tree.getRenderOutput(); expect(instance, 'to be defined'); expect(vdom, 'to be defined'); expect(vdom.type, 'to be', 'div'); expect(vdom.props.children[0].props, 'to have property', 'rootTag', 'h3'); expect(vdom.props.children[1].props, 'to have property', 'rootTag', 'div'); }); it('should render with custom tags', () => { const tree = sd.shallowRender( <AccordionItem rootTag="li" titleTag="h2" bodyTag="ul" /> ); instance = tree.getMountedInstance(); vdom = tree.getRenderOutput(); expect(instance, 'to be defined'); expect(vdom, 'to be defined'); expect(vdom.type, 'to be', 'li'); expect(vdom.props.children[0].props, 'to have property', 'rootTag', 'h2'); expect(vdom.props.children[1].props, 'to have property', 'rootTag', 'ul'); }); it('should have an unique id', () => { const tree = sd.shallowRender(<AccordionItem />); const treeAlt = sd.shallowRender(<AccordionItem />); instance = tree.getMountedInstance(); const anotherInstance = treeAlt.getMountedInstance(); expect(instance.uuid, 'not to equal', anotherInstance.uuid); }); it('should allow custom uuid', () => { const tree = sd.shallowRender(<AccordionItem uuid="first item" />); const treeAlt = sd.shallowRender(<AccordionItem uuid="second item" />); instance = tree.getMountedInstance(); const anotherInstance = treeAlt.getMountedInstance(); expect(instance.uuid, 'to equal', 'first item'); expect(anotherInstance.uuid, 'to equal', 'second item'); }); describe('disabled mode', () => { it('should be false by default', () => { const tree = sd.shallowRender(<AccordionItem />); vdom = tree.getRenderOutput(); expect(vdom.props.disabled, 'to be undefined'); }); it('should have react-sanfona-item-disabled className when disabled', () => { const tree = sd.shallowRender(<AccordionItem disabled />); vdom = tree.getRenderOutput(); expect( vdom.props.className, 'to be', 'react-sanfona-item react-sanfona-item-disabled' ); }); it('should have a custom className when provided', () => { const tree = sd.shallowRender( <AccordionItem disabled disabledClassName="customDisabled" /> ); vdom = tree.getRenderOutput(); expect( vdom.props.className, 'to be', 'react-sanfona-item react-sanfona-item-disabled customDisabled' ); }); }); });
app/javascript/mastodon/features/ui/index.js
amazedkoumei/mastodon
import classNames from 'classnames'; import React from 'react'; import { HotKeys } from 'react-hotkeys'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import NotificationsContainer from './containers/notifications_container'; import LoadingBarContainer from './containers/loading_bar_container'; import TabsBar from './components/tabs_bar'; import ModalContainer from './containers/modal_container'; import { isMobile } from '../../is_mobile'; import { debounce } from 'lodash'; import { uploadCompose, resetCompose } from '../../actions/compose'; import { expandHomeTimeline } from '../../actions/timelines'; import { expandNotifications } from '../../actions/notifications'; import { fetchFilters } from '../../actions/filters'; import { clearHeight } from '../../actions/height_cache'; import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers'; import UploadArea from './components/upload_area'; import ColumnsAreaContainer from './containers/columns_area_container'; import { Compose, Status, GettingStarted, KeyboardShortcuts, PublicTimeline, CommunityTimeline, AccountTimeline, AccountGallery, HomeTimeline, Followers, Following, Reblogs, Favourites, DirectTimeline, HashtagTimeline, Notifications, FollowRequests, GenericNotFound, FavouritedStatuses, ListTimeline, Blocks, DomainBlocks, Mutes, PinnedStatuses, Lists, } from './util/async-components'; import { me } from '../../initial_state'; import { previewState } from './components/media_modal'; // Dummy import, to make sure that <Status /> ends up in the application bundle. // Without this it ends up in ~8 very commonly used bundles. import '../../components/status'; const messages = defineMessages({ beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' }, }); const mapStateToProps = state => ({ isComposing: state.getIn(['compose', 'is_composing']), hasComposingText: state.getIn(['compose', 'text']) !== '', dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null, }); const keyMap = { help: '?', new: 'n', search: 's', forceNew: 'option+n', focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'], reply: 'r', favourite: 'f', boost: 'b', mention: 'm', open: ['enter', 'o'], openProfile: 'p', moveDown: ['down', 'j'], moveUp: ['up', 'k'], back: 'backspace', goToHome: 'g h', goToNotifications: 'g n', goToLocal: 'g l', goToFederated: 'g t', goToDirect: 'g d', goToStart: 'g s', goToFavourites: 'g f', goToPinned: 'g p', goToProfile: 'g u', goToBlocked: 'g b', goToMuted: 'g m', goToRequests: 'g r', toggleHidden: 'x', }; class SwitchingColumnsArea extends React.PureComponent { static propTypes = { children: PropTypes.node, location: PropTypes.object, onLayoutChange: PropTypes.func.isRequired, }; state = { mobile: isMobile(window.innerWidth), }; componentWillMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentDidUpdate (prevProps) { if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) { this.node.handleChildrenContentChange(); } } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } shouldUpdateScroll (_, { location }) { return location.state !== previewState; } handleResize = debounce(() => { // The cached heights are no longer accurate, invalidate this.props.onLayoutChange(); this.setState({ mobile: isMobile(window.innerWidth) }); }, 500, { trailing: true, }); setRef = c => { this.node = c.getWrappedInstance().getWrappedInstance(); } render () { const { children } = this.props; const { mobile } = this.state; const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />; return ( <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}> <WrappedSwitch> {redirect} <WrappedRoute path='/getting-started' component={GettingStarted} content={children} /> <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} /> <WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} /> <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} /> <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} /> <WrappedRoute path='/statuses/new' component={Compose} content={children} /> <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} /> <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute component={GenericNotFound} content={children} /> </WrappedSwitch> </ColumnsAreaContainer> ); } } @connect(mapStateToProps) @injectIntl @withRouter export default class UI extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { dispatch: PropTypes.func.isRequired, children: PropTypes.node, isComposing: PropTypes.bool, hasComposingText: PropTypes.bool, location: PropTypes.object, intl: PropTypes.object.isRequired, dropdownMenuIsOpen: PropTypes.bool, }; state = { draggingOver: false, }; handleBeforeUnload = (e) => { const { intl, isComposing, hasComposingText } = this.props; if (isComposing && hasComposingText) { // Setting returnValue to any string causes confirmation dialog. // Many browsers no longer display this text to users, // but we set user-friendly message for other browsers, e.g. Edge. e.returnValue = intl.formatMessage(messages.beforeUnload); } } handleLayoutChange = () => { // The cached heights are no longer accurate, invalidate this.props.dispatch(clearHeight()); } handleDragEnter = (e) => { e.preventDefault(); if (!this.dragTargets) { this.dragTargets = []; } if (this.dragTargets.indexOf(e.target) === -1) { this.dragTargets.push(e.target); } if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) { this.setState({ draggingOver: true }); } } handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); try { e.dataTransfer.dropEffect = 'copy'; } catch (err) { } return false; } handleDrop = (e) => { e.preventDefault(); this.setState({ draggingOver: false }); if (e.dataTransfer && e.dataTransfer.files.length === 1) { this.props.dispatch(uploadCompose(e.dataTransfer.files)); } } handleDragLeave = (e) => { e.preventDefault(); e.stopPropagation(); this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el)); if (this.dragTargets.length > 0) { return; } this.setState({ draggingOver: false }); } closeUploadModal = () => { this.setState({ draggingOver: false }); } handleServiceWorkerPostMessage = ({ data }) => { if (data.type === 'navigate') { this.context.router.history.push(data.path); } else { console.warn('Unknown message type:', data.type); } } componentWillMount () { window.addEventListener('beforeunload', this.handleBeforeUnload, false); document.addEventListener('dragenter', this.handleDragEnter, false); document.addEventListener('dragover', this.handleDragOver, false); document.addEventListener('drop', this.handleDrop, false); document.addEventListener('dragleave', this.handleDragLeave, false); document.addEventListener('dragend', this.handleDragEnd, false); if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage); } this.props.dispatch(expandHomeTimeline()); this.props.dispatch(expandNotifications()); setTimeout(() => this.props.dispatch(fetchFilters()), 500); } componentDidMount () { this.hotkeys.__mousetrap__.stopCallback = (e, element) => { return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName); }; } componentWillUnmount () { window.removeEventListener('beforeunload', this.handleBeforeUnload); document.removeEventListener('dragenter', this.handleDragEnter); document.removeEventListener('dragover', this.handleDragOver); document.removeEventListener('drop', this.handleDrop); document.removeEventListener('dragleave', this.handleDragLeave); document.removeEventListener('dragend', this.handleDragEnd); } setRef = c => { this.node = c; } handleHotkeyNew = e => { e.preventDefault(); const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea'); if (element) { element.focus(); } } handleHotkeySearch = e => { e.preventDefault(); const element = this.node.querySelector('.search__input'); if (element) { element.focus(); } } handleHotkeyForceNew = e => { this.handleHotkeyNew(e); this.props.dispatch(resetCompose()); } handleHotkeyFocusColumn = e => { const index = (e.key * 1) + 1; // First child is drawer, skip that const column = this.node.querySelector(`.column:nth-child(${index})`); if (column) { const status = column.querySelector('.focusable'); if (status) { status.focus(); } } } handleHotkeyBack = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } setHotkeysRef = c => { this.hotkeys = c; } handleHotkeyToggleHelp = () => { if (this.props.location.pathname === '/keyboard-shortcuts') { this.context.router.history.goBack(); } else { this.context.router.history.push('/keyboard-shortcuts'); } } handleHotkeyGoToHome = () => { this.context.router.history.push('/timelines/home'); } handleHotkeyGoToNotifications = () => { this.context.router.history.push('/notifications'); } handleHotkeyGoToLocal = () => { this.context.router.history.push('/timelines/public/local'); } handleHotkeyGoToFederated = () => { this.context.router.history.push('/timelines/public'); } handleHotkeyGoToDirect = () => { this.context.router.history.push('/timelines/direct'); } handleHotkeyGoToStart = () => { this.context.router.history.push('/getting-started'); } handleHotkeyGoToFavourites = () => { this.context.router.history.push('/favourites'); } handleHotkeyGoToPinned = () => { this.context.router.history.push('/pinned'); } handleHotkeyGoToProfile = () => { this.context.router.history.push(`/accounts/${me}`); } handleHotkeyGoToBlocked = () => { this.context.router.history.push('/blocks'); } handleHotkeyGoToMuted = () => { this.context.router.history.push('/mutes'); } handleHotkeyGoToRequests = () => { this.context.router.history.push('/follow_requests'); } render () { const { draggingOver } = this.state; const { children, isComposing, location, dropdownMenuIsOpen } = this.props; const handlers = { help: this.handleHotkeyToggleHelp, new: this.handleHotkeyNew, search: this.handleHotkeySearch, forceNew: this.handleHotkeyForceNew, focusColumn: this.handleHotkeyFocusColumn, back: this.handleHotkeyBack, goToHome: this.handleHotkeyGoToHome, goToNotifications: this.handleHotkeyGoToNotifications, goToLocal: this.handleHotkeyGoToLocal, goToFederated: this.handleHotkeyGoToFederated, goToDirect: this.handleHotkeyGoToDirect, goToStart: this.handleHotkeyGoToStart, goToFavourites: this.handleHotkeyGoToFavourites, goToPinned: this.handleHotkeyGoToPinned, goToProfile: this.handleHotkeyGoToProfile, goToBlocked: this.handleHotkeyGoToBlocked, goToMuted: this.handleHotkeyGoToMuted, goToRequests: this.handleHotkeyGoToRequests, }; return ( <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}> <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}> <TabsBar /> <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}> {children} </SwitchingColumnsArea> <NotificationsContainer /> <LoadingBarContainer className='loading-bar' /> <ModalContainer /> <UploadArea active={draggingOver} onClose={this.closeUploadModal} /> </div> </HotKeys> ); } }
generators/app/templates/app/assets/javascript/containers/home/index.js
ajaykumaryadav/react-bootstrap
import React, { Component } from 'react'; import { browserHistory } from 'react-router'; import Header from '../../components/shared/header' class homeContainer extends Component { render() { return ( <section> <Header /> {this.props.children} <div className="container"> <hr/> <footer> <p>&copy; 2016.</p> </footer> </div> </section> ); } } export default homeContainer;
src/components/ui/content/index.js
boxal/boxal
import React from 'react'; function Content({ children, isVisible = true, }) { return ( <div style={style[isVisible]}> {isVisible ? children : null} </div> ); } const style = { [true]: {}, [false]: { display: 'none', }, }; Content.propTypes = { children: React.PropTypes.node, isVisible: React.PropTypes.bool, }; export default Content;
src/Tag.js
captainill/react-tag-select
/* eslint react/no-multi-comp: 0 */ import React, { Component } from 'react'; class Tag extends Component { static propTypes = { labelField: React.PropTypes.string, onDelete: React.PropTypes.func.isRequired, tag: React.PropTypes.object.isRequired, removeComponent: React.PropTypes.func, readOnly: React.PropTypes.bool } static defaultProps = { labelField: 'text' } render() { const label = this.props.tag[this.props.labelField]; const { readOnly } = this.props; const CustomRemoveComponent = this.props.removeComponent; class RemoveComponent extends Component { render() { if (readOnly) { return <span/>; } if (CustomRemoveComponent) { return <CustomRemoveComponent {...this.props} />; } return <a {...this.props}>x</a>; } } return ( <span className="ReactTags-tag"> <RemoveComponent className="ReactTags-remove" onClick={this.props.onDelete} /> <span className="ReactTags-label">{label}</span> </span> ); } } module.exports = Tag;
cm19/ReactJS/your-first-react-app-exercises-master/exercise-17/Header.js
Brandon-J-Campbell/codemash
import React from 'react'; import classNames from 'classnames'; // import theme from './theme/static'; import ThemeContext from './theme/context'; import ThemeSwitcher from './theme/Switcher'; import styles from './Header.css'; export default function Header() { return ( <ThemeContext.Consumer> {({ theme }) => ( <header className={classNames(styles.appHeader, styles[theme])}> <h1 className={styles.appTitle}>Exercise 17</h1> <h2 className={styles.subTitle}>Testing Component Render</h2> <div className={styles.switcherWrapper}> <ThemeSwitcher /> </div> </header> )} </ThemeContext.Consumer> ); }
src/svg-icons/action/perm-phone-msg.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermPhoneMsg = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/> </SvgIcon> ); ActionPermPhoneMsg = pure(ActionPermPhoneMsg); ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg'; ActionPermPhoneMsg.muiName = 'SvgIcon'; export default ActionPermPhoneMsg;
pages/discover-more/related-projects.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from 'docs/src/pages/discover-more/related-projects/related-projects.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
components/styled-links.js
kentcdodds/glamorous-website
import React from 'react' import Link from 'next/link' import glamorous from 'glamorous' import {colors} from '../styles/global-styles' const getPathname = pathname => { return pathname === undefined ? '' : pathname } const basicLinkStyles = // @css {cursor: 'pointer'} const anchorStyles = // @css { textDecoration: 'underline', color: colors.primaryMed, } const activeLinkStyles = props => ({ color: props.active || props.external ? props.theme.colors.primary : props.theme.colors.primaryMed, textDecoration: props.active || props.external ? 'underline' : 'none', }) const slugStyles = // @css { position: 'relative', display: 'block', '& svg': { display: 'none', position: 'absolute', top: 0, left: '-2.5rem', width: '1.75em', height: '2.827em', }, '&:hover svg': { display: 'block', }, } const StyledAnchor = glamorous.a( basicLinkStyles, anchorStyles, activeLinkStyles, props => (props.isSlug ? slugStyles : ''), ) const Anchor = ({href, prefetch, external, pathname, isSlug, ...rest}) => { if (external) { return <StyledAnchor href={href} external {...rest} /> } if (isSlug) { return <StyledAnchor href={href} external isSlug {...rest} /> } return ( <Link prefetch={prefetch} href={href}> <StyledAnchor href={href} active={getPathname(pathname) === href} {...rest} /> </Link> ) } const solidColors = // @css {backgroundColor: colors.primaryMed, color: 'white'} const transparentColors = // @css { backgroundColor: 'rgba(255, 255, 255, 0.5)', color: colors.primary, } const secondaryButtonStyles = // @css {...transparentColors, ':hover': solidColors} const Button = glamorous(Anchor)( basicLinkStyles, { fontSize: '1em', border: `1px solid ${colors.primaryMed}`, width: '11em', padding: '0.7em 0', textDecoration: 'none', borderRadius: 4, display: 'inline-block', margin: '.5em 1em', transition: 'all .3s', ...solidColors, ':hover': transparentColors, }, props => ({...(props.secondary ? secondaryButtonStyles : {})}), ) export {Button, Anchor}
examples/async/index.js
dimaip/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/svg-icons/maps/local-taxi.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalTaxi = (props) => ( <SvgIcon {...props}> <path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5H15V3H9v2H6.5c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.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.5zM5 11l1.5-4.5h11L19 11H5z"/> </SvgIcon> ); MapsLocalTaxi = pure(MapsLocalTaxi); MapsLocalTaxi.displayName = 'MapsLocalTaxi'; MapsLocalTaxi.muiName = 'SvgIcon'; export default MapsLocalTaxi;
frontend/src/components/app.js
bhtucker/streamkov
import React from 'react' import VisibleChainList from '../containers/VisibleChainList' import Sampler from './Sampler' import UrlEntryBox from './UrlEntryBox' const App = () => ( <div> <h1>Streamkov</h1> <VisibleChainList /> <Sampler /> <UrlEntryBox /> </div> ) export default App
ui/src/components/footer.js
jollopre/mps
import React from 'react'; const style = { position: 'absolute', right: 0, bottom: 0, left:0, minHeight: '50px', padding: '1rem', textAlign: 'center', backgroundColor: '#222', color: '#fff', fontSize: 'small', }; export const Footer = function(){ return ( <div style={style}> <ul className="list-inline"> <li> &copy; {new Date().getFullYear()} <a className="text-warning" href="http://marshallpackaging.com" target="_blank" rel="noopener noreferrer"> Marshall Packaging Ltd </a> </li> <li>|</li> <li> <a className="text-warning" href="https://github.com/jollopre" target="_blank" rel="noopener noreferrer"> Powered by jollopre </a> </li> </ul> </div> ); }
src/index.js
weixing2014/iTodo
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' import todoApp from './reducers' import App from './components/App' let store = createStore(todoApp) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
app/src/components/AliasModal.js
GetStream/Winds
import React from 'react'; import PropTypes from 'prop-types'; import ReactModal from 'react-modal'; import { Img } from 'react-image'; import { connect } from 'react-redux'; import fetch from '../util/fetch'; import { getAliases } from '../api'; import saveIcon from '../images/icons/save.svg'; import exitIcon from '../images/buttons/exit.svg'; class AliasModal extends React.Component { constructor(props) { super(props); this.state = { error: false, submitting: false, success: false, }; } closeModal = () => { this.setState({ error: false, submitting: false, success: false }); this.props.toggleModal(); }; handleSubmit = (e) => { e.preventDefault(); const alias = new FormData(e.target).get('alias'); const id = this.props.isRss ? { rss: this.props.feedID } : { podcast: this.props.feedID }; this.setState({ submitting: true }); fetch('POST', '/aliases', { alias, ...id }) .then((res) => { if (res.data) { this.setState({ success: true, submitting: false }); getAliases(this.props.dispatch); setTimeout(() => this.closeModal(), 500); } }) .catch(() => this.setState({ error: true, submitting: false })); }; render() { let buttonText = 'SAVE'; if (this.state.submitting) { buttonText = 'Submitting...'; } else if (this.state.success) { buttonText = 'Success!'; } return ( <ReactModal className="modal add-new-content-modal" isOpen={this.props.isOpen} onRequestClose={this.closeModal} overlayClassName="modal-overlay" shouldCloseOnOverlayClick={true} > <header> <h1>Rename Feed</h1> <Img className="exit" onClick={this.closeModal} src={exitIcon} /> </header> <form onSubmit={this.handleSubmit}> <div className="input-box"> <input autoComplete="false" defaultValue={this.props.defVal} name="alias" placeholder="Enter new name" type="text" /> </div> {this.state.error && ( <div className="error-message"> Oops, something went wrong. Please try again later. </div> )} <div className="buttons"> <button className="btn primary alt with-circular-icon" disabled={this.state.submitting} type="submit" > <Img src={saveIcon} /> {buttonText} </button> <button className="btn link cancel" onClick={this.closeModal} type="cancel" > Cancel </button> </div> </form> </ReactModal> ); } } AliasModal.defaultProps = { isOpen: false, }; AliasModal.propTypes = { isOpen: PropTypes.bool, toggleModal: PropTypes.func.isRequired, defVal: PropTypes.string, isRss: PropTypes.bool, feedID: PropTypes.string, dispatch: PropTypes.func.isRequired, }; export default connect()(AliasModal);
docs/src/app/pages/components/Avatar/FallbackAvatar.js
GetAmbassador/react-ions
import React from 'react' import Avatar from 'react-ions/lib/components/Avatar' import Button from 'react-ions/lib/components/Button' import style from './style.scss' class ExampleAvatar extends React.Component { constructor(props) { super(props) } state = { letters: 'cf', size: '100' } randomize = () => { const possible = 'abcdefghijklmnopqrstuvwxyz' let letters = '' for (let i = 0; i < 2; i++) {letters += possible.charAt(Math.floor(Math.random() * possible.length))} const size = (Math.floor(Math.random() * 200) + 30).toString() this.setState({ letters, size }) } render = () => { return ( <div> <Avatar letters={this.state.letters} size={this.state.size} /> <div className={style['avatar-controls']}> <Button onClick={this.randomize}>Random letters/size</Button> </div> </div> ) } } export default ExampleAvatar
Libraries/TabBar/TabBar.web.js
brainpoint/citong-react-web
/** * Copyright (c) 2015-present, Alibaba Group Holding Limited. * All rights reserved. * * @providesModule ReactTabBar */ 'use strict'; import React from 'react'; import View from 'ReactView'; import TabBarItem from './TabBarItem.web'; import TabBarContents from './TabBarContents.web'; import assign from 'object-assign'; import StyleSheet from 'ReactStyleSheet'; let TabBar = React.createClass({ getInitialState() { return { selectedIndex: 0 }; }, statics: { Item: TabBarItem }, propTypes: { style: React.PropTypes.object, /** * Color of the currently selected tab icon */ tintColor: React.PropTypes.string, /** * Background color of the tab bar */ barTintColor: React.PropTypes.string, clientHeight: React.PropTypes.number }, getStyles() { return StyleSheet.create({ container: { width: '100%', height: this.props.clientHeight || document.documentElement.clientHeight, position: 'relative', overflow: 'hidden' }, content: { width: '100%', height: '100%' }, bar: { width: '100%', position: 'absolute', padding: 0, margin: 0, listStyle: 'none', left: 0, bottom: 0, // borderTop: '1px solid #e1e1e1', backgroundColor: 'rgba(250,250,250,.96)', display: 'table' } }); }, handleTouchTap(index) { this.setState({ selectedIndex: index }); }, render() { let self = this; let styles = self.getStyles(); let barStyle = assign(styles.bar, this.props.style || {}, this.props.barTintColor ? { backgroundColor: this.props.barTintColor } : {}); let tabContent = []; let tabs = React.Children.map(this.props.children, (tab, index) => { if (tab.type.displayName === 'TabBarItem') { if (tab.props.children) { tabContent.push(React.createElement(TabBarContents, { key: index, selected: self.state.selectedIndex === index }, tab.props.children)); } else { tabContent.push(undefined); } return React.cloneElement(tab, { index: index, selected: self.state.selectedIndex === index, selectedColor: self.props.tintColor, handleTouchTap: self.handleTouchTap }); } else { let type = tab.type.displayName || tab.type; throw 'Tabbar only accepts TabBar.Item Components as children. Found ' + type + ' as child number ' + (index + 1) + ' of Tabbar'; } }); return ( <View style={styles.container}> <View style={styles.content}>{tabContent}</View> <ul style={barStyle}> {tabs} </ul> </View> ); } }); TabBar.isReactNativeComponent = true; export default TabBar;
react-flux-mui/js/material-ui/src/svg-icons/av/replay.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/> </SvgIcon> ); AvReplay = pure(AvReplay); AvReplay.displayName = 'AvReplay'; AvReplay.muiName = 'SvgIcon'; export default AvReplay;
app/static/src/diagnostic/EquipmentForm_modules/NewManufacturerForm.js
SnowBeaver/Vision
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import Button from 'react-bootstrap/lib/Button'; import Panel from 'react-bootstrap/lib/Panel'; import {findDOMNode} from 'react-dom'; import { hashHistory } from 'react-router'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import {NotificationContainer, NotificationManager} from 'react-notifications'; var NewManufacturerForm = React.createClass({ getInitialState: function () { return { loading: false, errors: {}, fields: [ 'name', 'markings', 'location', 'description' ], changedFields: [] } }, _create: function () { var fields = this.state.changedFields; var data = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; var value = this.state[key]; if (value == ""){ value = null; } data[key] = value; } return $.authorizedAjax({ url: '/api/v1.0/manufacturer/', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _onSubmit: function (e) { e.preventDefault(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); return false; } var xhr = this._create(); xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading) }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { this.props.handleClose(); this.props.onCreate(data, this.props.fieldName); NotificationManager.success("Manufacturer added."); }, _onError: function (data) { var message = "Failed to create"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { // We get list of errors if (data.status >= 500) { message = res.error.join(". "); } else if (res.error instanceof Object){ // We get object of errors with field names as key for (var field in res.error) { var errorMessage = res.error[field]; if (Array.isArray(errorMessage)) { errorMessage = errorMessage.join(". "); } res.error[field] = errorMessage; } this.setState({ errors: res.error }); } else { message = res.error; } } NotificationManager.error(message); }, _onChange: function (e) { var state = {}; if (e.target.type == 'checkbox') { state[e.target.name] = e.target.checked; } else if (e.target.type == 'select-one') { state[e.target.name] = e.target.value; } else { state[e.target.name] = e.target.value; } state.changedFields = this.state.changedFields.concat([e.target.name]); var errors = this._validate(e); state = this._updateFieldErrors(e.target.name, state, errors); this.setState(state); }, _validate: function (e) { var errors = []; var error; error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type")); if (error){ errors.push(error); } error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len")); if (error){ errors.push(error); } return errors; }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/, "int": /^(-|\+)?(0|[1-9]\d*)$/ }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, _validateFieldLength: function (value, length){ var error = ""; if (value && length){ if (value.length > length){ error = "Value should be maximum " + length + " characters long" } } return error; }, _updateFieldErrors: function (fieldName, state, errors){ // Clear existing errors related to the current field as it has been edited state.errors = this.state.errors; delete state.errors[fieldName]; // Update errors with new ones, if present if (Object.keys(errors).length){ state.errors[fieldName] = errors.join(". "); } return state; }, is_valid: function () { return (Object.keys(this.state.errors).length <= 0); }, _formGroupClass: function (field) { var className = "form-group "; if (field) { className += " has-error" } return className; }, handleClick: function () { document.getElementById('test_prof').remove(); }, render: function () { return ( <div className="form-container"> <form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.name ? 'error' : null}> <FormControl type="text" placeholder="Name *" name="name" required data-len="50" /> <HelpBlock className="warning">{this.state.errors.name}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.markings ? 'error' : null}> <FormControl componentClass="textarea" placeholder="Markings" name="markings"/> <HelpBlock className="warning">{this.state.errors.markings}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.location ? 'error' : null}> <FormControl type="text" placeholder="Location" name="location" data-len="256" /> <HelpBlock className="warning">{this.state.errors.location}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.description ? 'error' : null}> <FormControl componentClass="textarea" placeholder="Description" name="description"/> <HelpBlock className="warning">{this.state.errors.description}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12 "> <Button bsStyle="success" className="pull-right" type="submit">Save</Button> &nbsp; <Button bsStyle="danger" className="pull-right margin-right-xs" onClick={this.props.handleClose} >Cancel</Button> </div> </div> </form> </div> ); } }); export default NewManufacturerForm;
src/lib/topics.js
trujunzhang/IEATTA-web
import Telescope from '../components/lib/index'; import React from 'react'; let _ = require('underscore'); const Topics = {}; export default Topics;
[3]. Demo_native/skin_demo/__tests__/index.ios.js
knightsj/RN_Demo
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
react/src/components/dashboard/settings/settings.daemonStdoutPanel.js
pbca26/EasyDEX-GUI
import React from 'react'; import translate from '../../../translate/translate'; import { connect } from 'react-redux'; import { coindGetStdout } from '../../../actions/actionCreators'; import Store from '../../../store'; class DaemonStdoutPanel extends React.Component { constructor() { super(); this.state = { coindStdOut: translate('INDEX.LOADING') + '...', coin: null, textareaHeight: '100px', }; this.getCoindGetStdout = this.getCoindGetStdout.bind(this); this.updateInput = this.updateInput.bind(this); } componentWillMount() { this.getCoindGetStdout(); } getCoindGetStdout() { const _coin = this.state.coin || this.props.ActiveCoin.coin; coindGetStdout(_coin) .then((res) => { this.setState({ coindStdOut: res.msg === 'success' ? res.result : `${translate('INDEX.ERROR_READING')} ${_coin} stdout`, }); setTimeout(() => { const _ta = document.querySelector('#settingsCoindStdoutTextarea'); _ta.style.height = '1px'; _ta.style.height = `${(15 + _ta.scrollHeight)}px`; }, 100); }); } updateInput(e) { this.setState({ [e.target.name]: e.target.value, }); this.getCoindGetStdout(); } renderCoinListSelectorOptions(coin) { let _items = []; let _nativeCoins = this.props.Main.coins.native; _nativeCoins.sort(); for (let i = 0; i < _nativeCoins.length; i++) { _items.push( <option key={ `coind-stdout-coins-${i}` } value={ `${_nativeCoins[i]}` }> { `${_nativeCoins[i]}` } </option> ); } return _items; } render() { return ( <div> <div className="row"> <div className="col-sm-12 padding-bottom-10"> <div> <div className="col-sm-3 no-padding-left"> <select className="form-control form-material" name="coin" value={ this.state.coin || this.props.ActiveCoin.coin || '' } onChange={ (event) => this.updateInput(event) } autoFocus> { this.renderCoinListSelectorOptions() } </select> </div> <div className="col-sm-1"> <i className="icon fa-refresh coind-stdout-refresh-icon pointer" onClick={ this.getCoindGetStdout }></i> </div> </div> </div> <div className="col-sm-12"> <div className="form-group form-material floating col-sm-8 no-padding-left"> <textarea readOnly id="settingsCoindStdoutTextarea" className="form-control settings-coind-stdout-textarea" value={ this.state.coindStdOut } style={{ height: this.state.textareaHeight }}></textarea> </div> </div> </div> </div> ); }; } const mapStateToProps = (state) => { return { ActiveCoin: { coin: state.ActiveCoin.coin, mode: state.ActiveCoin.mode, }, Main: state.Main, }; }; export default connect(mapStateToProps)(DaemonStdoutPanel);
src/components/ShareMenu/WaitingOverlay.js
Charlie9830/pounder
import React from 'react'; import { Modal, Grid, CircularProgress, Typography } from '@material-ui/core'; const WaitingOverlay = (props) => { let gridStyle = { width: '100%', height: '100%', } return ( <Modal open={props.open} disableAutoFocus={true}> <Grid container style={gridStyle} direction="column" justify="center" alignItems="center"> <Grid item> <CircularProgress /> </Grid> <Grid item> <Typography align="center" variant="h6"> {props.message} </Typography> </Grid> <Grid item style={{marginTop: '32px'}}> <Typography align="center" variant="h6"> {props.subMessage} </Typography> </Grid> </Grid> </Modal> ) } export default WaitingOverlay;
app/javascript/mastodon/components/domain.js
salvadorpla/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' }, }); export default @injectIntl class Account extends ImmutablePureComponent { static propTypes = { domain: PropTypes.string, onUnblockDomain: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleDomainUnblock = () => { this.props.onUnblockDomain(this.props.domain); } render () { const { domain, intl } = this.props; return ( <div className='domain'> <div className='domain__wrapper'> <span className='domain__domain-name'> <strong>{domain}</strong> </span> <div className='domain__buttons'> <IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} /> </div> </div> </div> ); } }
src/jsx/components/AddTransaction.js
luckychain/lucky
import React from 'react'; import Textarea from 'react-textarea-autosize'; import {Grid, Row, Col, Panel, FormGroup, Radio} from 'react-bootstrap'; import AppActions from '../actions/AppActions'; class AddTransaction extends React.Component { handleSubmit(event) { event.preventDefault(); var type = event.target.transactionType.value; var data = event.target.transactionData.value; if (!data) { AppActions.emptyTransaction(); this.refs.transactionDataField.focus(); } else { AppActions.addTransaction(type, data); } } render() { return ( <Grid> <Row> <Col sm={12}> <Panel header={(<h4>Add Transaction</h4>)}> <form onSubmit={this.handleSubmit.bind(this)}> <div className={'form-group ' + this.props.addTransactionState}> <label className="control-label">Transaction</label> <Textarea type="text" maxRows={20} className="form-control" name="transactionData" ref="transactionDataField" autoFocus /> <span className="help-block">{this.props.addTransactionHelp}</span> </div> <FormGroup> <Radio inline defaultChecked name="transactionType" value="data"> Data </Radio> {' '} <Radio inline name="transactionType" value="address"> IPFS Address </Radio> </FormGroup> <button type="submit" className="btn btn-primary">Submit</button> </form> </Panel> </Col> </Row> </Grid> ); } } export default AddTransaction;
node_modules/eslint-config-airbnb/test/test-react-order.js
edsrupp/eds-mess
import test from 'tape'; import { CLIEngine } from 'eslint'; import eslintrc from '../'; import baseConfig from '../base'; import reactRules from '../rules/react'; const cli = new CLIEngine({ useEslintrc: false, baseConfig: eslintrc, // This rule fails when executing on text. rules: {indent: 0}, }); function lint(text) { // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext return cli.executeOnText(text).results[0]; } function wrapComponent(body) { return ` import React from 'react'; export default class MyComponent extends React.Component { ${body} } `; } test('validate react prop order', t => { t.test('make sure our eslintrc has React linting dependencies', t => { t.plan(1); t.equal(reactRules.plugins[0], 'react', 'uses eslint-plugin-react'); }); t.test('passes a good component', t => { t.plan(3); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; } `)); t.notOk(result.warningCount, 'no warnings'); t.notOk(result.errorCount, 'no errors'); t.deepEquals(result.messages, [], 'no messages in results'); }); t.test('order: when random method is first', t => { t.plan(2); const result = lint(wrapComponent(` someMethod() {} componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', t => { t.plan(2); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); });
src/v2/stories/EmbeddedChannel.stories.js
aredotna/ervell
import React from 'react' import { storiesOf } from '@storybook/react' import Specimen from 'v2/stories/__components__/Specimen' import { EmbeddedChannel } from 'v2/pages/channel/EmbeddedChannelPage/components/EmbeddedChannel' storiesOf('EmbeddedChannel', module).add('default', () => ( <Specimen> <EmbeddedChannel id="hello" /> </Specimen> ))
react/L3/src/pages/Child.js
luolisave/starters
import React from 'react'; import {bindActionCreators} from 'redux'; import { connect } from 'react-redux'; import uuidv4 from 'uuid/v4'; // functions, should put to seperate file later. function clone(obj) { if (null === obj || "object" !== typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; } //Functions, should put to seperate file later. var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth']; var deca = ['twent', 'thirt', 'fort', 'fift', 'sixt', 'sevent', 'eight', 'ninet']; function stringifyNumber(n) { if (n < 20) return special[n]; if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth'; return deca[Math.floor(n/10)-2] + 'y-' + special[n%10]; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } //component class Child extends React.Component { child = {}; componentDidMount(){ this.child = clone(this.props.child); console.log("this.child = ", this.child); } render() { if(this.props.child.saved){ return ( <div className="childRow"> <div className="row"> <div className="col col-sm-2"> <h4>{capitalizeFirstLetter(stringifyNumber(this.props.myindex+1))} Child</h4> <p><a className="removeBtn" onClick={()=>{ this.props.removeChild(this.props.child); }} >Remove</a></p> </div> <div className="col col-sm-2"> First Name: <input type="text" name="first" defaultValue={this.props.child.first} disabled /> </div> <div className="col col-sm-2"> Last Name: <input type="text" name="last" defaultValue={this.props.child.last} disabled /> </div> <div className="col col-sm-2"> </div> </div> </div> ); }else{ return ( <div className="childRow"> <div className="row"> <div className="col col-sm-2"> <h4>{capitalizeFirstLetter(stringifyNumber(this.props.myindex+1))} Child</h4> <p><a className="removeBtn" onClick={ ()=>{ this.props.removeChild(this.props.child); this.props.resetHasMoreChildRadio(); } } >Remove</a></p> </div> <div className="col col-sm-2"> First Name: <input type="text" name="first" defaultValue={this.props.child.first} onChange={(event)=>{ this.child.first = event.target.value; console.log("child = ",this.child, " ||| event.target.value = ", event.target.value, " ||| uuidv4 = ", uuidv4()); }} /> </div> <div className="col col-sm-2"> Last Name: <input type="text" name="last" defaultValue={this.props.child.last} onChange={(event)=>{ this.child.last = event.target.value; console.log("child = ",this.child, " ||| event.target.value = ", event.target.value, " ||| uuidv4 = ", uuidv4()); }} /> </div> </div> <div className="row"> <div className="col col-sm-2"></div> <div className="col col-sm-2"></div> <div className="col col-sm-2"> <p>&nbsp; &nbsp;</p> <button title="Cancel" className="btn btn-primary">Cancel</button> &nbsp; &nbsp; <button title="Save" className="btn btn-primary" onClick={ (event)=>{ console.log("!!! this.props.children", this.props.children); //let myChildren = clone(this.props.children); //myChildren.push(this.child); //console.log("!!! myChildren", myChildren); this.props.saveChild(this.child); this.props.resetHasMoreChildRadio(); } }>Save</button></div> </div> </div> ); } } } function mapStateToProps(state) { return { children: state.children } } // Get actions and pass them as props to to UserList // > now UserList has this.props.selectUser function matchDispatchToProps(dispatch){ return bindActionCreators( { saveChild: function(payload) { console.log("action: Should Save Child to Children Reducer."); return { type: 'SAVE_CHILD', payload: payload } }, removeChild: function(payload) { console.log("action: Should Save Child to Children Reducer."); return { type: 'REMOVE_CHILD', payload: payload } } }, dispatch ); } export default connect(mapStateToProps, matchDispatchToProps)(Child); //export default Child;
src/containers/Asians/TabControls/PreliminaryRounds/EnterRoundResults/TraineeFeedback/index.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import Instance from './Instance' import ListSubheader from 'material-ui/List/ListSubheader' export default connect(mapStateToProps)(({ round, rooms, adjudicatorScores }) => { const filterRooms = roomToMatch => roomToMatch.round === round._id const roomsThisRound = rooms.filter(filterRooms) const adjudicatorScoresThisRound = adjudicatorScores.filter(filterRooms) const arr = [] roomsThisRound.forEach(room => { if (room.trainees.length > 0) { arr.push( <Instance key={room._id} room={room} adjudicatorScoresThisRound={adjudicatorScoresThisRound} /> ) } }) return ( <div> {arr.length > 0 && <ListSubheader disableSticky > {'Trainee feedback'} </ListSubheader> } {arr} </div> ) }) function mapStateToProps (state, ownProps) { return { rooms: Object.values(state.rooms.data), adjudicatorScores: Object.values(state.adjudicatorScores.data) } }
js/Details.js
aurimas-darguzis/react-intro
import React from 'react' import { connect } from 'react-redux' import { getOMDBDetails } from './actionCreators' import Header from './Header' const { shape, string, func } = React.PropTypes const Details = React.createClass({ propTypes: { show: shape({ title: string, year: string, poster: string, trailer: string, description: string, imdbID: string }), omdbData: shape({ imdbID: string }), dispatch: func }, componentDidMount () { if (!this.props.omdbData.imdbRating) { this.props.dispatch(getOMDBDetails(this.props.show.imdbID)) } }, render () { const { title, description, year, poster, trailer } = this.props.show let rating if (this.props.omdbData.imdbRating) { rating = <h3>{this.props.omdbData.imdbRating}</h3> } else { rating = <img src='/public/img/loading.png' alt='loading indicator' /> } return ( <div className='details'> <Header /> <section> <h1>{title}</h1> <h2>({year})</h2> {rating} <img src={`/public/img/posters/${poster}`} /> <p>{description}</p> </section> <div> <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&amp;controls=0&amp;showinfo=0`} frameBorder='0' allowFullScreen /> </div> </div> ) } }) const mapStateToProps = (state, ownProps) => { const omdbData = state.omdbData[ownProps.show.imdbID] ? state.omdbData[ownProps.show.imdbID] : {} return { omdbData } } export default connect(mapStateToProps)(Details)
src/svg-icons/editor/vertical-align-bottom.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignBottom = (props) => ( <SvgIcon {...props}> <path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z"/> </SvgIcon> ); EditorVerticalAlignBottom = pure(EditorVerticalAlignBottom); EditorVerticalAlignBottom.displayName = 'EditorVerticalAlignBottom'; export default EditorVerticalAlignBottom;
assets/node_modules/recompose/renderComponent.js
janta-devs/nyumbani
'use strict'; exports.__esModule = true; var _createHelper = require('./createHelper'); var _createHelper2 = _interopRequireDefault(_createHelper); var _createEagerFactory = require('./createEagerFactory'); var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // import React from 'react' var renderComponent = function renderComponent(Component) { return function (_) { var factory = (0, _createEagerFactory2.default)(Component); var RenderComponent = function RenderComponent(props) { return factory(props); }; // const RenderComponent = props => <Component {...props} /> if (process.env.NODE_ENV !== 'production') { /* eslint-disable global-require */ var wrapDisplayName = require('./wrapDisplayName').default; /* eslint-enable global-require */ RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent'); } return RenderComponent; }; }; exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false);
frontend/src/main/web/src/legacy.js
mvehar/zanata-server
/* * Copyright 2016, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { mapValues } from 'lodash' import { Icons } from './components' import WebFont from 'webfontloader' import Nav from './components/Nav' import './styles/base.css' import './styles/atomic.css' import './styles/extras.css' import { isJsonString } from './utils/StringUtils' /** * Root component that display only side menu bar. * Used jsf page that only needs side menu bar from frontend. */ WebFont.load({ google: { families: [ 'Source Sans Pro:200,400,600', 'Source Code Pro:400,600' ] }, timeout: 2000 }) window.config = mapValues(window.config, (value) => isJsonString(value) ? JSON.parse(value) : value) // baseUrl should be /zanata or '' window.config.baseUrl = window.config.baseUrl || '' const links = { 'context': window.config.baseUrl, '/login': window.config.links.loginUrl, '/signup': window.config.links.registerUrl } const activePath = window.location.pathname render( <div className='H(a) H(100%)--sm'> <Icons /> <Nav active={activePath} isJsfPage links={links} /> </div> , document.getElementById('root') )
src/BasicHtmlEditor.js
dburrows/draft-js-basic-html-editor
import React from 'react'; import ReactDOM from 'react-dom'; import debounce from 'lodash/debounce'; import { Editor, EditorState, ContentState, Entity, RichUtils, convertToRaw, CompositeDecorator, Modifier } from 'draft-js'; import htmlToContent from './utils/htmlToContent'; import draftRawToHtml from './utils/draftRawToHtml'; import Link from './components/Link'; import EntityControls from './components/EntityControls'; import InlineStyleControls from './components/InlineStyleControls'; import BlockStyleControls from './components/BlockStyleControls'; import findEntities from './utils/findEntities'; export default class BasicHtmlEditor extends React.Component { constructor(props) { super(props); let { value } = props; const decorator = new CompositeDecorator([ { strategy: findEntities.bind(null, 'link'), component: Link } ]); this.ENTITY_CONTROLS = [ {label: 'Add Link', action: this._addLink.bind(this) }, {label: 'Remove Link', action: this._removeLink.bind(this) } ]; this.INLINE_STYLES = [ {label: 'Bold', style: 'BOLD'}, {label: 'Italic', style: 'ITALIC'}, {label: 'Underline', style: 'UNDERLINE'}, {label: 'Monospace', style: 'CODE'}, {label: 'Strikethrough', style: 'STRIKETHROUGH'} ]; this.BLOCK_TYPES = [ {label: 'P', style: 'unstyled'}, {label: 'H1', style: 'header-one'}, {label: 'H2', style: 'header-two'}, {label: 'Blockquote', style: 'blockquote'}, {label: 'UL', style: 'unordered-list-item'}, {label: 'OL', style: 'ordered-list-item'}, {label: 'Code Block', style: 'code-block'} ]; this.state = { editorState: value ? EditorState.createWithContent( ContentState.createFromBlockArray(htmlToContent(value)), decorator ) : EditorState.createEmpty(decorator) }; // this.focus = () => this.refs.editor.focus(); this.onChange = (editorState) => { let previousContent = this.state.editorState.getCurrentContent(); this.setState({editorState}); // only emit html when content changes if( previousContent !== editorState.getCurrentContent() ) { this.emitHTML(editorState); } }; function emitHTML(editorState) { let raw = convertToRaw( editorState.getCurrentContent() ); let html = draftRawToHtml(raw); this.props.onChange(html); } this.emitHTML = debounce(emitHTML, this.props.debounce); this.handleKeyCommand = (command) => this._handleKeyCommand(command); this.toggleBlockType = (type) => this._toggleBlockType(type); this.toggleInlineStyle = (style) => this._toggleInlineStyle(style); this.handleReturn = (e) => this._handleReturn(e); this.addLink = this._addLink.bind(this); this.removeLink = this._removeLink.bind(this); } _handleKeyCommand(command) { const {editorState} = this.state; const newState = RichUtils.handleKeyCommand(editorState, command); if (newState) { this.onChange(newState); return true; } return false; } _handleReturn(e) { if (e.metaKey === true) { return this._addLineBreak(); } else { return false; } } _toggleBlockType(blockType) { this.onChange( RichUtils.toggleBlockType( this.state.editorState, blockType ) ); } _toggleInlineStyle(inlineStyle) { this.onChange( RichUtils.toggleInlineStyle( this.state.editorState, inlineStyle ) ); } _addLineBreak(/* e */) { let newContent, newEditorState; const {editorState} = this.state; const content = editorState.getCurrentContent(); const selection = editorState.getSelection(); const block = content.getBlockForKey(selection.getStartKey()); console.log(content.toJS(), selection.toJS(), block.toJS()); if (block.type === 'code-block') { newContent = Modifier.insertText(content, selection, '\n'); newEditorState = EditorState.push(editorState, newContent, 'add-new-line'); this.onChange(newEditorState); return true; } else { return false; } } _addLink(/* e */) { const {editorState} = this.state; const selection = editorState.getSelection(); if (selection.isCollapsed()) { return; } const href = window.prompt('Enter a URL'); const entityKey = Entity.create('link', 'MUTABLE', {href}); this.onChange(RichUtils.toggleLink(editorState, selection, entityKey)); } _removeLink(/* e */) { const {editorState} = this.state; const selection = editorState.getSelection(); if (selection.isCollapsed()) { return; } this.onChange( RichUtils.toggleLink(editorState, selection, null)); } render() { const {editorState} = this.state; // If the user changes block type before entering any text, we can // either style the placeholder or hide it. Let's just hide it now. let className = 'RichEditor-editor'; var contentState = editorState.getCurrentContent(); if (!contentState.hasText()) { if (contentState.getBlockMap().first().getType() !== 'unstyled') { className += ' RichEditor-hidePlaceholder'; } } return ( <div className="RichEditor-root draftjs-bhe"> <BlockStyleControls editorState={editorState} blockTypes={this.BLOCK_TYPES} onToggle={this.toggleBlockType} /> <InlineStyleControls editorState={editorState} onToggle={this.toggleInlineStyle} inlineStyles={this.INLINE_STYLES} /> <EntityControls editorState={editorState} entityControls={this.ENTITY_CONTROLS} /> <div className={className} /* onClick={this.focus} */> <Editor blockStyleFn={getBlockStyle} customStyleMap={styleMap} editorState={editorState} handleKeyCommand={this.handleKeyCommand} handleReturn={this.handleReturn} onChange={this.onChange} placeholder="Tell a story..." ref="editor" spellCheck={true} /> </div> </div> ); } } // Custom overrides for "code" style. const styleMap = { CODE: { backgroundColor: 'rgba(0, 0, 0, 0.05)', fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', fontSize: 16, padding: 2 } }; function getBlockStyle(block) { switch (block.getType()) { case 'blockquote': return 'RichEditor-blockquote'; default: return null; } }
app/react-icons/fa/gift.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaGift extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m23.7 30.3v-16h-7.1v16q0 0.5 0.4 0.8t1 0.3h4.3q0.6 0 1-0.3t0.4-0.8z m-10.2-18.9h4.4l-2.8-3.6q-0.6-0.7-1.6-0.7-0.9 0-1.5 0.7t-0.6 1.5 0.6 1.5 1.5 0.6z m15.4-2.1q0-0.9-0.6-1.5t-1.6-0.7q-0.9 0-1.5 0.7l-2.8 3.6h4.4q0.8 0 1.5-0.6t0.6-1.5z m8.4 5.7v7.1q0 0.4-0.2 0.6t-0.5 0.2h-2.2v9.2q0 0.9-0.6 1.6t-1.5 0.6h-24.3q-0.9 0-1.5-0.6t-0.6-1.6v-9.2h-2.2q-0.3 0-0.5-0.2t-0.2-0.6v-7.1q0-0.3 0.2-0.5t0.5-0.2h9.8q-2 0-3.5-1.5t-1.5-3.5 1.5-3.6 3.5-1.4q2.4 0 3.8 1.7l2.8 3.7 2.9-3.7q1.4-1.7 3.8-1.7 2 0 3.5 1.4t1.4 3.6-1.4 3.5-3.6 1.5h9.9q0.3 0 0.5 0.2t0.2 0.5z"/></g> </IconBase> ); } }
template/src/renderer/components/tempaltes/Main/Main.js
my-dish/template-electron
// @flow import React from 'react'; import styles from './style.css'; type Props = { left: React.Component<*>; right: React.Component<*>; children: React.Component<*>; }; const Main = (props: Props) => ( <div className={styles.container}> <div className={styles.left}>{props.left}</div> { props.children } <div className={styles.right}>{props.right}</div> </div> ); export default Main;
hello world/1.7 - router/src/components/routerList.js
wumouren/react-demo
import React from 'react'; export default class IndexList extends React.Component{ render(){ return ( <div> <h1>这是主要内容列表</h1> </div> ) } }
frontend/node_modules/react-recaptcha/example/main.js
andres81/auth-service
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import Recaptcha from '../src'; // site key const sitekey = 'xxxxxxx'; // specifying your onload callback function const callback = () => { console.log('Done!!!!'); }; const verifyCallback = (response) => { console.log(response); }; const expiredCallback = () => { console.log(`Recaptcha expired`); }; // define a variable to store the recaptcha instance let recaptchaInstance; // handle reset const resetRecaptcha = () => { recaptchaInstance.reset(); }; class App extends React.Component { render() { return ( <div> <h1>Google Recaptcha</h1> <Recaptcha ref={e => recaptchaInstance = e} sitekey={sitekey} size="compact" render="explicit" verifyCallback={verifyCallback} onloadCallback={callback} expiredCallback={expiredCallback} /> <br/> <button onClick={resetRecaptcha} > Reset </button> </div> ); } } ReactDOM.render(<App />, document.getElementById('app'));
test/specs/addons/Select/Select-test.js
mohammed88/Semantic-UI-React
import React from 'react' import Select from 'src/addons/Select/Select' import Dropdown from 'src/modules/Dropdown/Dropdown' import * as common from 'test/specs/commonTests' const requiredProps = { options: [], } describe('Select', () => { common.isConformant(Select, requiredProps) common.hasSubComponents(Select, [Dropdown.Divider, Dropdown.Header, Dropdown.Item, Dropdown.Menu]) it('renders a selection Dropdown', () => { shallow(<Select {...requiredProps} />) .first() .should.contain(<Dropdown {...requiredProps} selection />) }) })
client/extensions/woocommerce/app/promotions/fields/checkbox-field.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { omit } from 'lodash'; /** * Internal dependencies */ import FormCheckbox from 'components/forms/form-checkbox'; import FormField from './form-field'; const CheckboxField = props => { const { fieldName, explanationText, placeholderText, value, edit } = props; const renderedValue = 'undefined' !== typeof value ? value : false; const onChange = () => { edit( fieldName, ! value ); }; return ( <FormField { ...omit( props, 'explanationText' ) }> <FormCheckbox id={ fieldName + '-label' } aria-describedby={ explanationText && fieldName + '-description' } checked={ renderedValue } placeholder={ placeholderText } onChange={ onChange } /> <span>{ explanationText }</span> </FormField> ); }; CheckboxField.propTypes = { fieldName: PropTypes.string, explanationText: PropTypes.string, placeholderText: PropTypes.string, value: PropTypes.bool, edit: PropTypes.func, }; export default CheckboxField;
old_examples/conditional/app.js
reactjs/react-tabs
import React from 'react'; import { render } from 'react-dom'; import { Tab, Tabs, TabList, TabPanel } from '../../src/index'; import '../../style/react-tabs.css'; class App extends React.Component { constructor(props) { super(props); this.state = { showA: true, showB: true, showC: true, }; } handleCheckClicked = (e) => { this.setState({ [e.target.name]: e.target.checked, }); } render() { return ( <div style={{ padding: 50 }}> <p> <label> <input type="checkbox" checked={this.state.showA} name="showA" onChange={this.handleCheckClicked} /> Show A </label><br /> <label> <input type="checkbox" checked={this.state.showB} name="showB" onChange={this.handleCheckClicked} /> Show B </label><br /> <label> <input type="checkbox" checked={this.state.showC} name="showC" onChange={this.handleCheckClicked} /> Show C </label><br /> </p> <Tabs> <TabList> {this.state.showA && <Tab>Tab A</Tab>} {this.state.showB && <Tab>Tab B</Tab>} {this.state.showC && <Tab>Tab C</Tab>} </TabList> {this.state.showA && <TabPanel>This is tab A</TabPanel>} {this.state.showB && <TabPanel>This is tab B</TabPanel>} {this.state.showC && <TabPanel>This is tab C</TabPanel>} </Tabs> </div> ); } } render(<App />, document.getElementById('example'));
src/svg-icons/maps/directions-bike.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsBike = (props) => ( <SvgIcon {...props}> <path d="M15.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5zm5.8-10l2.4-2.4.8.8c1.3 1.3 3 2.1 5.1 2.1V9c-1.5 0-2.7-.6-3.6-1.5l-1.9-1.9c-.5-.4-1-.6-1.6-.6s-1.1.2-1.4.6L7.8 8.4c-.4.4-.6.9-.6 1.4 0 .6.2 1.1.6 1.4L11 14v5h2v-6.2l-2.2-2.3zM19 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5z"/> </SvgIcon> ); MapsDirectionsBike = pure(MapsDirectionsBike); MapsDirectionsBike.displayName = 'MapsDirectionsBike'; MapsDirectionsBike.muiName = 'SvgIcon'; export default MapsDirectionsBike;
src/containers/__tests__/views/browse-view-test.js
yursky/recommend
/** * Test to check if the component renders correctly */ /* global it expect */ import 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import BrowseView from '@containers/recipes/Browse/BrowseView'; it('BrowseView renders correctly', () => { // getMeals prop expects a promise const mockPromise = new Promise((resolve) => { resolve(); }); const tree = renderer.create( <BrowseView getMeals={() => mockPromise} />, ).toJSON(); expect(tree).toMatchSnapshot(); });
src/Thumbnail.js
Cellule/react-bootstrap
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Thumbnail = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'thumbnail' }; }, render() { let classes = this.getBsClassSet(); if(this.props.href) { return ( <a {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </a> ); } else { if(this.props.children) { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> <div className="caption"> {this.props.children} </div> </div> ); } else { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </div> ); } } } }); export default Thumbnail;
test/test-cases/public-path/src/app.js
seek-oss/sku
import React from 'react'; import styles from './app.less'; export default () => <div className={styles.root} />;
pages/profile.js
vinaypuppal/linklet-app
import React from 'react' import NProgress from 'nprogress' import Header from '../components/Header' import FaGithub from 'react-icons/lib/fa/github' import FaSignOut from 'react-icons/lib/fa/sign-out' import ContainerPage from '../hocs/ContainerPage' import PublicPage from '../hocs/PublicPage' import { login, logout } from '../utils/authenticate' class Profile extends React.Component { render () { return ( <div className='Profile'> <Header user={this.props.user} url={this.props.url} title='Linklet | Profile' /> <main> <p className='info'> {this.props.url.query && this.props.url.query.next === '/my-links' ? 'Please login to view links added by you!...' : this.props.url.query && this.props.url.query.next === '/submit-link' ? 'Please login to submit new link' : this.props.url.query && this.props.url.query.next === '/bookmarks' ? 'Please login to view links bookmarked by you!..' : ''} </p> {this.props.isAuthenticated ? ( <div className='actual'> <div className='avatar'> <img src={`//images.weserv.nl/?url=${this.props.user.avatarUrl .replace('http://', '') .replace('https://', '')}&w=180&h=180&shape=circle`} alt={this.props.username} /> </div> <div className='username'>@{this.props.user.username}</div> {this.props.user.name && ( <div className='name'> <span className='label'>Name</span> <span className='value'>{this.props.user.name}</span> </div> )} {this.props.user.email && ( <div className='email'> <span className='label'>Email</span> <span className='value'>{this.props.user.email}</span> </div> )} <button onClick={() => { NProgress.start() logout() }} > <FaSignOut size={20} /> <span>LogOut</span> </button> </div> ) : ( <div className='dummy'> <div className='avatar' /> <div className='info'> <div className='name' /> <div className='links-shared' /> <div className='notifications' /> </div> <button onClick={() => { NProgress.start() login() }} > <FaGithub size={40} /> <span>Login With Github</span> </button> </div> )} </main> <style jsx> {` .Profile { min-height: 100%; width: 100%; } main { padding: 70px 20px 20px 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } p.info { font-weight: bold; } .dummy .avatar { width: 150px; height: 150px; border-radius: 50%; background: rgba(37, 53, 146, 0.1); margin: 10px auto; } .dummy .name, .dummy .links-shared, .dummy .notifications { width: 280px; height: 20px; background: rgba(37, 53, 146, 0.1); margin: 10px auto; border-radius: 4px; } .dummy .links-shared { width: 250px; } .dummy .notifications { width: 200px; } .actual .avatar img { border-radius: 50%; margin: 20px auto; } .actual .username { font-weight: 600; font-size: 24px; margin: 20px auto; } .actaul .name, .actual .email { margin: 20px auto; } .actual .label { margin-right: 20px; font-weight: bold; } button { width: 100%; margin: 50px 0; border: none; outline: none; -webkit-appearence: none; padding: 10px 20px; color: #fff; font-size: 16px; text-transform: uppercase; background: #222; border-radius: 4px; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); cursor: pointer; } button span { padding: 0 5px; } button:hover { background: #111; } .actual button { background: #f1f2f3; color: #222; font-size: 12px; padding: 10px; } .actual button:hover { background: rgba(37, 53, 146, 0.1); } @media (max-width: 720px) { main { padding-bottom: 60px; } .dummy .avatar, .dummy .name, .dummy .links-shared, .dummy .notifications { margin: 10px auto; } .dummy .avatar { width: 100px; height: 100px; } .dummy button { margin: 20px auto; } .actual .avatar { margin: 0 auto; text-align: center; } .actual .avatar img { margin: 0 auto 10px auto; width: 100px; height: 100px; } } `} </style> </div> ) } } export default ContainerPage(PublicPage(Profile))
client/app/components/playerList.js
dat2/hanabi-clone-web
import React from 'react' import Player from './player' class PlayerList extends React.Component { render() { let { players } = this.props return ( <div> { players.map((p, pI) => ( <Player key={pI} player={p} playerIndex={pI} /> )) } </div> ) } } PlayerList.defaultProps = { players: [] } export default PlayerList
pages/sass.js
murej/ansambel
import React from 'react' import './example.scss' import DocumentTitle from 'react-document-title' import { config } from 'config' export default class Sass extends React.Component { render () { return ( <DocumentTitle title={`${config.siteTitle} | Hi sassy friends`}> <div> <h1 className="the-sass-class" > Hi sassy friends </h1> <div className="sass-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> </DocumentTitle> ) } }
MobileApp/node_modules/react-native/local-cli/templates/HelloNavigation/views/welcome/WelcomeScreen.js
VowelWeb/CoinTradePros.com
'use strict'; import React, { Component } from 'react'; import { Image, Platform, StyleSheet, } from 'react-native'; import ListItem from '../../components/ListItem'; import WelcomeText from './WelcomeText'; export default class WelcomeScreen extends Component { static navigationOptions = { title: 'Welcome', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./welcome-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } render() { return ( <WelcomeText /> ); } } const styles = StyleSheet.create({ icon: { width: 30, height: 26, }, });
internals/templates/appContainer.js
jdm85kor/sentbe
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
examples/todomvc/index.js
hetony/redux-devtools
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
frontend/src/containers/HomePage.js
OpenCollective/opencollective-website
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Numbro from 'numbro'; import 'numbro/dist/languages' import formatCurrency from '../lib/format_currency'; import i18n from '../lib/i18n'; import LoginTopBar from '../containers/LoginTopBar'; import MailChimpInputSection from '../components/homepage/MailChimpInputSection'; import PublicFooter from '../components/PublicFooter'; import CollectiveCard from '../components/CollectiveCard'; import fetchHome from '../actions/homepage/fetch'; export class HomePage extends Component { constructor(props) { super(props); this.state = { showSponsorMailInput: false }; } componentDidMount() { const { fetchHome, loadData} = this.props; if (loadData) { fetchHome(); } } render() { const { homepage, i18n } = this.props; const { showSponsorMailInput } = this.state; const currency = 'USD'; const opensource = homepage.collectives ? homepage.collectives.opensource : []; const meetup = homepage.collectives ? homepage.collectives.meetup : []; const sponsors = homepage.sponsors ? homepage.sponsors : []; const totalCollectives = homepage.stats ? homepage.stats.totalCollectives : 0; const totalAnnualBudget = homepage.stats ? homepage.stats.totalAnnualBudget : 0; const totalDonors = homepage.stats ? homepage.stats.totalDonors : 0; return ( <div className='HomePage'> <LoginTopBar /> <section className='HomePageHero'> <div className='title'> <svg width='500px' height='70px' className='align-middle'> <use xlinkHref='#svg-logotype' fill='#303233'/> </svg> </div> <div className='subtitle'>A new form of association, transparent by design</div> <div className='heading'>Open your finances to your community</div> </section> <section className='HomePageInfo' id='howitworks'> <div className='heading'>What is an open collective?</div> <div className='subheading'>A group of people with a shared mission that operates in full transparency</div> <div className='icons-container clearfix'> <div className='col sm-col-6 md-col-4'> <div className='-graphic -tghost'>&nbsp;</div> <div className='-heading'>Transparent</div> <div className='-description'>Anyone can follow the money.</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -oc'>&nbsp;</div> <div className='-heading'>Open</div> <div className='-description'>Anyone is welcome to join and contribute.</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -fluid'>&nbsp;</div> <div className='-heading'>Fluid</div> <div className='-description'>Leaders can change over time.</div> </div> </div> </section> <section className='HomePageOpenSource blue-gradient' id='opensource'> <div className='heading'>Collectives for <span className='color-blue'>Open Source</span> projects</div> <div className='subheading'>These open source projects have created open collectives to share their expenses and let their community chip in.</div> <div className='cards'> {opensource.map(group => <CollectiveCard key={group.id} i18n={i18n} group={group} />)} <a href='/opensource' className='seemore'>See more collectives</a> </div> <div className='cta'> <div className='text'>Have an open source project?</div> <a href='/opensource/apply'> <div className='button color-blue'>apply to create a collective!</div> </a> </div> </section> <section className='HomePageMeetups blue-gradient' id='meetups'> <div className='heading'>Collectives for <span className='color-green'>meetups</span></div> <div className='subheading'>Open Collective empowers local meetups to raise funds and have their own budget.</div> <div className='cards'> {meetup.map(group => <CollectiveCard key={group.id} i18n={i18n} group={group} />)} <a href='/discover?show=meetup' className='seemore'>See more meetups</a> </div> <div className='cta' id='apply'> <div className='text'>We are slowly letting in new kinds of collectives</div> <div className='button color-green'>join the waiting list!</div> </div> </section> <MailChimpInputSection mcListId='14d6233180' /> <section className='HomePageSponsors blue-gradient' id='sponsors'> <div className='heading'>Sponsors</div> <div className='subheading'>Great companies support great collectives with ❤️</div> <div className='cards'> {sponsors.map(sponsor => <CollectiveCard key={sponsor.id} i18n={i18n} publicUrl={`/${sponsor.slug}`} isSponsor={true} group={sponsor} />)} </div> <div className='cta'> <div className='text'>Become a sponsor and support your community</div> <div className='button color-green' onClick={() => this.setState({showSponsorMailInput: !showSponsorMailInput})}>become a sponsor</div> </div> </section> {showSponsorMailInput && <MailChimpInputSection mcListId='4cbda7da19' buttonLabel='Apply' />} <section className='HomePageNumber'> <div className='heading'>Open Numbers</div> <div className='numbers-container'> <div className='clearfix'> <div className='col sm-col-6 md-col-4'> <div className='-graphic -tghost'> <div className='-value'>{Numbro(totalCollectives).format('0,0')}</div> </div> <div className='-heading'>Collectives</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -oc'> <div className='-value'>{Numbro(totalDonors).format('0,0')}</div> </div> <div className='-heading'>Backers</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -fluid'> <div className='-value'>{formatCurrency(totalAnnualBudget, currency, { compact: true, precision: 0 })}</div> </div> <div className='-heading'>Annual budget</div> </div> </div> </div> </section> <PublicFooter /> </div> ) } } export default connect(mapStateToProps, { fetchHome })(HomePage); function mapStateToProps({ homepage, app}) { return { homepage, i18n: i18n('en'), loadData: app.rendered } }
src/client/home/components/FilterOptions/FilterOptions.js
noahamar/smlscrn
import R from 'ramda'; import React from 'react'; import classNames from 'classnames/bind'; import styles from './FilterOptions.styl'; const cx = classNames.bind(styles); export default class FilterOptions extends React.Component { constructor() { super(); } render() { const options = this.props.options || []; this.options = options .map(R.fromPairs) .map((item, i) => { return ( <option className={cx('FilterOptions__option')} key={item.id} value={item.id}> {item.label} </option>); }); return ( <div className={cx('FilterOptions')}> <select className={cx('FilterOptions__select')} onChange={this.props.onChange} value={this.props.selected}> { this.options } </select> <div className={cx('FilterOptions__triangle')}>&#9662;</div> </div> ); } }
src/components/Feedback/Feedback.js
lagache/e-voting-client
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.scss'; function Feedback() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit" >Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new" >Report an issue</a> </div> </div> ); } export default withStyles(Feedback, s);
react/features/base/components/buttons/QuickActionButton.js
jitsi/jitsi-meet
// @flow import { makeStyles } from '@material-ui/styles'; import React from 'react'; type Props = { /** * Label used for accessibility. */ accessibilityLabel: string, /** * Additional class name for custom styles. */ className: string, /** * Children of the component. */ children: string | React$Node, /** * Click handler. */ onClick: Function, /** * Data test id. */ testId?: string } const useStyles = makeStyles(theme => { return { button: { backgroundColor: theme.palette.action01, color: theme.palette.text01, borderRadius: `${theme.shape.borderRadius}px`, ...theme.typography.labelBold, lineHeight: `${theme.typography.labelBold.lineHeight}px`, padding: '8px 12px', display: 'flex', justifyContent: 'center', alignItems: 'center', border: 0, '&:hover': { backgroundColor: theme.palette.action01Hover } } }; }); const QuickActionButton = ({ accessibilityLabel, className, children, onClick, testId }: Props) => { const styles = useStyles(); return (<button aria-label = { accessibilityLabel } className = { `${styles.button} ${className}` } data-testid = { testId } onClick = { onClick }> {children} </button>); }; export default QuickActionButton;
examples/src/components/DisabledUpsellOptions.js
darrindickey/chc-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, onLabelClick: function (data, event) { console.log(data, event); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span>{option.label} {option.link} </span>; }, render: function() { var ops = [ { label: 'Basic customer support', value: 'basic' }, { label: 'Premium customer support', value: 'premium' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select onOptionLabelClick={this.onLabelClick} placeholder="Select your support level" options={ops} optionRenderer={this.renderOption} onChange={logChange} /> </div> ); } }); module.exports = DisabledUpsellOptions;
docs/src/pages/customization/TypographyTheme.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; function theme(outerTheme) { return createMuiTheme({ typography: { fontFamily: '-apple-system,system-ui,BlinkMacSystemFont,' + '"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif', body1: { fontWeight: outerTheme.typography.fontWeightMedium, }, button: { fontStyle: 'italic', }, }, }); } function TypographyTheme() { return ( <MuiThemeProvider theme={theme}> <div> <Typography type="body1">{'body1'}</Typography> <Button>{'Button'}</Button> </div> </MuiThemeProvider> ); } export default TypographyTheme;
src/index.js
ChronoBank/ChronoWAVES
import React from 'react'; import {Provider} from 'react-redux'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import injectTapEventPlugin from 'react-tap-event-plugin'; import './index.css'; import chronoTheme from './chrono-theme'; import store from './redux/store'; import router from './router'; import log from 'loglevel'; log.setLevel('debug'); // Needed for onTouchTap injectTapEventPlugin(); ReactDOM.render( <Provider store={store}> <MuiThemeProvider muiTheme={ chronoTheme }> {router} </MuiThemeProvider> </Provider>, document.getElementById('root') );
src/frontend/components/copyable.js
mweibel/esrscan-desktop
import React from 'react' import translation from './../translation' const {clipboard} = require('electron') export default class Copyable extends React.Component { constructor () { super() this.state = { 'copied': false } } onClick () { var text = this.props.textToCopy || this.props.text clipboard.writeText(text.trim()) this.setState({ copied: true }) } onMouseOut () { this.setState({ copied: false }) } render () { const onMouseOut = () => { this.onMouseOut() } const onClick = () => { this.onClick() } return ( <a onMouseOut={onMouseOut} onClick={onClick} className='copyable tooltip-link pos-rel dis-inline' href='#'> <span className='txt-grey prs'>{this.props.label}:</span> <span className='copyable-text'>{this.props.text}</span><i className='pls dis-hidden fa fa-clipboard'></i> <span className='mlm txt-small tooltip'>{this.state.copied ? translation.copied : translation.copyToClipboard}</span> </a> ) } } Copyable.propTypes = { text: React.PropTypes.string.isRequired, label: React.PropTypes.string.isRequired, // if not provided, this will be the text to copy textToCopy: React.PropTypes.string }
src/views/Card/CardMeta.js
shengnian/shengnian-ui-react
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, META, SUI, useTextAlignProp, } from '../../lib' /** * A card can contain content metadata. */ function CardMeta(props) { const { children, className, content, textAlign } = props const classes = cx( useTextAlignProp(textAlign), 'meta', className, ) const rest = getUnhandledProps(CardMeta, props) const ElementType = getElementType(CardMeta, props) return ( <ElementType {...rest} className={classes}> {childrenUtils.isNil(children) ? content : children} </ElementType> ) } CardMeta._meta = { name: 'CardMeta', parent: 'Card', type: META.TYPES.VIEW, } CardMeta.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** A card meta can adjust its text alignment. */ textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')), } export default CardMeta
src/app/containers/WeatherStations/components/MapInfoWindow/spec/MapInfoWindow.component.spec.js
atSistemas/react-base
import { expect } from 'chai'; import React from 'react'; import ShallowRenderer from 'react-test-renderer/shallow'; import weatherStationsMock from 'mocks/weatherStations.json'; import { MapInfoWindow } from '../'; const setup = data => { const props = { main: data }; const renderer = new ShallowRenderer(); renderer.render(<MapInfoWindow { ...props } />); const output = renderer.getRenderOutput(); return { props, output, renderer }; }; describe('component ', () => { describe('MapInfoWindow', () => { it('should render correctly', () => { const { output } = setup(weatherStationsMock[0].main); expect(output.type).to.equal('div'); }); it('should render with data incompconste', () => { const { output } = setup(weatherStationsMock[1].main); expect(output.type).to.equal('div'); }); it('should render data not found', () => { const { output } = setup(weatherStationsMock[2].main); expect(output.type).to.equal('div'); }); }); });
docs/client.js
Cellule/react-bootstrap
import 'bootstrap/less/bootstrap.less'; import './assets/docs.css'; import './assets/style.css'; import './assets/carousel.png'; import './assets/logo.png'; import './assets/favicon.ico'; import './assets/thumbnail.png'; import './assets/thumbnaildiv.png'; import 'codemirror/mode/htmlmixed/htmlmixed'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/theme/solarized.css'; import 'codemirror/lib/codemirror.css'; import './assets/CodeMirror.css'; import React from 'react'; import CodeMirror from 'codemirror'; import 'codemirror/addon/runmode/runmode'; import Router from 'react-router'; import routes from './src/Routes'; global.CodeMirror = CodeMirror; Router.run(routes, Router.RefreshLocation, Handler => { React.render( React.createElement(Handler, window.INITIAL_PROPS), document); });
node_modules/react-virtualized/dist/es/Grid/Grid.jest.js
xuan6/admin_dashboard_local_dev
import _Object$keys from 'babel-runtime/core-js/object/keys'; import _Object$getPrototypeOf from 'babel-runtime/core-js/object/get-prototype-of'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import _regeneratorRuntime from 'babel-runtime/regenerator'; import _Promise from 'babel-runtime/core-js/promise'; import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator'; import _extends from 'babel-runtime/helpers/extends'; var _this = this; import React from 'react'; import { findDOMNode } from 'react-dom'; import { Simulate } from 'react-dom/test-utils'; import { render } from '../TestUtils'; import Grid, { DEFAULT_SCROLLING_RESET_TIME_INTERVAL } from './Grid'; import { CellMeasurer, CellMeasurerCache } from '../CellMeasurer'; import { SCROLL_DIRECTION_BACKWARD, SCROLL_DIRECTION_FORWARD } from './defaultOverscanIndicesGetter'; import { DEFAULT_MAX_SCROLL_SIZE } from './utils/ScalingCellSizeAndPositionManager'; var DEFAULT_COLUMN_WIDTH = 50; var DEFAULT_HEIGHT = 100; var DEFAULT_ROW_HEIGHT = 20; var DEFAULT_WIDTH = 200; var NUM_ROWS = 100; var NUM_COLUMNS = 50; function getScrollbarSize0() { return 0; } function getScrollbarSize20() { return 20; } describe('Grid', function () { function defaultCellRenderer(_ref) { var columnIndex = _ref.columnIndex, key = _ref.key, rowIndex = _ref.rowIndex, style = _ref.style; return React.createElement( 'div', { className: 'gridItem', key: key, style: style }, 'row:' + rowIndex + ', column:' + columnIndex ); } function simulateScroll(_ref2) { var grid = _ref2.grid, _ref2$scrollLeft = _ref2.scrollLeft, scrollLeft = _ref2$scrollLeft === undefined ? 0 : _ref2$scrollLeft, _ref2$scrollTop = _ref2.scrollTop, scrollTop = _ref2$scrollTop === undefined ? 0 : _ref2$scrollTop; var target = { scrollLeft: scrollLeft, scrollTop: scrollTop }; grid._scrollingContainer = target; // HACK to work around _onScroll target check Simulate.scroll(findDOMNode(grid), { target: target }); } function getMarkup() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return React.createElement(Grid, _extends({ cellRenderer: defaultCellRenderer, columnCount: NUM_COLUMNS, columnWidth: DEFAULT_COLUMN_WIDTH, getScrollbarSize: getScrollbarSize0, height: DEFAULT_HEIGHT, overscanColumnCount: 0, overscanRowCount: 0, autoHeight: false, rowHeight: DEFAULT_ROW_HEIGHT, rowCount: NUM_ROWS, width: DEFAULT_WIDTH }, props)); } describe('number of rendered children', function () { it('should render enough children to fill the available area', function () { var rendered = findDOMNode(render(getMarkup())); expect(rendered.querySelectorAll('.gridItem').length).toEqual(20); // 5 rows x 4 columns }); it('should not render more rows than available if the area is not filled', function () { var rendered = findDOMNode(render(getMarkup({ rowCount: 2 }))); expect(rendered.querySelectorAll('.gridItem').length).toEqual(8); // 2 rows x 4 columns }); it('should not render more columns than available if the area is not filled', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 2 }))); expect(rendered.querySelectorAll('.gridItem').length).toEqual(10); // 5 rows x 2 columns }); // Small performance tweak added in 5.5.6 it('should not render/parent cells that are null or false', function () { function cellRenderer(_ref3) { var columnIndex = _ref3.columnIndex, key = _ref3.key, rowIndex = _ref3.rowIndex, style = _ref3.style; if (columnIndex === 0) { return null; } else if (rowIndex === 0) { return false; } else { return React.createElement( 'div', { className: 'cell', key: key, style: style }, 'row:' + rowIndex + ', column:' + columnIndex ); } } var rendered = findDOMNode(render(getMarkup({ columnCount: 3, overscanColumnCount: 0, overscanRowCount: 0, rowCount: 3, cellRenderer: cellRenderer }))); expect(rendered.querySelectorAll('.cell').length).toEqual(4); // [1,1], [1,2], [2,1], and [2,2] expect(rendered.textContent).not.toContain('column:0'); expect(rendered.textContent).not.toContain('row:0'); }); }); describe('shows and hides scrollbars based on rendered content', function () { it('should set overflowX:hidden if columns fit within the available width and y-axis has no scrollbar', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 4, getScrollbarSize: getScrollbarSize20, rowCount: 5 }))); expect(rendered.style.overflowX).toEqual('hidden'); }); it('should set overflowX:hidden if columns and y-axis scrollbar fit within the available width', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 4, getScrollbarSize: getScrollbarSize20, width: 200 + getScrollbarSize20() }))); expect(rendered.style.overflowX).toEqual('hidden'); }); it('should leave overflowX:auto if columns require more than the available width', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 4, getScrollbarSize: getScrollbarSize20, width: 200 - 1, rowCount: 5 }))); expect(rendered.style.overflowX).not.toEqual('hidden'); }); it('should leave overflowX:auto if columns and y-axis scrollbar require more than the available width', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 4, getScrollbarSize: getScrollbarSize20, width: 200 + getScrollbarSize20() - 1 }))); expect(rendered.style.overflowX).not.toEqual('hidden'); }); it('should set overflowY:hidden if rows fit within the available width and xaxis has no scrollbar', function () { var rendered = findDOMNode(render(getMarkup({ getScrollbarSize: getScrollbarSize20, rowCount: 5, columnCount: 4 }))); expect(rendered.style.overflowY).toEqual('hidden'); }); it('should set overflowY:hidden if rows and x-axis scrollbar fit within the available width', function () { var rendered = findDOMNode(render(getMarkup({ getScrollbarSize: getScrollbarSize20, rowCount: 5, height: 100 + getScrollbarSize20() }))); expect(rendered.style.overflowY).toEqual('hidden'); }); it('should leave overflowY:auto if rows require more than the available width', function () { var rendered = findDOMNode(render(getMarkup({ getScrollbarSize: getScrollbarSize20, rowCount: 5, height: 100 - 1, columnCount: 4 }))); expect(rendered.style.overflowY).not.toEqual('hidden'); }); it('should leave overflowY:auto if rows and x-axis scrollbar require more than the available width', function () { var rendered = findDOMNode(render(getMarkup({ getScrollbarSize: getScrollbarSize20, rowCount: 5, height: 100 + getScrollbarSize20() - 1 }))); expect(rendered.style.overflowY).not.toEqual('hidden'); }); it('should accept styles that overwrite calculated ones', function () { var rendered = findDOMNode(render(getMarkup({ columnCount: 1, getScrollbarSize: getScrollbarSize20, height: 1, rowCount: 1, style: { overflowY: 'visible', overflowX: 'visible' }, width: 1 }))); expect(rendered.style.overflowY).toEqual('visible'); expect(rendered.style.overflowX).toEqual('visible'); }); }); /** Tests scrolling via initial props */ describe(':scrollToColumn and :scrollToRow', function () { it('should scroll to the left', function () { var grid = render(getMarkup({ scrollToColumn: 0 })); expect(grid.state.scrollLeft).toEqual(0); }); it('should scroll over to the middle', function () { var grid = render(getMarkup({ scrollToColumn: 24 })); // 100 columns * 50 item width = 5,000 total item width // 4 columns can be visible at a time and :scrollLeft is initially 0, // So the minimum amount of scrolling leaves the 25th item at the right (just scrolled into view). expect(grid.state.scrollLeft).toEqual(1050); }); it('should scroll to the far right', function () { var grid = render(getMarkup({ scrollToColumn: 49 })); // 100 columns * 50 item width = 5,000 total item width // Target offset for the last item then is 5,000 - 200 expect(grid.state.scrollLeft).toEqual(2300); }); it('should scroll to the top', function () { var grid = render(getMarkup({ scrollToRow: 0 })); expect(grid.state.scrollTop).toEqual(0); }); it('should scroll down to the middle', function () { var grid = render(getMarkup({ scrollToRow: 49 })); // 100 rows * 20 item height = 2,000 total item height // 5 rows can be visible at a time and :scrollTop is initially 0, // So the minimum amount of scrolling leaves the 50th item at the bottom (just scrolled into view). expect(grid.state.scrollTop).toEqual(900); }); it('should scroll to the bottom', function () { var grid = render(getMarkup({ scrollToRow: 99 })); // 100 rows * 20 item height = 2,000 total item height // Target offset for the last item then is 2,000 - 100 expect(grid.state.scrollTop).toEqual(1900); }); it('should scroll to a row and column just added', function () { var grid = render(getMarkup()); expect(grid.state.scrollLeft).toEqual(0); expect(grid.state.scrollTop).toEqual(0); grid = render(getMarkup({ columnCount: NUM_COLUMNS + 1, rowCount: NUM_ROWS + 1, scrollToColumn: NUM_COLUMNS, scrollToRow: NUM_ROWS })); expect(grid.state.scrollLeft).toEqual(2350); expect(grid.state.scrollTop).toEqual(1920); }); it('should scroll back to a newly-added cell without a change in prop', function () { var grid = render(getMarkup({ columnCount: NUM_COLUMNS, rowCount: NUM_ROWS, scrollToColumn: NUM_COLUMNS, scrollToRow: NUM_ROWS })); grid = render(getMarkup({ columnCount: NUM_COLUMNS + 1, rowCount: NUM_ROWS + 1, scrollToColumn: NUM_COLUMNS, scrollToRow: NUM_ROWS })); expect(grid.state.scrollLeft).toEqual(2350); expect(grid.state.scrollTop).toEqual(1920); }); it('should scroll to the correct position for :scrollToAlignment "start"', function () { var grid = render(getMarkup({ scrollToAlignment: 'start', scrollToColumn: 24, scrollToRow: 49 })); // 100 columns * 50 item width = 5,000 total item width // 100 rows * 20 item height = 2,000 total item height // 4 columns and 5 rows can be visible at a time. // The minimum amount of scrolling leaves the specified cell in the bottom/right corner (just scrolled into view). // Since alignment is set to "start" we should scroll past this point until the cell is aligned top/left. expect(grid.state.scrollLeft).toEqual(1200); expect(grid.state.scrollTop).toEqual(980); }); it('should scroll to the correct position for :scrollToAlignment "end"', function () { render(getMarkup({ scrollToColumn: 99, scrollToRow: 99 })); var grid = render(getMarkup({ scrollToAlignment: 'end', scrollToColumn: 24, scrollToRow: 49 })); // 100 columns * 50 item width = 5,000 total item width // 100 rows * 20 item height = 2,000 total item height // We first scroll past the specified cell and then back. // The minimum amount of scrolling then should leave the specified cell in the top/left corner (just scrolled into view). // Since alignment is set to "end" we should scroll past this point until the cell is aligned bottom/right. expect(grid.state.scrollLeft).toEqual(1050); expect(grid.state.scrollTop).toEqual(900); }); it('should scroll to the correct position for :scrollToAlignment "center"', function () { render(getMarkup({ scrollToColumn: 99, scrollToRow: 99 })); var grid = render(getMarkup({ scrollToAlignment: 'center', scrollToColumn: 24, scrollToRow: 49 })); // 100 columns * 50 item width = 5,000 total item width // Viewport width is 200 // Column 24 starts at 1,200, center point at 1,225, so... expect(grid.state.scrollLeft).toEqual(1125); // 100 rows * 20 item height = 2,000 total item height // Viewport height is 100 // Row 49 starts at 980, center point at 990, so... expect(grid.state.scrollTop).toEqual(940); }); // Tests issue #218 it('should set the correct :scrollTop after row and column counts increase from 0', function () { var expectedScrollTop = 100 * DEFAULT_ROW_HEIGHT - DEFAULT_HEIGHT + DEFAULT_ROW_HEIGHT; render(getMarkup({ columnCount: 0, rowCount: 150, scrollToRow: 100 })); expect(findDOMNode(render(getMarkup({ columnCount: 150, rowCount: 150, scrollToRow: 100 }))).scrollTop).toEqual(expectedScrollTop); }); it('should support scrollToCell() public method', function () { var grid = render(getMarkup()); expect(grid.state.scrollLeft).toEqual(0); expect(grid.state.scrollTop).toEqual(0); grid.scrollToCell({ columnIndex: 24, rowIndex: 49 }); // 100 columns * 50 item width = 5,000 total item width // 4 columns can be visible at a time and :scrollLeft is initially 0, // So the minimum amount of scrolling leaves the 25th item at the right (just scrolled into view). expect(grid.state.scrollLeft).toEqual(1050); // 100 rows * 20 item height = 2,000 total item height // 5 rows can be visible at a time and :scrollTop is initially 0, // So the minimum amount of scrolling leaves the 50th item at the bottom (just scrolled into view). expect(grid.state.scrollTop).toEqual(900); // Change column without affecting row grid.scrollToCell({ columnIndex: 49 }); expect(grid.state.scrollLeft).toEqual(2300); expect(grid.state.scrollTop).toEqual(900); // Change row without affecting column grid.scrollToCell({ rowIndex: 99 }); expect(grid.state.scrollLeft).toEqual(2300); expect(grid.state.scrollTop).toEqual(1900); }); it('should support scrollToPosition() public method', function () { var grid = render(getMarkup()); expect(grid.state.scrollLeft).toEqual(0); expect(grid.state.scrollTop).toEqual(0); grid.scrollToPosition({ scrollLeft: 50, scrollTop: 100 }); expect(grid.state.scrollLeft).toEqual(50); expect(grid.state.scrollTop).toEqual(100); // Change column without affecting row grid.scrollToPosition({ scrollLeft: 25 }); expect(grid.state.scrollLeft).toEqual(25); expect(grid.state.scrollTop).toEqual(100); // Change row without affecting column grid.scrollToPosition({ scrollTop: 50 }); expect(grid.state.scrollLeft).toEqual(25); expect(grid.state.scrollTop).toEqual(50); }); it('should support getOffsetForCell() public method', function () { var grid = render(getMarkup()); var _grid$getOffsetForCel = grid.getOffsetForCell({ columnIndex: 24, rowIndex: 49 }), scrollLeft = _grid$getOffsetForCel.scrollLeft, scrollTop = _grid$getOffsetForCel.scrollTop; // 100 columns * 50 item width = 5,000 total item width // 4 columns can be visible at a time and :scrollLeft is initially 0, // So the minimum amount of scrolling leaves the 25th item at the right (just scrolled into view). expect(scrollLeft).toEqual(1050); // 100 rows * 20 item height = 2,000 total item height // 5 rows can be visible at a time and :scrollTop is initially 0, // So the minimum amount of scrolling leaves the 50th item at the bottom (just scrolled into view). expect(scrollTop).toEqual(900); }); // See issue #565 it('should update scroll position to account for changed cell sizes within a function prop wrapper', function () { var _rowHeight = 20; var props = { height: 100, rowCount: 100, rowHeight: function rowHeight(_ref4) { var index = _ref4.index; return index === 99 ? _rowHeight : 20; }, scrollToRow: 99 }; var grid = render(getMarkup(props)); var node = findDOMNode(grid); expect(node.scrollTop).toBe(1900); _rowHeight = 40; grid.recomputeGridSize({ rowIndex: 99 }); expect(node.scrollTop).toBe(1920); }); it('should restore scroll offset for column when row count increases from 0 (and vice versa)', function () { var props = { columnWidth: 50, columnCount: 100, height: 100, rowCount: 100, rowHeight: 20, scrollToColumn: 50, scrollToRow: 50, width: 100 }; var grid = render(getMarkup(props)); expect(grid.state.scrollLeft).toEqual(2450); expect(grid.state.scrollTop).toEqual(920); render(getMarkup(_extends({}, props, { columnCount: 0 }))); expect(grid.state.scrollLeft).toEqual(0); expect(grid.state.scrollTop).toEqual(0); render(getMarkup(props)); expect(grid.state.scrollLeft).toEqual(2450); expect(grid.state.scrollTop).toEqual(920); render(getMarkup(_extends({}, props, { rowCount: 0 }))); expect(grid.state.scrollLeft).toEqual(0); expect(grid.state.scrollTop).toEqual(0); render(getMarkup(props)); expect(grid.state.scrollLeft).toEqual(2450); expect(grid.state.scrollTop).toEqual(920); }); it('should take scrollbar size into account when aligning cells', function () { var grid = render(getMarkup({ columnWidth: 50, columnCount: 100, getScrollbarSize: getScrollbarSize20, height: 100, rowCount: 100, rowHeight: 20, scrollToColumn: 50, scrollToRow: 50, width: 100 })); expect(grid.state.scrollLeft).toEqual(2450 + getScrollbarSize20()); expect(grid.state.scrollTop).toEqual(920 + getScrollbarSize20()); }); }); describe('property updates', function () { it('should update :scrollToColumn position when :columnWidth changes', function () { var grid = findDOMNode(render(getMarkup({ scrollToColumn: 25 }))); expect(grid.textContent).toContain('column:25'); // Making columns taller pushes name off/beyond the scrolled area grid = findDOMNode(render(getMarkup({ scrollToColumn: 25, columnWidth: 20 }))); expect(grid.textContent).toContain('column:25'); }); it('should update :scrollToRow position when :rowHeight changes', function () { var grid = findDOMNode(render(getMarkup({ scrollToRow: 50 }))); expect(grid.textContent).toContain('row:50'); // Making rows taller pushes name off/beyond the scrolled area grid = findDOMNode(render(getMarkup({ scrollToRow: 50, rowHeight: 20 }))); expect(grid.textContent).toContain('row:50'); }); it('should update :scrollToColumn position when :width changes', function () { var grid = findDOMNode(render(getMarkup({ scrollToColumn: 25 }))); expect(grid.textContent).toContain('column:25'); // Making the grid narrower leaves only room for 1 item grid = findDOMNode(render(getMarkup({ scrollToColumn: 25, width: 50 }))); expect(grid.textContent).toContain('column:25'); }); it('should update :scrollToRow position when :height changes', function () { var grid = findDOMNode(render(getMarkup({ scrollToRow: 50 }))); expect(grid.textContent).toContain('row:50'); // Making the grid shorter leaves only room for 1 item grid = findDOMNode(render(getMarkup({ scrollToRow: 50, height: 20 }))); expect(grid.textContent).toContain('row:50'); }); it('should update :scrollToColumn position when :scrollToColumn changes', function () { var grid = findDOMNode(render(getMarkup())); expect(grid.textContent).not.toContain('column:25'); grid = findDOMNode(render(getMarkup({ scrollToColumn: 25 }))); expect(grid.textContent).toContain('column:25'); }); it('should update :scrollToRow position when :scrollToRow changes', function () { var grid = findDOMNode(render(getMarkup())); expect(grid.textContent).not.toContain('row:50'); grid = findDOMNode(render(getMarkup({ scrollToRow: 50 }))); expect(grid.textContent).toContain('row:50'); }); it('should update scroll position if size shrinks smaller than the current scroll', function () { var grid = findDOMNode(render(getMarkup({ scrollToColumn: 250 }))); grid = findDOMNode(render(getMarkup())); grid = findDOMNode(render(getMarkup({ scrollToColumn: 250, columnCount: 10 }))); expect(grid.textContent).toContain('column:9'); }); it('should update scroll position if size shrinks smaller than the current scroll', function () { var grid = findDOMNode(render(getMarkup({ scrollToRow: 500 }))); grid = findDOMNode(render(getMarkup())); grid = findDOMNode(render(getMarkup({ scrollToRow: 500, rowCount: 10 }))); expect(grid.textContent).toContain('row:9'); }); }); describe('noContentRenderer', function () { it('should call :noContentRenderer if :columnCount is 0', function () { var list = findDOMNode(render(getMarkup({ noContentRenderer: function noContentRenderer() { return React.createElement( 'div', null, 'No data' ); }, columnCount: 0 }))); expect(list.textContent).toEqual('No data'); }); it('should call :noContentRenderer if :rowCount is 0', function () { var list = findDOMNode(render(getMarkup({ noContentRenderer: function noContentRenderer() { return React.createElement( 'div', null, 'No data' ); }, rowCount: 0 }))); expect(list.textContent).toEqual('No data'); }); // Sanity check for bvaughn/react-virtualized/pull/348 it('should render an empty body if :rowCount or :columnCount changes to 0', function () { function noContentRenderer() { return React.createElement( 'div', null, 'No data' ); } var list = findDOMNode(render(getMarkup({ noContentRenderer: noContentRenderer }))); expect(list.textContent).not.toEqual('No data'); list = findDOMNode(render(getMarkup({ noContentRenderer: noContentRenderer, rowCount: 0 }))); expect(list.textContent).toEqual('No data'); list = findDOMNode(render(getMarkup({ noContentRenderer: noContentRenderer }))); expect(list.textContent).not.toEqual('No data'); list = findDOMNode(render(getMarkup({ columnCount: 0, noContentRenderer: noContentRenderer }))); expect(list.textContent).toEqual('No data'); }); it('should render an empty body if :columnCount is 0 and there is no :noContentRenderer', function () { var list = findDOMNode(render(getMarkup({ columnCount: 0 }))); expect(list.textContent).toEqual(''); }); it('should render an empty body if :rowCount is 0 and there is no :noContentRenderer', function () { var list = findDOMNode(render(getMarkup({ rowCount: 0 }))); expect(list.textContent).toEqual(''); }); it('should render an empty body there is a :noContentRenderer but :height or :width are 0', function () { var list = findDOMNode(render(getMarkup({ height: 0, noContentRenderer: function noContentRenderer() { return React.createElement( 'div', null, 'No data' ); } }))); expect(list.textContent).toEqual(''); list = findDOMNode(render(getMarkup({ noContentRenderer: function noContentRenderer() { return React.createElement( 'div', null, 'No data' ); }, width: 0 }))); expect(list.textContent).toEqual(''); }); }); describe('onSectionRendered', function () { it('should call :onSectionRendered if at least one cell is rendered', function () { var columnStartIndex = void 0, columnStopIndex = void 0, rowStartIndex = void 0, rowStopIndex = void 0; render(getMarkup({ onSectionRendered: function onSectionRendered(params) { var _params; return _params = params, columnStartIndex = _params.columnStartIndex, columnStopIndex = _params.columnStopIndex, rowStartIndex = _params.rowStartIndex, rowStopIndex = _params.rowStopIndex, _params; } })); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(4); }); it('should not call :onSectionRendered unless the column or row start or stop indices have changed', function () { var numCalls = 0; var columnStartIndex = void 0, columnStopIndex = void 0, rowStartIndex = void 0, rowStopIndex = void 0; var onSectionRendered = function onSectionRendered(params) { columnStartIndex = params.columnStartIndex; columnStopIndex = params.columnStopIndex; rowStartIndex = params.rowStartIndex; rowStopIndex = params.rowStopIndex; numCalls++; }; render(getMarkup({ onSectionRendered: onSectionRendered })); expect(numCalls).toEqual(1); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(4); render(getMarkup({ onSectionRendered: onSectionRendered })); expect(numCalls).toEqual(1); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(4); }); it('should call :onSectionRendered if the row or column start or stop indices have changed', function () { var numCalls = 0; var columnStartIndex = void 0, columnStopIndex = void 0, rowStartIndex = void 0, rowStopIndex = void 0; var onSectionRendered = function onSectionRendered(params) { columnStartIndex = params.columnStartIndex; columnStopIndex = params.columnStopIndex; rowStartIndex = params.rowStartIndex; rowStopIndex = params.rowStopIndex; numCalls++; }; render(getMarkup({ onSectionRendered: onSectionRendered })); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(4); render(getMarkup({ height: 50, onSectionRendered: onSectionRendered })); expect(numCalls).toEqual(2); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(2); render(getMarkup({ height: 50, onSectionRendered: onSectionRendered, width: 100 })); expect(numCalls).toEqual(3); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(1); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(2); }); it('should not call :onSectionRendered if no cells are rendered', function () { var numCalls = 0; render(getMarkup({ height: 0, onSectionRendered: function onSectionRendered(params) { return numCalls++; } })); expect(numCalls).toEqual(0); }); }); describe(':scrollLeft and :scrollTop properties', function () { it('should render correctly when an initial :scrollLeft and :scrollTop properties are specified', function () { var columnStartIndex = void 0, columnStopIndex = void 0, rowStartIndex = void 0, rowStopIndex = void 0; findDOMNode(render(getMarkup({ onSectionRendered: function onSectionRendered(params) { var _params2; return _params2 = params, columnStartIndex = _params2.columnStartIndex, columnStopIndex = _params2.columnStopIndex, rowStartIndex = _params2.rowStartIndex, rowStopIndex = _params2.rowStopIndex, _params2; }, scrollLeft: 250, scrollTop: 100 }))); expect(rowStartIndex).toEqual(5); expect(rowStopIndex).toEqual(9); expect(columnStartIndex).toEqual(5); expect(columnStopIndex).toEqual(8); }); it('should render correctly when :scrollLeft and :scrollTop properties are updated', function () { var columnStartIndex = void 0, columnStopIndex = void 0, rowStartIndex = void 0, rowStopIndex = void 0; render(getMarkup({ onSectionRendered: function onSectionRendered(params) { var _params3; return _params3 = params, columnStartIndex = _params3.columnStartIndex, columnStopIndex = _params3.columnStopIndex, rowStartIndex = _params3.rowStartIndex, rowStopIndex = _params3.rowStopIndex, _params3; } })); expect(rowStartIndex).toEqual(0); expect(rowStopIndex).toEqual(4); expect(columnStartIndex).toEqual(0); expect(columnStopIndex).toEqual(3); render(getMarkup({ onSectionRendered: function onSectionRendered(params) { var _params4; return _params4 = params, columnStartIndex = _params4.columnStartIndex, columnStopIndex = _params4.columnStopIndex, rowStartIndex = _params4.rowStartIndex, rowStopIndex = _params4.rowStopIndex, _params4; }, scrollLeft: 250, scrollTop: 100 })); expect(rowStartIndex).toEqual(5); expect(rowStopIndex).toEqual(9); expect(columnStartIndex).toEqual(5); expect(columnStopIndex).toEqual(8); }); }); describe('styles, classNames, and ids', function () { it('should use the expected global CSS classNames', function () { var rendered = findDOMNode(render(getMarkup())); expect(rendered.className).toEqual('ReactVirtualized__Grid'); }); it('should use a custom :className if specified', function () { var rendered = findDOMNode(render(getMarkup({ className: 'foo' }))); expect(rendered.className).toContain('foo'); }); it('should use a custom :id if specified', function () { var rendered = findDOMNode(render(getMarkup({ id: 'bar' }))); expect(rendered.getAttribute('id')).toEqual('bar'); }); it('should use a custom :style if specified', function () { var style = { backgroundColor: 'red' }; var rendered = findDOMNode(render(getMarkup({ style: style }))); expect(rendered.style.backgroundColor).toEqual('red'); }); it('should use a custom :containerStyle if specified', function () { var containerStyle = { backgroundColor: 'red' }; var rendered = findDOMNode(render(getMarkup({ containerStyle: containerStyle }))); expect(rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer').style.backgroundColor).toEqual('red'); }); }); describe('onScroll', function () { it('should trigger callback when component is mounted', function () { var onScrollCalls = []; render(getMarkup({ onScroll: function onScroll(params) { return onScrollCalls.push(params); }, scrollLeft: 50, scrollTop: 100 })); expect(onScrollCalls).toEqual([{ clientHeight: 100, clientWidth: 200, scrollHeight: 2000, scrollLeft: 50, scrollTop: 100, scrollWidth: 2500 }]); }); it('should trigger callback when component scrolls horizontally', function () { var onScrollCalls = []; var grid = render(getMarkup({ onScroll: function onScroll(params) { return onScrollCalls.push(params); } })); simulateScroll({ grid: grid, scrollLeft: 100, scrollTop: 0 }); expect(onScrollCalls.length).toEqual(2); expect(onScrollCalls[1]).toEqual({ clientHeight: 100, clientWidth: 200, scrollHeight: 2000, scrollLeft: 100, scrollTop: 0, scrollWidth: 2500 }); }); it('should trigger callback when component scrolls vertically', function () { var onScrollCalls = []; var grid = render(getMarkup({ onScroll: function onScroll(params) { return onScrollCalls.push(params); } })); simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 100 }); expect(onScrollCalls.length).toEqual(2); expect(onScrollCalls[1]).toEqual({ clientHeight: 100, clientWidth: 200, scrollHeight: 2000, scrollLeft: 0, scrollTop: 100, scrollWidth: 2500 }); }); it('should trigger callback with scrollLeft of 0 when total columns width is less than width', function () { var onScrollCalls = []; var grid = render(getMarkup({ columnCount: 1, columnWidth: 50, onScroll: function onScroll(params) { return onScrollCalls.push(params); }, scrollLeft: 0, scrollTop: 10, width: 200 })); simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 0 }); expect(onScrollCalls.length).toEqual(2); expect(onScrollCalls[1]).toEqual({ clientHeight: 100, clientWidth: 200, scrollHeight: 2000, scrollLeft: 0, scrollTop: 0, scrollWidth: 50 }); }); it('should trigger callback with scrollTop of 0 when total rows height is less than height', function () { var onScrollCalls = []; var grid = render(getMarkup({ rowCount: 1, rowHeight: 50, onScroll: function onScroll(params) { return onScrollCalls.push(params); }, scrollLeft: 0, scrollTop: 10, height: 200 })); simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 0 }); expect(onScrollCalls.length).toEqual(2); expect(onScrollCalls[1]).toEqual({ clientHeight: 200, clientWidth: 200, scrollHeight: 50, scrollLeft: 0, scrollTop: 0, scrollWidth: 2500 }); }); // Support use-cases like WindowScroller; enable them to stay in sync with scroll-to-cell changes. it('should trigger when :scrollToColumn or :scrollToRow are changed via props', function () { var onScrollCalls = []; render(getMarkup()); render(getMarkup({ onScroll: function onScroll(params) { return onScrollCalls.push(params); }, scrollToColumn: 24, scrollToRow: 49 })); expect(onScrollCalls).toEqual([{ clientHeight: 100, clientWidth: 200, scrollHeight: 2000, scrollLeft: 1050, scrollTop: 900, scrollWidth: 2500 }]); }); }); describe('overscanColumnCount & overscanRowCount', function () { function createHelper() { var _columnOverscanStartIndex = void 0, _columnOverscanStopIndex = void 0, _columnStartIndex = void 0, _columnStopIndex = void 0, _rowOverscanStartIndex = void 0, _rowOverscanStopIndex = void 0, _rowStartIndex = void 0, _rowStopIndex = void 0; function onSectionRendered(params) { _columnOverscanStartIndex = params.columnOverscanStartIndex; _columnOverscanStopIndex = params.columnOverscanStopIndex; _columnStartIndex = params.columnStartIndex; _columnStopIndex = params.columnStopIndex; _rowOverscanStartIndex = params.rowOverscanStartIndex; _rowOverscanStopIndex = params.rowOverscanStopIndex; _rowStartIndex = params.rowStartIndex; _rowStopIndex = params.rowStopIndex; } return { columnOverscanStartIndex: function columnOverscanStartIndex() { return _columnOverscanStartIndex; }, columnOverscanStopIndex: function columnOverscanStopIndex() { return _columnOverscanStopIndex; }, columnStartIndex: function columnStartIndex() { return _columnStartIndex; }, columnStopIndex: function columnStopIndex() { return _columnStopIndex; }, onSectionRendered: onSectionRendered, rowOverscanStartIndex: function rowOverscanStartIndex() { return _rowOverscanStartIndex; }, rowOverscanStopIndex: function rowOverscanStopIndex() { return _rowOverscanStopIndex; }, rowStartIndex: function rowStartIndex() { return _rowStartIndex; }, rowStopIndex: function rowStopIndex() { return _rowStopIndex; } }; } it('should not overscan if disabled', function () { var helper = createHelper(); render(getMarkup({ onSectionRendered: helper.onSectionRendered })); expect(helper.columnOverscanStartIndex()).toEqual(helper.columnStartIndex()); expect(helper.columnOverscanStopIndex()).toEqual(helper.columnStopIndex()); expect(helper.rowOverscanStartIndex()).toEqual(helper.rowStartIndex()); expect(helper.rowOverscanStopIndex()).toEqual(helper.rowStopIndex()); }); it('should overscan the specified amount', function () { var helper = createHelper(); render(getMarkup({ onSectionRendered: helper.onSectionRendered, overscanColumnCount: 2, overscanRowCount: 5, scrollToColumn: 25, scrollToRow: 50 })); expect(helper.columnOverscanStartIndex()).toEqual(22); expect(helper.columnOverscanStopIndex()).toEqual(27); expect(helper.columnStartIndex()).toEqual(22); expect(helper.columnStopIndex()).toEqual(25); expect(helper.rowOverscanStartIndex()).toEqual(46); expect(helper.rowOverscanStopIndex()).toEqual(55); expect(helper.rowStartIndex()).toEqual(46); expect(helper.rowStopIndex()).toEqual(50); }); it('should not overscan beyond the bounds of the grid', function () { var helper = createHelper(); render(getMarkup({ onSectionRendered: helper.onSectionRendered, columnCount: 6, overscanColumnCount: 10, overscanRowCount: 10, rowCount: 5 })); expect(helper.columnOverscanStartIndex()).toEqual(0); expect(helper.columnOverscanStopIndex()).toEqual(5); expect(helper.columnStartIndex()).toEqual(0); expect(helper.columnStopIndex()).toEqual(3); expect(helper.rowOverscanStartIndex()).toEqual(0); expect(helper.rowOverscanStopIndex()).toEqual(4); expect(helper.rowStartIndex()).toEqual(0); expect(helper.rowStopIndex()).toEqual(4); }); it('should set the correct scroll direction', function () { // Do not pass in the initial state as props, otherwise the internal state is forbidden from updating itself var grid = render(getMarkup()); // Simulate a scroll to set the initial internal state simulateScroll({ grid: grid, scrollLeft: 50, scrollTop: 50 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 0 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_BACKWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_BACKWARD); simulateScroll({ grid: grid, scrollLeft: 100, scrollTop: 100 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); }); it('should set the correct scroll direction when scroll position is updated from props', function () { var grid = render(getMarkup({ scrollLeft: 50, scrollTop: 50 })); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); grid = render(getMarkup({ scrollLeft: 0, scrollTop: 0 })); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_BACKWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_BACKWARD); grid = render(getMarkup({ scrollLeft: 100, scrollTop: 100 })); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); }); it('should not reset scroll direction for one axis when scrolled in another', function () { // Do not pass in the initial state as props, otherwise the internal state is forbidden from updating itself var grid = render(getMarkup()); // Simulate a scroll to set the initial internal state simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 5 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); simulateScroll({ grid: grid, scrollLeft: 5, scrollTop: 5 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_FORWARD); simulateScroll({ grid: grid, scrollLeft: 5, scrollTop: 0 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_FORWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_BACKWARD); simulateScroll({ grid: grid, scrollLeft: 0, scrollTop: 0 }); expect(grid.state.scrollDirectionHorizontal).toEqual(SCROLL_DIRECTION_BACKWARD); expect(grid.state.scrollDirectionVertical).toEqual(SCROLL_DIRECTION_BACKWARD); }); it('should overscan in the direction being scrolled', function () { var _ref5 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(done) { var helper, onSectionRenderedResolve, onSectionRendered, grid, onSectionRenderedPromise; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: onSectionRendered = function onSectionRendered(params) { helper.onSectionRendered(params); if (onSectionRenderedResolve) { onSectionRenderedResolve(); } }; helper = createHelper(); onSectionRenderedResolve = void 0; grid = render(getMarkup({ onSectionRendered: onSectionRendered, overscanColumnCount: 2, overscanRowCount: 5 })); // Wait until the onSectionRendered handler / debouncer has processed onSectionRenderedPromise = new _Promise(function (resolve) { onSectionRenderedResolve = resolve; }); simulateScroll({ grid: grid, scrollLeft: 200, scrollTop: 200 }); _context.next = 8; return onSectionRenderedPromise; case 8: // It should overscan in the direction being scrolled while scroll is in progress expect(helper.columnOverscanStartIndex()).toEqual(4); expect(helper.columnOverscanStopIndex()).toEqual(9); expect(helper.columnStartIndex()).toEqual(4); expect(helper.columnStopIndex()).toEqual(7); expect(helper.rowOverscanStartIndex()).toEqual(10); expect(helper.rowOverscanStopIndex()).toEqual(19); expect(helper.rowStartIndex()).toEqual(10); expect(helper.rowStopIndex()).toEqual(14); // Wait until the onSectionRendered handler / debouncer has processed onSectionRenderedPromise = new _Promise(function (resolve) { onSectionRenderedResolve = resolve; }); simulateScroll({ grid: grid, scrollLeft: 100, scrollTop: 100 }); _context.next = 20; return onSectionRenderedPromise; case 20: // It reset overscan once scrolling has finished expect(helper.columnOverscanStartIndex()).toEqual(0); expect(helper.columnOverscanStopIndex()).toEqual(5); expect(helper.columnStartIndex()).toEqual(2); expect(helper.columnStopIndex()).toEqual(5); expect(helper.rowOverscanStartIndex()).toEqual(0); expect(helper.rowOverscanStopIndex()).toEqual(9); expect(helper.rowStartIndex()).toEqual(5); expect(helper.rowStopIndex()).toEqual(9); done(); case 29: case 'end': return _context.stop(); } } }, _callee, _this); })); return function (_x2) { return _ref5.apply(this, arguments); }; }()); }); describe('cellRangeRenderer', function () { it('should use a custom :cellRangeRenderer if specified', function () { var cellRangeRendererCalled = 0; var cellRangeRendererParams = void 0; var rendered = findDOMNode(render(getMarkup({ cellRangeRenderer: function cellRangeRenderer(params) { cellRangeRendererParams = params; cellRangeRendererCalled++; return [React.createElement( 'div', { key: '0' }, 'Fake content' )]; } }))); expect(cellRangeRendererCalled).toEqual(1); expect(cellRangeRendererParams.columnStartIndex).toEqual(0); expect(cellRangeRendererParams.columnStopIndex).toEqual(3); expect(cellRangeRendererParams.rowStartIndex).toEqual(0); expect(cellRangeRendererParams.rowStopIndex).toEqual(4); expect(rendered.textContent).toContain('Fake content'); }); }); describe('estimated row and column sizes', function () { it('should not estimate sizes if actual sizes are numbers', function () { var grid = render(getMarkup({ columnWidth: 100, estimatedColumnSize: 150, estimatedRowSize: 15, rowHeight: 20 })); expect(grid._getEstimatedColumnSize(grid.props)).toEqual(100); expect(grid._getEstimatedRowSize(grid.props)).toEqual(20); }); it('should estimate row and column sizes if actual sizes are functions', function () { var grid = render(getMarkup({ columnWidth: function columnWidth() { return 100; }, estimatedColumnSize: 150, estimatedRowSize: 15, rowHeight: function rowHeight() { return 20; } })); expect(grid._getEstimatedColumnSize(grid.props)).toEqual(150); expect(grid._getEstimatedRowSize(grid.props)).toEqual(15); }); }); it('should pass the cellRenderer an :isScrolling flag when scrolling is in progress', function () { var _ref6 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(done) { var cellRendererCalls, cellRenderer, grid; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: cellRenderer = function cellRenderer(_ref7) { var columnIndex = _ref7.columnIndex, isScrolling = _ref7.isScrolling, key = _ref7.key, rowIndex = _ref7.rowIndex, style = _ref7.style; cellRendererCalls.push(isScrolling); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); }; cellRendererCalls = []; grid = render(getMarkup({ cellRenderer: cellRenderer })); expect(cellRendererCalls[0]).toEqual(false); cellRendererCalls.splice(0); // Give React time to process the queued setState() _context2.next = 7; return new _Promise(function (resolve) { return setTimeout(resolve, 1); }); case 7: simulateScroll({ grid: grid, scrollTop: 100 }); expect(cellRendererCalls[0]).toEqual(true); done(); case 10: case 'end': return _context2.stop(); } } }, _callee2, _this); })); return function (_x3) { return _ref6.apply(this, arguments); }; }()); it('should pass the cellRenderer an :isScrolling flag based on props override', function () { var cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (_ref8) { var key = _ref8.key, style = _ref8.style; return React.createElement('div', { key: key, style: style }); }); render(getMarkup({ cellRenderer: cellRenderer, isScrolling: true })); expect(cellRenderer).toHaveBeenCalled(); expect(cellRenderer.mock.calls[0][0].isScrolling).toBe(true); cellRenderer.mockReset(); render(getMarkup({ cellRenderer: cellRenderer, isScrolling: false, width: DEFAULT_WIDTH + 1 })); expect(cellRenderer).toHaveBeenCalled(); expect(cellRenderer.mock.calls[0][0].isScrolling).toBe(false); }); it('should pass the cellRenderer an :isVisible flag', function () { var cellRendererCalls = []; function cellRenderer(props) { cellRendererCalls.push(props); return defaultCellRenderer(props); } render(getMarkup({ cellRenderer: cellRenderer, height: DEFAULT_ROW_HEIGHT, overscanColumnCount: 1, overscanRowCount: 1, width: DEFAULT_COLUMN_WIDTH })); cellRendererCalls.forEach(function (props) { expect(props.isVisible).toEqual(props.columnIndex === 0 && props.rowIndex === 0); // Only the first cell is visible }); }); describe('cell caching', function () { it('should not cache cells if the Grid is not scrolling', function () { var cellRendererCalls = []; function cellRenderer(_ref9) { var columnIndex = _ref9.columnIndex, key = _ref9.key, rowIndex = _ref9.rowIndex, style = _ref9.style; cellRendererCalls.push({ columnIndex: columnIndex, rowIndex: rowIndex }); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); } var props = { cellRenderer: cellRenderer, columnWidth: 100, height: 40, rowHeight: 20, scrollToRow: 0, width: 100 }; render(getMarkup(_extends({}, props, { scrollToRow: 0 }))); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 0 }, { columnIndex: 0, rowIndex: 1 }]); cellRendererCalls.splice(0); render(getMarkup(_extends({}, props, { scrollToRow: 1 }))); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 0 }, { columnIndex: 0, rowIndex: 1 }]); }); it('should cache a cell once it has been rendered while scrolling', function () { var cellRendererCalls = []; function cellRenderer(_ref10) { var columnIndex = _ref10.columnIndex, key = _ref10.key, rowIndex = _ref10.rowIndex, style = _ref10.style; cellRendererCalls.push({ columnIndex: columnIndex, rowIndex: rowIndex }); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); } var props = { cellRenderer: cellRenderer, columnWidth: 100, height: 40, rowHeight: 20, width: 100 }; var grid = render(getMarkup(_extends({}, props, { scrollToRow: 0 }))); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 0 }, { columnIndex: 0, rowIndex: 1 }]); simulateScroll({ grid: grid, scrollTop: 1 }); cellRendererCalls.splice(0); // Rows 0-2 have already rendered but row 3 is not yet visible // This means that only row 3 should be newly-created // The others should come from the cache render(getMarkup(_extends({}, props, { scrollToRow: 3 }))); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 3 }]); }); it('should clear cache once :isScrolling is false', function () { var _ref11 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee3(done) { var cellRendererCalls, cellRenderer, props, grid; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: cellRenderer = function cellRenderer(_ref12) { var columnIndex = _ref12.columnIndex, key = _ref12.key, rowIndex = _ref12.rowIndex, style = _ref12.style; cellRendererCalls.push({ columnIndex: columnIndex, rowIndex: rowIndex }); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); }; cellRendererCalls = []; props = { cellRenderer: cellRenderer, columnWidth: 100, height: 40, rowHeight: 20, scrollToRow: 0, width: 100 }; grid = render(getMarkup(props)); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 0 }, { columnIndex: 0, rowIndex: 1 }]); simulateScroll({ grid: grid, scrollTop: 1 }); // Allow scrolling timeout to complete so that cell cache is reset _context3.next = 8; return new _Promise(function (resolve) { return setTimeout(resolve, DEFAULT_SCROLLING_RESET_TIME_INTERVAL * 2); }); case 8: cellRendererCalls.splice(0); render(getMarkup(_extends({}, props, { scrollToRow: 1 }))); expect(cellRendererCalls.length).not.toEqual(0); done(); case 12: case 'end': return _context3.stop(); } } }, _callee3, _this); })); return function (_x4) { return _ref11.apply(this, arguments); }; }()); it('should clear cache once :isScrolling via props is false', _asyncToGenerator(_regeneratorRuntime.mark(function _callee4() { var cellRenderer, props, scrollingStyle; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (params) { return React.createElement('div', { key: params.key, style: params.style }); }); props = { autoHeight: true, cellRenderer: cellRenderer, columnCount: 1, isScrolling: true, rowCount: 1 }; render(getMarkup(props)); render(getMarkup(props)); expect(cellRenderer).toHaveBeenCalledTimes(1); // Due to cell cache scrollingStyle = cellRenderer.mock.calls[0][0].style; cellRenderer.mockReset(); render(getMarkup(_extends({}, props, { isScrolling: false }))); expect(cellRenderer.mock.calls[0][0].style).toBe(scrollingStyle); expect(cellRenderer).toHaveBeenCalledTimes(1); // Reset cache cellRenderer.mockReset(); render(getMarkup(_extends({}, props, { isScrolling: true }))); expect(cellRenderer.mock.calls[0][0].style).toBe(scrollingStyle); expect(cellRenderer).toHaveBeenCalledTimes(1); // Only cached when scrolling case 15: case 'end': return _context4.stop(); } } }, _callee4, _this); }))); it('should clear cache if :recomputeGridSize is called', function () { var cellRendererCalls = []; function cellRenderer(_ref14) { var columnIndex = _ref14.columnIndex, key = _ref14.key, rowIndex = _ref14.rowIndex, style = _ref14.style; cellRendererCalls.push({ columnIndex: columnIndex, rowIndex: rowIndex }); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); } var props = { cellRenderer: cellRenderer, columnWidth: 100, height: 40, rowHeight: 20, scrollTop: 0, width: 100 }; var grid = render(getMarkup(props)); expect(cellRendererCalls).toEqual([{ columnIndex: 0, rowIndex: 0 }, { columnIndex: 0, rowIndex: 1 }]); simulateScroll({ grid: grid, scrollTop: 1 }); cellRendererCalls.splice(0); grid.recomputeGridSize(); expect(cellRendererCalls.length).not.toEqual(0); }); it('should support a custom :scrollingResetTimeInterval prop', function () { var _ref15 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee5(done) { var cellRendererCalls, scrollingResetTimeInterval, cellRenderer, props, grid; return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: cellRenderer = function cellRenderer(_ref16) { var columnIndex = _ref16.columnIndex, key = _ref16.key, rowIndex = _ref16.rowIndex, style = _ref16.style; cellRendererCalls.push({ columnIndex: columnIndex, rowIndex: rowIndex }); return defaultCellRenderer({ columnIndex: columnIndex, key: key, rowIndex: rowIndex, style: style }); }; cellRendererCalls = []; scrollingResetTimeInterval = DEFAULT_SCROLLING_RESET_TIME_INTERVAL * 2; props = { cellRenderer: cellRenderer, scrollingResetTimeInterval: scrollingResetTimeInterval }; grid = render(getMarkup(props)); expect(cellRendererCalls.length > 0).toEqual(true); simulateScroll({ grid: grid, scrollTop: 1 }); _context5.next = 9; return new _Promise(function (resolve) { return setTimeout(resolve, DEFAULT_SCROLLING_RESET_TIME_INTERVAL); }); case 9: cellRendererCalls.splice(0); render(getMarkup(_extends({}, props, { className: 'foo' }))); expect(cellRendererCalls.length).toEqual(0); _context5.next = 14; return new _Promise(function (resolve) { return setTimeout(resolve, DEFAULT_SCROLLING_RESET_TIME_INTERVAL * 2); }); case 14: cellRendererCalls.splice(0); render(getMarkup(_extends({}, props, { className: 'bar' }))); expect(cellRendererCalls.length).not.toEqual(0); done(); case 18: case 'end': return _context5.stop(); } } }, _callee5, _this); })); return function (_x5) { return _ref15.apply(this, arguments); }; }()); }); describe('measureAllCells', function () { it('should measure any unmeasured columns and rows', function () { var grid = render(getMarkup({ columnCount: 10, columnWidth: function columnWidth() { return 100; }, estimatedColumnSize: 150, estimatedRowSize: 15, height: 0, rowCount: 10, rowHeight: function rowHeight() { return 20; }, width: 0 })); expect(grid._columnSizeAndPositionManager.getTotalSize()).toEqual(1500); expect(grid._rowSizeAndPositionManager.getTotalSize()).toEqual(150); grid.measureAllCells(); expect(grid._columnSizeAndPositionManager.getTotalSize()).toEqual(1000); expect(grid._rowSizeAndPositionManager.getTotalSize()).toEqual(200); }); }); describe('recomputeGridSize', function () { it('should recompute cell sizes and other values when called', function () { var columnIndices = []; var rowIndices = []; function columnWidth(_ref17) { var index = _ref17.index; columnIndices.push(index); return 10; } function rowHeight(_ref18) { var index = _ref18.index; rowIndices.push(index); return 10; } var props = { columnCount: 50, columnWidth: columnWidth, height: 50, rowHeight: rowHeight, rowCount: 50, width: 100 }; var component = render(getMarkup(props)); columnIndices.splice(0); rowIndices.splice(0); component.recomputeGridSize(); // Only the rows required to fill the current viewport will be rendered expect(columnIndices[0]).toEqual(0); expect(columnIndices[columnIndices.length - 1]).toEqual(9); expect(rowIndices[0]).toEqual(0); expect(rowIndices[rowIndices.length - 1]).toEqual(4); columnIndices.splice(0); rowIndices.splice(0); component.recomputeGridSize({ columnIndex: 4, rowIndex: 2 }); // Only the rows required to fill the current viewport will be rendered expect(columnIndices[0]).toEqual(4); expect(columnIndices[columnIndices.length - 1]).toEqual(9); expect(rowIndices[0]).toEqual(2); expect(rowIndices[rowIndices.length - 1]).toEqual(4); }); }); describe('autoContainerWidth', function () { it('should set the innerScrollContainer width to auto to better support single-column HOCs', function () { var props = { autoContainerWidth: true }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer').style.width).toEqual('auto'); }); it('should set the innerScrollContainer width to :totalColumnsWidth unless :autoContainerWidth', function () { var props = { autoContainerWidth: false }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer').style.width).toEqual('2500px'); // 50 columns x 50px }); }); describe('autoHeight', function () { it('should set the container height to auto to adjust to innerScrollContainer height', function () { var props = { autoHeight: true }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.style.height).toEqual('auto'); }); it('should have container height still affecting number of rows rendered', function () { var props = { height: 500, autoHeight: true }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.querySelectorAll('.gridItem').length).toEqual(100); // 25 rows x 4 columns }); it('should have innerScrollContainer height to be equal number of rows * rowHeight', function () { var props = { autoHeight: true }; var grid = render(getMarkup(props)); var rendered = findDOMNode(grid); expect(rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer').style.height).toEqual('2000px'); // 100 rows * 20px rowHeight expect(grid._rowSizeAndPositionManager.getTotalSize()).toEqual(2000); }); }); describe('autoWidth', function () { it('should set the container width to auto to adjust to innerScrollContainer width', function () { var props = { autoWidth: true }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.style.width).toEqual('auto'); }); it('should have container width still affecting number of columns rendered', function () { var props = { width: 500, autoWidth: true }; var rendered = findDOMNode(render(getMarkup(props))); expect(rendered.querySelectorAll('.gridItem').length).toEqual(50); // 5 rows x 10 columns }); it('should have innerScrollContainer width to be equal number of columns * columnWidth', function () { var props = { autoWidth: true }; var grid = render(getMarkup(props)); var rendered = findDOMNode(grid); expect(rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer').style.width).toEqual('2500px'); // 50 columns * 50px columnWidth expect(grid._columnSizeAndPositionManager.getTotalSize()).toEqual(2500); }); }); describe('tabIndex', function () { it('should be focusable by default', function () { var rendered = findDOMNode(render(getMarkup())); expect(rendered.tabIndex).toEqual(0); }); it('should allow tabIndex to be overridden', function () { var rendered = findDOMNode(render(getMarkup({ tabIndex: -1 }))); expect(rendered.tabIndex).toEqual(-1); }); }); describe('role', function () { it('should have grid role by default', function () { var rendered = findDOMNode(render(getMarkup())); expect(rendered.getAttribute('role')).toEqual('grid'); }); it('should allow role to be overridden', function () { var role = null; var rendered = findDOMNode(render(getMarkup({ role: role }))); expect(rendered.getAttribute('role')).toEqual(role); }); }); describe('pure', function () { it('should not re-render unless props have changed', function () { var cellRendererCalled = false; function cellRenderer(_ref19) { var key = _ref19.key, style = _ref19.style; cellRendererCalled = true; return React.createElement('div', { key: key, style: style }); } var markup = getMarkup({ cellRenderer: cellRenderer }); render(markup); expect(cellRendererCalled).toEqual(true); cellRendererCalled = false; render(markup); expect(cellRendererCalled).toEqual(false); }); it('should not re-render grid components if they extend PureComponent', function () { var componentUpdates = 0; var GridComponent = function (_React$PureComponent) { _inherits(GridComponent, _React$PureComponent); function GridComponent() { _classCallCheck(this, GridComponent); return _possibleConstructorReturn(this, (GridComponent.__proto__ || _Object$getPrototypeOf(GridComponent)).apply(this, arguments)); } _createClass(GridComponent, [{ key: 'componentDidUpdate', value: function componentDidUpdate() { componentUpdates++; } }, { key: 'render', value: function render() { var _props = this.props, columnIndex = _props.columnIndex, rowIndex = _props.rowIndex, style = _props.style; return React.createElement( 'div', { className: 'gridItem', style: style }, 'row:' + rowIndex + ', column:' + columnIndex ); } }]); return GridComponent; }(React.PureComponent); function cellRenderer(_ref20) { var columnIndex = _ref20.columnIndex, key = _ref20.key, rowIndex = _ref20.rowIndex, style = _ref20.style; return React.createElement(GridComponent, { key: key, columnIndex: columnIndex, rowIndex: rowIndex, style: style }); } var props = { cellRenderer: cellRenderer, columnWidth: 100, height: 40, rowHeight: 20, scrollTop: 0, width: 100 }; var grid = render(getMarkup(props)); simulateScroll({ grid: grid, scrollTop: 1 }); expect(componentUpdates).toEqual(0); }); it('should clear all but the visible rows from the style cache once :isScrolling is false', function () { var _ref21 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee6(done) { var props, grid; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: props = { columnWidth: 50, height: 100, overscanColumnCount: 0, overscanRowCount: 0, rowHeight: 50, width: 100 }; grid = render(getMarkup(props)); expect(_Object$keys(grid._styleCache).length).toBe(4); simulateScroll({ grid: grid, scrollTop: 50 }); expect(_Object$keys(grid._styleCache).length).toBe(6); // Allow scrolling timeout to complete so that cell cache is reset _context6.next = 7; return new _Promise(function (resolve) { return setTimeout(resolve, DEFAULT_SCROLLING_RESET_TIME_INTERVAL * 2); }); case 7: expect(_Object$keys(grid._styleCache).length).toBe(4); done(); case 9: case 'end': return _context6.stop(); } } }, _callee6, _this); })); return function (_x6) { return _ref21.apply(this, arguments); }; }()); it('should clear style cache if :recomputeGridSize is called', function () { var props = { columnWidth: 50, height: 100, overscanColumnCount: 0, overscanRowCount: 0, rowHeight: 50, width: 100 }; var grid = render(getMarkup(props)); expect(_Object$keys(grid._styleCache).length).toBe(4); render(getMarkup(_extends({}, props, { scrollTop: 50 }))); expect(_Object$keys(grid._styleCache).length).toBe(6); grid.recomputeGridSize(); expect(_Object$keys(grid._styleCache).length).toBe(4); }); it('should clear style cache if cell sizes change', function () { var cellRendererCalls = []; function cellRenderer(params) { cellRendererCalls.push(params); return React.createElement('div', { key: params.key, style: params.style }); } var props = { cellRenderer: cellRenderer, columnWidth: 100, height: 100, overscanColumnCount: 0, overscanRowCount: 0, rowHeight: 100, width: 100 }; render(getMarkup(props)); expect(cellRendererCalls.length).toEqual(1); expect(cellRendererCalls[0].style.width).toEqual(100); render(getMarkup(_extends({}, props, { columnWidth: 50, width: 50 }))); expect(cellRendererCalls.length).toEqual(2); expect(cellRendererCalls[1].style.width).toEqual(50); }); }); it('should not pull from the style cache while scrolling if there is an offset adjustment', function () { var cellRendererCalls = []; function cellRenderer(params) { cellRendererCalls.push(params); return React.createElement('div', { key: params.key, style: params.style }); } var grid = render(getMarkup({ cellRenderer: cellRenderer, width: 100, height: 100, rowHeight: 100, columnWidth: 100, rowCount: DEFAULT_MAX_SCROLL_SIZE * 2 / 100, // lots of offset scrollTop: 2000 })); simulateScroll({ grid: grid, scrollTop: 2100 }); // cellRendererCalls[0] is the element at rowIndex 0 var firstProps = cellRendererCalls[1]; var secondProps = cellRendererCalls[2]; expect(cellRendererCalls.length).toEqual(3); expect(firstProps.style).not.toBe(secondProps.style); }); it('should only cache styles when a :deferredMeasurementCache is provided if the cell has already been measured', function () { var cache = new CellMeasurerCache({ fixedWidth: true }); cache.set(0, 0, 100, 100); cache.set(1, 1, 100, 100); var grid = render(getMarkup({ columnCount: 2, deferredMeasurementCache: cache, rowCount: 2 })); var keys = _Object$keys(grid._styleCache); expect(keys).toEqual(['0-0', '1-1']); }); describe('DEV warnings', function () { it('should warn about cells that forget to include the :style property', function () { spyOn(console, 'warn'); function cellRenderer(params) { return React.createElement('div', { key: params.key }); } render(getMarkup({ cellRenderer: cellRenderer })); expect(console.warn).toHaveBeenCalledWith('Rendered cell should include style property for positioning.'); expect(console.warn).toHaveBeenCalledTimes(1); }); it('should warn about CellMeasurer measured cells that forget to include the :style property', function () { spyOn(console, 'warn'); var cache = new CellMeasurerCache({ fixedWidth: true }); var cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (params) { return React.createElement( CellMeasurer, { cache: cache, columnIndex: params.columnIndex, key: params.key, parent: params.parent, rowIndex: params.rowIndex, style: params.style }, React.createElement('div', null) ); }); render(getMarkup({ cellRenderer: cellRenderer, columnCount: 1, deferredMeasurementCache: cache, rowCount: 1 })); expect(console.warn).toHaveBeenCalledWith('Rendered cell should include style property for positioning.'); expect(console.warn).toHaveBeenCalledTimes(1); }); }); describe('deferredMeasurementCache', function () { it('invalidateCellSizeAfterRender should invalidate cache and refresh displayed cells after mount', function () { var cache = new CellMeasurerCache({ fixedWidth: true }); var invalidateCellSizeAfterRender = true; var cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (params) { // Don't get stuck in a loop if (invalidateCellSizeAfterRender) { invalidateCellSizeAfterRender = false; params.parent.invalidateCellSizeAfterRender({ columnIndex: 1, rowIndex: 0 }); } return React.createElement('div', { key: params.key, style: params.style }); }); var props = { cellRenderer: cellRenderer, columnCount: 2, deferredMeasurementCache: cache, rowCount: 2 }; render(getMarkup(props)); // 4 times for initial render + 4 once cellCache was cleared expect(cellRenderer).toHaveBeenCalledTimes(8); }); it('should invalidate cache and refresh displayed cells after update', function () { var cache = new CellMeasurerCache({ fixedWidth: true }); var cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (params) { return React.createElement('div', { key: params.key, style: params.style }); }); var props = { cellRenderer: cellRenderer, columnCount: 2, deferredMeasurementCache: cache, rowCount: 2 }; var grid = render(getMarkup(props)); expect(cellRenderer).toHaveBeenCalledTimes(4); var invalidateCellSizeAfterRender = false; cellRenderer.mockReset(); cellRenderer.mockImplementation(function (params) { // Don't get stuck in a loop if (invalidateCellSizeAfterRender) { invalidateCellSizeAfterRender = false; params.parent.invalidateCellSizeAfterRender({ columnIndex: 1, rowIndex: 0 }); } return React.createElement('div', { key: params.key, style: params.style }); }); invalidateCellSizeAfterRender = true; grid.recomputeGridSize(); // 4 times for initial render + 4 once cellCache was cleared expect(cellRenderer).toHaveBeenCalledTimes(8); }); it('should not cache cells until they have been measured by CellMeasurer', function () { var cache = new CellMeasurerCache({ fixedWidth: true }); // Fake measure cell 0,0 but not cell 0,1 cache.set(0, 0, 100, 30); var cellRenderer = jest.fn(); cellRenderer.mockImplementation(function (params) { return React.createElement('div', { key: params.key, style: params.style }); }); var props = { cellRenderer: cellRenderer, columnCount: 2, deferredMeasurementCache: cache, rowCount: 1 }; // Trigger 2 renders // The second render should re-use the style for cell 0,0 // But should not re-use the style for cell 0,1 since it was not measured var grid = render(getMarkup(props)); grid.forceUpdate(); // 0,0 - 0,1 - 0,0 - 0,1 expect(cellRenderer).toHaveBeenCalledTimes(4); var style00A = cellRenderer.mock.calls[0][0].style; var style01A = cellRenderer.mock.calls[1][0].style; var style00B = cellRenderer.mock.calls[2][0].style; var style01B = cellRenderer.mock.calls[3][0].style; expect(style00A).toBe(style00B); expect(style01A).not.toBe(style01B); }); }); });
src/components/Nav.js
limal/wolnik
import React from 'react'; import { Link } from 'gatsby'; export default function Nav({ onMenuToggle = () => {} }) { return ( <nav id="nav"> <ul> <li className="special"> <a href="#menu" onClick={e => { e.preventDefault(); onMenuToggle(); }} className="menuToggle" > <span>Menu</span> </a> <div id="menu"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/Generic">Generic Page</Link> </li> <li> <Link to="/Elements">Elements</Link> </li> </ul> <a className="close" onClick={e => { e.preventDefault(); onMenuToggle(); }} href="#menu" > {''} </a> </div> </li> </ul> </nav> ); }
src/Input.js
victorzhang17/react-bootstrap
import React from 'react'; import InputBase from './InputBase'; import * as FormControls from './FormControls'; import deprecationWarning from './utils/deprecationWarning'; class Input extends InputBase { render() { if (this.props.type === 'static') { deprecationWarning('Input type=static', 'StaticText'); return <FormControls.Static {...this.props} />; } return super.render(); } } Input.propTypes = { type: React.PropTypes.string }; export default Input;
src/components/TodoList.js
JarmoLaine/ModernWebDev
import React from 'react'; import Todo from './Todo'; const TodoList = ({ todos, onRemove, onToggle }) => <div> <h2>{todos.count()} items in my todo list</h2> <ul> {todos .map((todo, i) => <Todo key={i} onToggle={onToggle} onRemove={onRemove} todo={todo} /> ) } </ul> </div> export default TodoList;
src/main/index.js
tomaszkepa/san-antonio-tourist
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.getElementById('app'), );
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
Chronister/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'; 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 '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 }} 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'> <i className={`fa fa-fw fa-${item.icon}`} /> </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(); 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; } } handleClose = () => { 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-alt', 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) === 0 })}> <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} 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> ); } }
js/components/inputgroup/regular.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, Text, Body, Left, Right, Input, Item } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; const { popRoute, } = actions; class Regular extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Regular</Title> </Body> <Right /> </Header> <Content padder> <Item regular> <Input placeholder="Regular Textbox" /> </Item> </Content> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Regular);
src/Badge.js
15lyfromsaturn/react-materialize
import React from 'react'; import cx from 'classnames'; class Badge extends React.Component { render() { let { className, newIcon, children, ...props } = this.props; let classes = { badge: true, 'new': newIcon }; return ( <span className={cx(classes, className)} {...props}> {children} </span> ); } } Badge.propTypes = { /** * Add the <b>new</b> class name */ newIcon: React.PropTypes.bool }; export default Badge;
spec/react/siteframe/header.spec.js
pivotal-cf/pivotal-ui
import React from 'react'; import ReactDOM from 'react-dom'; import {FlexCol} from '../../../src/react/flex-grids'; import {Header} from '../../../src/react/siteframe/header'; describe('Header', () => { describe('with a string companyName', () => { beforeEach(() => { ReactDOM.render(<Header {...{companyName: 'Pivotal'}}/>, root); }); it('renders a grid with one column', () => { expect('.pui-siteframe-header').toHaveClass('grid'); expect('.pui-siteframe-header > .col.pui-siteframe-header-title').toHaveLength(1); }); it('renders a fixed column with the company name', () => { expect('.pui-siteframe-header .col.pui-siteframe-header-title').toHaveClass('col-fixed'); expect('.pui-siteframe-header .col.pui-siteframe-header-title h4').toContainText('Pivotal'); }); it('does not render a span containing the product name', () => { expect('.pui-siteframe-header .col.pui-siteframe-header-title h4 span').not.toExist(); }); }); describe('with a node companyName', () => { beforeEach(() => { ReactDOM.render(<Header {...{companyName: <a href="#">Pivotal</a>}}/>, root); }); it('renders a grid with one column', () => { expect('.pui-siteframe-header').toHaveClass('grid'); expect('.pui-siteframe-header > .col.pui-siteframe-header-title').toHaveLength(1); }); it('renders a fixed column with the company name', () => { expect('.pui-siteframe-header .col.pui-siteframe-header-title').toHaveClass('col-fixed'); expect('.pui-siteframe-header .col.pui-siteframe-header-title h4 a').toContainText('Pivotal'); }); it('does not render a span containing the product name', () => { expect('.pui-siteframe-header .col.pui-siteframe-header-title h4 span').not.toExist(); }); }); describe('with props', () => { let className, companyName, onClick, logoSrc, productName, cols, logo; beforeEach(() => { className = 'other-class-name'; companyName = 'some-company-name'; onClick = jasmine.createSpy('onClick'); logoSrc = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; logo = <a {...{onClick}}><img src={logoSrc}/></a>; productName = <a href="#">some-product-name</a>; cols = [<FlexCol>first custom column</FlexCol>, <FlexCol>second custom column</FlexCol>]; ReactDOM.render(<Header {...{className, cols, companyName, logo, productName}}/>, root); }); it('renders a grid with four columns', () => { expect('.pui-siteframe-header').toHaveClass('grid'); expect('.pui-siteframe-header > .col').toHaveLength(4); }); it('adds any additional class names to the header', () => { expect('.pui-siteframe-header').toHaveClass('other-class-name'); }); it('renders a fixed first column with the logo', () => { expect('.pui-siteframe-header .col:eq(0)').toHaveClass('col-fixed'); expect('.pui-siteframe-header .col:eq(0) a img').toHaveAttr('src', logoSrc); }); it('renders a fixed second column with the company and product names', () => { expect('.pui-siteframe-header .col:eq(1)').toHaveClass('col-fixed'); expect('.pui-siteframe-header .col:eq(1) h4').toContainText(companyName); expect('.pui-siteframe-header .col:eq(1) h4 span.em-high a').toHaveText('some-product-name'); }); it('renders the first custom column', () => { expect('.pui-siteframe-header .col:eq(2)').toHaveText('first custom column'); }); it('renders the second custom column', () => { expect('.pui-siteframe-header .col:eq(3)').toHaveText('second custom column'); }); }); });
example/index.js
tether/react-download-ios
/** * Dependencies. */ import React from 'react' import ReactDOM from 'react-dom' import Badge from '..' /** * Render badge. */ ReactDOM.render( <Badge id="com.petrofeed.workidapp"/>, document.querySelector('main') )
client/src/components/SignupForm.js
richb-hanover/reactathon
import React from 'react'; import validator from 'validator'; import { FormErrors } from './partials'; import { Button, Input, ButtonInput } from 'react-bootstrap'; import { AppActions } from '../actions/AppActions'; import { AppStore } from '../stores/AppStore'; export class SignupForm extends React.Component { constructor() { super(); this.state = { ...AppStore.getState(), username: '', password: '', email: '' }; this.onChange = this.onChange.bind(this); } componentDidMount() { AppStore.listen(this.onChange); } componentWillUnmount() { AppStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } clearState = () => { this.setState({ username: '', password: '', email: '' }); }; handleUsernameChange = (e => this.onChange( {username: e.target.value}) ); handlePasswordChange = (e => this.onChange( {password: e.target.value}) ); handleEmailChange = (e => this.onChange( {email: e.target.value}) ); validate = () => { var errors = []; var { username, password, email } = this.state; const rules = [ { failOn: !validator.isEmail(email), error: 'Please use a valid email address' }, { failOn: username.trim().length < 4, error: 'Username must be at least 4 characters' }, { failOn: password.trim().length < 5, error: 'Password must be at least 5 characters' } ]; rules.forEach((rule) => { if (rule.failOn) { errors.push(rule); } }); if (errors.length) { return { errors: errors, valid: false }; } else { return { errors: null, valid: true }; } }; handleSubmit = (e) => { e.preventDefault(); var valid = this.validate(); if (valid.errors) { let article = valid.errors.length > 1 ? 'are' : 'is'; let noun = valid.errors.length > 1 ? 'errors' : 'error'; let count = valid.errors.length > 1 ? valid.errors.length : 'one'; this.setState({ error: { message: `There ${article} ${count} ${noun}, please try again.`, data: valid.errors } }); return; } AppActions.signup({ username: this.state.username, password: this.state.password, email: this.state.email }); }; render() { // handlers let { handleSubmit, handleUsernameChange, handlePasswordChange, handleEmailChange } = this; // state let { error, username, password, email } = this.state; return ( <section> {error ? <FormErrors {...error} /> : ''} <form onSubmit={handleSubmit}> <h4>Create an Account</h4> <hr/> <Input disabled={this.state.signupPending} type="text" label="Username" value={username} onChange={handleUsernameChange} placeholder="Enter a username" /> <Input disabled={this.state.signupPending} type="email" label="Email Address" value={email} onChange={handleEmailChange} placeholder="Enter email" /> <Input disabled={this.state.signupPending} type="password" value={password} onChange={handlePasswordChange} label="Password" /> {this.state.signupPending ? <Button disabled>Signing up...</Button> : <ButtonInput bsStyle="primary" type="submit" value="Signup" /> } </form> </section> ); } }
src/svg-icons/image/filter-center-focus.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterCenterFocus = (props) => ( <SvgIcon {...props}> <path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ImageFilterCenterFocus = pure(ImageFilterCenterFocus); ImageFilterCenterFocus.displayName = 'ImageFilterCenterFocus'; ImageFilterCenterFocus.muiName = 'SvgIcon'; export default ImageFilterCenterFocus;
src/layouts/Card/CardLayout.js
armaanshah96/lunchbox
import React from 'react' import { IndexLink, Link } from 'react-router' import PropTypes from 'prop-types' import Avatar from 'material-ui/Avatar'; import Checkbox from 'material-ui/Checkbox'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import FileFolder from 'material-ui/FontIcon'; import { List, ListItem } from 'material-ui/List'; export const CardLayout = ({ id, children, check, name, details, selectedRestaurantId }) => { const avatar = <Avatar icon={<FileFolder />} />; const updateCheck = function(event, isInputChecked) { check(isInputChecked, id) } console.log(id, selectedRestaurantId) const checkbox = <Checkbox onCheck={updateCheck}/> const boom = ( <List> <ListItem leftCheckbox={ checkbox } rightAvatar={ avatar } primaryText={ name } secondaryText={ details } ></ListItem> </List> ) return ( <Card> <CardText children={ boom } /> </Card> ); } CardLayout.propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, details: PropTypes.string.isRequired, children: PropTypes.node, check: PropTypes.func.isRequired, selectedRestaurantId: PropTypes.string.isRequired } export default CardLayout
app/components/Pages/Team.js
alexpell00/FRCUltimateManager
/* * @Author: alexpelletier * @Date: 2016-03-23 22:17:30 * @Last Modified by: alexpelletier * @Last Modified time: 2016-03-24 05:44:31 */ import React from 'react'; import request from 'superagent'; import MatchesTable from '../Elements/MatchesTable' import PitStats from '../Elements/PitStats' import RobotStats from '../Elements/RobotStats' var Team = React.createClass({ getInitialState() { return {team:{}}; }, componentDidMount() { request .post('/Api/Teams/GetSingle') .send({'teamid':this.props.params.teamid}) .set('Accept', 'application/json') .end(function(err, res){ let team = JSON.parse(res.text); this.setState({ team: team }); }.bind(this)); }, render: function() { return ( <div className="content container"> <h2 className="page-title">Team <small></small></h2> <section className="widget"> <div className="row"> <div className="body col-sm-7"> <div className="row"> <div className="col-sm-4"> <div className="text-align-center"> <img className="img-circle" src="img/15.jpg" alt="64x64" style={{height: "112px"}}/> </div> </div> <div className="col-sm-8"> <h3 className="mt-sm mb-xs">{this.state.team.name}</h3> <address> <abbr title="">#</abbr>{this.state.team.number}<br/> <abbr title="">Location: </abbr>{this.state.team.location}<br/> <abbr title="">Website: </abbr><a href={this.state.team.website} target='_blank'>{this.state.team.website}</a><br/> </address> </div> </div> </div> </div> </section> <section className="widget widget-tabs"> <header> <ul className="nav nav-tabs"> <li className="active"> <a href="#matches" data-toggle="tab">Matches</a> </li> <li> <a href="#matchstats" data-toggle="tab">Match Stats</a> </li> <li> <a href="#robotstats" data-toggle="tab">Robot Stats</a> </li> <li> <a href="#pitstats" data-toggle="tab">Pit Stats</a> </li> </ul> </header> <div className="body tab-content"> <div id="matches" className="tab-pane active clearfix"> <MatchesTable teamid={this.props.params.teamid}/> </div> <div id="matchstats" className="tab-pane"> </div> <div id="robotstats" className="tab-pane"> <RobotStats teamid={this.props.params.teamid}/> </div> <div id="pitstats" className="tab-pane"> <PitStats teamid={this.props.params.teamid}/> </div> </div> </section> </div> ); } }); module.exports = Team;
src/components/docs/callout.js
nordsoftware/react-foundation-docs
import React from 'react'; import Playground from 'component-playground'; import { Colors, Sizes, Grid, Cell, Callout, } from 'react-foundation'; export const CalloutDocs = () => ( <section className="callout-docs"> <Grid> <Cell large={12}> <h2>Callout</h2> <div> <h3>Basics</h3> <Playground codeText={require('raw-loader!../examples/callout/basics').default} scope={{ React, Callout }} theme="eiffel"/> </div> <div> <h3>Coloring</h3> <Playground codeText={require('raw-loader!../examples/callout/colors').default} scope={{ React, Colors, Callout }} theme="eiffel"/> </div> <div> <h3>Sizing</h3> <Playground codeText={require('raw-loader!../examples/callout/sizes').default} scope={{ React, Sizes, Callout }} theme="eiffel"/> </div> </Cell> </Grid> </section> ); export default CalloutDocs;
submissions/leoasis/src/JediSlot.js
staltz/flux-challenge
import React from 'react'; export default class JediSlot extends React.Component { render() { const { jedi } = this.props; return <li className="css-slot"> {jedi && !jedi.fetching && <div style={jedi.isInCurrentPlanet ? { color: 'red' } : null}> <h3>{jedi.name}</h3> <h6>Homeworld: {jedi.homeworld.name}</h6> </div>} </li> } }
Console/app/node_modules/rc-slider/es/common/Track.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; /* eslint-disable react/prop-types */ import React from 'react'; var Track = function Track(props) { var className = props.className, included = props.included, vertical = props.vertical, offset = props.offset, length = props.length, style = props.style; var positonStyle = vertical ? { bottom: offset + '%', height: length + '%' } : { left: offset + '%', width: length + '%' }; var elStyle = _extends({ visibility: included ? 'visible' : 'hidden' }, style, positonStyle); return React.createElement('div', { className: className, style: elStyle }); }; export default Track;
docs/app/Examples/collections/Grid/Content/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const GridContentExamples = () => ( <ExampleSection title='Content'> <ComponentExample title='Rows' description='A row is a horizontal grouping of columns.' examplePath='collections/Grid/Content/GridExampleRows' /> <ComponentExample title='Columns' description='Columns each contain gutters giving them equal spacing from other columns.' examplePath='collections/Grid/Content/GridExampleColumns' /> </ExampleSection> ) export default GridContentExamples
src/client.js
MeetDay/dreampark-web
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { match, Router, browserHistory, applyRouterMiddleware } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect } from 'redux-async-connect' import { useScroll } from 'react-router-scroll'; import APIClient from './helpers/APIClient'; import createStore from './store'; import routes from './routes'; const client = new APIClient(); const store = createStore(browserHistory, client, window.__redux_data__); const history = syncHistoryWithStore(browserHistory, store); const userReduxConnect = () => ({ renderRouterContext: (child, props) => ( <ReduxAsyncConnect {...props} helpers={{ client, serverSide: false }} filter={item => item.deferred}> { child } </ReduxAsyncConnect> ) }); const dest = document.getElementById("app"); match({ history, routes: routes(store) }, (error, redirectLocation, renderProps) => { const component = ( <Provider store={store} key="provider"> <Router {...renderProps} history={history} render={ applyRouterMiddleware(useScroll(), userReduxConnect()) } /> </Provider> ); ReactDOM.render(component, dest); })
src/components/LoginForm/LoginForm.js
Nuriddinkhuja/photoshare
import React, { Component } from 'react'; import { reduxForm, propTypes, Field } from 'redux-form'; import { Form, Input, Button } from 'semantic-ui-react'; import loginValidation from './loginValidation'; @reduxForm({ form: 'login', validate: loginValidation }) export default class LoginForm extends Component { static propTypes = { ...propTypes } renderInput = ({ input, placeholder, type, meta: { touched, error } }) => { let errorText; if (error && touched) { errorText = error; } else { errorText = ''; } return <Input {...input} type={type} placeholder={placeholder} error={!!errorText} />; } render() { const { handleSubmit, error } = this.props; return ( <div className="ui middle aligned center aligned grid"> <div className="column"> <h2 className="ui white image header"> <div className="content"> Log-in to your account </div> </h2> {error && <p className="text-danger"><strong>{error}</strong></p>} <Form onSubmit={handleSubmit}> <div className="ui stacked segment"> <Form.Field > <div className="ui left icon input"> <i className="user icon"></i> <Field name="email" type="text" component={this.renderInput} placeholder="Email" /> </div> </Form.Field> <Form.Field > <div className="ui left icon input"> <i className="user icon"></i> <Field name="password" type="password" component={this.renderInput} placeholder="Password" /> </div> </Form.Field> <Button type="submit" className="fluid teal">Submit</Button> </div> </Form> </div> </div> ); } }
components/value_validation_component.js
KingHenne/react-common
import React from 'react'; import validate from '../utils/validate'; import validationStates from '../utils/validation_states'; // ValueValidationComponent is an abstract component. // The static props of this class will not be inherited on IE <= 10, // see: https://babeljs.io/docs/usage/caveats/#classes-10-and-below- export default class ValueValidationComponent extends React.Component { static validationProps = [ 'required', 'pattern', 'type', 'minAge', 'maxAge' ] state = { value: this.props.value, valid: this.props.value ? this.isValid(this.props.value) : undefined } componentDidMount() { if (this.props.onValidation) { // Send the initial valid state to the parent component. this.props.onValidation(this.props.name, this.state.valid, this.props.disabled); } } componentWillReceiveProps(nextProps) { if (nextProps.value != this.props.value && nextProps.value != this.state.value) { this.setState({ value: nextProps.value }, () => { this.validate(); }); } else if (nextProps.shouldValidate && !this.props.shouldValidate) { this.validate(true); } else if (nextProps.disabled != this.props.disabled && nextProps.onValidation) { nextProps.onValidation(nextProps.name, this.state.valid, nextProps.disabled); } } shouldComponentUpdate(nextProps, nextState) { // Ignore resetting of the validation request. if (nextProps.shouldValidate == false && this.props.shouldValidate) { return false; } return true; } // Can be override when other properties of target shall be used as value. getValueFromTarget(target) { return target.value; } handleChange(e) { var value = this.getValueFromTarget(e.target); this.setState({value}, () => { this.validate(); if (this.props.onChange) { this.props.onChange(value); } }); } handleBlur() { if (this.state.value) this.validate(true); } validate(alwaysChangeValidState = false) { var valid = this.isValid(this.state.value); var fromPendingToValid = this.state.valid == validationStates.PENDING && valid; var validChanged = this.state.valid != validationStates.PENDING && this.state.valid != valid; if (fromPendingToValid || validChanged || alwaysChangeValidState) { this.setState({valid}); if (this.props.onValidation) { this.props.onValidation(this.props.name, valid, this.props.disabled); } } return valid; } // Returns true (valid), false (invalid) or undefined (pending). isValid(value) { // Non-required fields with falsy values are valid, // regardless of their other validation props: if (!this.props.required && !value) return validationStates.VALID; // Otherwise every validation prop must be evaluated. return ValueValidationComponent.validationProps.every(function(prop) { if (prop in this.props) { return validate(prop, this.props[prop], value); } return validationStates.VALID; }, this); } }
app/components/PreviewExperimentComponent.js
openexp/OpenEXP
// @flow import React, { Component } from 'react'; import { Experiment } from 'jspsych-react'; import { Segment } from 'semantic-ui-react'; import callbackHTMLDisplay from '../utils/jspsych/plugins/callback-html-display'; import callbackImageDisplay from '../utils/jspsych/plugins/callback-image-display'; import { parseTimeline, instantiateTimeline, getImages } from '../utils/jspsych/functions'; import { MainTimeline, Trial, ExperimentParameters } from '../constants/interfaces'; interface Props { params: ExperimentParameters; isPreviewing: boolean; mainTimeline: MainTimeline; trials: { [string]: Trial }; timelines: {}; } export default class PreviewExperimentComponent extends Component<Props> { props: Props; handleTimeline: () => void; constructor(props: Props) { super(props); this.handleTimeline = this.handleTimeline.bind(this); } handleTimeline() { const timeline = instantiateTimeline( parseTimeline( this.props.params, this.props.mainTimeline, this.props.trials, this.props.timelines ), (value, time) => {}, // event callback () => {}, // start callback () => {}, // stop callback this.props.params.showProgessBar ); return timeline; } handleImages() { return getImages(this.props.params); } // This function could be used in the future in order to load custom pre-coded jspsych experiments // async handleCustomExperimentLoad() { // const timelinePath = await loadFromSystemDialog(FILE_TYPES.TIMELINE); // } render() { if (!this.props.isPreviewing) { return <Segment basic />; } return ( <Experiment settings={{ timeline: this.handleTimeline(), show_progress_bar: this.props.params.showProgessBar, auto_update_progress_bar: false, preload_images: this.handleImages() }} plugins={{ 'callback-image-display': callbackImageDisplay, 'callback-html-display': callbackHTMLDisplay }} /> ); } }
src/layouts/layout-5-1.js
nuruddeensalihu/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} </div> <div className="vertical"> {components[1]} {components[2]} {components[3]} {components[4]} </div> </div> );
src/components/PullRequest.js
nchaulet/bitbucket-team-pullrequests
import React from 'react'; import moment from 'moment'; import PullRequestDate from './PullRequestDate'; class PullRequest extends React.Component { render() { const {pr} = this.props; const avatarStyle = { marginRight: 10 }; const approved = pr.participants.reduce((sum, participant) => { return sum + (participant.approved ? 1 : 0); }, 0); const old = moment(pr.updated_on).diff(new Date()) * -1 / 1000 / 60 / 60 > 20; const statusClass = "bg-" + (approved ? 'success': 'info'); const pullRequestStyle = { padding: '10px', marginTop: 10, borderRadius: '4px', fontSize: '1.4em' }; const pullRequestTitleStyle = { fontSize: '1.1em', marginLeft: 40, }; return ( <div className={statusClass} style={pullRequestStyle}> <span className="pull-right small"> {approved != 0 ? ( <div><i className="fa fa-thumbs-o-up"></i> {approved}</div> ) : null} {approved != 0 ? ( <br/> ): null} {pr.commentsCount != 0 ? ( <div><i className="fa fa-comment-o"></i> {pr.commentsCount}</div> ) : null} </span> <img className="img-circle pull-left" style={avatarStyle} width="30" src={pr.author.links.avatar.href} /> <div style={pullRequestTitleStyle}> <a href={pr.links.html.href} target="_blank"> {pr.title} <br/> <small> {pr.source.repository.full_name} <br/><i className="fa fa-clock-o"></i> <PullRequestDate date={pr.updated_on}/> </small> </a> </div> <div className="clearfix" /> </div> ); } } export default PullRequest;
src/interface/ReportSelectionHeader.js
yajinni/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Trans } from '@lingui/macro'; import { ReactComponent as Logo } from 'interface/images/logo.svg'; import AlertWarning from 'interface/AlertWarning'; import { getReportHistory } from 'interface/selectors/reportHistory'; import NameSearch, { SearchType } from 'interface/NameSearch'; import ReportIcon from 'interface/icons/Events'; import CharacterIcon from 'interface/icons/Person'; import GuildIcon from 'interface/icons/People'; import ReportSelecter from './ReportSelecter'; import ReportHistory from './ReportHistory'; import './Header.scss'; const STATE_SEARCH_REPORT = 0; const STATE_SEARCH_CHAR = 1; const STATE_SEARCH_GUILD = 2; class ReportSelectionHeader extends React.PureComponent { static propTypes = { reportHistory: PropTypes.array.isRequired, }; constructor(props) { super(props); this.state = { searchType: STATE_SEARCH_REPORT, }; this.handleCharacterSearchClick = this.handleCharacterSearchClick.bind(this); this.handleReportSearchClick = this.handleReportSearchClick.bind(this); this.handleGuildSearchClick = this.handleGuildSearchClick.bind(this); } handleCharacterSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_CHAR, }); } handleReportSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_REPORT, }); } handleGuildSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_GUILD, }); } renderSearch() { switch (this.state.searchType) { case STATE_SEARCH_CHAR: return ( <> <NameSearch type={SearchType.CHARACTER} /> <br /> <AlertWarning> <Trans id="interface.home.reportSelectionHeader.onlyRankedWCLogs"> The character page will only show fights that have been ranked by Warcraft Logs. Wipes are not included and during busy periods there might be a delay before new reports appear. You can still analyze these fights by manually finding the report on Warcraft Logs and using the report link. </Trans> </AlertWarning> </> ); case STATE_SEARCH_GUILD: return <NameSearch type={SearchType.GUILD} />; case STATE_SEARCH_REPORT: default: return <ReportSelecter />; } } render() { const { reportHistory } = this.props; return ( <header className="report-selection"> <div className="container"> <div className="row"> <div className={reportHistory.length !== 0 ? 'col-md-8' : 'col-md-12'}> <a href="/" className="brand-name"> <Logo /> <h1>WoWAnalyzer</h1> </a> <div id="reportSelectionHeader.improveYourPerformance"> <Trans id="interface.home.reportSelectionHeader.improveYourPerformance"> Improve your performance with personal feedback and stats. Just enter the link of a{' '} <a href="https://www.warcraftlogs.com/" target="_blank" rel="noopener noreferrer"> Warcraft Logs </a>{' '} report below. </Trans> </div> <div style={{ margin: '30px auto', maxWidth: 700, textAlign: 'left' }}> <nav> <ul> <li key="report" className={ this.state.searchType === STATE_SEARCH_REPORT ? 'active' : undefined } > <a href="/" style={{ padding: '5px' }} onClick={this.handleReportSearchClick}> <ReportIcon /> <Trans id="interface.home.reportSelectionHeader.report">Report</Trans> </a> </li> <li key="character" className={this.state.searchType === STATE_SEARCH_CHAR ? 'active' : undefined} > <a href="/" style={{ padding: '5px' }} onClick={this.handleCharacterSearchClick} > <CharacterIcon /> <Trans id="interface.home.reportSelectionHeader.character">Character</Trans> </a> </li> <li key="guild" className={ this.state.searchType === STATE_SEARCH_GUILD ? 'active' : undefined } > <a href="/" style={{ padding: '5px' }} onClick={this.handleGuildSearchClick}> <GuildIcon /> <Trans id="interface.home.reportSelectionHeader.guild">Guild</Trans> </a> </li> </ul> </nav> {this.renderSearch()} </div> </div> {reportHistory.length !== 0 && ( <div className="col-md-4 text-left" style={{ marginTop: -10, marginBottom: -10 }}> <small> <Trans id="interface.home.reportSelectionHeader.recentlyViewed"> Recently viewed </Trans> </small> <br /> <ReportHistory reportHistory={reportHistory} /> </div> )} </div> </div> </header> ); } } const mapStateToProps = (state) => ({ reportHistory: getReportHistory(state), }); export default connect(mapStateToProps)(ReportSelectionHeader);
packages/react/src/components/SecondaryButton/SecondaryButton.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import Button from '../Button'; const SecondaryButton = (props) => <Button kind="secondary" {...props} />; export default SecondaryButton;
app/js/todo/form.js
pengux/electron-react-starter
import React from 'react'; import TodoActions from './actions'; export default React.createClass({ create(e) { e.preventDefault(); var task = this.refs.newTask.value; TodoActions.create({"name": task}); }, render() { return ( <form onSubmit={this.create}> <label> Add task <input type="text" ref="newTask" /> </label> </form> ); } });
ui/src/common/BatchPlayButton.js
cloudsonic/sonic-server
import React from 'react' import PropTypes from 'prop-types' import { Button, useDataProvider, useTranslate, useUnselectAll, useNotify, } from 'react-admin' import { useDispatch } from 'react-redux' export const BatchPlayButton = ({ resource, selectedIds, action, label, icon, className, }) => { const dispatch = useDispatch() const translate = useTranslate() const dataProvider = useDataProvider() const unselectAll = useUnselectAll() const notify = useNotify() const addToQueue = () => { dataProvider .getMany(resource, { ids: selectedIds }) .then((response) => { // Add tracks to a map for easy lookup by ID, needed for the next step const tracks = response.data.reduce( (acc, cur) => ({ ...acc, [cur.id]: cur }), {} ) // Add the tracks to the queue in the selection order dispatch(action(tracks, selectedIds)) }) .catch(() => { notify('ra.page.error', 'warning') }) unselectAll(resource) } const caption = translate(label) return ( <Button aria-label={caption} onClick={addToQueue} label={caption} className={className} > {icon} </Button> ) } BatchPlayButton.propTypes = { action: PropTypes.func.isRequired, label: PropTypes.string.isRequired, icon: PropTypes.object.isRequired, }
app/react-icons/fa/copyright.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaCopyright extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m28.7 24v2.4q0 1.1-0.8 2t-2.1 1.3-2.7 0.8-2.6 0.2q-4.6 0-7.6-3.1t-3.1-7.7q0-4.5 3-7.6t7.6-3q0.7 0 1.7 0.1t2 0.4 2.1 0.7 1.6 1.3 0.6 1.8v2.4q0 0.4-0.4 0.4h-2.6q-0.4 0-0.4-0.4v-1.5q0-1-1.4-1.5t-3.1-0.6q-3.1 0-5.1 2.1t-2 5.3q0 3.3 2.1 5.5t5.2 2.2q1.5 0 3.1-0.5t1.5-1.5v-1.5q0-0.2 0.1-0.3t0.3-0.1h2.6q0.1 0 0.3 0.1t0.1 0.3z m-8.6-18.3q-2.9 0-5.5 1.2t-4.6 3-3 4.6-1.1 5.5 1.1 5.5 3 4.6 4.6 3 5.5 1.2 5.6-1.2 4.5-3 3.1-4.6 1.1-5.5-1.1-5.5-3.1-4.6-4.5-3.1-5.6-1.1z m17.2 14.3q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"/></g> </IconBase> ); } }
client/src/routes.js
Enter-36-chambers-of-wu-tang-fam/Ilera-health
// React import React from 'react'; import ReactDOM from 'react-dom'; // React Router import { Router, Route, IndexRoute } from 'react-router'; //Authentication Requirement import PhysicianAuth from './auth-shared/higher-order-components/physician_auth.jsx'; import PatientAuth from './auth-shared/higher-order-components/patient_auth.jsx'; import StaffAuth from './auth-shared/higher-order-components/staff_auth.jsx'; import GeneralAuth from './auth-shared/higher-order-components/general_auth.jsx'; //Shared Components import App from './main/app.js'; import Welcome from './auth-shared/components/landing-page/welcome.jsx'; import Signin from './auth-shared/components/signin-component.jsx'; import Signup from './auth-shared/components/signup-component.jsx'; import AllPhysicians from './patients/components/physicians-dash/allPhysicians.jsx'; import AllPhysicianProfile from './patients/components/physicians-dash/allPhysicianProfile.jsx' import Chat from './patients/containers/messages/chat-container.js'; // Physician Components import PhysicianApp from './physicians/physician-app/physician-app.jsx'; import ProviderAppFormContainer from './physicians/containers/onboarding/provider-signup-forms.jsx'; import PhysicianDashboard from './physicians/containers/main-dash/provider-dash.jsx'; import Notes from './physicians/physician-app/notes.jsx'; import Calendar from './physicians/physician-app/calendar.jsx'; import ProvPatProfile from './physicians/components/patient-ind-profile-dash/profile-main.jsx'; import AllUsers from './physicians/components/patients-dash/allUsers.jsx' import PhysProfile from './physicians/components/profile-dash/patient-profile.jsx'; // Patient Components import PatientApp from './patients/containers/patient-app.jsx'; import PatientDashboard from './patients/containers/main-dash/patient-dashboard.jsx'; import HealthLog from './patients/components/health-log-dash/health-log.jsx'; import Profile from './patients/components/profile-dash/patient-profile.jsx'; import Medication from './patients/containers/medication/medication-container.js'; import PhysicianCalendar from './patients/components/physicians-dash/physicianAppointment.jsx'; import PatientAppFormContainer from './patients/components/onboarding/patient-signup-forms.jsx'; import MedicalHistory from './patients/components/medical-history-dash/medical-history-dashboard.jsx'; import MedicalHistoryUpload from './patients/components/medical-history-dash/uploadDocuments.jsx'; import MedicalHistoryAppointment from './patients/components/medical-history-dash/appointment-history-dashboard.jsx'; // Staff Components import StaffApp from './staff/components/staff-app.jsx'; import StaffAppFormContainer from './staff/components/onboarding/staff-signup-forms.jsx'; import StaffDashboard from './staff/components/main-dash/staff-dashboard.jsx'; export default ( <Router path='/' component= { App } > <IndexRoute component={ GeneralAuth(Welcome) }/> <Route path='signup' component={ GeneralAuth(Signup) } /> <Route path='signin' component={ GeneralAuth(Signin) } /> <Route path='provider' component={ PhysicianAuth(PhysicianApp) } > <Route path="welcome" > <IndexRoute component={ ProviderAppFormContainer } /> </Route> <Route path="dashboard" component={ PhysicianDashboard } /> <Route path="/provider/patients" component={ AllUsers } /> <Route path='/provider/patients/:patientId' component={ ProvPatProfile } /> <Route path='test' component={ ProvPatProfile } /> <Route path="notes" component={ Notes } /> <Route path="messages" component={ Chat } /> <Route path="profile" component={ PhysProfile } /> <Route path="calendar" component ={ Calendar }/> </Route> <Route path='patient' component={ PatientAuth(PatientApp) } > <Route path="welcome" > <IndexRoute component={ PatientAppFormContainer } /> </Route> <Route path="dashboard" component={ PatientDashboard } /> <Route path="healthlog" component={ HealthLog } /> <Route path="physicians" component={ AllPhysicians } /> <Route path='physicians/:provider' component={ AllPhysicianProfile } > <Route path='individual' component={ PhysicianCalendar } /> </Route> <Route path="messages" component={ Chat } /> <Route path="profile" component={ Profile } /> <Route path="medications" component={ Medication } /> <Route path="records" component={ MedicalHistory } /> <Route path="records/upload" component={ MedicalHistoryUpload } /> <Route path="records/appointments" component={ MedicalHistoryAppointment } /> </Route> <Route path='staff' component={ StaffAuth(StaffApp) } > <Route path="form" > <IndexRoute component={ StaffAppFormContainer } /> </Route> <Route path="dashboard" component={ StaffDashboard } /> </Route> </Router> );
src/svg-icons/image/burst-mode.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBurstMode = (props) => ( <SvgIcon {...props}> <path d="M1 5h2v14H1zm4 0h2v14H5zm17 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z"/> </SvgIcon> ); ImageBurstMode = pure(ImageBurstMode); ImageBurstMode.displayName = 'ImageBurstMode'; ImageBurstMode.muiName = 'SvgIcon'; export default ImageBurstMode;