path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
blueocean-material-icons/src/js/components/svg-icons/hardware/phonelink.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwarePhonelink = (props) => ( <SvgIcon {...props}> <path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/> </SvgIcon> ); HardwarePhonelink.displayName = 'HardwarePhonelink'; HardwarePhonelink.muiName = 'SvgIcon'; export default HardwarePhonelink;
src/layouts/BasicLayout.js
wu-sheng/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import { Layout, Icon } from 'antd'; import DocumentTitle from 'react-document-title'; import { connect } from 'dva'; import { Route, Redirect, Switch, routerRedux } from 'dva/router'; import { ContainerQuery } from 'react-container-query'; import classNames from 'classnames'; import lodash from 'lodash'; import GlobalHeader from '../components/GlobalHeader'; import GlobalFooter from '../components/GlobalFooter'; import SiderMenu from '../components/SiderMenu'; import DurationPanel from '../components/Duration/Panel'; import NotFound from '../routes/Exception/404'; import { getRoutes } from '../utils/utils'; import Authorized from '../utils/Authorized'; import { getMenuData } from '../common/menu'; import logo from '../assets/sw-2.png'; const { Content } = Layout; const { AuthorizedRoute } = Authorized; const redirectData = []; const getRedirect = (item) => { if (item && item.children) { if (item.children[0] && item.children[0].path) { redirectData.push({ from: `/${item.path}`, to: `/${item.children[0].path}`, }); item.children.forEach((children) => { getRedirect(children); }); } } }; getMenuData().forEach(getRedirect); const query = { 'screen-xs': { maxWidth: 575, }, 'screen-sm': { minWidth: 576, maxWidth: 767, }, 'screen-md': { minWidth: 768, maxWidth: 991, }, 'screen-lg': { minWidth: 992, maxWidth: 1199, }, 'screen-xl': { minWidth: 1200, }, }; class BasicLayout extends React.PureComponent { static childContextTypes = { location: PropTypes.object, breadcrumbNameMap: PropTypes.object, } getChildContext() { const { location, routerData } = this.props; return { location, breadcrumbNameMap: routerData, }; } componentWillUpdate(nextProps) { const {...propsData} = this.props; const { globalVariables: { duration }, isMonitor } = nextProps; if (!isMonitor) { return; } if (!duration || Object.keys(duration).length < 1) { return; } const { globalVariables: { duration: preDuration } } = this.props; if (duration === preDuration) { return; } propsData.dispatch({ type: 'global/fetchNotice', payload: { variables: { duration } }, }); } getPageTitle() { const { routerData, location } = this.props; const { pathname } = location; let title = 'Sky Walking'; if (routerData[pathname] && routerData[pathname].name) { title = `${routerData[pathname].name} - SW`; } return title; } getBashRedirect = () => { // According to the url parameter to redirect const urlParams = new URL(window.location.href); const redirect = urlParams.searchParams.get('redirect'); // Remove the parameters in the url if (redirect) { urlParams.searchParams.delete('redirect'); window.history.replaceState(null, 'redirect', urlParams.href); } else { return '/monitor/dashboard'; } return redirect; } handleDurationToggle = () => { const {...propsData} = this.props; propsData.dispatch({ type: 'global/changeDurationCollapsed', payload: propsData.duration.collapsed, }); } handleDurationReload = () => { const {...propsData} = this.props; propsData.dispatch({ type: 'global/reloadDuration', }); } handleDurationSelected = (selectedDuration) => { const {...propsData} = this.props; propsData.dispatch({ type: 'global/changeDuration', payload: selectedDuration, }); if (this.intervalId) { clearInterval(this.intervalId); } const { step = 0 } = selectedDuration; if (step < 1) { return; } this.intervalId = setInterval(this.handleDurationReload, step); } handleMenuCollapse = (collapsed) => { const {...propsData} = this.props; propsData.dispatch({ type: 'global/changeLayoutCollapsed', payload: collapsed, }); } handleMenuClick = ({ key }) => { const {...propsData} = this.props; if (key === 'triggerError') { propsData.dispatch(routerRedux.push('/exception/trigger')); return; } if (key === 'logout') { propsData.dispatch({ type: 'login/logout', }); } } handleNoticeVisibleChange = (visible) => { const {...propsData} = this.props; if (visible) { propsData.dispatch({ type: 'global/fetchNotices', }); } } handleRedirect = (path) => { const { history } = this.props; if (history.location.pathname === path.pathname) { return; } history.push(path); } render() { const {...propsData} = this.props; const { isMonitor, collapsed, fetching, notices, routerData, match, location, zone, duration: { selected: dSelected, collapsed: dCollapsed }, } = this.props; const bashRedirect = this.getBashRedirect(); const layout = ( <Layout> <SiderMenu logo={logo} // If you do not have the Authorized parameter // you will be forced to jump to the 403 interface without permission Authorized={Authorized} menuData={getMenuData()} collapsed={collapsed} location={location} onCollapse={this.handleMenuCollapse} /> <Layout> <GlobalHeader logo={logo} fetching={fetching} notices={notices} collapsed={collapsed} selectedDuration={dSelected} isMonitor={isMonitor} onNoticeClear={this.handleNoticeClear} onCollapse={this.handleMenuCollapse} onMenuClick={this.handleMenuClick} onNoticeVisibleChange={this.handleNoticeVisibleChange} onDurationToggle={this.handleDurationToggle} onDurationReload={this.handleDurationReload} onRedirect={this.handleRedirect} /> {isMonitor ? ( <DurationPanel selected={dSelected} onSelected={this.handleDurationSelected} collapsed={dCollapsed} zone={zone} dispatch={propsData.dispatch} /> ) : null} <Content style={{ margin: '24px 24px 0', height: '100%' }}> <Switch> { redirectData.map(item => <Redirect key={item.from} exact from={item.from} to={item.to} /> ) } { getRoutes(match.path, routerData).map(item => ( <AuthorizedRoute key={item.key} path={item.path} component={item.component} exact={item.exact} authority={item.authority} redirectPath="/exception/403" /> ) ) } <Redirect exact from="/" to={bashRedirect} /> <Route render={NotFound} /> </Switch> </Content> <GlobalFooter links={[{ key: 'SkyWalking', title: 'Apache SkyWalking', href: 'http://skywalking.apache.org', blankTarget: true, }, { key: 'GitHub', title: 'GitHub', href: 'https://github.com/apache/incubator-skywalking', blankTarget: true, }]} copyright={ <div> Copyright <Icon type="copyright" /> 2017 - 2019 The Apache Software Foundation, Licensed under the Apache License, Version 2.0. </div> } /> </Layout> </Layout> ); return ( <DocumentTitle title={this.getPageTitle()}> <ContainerQuery query={query}> {params => <div className={classNames(params)}>{layout}</div>} </ContainerQuery> </DocumentTitle> ); } } export default connect(({ global, loading }) => ({ isMonitor: global.isMonitor, collapsed: global.collapsed, fetching: lodash.values(loading.models).findIndex(_ => _) > -1, notices: global.notices, duration: global.duration, globalVariables: global.globalVariables, zone: global.zone, }))(BasicLayout);
src/svg-icons/image/filter-2.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter2 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-4-4h-4v-2h2c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2h-4v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2z"/> </SvgIcon> ); ImageFilter2 = pure(ImageFilter2); ImageFilter2.displayName = 'ImageFilter2'; ImageFilter2.muiName = 'SvgIcon'; export default ImageFilter2;
node_modules/react-bootstrap/es/MediaLeft.js
superKaigon/TheCave
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Media from './Media'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: PropTypes.oneOf(['top', 'middle', 'bottom']) }; var MediaLeft = function (_React$Component) { _inherits(MediaLeft, _React$Component); function MediaLeft() { _classCallCheck(this, MediaLeft); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaLeft.prototype.render = function render() { var _props = this.props, align = _props.align, className = _props.className, props = _objectWithoutProperties(_props, ['align', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); if (align) { // The class is e.g. `media-top`, not `media-left-top`. classes[prefix(Media.defaultProps, align)] = true; } return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaLeft; }(React.Component); MediaLeft.propTypes = propTypes; export default bsClass('media-left', MediaLeft);
src/client/components/FeaturesAsync/Features.js
EdgeJay/web-starterkit
/* eslint-disable react/no-danger */ import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { bindActions, mapStateToProps } from '../../stores'; import * as actions from '../../actions/main'; import PageHeader from '../PageHeader'; const CustomFontElem = styled.p` font-family: 'IndieFlower', san-serif, Helvetica, Arial; `; class Features extends React.PureComponent { onTestCSRFToken(evt, withToken) { evt.preventDefault(); this.validateCSRFToken(withToken); } validateCSRFToken(withToken) { const payload = {}; if (withToken) { // eslint-disable-next-line dot-notation payload['_csrf'] = this.props.store.csrf; } this.props.actions.validateCSRF(payload); } render() { const buttonLabel = 'Test CSRF token validity'; const { enableCSRFTest } = this.props.store; return ( <div> <PageHeader>{'Features'}</PageHeader> <h2>Custom Fonts</h2> <CustomFontElem> {'This project supports custom fonts.'} <br /> {'(Using "Indie Flower" from Google Fonts)'} </CustomFontElem> <h2>CSRF</h2> <p dangerouslySetInnerHTML={{ __html: `Generated CSRF token is <code>${ this.props.store.csrf }</code>. Tap on "${buttonLabel}" to test the token.`, }} /> <button onClick={evt => this.onTestCSRFToken(evt, true)} disabled={!enableCSRFTest}> {buttonLabel} </button>{' '} <button onClick={evt => this.onTestCSRFToken(evt, false)} disabled={!enableCSRFTest}> {'Test without CSRF token'} </button> <pre>{JSON.stringify(this.props.store.csrfResponse)}</pre> </div> ); } } Features.propTypes = { actions: PropTypes.oneOfType([PropTypes.object]).isRequired, store: PropTypes.oneOfType([PropTypes.object]).isRequired, }; export default connect(mapStateToProps('main'), bindActions(actions))(Features);
examples/with-redux-reselect-recompose/components/addCount.js
giacomorebonato/next.js
import React from 'react' import PropTypes from 'prop-types' import { compose, setDisplayName, pure, setPropTypes } from 'recompose' const AddCount = ({ count, addCount }) => <div> <style jsx>{` div { padding: 0 0 20px 0; } `}</style> <h1>AddCount: <span>{count}</span></h1> <button onClick={addCount}>Add To Count</button> </div> export default compose( setDisplayName('AddCount'), setPropTypes({ count: PropTypes.number, addCount: PropTypes.func }), pure )(AddCount)
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
Ttommeke/Ttommeke.github.io
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
frontend/src/components/dashboard/agencyDashboard/listOfOpenCfeiTable.js
unicef/un-partner-portal
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { TableCell } from 'material-ui/Table'; import Typography from 'material-ui/Typography'; import { loadOpenCfeiList } from '../../../reducers/openCfeiDashboardList'; import PaginatedList from '../../common/list/paginatedList'; import TableWithLocalState from '../../common/hoc/tableWithLocalState'; import { formatDateForPrint } from '../../../helpers/dates'; const columns = [ { name: 'title', title: 'Project Title', width: 250 }, { name: 'displayID', title: 'CFEI' }, { name: 'applications_count', title: 'Number of Applications' }, { name: 'deadline_date', title: 'Application deadline' }, ]; const renderCells = ({ row, column, value }) => { if (column.name === 'displayID') { return ( <TableCell > <Typography color="accent" component={Link} to={`/cfei/open/${row.id}`} > {row.displayID} </Typography> </TableCell>); } else if (column.name === 'deadline_date') { return ( <TableCell > {formatDateForPrint(row.deadline_date)} </TableCell>); } return <TableCell><Typography>{value}</Typography></TableCell>; }; renderCells.propTypes = { row: PropTypes.object, column: PropTypes.object, }; class ListOfCOpenCfeiTable extends Component { componentWillMount() { } render() { const { loading, data, loadApplications, itemsCount } = this.props; return ( <TableWithLocalState component={PaginatedList} items={data} itemsCount={itemsCount} columns={columns} loading={loading} templateCell={renderCells} loadingFunction={loadApplications} /> ); } } ListOfCOpenCfeiTable.propTypes = { loading: PropTypes.bool, data: PropTypes.array, loadApplications: PropTypes.func, itemsCount: PropTypes.number, }; const mapStateToProps = state => ({ loading: state.openCfeiDashboardList.status.loading, data: state.openCfeiDashboardList.data.applications, itemsCount: state.openCfeiDashboardList.data.count, }); const mapDispatchToProps = dispatch => ({ loadApplications: params => dispatch(loadOpenCfeiList(params)), }); export default connect(mapStateToProps, mapDispatchToProps)(ListOfCOpenCfeiTable);
src/routers/ProjectRouter.js
adisrini/personal-website
import React from 'react' import { Route, withRouter } from 'react-router-dom'; import NotFound from '../templates/NotFound/NotFound'; import ProjectWriteup from '../templates/Projects/ProjectWriteup'; import projectdata from '../assets/data/projects'; import Switch from 'react-router-dom/Switch'; const projects = projectdata.projects; class ProjectRouter extends React.Component { render() { return ( <Switch> {this.renderProjectRoute("meals")} {this.renderProjectRoute("pantry-pals")} {this.renderProjectRoute("tiger")} {this.renderProjectRoute("fpga")} {this.renderProjectRoute("vooga")} {this.renderProjectRoute("myomusc")} {this.renderProjectRoute("slogo")} {this.renderProjectRoute("cell-society")} <Route path="/projects/*" component={ NotFound } /> </Switch> ) } renderProjectRoute = (route) => { const projectObject = projects.find(p => p.route === route); return ( <Route exact path={`/projects/${route}`} render = { (props) => <ProjectWriteup {...props} project={projectObject} /> } /> ); } } export default withRouter(ProjectRouter);
source/server.js
jchavezjs/platzi-react
import http from 'http'; import React from 'react'; import { renderToString, renderToStaticMarkup } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import Pages from './pages/containers/Page.jsx'; import Layout from './pages/components/Layout.jsx'; import store from './store'; function requestHandler(request, response){ const context = {}; let html = renderToString( <Provider store={store}> <StaticRouter location={request.url} context={context}> <Pages /> </StaticRouter> </Provider> ); response.setHeader('Content-Type', 'text/html'); if(context.url){ response.writeHead(301, { location: context.url }); response.end(); } if(context.url){ response.writeHead(404); html = renderToString( <Provider store={store}> <StaticRouter location={request.url} context={context}> <Pages /> </StaticRouter> </Provider> ); } response.write( renderToStaticMarkup( <Layout title="Aplicación" content={html} /> ) ); response.end(); } const server = http.createServer(requestHandler); server.listen(3000);
docs/src/pages/components/steppers/HorizontalNonLinearStepperWithError.js
lgollut/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { width: '100%', }, button: { marginRight: theme.spacing(1), }, instructions: { marginTop: theme.spacing(1), marginBottom: theme.spacing(1), }, })); function getSteps() { return ['Select campaign settings', 'Create an ad group', 'Create an ad']; } function getStepContent(step) { switch (step) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'Unknown step'; } } export default function HorizontalNonLinearStepperWithError() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const [skipped, setSkipped] = React.useState(new Set()); const steps = getSteps(); const isStepOptional = (step) => { return step === 1; }; const isStepFailed = (step) => { return step === 1; }; const isStepSkipped = (step) => { return skipped.has(step); }; const handleNext = () => { let newSkipped = skipped; if (isStepSkipped(activeStep)) { newSkipped = new Set(skipped.values()); newSkipped.delete(activeStep); } setActiveStep((prevActiveStep) => prevActiveStep + 1); setSkipped(newSkipped); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleSkip = () => { if (!isStepOptional(activeStep)) { // You probably want to guard against something like this, // it should never occur unless someone's actively trying to break something. throw new Error("You can't skip a step that isn't optional."); } setSkipped((prevSkipped) => { const newSkipped = new Set(prevSkipped.values()); newSkipped.add(activeStep); return newSkipped; }); setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleReset = () => { setActiveStep(0); }; return ( <div className={classes.root}> <Stepper activeStep={activeStep}> {steps.map((label, index) => { const stepProps = {}; const labelProps = {}; if (isStepOptional(index)) { labelProps.optional = ( <Typography variant="caption" color="error"> Alert message </Typography> ); } if (isStepFailed(index)) { labelProps.error = true; } if (isStepSkipped(index)) { stepProps.completed = false; } return ( <Step key={label} {...stepProps}> <StepLabel {...labelProps}>{label}</StepLabel> </Step> ); })} </Stepper> <div> {activeStep === steps.length ? ( <div> <Typography className={classes.instructions}> All steps completed - you&apos;re finished </Typography> <Button onClick={handleReset} className={classes.button}> Reset </Button> </div> ) : ( <div> <Typography className={classes.instructions}>{getStepContent(activeStep)}</Typography> <div> <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}> Back </Button> {isStepOptional(activeStep) && ( <Button variant="contained" color="primary" onClick={handleSkip} className={classes.button} > Skip </Button> )} <Button variant="contained" color="primary" onClick={handleNext} className={classes.button} > {activeStep === steps.length - 1 ? 'Finish' : 'Next'} </Button> </div> </div> )} </div> </div> ); }
widgets/TextAreaWidget.js
FaridSafi/react-native-gifted-form
import React from 'react'; import createReactClass from 'create-react-class'; import { View, TextInput, PixelRatio } from 'react-native'; var WidgetMixin = require('../mixins/WidgetMixin.js'); module.exports = createReactClass({ mixins: [WidgetMixin], getDefaultProps() { return { type: 'TextAreaWidget', }; }, render() { return ( <View style={this.getStyle('textAreaRow')}> <TextInput style={this.getStyle('textArea')} multiline={true} {...this.props} onFocus={() => this.props.onFocus(true)} onChangeText={this._onChange} value={this.state.value} /> </View> ); }, defaultStyles: { textAreaRow: { backgroundColor: '#FFF', height: 120, borderBottomWidth: 1 / PixelRatio.get(), borderColor: '#c8c7cc', alignItems: 'center', paddingLeft: 10, paddingRight: 10, }, textArea: { fontSize: 15, flex: 1, }, }, });
benchmarks/dom-comparison/src/implementations/inline-styles/Dot.js
risetechnologies/fela
/* eslint-disable react/prop-types */ import React from 'react'; const Dot = ({ size, x, y, children, color }) => ( <div style={{ ...styles.root, ...{ borderBottomColor: color, borderRightWidth: `${size / 2}px`, borderBottomWidth: `${size / 2}px`, borderLeftWidth: `${size / 2}px`, marginLeft: `${x}px`, marginTop: `${y}px` } }} > {children} </div> ); const styles = { root: { position: 'absolute', cursor: 'pointer', width: 0, height: 0, borderColor: 'transparent', borderStyle: 'solid', borderTopWidth: 0, transform: 'translate(50%, 50%)' } }; export default Dot;
src/AffixMixin.js
wjb12/react-bootstrap
import React from 'react'; import domUtils from './utils/domUtils'; import EventListener from './utils/EventListener'; const AffixMixin = { propTypes: { offset: React.PropTypes.number, offsetTop: React.PropTypes.number, offsetBottom: React.PropTypes.number }, getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition() { let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom, affix, affixType, affixPositionTop; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = React.findDOMNode(this); scrollHeight = domUtils.getDocumentHeight(); scrollTop = window.pageYOffset; position = domUtils.getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && (scrollTop + this.unpin <= position.top)) { affix = false; } else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) { affix = 'bottom'; } else if (offsetTop != null && (scrollTop <= offsetTop)) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop }); }, checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount() { this._onWindowScrollListener = EventListener.listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; export default AffixMixin;
src/svg-icons/editor/border-top.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderTop = (props) => ( <SvgIcon {...props}> <path d="M7 21h2v-2H7v2zm0-8h2v-2H7v2zm4 0h2v-2h-2v2zm0 8h2v-2h-2v2zm-8-4h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2v-2H3v2zm0-4h2V7H3v2zm8 8h2v-2h-2v2zm8-8h2V7h-2v2zm0 4h2v-2h-2v2zM3 3v2h18V3H3zm16 14h2v-2h-2v2zm-4 4h2v-2h-2v2zM11 9h2V7h-2v2zm8 12h2v-2h-2v2zm-4-8h2v-2h-2v2z"/> </SvgIcon> ); EditorBorderTop = pure(EditorBorderTop); EditorBorderTop.displayName = 'EditorBorderTop'; EditorBorderTop.muiName = 'SvgIcon'; export default EditorBorderTop;
src/components/Main.js
wang-yin-long/test1-by-react
require('normalize.css/normalize.css'); require('styles/App.css'); require('styles/my.css'); import React from 'react'; // 获取图像数据 var imgDatas = require('../datas/pics.json'); // 图像数据转化为图像URL function getImgURL(imgDatasArr) { for (var i = 0; i < imgDatasArr.length; i++) { var oneImgData = imgDatasArr[i]; oneImgData.imgURL = require('../images/' + oneImgData.imageName); imgDatasArr[i] = oneImgData; } return imgDatasArr; } imgDatas = getImgURL(imgDatas); class ImgFigure extends React.Component { render() { return ( <figure className="img-figure"> <img src={this.props.data.imgURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> </figcaption> </figure> ); } } class AppComponent extends React.Component { render() { var controllerUnits = [], imgFigures = []; imgDatas.forEach(function (value) { imgFigures.push(<ImgFigure data={value}/>); }); return ( <section className="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = {}; export default AppComponent;
src/components/Messages.js
GovReady/GovReady-Agent-Client
import React, { Component } from 'react'; import { PropTypes as PT } from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { default as config } from 'config'; import { actions } from 'redux/modules/messageReducer'; class Messages extends Component { // First mount componentDidMount() { if(this.props.messages.length) { this.props.actions.messagesSeen(); } } // Data updates componentWillReceiveProps(nextProps) { if(nextProps.messages.length) { this.props.actions.messagesSeen(); } } componentWillUnmount() { // Clear on exit this.props.actions.messageDismissAll(); } render() { const { messages } = this.props; const messageMarkup = (message, index) => { return <div key={index.toString()} className={`alert alert-${message.level}`}>{message.content}</div> } return ( <div className="govready-messages"> {messages.map((message, index) => messageMarkup(message, index))} </div> ) } } Messages.propTypes = { actions: PT.object.isRequired, messages: PT.array.isRequired }; function mapStateToProps (state) { return { messages: state.messageState.messages }; } function mapDispatchToProps (dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(Messages);
core/packages/iframes/shared/components/index.js
wp-pwa/wp-pwa
import React from 'react'; import PropTypes from 'prop-types'; import { inject } from 'mobx-react'; import { Fill } from 'react-slot-fill'; import LazyIframe from './LazyIframe'; const Iframes = ({ iframes }) => iframes.map(props => ( <Fill key={props.name} name={props.name}> <LazyIframe {...props} /> </Fill> )); Iframes.propTypes = { iframes: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, src: PropTypes.string.isRequired, className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), }), ), }; export default inject(({ stores: { settings, build } }) => ({ iframes: (settings.theme.iframes && settings.theme.iframes.filter(({ device: iframeDevice }) => iframeDevice === build.device)) || [], }))(Iframes);
src/main/webapp/static/js/club/errorPage.js
weijiafen/antBlog
import React from 'react'; var Application=React.createClass({ render(){ return ( <div> error page </div> ); } }) export default Application;
src/views/MonthsView.js
YouCanBookMe/react-datetime
import React from 'react'; import ViewNavigation from '../parts/ViewNavigation'; export default class MonthsView extends React.Component { render() { return ( <div className="rdtMonths"> <table> <thead> { this.renderNavigation() } </thead> </table> <table> <tbody> { this.renderMonths() } </tbody> </table> </div> ); } renderNavigation() { let year = this.props.viewDate.year(); return ( <ViewNavigation onClickPrev={ () => this.props.navigate( -1, 'years' ) } onClickSwitch={ () => this.props.showView( 'years' ) } onClickNext={ () => this.props.navigate( 1, 'years' ) } switchContent={ year } switchColSpan="2" /> ); } renderMonths() { // 12 months in 3 rows for every view let rows = [ [], [], [] ]; for ( let month = 0; month < 12; month++ ) { let row = getRow( rows, month ); row.push( this.renderMonth( month ) ); } return rows.map( (months, i) => ( <tr key={i}>{ months }</tr> )); } renderMonth( month ) { const selectedDate = this.props.selectedDate; let className = 'rdtMonth'; let onClick; if ( this.isDisabledMonth( month ) ) { className += ' rdtDisabled'; } else { onClick = this._updateSelectedMonth; } if ( selectedDate && selectedDate.year() === this.props.viewDate.year() && selectedDate.month() === month ) { className += ' rdtActive'; } let props = {key: month, className, 'data-value': month, onClick }; if ( this.props.renderMonth ) { return this.props.renderMonth( props, month, this.props.viewDate.year(), this.props.selectedDate && this.props.selectedDate.clone() ); } return ( <td { ...props }> { this.getMonthText( month ) } </td> ); } isDisabledMonth( month ) { let isValidDate = this.props.isValidDate; if ( !isValidDate ) { // If no validator is set, all days are valid return false; } // If one day in the month is valid, the year should be clickable let date = this.props.viewDate.clone().set({month}); let day = date.endOf( 'month' ).date() + 1; while ( day-- > 1 ) { if ( isValidDate( date.date(day) ) ) { return false; } } return true; } getMonthText( month ) { const localMoment = this.props.viewDate; const monthStr = localMoment.localeData().monthsShort( localMoment.month( month ) ); // Because some months are up to 5 characters long, we want to // use a fixed string length for consistency return capitalize( monthStr.substring( 0, 3 ) ); } _updateSelectedMonth = event => { this.props.updateDate( event ); } } function getRow( rows, year ) { if ( year < 4 ) { return rows[0]; } if ( year < 8 ) { return rows[1]; } return rows[2]; } function capitalize( str ) { return str.charAt( 0 ).toUpperCase() + str.slice( 1 ); }
app/components/Increment/Increment.js
djizco/boilerplate-react-native
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-native'; export default function Increment({ increment }) { return ( <Button title="Increment" onPress={increment} /> ); } Increment.propTypes = { increment: PropTypes.func.isRequired, };
js/components/pages/DoingsPage.react.js
ciccia/i-done-that
import React, { Component } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import * as doingsActions from '../../actions/doingsActions'; import { doingsSelector } from '../../selectors/doingsSelectors'; import DoingsFormFull from '../doings/DoingsForm/full'; import DoingsListFull from '../doings/DoingsLists/full'; class DoingsPage extends Component { constructor(props) { super(props); this.state = { selectedDate: new Date() } } _handleDateChange(e) { const date = e.target.value; this.setState({selectedDate: new Date(date)}) } _handleToggleDoings(id) { const { markDoneAsDoing, markDoneAsDone, doings } = this.props; const doing = doings.find(item => item.get('id') === id); doing.get('done') ? markDoneAsDoing(id) : markDoneAsDone(id); } render() { const { doings, addDone, deleteDone, updateDone } = this.props; const { selectedDate } = this.state; const filteredDoings = doings.filter(doing => { return moment(doing.get('date')).isSame(selectedDate, 'day') }); return ( <div className="row"> <div className="col s12 l6"> <DoingsFormFull date={selectedDate} onDateChange={(e) => {this._handleDateChange(e)}} onSubmit={addDone}/> </div> <div className="col s12 l6 right-align"> <div className="divider hide-on-large-only"></div> <h4 className="materialize-red-text text-lighten-2" style={{fontWeight: 300}}> iDoneThat list </h4> <DoingsListFull doings={filteredDoings} onClick={this._handleToggleDoings.bind(this)} onDelete={deleteDone} onUpdate={updateDone}/> </div> </div> ); } } export default connect(doingsSelector, doingsActions)(DoingsPage);
src/components/NextView.js
dominictracey/hangboard
import React from 'react' import PropTypes from 'prop-types' import {View} from 'react-native' import AppText from './AppText'; import {StyleSheet} from 'react-native'; NextView.propTypes = { nextWeight: PropTypes.number, nextGrip: PropTypes.string.isRequired, } function NextView(props) { const weightLabel = props.nextGrip === 'Complete' ? '' : 'Weight ' + props.nextWeight return ( <View style={styles.container}> <View style={styles.row}> <AppText size='lg'>Next</AppText> </View> <View style={[styles.row, styles.rowplus]}> <View style={styles.container}> <AppText size='sm'>{props.nextGrip}</AppText> <AppText size='sm'>{weightLabel}</AppText> </View> </View> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }, row: { flex: .5, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', }, rowplus: { flex: 1, }, }) export default NextView
demo/components/AddTodo.js
dsibiski/cerebral
import React from 'react'; import {Decorator as Cerebral} from './../CustomController.js'; @Cerebral({ isSaving: ['isSaving'], newTodoTitle: ['newTodoTitle'] }) class AddTodo extends React.Component { onFormSubmit(event) { event.preventDefault(); this.props.signals.newTodoSubmitted(); } onNewTodoTitleChange(event) { this.props.signals.newTodoTitleChanged({ title: event.target.value }); } render() { return ( <form id="todo-form" onSubmit={(e) => this.onFormSubmit(e)}> <input id="new-todo" autoComplete="off" placeholder="What needs to be done?" disabled={this.props.isSaving} value={this.props.newTodoTitle} onChange={(e) => this.onNewTodoTitleChange(e)} /> </form> ); } } export default AddTodo;
src/components/screen/ScreenHeader.js
hostables/musicquiz
import React from 'react' import ScreenBar from './ScreenBar' import './ScreenHeader.css' import '../../variables.css' const ScreenHeader = ({ children, className }) => ( <ScreenBar className={className ? `ScreenHeader ${className}` : 'ScreenHeader'} backgroundColor="var(--primary)" > {children} </ScreenBar> ) export default ScreenHeader
src/app/component/material-image/material-image.js
all3dp/printing-engine-client
import PropTypes from 'prop-types' import React from 'react' import propTypes from '../../prop-types' import cn from '../../lib/class-names' const MaterialImage = ({classNames, color = '#ffffff', image, zoom, square, onClick}) => { const style = { backgroundColor: color } if (image) { style.backgroundImage = `url(${image})` } return React.createElement(onClick ? 'button' : 'span', { className: cn( 'MaterialImage', {border: color === '#ffffff' || image, zoom, square}, classNames ), type: onClick ? 'button' : undefined, style, onClick }) } MaterialImage.propTypes = { ...propTypes.component, color: PropTypes.string, image: PropTypes.string, zoom: PropTypes.bool, square: PropTypes.bool, onClick: PropTypes.func } export default MaterialImage
lib/utils/plugins.js
wilsontayar/hyper
import {remote} from 'electron'; import {connect as reduxConnect} from 'react-redux'; // patching Module._load // so plugins can `require` them wihtout needing their own version // https://github.com/zeit/hyper/issues/619 import React from 'react'; import ReactDOM from 'react-dom'; import Component from '../component'; import Notification from '../components/notification'; import notify from './notify'; const Module = require('module'); // eslint-disable-line import/newline-after-import const originalLoad = Module._load; Module._load = function (path) { switch (path) { case 'react': return React; case 'react-dom': return ReactDOM; case 'hyper/component': return Component; case 'hyper/notify': return notify; case 'hyper/Notification': return Notification; case 'hyper/decorate': return decorate; default: return originalLoad.apply(this, arguments); } }; // remote interface to `../plugins` const plugins = remote.require('./plugins'); // `require`d modules let modules; // cache of decorated components let decorated = {}; // various caches extracted of the plugin methods let connectors; let middlewares; let uiReducers; let sessionsReducers; let termGroupsReducers; let tabPropsDecorators; let tabsPropsDecorators; let termPropsDecorators; let termGroupPropsDecorators; let propsDecorators; let reducersDecorators; // the fs locations where user plugins are stored const {path, localPath} = plugins.getBasePaths(); const clearModulesCache = () => { // trigger unload hooks modules.forEach(mod => { if (mod.onRendererUnload) { mod.onRendererUnload(window); } }); // clear require cache for (const entry in window.require.cache) { if (entry.indexOf(path) === 0 || entry.indexOf(localPath) === 0) { // `require` is webpacks', `window.require` is electron's delete window.require.cache[entry]; } } }; const pathModule = window.require('path'); const getPluginName = path => pathModule.basename(path); const getPluginVersion = path => { let version = null; try { version = window.require(pathModule.resolve(path, 'package.json')).version; } catch (err) { console.warn(`No package.json found in ${path}`); } return version; }; const loadModules = () => { console.log('(re)loading renderer plugins'); const paths = plugins.getPaths(); // initialize cache that we populate with extension methods connectors = { Terms: {state: [], dispatch: []}, Header: {state: [], dispatch: []}, Hyper: {state: [], dispatch: []}, Notifications: {state: [], dispatch: []} }; uiReducers = []; middlewares = []; sessionsReducers = []; termGroupsReducers = []; tabPropsDecorators = []; tabsPropsDecorators = []; termPropsDecorators = []; termGroupPropsDecorators = []; propsDecorators = { getTermProps: termPropsDecorators, getTabProps: tabPropsDecorators, getTabsProps: tabsPropsDecorators, getTermGroupProps: termGroupPropsDecorators }; reducersDecorators = { reduceUI: uiReducers, reduceSessions: sessionsReducers, reduceTermGroups: termGroupsReducers }; modules = paths.plugins.concat(paths.localPlugins) .map(path => { let mod; const pluginName = getPluginName(path); const pluginVersion = getPluginVersion(path); // window.require allows us to ensure this doesn't get // in the way of our build try { mod = window.require(path); } catch (err) { console.error(err.stack); notify('Plugin load error', `"${pluginName}" failed to load in the renderer process. Check Developer Tools for details.`); return undefined; } for (const i in mod) { if ({}.hasOwnProperty.call(mod, i)) { mod[i]._pluginName = pluginName; mod[i]._pluginVersion = pluginVersion; } } // mapHyperTermState mapping for backwards compatibility with hyperterm if (mod.mapHyperTermState) { mod.mapHyperState = mod.mapHyperTermState; console.error('mapHyperTermState is deprecated. Use mapHyperState instead.'); } // mapHyperTermDispatch mapping for backwards compatibility with hyperterm if (mod.mapHyperTermDispatch) { mod.mapHyperDispatch = mod.mapHyperTermDispatch; console.error('mapHyperTermDispatch is deprecated. Use mapHyperDispatch instead.'); } if (mod.middleware) { middlewares.push(mod.middleware); } if (mod.reduceUI) { uiReducers.push(mod.reduceUI); } if (mod.reduceSessions) { sessionsReducers.push(mod.reduceSessions); } if (mod.reduceTermGroups) { termGroupsReducers.push(mod.reduceTermGroups); } if (mod.mapTermsState) { connectors.Terms.state.push(mod.mapTermsState); } if (mod.mapTermsDispatch) { connectors.Terms.dispatch.push(mod.mapTermsDispatch); } if (mod.mapHeaderState) { connectors.Header.state.push(mod.mapHeaderState); } if (mod.mapHeaderDispatch) { connectors.Header.dispatch.push(mod.mapHeaderDispatch); } if (mod.mapHyperState) { connectors.Hyper.state.push(mod.mapHyperState); } if (mod.mapHyperDispatch) { connectors.Hyper.dispatch.push(mod.mapHyperDispatch); } if (mod.mapNotificationsState) { connectors.Notifications.state.push(mod.mapNotificationsState); } if (mod.mapNotificationsDispatch) { connectors.Notifications.dispatch.push(mod.mapNotificationsDispatch); } if (mod.getTermGroupProps) { termGroupPropsDecorators.push(mod.getTermGroupProps); } if (mod.getTermProps) { termPropsDecorators.push(mod.getTermProps); } if (mod.getTabProps) { tabPropsDecorators.push(mod.getTabProps); } if (mod.getTabsProps) { tabsPropsDecorators.push(mod.getTabsProps); } if (mod.onRendererWindow) { mod.onRendererWindow(window); } console.log(`Plugin ${pluginName} (${pluginVersion}) loaded.`); return mod; }) .filter(mod => Boolean(mod)); }; // load modules for initial decoration loadModules(); export function reload() { clearModulesCache(); loadModules(); // trigger re-decoration when components // get re-rendered decorated = {}; } function getProps(name, props, ...fnArgs) { const decorators = propsDecorators[name]; let props_; decorators.forEach(fn => { let ret_; if (!props_) { props_ = Object.assign({}, props); } try { ret_ = fn(...fnArgs, props_); } catch (err) { console.error(err.stack); notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`); return; } if (!ret_ || typeof ret_ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\` (object expected).`); return; } props_ = ret_; }); return props_ || props; } export function getTermGroupProps(uid, parentProps, props) { return getProps('getTermGroupProps', props, uid, parentProps); } export function getTermProps(uid, parentProps, props) { return getProps('getTermProps', props, uid, parentProps); } export function getTabsProps(parentProps, props) { return getProps('getTabsProps', props, parentProps); } export function getTabProps(tab, parentProps, props) { return getProps('getTabProps', props, tab, parentProps); } // connects + decorates a class // plugins can override mapToState, dispatchToProps // and the class gets decorated (proxied) export function connect(stateFn, dispatchFn, c, d = {}) { return (Class, name) => { return reduxConnect( state => { let ret = stateFn(state); connectors[name].state.forEach(fn => { let ret_; try { ret_ = fn(state, ret); } catch (err) { console.error(err.stack); notify('Plugin error', `${fn._pluginName}: Error occurred in \`map${name}State\`. Check Developer Tools for details.`); return; } if (!ret_ || typeof ret_ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}State\` (object expected).`); return; } ret = ret_; }); return ret; }, dispatch => { let ret = dispatchFn(dispatch); connectors[name].dispatch.forEach(fn => { let ret_; try { ret_ = fn(dispatch, ret); } catch (err) { console.error(err.stack); notify('Plugin error', `${fn._pluginName}: Error occurred in \`map${name}Dispatch\`. Check Developer Tools for details.`); return; } if (!ret_ || typeof ret_ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}Dispatch\` (object expected).`); return; } ret = ret_; }); return ret; }, c, d )(decorate(Class, name)); }; } function decorateReducer(name, fn) { const reducers = reducersDecorators[name]; return (state, action) => { let state_ = fn(state, action); reducers.forEach(pluginReducer => { let state__; try { state__ = pluginReducer(state_, action); } catch (err) { console.error(err.stack); notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`); return; } if (!state__ || typeof state__ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\`.`); return; } state_ = state__; }); return state_; }; } export function decorateTermGroupsReducer(fn) { return decorateReducer('reduceTermGroups', fn); } export function decorateUIReducer(fn) { return decorateReducer('reduceUI', fn); } export function decorateSessionsReducer(fn) { return decorateReducer('reduceSessions', fn); } // redux middleware generator export const middleware = store => next => action => { const nextMiddleware = remaining => action => remaining.length ? remaining[0](store)(nextMiddleware(remaining.slice(1)))(action) : next(action); nextMiddleware(middlewares)(action); }; // expose decorated component instance to the higher-order components function exposeDecorated(Component) { return class extends React.Component { constructor(props, context) { super(props, context); this.onRef = this.onRef.bind(this); } onRef(decorated) { if (this.props.onDecorated) { this.props.onDecorated(decorated); } } render() { return React.createElement(Component, Object.assign({}, this.props, {ref: this.onRef})); } }; } function getDecorated(parent, name) { if (!decorated[name]) { let class_ = exposeDecorated(parent); class_.displayName = `_exposeDecorated(${name})`; modules.forEach(mod => { const method = 'decorate' + name; const fn = mod[method]; if (fn) { let class__; try { class__ = fn(class_, {React, Component, Notification, notify}); class__.displayName = `${fn._pluginName}(${name})`; } catch (err) { console.error(err.stack); notify('Plugin error', `${fn._pluginName}: Error occurred in \`${method}\`. Check Developer Tools for details`); return; } if (!class__ || typeof class__.prototype.render !== 'function') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${method}\`. No \`render\` method found. Please return a \`React.Component\`.`); return; } class_ = class__; } }); decorated[name] = class_; } return decorated[name]; } // for each component, we return a higher-order component // that wraps with the higher-order components // exposed by plugins export function decorate(Component, name) { return class extends React.Component { render() { const Sub = getDecorated(Component, name); return React.createElement(Sub, this.props); } }; }
app/javascript/mastodon/features/status/index.js
3846masa/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchStatus } from '../../actions/statuses'; import Immutable from 'immutable'; import EmbeddedStatus from '../../components/status'; import MissingIndicator from '../../components/missing_indicator'; import DetailedStatus from './components/detailed_status'; import ActionBar from './components/action_bar'; import Column from '../ui/components/column'; import { favourite, unfavourite, reblog, unreblog, } from '../../actions/interactions'; import { replyCompose, mentionCompose, } from '../../actions/compose'; import { deleteStatus } from '../../actions/statuses'; import { initReport } from '../../actions/reports'; import { makeGetStatus, getStatusAncestors, getStatusDescendants, } from '../../selectors'; import { ScrollContainer } from 'react-router-scroll'; import ColumnBackButton from '../../components/column_back_button'; import StatusContainer from '../../containers/status_container'; import { openModal } from '../../actions/modal'; import { isMobile } from '../../is_mobile'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' }, }); const makeMapStateToProps = () => { const getStatus = makeGetStatus(); const mapStateToProps = (state, props) => ({ status: getStatus(state, Number(props.params.statusId)), ancestorsIds: state.getIn(['timelines', 'ancestors', Number(props.params.statusId)]), descendantsIds: state.getIn(['timelines', 'descendants', Number(props.params.statusId)]), me: state.getIn(['meta', 'me']), boostModal: state.getIn(['meta', 'boost_modal']), autoPlayGif: state.getIn(['meta', 'auto_play_gif']), }); return mapStateToProps; }; class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, status: ImmutablePropTypes.map, ancestorsIds: ImmutablePropTypes.list, descendantsIds: ImmutablePropTypes.list, me: PropTypes.number, boostModal: PropTypes.bool, autoPlayGif: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchStatus(Number(this.props.params.statusId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchStatus(Number(nextProps.params.statusId))); } } handleFavouriteClick = (status) => { if (status.get('favourited')) { this.props.dispatch(unfavourite(status)); } else { this.props.dispatch(favourite(status)); } } handleReplyClick = (status) => { this.props.dispatch(replyCompose(status, this.context.router)); } handleModalReblog = (status) => { this.props.dispatch(reblog(status)); } handleReblogClick = (status, e) => { if (status.get('reblogged')) { this.props.dispatch(unreblog(status)); } else { if (e.shiftKey || !this.props.boostModal) { this.handleModalReblog(status); } else { this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog })); } } } handleDeleteClick = (status) => { const { dispatch, intl } = this.props; dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.deleteMessage), confirm: intl.formatMessage(messages.deleteConfirm), onConfirm: () => dispatch(deleteStatus(status.get('id'))), })); } handleMentionClick = (account, router) => { this.props.dispatch(mentionCompose(account, router)); } handleOpenMedia = (media, index) => { this.props.dispatch(openModal('MEDIA', { media, index })); } handleOpenVideo = (media, time) => { this.props.dispatch(openModal('VIDEO', { media, time })); } handleReport = (status) => { this.props.dispatch(initReport(status.get('account'), status)); } renderChildren (list) { return list.map(id => <StatusContainer key={id} id={id} />); } render () { let ancestors, descendants; const { status, ancestorsIds, descendantsIds, me, autoPlayGif } = this.props; if (status === null) { return ( <Column> <ColumnBackButton /> <MissingIndicator /> </Column> ); } const account = status.get('account'); if (ancestorsIds && ancestorsIds.size > 0) { ancestors = <div>{this.renderChildren(ancestorsIds)}</div>; } if (descendantsIds && descendantsIds.size > 0) { descendants = <div>{this.renderChildren(descendantsIds)}</div>; } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='thread'> <div className='scrollable detailed-status__wrapper'> {ancestors} <DetailedStatus status={status} autoPlayGif={autoPlayGif} me={me} onOpenVideo={this.handleOpenVideo} onOpenMedia={this.handleOpenMedia} /> <ActionBar status={status} me={me} onReply={this.handleReplyClick} onFavourite={this.handleFavouriteClick} onReblog={this.handleReblogClick} onDelete={this.handleDeleteClick} onMention={this.handleMentionClick} onReport={this.handleReport} /> {descendants} </div> </ScrollContainer> </Column> ); } } export default injectIntl(connect(makeMapStateToProps)(Status));
actor-apps/app-web/src/app/components/JoinGroup.react.js
voidException/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import DialogActionCreators from 'actions/DialogActionCreators'; import JoinGroupActions from 'actions/JoinGroupActions'; import JoinGroupStore from 'stores/JoinGroupStore'; // eslint-disable-line class JoinGroup extends React.Component { static propTypes = { params: React.PropTypes.object }; static contextTypes = { router: React.PropTypes.func }; constructor(props) { super(props); JoinGroupActions.joinGroup(props.params.token) .then((peer) => { this.context.router.replaceWith('/'); DialogActionCreators.selectDialogPeer(peer); }).catch((e) => { console.warn(e, 'User is already a group member'); this.context.router.replaceWith('/'); }); } render() { return null; } } export default requireAuth(JoinGroup);
packages/core/admin/admin/src/content-manager/icons/Media/index.js
wistityhq/strapi
import React from 'react'; const Media = () => { return ( <svg width="12" height="11" xmlns="http://www.w3.org/2000/svg"> <g fill="#333740" fillRule="evenodd"> <path d="M9 4.286a1.286 1.286 0 1 0 0-2.572 1.286 1.286 0 0 0 0 2.572z" /> <path d="M11.25 0H.75C.332 0 0 .34 0 .758v8.77c0 .418.332.758.75.758h10.5c.418 0 .75-.34.75-.758V.758A.752.752 0 0 0 11.25 0zM8.488 5.296a.46.46 0 0 0-.342-.167c-.137 0-.234.065-.343.153l-.501.423c-.105.075-.188.126-.308.126a.443.443 0 0 1-.295-.11 3.5 3.5 0 0 1-.115-.11L5.143 4.054a.59.59 0 0 0-.897.008L.857 8.148V1.171a.353.353 0 0 1 .351-.314h9.581a.34.34 0 0 1 .346.322l.008 6.975-2.655-2.858z" /> </g> </svg> ); }; export default Media;
website/modules/components/NativeExample.js
DelvarWorld/react-router
import React from 'react' import PropTypes from 'prop-types' import Media from 'react-media' import { Block, Col } from 'jsxstyle' import Bundle from './Bundle' import SourceViewer from './SourceViewer' import SmallScreen from './SmallScreen' import Loading from './Loading' const NativeExample = ({ example }) => ( <Bundle load={example.loadSource}> {(src) => src ? ( <Media query="(min-width: 1170px)"> {(largeScreen) => ( <SmallScreen> {(smallScreen) => ( <Block minHeight="100vh" background="rgb(45, 45, 45)" padding="40px" > <Col position={largeScreen ? 'fixed' : 'static'} width={largeScreen ? '435px' : 'auto'} left="290px" top="40px" bottom="40px" > {example.appetizeURL && <iframe src={`${example.appetizeURL}?device=iphone6&scale=50&autoplay=false&orientation=portrait&deviceColor=white`} width="208px" height="435px" style={smallScreen ? { margin: 'auto' } : null} frameBorder="0" scrolling="no" ></iframe>} </Col> <SourceViewer code={src} fontSize="11px" marginLeft={largeScreen ? '280px' : null} marginTop={largeScreen ? null : '40px'} /> </Block> )} </SmallScreen> )} </Media> ) : <Loading/>} </Bundle> ) NativeExample.propTypes = { example: PropTypes.object } export default NativeExample
samples/BasicComponents.js
adamweeks/react-ciscospark-1
import React from 'react'; import Button from '@webex/react-component-button'; import Icon, {ICONS} from '@webex/react-component-icon'; function BasicComponents() { function onClick() { // eslint-disable-next-line no-alert window.alert('onClick'); } const buttonContainerStyle = { width: '40px', height: '40px', border: '1px solid rgba(0, 0, 0, 0.06)', borderRadius: '50%' }; return ( <div> <h3>Buttons</h3> <div style={{display: 'flex', flexDirection: 'row'}}> <div style={buttonContainerStyle}> <Button accessibilityLabel="Main Menu" iconColor="black" iconType={ICONS.ICON_TYPE_WAFFLE} onClick={onClick} /> </div> <div style={buttonContainerStyle}> <Button iconColor="purple" iconType={ICONS.ICON_TYPE_DELETE} onClick={onClick} title="delete" /> </div> </div> <h3>Icons</h3> <div style={{display: 'flex', flexDirection: 'row'}}> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Add Icon" type={ICONS.ICON_TYPE_ADD} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Contact Icon" type={ICONS.ICON_TYPE_CONTACT} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Delete Icon" type={ICONS.ICON_TYPE_DELETE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="DND Icon" type={ICONS.ICON_TYPE_DND} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Document Icon" type={ICONS.ICON_TYPE_DOCUMENT} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Download" type={ICONS.ICON_TYPE_DOWNLOAD} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Exit Icon" type={ICONS.ICON_TYPE_EXIT} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="External User Icon" type={ICONS.ICON_TYPE_EXTERNAL_USER} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="External User Outline Icon" type={ICONS.ICON_TYPE_EXTERNAL_USER_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Files Icon" type={ICONS.ICON_TYPE_FILES} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Flagged Icon" type={ICONS.ICON_TYPE_FLAGGED} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Flagged Outline Icon" type={ICONS.ICON_TYPE_FLAGGED_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Invite Icon" type={ICONS.ICON_TYPE_INVITE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Message Icon" type={ICONS.ICON_TYPE_MESSAGE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Message Outline Icon" type={ICONS.ICON_TYPE_MESSAGE_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="More Icon" type={ICONS.ICON_TYPE_MORE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Mute Icon" type={ICONS.ICON_TYPE_MUTE_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Participant List Icon" type={ICONS.ICON_TYPE_PARTICIPANT_LIST} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="PTO Icon" type={ICONS.ICON_TYPE_PTO} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Right Arrow Icon" type={ICONS.ICON_TYPE_RIGHT_ARROW} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Video Cross Outline Icon" type={ICONS.ICON_TYPE_VIDEO_CROSS_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Video Outline Icon" type={ICONS.ICON_TYPE_VIDEO_OUTLINE} /> </div> <div style={{height: '25px', width: '25px', backgroundColor: 'blueviolet'}}> <Icon color="white" title="Waffle Icon" type={ICONS.ICON_TYPE_WAFFLE} /> </div> </div> </div> ); } export default BasicComponents;
src/framework/react/demo/AppContext.js
baukh789/GridManager
import React from 'react'; const AppContext = React.createContext({gridManagerName: 'testReact'}); export default AppContext;
examples/src/index.js
alexkuz/react-json-tree
import { render } from 'react-dom'; import React from 'react'; import App from './App'; render(<App />, document.getElementById('root'));
Console/app/node_modules/antd/es/tree-select/index.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; 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'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import RcTreeSelect, { TreeNode, SHOW_ALL, SHOW_PARENT, SHOW_CHILD } from 'rc-tree-select'; import classNames from 'classnames'; import injectLocale from '../locale-provider/injectLocale'; import warning from '../_util/warning'; var TreeSelect = function (_React$Component) { _inherits(TreeSelect, _React$Component); function TreeSelect(props) { _classCallCheck(this, TreeSelect); var _this = _possibleConstructorReturn(this, (TreeSelect.__proto__ || Object.getPrototypeOf(TreeSelect)).call(this, props)); warning(props.multiple !== false || !props.treeCheckable, '`multiple` will alway be `true` when `treeCheckable` is true'); return _this; } _createClass(TreeSelect, [{ key: 'render', value: function render() { var _classNames; var locale = this.getLocale(); var _a = this.props, prefixCls = _a.prefixCls, className = _a.className, size = _a.size, _a$notFoundContent = _a.notFoundContent, notFoundContent = _a$notFoundContent === undefined ? locale.notFoundContent : _a$notFoundContent, dropdownStyle = _a.dropdownStyle, restProps = __rest(_a, ["prefixCls", "className", "size", "notFoundContent", "dropdownStyle"]); var cls = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, prefixCls + '-sm', size === 'small'), _classNames), className); var checkable = restProps.treeCheckable; if (checkable) { checkable = React.createElement('span', { className: prefixCls + '-tree-checkbox-inner' }); } return React.createElement(RcTreeSelect, _extends({}, restProps, { prefixCls: prefixCls, className: cls, dropdownStyle: _extends({ maxHeight: '100vh', overflow: 'auto' }, dropdownStyle), treeCheckable: checkable, notFoundContent: notFoundContent })); } }]); return TreeSelect; }(React.Component); TreeSelect.TreeNode = TreeNode; TreeSelect.SHOW_ALL = SHOW_ALL; TreeSelect.SHOW_PARENT = SHOW_PARENT; TreeSelect.SHOW_CHILD = SHOW_CHILD; TreeSelect.defaultProps = { prefixCls: 'ant-select', transitionName: 'slide-up', choiceTransitionName: 'zoom', showSearch: false, dropdownClassName: 'ant-select-tree-dropdown' }; // Use Select's locale var injectSelectLocale = injectLocale('Select', {}); export default injectSelectLocale(TreeSelect);
src/components/navigation/Header/NavBar/NavBarHeader.js
cltk/cltk_frontend
import React from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { toggleLeftMenu } from '../../../../actions/leftMenu'; import './NavBarHeader.css'; const NavBarHeader = ({ dispatchToggleLeftMenu, leftMenuOpen }) => ( <div className="nav-header"> <i className="mdi mdi-menu left-menu-toggle-icon" onClick={dispatchToggleLeftMenu.bind(this, !leftMenuOpen)} /> <Link to="/"> <h2 className="site-title"> CLTK Archive </h2> </Link> </div> ); const mapStateToProps = state => ({ userId: state.auth.userId, leftMenuOpen: state.leftMenu.open, }); const mapDispatchToProps = dispatch => ({ dispatchToggleLeftMenu: (open) => { dispatch(toggleLeftMenu(open)); }, }); export default connect( mapStateToProps, mapDispatchToProps )(NavBarHeader);
src/components/ShareExperience/common/FailFeedback.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import Feedback from 'common/Feedback'; const FailFeedback = ({ info, buttonClick }) => ( <Feedback buttonClick={buttonClick} heading="Oops 有些錯誤發生" info={ info || '請查看你的網路連線再試一次,如果你還沒填寫完,請先別關閉瀏覽器!' } buttonText="好,我知道了" /> ); FailFeedback.propTypes = { info: PropTypes.string, buttonClick: PropTypes.func, }; export default FailFeedback;
app/src/components/App/RouteTransition.js
AlexandreBourdeaudhui/abourdeaudhui.fr
// /* // * Package Import // */ // import React from 'react'; // import PropTypes from 'prop-types'; // import { CSSTransitionGroup } from 'react-transition-group'; // import { Route } from 'react-router-dom'; // // // /* // * Local Import // */ // // // /* // * Component // */ // const RouteTransition = ({ component: Component, location, path }) => ( // <CSSTransitionGroup // transitionName="fade" // transitionEnterTimeout={300} // transitionLeaveTimeout={300} // > // <Route // location={location} // key={location.key} // path={path} // component={Component} // /> // </CSSTransitionGroup> // ); // // // /* // * PropTypes // */ // RouteTransition.propTypes = { // component: PropTypes.func.isRequired, // }; // // // /* // * Export // */ // export default RouteTransition;
src/svg-icons/device/battery-90.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery90 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/> </SvgIcon> ); DeviceBattery90 = pure(DeviceBattery90); DeviceBattery90.displayName = 'DeviceBattery90'; DeviceBattery90.muiName = 'SvgIcon'; export default DeviceBattery90;
lib/react/components/MenuButton.js
bwyap/ptc-amazing-g-race
import React from 'react'; import PropTypes from 'prop-types'; import autobind from 'core-decorators/es/autobind'; import { Popover, Position, Button } from "@blueprintjs/core"; @autobind class MenuButton extends React.Component { static propTypes = { menu: PropTypes.element, iconName: PropTypes.string, text: PropTypes.string, loading: PropTypes.bool, buttonClass: PropTypes.string, popoverClass: PropTypes.string, position: PropTypes.oneOf(Object.keys(Position).map( (value) => { const num = parseInt(value); if (isNaN(num)) return value; else return num; } )) } static defaultProps = { loading: false, position: Position.BOTTOM_RIGHT } render() { return ( <Popover className={this.props.popoverClass} content={this.props.menu} position={this.props.position} isDisabled={this.props.loading}> <Button type='button' loading={this.props.loading} className={this.props.buttonClass} iconName={this.props.iconName} > {this.props.text} </Button> </Popover> ); } } export default MenuButton;
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-bricks-swiper.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, ContentMixin, SwipeMixin, Tools} from '../common/common.js'; import SwiperBody from './swiper-body.js'; import SwiperMenu from './swiper-menu.js'; import './swiper.less'; export const Swiper = React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, ContentMixin, SwipeMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Bricks.Swiper', classNames: { main: 'uu5-bricks-swiper' }, defaults: { bodyTagName: 'UU5.Bricks.Swiper.Body', menuTagName: 'UU5.Bricks.Swiper.Menu' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { leftMenuOpened: React.PropTypes.bool, rightMenuOpened: React.PropTypes.bool, onSwipeOpenLeftMenu: React.PropTypes.func, onSwipeCloseLeftMenu: React.PropTypes.func, onSwipeOpenRightMenu: React.PropTypes.func, onSwipeCloseRightMenu: React.PropTypes.func, allowBodyTags: React.PropTypes.array, allowMenuTags: React.PropTypes.array }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { leftMenuOpened: false, rightMenuOpened: false, onSwipeOpenLeftMenu: null, onSwipeCloseLeftMenu: null, onSwipeOpenRightMenu: null, onSwipeCloseRightMenu: null, allowBodyTags: [], allowMenuTags: [] }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle getInitialState: function () { return { leftMenuOpened: this.props.leftMenuOpened, rightMenuOpened: this.props.rightMenuOpened, allowBodyTags: this.props.allowBodyTags.concat(this.getDefault().bodyTagName), allowMenuTags: this.props.allowBodyTags.concat(this.getDefault().menuTagName) }; }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface openLeftMenu: function (setStateCallback) { this.setState({ leftMenuOpened: true, rightMenuOpened: false }, setStateCallback); return this; }, closeLeftMenu: function (setStateCallback) { this.setState({ leftMenuOpened: false }, setStateCallback); return this; }, toggleLeftMenu: function (setStateCallback) { this.setState(function (state) { var newState = { leftMenuOpened: !state.leftMenuOpened }; !state.leftMenuOpened && (newState.rightMenuOpened = false); return newState; }, setStateCallback); return this; }, openRightMenu: function (setStateCallback) { this.setState({ leftMenuOpened: false, rightMenuOpened: true }, setStateCallback ); return this; }, closeRightMenu: function (setStateCallback) { this.setState({ rightMenuOpened: false }, setStateCallback ); return this; }, toggleRightMenu: function (setStateCallback) { this.setState(function (state) { var newState = { rightMenuOpened: !state.rightMenuOpened }; !state.rightMenuOpened && (newState.leftMenuOpened = false); return newState; }, setStateCallback); return this; }, isLeftMenuOpened: function () { return this.state.leftMenuOpened; }, isRightMenuOpened: function () { return this.state.rightMenuOpened; }, //@@viewOff:interface //@@viewOn:overridingMethods shouldChildRender_: function (child) { var childTagName = Tools.getChildTagName(child); return this.state.allowMenuTags.indexOf(childTagName) > -1 || this.state.allowBodyTags.indexOf(childTagName) > -1; }, expandChildProps_: function (child) { var newChildProps = Tools.mergeDeep({}, child.props); if (this.state.allowMenuTags.indexOf(Tools.getChildTagName(child)) > -1) { if (child.props.pullRight) { newChildProps._opened = this.isRightMenuOpened(); } else { newChildProps._opened = this.isLeftMenuOpened(); } } return newChildProps || child.props; }, //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _onSwipeEnd: function () { if (this.isSwipedRight()) { if (this.isRightMenuOpened()) { if (typeof this.props.onSwipeCloseRightMenu === 'function') { this.props.onSwipeCloseRightMenu(this); } else { this.closeRightMenu(); } } else { if (typeof this.props.onSwipeOpenLeftMenu === 'function') { this.props.onSwipeOpenLeftMenu(this); } else { this.openLeftMenu(); } } } else if (this.isSwipedLeft()) { if (this.isLeftMenuOpened()) { if (typeof this.props.onSwipeCloseLeftMenu === 'function') { this.props.onSwipeCloseLeftMenu(this); } else { this.closeLeftMenu(); } } else { if (typeof this.props.onSwipeOpenRightMenu === 'function') { this.props.onSwipeOpenRightMenu(this); } else { this.openRightMenu(); } } } return this; }, //@@viewOff:componentSpecificHelpers // Render _buildChildren: function () { var menuLeft; var menuRight; var body; var children = this.getChildren(); if (children) { children.forEach(function (child) { if (this.state.allowBodyTags.indexOf(Tools.getChildTagName(child)) > -1) { body = child; } else if (this.state.allowMenuTags.indexOf(Tools.getChildTagName(child)) > -1) { if (child.props.pullRight) { menuRight = menuRight || child; } else { menuLeft = menuLeft || child; } } }.bind(this)); } var newChildren = []; menuLeft && newChildren.push(menuLeft); menuRight && newChildren.push(menuRight); body && newChildren.push(body); return newChildren; }, //@@viewOn:render render: function () { return ( <div {...this.buildMainAttrs()} onTouchStart={this.swipeOnTouchStart} onTouchMove={this.swipeOnTouchMove} onTouchEnd={this.swipeOnTouchEnd.bind(this, this._onSwipeEnd)} > {this._buildChildren()} {this.getDisabledCover()} </div> ); } //@@viewOff:render }); Swiper.Menu = SwiperMenu; Swiper.Body = SwiperBody; export default Swiper;
src/main.js
woutervh-/cancun-react
import App from './App'; import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import style from './style'; import FeaturesProvider from './FeaturesProvider'; // Needed for onTouchTap // Can go away when react 1.0 release // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); ReactDOM.render( <FeaturesProvider><App/></FeaturesProvider>, document.getElementById('react-main-mount') );
app/containers/Dashboard/index.js
acebusters/ab-web
import React from 'react'; import PropTypes from 'prop-types'; import { createStructuredSelector } from 'reselect'; import { FormattedMessage } from 'react-intl'; import web3Connect from '../AccountProvider/web3Connect'; import makeSelectAccountData from '../AccountProvider/selectors'; import Container from '../../components/Container'; import Balances from '../../components/Dashboard/Balances'; import Tabs from '../../components/Dashboard/Tabs'; import { setActiveTab } from './actions'; import { ADVANCED, OVERVIEW } from './constants'; import messages from './messages'; import { getActiveTab } from './selectors'; import { ABI_TOKEN_CONTRACT, conf } from '../../app.config'; const confParams = conf(); const TABS = [ { name: OVERVIEW, title: <FormattedMessage {...messages[OVERVIEW]} />, to: '/dashboard', icon: 'fa-tachometer', onlyActiveOnIndex: true, }, { name: ADVANCED, title: <FormattedMessage {...messages[ADVANCED]} />, to: '/dashboard/advanced', icon: 'fa-exclamation-triangle', }, ]; class DashboardRoot extends React.Component { constructor(props) { super(props); this.token = this.web3.eth.contract(ABI_TOKEN_CONTRACT).at(confParams.ntzAddr); } get web3() { return this.props.web3Redux.web3; } render() { const { account } = this.props; const weiBalance = this.web3.eth.balance(account.signerAddr); const babzBalance = this.token.balanceOf(account.signerAddr); return ( <Container> <Tabs tabs={TABS} {...this.props} /> <Balances babzBalance={babzBalance} weiBalance={weiBalance} /> {this.props.children} </Container> ); } } DashboardRoot.propTypes = { children: PropTypes.any, account: PropTypes.object, web3Redux: PropTypes.any, }; const mapStateToProps = createStructuredSelector({ activeTab: getActiveTab(), account: makeSelectAccountData(), }); export default web3Connect( mapStateToProps, () => ({ setActiveTab }), )(DashboardRoot);
docs/v5/layouts/src/demos/widgets/ActionBarExpandingContent.js
Bandwidth/shared-components
import React from 'react'; import Form from './Form'; const style = { marginTop: '30px', paddingLeft: '30px', paddingRight: '30px', paddingBottom: '30px', }; export default ({ barHeight, expanded, children }) => ( <div style={style}>{children}</div> );
src/js/components/menuNav.js
ShiningZeng/EasyChat
import React, { Component } from 'react'; import {socket, NAME, PHOTO, isPC} from '../main'; export class MenuNav extends Component { constructor(props) { super(props); } componentDidMount() { const funcMode = this.refs.funcMode; this.changeState = this.changeState.bind(this); funcMode.addEventListener('click', this.changeState, false); } changeState(e) { const domComment = this.refs.domComment; const domUser = this.refs.domUser; e = e || window.event;//这一行及下一行是为兼容IE8及以下版本 var target = e.target || e.srcElement; const {changeState} = this.props; if(e.target) { switch(e.target.getAttribute('data-mode')) { case 'chat': changeState('chatList'); break; case 'user': changeState('friendList'); break; case 'share': changeState('share'); break; case 'individual': changeState('individual'); break; } } } render() { return (<div id='menu-nav'> <ul ref="funcMode"> {isPC ? <li> <img src={PHOTO} /> </li> : null} <li ref="domComment" data-mode="chat"> <i className="icon iconfont icon-chat" data-mode="chat"></i> </li> <li ref="domUser" data-mode="user"> <i className="icon iconfont icon-friendl01" data-mode="user"></i> </li> <li data-mode="share"> <i className="icon iconfont icon-footfound" data-mode="share"></i> </li> <li data-mode="individual"> <i className="icon iconfont icon-iconsetting" data-mode="individual"></i> </li> </ul> </div>); } }
src/web/components/ListItem/index.js
lukemarsh/react-redux-boilerplate
import React from 'react'; import styles from './styles.css'; const ListItem = (props) => ( <li className={props.className || styles.item}> <div className={styles.itemContent}> {props.item} </div> </li> ); ListItem.propTypes = { className: React.PropTypes.string, item: React.PropTypes.any, }; export default ListItem;
src/static/template.js
dhruv-kumar-jha/react-static-complete-website
'use strict'; import React from 'react'; import _ from 'lodash'; import Meta from '../meta'; const HTML = ( props ) => { const body = props.body; // lets find the file names for vendor, bundle and manifest file from the manifest object provided to us by the react-static-webpack-plugin const vendor = _.find( props.manifest, (file) => { return _.includes(file, 'vendor'); }); const bundle = _.find( props.manifest, (file) => { return _.includes(file, 'bundle'); }); const manifest = _.find( props.manifest, (file) => { return _.includes( file, 'manifest' ); }); // let's find the name of the url for which the html file is being generated // we will use that to find its meta details. let url = ''; let urls = props.reactStaticCompilation.renderProps.location.pathname; urls = urls.split('/'); if ( urls.length == 2 && urls[1] == '' ) { url = 'home'; } else { if ( urls.length == 2 ) { url = urls[1]; } else { url = urls[2]; } } let content = _.find( Meta, { url: url } ); if ( ! content ) { content = _.find( Meta, { url: 'default' } ); } return ( <html lang='en'> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <title>{ content.title }</title> <meta name="description" content={ content.description } data-react-helmet="true" /> <meta name="keywords" content={ content.keywords } data-react-helmet="true" /> <link rel="icon" href="/images/favicon.ico" /> <link href="/styles.css" rel="stylesheet" /> </head> <body> <div id='root'> <div dangerouslySetInnerHTML={{ __html: body }} /> </div> <script defer src={`/${ manifest }`} /> <script defer src={`/${ vendor }`} /> <script defer src={`/${ bundle }`} /> </body> </html> ); } export default HTML;
app/javascript/mastodon/features/notifications/components/clear_column_button.js
honpya/taketodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; export default class ClearColumnButton extends React.PureComponent { static propTypes = { onClick: PropTypes.func.isRequired, }; render () { return ( <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><i className='fa fa-eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button> ); } }
node_modules/react-native-vector-icons/RNIMigration.js
RahulDesai92/PHR
import React from 'react'; import PropTypes from 'prop-types'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import Zocial from 'react-native-vector-icons/Zocial'; import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'; const ICON_SET_MAP = { fontawesome: FontAwesome, foundation: Foundation, ion: Ionicons, material: MaterialIcons, zocial: Zocial, simpleline: SimpleLineIcons, }; // This is a composition is a drop in replacement for users migrating from the // react-native-icons module. Please don't use this component for new apps/views. export default class Icon extends React.Component { static propTypes = { name: PropTypes.string.isRequired, size: PropTypes.number, color: PropTypes.string, }; setNativeProps(nativeProps) { if (this.iconRef) { this.iconRef.setNativeProps(nativeProps); } } iconRef = null; handleComponentRef = ref => { this.iconRef = ref; }; render() { const nameParts = this.props.name.split('|'); const setName = nameParts[0]; const name = nameParts[1]; const IconSet = ICON_SET_MAP[setName]; if (!IconSet) { throw new Error(`Invalid icon set "${setName}"`); } return ( <IconSet allowFontScaling={false} ref={this.handleComponentRef} {...this.props} name={name} /> ); } }
docs/src/client-render.js
seek-oss/seek-style-guide
// Polyfills import 'core-js/fn/array/fill'; import 'core-js/fn/array/includes'; import 'core-js/fn/array/from'; import 'core-js/fn/string/ends-with'; import 'core-js/fn/string/includes'; import 'core-js/fn/string/starts-with'; import 'core-js/fn/object/get-own-property-symbols'; import React from 'react'; import { hydrate, render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import BrowserRouter from './BrowserRouter'; const appElement = document.getElementById('app'); hydrate( <AppContainer> <BrowserRouter /> </AppContainer>, appElement ); if (module.hot) { module.hot.accept('./BrowserRouter', () => { const NextBrowserRouter = require('./BrowserRouter').default; render( <AppContainer> <NextBrowserRouter /> </AppContainer>, appElement ); }); }
src/components/common/hocs/PagedContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import AppButton from '../AppButton'; import messages from '../../../resources/messages'; /** * Use this with the JS Composition pattern to make a Container that has paging controls. * * Your container MUST expost a `links` property. * * Your container MUST do one of the following: * (a) expose `previousPage` and `nextPage` event handler methods. * (b) pass in a onPageChange handler function that accepts (dispatch, props, linkId) * * Your container receives two buttons: * - nextButton (if there is another page) * - prevButton (if there is previous page) */ function withPaging(onPageChange) { function withPagingInner(ComposedContainer) { // eslint-disable-next-line react/prefer-stateless-function class PagedContainer extends React.Component { render() { const { links, nextPage, previousPage, dispatch } = this.props; const { formatMessage } = this.props.intl; let previousButton = null; if ((links !== undefined) && {}.hasOwnProperty.call(links, 'previous')) { const prevHandler = onPageChange || previousPage; previousButton = ( <div className="paging-button paging-button-previous"> <AppButton label={formatMessage(messages.previousPage)} onClick={() => prevHandler(dispatch, this.props, links.previous)} > <FormattedMessage {...messages.previousPage} /> </AppButton> </div> ); } let nextButton = null; if ((links !== undefined) && {}.hasOwnProperty.call(links, 'next')) { const nextHandler = onPageChange || nextPage; nextButton = ( <div className="paging-button paging-button-previous"> <AppButton primary label={formatMessage(messages.nextPage)} onClick={() => nextHandler(dispatch, this.props, links.next)} > <FormattedMessage {...messages.nextPage} /> </AppButton> </div> ); } return <ComposedContainer {...this.props} nextButton={nextButton} previousButton={previousButton} />; } } PagedContainer.propTypes = { // from compositional chain intl: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, // from child links: PropTypes.object.isRequired, nextPage: PropTypes.func, previousPage: PropTypes.func, }; return connect()(PagedContainer); } return withPagingInner; } export default withPaging;
src/svg-icons/action/view-week.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewWeek = (props) => ( <SvgIcon {...props}> <path d="M6 5H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm14 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm-7 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z"/> </SvgIcon> ); ActionViewWeek = pure(ActionViewWeek); ActionViewWeek.displayName = 'ActionViewWeek'; ActionViewWeek.muiName = 'SvgIcon'; export default ActionViewWeek;
src/containers/Launch/LaunchView.js
npdat/Demo_React_Native
/** * Launch Screen * - Shows a nice loading screen whilst: * - Preloading any specified app content * - Checking if user is logged in, and redirects from there * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Image, Alert, StatusBar, StyleSheet, ActivityIndicator, } from 'react-native'; import { Actions } from 'react-native-router-flux'; // Consts and Libs import { AppStyles, AppSizes } from '@theme/'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ launchImage: { width: AppSizes.screen.width, height: AppSizes.screen.height, }, }); /* Component ==================================================================== */ class AppLaunch extends Component { static componentName = 'AppLaunch'; static propTypes = { login: PropTypes.func.isRequired, getRecipes: PropTypes.func.isRequired, getMeals: PropTypes.func.isRequired, } componentDidMount = () => { // Show status bar on app launch StatusBar.setHidden(false, true); // Preload content here Promise.all([ this.props.getMeals(), this.props.getRecipes(), ]).then(() => { // Once we've preloaded basic content, // - Try to authenticate based on existing token this.props.login() // Logged in, show index screen .then(() => Actions.app({ type: 'reset' })) // Not Logged in, show Login screen .catch(() => Actions.authenticate({ type: 'reset' })); }).catch(err => Alert.alert(err.message)); } render = () => ( <View style={[AppStyles.container]}> <Image source={require('../../images/launch.jpg')} style={[styles.launchImage, AppStyles.containerCentered]} > <ActivityIndicator animating size={'large'} color={'#C1C5C8'} /> </Image> </View> ); } /* Export Component ==================================================================== */ export default AppLaunch;
src/common/components/select-repository-row/index.js
canonical-websites/build.snapcraft.io
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import classNames from 'classnames'; import styles from './selectRepositoryRow.css'; class SelectRepositoryRow extends Component { render() { const { errorMsg, repository, onChange, isRepoEnabled // is repository already enabled as a snap build } = this.props; // TODO tidy up when we get rid of prefixes const isChecked = repository.isSelected || isRepoEnabled; const isFetching = repository.isFetching; const isInputDisabled = isRepoEnabled || isFetching || !repository.isAdmin; const rowClass = classNames({ [styles.repositoryRow]: true, [styles.error]: errorMsg, [styles.disabled]: isRepoEnabled || !repository.isAdmin }); const tooltip = !repository.isAdmin ? 'You don’t have admin permission for this repo' : ''; return ( <label htmlFor={ repository.fullName } className={ rowClass } title={tooltip}> <input id={ repository.fullName } type="checkbox" onChange={ onChange } checked={ isChecked } disabled={ isInputDisabled } /> { repository.fullName } { errorMsg && <div className={ styles.errorMessage }> { errorMsg } </div> } </label> ); } } SelectRepositoryRow.defaultProps = { isSelected: false, isRepoEnabled: false }; SelectRepositoryRow.propTypes = { errorMsg: PropTypes.node, repository: PropTypes.shape({ fullName: PropTypes.string.isRequired }).isRequired, isRepoEnabled: PropTypes.bool, onChange: PropTypes.func, isSelected: PropTypes.bool }; export default SelectRepositoryRow;
new-lamassu-admin/src/pages/Dashboard/Alerts/Alerts.js
lamassu/lamassu-server
import { useQuery } from '@apollo/react-hooks' import Button from '@material-ui/core/Button' import Grid from '@material-ui/core/Grid' import { makeStyles } from '@material-ui/core/styles' import classnames from 'classnames' import gql from 'graphql-tag' import * as R from 'ramda' import React from 'react' import { cardState } from 'src/components/CollapsibleCard' import { Label1, H4 } from 'src/components/typography' import styles from './Alerts.styles' import AlertsTable from './AlertsTable' const NUM_TO_RENDER = 3 const GET_ALERTS = gql` query getAlerts { alerts { id type detail message created read valid } machines { deviceId name } } ` const useStyles = makeStyles(styles) const Alerts = ({ onReset, onExpand, size }) => { const classes = useStyles() const showAllItems = size === cardState.EXPANDED const { data } = useQuery(GET_ALERTS) const alerts = R.path(['alerts'])(data) ?? [] const machines = R.compose( R.map(R.prop('name')), R.indexBy(R.prop('deviceId')) )(data?.machines ?? []) const alertsLength = alerts.length const alertsTableContainerClasses = { [classes.alertsTableContainer]: !showAllItems, [classes.expandedAlertsTableContainer]: showAllItems } return ( <> <div className={classes.container}> <H4 className={classes.h4}>{`Alerts (${alertsLength})`}</H4> {showAllItems && ( <Label1 className={classes.upperButtonLabel}> <Button onClick={onReset} size="small" disableRipple disableFocusRipple className={classes.button}> {'Show less'} </Button> </Label1> )} </div> <Grid className={classnames(alertsTableContainerClasses)} container spacing={1}> <Grid item xs={12}> {!alerts.length && ( <Label1 className={classes.noAlertsLabel}> No new alerts. Your system is running smoothly. </Label1> )} <AlertsTable numToRender={showAllItems ? alerts.length : NUM_TO_RENDER} alerts={alerts} machines={machines} /> </Grid> </Grid> {!showAllItems && alertsLength > NUM_TO_RENDER && ( <Grid item xs={12}> <Label1 className={classes.centerLabel}> <Button onClick={() => onExpand('alerts')} size="small" disableRipple disableFocusRipple className={classes.button}> {`Show all (${alerts.length})`} </Button> </Label1> </Grid> )} </> ) } export default Alerts
App.js
AlexMarin/SensorInsights
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import { AppNav } from './app/config/router'; export default class App extends Component { render() { return <AppNav />; } } AppRegistry.registerComponent('SensorInsights', () => App);
app/components/todolist/AddTodo.js
flanamacca/react-learning-kit
import React from 'react'; import classNames from 'classnames/bind'; import styles from '../../css/todolist.css'; const cx = classNames.bind(styles); const AddTodo = ({addTodo}) => { let input; return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } let data = { text: input.value, complete: false, isPrivate: false } addTodo(data); input.value = '' }}> <input className={cx('todoEntry')} ref={node => { input = node }} /> <button className={cx('todoAddBtn')} type="submit"> Add Todo </button> </form> </div> ) } export default AddTodo;
src/components/PageHeroes.js
dfilipidisz/overfwolf-hots-talents
import React from 'react'; import { connect } from 'react-redux'; import HeroSelection from './HeroSelection'; import { Grid } from 'semantic-ui-react'; import Separator from './Separator'; import TalentStats from './TalentStats'; import TalentTypeChooser from './TalentTypeChooser'; import { Button } from 'semantic-ui-react'; import { HEROES } from '../constants'; import StatDetails from './StatDetails'; class PageHeroes extends React.Component { constructor() { super(); this.openBuild = this.openBuild.bind(this); this.composeBuild = this.composeBuild.bind(this); this.openStatDetails = this.openStatDetails.bind(this); this.closeStatDetails = this.closeStatDetails.bind(this); this.state = { isStatDetailsOpen: false, statDetailsLvl: null, }; } composeBuild() { const data = this.props.heroData; const { selectedHero, heroTalentFilter } = this.props; const hero = data[selectedHero]; const lvls = ['1', '4', '7', '10', '13', '16', '20']; const build = []; lvls.forEach((lvl) => { let topTalent = null; let topp = 0; hero[`lvl${lvl}`].forEach((talent) => { if (parseFloat(talent[heroTalentFilter]) > topp) { topp = parseFloat(talent[heroTalentFilter]); topTalent = Object.assign({}, talent); } }); build.push(topTalent); }); return { talents: build, hero: HEROES.find(h => h.value === selectedHero), buildName: heroTalentFilter === 'popularity' ? 'Popular Build (HotsLogs)' : 'Winrate Build (HotsLogs)', }; } openBuild() { overwolf.windows.sendMessage(this.props.widgetWindowid, 'show-yourself', null, () => {}); overwolf.windows.sendMessage(this.props.widgetWindowid, 'open-build', this.composeBuild(), () => {}); } openStatDetails(lvl) { this.setState({ isStatDetailsOpen: true, statDetailsLvl: lvl }); } closeStatDetails() { this.setState({ isStatDetailsOpen: false, statDetailsLvl: null }); } render () { const { selectedHero, forceSelection } = this.props; if (selectedHero === null || forceSelection) { return <HeroSelection />; } return ( <div className='page-heroes'> <Grid columns={16}> <Grid.Column width={8}> <Separator title='Individual Talent Stats' /> <TalentTypeChooser /> <TalentStats data={this.props.heroData} selectedHero={selectedHero} openStatDetails={this.openStatDetails} /> <div style={{ padding: '0 10px', marginTop: '11px' }}> <Button secondary fluid compact icon='external' labelPosition='right' content="Show this build in-game" onClick={this.openBuild} /> </div> </Grid.Column> <Grid.Column width={8} style={{paddingLeft: 0}}> <StatDetails open={this.state.isStatDetailsOpen} close={this.closeStatDetails} lvl={this.state.statDetailsLvl} data={this.props.heroData} selectedHero={selectedHero} /> </Grid.Column> </Grid> </div> ); } } export default connect( state => ({ selectedHero: state.app.selectedHero, forceSelection: state.app.forceSelection, heroData: state.app.heroData, widgetWindowid: state.app.widgetWindowid, windowid: state.app.windowid, heroTalentFilter: state.app.heroTalentFilter, }) )(PageHeroes);
app/containers/Tournament.js
jaadam/golfer-web
import React from 'react'; class Tournament extends React.Component { render() { return ( <h1>Tournament</h1> ); } } export default Tournament;
src/svg-icons/editor/show-chart.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorShowChart = (props) => ( <SvgIcon {...props}> <path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z"/> </SvgIcon> ); EditorShowChart = pure(EditorShowChart); EditorShowChart.displayName = 'EditorShowChart'; EditorShowChart.muiName = 'SvgIcon'; export default EditorShowChart;
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
alessandrostone/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ActorClient from 'utils/ActorClient'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import TypingActionCreators from 'actions/TypingActionCreators'; import DraftActionCreators from 'actions/DraftActionCreators'; import DraftStore from 'stores/DraftStore'; import AvatarItem from 'components/common/AvatarItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { text: DraftStore.getDraft(), profile: ActorClient.getUser(ActorClient.getUid()) }; }; var ComposeSection = React.createClass({ displayName: 'ComposeSection', propTypes: { peer: React.PropTypes.object.isRequired }, childContextTypes: { muiTheme: React.PropTypes.object }, mixins: [PureRenderMixin], getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; }, componentWillMount() { ThemeManager.setTheme(ActorTheme); DraftStore.addLoadDraftListener(this.onDraftLoad); }, componentWillUnmount() { DraftStore.removeLoadDraftListener(this.onDraftLoad); }, getInitialState: function() { return getStateFromStores(); }, onDraftLoad() { this.setState(getStateFromStores()); }, _onChange: function(event) { TypingActionCreators.onTyping(this.props.peer); this.setState({text: event.target.value}); }, _onKeyDown: function(event) { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this._sendTextMessage(); } else if (event.keyCode === 50 && event.shiftKey) { console.warn('Mention should show now.'); } }, onKeyUp() { DraftActionCreators.saveDraft(this.state.text); }, _sendTextMessage() { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } this.setState({text: ''}); DraftActionCreators.saveDraft('', true); }, _onSendFileClick: function() { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }, _onSendPhotoClick: function() { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }, _onFileInputChange: function() { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }, _onPhotoInputChange: function() { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }, _onPaste: function(event) { let preventDefault = false; _.forEach(event.clipboardData.items, function(item) { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }, render: function() { const text = this.state.text; const profile = this.state.profile; return ( <section className="compose" onPaste={this._onPaste}> <AvatarItem image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this._onChange} onKeyDown={this._onKeyDown} onKeyUp={this.onKeyUp} value={text}> </textarea> <footer className="compose__footer row"> <button className="button" onClick={this._onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this._onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this._sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this._onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this._onPhotoInputChange} type="file"/> </div> </section> ); } }); export default ComposeSection;
docs/src/app/components/pages/components/Tabs/ExampleIconText.js
mtsandeep/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; import FontIcon from 'material-ui/FontIcon'; import MapsPersonPin from 'material-ui/svg-icons/maps/person-pin'; const TabsExampleIconText = () => ( <Tabs> <Tab icon={<FontIcon className="material-icons">phone</FontIcon>} label="RECENTS" /> <Tab icon={<FontIcon className="material-icons">favorite</FontIcon>} label="FAVORITES" /> <Tab icon={<MapsPersonPin />} label="NEARBY" /> </Tabs> ); export default TabsExampleIconText;
components/Champion.js
hobinjk/illuminate
import React from 'react'; import staticApi from '../static/api'; import ChampionIcon from './ChampionIcon'; import ChampionStore from '../stores/ChampionStore'; import ChampionPicker from './ChampionPicker'; import { connectToStores } from 'fluxible-addons-react'; class Champion extends React.Component { constructor(props) { super(props); this.showPicker = this.showPicker.bind(this); } showPicker(event, champion) { let picker = this.refs.picker; picker.setState({visible: true, target: event.target, champion: champion}); } render() { return (<span className="champion"> <ChampionIcon onClick={this.showPicker} champion={this.props.champion}/> <ChampionPicker ref="picker"/> </span>); } } Champion = connectToStores(Champion, [ChampionStore], (context, props) => ({ champion: context.getStore(ChampionStore).getChampion() })) export default Champion;
src/svg-icons/social/party-mode.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPartyMode = (props) => ( <SvgIcon {...props}> <path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/> </SvgIcon> ); SocialPartyMode = pure(SocialPartyMode); SocialPartyMode.displayName = 'SocialPartyMode'; SocialPartyMode.muiName = 'SvgIcon'; export default SocialPartyMode;
examples/auth-with-shared-root/components/User.js
mattkrick/react-router
import React from 'react' const User = React.createClass({ render() { return <h1>User: {this.props.params.id}</h1> } }) export default User
packages/react-scripts/fixtures/kitchensink/src/features/env/NodePath.js
0xaio/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import load from 'absoluteLoad'; export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-node-path"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
js/react/offline.js
CANTUS-Project/vitrail
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Program Name: vitrail // Program Description: HTML/CSS/JavaScript user agent for the Cantus API. // // Filename: js/react/offline.js // Purpose: React components to manage Vitrail's use of offline caches. // // Copyright (C) 2016 Christopher Antila // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // ------------------------------------------------------------------------------------------------ import React from 'react'; import {Link} from 'react-router'; import Button from 'react-bootstrap/lib/Button'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import PageHeader from 'react-bootstrap/lib/PageHeader'; import Panel from 'react-bootstrap/lib/Panel'; import {getters} from '../nuclear/getters'; import {reactor} from '../nuclear/reactor'; import {SIGNALS as signals} from '../nuclear/signals'; /** The whole "Offline" page. * * Note: We could do a "serviceWorker in navigator" check here, but we'll consolidate the check for * supportedness so that we can change it easily if required. */ const OfflineManager = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return {swSupported: getters.swSupported}; }, render() { if (this.state.swSupported) { return ( <div className="container"> <PageHeader> {`Use Cantus Offline`} </PageHeader> <YesServiceWorker/> </div> ); } else { return ( <div className="container"> <PageHeader> {`Use Cantus Offline`} </PageHeader> <NoServiceWorker/> </div> ); } }, }); /** Shown when the browser does support ServiceWorker. */ const YesServiceWorker = React.createClass({ render() { return ( <Panel> <p> {`Your browser can save the Cantus Database as a browser app for offline use.`} </p> <p> {`When you "install" the Cantus Database, that means you can load the database by visiting our homepage URL even when you're not connected to the internet.`} </p> <p> {`When you're offline, you can view any chants that you saved in the `} <Link to="/workspace">{`Workspace`}</Link>{`. However, you can only search the database when you're online.`} </p> <hr/> <InstallOrUninstall/> </Panel> ); }, }); /** Shows the "Install" or "Uninstall" button as required. * * State * ----- * @param {str} emitted - Either undefined, "install," or "uninstall," indicating the signal called * most recently by clicking this button. * @param {bool} swInstalled - From NuclearJS, indicating whether Vitrail's assets are currently * cached by the browser. */ const InstallOrUninstall = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return {swInstalled: getters.swInstalled}; }, handleButtonClick() { // NB: we use setTimeout() so that it looks like it takes a moment to (un)install Vitrail! if (this.state.swInstalled) { this.setState({emitted: 'uninstall'}); window.setTimeout(() => { signals.swUninstall(); }, 1000); } else { this.setState({emitted: 'install'}); window.setTimeout(() => { signals.swInstall(); }, 1000); } }, render() { let working = false; // whether install/uninstall signal was emitted and isn't done yet let buttonText = 'Install'; if (this.state.swInstalled) { if (this.state.emitted === 'uninstall') { buttonText = '(uninstalling)'; working = true; } else { buttonText = 'Uninstall'; } } else { if (this.state.emitted === 'install') { buttonText = '(installing)'; working = true; } } return ( <Button onClick={this.handleButtonClick} disabled={working}>{buttonText}</Button> ); }, }); /** Shown when the browser doesn't support ServiceWorker. */ const NoServiceWorker = React.createClass({ render() { return ( <Panel> <p> {`If you want to use the Cantus Database when you're not connected to the web, remember to load it in your browser before you go offline.`} </p> <p> {`When you're offline, you can view any chants that you saved in the `} <Link to="/workspace">{`Workspace`}</Link>{`. However, you can only search the database when you're online.`} </p> <p> {`Some devices and browsers allow you to save the Cantus Database as a browser app for offline use. Unfortunately your browser does not have this feature.`} </p> </Panel> ); }, }); export default OfflineManager export {OfflineManager};
src/components/homepage/legal.js
LegalCheck/main
import React from 'react' const Legal = () => ( <div className="homeLegal"> <p>All of your answers will be confidential. Answering these questions does not make you a client of Community Law Wellington and Hutt Valley.</p> </div> ) export default Legal
src/screens/team/components/TeamDetail/TeamDetail.js
vio-lets/Larkyo-Client
import React from 'react'; import {Link} from 'react-router-dom'; import './TeamDetail.css'; export default class TeamDetail extends React.Component { constructor(props){ super(props); this.handleCreateNewTeamClicked = this.handleCreateNewTeamClicked.bind(this); this.handleMyTeamClicked = this.handleMyTeamClicked.bind(this); this.state = { teamDetail:{ id: 1, name: "Jesse's Team", description: "This is Jesse's team. Welcome everyone", members: [ {id:1, name:"Jesse", role:"Trip Planner"}, {id:2, name:"Clyde", role:"Travel Guide"}, {id:3, name:"Diadawnfly", role:"Photographer"}, {id:4, name:"Frank", role:"Accountant"}, {id:5, name:"Kevin", role:""}, {id:6, name:"Lawrence", role:"Food Supply"}, {id:7, name:"Leon", role:""}, {id:8, name:"Mike", role:"The Clown"}, {id:9, name:"Randy", role:"Food Supply"}], desiredSize: 100, desiredLocation: ["Mars","Earth","Venus","Moon"], vancantRole:["Travel Talent", "Producer", "Shutterbug", "Number Cruncher", "Caterer", "Entertainer"], notification: "The upcoming event is updated. Our next destination is the moon. Please prepare your camera and the Nindendo switch. It will be a long trip..." } } } handleCreateNewTeamClicked(){ this.props.handleRoute("CreateTeam"); }; handleMyTeamClicked(){ this.props.handleRoute("MyTeam"); } render() { return ( <div className="teamDetailPage"> <div className="header"> <div className="searchNavbar"> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav"> <li className="dropdown"> <a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Plans <span className="caret"/></a> <ul className="dropdown-menu"> <li><a href="#">Active Plan</a></li> <li><a href="#">Past Plans</a></li> <li><a href="#">Future Plans</a></li> </ul> </li> </ul> <ul className="nav navbar-nav"> <li className="dropdown"> <a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Team Management <span className="caret"/></a> <ul className="dropdown-menu"> <li><a href="#">Approve member</a></li> <li><a href="#">Change leader</a></li> <li><a href="#">Remove member</a></li> </ul> </li> </ul> <ul className="nav navbar-nav navbar-right"> <li><a href="#" onClick={this.handleCreateNewTeamClicked}>Create New Team</a></li> <li><a href="#" onClick={this.handleMyTeamClicked}>My Team</a></li> </ul> </div> </div> </nav> </div> </div> <div className="alert alert-info" role="alert"> <p className="highLight">Notification:</p> <p className="notification">{this.state.teamDetail.notification}</p> </div> <div className="basicInfo"> <p className="teamID">#{this.state.teamDetail.id}</p> <p className="teamName">{this.state.teamDetail.name}</p> <p className="description">{this.state.teamDetail.description}</p> <p className="desiredSize"> <span className="glyphicon glyphicon-user" aria-hidden="true"></span> Desired Size: {this.state.teamDetail.desiredSize}</p> <p className="desiredLocation"> <span className="glyphicon glyphicon-map-marker" aria-hidden="true"></span> Desired Location: {this.state.teamDetail.desiredLocation.map( each => {return each + " "} )}</p> <p className="vacantRole"> <span className="glyphicon glyphicon-plus" aria-hidden="true"></span> Vacant Roles: {this.state.teamDetail.vancantRole.map( each => {return each + " "} )}</p> </div> <div className="memberWrapper"> <table className="table table-hover table-striped memberTable"> <thead> <tr> <th>#</th> <th>Current Members</th> <th>Assigned Role</th> </tr> </thead> <tbody> {this.state.teamDetail.members.map( each => {return( <tr key={each.id}> <td>#{each.id}</td> <td>{each.name}</td> <td>{each.role}</td> </tr> )})} </tbody> </table> </div> <ul className="nav navbar-nav links"> <li><Link to="/">Back to Home</Link></li> </ul> </div> ); } }
src/Subheader/Subheader.js
igorbt/material-ui
import React from 'react'; import PropTypes from 'prop-types'; const Subheader = (props, context) => { const { children, inset, style, ...other } = props; const { prepareStyles, subheader, } = context.muiTheme; const styles = { root: { boxSizing: 'border-box', color: subheader.color, fontSize: 14, fontWeight: subheader.fontWeight, lineHeight: '48px', paddingLeft: inset ? 72 : 16, width: '100%', }, }; return ( <div {...other} style={prepareStyles(Object.assign(styles.root, style))}> {children} </div> ); }; Subheader.muiName = 'Subheader'; Subheader.propTypes = { /** * Node that will be placed inside the `Subheader`. */ children: PropTypes.node, /** * If true, the `Subheader` will be indented. */ inset: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; Subheader.defaultProps = { inset: false, }; Subheader.contextTypes = { muiTheme: PropTypes.object.isRequired, }; export default Subheader;
webapp/app/components/Software/Filters/Groups/index.js
EIP-SAM/SAM-Solution-Node-js
// // Filters page software // import React from 'react'; import { FormGroup, ControlLabel, FormControl, Col } from 'react-bootstrap'; import styles from 'components/Software/Filters/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class SoftwareFiltersGroups extends React.Component { constructor(props) { super(props); this.selectGroup = this.selectGroup.bind(this); } componentDidMount() { this.props.getGroupsRequest(); } selectGroup(e) { this.props.getCurrentGroup(e.target.value); this.props.filterUsers(this.props.currentTypeUser, e.target.value, this.props.allUsers); } render() { const selectGroups = []; selectGroups.push(<option key="option-all" value="All">All Groups</option>); if (this.props.groups !== undefined) { if (this.props.groups.length > 0) { this.props.groups.map((group, index) => ( selectGroups.push(<option key={`option-${index}`} value={group.name}>{group.name}</option>) )); } } return ( <FormGroup controlId="groups" bsSize="small"> <Col componentClass={ControlLabel} sm={2}> Groups : </Col> <Col sm={4}> <FormControl componentClass="select" className={styles.select} onChange={this.selectGroup}> {selectGroups} </FormControl> </Col> </FormGroup> ); } } SoftwareFiltersGroups.propTypes = { groups: React.PropTypes.arrayOf(React.PropTypes.object), currentTypeUser: React.PropTypes.string, allUsers: React.PropTypes.arrayOf(React.PropTypes.object), getCurrentGroup: React.PropTypes.func, getGroupsRequest: React.PropTypes.func, filterUsers: React.PropTypes.func, };
src/containers/Asians/_components/PublishedBreakRound/Ballots/SmallBallots/Instance/OverviewInstance/SpeakerDisplay.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import List, { ListItem, ListItemText } from 'material-ui/List' export default connect(mapStateToProps)(({ speaker, debatersById, score }) => <List> <ListItem dense > <ListItemText primary={`${debatersById[speaker].firstName} ${debatersById[speaker].lastName}`} secondary={score.toFixed(2)} /> </ListItem> </List> ) function mapStateToProps (state, ownProps) { return { debatersById: state.debaters.data } }
src/CardContext.js
glenjamin/react-bootstrap
import React from 'react'; export default React.createContext(null);
src/games/Game0.js
Breta01/MemoryKing
import React from 'react'; import { Link } from 'react-router'; import gameNumbers from './Numbers'; const NumbersGame = React.createClass({ render() { return ( <div className="game"> <h1>Welcome to the Number:</h1> <div id="gameContent"></div> <div id="gameControler"> <a id="gameSubmit">Submit</a> </div> </div> ) }, componentDidMount: function() { // Upgrading all Material Design Lite upgradable components // Only important for dynamicaly loading components gameNumbers.start(5); } }); export default NumbersGame
src/components/MemoryList/MemoryList.js
rdanieldesign/MemoryApp-ReactStarter
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import Link from '../Link'; import MemoryItem from '../MemoryItem'; import { getAllMemories } from '../../stores/MemoryStore'; class MemoryList extends Component { constructor() { super(); this.state = { items: [] }; } componentDidMount() { getAllMemories.call(this, this.handleNewData); } handleNewData(data) { this.setState({ items: data }); } render() { let items = []; this.state.items.forEach( item => { items.push(<MemoryItem title={item.title} type={item.type} properties={item.properties} _id={item._id} key={item._id} />) }); return ( <ul className="MemoryList"> { items } </ul> ); } } export default MemoryList;
src/index.js
licken/React-Common
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/index.js
danleavitt0/live-react-editor
import React from 'react' import AceEditor from 'react-ace' import $ from 'jquery' var Babel = require('babel') require('brace/mode/jsx') require('brace/theme/monokai') class Home extends React.Component { render () { return( <div> <button onClick={this._save.bind(this)}> save </button> <AceEditor mode="jsx" theme="monokai" name="UNIQUE_ID_OF_DIV" ref="editor" /> </div> ) } _save () { var value = this.refs.editor.editor.getValue() var transformed = Babel.transform(value).code } } console.log('hello') $(document).ready(function(){ React.render(<Home />, document.getElementById('container')) })
examples/forms-bootstrap/src/components/dialogs-destroy-optimistic/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; export default createReactClass({ displayName: 'Hook', propTypes: { model: PropTypes.object.isRequired }, render: function() { const { model } = this.props; return ( <div style={{ padding: '20px' }}> <button className="btn btn-primary" onClick={() => { lore.dialog.show(() => ( lore.dialogs.tweet.destroy(model, { blueprint: 'optimistic' }) )) }} > Open Dialog </button> </div> ); } });
node_modules/react-bootstrap/es/DropdownToggle.js
ASIX-ALS/asix-final-project-frontend
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Button from './Button'; import SafeAnchor from './SafeAnchor'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; var propTypes = { noCaret: PropTypes.bool, open: PropTypes.bool, title: PropTypes.string, useAnchor: PropTypes.bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = function (_React$Component) { _inherits(DropdownToggle, _React$Component); function DropdownToggle() { _classCallCheck(this, DropdownToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DropdownToggle.prototype.render = function render() { var _props = this.props, noCaret = _props.noCaret, open = _props.open, useAnchor = _props.useAnchor, bsClass = _props.bsClass, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? SafeAnchor : Button; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return React.createElement( Component, _extends({}, props, { role: 'button', className: classNames(className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && React.createElement('span', { className: 'caret' }) ); }; return DropdownToggle; }(React.Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; export default setBsClass('dropdown-toggle', DropdownToggle);
src/components/logo.js
barrierandco/barrierandco
import React from 'react' import styled from 'styled-components' import LogoImage from '../assets/images/logo.svg' const LogoIcon = styled.img` display: block; height: auto; margin: 0 0 8px; width: 64px; @media ${props => props.theme.breakpoint} { margin: 0 auto 8px; width: 80px; } ` const LogoStyle = styled.div` color: ${props => props.inverted ? 'white' : props.theme.colors.red}; font-family: 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: 400; font-size: 1.5rem; margin-bottom: 16px; @media ${props => props.theme.breakpoint} { margin-bottom: ${props => props.inverted ? '32px' : '48px'}; text-align: center; } ` const Logo = props => ( <LogoStyle inverted={props.inverted}> { !props.inverted && <LogoIcon src={LogoImage} alt="logo mark for barrier and company stylized to be similar to a pair of glasses" /> } Barrier&nbsp;&amp;&nbsp;Co. </LogoStyle> ) export default Logo
src/components/antd/spin/index.js
hyd378008136/olymComponents
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; }; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Animate from 'rc-animate'; import isCssAnimationSupported from '../_util/isCssAnimationSupported'; import omit from 'omit.js'; export default class Spin extends React.Component { constructor(props) { super(props); const spinning = props.spinning; this.state = { spinning, }; } isNestedPattern() { return !!(this.props && this.props.children); } componentDidMount() { if (!isCssAnimationSupported()) { // Show text in IE8/9 this.setState({ notCssAnimationSupported: true, }); } } componentWillUnmount() { if (this.debounceTimeout) { clearTimeout(this.debounceTimeout); } if (this.delayTimeout) { clearTimeout(this.delayTimeout); } } componentWillReceiveProps(nextProps) { const currentSpinning = this.props.spinning; const spinning = nextProps.spinning; const { delay } = this.props; if (this.debounceTimeout) { clearTimeout(this.debounceTimeout); } if (currentSpinning && !spinning) { this.debounceTimeout = setTimeout(() => this.setState({ spinning }), 200); if (this.delayTimeout) { clearTimeout(this.delayTimeout); } } else { if (spinning && delay && !isNaN(Number(delay))) { if (this.delayTimeout) { clearTimeout(this.delayTimeout); } this.delayTimeout = setTimeout(() => this.setState({ spinning }), delay); } else { this.setState({ spinning }); } } } render() { const _a = this.props, { className, size, prefixCls, tip, wrapperClassName } = _a, restProps = __rest(_a, ["className", "size", "prefixCls", "tip", "wrapperClassName"]); const { spinning, notCssAnimationSupported } = this.state; const spinClassName = classNames(prefixCls, { [`${prefixCls}-sm`]: size === 'small', [`${prefixCls}-lg`]: size === 'large', [`${prefixCls}-spinning`]: spinning, [`${prefixCls}-show-text`]: !!tip || notCssAnimationSupported, }, className); // fix https://fb.me/react-unknown-prop const divProps = omit(restProps, [ 'spinning', 'delay', ]); const spinElement = (React.createElement("div", Object.assign({}, divProps, { className: spinClassName }), React.createElement("span", { className: `${prefixCls}-dot` }, React.createElement("i", null), React.createElement("i", null), React.createElement("i", null), React.createElement("i", null)), tip ? React.createElement("div", { className: `${prefixCls}-text` }, tip) : null)); if (this.isNestedPattern()) { let animateClassName = prefixCls + '-nested-loading'; if (wrapperClassName) { animateClassName += ' ' + wrapperClassName; } const containerClassName = classNames({ [`${prefixCls}-container`]: true, [`${prefixCls}-blur`]: spinning, }); return (React.createElement(Animate, Object.assign({}, divProps, { component: "div", className: animateClassName, style: null, transitionName: "fade" }), spinning && React.createElement("div", { key: "loading" }, spinElement), React.createElement("div", { className: containerClassName, key: "container" }, this.props.children))); } return spinElement; } } Spin.defaultProps = { prefixCls: 'ant-spin', spinning: true, size: 'default', wrapperClassName: '', }; Spin.propTypes = { prefixCls: PropTypes.string, className: PropTypes.string, spinning: PropTypes.bool, size: PropTypes.oneOf(['small', 'default', 'large']), wrapperClassName: PropTypes.string, };
examples/counter/containers/App.js
afram/redux
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createRedux } from 'redux'; import { Provider } from 'redux/react'; import * as stores from '../stores'; const redux = createRedux(stores); export default class App extends Component { render() { return ( <Provider redux={redux}> {() => <CounterApp />} </Provider> ); } }
fields/components/NestedFormField.js
Pop-Code/keystone
import React from 'react'; import { FormField, FormLabel } from '../../admin/client/App/elemental'; import theme from '../../admin/client/theme'; function NestedFormField ({ children, className, label, ...props }) { return ( <FormField {...props}> <FormLabel cssStyles={classes.label}> {label} </FormLabel> {children} </FormField> ); }; const classes = { label: { color: theme.color.gray40, fontSize: theme.font.size.small, [`@media (min-width: ${theme.breakpoint.tabletLandscapeMin})`]: { paddingLeft: '1em', }, }, }; module.exports = NestedFormField;
src/Alert.js
HorizonXP/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Alert = React.createClass({ mixins: [BootstrapMixin], propTypes: { onDismiss: React.PropTypes.func, dismissAfter: React.PropTypes.number, closeLabel: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info', closeLabel: 'Close Alert' }; }, renderDismissButton() { return ( <button type="button" className="close" onClick={this.props.onDismiss} aria-hidden="true"> <span>&times;</span> </button> ); }, renderSrOnlyDismissButton() { return ( <button type="button" className="close sr-only" onClick={this.props.onDismiss}> {this.props.closeLabel} </button> ); }, render() { let classes = this.getBsClassSet(); let isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return ( <div {...this.props} role="alert" className={classNames(this.props.className, classes)}> {isDismissable ? this.renderDismissButton() : null} {this.props.children} {isDismissable ? this.renderSrOnlyDismissButton() : null} </div> ); }, componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount() { clearTimeout(this.dismissTimer); } }); export default Alert;
node_modules/[email protected]@rc-calendar/es/Calendar.js
ligangwolai/blog
import _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import ReactDOM from 'react-dom'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import KeyCode from 'rc-util/es/KeyCode'; import DateTable from './date/DateTable'; import CalendarHeader from './calendar/CalendarHeader'; import CalendarFooter from './calendar/CalendarFooter'; import CalendarMixin from './mixin/CalendarMixin'; import CommonMixin from './mixin/CommonMixin'; import DateInput from './date/DateInput'; import { getTimeConfig, getTodayTime, syncTime } from './util'; function noop() {} function goStartMonth() { var next = this.state.value.clone(); next.startOf('month'); this.setValue(next); } function goEndMonth() { var next = this.state.value.clone(); next.endOf('month'); this.setValue(next); } function goTime(direction, unit) { var next = this.state.value.clone(); next.add(direction, unit); this.setValue(next); } function goMonth(direction) { return goTime.call(this, direction, 'months'); } function goYear(direction) { return goTime.call(this, direction, 'years'); } function goWeek(direction) { return goTime.call(this, direction, 'weeks'); } function goDay(direction) { return goTime.call(this, direction, 'days'); } var Calendar = createReactClass({ displayName: 'Calendar', propTypes: { disabledDate: PropTypes.func, disabledTime: PropTypes.any, value: PropTypes.object, selectedValue: PropTypes.object, defaultValue: PropTypes.object, className: PropTypes.string, locale: PropTypes.object, showWeekNumber: PropTypes.bool, style: PropTypes.object, showToday: PropTypes.bool, showDateInput: PropTypes.bool, visible: PropTypes.bool, onSelect: PropTypes.func, onOk: PropTypes.func, showOk: PropTypes.bool, prefixCls: PropTypes.string, onKeyDown: PropTypes.func, timePicker: PropTypes.element, dateInputPlaceholder: PropTypes.any, onClear: PropTypes.func, onChange: PropTypes.func, renderFooter: PropTypes.func, renderSidebar: PropTypes.func }, mixins: [CommonMixin, CalendarMixin], getDefaultProps: function getDefaultProps() { return { showToday: true, showDateInput: true, timePicker: null, onOk: noop }; }, getInitialState: function getInitialState() { return { showTimePicker: false }; }, onKeyDown: function onKeyDown(event) { if (event.target.nodeName.toLowerCase() === 'input') { return undefined; } var keyCode = event.keyCode; var ctrlKey = event.ctrlKey || event.metaKey; var disabledDate = this.props.disabledDate; var value = this.state.value; switch (keyCode) { case KeyCode.DOWN: goWeek.call(this, 1); event.preventDefault(); return 1; case KeyCode.UP: goWeek.call(this, -1); event.preventDefault(); return 1; case KeyCode.LEFT: if (ctrlKey) { goYear.call(this, -1); } else { goDay.call(this, -1); } event.preventDefault(); return 1; case KeyCode.RIGHT: if (ctrlKey) { goYear.call(this, 1); } else { goDay.call(this, 1); } event.preventDefault(); return 1; case KeyCode.HOME: goStartMonth.call(this); event.preventDefault(); return 1; case KeyCode.END: goEndMonth.call(this); event.preventDefault(); return 1; case KeyCode.PAGE_DOWN: goMonth.call(this, 1); event.preventDefault(); return 1; case KeyCode.PAGE_UP: goMonth.call(this, -1); event.preventDefault(); return 1; case KeyCode.ENTER: if (!disabledDate || !disabledDate(value)) { this.onSelect(value, { source: 'keyboard' }); } event.preventDefault(); return 1; default: this.props.onKeyDown(event); return 1; } }, onClear: function onClear() { this.onSelect(null); this.props.onClear(); }, onOk: function onOk() { var selectedValue = this.state.selectedValue; if (this.isAllowedDate(selectedValue)) { this.props.onOk(selectedValue); } }, onDateInputChange: function onDateInputChange(value) { this.onSelect(value, { source: 'dateInput' }); }, onDateTableSelect: function onDateTableSelect(value) { var timePicker = this.props.timePicker; var selectedValue = this.state.selectedValue; if (!selectedValue && timePicker) { var timePickerDefaultValue = timePicker.props.defaultValue; if (timePickerDefaultValue) { syncTime(timePickerDefaultValue, value); } } this.onSelect(value); }, onToday: function onToday() { var value = this.state.value; var now = getTodayTime(value); this.onSelect(now, { source: 'todayButton' }); }, getRootDOMNode: function getRootDOMNode() { return ReactDOM.findDOMNode(this); }, openTimePicker: function openTimePicker() { this.setState({ showTimePicker: true }); }, closeTimePicker: function closeTimePicker() { this.setState({ showTimePicker: false }); }, render: function render() { var props = this.props; var locale = props.locale, prefixCls = props.prefixCls, disabledDate = props.disabledDate, dateInputPlaceholder = props.dateInputPlaceholder, timePicker = props.timePicker, disabledTime = props.disabledTime; var state = this.state; var value = state.value, selectedValue = state.selectedValue, showTimePicker = state.showTimePicker; var disabledTimeConfig = showTimePicker && disabledTime && timePicker ? getTimeConfig(selectedValue, disabledTime) : null; var timePickerEle = null; if (timePicker && showTimePicker) { var timePickerProps = _extends({ showHour: true, showSecond: true, showMinute: true }, timePicker.props, disabledTimeConfig, { onChange: this.onDateInputChange, value: selectedValue, disabledTime: disabledTime }); if (timePicker.props.defaultValue !== undefined) { timePickerProps.defaultOpenValue = timePicker.props.defaultValue; } timePickerEle = React.cloneElement(timePicker, timePickerProps); } var dateInputElement = props.showDateInput ? React.createElement(DateInput, { format: this.getFormat(), key: 'date-input', value: value, locale: locale, placeholder: dateInputPlaceholder, showClear: true, disabledTime: disabledTime, disabledDate: disabledDate, onClear: this.onClear, prefixCls: prefixCls, selectedValue: selectedValue, onChange: this.onDateInputChange }) : null; var children = [props.renderSidebar(), React.createElement( 'div', { className: prefixCls + '-panel', key: 'panel' }, dateInputElement, React.createElement( 'div', { className: prefixCls + '-date-panel' }, React.createElement(CalendarHeader, { locale: locale, onValueChange: this.setValue, value: value, showTimePicker: showTimePicker, prefixCls: prefixCls }), timePicker && showTimePicker ? React.createElement( 'div', { className: prefixCls + '-time-picker' }, React.createElement( 'div', { className: prefixCls + '-time-picker-panel' }, timePickerEle ) ) : null, React.createElement( 'div', { className: prefixCls + '-body' }, React.createElement(DateTable, { locale: locale, value: value, selectedValue: selectedValue, prefixCls: prefixCls, dateRender: props.dateRender, onSelect: this.onDateTableSelect, disabledDate: disabledDate, showWeekNumber: props.showWeekNumber }) ), React.createElement(CalendarFooter, { showOk: props.showOk, renderFooter: props.renderFooter, locale: locale, prefixCls: prefixCls, showToday: props.showToday, disabledTime: disabledTime, showTimePicker: showTimePicker, showDateInput: props.showDateInput, timePicker: timePicker, selectedValue: selectedValue, value: value, disabledDate: disabledDate, okDisabled: !this.isAllowedDate(selectedValue), onOk: this.onOk, onSelect: this.onSelect, onToday: this.onToday, onOpenTimePicker: this.openTimePicker, onCloseTimePicker: this.closeTimePicker }) ) )]; return this.renderRoot({ children: children, className: props.showWeekNumber ? prefixCls + '-week-number' : '' }); } }); export default Calendar;
src/index.js
uoyknaht/tourreact2
import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import './styles/styles.scss'; //Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') );
src/routes/Library/components/SearchResults/SearchResults.js
bhj/karaoke-forever
import PropTypes from 'prop-types' import React from 'react' import PaddedList from 'components/PaddedList' import ArtistItem from '../ArtistItem' import SongList from '../SongList' import styles from './SearchResults.css' const ARTIST_HEADER_HEIGHT = 22 const ARTIST_RESULT_HEIGHT = 44 const SONG_HEADER_HEIGHT = 22 const SONG_RESULT_HEIGHT = 60 class SearchResults extends React.Component { static propTypes = { artists: PropTypes.object.isRequired, artistsResult: PropTypes.array.isRequired, expandedArtistResults: PropTypes.array.isRequired, filterKeywords: PropTypes.array.isRequired, filterStarred: PropTypes.bool.isRequired, queuedSongs: PropTypes.array.isRequired, songs: PropTypes.object.isRequired, songsResult: PropTypes.array.isRequired, starredSongs: PropTypes.array.isRequired, starredArtistCounts: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, // actions toggleArtistResultExpanded: PropTypes.func.isRequired, } componentDidUpdate (prevProps) { if (this.list) { // @todo: clear size cache starting from the toggled artist this.list.resetAfterIndex(0) } } render () { return ( <PaddedList numRows={this.props.artistsResult.length + 3} // both headers + SongList rowHeight={this.rowHeight} rowRenderer={this.rowRenderer} paddingTop={this.props.ui.headerHeight} paddingRight={4} paddingBottom={this.props.ui.footerHeight} width={this.props.ui.innerWidth} height={this.props.ui.innerHeight} onRef={this.setRef} /> ) } rowRenderer = ({ index, style }) => { const { artistsResult, songsResult, filterStarred } = this.props // # artist results heading if (index === 0) { return ( <div key={'artistsHeading'} style={style} className={styles.artistsHeading}> {artistsResult.length} {filterStarred ? 'starred ' : ''} {artistsResult.length === 1 ? 'artist' : 'artists'} </div> ) } // artist results if (index > 0 && index < artistsResult.length + 1) { const artistId = artistsResult[index - 1] const artist = this.props.artists[artistId] return ( <ArtistItem artistId={artistId} songs={this.props.songs} name={artist.name} numStars={this.props.starredArtistCounts[artistId] || 0} artistSongIds={artist.songIds} // "children" queuedSongs={this.props.queuedSongs} starredSongs={this.props.starredSongs} isExpanded={this.props.expandedArtistResults.includes(artistId)} filterKeywords={this.props.filterKeywords} onArtistClick={this.props.toggleArtistResultExpanded} key={artistId} style={style} /> ) } // # song results heading if (index === artistsResult.length + 1) { return ( <div key={'songsHeading'} style={style} className={styles.songsHeading}> {songsResult.length} {filterStarred ? 'starred ' : ''} {songsResult.length === 1 ? 'song' : 'songs'} </div> ) } // song results return ( <div style={style} key={'songs'}> <SongList songIds={songsResult} showArtist filterKeywords={this.props.filterKeywords} queuedSongs={this.props.queuedSongs} /> </div> ) } rowHeight = index => { // artists heading if (index === 0) return ARTIST_HEADER_HEIGHT // artist results if (index > 0 && index < this.props.artistsResult.length + 1) { let rows = 1 const artistId = this.props.artistsResult[index - 1] if (this.props.expandedArtistResults.includes(artistId)) { rows += this.props.artists[artistId].songIds.length } return rows * ARTIST_RESULT_HEIGHT } // songs heading if (index === this.props.artistsResult.length + 1) return SONG_HEADER_HEIGHT // song results return this.props.songsResult.length * SONG_RESULT_HEIGHT } setRef = (ref) => { this.list = ref } } export default SearchResults
Admin/Header/Index.js
wangmengling/MaoMobxBlog
import React, { Component } from 'react'; import Header from './Header'; export default () => ( <Header /> )
node_modules/antd/es/locale-provider/index.js
ZSMingNB/react-news
import _extends from 'babel-runtime/helpers/extends'; 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 React from 'react'; import PropTypes from 'prop-types'; import { changeConfirmLocale } from '../modal/locale'; var LocaleProvider = function (_React$Component) { _inherits(LocaleProvider, _React$Component); function LocaleProvider() { _classCallCheck(this, LocaleProvider); return _possibleConstructorReturn(this, (LocaleProvider.__proto__ || Object.getPrototypeOf(LocaleProvider)).apply(this, arguments)); } _createClass(LocaleProvider, [{ key: 'getChildContext', value: function getChildContext() { return { antLocale: _extends({}, this.props.locale, { exist: true }) }; } }, { key: 'componentWillMount', value: function componentWillMount() { this.componentDidUpdate(); } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { var locale = this.props.locale; changeConfirmLocale(locale && locale.Modal); } }, { key: 'componentWillUnMount', value: function componentWillUnMount() { changeConfirmLocale(); } }, { key: 'render', value: function render() { return React.Children.only(this.props.children); } }]); return LocaleProvider; }(React.Component); export default LocaleProvider; LocaleProvider.propTypes = { locale: PropTypes.object }; LocaleProvider.childContextTypes = { antLocale: PropTypes.object };
src/svg-icons/notification/vpn-lock.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationVpnLock = (props) => ( <SvgIcon {...props}> <path d="M22 4v-.5C22 2.12 20.88 1 19.5 1S17 2.12 17 3.5V4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm-.8 0h-3.4v-.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V4zm-2.28 8c.04.33.08.66.08 1 0 2.08-.8 3.97-2.1 5.39-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H7v-2h2c.55 0 1-.45 1-1V8h2c1.1 0 2-.9 2-2V3.46c-.95-.3-1.95-.46-3-.46C5.48 3 1 7.48 1 13s4.48 10 10 10 10-4.48 10-10c0-.34-.02-.67-.05-1h-2.03zM10 20.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L8 16v1c0 1.1.9 2 2 2v1.93z"/> </SvgIcon> ); NotificationVpnLock = pure(NotificationVpnLock); NotificationVpnLock.displayName = 'NotificationVpnLock'; NotificationVpnLock.muiName = 'SvgIcon'; export default NotificationVpnLock;
src/view/frontend/about-us/goals/index.js
MoosemanStudios/app.moosecraft.us
import React from 'react'; import classNames from 'classnames'; import Helmet from 'react-helmet'; import Column from 'src/components/layout/column'; import Heading from 'src/components/component/heading'; import misc from 'src/styles/misc.scss'; import layout from 'src/styles/layout.scss'; import colors from 'src/styles/colors.scss'; export default () => ( <div className="content"> <Heading title="Our Goals" /> <div className={classNames(layout.container, layout.box_width)}> <div className={layout.row}> <Column width={layout.one_full} classes={classNames(colors.background_white, misc.box_shadow)}> <p className={misc.side_padding}>Goal listed here</p> </Column> </div> </div> <Helmet> <title>Our Goals</title> </Helmet> </div> );
packages/ringcentral-widgets-docs/src/app/pages/Components/LogSection/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/LogSection'; const LogSectionPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="LogSection" description={info.description} /> <CodeExample code={demoCode} title="LogSection Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default LogSectionPage;
src/svg-icons/notification/sync-problem.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSyncProblem = (props) => ( <SvgIcon {...props}> <path d="M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z"/> </SvgIcon> ); NotificationSyncProblem = pure(NotificationSyncProblem); NotificationSyncProblem.displayName = 'NotificationSyncProblem'; NotificationSyncProblem.muiName = 'SvgIcon'; export default NotificationSyncProblem;
src/svg-icons/content/undo.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentUndo = (props) => ( <SvgIcon {...props}> <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/> </SvgIcon> ); ContentUndo = pure(ContentUndo); ContentUndo.displayName = 'ContentUndo'; ContentUndo.muiName = 'SvgIcon'; export default ContentUndo;
mobile/SchemaAnalyser/src/Home.js
lealhugui/schema-analyser
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; import { Card, Button } from 'react-native-elements'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'DOUBLE TAP R ON YOUR KEYBOARD TO RELOAD,\n' + 'SHAKE OR PRESS MENU BUTTON FOR DEV MENU', }); type Props = {}; export class Home extends Component<Props> { static navigationOptions = { title: "HOME", header: null } render() { return ( <View style={styles.container}> <Card title='WELCOME TO REACT NATIVE!' style={styles.cardBlue}> <Text style={styles.instructions}> To get started, edit App.js </Text> <Button title="GO TO SCREENONE" icon={{name: 'code'}} backgroundColor='#03A9F4' onPress={()=>this.props.navigation.navigate('ScreenOne')} /> </Card> <Card title='INSTRUCTIONS'> <Text style={styles.instructions}> {instructions} </Text> </Card> </View> ); } } const styles = StyleSheet.create({ cardBlue: { color: '#4286F4', }, container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: '#4286F4' }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
src/utils/CustomPropTypes.js
azmenak/react-bootstrap
import React from 'react'; import warning from 'react/lib/warning'; const ANONYMOUS = '<<anonymous>>'; const CustomPropTypes = { deprecated(propType, explanation){ return function(props, propName, componentName){ if (props[propName] != null) { warning(false, `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`); } return propType(props, propName, componentName); }; }, isRequiredForA11y(propType){ return function(props, propName, componentName){ if (props[propName] === null) { return new Error( 'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `' ); } return propType(props, propName, componentName); }; }, /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ elementType: createElementTypeChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker, all }; function errMsg(props, propName, componentName, msgContinuation) { return `Invalid prop '${propName}' of value '${props[propName]}'` + ` supplied to '${componentName}'${msgContinuation}`; } /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error( `Required prop '${propName}' was not specified in '${componentName}'.` ); } } else { return validate(props, propName, componentName); } } let chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error( errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method') ); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { let propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { let valuesString = JSON.stringify(Object.keys(obj)); return new Error( errMsg(props, propName, componentName, `, expected one of ${valuesString}.`) ); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName, componentName) { const usedPropCount = arrOfProps .map(listedProp => props[listedProp]) .reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0); if (usedPropCount > 1) { const [first, ...others] = arrOfProps; const message = `${others.join(', ')} and ${first}`; return new Error( `Invalid prop '${propName}', only one of the following ` + `may be provided: ${message}` ); } } return validate; } function all(propTypes) { if (propTypes === undefined) { throw new Error('No validations provided'); } if (!(propTypes instanceof Array)) { throw new Error('Invalid argument must be an array'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } return function(props, propName, componentName) { for(let i = 0; i < propTypes.length; i++) { let result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } }; } function createElementTypeChecker() { function validate(props, propName, componentName) { let errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (React.isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } return createChainableTypeChecker(validate); } export default CustomPropTypes;
src/Components/Utils/NavBar.js
abhishekdhaduvai/readable_react
import React from 'react'; import AppBar from 'material-ui/AppBar'; class NavBar extends React.Component { render(){ return ( <AppBar title="Readable" iconClassNameRight="muidocs-icon-navigation-expand-more" onClick={() => this.props.handleToggle()}/> ) } } export default NavBar;
src/login.js
cemiltokatli/ClearNotes
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import './assets/css/login-register.css'; import UserIcon from './assets/images/user-icon.png'; import PassIcon from './assets/images/lock-icon.png'; class Login extends Component { constructor(props) { super(props); this.formSubmitted = this.formSubmitted.bind(this); } formSubmitted(e) { this.submit.classList.add('loading'); this.submit.setAttribute('disabled','true'); let formData = new FormData(); formData.append('email',this.email.value); formData.append('password',this.password.value); let request = new XMLHttpRequest(); request.open('POST','api.php?t=login',true); request.addEventListener('load', e => { if(e.target.responseText) { this.form.classList.add('error'); this.submit.classList.remove('loading'); this.submit.removeAttribute('disabled'); } else { window.location = "."; } }); request.send(formData); e.preventDefault(); } render() { return( <div className="box"> <header>USER LOGIN</header> <section> <form id="login-form" onSubmit={this.formSubmitted} ref={elm => this.form = elm}> <div className="input-wrapper"> <div> <label> <input type="email" required placeholder="Email" ref={elm => this.email = elm} /> <img src={UserIcon} alt="" /> </label> </div> <div> <label> <input type="password" required placeholder="Password" ref={elm => this.password = elm} /> <img src={PassIcon} alt="" /> </label> </div> </div> <button type="submit" ref={elm => this.submit = elm}><span>Submit</span></button> </form> <a href="register">Register</a> </section> </div> ); } } class Background extends Component { shouldComponentUpdate() { return false; } render() { return( <div className="background-container"> <div className="background"></div> </div> ); } } class App extends Component { render() { return( <div> <Background /> <Login /> </div> ) } } ReactDOM.render(<App />, document.querySelector('#app'));
web/src/client/components/settings.js
mrsharpoblunto/it-gets-the-hose-again
/* * @format */ import React from 'react'; import {useState, useEffect, useContext} from 'react'; import keys from '../../../keys.json'; import {getSettings, updateSettings} from '../actions/settings'; import {useHistory} from 'react-router-dom'; import Loading from './loading'; import {StoreContext} from '../store-provider'; import M from 'materialize-css'; import {Map, Marker, GoogleApiWrapper} from 'google-maps-react'; export default function SettingsComponent() { const history = useHistory(); const [ { settings: {updating, initialized, settings}, }, dispatch, ] = useContext(StoreContext); const hasLocation = !!settings.location; const [locationError, setLocationError] = useState(null); const [updatingLocation, setUpdatingLocation] = useState(false); const [checkWeather, setCheckWeather] = useState(hasLocation); const [shutoffDuration, setShutoffDuration] = useState( settings.shutoffDuration, ); // initialize the UI and keep it in sync with // store changes useEffect(() => { if (!initialized) { dispatch(getSettings(history)); } else { M.updateTextFields(); setShutoffDuration(settings.shutoffDuration); if (!updatingLocation) { setCheckWeather(hasLocation); } } }, [ initialized, updatingLocation, hasLocation, dispatch, history, settings.shutoffDuration, ]); // get the users location useEffect(() => { if (!updatingLocation) { return; } let cancelled = false; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( position => { if (cancelled) { return; } setUpdatingLocation(false); setLocationError(null); dispatch( updateSettings({ location: { latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }, }), ); }, () => { if (cancelled) { return; } setUpdatingLocation(false); setLocationError('denied'); }, ); } else { setUpdatingLocation(false); setLocationError('notSupported'); } return () => { cancelled = true; }; }, [updatingLocation, dispatch]); const handleChangeShutoffDuration = e => { const newSettings = { shutoffDuration: parseInt(e.target.value), }; setShutoffDuration(newSettings.shutoffDuration); dispatch(updateSettings(newSettings, history)); }; const handleCheckWeather = e => { const newSettings = { location: null, }; setCheckWeather(e.target.checked); dispatch(updateSettings(newSettings, history)); if (e.target.checked) { setUpdatingLocation(true); } }; const handleRefreshLocation = () => { setUpdatingLocation(true); }; return !initialized ? ( <Loading /> ) : ( <div className="row"> <h3> Settings {updating && ( <div className="preloader-wrapper small active"> <div className="spinner-layer spinner-green-only"> <div className="circle-clipper left"> <div className="circle"></div> </div> <div className="gap-patch"> <div className="circle"></div> </div> <div className="circle-clipper right"> <div className="circle"></div> </div> </div> </div> )} </h3> <form className="col s12"> <div className="row"> <div className="col s12"> <p> The 8 digit Pin code required to register this device with Apple HomeKit. </p> </div> </div> <div className="row"> <div className="input-field col s12"> <label htmlFor="homekit-pin">HomeKit Pin</label> <input value={settings.homekitPin} readOnly={true} id="homekit-pin" type="text" /> </div> </div> <div className="row"> <div className="col s12"> <p> Automatically switch off the valve after a set duration of time. This setting does not affect scheduled waterings. </p> </div> </div> <div className="row"> <div className="col s12"> <label>Automatic valve shut-off</label> <select className="browser-default" value={shutoffDuration} onChange={handleChangeShutoffDuration}> <option value="0">Disabled</option> <option value="1">1 Minute</option> <option value="2">2 Minutes</option> <option value="5">5 Minutes</option> <option value="10">10 Minutes</option> <option value="15">15 Minutes</option> <option value="30">30 Minutes</option> <option value="60">60 Minutes</option> </select> </div> </div> <div className="row"> <div className="col s12"> <p> Check the weather in your location and don&apos;t start scheduled waterings if it currently raining. </p> </div> </div> <div className="row weather-row"> <div className="col s12"> <p> <label> <input type="checkbox" id="checkWeather" className="filled-in" onChange={handleCheckWeather} checked={checkWeather} /> <span>Check weather</span> </label> {checkWeather ? ( <a className="waves-effect weather-btn btn-flat right" onClick={handleRefreshLocation}> <i className="material-icons left">refresh</i> Refresh </a> ) : null} </p> </div> </div> <div className="row"> <div className="col s12"> {updatingLocation && ( <div className="progress"> <div className="indeterminate"></div> </div> )} {checkWeather && !updatingLocation && settings.location && ( <UserLocationComponent location={settings.location} /> )} </div> </div> {(locationError === 'denied' || locationError === 'notSupported') && ( <div className="row"> <div className="col s12"> <div className="card-panel green accent-4"> <span className="white-text"> {locationError === 'denied' ? 'To use the weather checking feature this application must be able to determine your current location. Ensure that you have given permission for this website to view your location information.' : 'Your browser doesn\t support geolocation. To use the weather checking feature this application must be able to determine your current location.'}{' '} </span> </div> </div> </div> )} </form> </div> ); } function useWeather(location) { const [weather, setWeather] = useState(null); useEffect(() => { let controller = null; if (location) { controller = new AbortController(); fetch( `/api/1/weather?lat=${location.latitude}&lon=${location.longitude}`, {signal: controller.signal}, ) .then(res => res.json()) .then(res => { if (res.success) { setWeather(res.weather); } }) .catch(err => { if (err.name !== 'AbortError') { setWeather(null); } }); } else { setWeather(null); } return () => { if (controller) { controller.abort(); } }; }, [location]); return weather; } const MapContainer = GoogleApiWrapper({ apiKey: keys.GOOGLE_MAPS_API_KEY, })(props => { return ( <Map google={props.google} zoom={15} containerStyle={{ position: 'relative', width: '100%', maxWidth: '100%', height: '100vh', }} scrollWheel={false} draggable={false} keyboardShortcuts={false} disableDoubleClickZoom={true} zoomControl={false} mapTypeControl={false} scaleControl={false} streetViewControl={false} panControl={false} rotateControl={false} fullscreenControl={false} initialCenter={props.center}> <Marker /> </Map> ); }); function UserLocationComponent({location}) { const weather = useWeather(location); return ( <div className="row"> <div className="col s12"> {weather ? ( <div className="weather-info"> <img src={weather.icon} /> <h5 className="right">{weather.description}</h5> </div> ) : null} <MapContainer center={{lat: location.latitude, lng: location.longitude}} /> </div> </div> ); }
pkg/interface/link/src/js/components/lib/links-tabbar.js
jfranklin9000/urbit
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { makeRoutePath } from '../../lib/util'; export class LinksTabBar extends Component { render() { let props = this.props; let memColor = '', setColor = ''; if (props.location.pathname.includes('/settings')) { memColor = 'gray3'; setColor = 'black white-d'; } else if (props.location.pathname.includes('/members')) { memColor = 'black white-d'; setColor = 'gray3'; } else { memColor = 'gray3'; setColor = 'gray3'; } let hidePopoutIcon = (props.popout) ? "dn-m dn-l dn-xl" : "dib-m dib-l dib-xl"; return ( <div className="dib flex-shrink-0 flex-grow-1"> {!!props.amOwner ? ( <div className={"dib pt2 f9 pl6 lh-solid"}> <Link className={"no-underline " + memColor} to={makeRoutePath(props.resourcePath, props.popout) + '/members'}> Members </Link> </div> ) : ( <div className="dib" style={{ width: 0 }}></div> )} <div className={"dib pt2 f9 pl6 pr6 lh-solid"}> <Link className={"no-underline " + setColor} to={makeRoutePath(props.resourcePath, props.popout) + '/settings'}> Settings </Link> </div> <a href={makeRoutePath(props.resourcePath, true, props.page)} target="_blank" className="dib fr pt2 pr1"> <img className={`flex-shrink-0 pr3 dn ` + hidePopoutIcon} src="/~link/img/popout.png" height="16" width="16"/> </a> </div> ); } } export default LinksTabBar