path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
packages/react/components/actions.js
iamxiaoma/Framework7
import React from 'react'; import Mixins from '../utils/mixins'; import Utils from '../utils/utils'; import __reactComponentWatch from '../runtime-helpers/react-component-watch.js'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Actions extends React.Component { constructor(props, context) { super(props, context); this.__reactRefs = {}; (() => { Utils.bindMethods(this, ['onOpen', 'onOpened', 'onClose', 'onClosed']); })(); } onOpen(instance) { this.dispatchEvent('actions:open actionsOpen', instance); } onOpened(instance) { this.dispatchEvent('actions:opened actionsOpened', instance); } onClose(instance) { this.dispatchEvent('actions:close actionsClose', instance); } onClosed(instance) { this.dispatchEvent('actions:closed actionsClosed', instance); } open(animate) { const self = this; if (!self.f7Actions) return undefined; return self.f7Actions.open(animate); } close(animate) { const self = this; if (!self.f7Actions) return undefined; return self.f7Actions.close(animate); } render() { const self = this; const props = self.props; const { className, id, style, grid } = props; const classes = Utils.classNames(className, 'actions-modal', { 'actions-grid': grid }, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, ref: __reactNode => { this.__reactRefs['el'] = __reactNode; }, className: classes }, this.slots['default']); } componentWillUnmount() { const self = this; if (self.f7Actions) self.f7Actions.destroy(); delete self.f7Actions; } componentDidMount() { const self = this; const el = self.refs.el; if (!el) return; const props = self.props; const { grid, target, convertToPopover, forceToPopover, opened, closeByBackdropClick, closeByOutsideClick, closeOnEscape, backdrop, backdropEl } = props; const actionsParams = { el, grid, on: { open: self.onOpen, opened: self.onOpened, close: self.onClose, closed: self.onClosed } }; if (target) actionsParams.targetEl = target; { if ('convertToPopover' in props) actionsParams.convertToPopover = convertToPopover; if ('forceToPopover' in props) actionsParams.forceToPopover = forceToPopover; if ('backdrop' in props) actionsParams.backdrop = backdrop; if ('backdropEl' in props) actionsParams.backdropEl = backdropEl; if ('closeByBackdropClick' in props) actionsParams.closeByBackdropClick = closeByBackdropClick; if ('closeByOutsideClick' in props) actionsParams.closeByOutsideClick = closeByOutsideClick; if ('closeOnEscape' in props) actionsParams.closeOnEscape = closeOnEscape; } self.$f7ready(() => { self.f7Actions = self.$f7.actions.create(actionsParams); if (opened) { self.f7Actions.open(false); } }); } get slots() { return __reactComponentSlots(this.props); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } get refs() { return this.__reactRefs; } set refs(refs) {} componentDidUpdate(prevProps, prevState) { __reactComponentWatch(this, 'props.opened', prevProps, prevState, opened => { const self = this; if (!self.f7Actions) return; if (opened) { self.f7Actions.open(); } else { self.f7Actions.close(); } }); } } __reactComponentSetProps(F7Actions, Object.assign({ id: [String, Number], className: String, style: Object, opened: Boolean, grid: Boolean, convertToPopover: Boolean, forceToPopover: Boolean, target: [String, Object], backdrop: Boolean, backdropEl: [String, Object, window.HTMLElement], closeByBackdropClick: Boolean, closeByOutsideClick: Boolean, closeOnEscape: Boolean }, Mixins.colorProps)); F7Actions.displayName = 'f7-actions'; export default F7Actions;
docs/src/app/components/pages/components/RaisedButton/ExampleIcon.js
pradel/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import {fullWhite} from 'material-ui/styles/colors'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import FontIcon from 'material-ui/FontIcon'; const style = { margin: 12, }; const RaisedButtonExampleIcon = () => ( <div> <RaisedButton icon={<ActionAndroid />} style={style} /> <RaisedButton backgroundColor="#a4c639" icon={<ActionAndroid color={fullWhite} />} style={style} /> <RaisedButton linkButton={true} href="https://github.com/callemall/material-ui" secondary={true} icon={<FontIcon className="muidocs-icon-custom-github" />} style={style} /> </div> ); export default RaisedButtonExampleIcon;
src/mongostick/frontend/src/screens/DatabaseOverview.js
RockingRolli/mongostick
import React from 'react' import { Col, Row, Table } from 'antd' import { connect } from 'react-redux' import { formatBytes } from '../lib/mongodb' import { Link } from 'react-router-dom' class Databases extends React.Component { getColumns = () => { return [ { title: 'Name', dataIndex: 'stats.db', key: 'db', render: text => <Link to={`/databases/overview/${text}`}>{text}</Link> }, { title: 'Collections', dataIndex: 'stats.collections', key: 'collections', sorter: (a, b) => a.stats.collections - b.stats.collections, }, { title: 'Storage Size', dataIndex: 'stats.storageSize', key: 'storageSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.storageSize - b.stats.storageSize, }, { title: 'Data Size', dataIndex: 'stats.dataSize', key: 'dataSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.dataSize - b.stats.dataSize, }, { title: 'AVG Obj Size', dataIndex: 'stats.avgObjSize', key: 'avgObjSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.avgObjSize - b.stats.avgObjSize, }, { title: 'objects', dataIndex: 'stats.objects', key: 'objects', render: text => text.toLocaleString(), sorter: (a, b) => a.stats.objects - b.stats.objects, }, { title: 'Indexes', dataIndex: 'stats.indexes', key: 'indexes', sorter: (a, b) => a.stats.indexes - b.stats.indexes, }, { title: 'Indexes', dataIndex: 'stats.indexSize', key: 'indexSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.indexSize - b.stats.indexSize, }, ] } getDataSource = () => { const { databases } = this.props return Object.keys(databases).map((index) => databases[index]) } render() { return ( <div> <Row style={{ background: '#fff' }}> <Col span={24} style={{ background: '#fff', padding: '10px' }}> <Table dataSource={this.getDataSource()} columns={this.getColumns()} size="small" rowKey={record => record.stats.db} /> </Col> </Row> </div> ) } } const mapStateToProps = store => { return { databases: store.databases, } } export default connect(mapStateToProps)(Databases)
app/addons/documents/routes-mango.js
apache/couchdb-fauxton
// Licensed 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 app from '../../app'; import FauxtonAPI from '../../core/api'; import Databases from '../databases/resources'; import DatabaseActions from '../databases/actions'; import Documents from './shared-resources'; import {MangoLayoutContainer} from './mangolayout'; const MangoIndexEditorAndQueryEditor = FauxtonAPI.RouteObject.extend({ selectedHeader: 'Databases', hideApiBar: true, hideNotificationCenter: true, routes: { 'database/:database/_partition/:partitionkey/_index': { route: 'createIndex', roles: ['fx_loggedIn'] }, 'database/:database/_index': { route: 'createIndexNoPartition', roles: ['fx_loggedIn'] }, 'database/:database/_partition/:partitionkey/_find': { route: 'findUsingIndex', roles: ['fx_loggedIn'] }, 'database/:database/_find': { route: 'findUsingIndexNoPartition', roles: ['fx_loggedIn'] }, }, initialize: function (route, options) { var databaseName = options[0]; this.databaseName = databaseName; this.database = new Databases.Model({id: databaseName}); }, findUsingIndexNoPartition: function (database) { return this.findUsingIndex(database, ''); }, findUsingIndex: function (database, partitionKey) { const encodedPartitionKey = partitionKey ? encodeURIComponent(partitionKey) : ''; const url = FauxtonAPI.urls( 'allDocs', 'app', encodeURIComponent(this.databaseName), encodedPartitionKey ); const partKeyUrlComponent = partitionKey ? `/${encodedPartitionKey}` : ''; const fetchUrl = '/' + encodeURIComponent(this.databaseName) + partKeyUrlComponent + '/_find'; const crumbs = [ {name: database, link: url}, {name: app.i18n.en_US['mango-title-editor']} ]; const endpoint = FauxtonAPI.urls('mango', 'query-apiurl', encodeURIComponent(this.databaseName), encodedPartitionKey); const navigateToPartitionedView = (partKey) => { const baseUrl = FauxtonAPI.urls('mango', 'query-app', encodeURIComponent(database), encodeURIComponent(partKey)); FauxtonAPI.navigate('#/' + baseUrl); }; const navigateToGlobalView = () => { const baseUrl = FauxtonAPI.urls('mango', 'query-app', encodeURIComponent(database)); FauxtonAPI.navigate('#/' + baseUrl); }; return <MangoLayoutContainer database={database} crumbs={crumbs} docURL={FauxtonAPI.constants.DOC_URLS.MANGO_SEARCH} endpoint={endpoint} edit={false} databaseName={this.databaseName} fetchUrl={fetchUrl} partitionKey={partitionKey} onPartitionKeySelected={navigateToPartitionedView} onGlobalModeSelected={navigateToGlobalView} globalMode={partitionKey === ''} />; }, createIndexNoPartition: function (database) { return this.createIndex(database, ''); }, createIndex: function (database, partitionKey) { const designDocs = new Documents.AllDocs(null, { database: this.database, paging: { pageSize: 500 }, params: { startkey: '_design/', endkey: '_design0', include_docs: true, limit: 500 } }); const encodedPartitionKey = partitionKey ? encodeURIComponent(partitionKey) : ''; const url = FauxtonAPI.urls( 'allDocs', 'app', encodeURIComponent(this.databaseName), encodedPartitionKey ); const endpoint = FauxtonAPI.urls('mango', 'index-apiurl', encodeURIComponent(this.databaseName), encodedPartitionKey); const crumbs = [ {name: database, link: url}, {name: app.i18n.en_US['mango-indexeditor-title']} ]; DatabaseActions.fetchSelectedDatabaseInfo(database); return <MangoLayoutContainer showIncludeAllDocs={false} crumbs={crumbs} docURL={FauxtonAPI.constants.DOC_URLS.MANGO_INDEX} endpoint={endpoint} edit={true} designDocs={designDocs} databaseName={this.databaseName} partitionKey={partitionKey} />; } }); export default { MangoIndexEditorAndQueryEditor: MangoIndexEditorAndQueryEditor };
src/Row.js
westonplatter/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
src/components/Layer/Layer.js
nambawan/g-old
// from : https://github.com/grommet/grommet/blob/master/src/js/components/Layer.js import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import withStyles from 'isomorphic-style-loader/withStyles'; import StyleContext from 'isomorphic-style-loader/StyleContext'; import { Provider as ReduxProvider } from 'react-redux'; import { IntlProvider } from 'react-intl'; import cn from 'classnames'; import LayerContents from '../LayerContents'; import s from './Layer.css'; class Layer extends React.Component { static propTypes = { onClose: PropTypes.func.isRequired, id: PropTypes.string, hidden: PropTypes.bool, fill: PropTypes.bool, }; static defaultProps = { id: null, hidden: false, fill: false, }; componentDidMount() { this.originalFocusedElement = document.activeElement; this.originalScrollPosition = { top: window.pageYOffset, left: window.pageXOffset, }; this.addLayer(); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { const { hidden } = this.props; if (this.originalFocusedElement && !hidden) { if (this.originalFocusedElement.focus) { // wait for the fixed positioning to come back to normal // see layer styling for reference setTimeout(() => { this.originalFocusedElement.focus(); window.scrollTo( this.originalScrollPosition.left, this.originalScrollPosition.top, ); }, 0); } else if ( this.originalFocusedElement.parentNode && this.originalFocusedElement.parentNode.focus ) { // required for IE11 and Edge this.originalFocusedElement.parentNode.focus(); window.scrollTo( this.originalScrollPosition.left, this.originalScrollPosition.top, ); } } this.removeLayer(); } addLayer() { const { id } = this.props; const element = document.createElement('div'); if (id) { element.id = id; } element.className = s.layer; const appElements = document.querySelectorAll('#app'); let beforeElement; if (appElements.length > 0) { [beforeElement] = appElements; } else { beforeElement = document.body.firstChild; } if (beforeElement) { this.element = beforeElement.parentNode.insertBefore( element, beforeElement, ); } } removeLayer() { this.element.removeEventListener('animationend', this.onAnimationEnd); ReactDOM.unmountComponentAtNode(this.element); this.element.parentNode.removeChild(this.element); this.element = undefined; this.handleAriaHidden(true); } handleAriaHidden(hideOverlay) { setTimeout(() => { const hidden = hideOverlay || false; const apps = document.querySelectorAll('#app'); const visibleLayers = document.querySelectorAll( `.${s.layer}:not(.${s.hidden})`, ); if (apps) { /* eslint-disable no-param-reassign */ Array.prototype.slice.call(apps).forEach(app => { if (hidden && visibleLayers.length === 0) { // make sure to only show grommet apps if there is no other layer app.setAttribute('aria-hidden', false); app.classList.remove(s.hidden); // scroll body content to the original position app.style.top = `-${this.originalScrollPosition.top}px`; app.style.left = `-${this.originalScrollPosition.left}px`; } else { app.setAttribute('aria-hidden', true); app.classList.add(s.hidden); // this must be null to work app.style.top = null; app.style.left = null; // app.style.top = `-${this.originalScrollPosition.top}px`; // app.style.left = `-${this.originalScrollPosition.left}px`; } }, this); /* eslint-enable no-param-reassign */ } }, 0); } renderLayer() { if (this.element) { this.element.className = s.layer; const { insertCss, store, intl } = this.context; const { onClose, fill } = this.props; const contents = ( <StyleContext.Provider value={{ insertCss }}> <ReduxProvider store={store}> <LayerContents {...this.props} className={cn(s.container, fill && s.fill)} intl={intl} onClose={onClose} /> </ReduxProvider> </StyleContext.Provider> ); ReactDOM.render(contents, this.element, () => { const { hidden } = this.props; if (hidden) { this.handleAriaHidden(true); } else { this.handleAriaHidden(false); } }); } } render() { return null; } } Layer.contextTypes = { insertCss: PropTypes.func.isRequired, intl: IntlProvider.childContextTypes.intl, locale: PropTypes.string, store: PropTypes.shape({ subscribe: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, getState: PropTypes.func.isRequired, }), }; export default withStyles(s)(Layer);
src/components/AppRoutes.js
trda/seslisozluk-simple-ui-project
import React from 'react'; import { Router, browserHistory } from 'react-router'; import routes from '../routes'; export default class AppRoutes extends React.Component { render() { return ( <Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/> ); } }
src/navigators/ReduxNavigation.js
jfilter/frag-den-staat-app
import { BackHandler, Linking, Platform } from 'react-native'; import { NavigationActions } from 'react-navigation'; import { connect } from 'react-redux'; import { createReactNavigationReduxMiddleware, createReduxContainer, } from 'react-navigation-redux-helpers'; import React from 'react'; import BackgroundFetch from 'react-native-background-fetch'; import { GET_REQUEST_ID_HOSTNAME, OAUTH_REDIRECT_URI, ORIGIN, FDROID, } from '../globals'; import I18n from '../i18n'; import { errorAlert, successAlert } from '../utils/dropDownAlert'; import { getUserInformation, receiveOauthRedirectError, oauthUpdateToken, } from '../actions/authentication'; import { loadToken, saveToken } from '../utils/secureStorage'; import AppNavigator from './AppNavigator'; import { fetchInitialToken } from '../utils/oauth'; import { searchUpdateAlertMatchesAction } from '../actions/search'; import { localNotif, setUp } from '../utils/notifications'; // Note: createReactNavigationReduxMiddleware must be run before createReduxBoundAddListener const navMiddleware = createReactNavigationReduxMiddleware( state => state.navigation ); const App = createReduxContainer(AppNavigator, 'root'); class ReduxNavigation extends React.Component { async componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.onBackPress); // universal linking, when app was closed // (and all android calls) Linking.getInitialURL().then(url => { if (url !== null) this.urlRouter(url); }); // deep linking (and all ios) Linking.addEventListener('url', this.handleUrlEvent); const token = await loadToken(); if (token !== null && Object.keys(token).length !== 0) { await this.props.updateToken(token); this.props.getUserInformation(); } const nav = id => { this.props.dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); }; if (!FDROID) setUp(nav); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.onBackPress); Linking.removeEventListener('url', this.handleUrlEvent); } handleUrlEvent = event => this.urlRouter(event.url); onBackPress = () => { const { dispatch, navigation } = this.props; // close the app when pressing back button on initial screen // because everything is wrapped in a Drawer, we need to go over this first // navigator if ( navigation.routes[0].index === 0 && navigation.routes[0].routes[0].index === 0 ) { return false; } dispatch(NavigationActions.back()); return true; }; urlRouter = url => { if (url.startsWith(OAUTH_REDIRECT_URI)) { this.handleLoginRedirect(url); } else { this.navigate(url); } }; handleLoginRedirect = url => { // 1. go back to page where clicked login (on iOS) if (Platform.OS === 'ios') this.props.dispatch(NavigationActions.back()); fetchInitialToken(url) .then(token => { // 2. show message on top successAlert .getDropDown() .alertWithType( 'success', I18n.t('loginSuccess'), I18n.t('loginSuccessMessage') ); // 3. update token in redux store this.props.updateToken(token); // 4. fetch information about user from server this.props.getUserInformation(); // 5. persists token saveToken(token); }) .catch(error => errorAlert.getDropDown().alertWithType('error', 'Error', error.message) ); }; navigate = async url => { const { dispatch } = this.props; // difference for deep linking and unviversal linking let route; if (url.startsWith(ORIGIN)) { route = url.replace(`${ORIGIN}/`, ''); } else { route = url.replace(/.*?:\/\//g, ''); } const routeParts = route .split('#')[0] .split('/') .filter(x => x.length > 0); const routeName = routeParts[0]; // a for anfrage if (routeName === 'a') { // short url with the request id const id = route.match(/\/([^\/]+)\/?$/)[1]; dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); } if (routeName === 'anfrage' && routeParts.length !== 5) { // open request (defined by slug) in app // TODO: currently the same request is fetched twice const slug = routeParts.reverse()[0]; const res = await fetch(`${ORIGIN}/api/v1/request/?slug=${slug}`); const id = (await res.json()).objects[0].id; dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); } if (routeName === 'anfrage' && routeParts.length === 5) { // open an attachment in app const messageId = routeParts[2]; const res = await fetch( `https://fragdenstaat.de/api/v1/message/${messageId}` ); const message = await res.json(); const id = message.request.split('/').reverse()[1]; message.attachments.forEach(x => { if (x.name.toLowerCase() === routeParts[4].toLowerCase()) { const action1 = NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }); // first to request, then to attachment dispatch(action1); const action2 = NavigationActions.navigate({ routeName: 'FoiRequestsPdfViewer', params: { url: x.site_url, fileUrl: x.file_url }, }); dispatch(action2); } }); } }; render() { const { pastAlertMatches, alerts, hasNotificationPermission, searchUpdateAlertMatches, } = this.props; // background stuff if (hasNotificationPermission && alerts.length) { BackgroundFetch.configure( { minimumFetchInterval: 60, // <-- minutes (15 is minimum allowed) stopOnTerminate: false, // <-- Android-only, startOnBoot: true, // <-- Android-only, enableHeadless: true, }, async () => { console.log('[js] Received background-fetch event'); const data = await Promise.all( alerts.map(async x => { const response = await fetch( `https://fragdenstaat-alerts.app.vis.one/min/${x}` ); console.log(response); const responseJson = await response.json(); return { terms: x, res: responseJson }; }) ); console.log(pastAlertMatches); data.forEach(x => { x.res.forEach(({ id }) => { // only works on request ids and not message ids. if ( pastAlertMatches[x.terms] === undefined || pastAlertMatches[x.terms].indexOf(id) < 0 ) { localNotif(`Neuer Treffer für "${x.terms}"`, id); } searchUpdateAlertMatches(x.terms, id); }); }); console.log(data); BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA); }, error => { console.log('[js] RNBackgroundFetch failed to start', error); } ); // Optional: Query the authorization status. BackgroundFetch.status(status => { switch (status) { case BackgroundFetch.STATUS_RESTRICTED: console.log('BackgroundFetch restricted'); break; case BackgroundFetch.STATUS_DENIED: console.log('BackgroundFetch denied'); break; case BackgroundFetch.STATUS_AVAILABLE: console.log('BackgroundFetch is enabled'); break; default: console.log('default'); } }); } const { navigation, dispatch } = this.props; return <App state={navigation} dispatch={dispatch} />; } } const mapStateToProps = state => ({ navigation: state.navigation, alerts: state.search.alerts, pastAlertMatches: state.search.pastAlertMatches, hasNotificationPermission: state.settings.hasNotificationPermission, }); const mapDispatchToProps = dispatch => ({ updateToken: token => dispatch(oauthUpdateToken(token)), redirectError: errorMessage => dispatch(receiveOauthRedirectError(errorMessage)), getUserInformation: () => dispatch(getUserInformation()), searchUpdateAlertMatches: (term, id) => dispatch(searchUpdateAlertMatchesAction(term, id)), dispatch, }); const AppWithNavigationState = connect( mapStateToProps, mapDispatchToProps )(ReduxNavigation); export { AppWithNavigationState, navMiddleware };
node_modules/react-bootstrap/es/Popover.js
darklilium/Factigis_2
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 isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * Title content */ title: React.PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: 'arrow', style: arrowStyle }), title && React.createElement( 'h3', { className: prefix(bsProps, 'title') }, title ), React.createElement( 'div', { className: prefix(bsProps, 'content') }, children ) ); }; return Popover; }(React.Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);
admin/client/App/components/Navigation/Mobile/SectionItem.js
benkroeger/keystone
/** * A mobile section */ import React from 'react'; import MobileListItem from './ListItem'; import { Link } from 'react-router'; const MobileSectionItem = React.createClass({ displayName: 'MobileSectionItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, currentListKey: React.PropTypes.string, href: React.PropTypes.string.isRequired, lists: React.PropTypes.array, }, // Render the lists renderLists () { if (!this.props.lists || this.props.lists.length <= 1) return null; const navLists = this.props.lists.map((item) => { // Get the link and the classname const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`; const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item'; return ( <MobileListItem key={item.path} href={href} className={className} onClick={this.props.onClick}> {item.label} </MobileListItem> ); }); return ( <div className="MobileNavigation__lists"> {navLists} </div> ); }, render () { return ( <div className={this.props.className}> <Link className="MobileNavigation__section-item" to={this.props.href} tabIndex="-1" onClick={this.props.onClick} > {this.props.children} </Link> {this.renderLists()} </div> ); }, }); module.exports = MobileSectionItem;
client/components/ui/label.js
bnjbvr/kresus
import React from 'react'; import PropTypes from 'prop-types'; import { translate as $t } from '../../helpers'; class LabelComponent extends React.Component { state = { value: null }; handleChange = e => { this.setState({ value: e.target.value }); }; handleFocus = event => { // Set the caret at the end of the text. let end = (event.target.value || '').length; event.target.selectionStart = end; event.target.selectionEnd = end; }; handleKeyUp = event => { if (event.key === 'Enter') { event.target.blur(); } else if (event.key === 'Escape') { let { target } = event; this.setState( { value: null }, () => target.blur() ); } }; handleBlur = () => { if (this.state.value === null) { return; } let label = this.state.value.trim(); // If the custom label is equal to the label, remove the custom label. if (label === this.props.getLabel()) { label = ''; } let { customLabel } = this.props.item; if (label !== customLabel && (label || customLabel)) { this.props.setCustomLabel(label); } this.setState({ value: null }); }; getCustomLabel() { let { customLabel } = this.props.item; if (customLabel === null || !customLabel.trim().length) { return ''; } return customLabel; } getDefaultValue() { let label = this.getCustomLabel(); if (!label && this.props.displayLabelIfNoCustom) { label = this.props.getLabel(); } return label; } render() { let label = this.state.value !== null ? this.state.value : this.getDefaultValue(); let forceEditMode = this.props.forceEditMode ? 'force-edit-mode' : ''; return ( <div className={`label-component-container ${forceEditMode}`}> <span>{label}</span> <input className="form-element-block" type="text" value={label} onChange={this.handleChange} onFocus={this.handleFocus} onKeyUp={this.handleKeyUp} onBlur={this.handleBlur} placeholder={$t('client.general.add_custom_label')} /> </div> ); } } LabelComponent.propTypes /* remove-proptypes */ = { // The item from which to get the label. item: PropTypes.object.isRequired, // Whether to display the label if there is no custom label. displayLabelIfNoCustom: PropTypes.bool, // A function to set the custom label when modified. setCustomLabel: PropTypes.func.isRequired, // Force the display of the input even on small screens forceEditMode: PropTypes.bool, // A function that returns the displayed label. getLabel: PropTypes.func.isRequired }; LabelComponent.defaultProps = { displayLabelIfNoCustom: true, forceEditMode: false }; export default LabelComponent;
src/svg-icons/av/explicit.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvExplicit = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"/> </SvgIcon> ); AvExplicit = pure(AvExplicit); AvExplicit.displayName = 'AvExplicit'; AvExplicit.muiName = 'SvgIcon'; export default AvExplicit;
src/components/ExplanationSelection.js
quintel/etmobile
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import offSvg from '../images/explanations/off.svg'; import onSvg from '../images/explanations/on.svg'; import offSelectedSvg from '../images/explanations/off-selected.svg'; import onSelectedSvg from '../images/explanations/on-selected.svg'; class ExplanationSelection extends React.Component { constructor() { super(); this.state = { selected: null }; this.choose = this.choose.bind(this); } selectedValue() { if (this.state.selected !== null) { return this.state.selected; } return this.props.selected; } choose(event) { const showExplanations = event.target.value === 'yes'; this.props.onChange(showExplanations); this.setState({ selected: showExplanations }); } render() { const selected = this.selectedValue(); const yesClasses = classNames({ selected: selected === true }); const noClasses = classNames({ selected: selected !== true }); let yesImg = onSvg; let noImg = offSelectedSvg; if (selected) { yesImg = onSelectedSvg; noImg = offSvg; } return ( <div className="app-option explanation-selection"> <span className="prompt"> <FormattedMessage id="app.showExplanations" /> </span> <ul> <li className={yesClasses}> <button onClick={this.choose} value="yes" className="yes" style={{ backgroundImage: `url(${yesImg})` }} > <FormattedMessage id="app.yes" /> </button> </li> <li className={noClasses}> <button onClick={this.choose} value="no" className="no" style={{ backgroundImage: `url(${noImg})` }} > <FormattedMessage id="app.no" /> </button> </li> </ul> </div> ); } } ExplanationSelection.propTypes = { selected: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired }; export default ExplanationSelection;
test/OverlayDeprecationSpec.js
sheep902/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Position from '../src/Position'; import Transition from '../src/Transition'; import Portal from '../src/Portal'; import { shouldWarn } from './helpers'; describe('Components moved to react-overlays', () => { it('should warn about Position', () => { ReactTestUtils.renderIntoDocument(<Position><div/></Position>); shouldWarn(/Position component is deprecated/); }); it('should warn about Transition', () => { ReactTestUtils.renderIntoDocument(<Transition><div/></Transition>); shouldWarn(/Transition component is deprecated/); }); it('should warn about Portal', () => { ReactTestUtils.renderIntoDocument(<Portal><div/></Portal>); shouldWarn(/Portal component is deprecated/); }); });
src/views/Components/NavigationTree.js
pranked/cs2-web
/** * Created by dom on 9/15/16. */ import React from 'react'; import { Link } from 'react-router'; const NavigationTree = React.createClass({ propTypes: { items: React.PropTypes.array.isRequired }, render() { const flatten = (item) => { return ( <li key={item.name}> <Link to={item.url} activeClassName="selected">{item.name}</Link> </li> ); }; return ( <ul className="nav nav-pills"> {this.props.items.map(flatten)} </ul> ); } }); export default NavigationTree;
app/javascript/mastodon/features/compose/components/warning.js
SerCom-KC/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; export default class Warning extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, }; render () { const { message } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='compose-form__warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> {message} </div> )} </Motion> ); } }
stalk-messenger/app/components/tabs/chats/index.js
JohnKim/stalk.messenger
/** * * @flow */ 'use strict'; import React, { Component } from 'react'; import { View, StyleSheet, Text, TouchableOpacity, } from 'react-native'; import ChatCell from './ChatCell'; import { loadChats, leaveChat } from 's5-action'; import { S5Header, S5SwipeListView } from 's5-components'; import { connect } from 'react-redux'; import ActionButton from 'react-native-action-button'; class ChatsScreen extends Component { static propTypes = { chats: React.PropTypes.object.isRequired, messages: React.PropTypes.object.isRequired, user: React.PropTypes.object, navigator: React.PropTypes.object.isRequired, leaveChat: React.PropTypes.func.isRequired, }; state = { listViewData: [] }; constructor(props) { super(props); this._openAddUserView = this._openAddUserView.bind(this); } componentDidMount(){ this.setState({ listViewData: this.props.chats.list }); } componentWillReceiveProps (nextProps) { if (nextProps.chats.list !== this.props.chats.list) { this.setState({ listViewData: nextProps.chats.list }); } } _onRowPress(chat) { this.props.navigator.push({ chatView: true, chat, }); } _deleteRow(secId, rowId, rowMap, chatId) { rowMap[`${secId}${rowId}`].closeRow(); this.props.leaveChat(chatId).then(() => { // TODO do something after deleting. }); } _openAddUserView() { this.props.navigator.push({selectUserView: 1}); } _renderRow(chat) { return ( <ChatCell key={chat.id} chat={chat} message={this.props.messages.latest[chat.channelId]} onPress={() => this._onRowPress(chat)} /> ) } render() { return ( <View style={styles.container}> <S5Header title="Chats" style={{backgroundColor: '#224488'}} /> <S5SwipeListView ref="listView" data={this.state.listViewData} renderRow={ (data) => this._renderRow(data) } renderHiddenRow={ (data, secId, rowId, rowMap) => ( <View style={styles.rowBack}> <View style={[styles.backRightBtn, styles.backRightBtnLeft]}> <Text style={styles.backTextWhite}>Mark as Read</Text> </View> <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={ () => this._deleteRow(secId, rowId, rowMap, data.id) }> <Text style={styles.backTextWhite}>Leave</Text> </TouchableOpacity> </View> ) } enableEmptySections={true} rightOpenValue={-150} removeClippedSubviews={false} /> <ActionButton buttonColor="rgba(231,76,60,1)" onPress={this._openAddUserView} /> </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', flex: 1 }, standalone: { marginTop: 30, marginBottom: 30, }, standaloneRowFront: { alignItems: 'center', backgroundColor: '#CCC', justifyContent: 'center', height: 50, }, standaloneRowBack: { alignItems: 'center', backgroundColor: '#8BC645', flex: 1, flexDirection: 'row', justifyContent: 'space-between', padding: 15 }, backTextWhite: { color: '#FFF' }, rowFront: { alignItems: 'center', backgroundColor: '#CCC', borderBottomColor: 'black', borderBottomWidth: 1, justifyContent: 'center', height: 50, }, rowBack: { alignItems: 'center', backgroundColor: '#DDD', flex: 1, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 15, }, backRightBtn: { alignItems: 'center', bottom: 0, justifyContent: 'center', position: 'absolute', top: 0, width: 75 }, backRightBtnLeft: { backgroundColor: 'blue', right: 75 }, backRightBtnRight: { backgroundColor: 'red', right: 0 }, controls: { alignItems: 'center', marginBottom: 30 }, switchContainer: { flexDirection: 'row', justifyContent: 'center', marginBottom: 5 }, switch: { alignItems: 'center', borderWidth: 1, borderColor: 'black', paddingVertical: 10, width: 100, } }); function select(store) { return { user: store.user, chats: store.chats, messages: store.messages, }; } function actions(dispatch) { return { loadChats: () => dispatch(loadChats()), // @ TODO not used !! leaveChat: (chatId) => dispatch(leaveChat(chatId)), }; } module.exports = connect(select, actions)(ChatsScreen);
lib/editor/components/question_editors/parts/BulkAddItemsEditorPart.js
jirokun/survey-designer-js
/* eslint-env browser */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import S from 'string'; import * as EditorActions from '../../../actions'; class BulkAddItemsEditorPart extends Component { constructor(props) { super(props); this.state = { inputText: '' }; } /** 一括追加を実行する */ handleBulkAddItems() { const { bulkAddItems, bulkAddSubItems, handleExecute, page, question, isTargetSubItems } = this.props; if (isTargetSubItems) { bulkAddSubItems(page.getId(), question.getId(), this.state.inputText); } else { bulkAddItems(page.getId(), question.getId(), this.state.inputText); } handleExecute(); } /** タブを改行に置換する */ handleClickConvertTabToLineBreak() { const replacedStr = this.state.inputText.replace(/\t/g, '\n'); this.setState({ inputText: replacedStr }); } /** 空行を削除する */ handleClickDeleteEmptyLines() { const lines = this.state.inputText.split(/\n/); const replacedStr = lines.filter(line => !S(line).isEmpty()).join('\n'); this.setState({ inputText: replacedStr }); } render() { return ( <div> <div>1行に1項目を指定してください。HTMLも指定可能です。</div> <div><textarea className="item-bulk-add-editor" value={this.state.inputText} onChange={e => this.setState({ inputText: e.target.value })} /></div> <div className="clearfix"> <div className="btn-group pull-right"> <button type="button" className="btn btn-info" onClick={() => this.handleClickConvertTabToLineBreak()}>タブを改行に変換</button> <button type="button" className="btn btn-info" onClick={() => this.handleClickDeleteEmptyLines()}>空行の削除</button> <button type="button" className="btn btn-primary" onClick={() => this.handleBulkAddItems()}>一括追加</button> </div> </div> </div> ); } } const stateToProps = state => ({ survey: state.getSurvey(), runtime: state.getRuntime(), view: state.getViewSetting(), options: state.getOptions(), }); const actionsToProps = dispatch => ({ bulkAddItems: (pageId, questionId, text) => dispatch(EditorActions.bulkAddItems(pageId, questionId, text)), bulkAddSubItems: (pageId, questionId, text) => dispatch(EditorActions.bulkAddSubItems(pageId, questionId, text)), }); export default connect( stateToProps, actionsToProps, )(BulkAddItemsEditorPart);
test/integration/image-component/default/pages/missing-src.js
zeit/next.js
import React from 'react' import Image from 'next/image' const Page = () => { return ( <div> <Image width={200}></Image> </div> ) } export default Page
src/js/components/icons/base/ShieldSecurity.js
odedre/grommet-final
/** * @description ShieldSecurity SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M12,22 C12,22 2.99999999,18 3,11 L3,5 L12,2 L21,5 C21,5 21,11 21,11 C21,18 12,22 12,22 Z M12,14 C13.6568542,14 15,12.6568542 15,11 C15,9.34314575 13.6568542,8 12,8 C10.3431458,8 9,9.34314575 9,11 C9,12.6568542 10.3431458,14 12,14 Z M12,8 L12,5 M12,17 L12,14 M6,11 L9,11 M15,11 L18,11 M8,7 L10,9 M14,13 L16,15 M16,7 L14,9 M10,13 L8,15"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-shield-security`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'shield-security'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,22 C12,22 2.99999999,18 3,11 L3,5 L12,2 L21,5 C21,5 21,11 21,11 C21,18 12,22 12,22 Z M12,14 C13.6568542,14 15,12.6568542 15,11 C15,9.34314575 13.6568542,8 12,8 C10.3431458,8 9,9.34314575 9,11 C9,12.6568542 10.3431458,14 12,14 Z M12,8 L12,5 M12,17 L12,14 M6,11 L9,11 M15,11 L18,11 M8,7 L10,9 M14,13 L16,15 M16,7 L14,9 M10,13 L8,15"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'ShieldSecurity'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
actor-apps/app-web/src/app/components/common/Fold.React.js
luwei2012/actor-platform
/* eslint-disable */ import React from 'react'; import classnames from 'classnames'; class Fold extends React.Component { static PropTypes = { icon: React.PropTypes.string, iconClassName: React.PropTypes.string, title: React.PropTypes.string.isRequired }; state = { isOpen: false }; constructor(props) { super(props); } render() { const { icon, iconClassName, title, iconElement } = this.props; const titleIconClassName = classnames('material-icons icon', iconClassName); const className = classnames({ 'fold': true, 'fold--open': this.state.isOpen }); let foldIcon; if (icon) { foldIcon = <i className={titleIconClassName}>{icon}</i>; } if (iconElement) { foldIcon = iconElement; } return ( <div className={className}> <div className="fold__title" onClick={this.onClick}> {foldIcon} {title} <i className="fold__indicator material-icons pull-right">arrow_drop_down</i> </div> <div className="fold__content"> {this.props.children} </div> </div> ); } onClick = () => { this.setState({isOpen: !this.state.isOpen}); }; } export default Fold;
src/propTypes/TextStylePropTypes.js
lelandrichardson/react-native-mock
/** * https://github.com/facebook/react-native/blob/master/Libraries/Text/TextStylePropTypes.js */ import React from 'react'; import ColorPropType from './ColorPropType'; import ViewStylePropTypes from './ViewStylePropTypes'; const { PropTypes } = React; // TODO: use spread instead of Object.assign/create after #6560135 is fixed const TextStylePropTypes = Object.assign(Object.create(ViewStylePropTypes), { color: ColorPropType, fontFamily: PropTypes.string, fontSize: PropTypes.number, fontStyle: PropTypes.oneOf(['normal', 'italic']), /** * Specifies font weight. The values 'normal' and 'bold' are supported for * most fonts. Not all fonts have a variant for each of the numeric values, * in that case the closest one is chosen. */ fontWeight: PropTypes.oneOf( ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'] ), textShadowOffset: PropTypes.shape( { width: PropTypes.number, height: PropTypes.number } ), textShadowRadius: PropTypes.number, textShadowColor: ColorPropType, /** * @platform ios */ letterSpacing: PropTypes.number, lineHeight: PropTypes.number, /** * Specifies text alignment. The value 'justify' is only supported on iOS. */ textAlign: PropTypes.oneOf( ['auto', 'left', 'right', 'center', 'justify'] ), /** * @platform android */ textAlignVertical: PropTypes.oneOf( ['auto', 'top', 'bottom', 'center'] ), /** * @platform ios */ textDecorationLine: PropTypes.oneOf( ['none', 'underline', 'line-through', 'underline line-through'] ), /** * @platform ios */ textDecorationStyle: PropTypes.oneOf( ['solid', 'double', 'dotted', 'dashed'] ), /** * @platform ios */ textDecorationColor: ColorPropType, /** * @platform ios */ writingDirection: PropTypes.oneOf( ['auto', 'ltr', 'rtl'] ), }); module.exports = TextStylePropTypes;
components/DefaultHTMLLayout.js
slidewiki/slidewiki-platform
import React from 'react'; import ApplicationStore from '../stores/ApplicationStore'; //import ga from '../plugins/googleAnalytics/ga'; import { Microservices } from '../configs/microservices'; let hook = require('css-modules-require-hook'); hook({ generateScopedName: '[hash:base64:5]', }); class DefaultHTMLLayout extends React.Component { render() { let user = this.props.context.getUser(); let pageDescription = this.props.context.getStore(ApplicationStore).getPageDescription(); return ( <html lang={ this.props.lang }> <head> <meta charSet="utf-8" /> <title>{this.props.context.getStore(ApplicationStore).getPageTitle()}</title> <meta name="thumbnail" content={this.props.context.getStore(ApplicationStore).getPageThumbnail()} /> <meta property="og:title" content={this.props.context.getStore(ApplicationStore).getPageTitle()} /> <meta property="og:type" content="website" /> <meta property="og:image" content={this.props.context.getStore(ApplicationStore).getPageThumbnail()} /> {pageDescription ? <meta property="og:description" content={pageDescription} /> : ''} <meta name="viewport" content="width=device-width" /> <link href="/assets/custom-semantic-ui/dist/semantic.min.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/custom.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/home-custom.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/home-layout.css" rel="stylesheet" type="text/css" /> <link href="/sweetalert2/dist/sweetalert2.min.css" rel="stylesheet" type="text/css" /> <link href="/custom_modules/reveal.js/css/reveal.css" rel="stylesheet" type="text/css" /> <link href="/custom_modules/reveal.js/lib/css/zenburn.css" rel="stylesheet" type="text/css" /> <link href="/glidejs/dist/css/glide.core.min.css" rel="stylesheet" type="text/css" /> <link href="/glidejs/dist/css/glide.theme.min.css" rel="stylesheet" type="text/css" /> { user ? <link href="/jquery-ui-dist/jquery-ui.min.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="jquery-ui" /> } { user ? <link href="/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="font-awesome" /> } { user ? <link href="/jquery-contextmenu/dist/jquery.contextMenu.min.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="jquery.contextMenu" /> } {/* Vendors css bundle */ this.props.addAssets ? <link href="/public/css/vendor.bundle.css" rel="stylesheet" type="text/css" />: <style></style> } {/*<link href="/custom_modules/reveal.js/css/print/pdf.css" rel="stylesheet" type="text/css" />*/} {/* we add this config option for mathjax so we can better control when the typesetting will occur */} <script type="text/x-mathjax-config" dangerouslySetInnerHTML={{__html:'MathJax.Hub.Config({skipStartupTypeset: true});'}}></script> <script src="/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML" defer></script> </head> <body> <div id="app" aria-hidden="false" dangerouslySetInnerHTML={{__html: this.props.markup}}></div> {/* Following are added only to support IE browser */} <script src="/es5-shim/es5-shim.min.js"></script> <script src="/es5-shim/es5-sham.min.js"></script> <script src="/json3/lib/json3.min.js"></script> <script src="/es6-shim/es6-shim.min.js"></script> <script src="/es6-shim/es6-sham.min.js"></script> {/* Above are added only to support IE browser */} <script dangerouslySetInnerHTML={{__html: this.props.state}}></script> <script src="/jquery/dist/jquery.min.js"></script> {/* TODO: load specific parts of jquery UI for performance */} { user ? <script src="/jquery-ui-dist/jquery-ui.min.js" defer></script> : '' } <script src="/glidejs/dist/glide.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/progress.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/accordion.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/transition.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/popup.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/dropdown.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/checkbox.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/dimmer.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/modal.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/form.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/tab.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/search.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/api.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/sidebar.min.js" defer></script> {/* All external vendors bundle*/ this.props.addAssets ? <script src={'/public/js/vendor.bundle.js'} defer></script> : '' } { user ? <script src="/ckeditor/ckeditor.js" defer></script> : '' } <script src={ Microservices.webrtc.uri + '/socket.io/socket.io.js' }></script> <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> <script src="/headjs/dist/1.0.0/head.min.js"></script> {/* Adding for dependency loading with reveal.js*/} <script src="/custom_modules/reveal.js/js/reveal.js" defer></script> {/* Main app settings */} <script src="/public/js/settings.js" defer></script> {/* Main app bundle */} <script src={'/public/js/' + this.props.clientFile} defer></script> {/*<script type="text/javascript" src="https://slidewiki.atlassian.net/s/5e2fc7b2a8ba40bc00a09a4f81a301c8-T/rfg5q6/100012/c/1000.0.9/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?locale=en-UK&collectorId=241c9e18" defer></script>*/} <script src="/sweetalert2/dist/sweetalert2.min.js" defer></script> { user ? <script src="/jquery-contextmenu/dist/jquery.contextMenu.min.js" defer></script> : '' } {/*<script src="/custom_modules/simple-draggable/lib/index.js"></script> <script src="/custom_modules/slide-edit-input-controls/lib/index.js"></script>*/} {/*<script>hljs.initHighlightingOnLoad();</script>*/} {/*<script dangerouslySetInnerHTML={ {__html: ga} } />*/} </body> </html> ); } } export default DefaultHTMLLayout;
dashboard-ui/app/components/usageAnalytics/usageAnalytics.js
CloudBoost/cloudboost
/** * Created by Jignesh on 28-06-2017. */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { resetAnalytics } from '../../actions'; export class AppAnalytics extends React.Component { static propTypes = { appData: PropTypes.any, resetAnalytics: PropTypes.any } constructor (props) { super(props); this.state = { noData: false }; } static get contextTypes () { return { router: React.PropTypes.object.isRequired }; } componentWillMount () { // redirect if active app not found if (!this.props.appData.viewActive) { this.context.router.push(window.DASHBOARD_BASE_URL); }// else { // this.props.fetchAppAnalytics(this.props.appData.appId); // } } componentDidMount () { this.buildMonthyGraph(); this.buildDailyGraph(); } componentWillUnmount () { this.props.resetAnalytics(); } buildMonthyGraph () { // eslint-disable-next-line let MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; // eslint-disable-next-line let config = { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'Unique Active registered users', fill: false, backgroundColor: 'rgb(54, 162, 235)', borderColor: 'rgb(54, 162, 235)', data: [ (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000) ] }] }, options: { responsive: true, title: { display: true, text: 'Monthly Active Users' }, tooltips: { mode: 'index', intersect: false }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Month' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Active Users' } }] } } }; return document.getElementById('graph').getContext('2d'); } buildDailyGraph () { // eslint-disable-next-line let config = { type: 'line', data: { labels: ['29th May', '30', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '28th July'], datasets: [{ label: 'Unique Active registered users', fill: false, backgroundColor: 'rgb(54, 162, 235)', borderColor: 'rgb(54, 162, 235)', data: [ (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100) ] }] }, options: { responsive: true, title: { display: true, text: 'Daily Active Users' }, tooltips: { mode: 'index', intersect: false }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Day' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Active Users' } }] } } }; return document.getElementById('graph2').getContext('2d'); } render () { return ( <div className='panel-body' style={{ backgroundColor: '#FFF' }}> <div className='app-analytics' style={{ textAlign: 'center' }}> <h5>45 Active Users at { new Date().toLocaleTimeString() }</h5> </div> <br /> <div className='app-analytics' style={{ width: '75%' }}> { (this.state.noData === false) && <canvas id='graph' /> } { (this.state.noData === true) && <div style={{ width: '100%', height: '100%' }} className='flex-general-column-wrapper-center'> <div> <span style={{ fontSize: 20, color: '#D1D1D1' }}>Monthly Data not available</span> </div> </div> } </div> <div className='app-analytics' style={{ width: '75%' }}> { (this.state.noData === false) && <canvas id='graph2' /> } { (this.state.noData === true) && <div style={{ width: '100%', height: '100%' }} className='flex-general-column-wrapper-center'> <div> <span style={{ fontSize: 20, color: '#D1D1D1' }}>Daily Data not available</span> </div> </div> } </div> </div> ); } } const mapStateToProps = (state) => { return { appData: state.manageApp // analyticsApi: state.analytics.appAnalytics }; }; const mapDispatchToProps = (dispatch) => { return { // fetchAppAnayltics: (appId) => dispatch(fetchAppAnayltics(appId)), resetAnalytics: () => dispatch(resetAnalytics()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(AppAnalytics);
recipe-server/client/control/tests/components/test_ActiveFilters.js
Osmose/normandy
/* eslint-disable react/prop-types */ import React from 'react'; import { mount, shallow } from 'enzyme'; import ActiveFilters from 'control/components/ActiveFilters'; const noop = () => {}; const propFactory = props => ({ selectedFilters: [], onResetFilters: noop, onFilterSelect: noop, className: null, ...props, }); const stubbedFilters = [{ value: 'channels', label: 'Channels', multiple: true, options: [{ value: 'aurora', label: 'Developer Edition', }, { value: 'beta', label: 'Beta', selected: true, }, { value: 'nightly', label: 'Nightly', selected: true, }, { value: 'release', label: 'Release', }], selected: true, }, { value: 'status', label: 'Status', multiple: false, options: [{ value: 'enabled', label: 'Enabled', selected: true, }, { value: 'disabled', label: 'Disabled', }], selected: true, }]; describe('<ActiveFilters>', () => { it('should work', () => { const wrapper = () => mount(<ActiveFilters {...propFactory()} />); expect(wrapper).not.toThrow(); }); describe('Filter groups', () => { it('should display based on the `selectedFilters` prop', () => { const wrapper = mount(<ActiveFilters {...propFactory({ selectedFilters: [], })} />); expect(wrapper.find('.filter-group').length).toBe(0); wrapper.setProps({ selectedFilters: stubbedFilters, }); expect(wrapper.find('.filter-group').length).toBe(2); }); it('should fire the `onFilterSelect` prop when the user clicks an item', () => { let hasFired = false; let hasData = false; const wrapper = mount(<ActiveFilters {...propFactory({ selectedFilters: stubbedFilters, onFilterSelect: (group, option) => { hasFired = true; hasData = !!group && !!option; }, })} />); wrapper.find('.filter-option').first().simulate('click'); expect(hasFired).toBe(true); expect(hasData).toBe(true); }); it('should append the className prop (if any) to the root element', () => { // we have to use shallow to use `hasClass` on the wrapper // see: https://github.com/airbnb/enzyme/issues/134 const wrapper = shallow(<ActiveFilters {...propFactory({ selectedFilters: stubbedFilters, })} />); expect(wrapper.hasClass('active-filters')).toBe(true); wrapper.setProps({ className: 'test' }); // default class should still be on the element expect(wrapper.hasClass('active-filters')).toBe(true); // and it should also have the `test` class on it expect(wrapper.hasClass('test')).toBe(true); // update the prop again wrapper.setProps({ className: 'test-again' }); // should still only have one element expect(wrapper.hasClass('active-filters')).toBe(true); // the old prop should be gone expect(wrapper.hasClass('test')).toBe(false); // and the new one should be present expect(wrapper.hasClass('test-again')).toBe(true); // falsy values should not add any class wrapper.setProps({ className: false }); expect(wrapper.hasClass('active-filters')).toBe(true); expect(wrapper.hasClass('test')).toBe(false); expect(wrapper.hasClass('test-again')).toBe(false); }); }); describe('Reset button', () => { it('should not appear when there no active filters', () => { const wrapper = mount(<ActiveFilters {...propFactory({ selectedFilters: [], })} />); expect(wrapper.find('.filter-button.reset').length).toBe(0); }); it('should appear when there active filters', () => { const wrapper = mount(<ActiveFilters {...propFactory({ selectedFilters: stubbedFilters, })} />); expect(wrapper.find('.filter-button.reset').length).toBe(1); }); it('should fire the onResetFilters prop on click', () => { let hasFired = false; const onResetFilters = () => { hasFired = true; }; const wrapper = mount(<ActiveFilters {...propFactory({ selectedFilters: stubbedFilters, onResetFilters, })} />); wrapper.find('.filter-button.reset').simulate('click'); expect(hasFired).toBe(true); }); }); });
examples/parcel/src/withRoot.js
cherniavskii/material-ui
import React from 'react'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'; import purple from 'material-ui/colors/purple'; import green from 'material-ui/colors/green'; import CssBaseline from 'material-ui/CssBaseline'; // A theme with custom primary and secondary color. // It's optional. const theme = createMuiTheme({ palette: { primary: { light: purple[300], main: purple[500], dark: purple[700], }, secondary: { light: green[300], main: green[500], dark: green[700], }, }, }); function withRoot(Component) { function WithRoot(props) { // MuiThemeProvider makes the theme available down the React tree // thanks to React context. return ( <MuiThemeProvider theme={theme}> {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */} <CssBaseline /> <Component {...props} /> </MuiThemeProvider> ); } return WithRoot; } export default withRoot;
docs/app/Examples/elements/Image/Types/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const ImageTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Image' description='An image.' examplePath='elements/Image/Types/ImageExampleImage' > <Message> Unless a size is specified, images will use the original dimensions of the image up to the size of its container. </Message> </ComponentExample> <ComponentExample description='An image can render wrapped in a div.ui.image as alternative HTML markup.' examplePath='elements/Image/Types/ImageExampleWrapped' /> <ComponentExample title='Image Link' description='An image can be formatted to link to other content.' examplePath='elements/Image/Types/ImageExampleLink' /> </ExampleSection> ) export default ImageTypesExamples
examples/counter/test/components/Counter.spec.js
dieface/redux
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Counter from '../../components/Counter' function setup() { const actions = { increment: expect.createSpy(), incrementIfOdd: expect.createSpy(), incrementAsync: expect.createSpy(), decrement: expect.createSpy() } const component = TestUtils.renderIntoDocument(<Counter counter={1} {...actions} />) return { component: component, actions: actions, buttons: TestUtils.scryRenderedDOMComponentsWithTag(component, 'button'), p: TestUtils.findRenderedDOMComponentWithTag(component, 'p') } } describe('Counter component', () => { it('should display count', () => { const { p } = setup() expect(p.textContent).toMatch(/^Clicked: 1 times/) }) it('first button should call increment', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[0]) expect(actions.increment).toHaveBeenCalled() }) it('second button should call decrement', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[1]) expect(actions.decrement).toHaveBeenCalled() }) it('third button should call incrementIfOdd', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[2]) expect(actions.incrementIfOdd).toHaveBeenCalled() }) it('fourth button should call incrementAsync', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[3]) expect(actions.incrementAsync).toHaveBeenCalled() }) })
router_tutorial/06-params/modules/About.js
Muzietto/react-playground
import React from 'react' export default React.createClass({ render() { return <div>About</div> } })
code/workspaces/web-app/src/pages/Page.js
NERC-CEH/datalab
import React from 'react'; import PropTypes from 'prop-types'; import { Typography, withStyles } from '@material-ui/core'; import Footer from '../components/app/Footer'; const style = theme => ({ pageTemplate: { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: `0 ${theme.spacing(4)}px`, margin: '0 auto', width: '100%', minWidth: '400px', maxWidth: '1000px', }, contentArea: { flexGrow: 1, }, title: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), }, }); function Page({ title, children, className, classes }) { return ( <div className={getClassname(classes.pageTemplate, className)}> {title ? <Typography variant="h4" className={classes.title}>{title}</Typography> : null} <div className={classes.contentArea}> {children} </div> <Footer/> </div> ); } const getClassname = (...classNames) => (classNames.filter(item => item).join(' ')); Page.propTypes = { title: PropTypes.string, classes: PropTypes.object.isRequired, }; export default withStyles(style)(Page);
src/components/routes/animal/AnimalForm.js
fredmarques/petshop
import './Animal.css'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import { registerAnimal } from '../../../actions/animals'; class AnimalForm extends Component { renderField(field) { const { meta: { touched, error } } = field; const className = ''; return ( <div className={className}> <input className="form-control" type={field.type} placeholder={field.placeholder} {...field.input} /> <div className="text-help"> {touched ? error : ''} </div> </div> ); } onSubmit(values) { this.props.registerAnimal(values) } render() { const { handleSubmit } = this.props; return ( <div className={'animalForm'}> <h3>Cadastre seu pet</h3> <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className={'form-inline'}> <Field name="name" label="Nome" placeholder="Nome" type="text" component={this.renderField} /> <Field name="id" label="ID" placeholder="ID" type="text" component={this.renderField} /> <Field name="age" label="Idade" placeholder="Idade" type="text" component={this.renderField} /> <Field name="breed" label="Raça" placeholder="Raça" component={this.renderField} /> <button type="submit" className="btn btn-primary">Entrar</button> <Link to="/" className="btn btn-danger">Cancelar</Link> </form> </div> ); } } export default reduxForm({ form: 'Animal' })( connect(null, {registerAnimal})(AnimalForm) );
src/icons/BorderClearIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class BorderClearIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M14 10h4V6h-4v4zm0 16h4v-4h-4v4zm0 16h4v-4h-4v4zm8-8h4v-4h-4v4zm0 8h4v-4h-4v4zM6 42h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4V6H6v4zm16 16h4v-4h-4v4zm16 8h4v-4h-4v4zm0-8h4v-4h-4v4zm0 16h4v-4h-4v4zm0-24h4v-4h-4v4zm-16 0h4v-4h-4v4zM38 6v4h4V6h-4zm-16 4h4V6h-4v4zm8 32h4v-4h-4v4zm0-16h4v-4h-4v4zm0-16h4V6h-4v4z"/></svg>;} };
packages/base-shell/src/components/AuthorizedRoute.js
TarikHuber/react-most-wanted
import React from 'react' import { Navigate, useLocation } from 'react-router-dom' import { useAuth } from '../providers/Auth' import { useConfig } from '../providers/Config' function AuthorizedRoute({ children }) { const { appConfig } = useConfig() const { auth: authConfig } = appConfig || {} const { signInURL = '/signin' } = authConfig || {} const { auth } = useAuth() const location = useLocation() if (auth.isAuthenticated) { return children } else { return ( <Navigate //to={`${signInURL}?from=${location.pathname}`} to={{ pathname: signInURL, search: `from=${location.pathname}`, state: { from: location }, }} replace /> ) } } export default AuthorizedRoute
examples/js/sort/sort-style-table.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class SortTable extends React.Component { customSortStyle = (order, dataField) => { if (order === 'desc') { return 'sort-desc'; } return 'sort-asc'; } render() { return ( <div> <BootstrapTable ref='table' data={ products }> <TableHeaderColumn dataField='id' isKey dataSort sortHeaderColumnClassName='sorting'>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' dataSort sortHeaderColumnClassName={ this.customSortStyle }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } }
lib/components/tabs.js
whitelynx/hyperterm
import React from 'react'; import Component from '../component'; import {decorate, getTabProps} from '../utils/plugins'; import Tab_ from './tab'; const Tab = decorate(Tab_, 'Tab'); const isMac = /Mac/.test(navigator.userAgent); export default class Tabs extends Component { template(css) { const { tabs = [], borderColor, onChange, onClose } = this.props; const hide = !isMac && tabs.length === 1; return (<nav className={css('nav', hide && 'hiddenNav')}> { this.props.customChildrenBefore } { tabs.length === 1 && isMac ? <div className={css('title')}>{tabs[0].title}</div> : null } { tabs.length > 1 ? [ <ul key="list" className={css('list')} > { tabs.map((tab, i) => { const {uid, title, isActive, hasActivity} = tab; const props = getTabProps(tab, this.props, { text: title === '' ? 'Shell' : title, isFirst: i === 0, isLast: tabs.length - 1 === i, borderColor, isActive, hasActivity, onSelect: onChange.bind(null, uid), onClose: onClose.bind(null, uid) }); return <Tab key={`tab-${uid}`} {...props}/>; }) } </ul>, isMac && <div key="shim" style={{borderColor}} className={css('borderShim')} /> ] : null } { this.props.customChildren } </nav>); } styles() { return { nav: { fontSize: '12px', height: '34px', lineHeight: '34px', verticalAlign: 'middle', color: '#9B9B9B', cursor: 'default', position: 'relative', WebkitUserSelect: 'none', WebkitAppRegion: isMac ? 'drag' : '', top: isMac ? '' : '34px' }, hiddenNav: { display: 'none' }, title: { textAlign: 'center', color: '#fff' }, list: { maxHeight: '34px', display: 'flex', flexFlow: 'row', marginLeft: isMac ? 76 : 0 }, borderShim: { position: 'absolute', width: '76px', bottom: 0, borderColor: '#ccc', borderBottomStyle: 'solid', borderBottomWidth: '1px' } }; } }
src/js/components/icons/base/Note.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-note`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'note'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,23 L16,23 L23,16 L23,1 L1,1 L1,23 Z M15,23 L15,15 L23,15"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Note'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/parser/paladin/holy/modules/beacons/BeaconHealingDone.js
sMteX/WoWAnalyzer
import React from 'react'; import { Trans } from '@lingui/macro'; import Panel from 'interface/statistics/Panel'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import HealingValue from 'parser/shared/modules/HealingValue'; import HealingDone from 'parser/shared/modules/throughput/HealingDone'; import BeaconHealSource from './BeaconHealSource'; import BeaconHealingBreakdown from './BeaconHealingBreakdown'; class BeaconHealingDone extends Analyzer { static dependencies = { beaconHealSource: BeaconHealSource, healingDone: HealingDone, }; _totalBeaconHealing = new HealingValue(); _beaconHealingBySource = {}; constructor(options) { super(options); this.addEventListener(this.beaconHealSource.beacontransfer.by(SELECTED_PLAYER), this._onBeaconTransfer); } _onBeaconTransfer(event) { this._totalBeaconHealing = this._totalBeaconHealing.add(event.amount, event.absorbed, event.overheal); const source = event.originalHeal; const spellId = source.ability.guid; let sourceHealing = this._beaconHealingBySource[spellId]; if (!sourceHealing) { sourceHealing = this._beaconHealingBySource[spellId] = { ability: source.ability, healing: new HealingValue(), }; } sourceHealing.healing = sourceHealing.healing.add(event.amount, event.absorbed, event.overheal); } statistic() { return ( <Panel title={<Trans>Beacon healing sources</Trans>} explanation={( <Trans> Beacon healing is triggered by the <b>raw</b> healing done of your primary spells. This breakdown shows the amount of effective beacon healing replicated by each beacon transfering heal. </Trans> )} position={120} pad={false} > <BeaconHealingBreakdown totalHealingDone={this.healingDone.total} totalBeaconHealing={this._totalBeaconHealing} beaconHealingBySource={this._beaconHealingBySource} fightDuration={this.owner.fightDuration} /> </Panel> ); } } export default BeaconHealingDone;
src/components/Auth/signin.js
gperl27/liftr-v2
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import * as actions from '../../actions'; class Signin extends Component { handleFormSubmit({email, password}){ console.log(email, password); // need to do something to log user in this.props.signinUser({ email, password }); } renderAlert(){ if(this.props.errorMessage){ return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ) } } render() { const { handleSubmit, fields: { email, password }} = this.props; return ( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <label>Email: </label> <input {...email} className="form-control" /> </fieldset> <fieldset className="form-group"> <label>Password: </label> <input {...password} type="password" className="form-control" /> </fieldset> {this.renderAlert()} <button action="submit" className="btn btn-primary">Sign in</button> </form> ) } } function mapStateToProps(state){ return { errorMessage: state.auth.error }; } export default reduxForm({ form: 'signin', fields: ['email', 'password'] }, mapStateToProps, actions)(Signin);
src/components/MenuAside.js
Leobuaa/online-disk
import React, { Component } from 'react'; class MenuAside extends Component { constructor(props) { super(props); } isActiveButton(index) { if (index === this.props.menuAside.buttonActiveIndex) { return 'item-active'; } return ''; } render() { const lists = [ { index: 0, name: 'all', icon: 'glyphicon-th-list', 'chinese': '全部', }, { index: 1, name: 'image', icon: 'glyphicon-picture', 'chinese': '图片', }, { index: 2, name: 'doc', icon: 'glyphicon-file', 'chinese': '文档', }, { index: 3, name: 'video', icon: 'glyphicon-facetime-video', 'chinese': '视频', }, { index: 4, name: 'music', icon: 'glyphicon-music', 'chinese': '音乐', }, { index: 5, name: 'trash', icon: 'glyphicon-trash', 'chinese': '回收站', } ]; const menuLists = lists.map((obj) => <button key={obj.name} name={obj.name} type="button" className={'list-group-item list-item ' + this.isActiveButton(obj.index)} onClick={this.props.onMenuAsideButtonClick}> <span className={'glyphicon ' + obj.icon} aria-hidden="true"></span> {obj.chinese} </button> ); return ( <div className="menu-aside-wrapper"> <div className="list-group menu-list" data-active-index={this.props.menuAside.buttonActiveIndex}> {menuLists} </div> </div> ) } } export default MenuAside;
src/svg-icons/editor/drag-handle.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorDragHandle = (props) => ( <SvgIcon {...props}> <path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/> </SvgIcon> ); EditorDragHandle = pure(EditorDragHandle); EditorDragHandle.displayName = 'EditorDragHandle'; EditorDragHandle.muiName = 'SvgIcon'; export default EditorDragHandle;
src/js/components/icons/base/DocumentVideo.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-document-video`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-video'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L22.9999998,23 L4,23 M18,1 L18,6 L23,6 M3,10 L12,10 L12,19 L3,19 L3,10 Z M12,13 L17,10.5 L17,18.5 L12,16 L12,13 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentVideo'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/svg-icons/image/crop-free.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropFree = (props) => ( <SvgIcon {...props}> <path d="M3 5v4h2V5h4V3H5c-1.1 0-2 .9-2 2zm2 10H3v4c0 1.1.9 2 2 2h4v-2H5v-4zm14 4h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zm0-16h-4v2h4v4h2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ImageCropFree = pure(ImageCropFree); ImageCropFree.displayName = 'ImageCropFree'; ImageCropFree.muiName = 'SvgIcon'; export default ImageCropFree;
client/views/admin/federationDashboard/FederationDashboardPage.stories.js
VoiSmart/Rocket.Chat
import React from 'react'; import FederationDashboardPage from './FederationDashboardPage'; export default { title: 'admin/federationDashboard/FederationDashboardPage', component: FederationDashboardPage, }; export const Default = () => <FederationDashboardPage />;
frontend/src/components/dialog/list-repo-drafts-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { gettext, siteRoot } from '../../utils/constants'; import { seafileAPI } from '../../utils/seafile-api'; import moment from 'moment'; import editorUtilities from '../../utils/editor-utilities'; import toaster from '../../components/toast'; import { Utils } from '../../utils/utils'; import Draft from '../../models/draft'; const propTypes = { repoID: PropTypes.string.isRequired, toggle: PropTypes.func.isRequired, }; class ListRepoDraftsDialog extends React.Component { constructor(props) { super(props); this.state = { drafts: [], }; } componentDidMount() { seafileAPI.listRepoDrafts(this.props.repoID).then(res => { let drafts = res.data.drafts.map(item => { let draft = new Draft(item); return draft; }); this.setState({ drafts: drafts }); }); } onDeleteDraftItem = (draft) => { editorUtilities.deleteDraft(draft.id).then(() => { let drafts = this.state.drafts.filter(item => { return item.id !== draft.id; }); this.setState({drafts: drafts}); let msg = gettext('Successfully deleted draft %(draft)s.'); msg = msg.replace('%(draft)s', draft.draftFilePath); toaster.success(msg); }).catch(() => { let msg = gettext('Failed to delete draft %(draft)s.'); msg = msg.replace('%(draft)s', draft.draftFilePath); toaster.danger(msg); }); } toggle = () => { this.props.toggle(); } render() { return ( <Modal isOpen={true}> <ModalHeader toggle={this.toggle}>{gettext('Drafts')}</ModalHeader> <ModalBody className="dialog-list-container"> <table> <thead> <tr> <th width='50%' className="ellipsis">{gettext('Name')}</th> <th width='20%'>{gettext('Owner')}</th> <th width='20%'>{gettext('Last Update')}</th> <th width='10%'></th> </tr> </thead> <tbody> {this.state.drafts.map((item, index) => { return ( <DraftItem key={index} draftItem={item} onDeleteDraftItem={this.onDeleteDraftItem} /> ); })} </tbody> </table> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggle}>{gettext('Close')}</Button> </ModalFooter> </Modal> ); } } ListRepoDraftsDialog.propTypes = propTypes; export default ListRepoDraftsDialog; const DraftItemPropTypes = { draftItem: PropTypes.object, onDeleteDraftItem: PropTypes.func.isRequired, }; class DraftItem extends React.Component { constructor(props) { super(props); this.state = ({ active: false, }); } onMouseEnter = () => { this.setState({ active: true }); } onMouseLeave = () => { this.setState({ active: false }); } render() { const draftItem = this.props.draftItem; let href = siteRoot + 'drafts/' + draftItem.id + '/'; let className = this.state.active ? 'action-icon sf2-icon-x3' : 'action-icon vh sf2-icon-x3'; return ( <tr onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}> <td className="name"> <a href={href} target='_blank'>{Utils.getFileName(draftItem.draftFilePath)}</a> </td> <td>{draftItem.ownerNickname}</td> <td>{moment(draftItem.createdStr).fromNow()}</td> <td> <i className={className} onClick={this.props.onDeleteDraftItem.bind(this, draftItem)}></i> </td> </tr> ); } } DraftItem.propTypes = DraftItemPropTypes;
wrappers/html.js
pcm-ca/pcm-ca.github.io
import React from 'react' import Helmet from 'react-helmet' import { config } from 'config' module.exports = React.createClass({ propTypes () { return { router: React.PropTypes.object, } }, render () { const page = this.props.route.page.data return ( <div> <Helmet title={`${config.siteTitle} | ${page.title}`} /> <div dangerouslySetInnerHTML={{ __html: page.body }} /> </div> ) }, })
src/other/DescriptionTeaser.js
ndlib/beehive
import React from 'react' import PropTypes from 'prop-types' import createReactClass from 'create-react-class' const DescriptionTeaser = createReactClass({ displayName: 'Teaser Text', propTypes: { description: PropTypes.string, }, style: function () { return { overflow: 'hidden', textOverflow: 'ellipsis', } }, render: function () { return ( <div className='item-description' dangerouslySetInnerHTML={{ __html: this.props.description }} style={this.style()} /> ) }, }) export default DescriptionTeaser
app/server.js
nurogenic/universal-react-boilerplate
import path from 'path'; import React from 'react'; import Router from 'react-router'; import Hapi from 'hapi'; import _merge from 'lodash.merge'; import routes from './routes.jsx'; import component from './components/Html.jsx'; const server = new Hapi.Server(); server.connection({port: 8000}); server.route({ method: 'GET', path: '/hello', handler: function (request, reply) { reply('don\'t worry, be hapi!'); } }); server.route({ method: 'GET', path: '/js/{param*}', handler: { directory: { path: './public/js', listing: true, index: true } } }); server.route({ method: 'GET', path: '/images/{param*}', handler: { directory: { path: './public/images', listing: true, index: true } } }); server.ext('onPostHandler', (request, replay) => { Router.run(routes, request.url.path, (Handler, state) => { if (!state.routes.length) { return replay.continue(); } let html = React.renderToStaticMarkup(component({ title: 'test', markup: React.renderToString(React.createFactory(Handler)()) })); return replay('<!DOCTYPE html>' + html); }); }); server.start(() => { console.log('Server running at: ' + server.info.uri); });
packages/mineral-ui-icons/src/IconHealing.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconHealing(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M17.73 12.02l3.98-3.98a.996.996 0 0 0 0-1.41l-4.34-4.34a.996.996 0 0 0-1.41 0l-3.98 3.98L8 2.29a1.001 1.001 0 0 0-1.41 0L2.25 6.63a.996.996 0 0 0 0 1.41l3.98 3.98L2.25 16a.996.996 0 0 0 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34a.996.996 0 0 0 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z"/> </g> </Icon> ); } IconHealing.displayName = 'IconHealing'; IconHealing.category = 'image';
code/schritte/2-hierarchy/src/GreetingMaster.js
st-he/react-workshop
import React from 'react'; const GreetingMaster = (props) => { const {greetings, onAdd} = props; const body = greetings.map(greeting => <tr key={greeting.id}><td>{greeting.name}</td><td>{greeting.greeting}</td></tr>); return ( <div> <table> <thead> <tr><th>Name</th><th>Greeting</th></tr> </thead> <tbody> {body} </tbody> </table> <button onClick={onAdd}> Add </button> </div> ); }; export default GreetingMaster;
assets/jqwidgets/demos/react/app/tabs/mapinsidetab/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js'; class App extends React.Component { render() { let initialize = () => { let mapCanvas = document.getElementById('map-canvas'); let mapOptions = { center: new google.maps.LatLng(29.979234, 31.134202), zoom: 17, mapTypeId: google.maps.MapTypeId.ROADMAP } let map = new google.maps.Map(mapCanvas, mapOptions) }; let initTabContent = (tab) => { if (tab === 0) { google.maps.event.addDomListener(window, 'load', initialize); } }; return ( <div> <p style={{ fontFamily: 'Verdana' }}> Great Pyramid of Giza</p> <JqxTabs ref='myTabs' width={600} height={400} initTabContent={initTabContent} > <ul style={{ marginLeft: 20 }}> <li>Map</li> <li>Information</li> </ul> <div> <div id="map-canvas" style={{ width: '100%', height: '100%' }}> </div> </div> <div> The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza Necropolis bordering what is now El Giza, Egypt. It is the oldest of the Seven Wonders of the Ancient World, and the only one to remain largely intact. </div> </JqxTabs> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/av/radio.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRadio = (props) => ( <SvgIcon {...props}> <path d="M3.24 6.15C2.51 6.43 2 7.17 2 8v12c0 1.1.89 2 2 2h16c1.11 0 2-.9 2-2V8c0-1.11-.89-2-2-2H8.3l8.26-3.34L15.88 1 3.24 6.15zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z"/> </SvgIcon> ); AvRadio = pure(AvRadio); AvRadio.displayName = 'AvRadio'; AvRadio.muiName = 'SvgIcon'; export default AvRadio;
src/components/shared/top-bar/logo/logo.spec.js
david-mart/react-boilerplate-edited
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import Logo from './index'; describe('<Logo />', () => { it('should have read "dotmaps" text', () => { const expected = 'dotmaps'; const wrapper = shallow(<Logo />); const actual = wrapper.text(); expect(actual).equals(expected); }); });
test/components/Todo/Form.spec.js
elemus/react-redux-todo-example
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import Form from '../../../src/components/Todo/Form'; const setup = (props = { onTaskAdd() {} }) => shallow(<Form {...props} />); describe('Component | Todo | Form', () => { it('renders', () => { const wrapper = setup(); expect(wrapper.find('form')).to.have.lengthOf(1); expect(wrapper.find('input')).to.have.lengthOf(1); expect(wrapper.find('button').text()).to.equal('Add'); }); it('should change state on input event', () => { const wrapper = setup(); const description = 'test task'; wrapper.find('input').simulate('input', { target: { value: description } }); expect(wrapper.state().description).to.equal(description); }); it('should call onTaskAdd() on form submit', () => { const onTaskAdd = sinon.spy(); const wrapper = setup({ onTaskAdd }); const description = 'test task'; wrapper.find('input').simulate('input', { target: { value: description } }); wrapper.find('form').simulate('submit', { preventDefault() {} }); expect(onTaskAdd.calledOnce).to.equal(true); expect(onTaskAdd.calledWith(description)).to.equal(true); expect(wrapper.state().description).to.equal(''); }); });
imports/ui/pages/Index.js
KyneSilverhide/expense-manager
import React from 'react'; import Grid from 'material-ui/Grid'; import EventsListDashboard from '../containers/events/EventsListDashboard'; import Debts from '../containers/debts/Debts'; const Index = () => <Grid container direction="row"> <Grid item xs={12} lg={9}> <EventsListDashboard /> </Grid> <Grid item xs={12} lg={3}> <Debts /> </Grid> </Grid>; export default Index;
examples/js/style/tr-class-function-table.js
rolandsusans/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(9); function trClassFormat(rowData, rIndex) { return rIndex % 3 === 0 ? 'tr-function-example' : ''; } export default class TrClassStringTable extends React.Component { render() { return ( <BootstrapTable data={ products } trClassName={ trClassFormat }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
assets/react/source/grid_offset.js
theroyalstudent/unsemantic-100-grid
// Dependencies. import React from 'react' import PropTypes from 'prop-types' // Define class. class GridOffset extends React.Component { // Render method. render () { // Expose UI. return ( <div className='grid-offset'> {this.props.children} </div> ) } } // Validation. GridOffset.propTypes = { children: PropTypes.node } // Export. export default GridOffset
src/mui/detail/Create.js
azureReact/AzureReact
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Card } from 'material-ui/Card'; import compose from 'recompose/compose'; import inflection from 'inflection'; import ViewTitle from '../layout/ViewTitle'; import Title from '../layout/Title'; import { crudCreate as crudCreateAction } from '../../actions/dataActions'; import DefaultActions from './CreateActions'; import translate from '../../i18n/translate'; import withPermissionsFilteredChildren from '../../auth/withPermissionsFilteredChildren'; class Create extends Component { getBasePath() { const { location } = this.props; return location.pathname .split('/') .slice(0, -1) .join('/'); } defaultRedirectRoute() { const { hasShow, hasEdit } = this.props; if (hasEdit) return 'edit'; if (hasShow) return 'show'; return 'list'; } save = (record, redirect) => { this.props.crudCreate( this.props.resource, record, this.getBasePath(), redirect ); }; render() { const { actions = <DefaultActions />, children, isLoading, resource, title, translate, hasList, } = this.props; if (!children) return null; const basePath = this.getBasePath(); const resourceName = translate(`resources.${resource}.name`, { smart_count: 1, _: inflection.humanize(inflection.singularize(resource)), }); const defaultTitle = translate('aor.page.create', { name: `${resourceName}`, }); const titleElement = ( <Title title={title} defaultTitle={defaultTitle} /> ); return ( <div className="create-page"> <Card style={{ opacity: isLoading ? 0.8 : 1 }}> {actions && React.cloneElement(actions, { basePath, resource, hasList, })} <ViewTitle title={titleElement} /> {React.cloneElement(children, { save: this.save, resource, basePath, record: {}, translate, redirect: typeof children.props.redirect === 'undefined' ? this.defaultRedirectRoute() : children.props.redirect, })} </Card> </div> ); } } Create.propTypes = { actions: PropTypes.element, children: PropTypes.element, crudCreate: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, location: PropTypes.object.isRequired, resource: PropTypes.string.isRequired, title: PropTypes.any, translate: PropTypes.func.isRequired, hasList: PropTypes.bool, }; Create.defaultProps = { data: {}, }; function mapStateToProps(state) { return { isLoading: state.admin.loading > 0, }; } const enhance = compose( connect(mapStateToProps, { crudCreate: crudCreateAction }), translate, withPermissionsFilteredChildren ); export default enhance(Create);
src/js/components/Projects/TableRow.js
appdev-academy/appdev.academy-react
import PropTypes from 'prop-types' import React from 'react' import { findDOMNode } from 'react-dom' import { Link } from 'react-router' import { DragSource, DropTarget } from 'react-dnd' import GreenButton from '../Buttons/Green' import OrangeButton from '../Buttons/Orange' const style = { border: '1px dashed gray', padding: '0.5rem 1rem', marginBottom: '.5rem', backgroundColor: 'white', cursor: 'move' } const cardSource = { beginDrag(props) { return { id: props.id, index: props.index } }, endDrag(props, monitor, component) { if (monitor.didDrop()) { let startIndex = props.index let dropIndex = monitor.getItem().index props.moveRow(startIndex, dropIndex) } } } const cardTarget = { hover(props, monitor, component) { // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = props.index } } @DropTarget( "PROJECT_ROW", cardTarget, connect => ({ connectDropTarget: connect.dropTarget() }) ) @DragSource( "PROJECT_ROW", cardSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }) ) export default class TableRow extends React.Component { static propTypes = { connectDragSource: PropTypes.func.isRequired, connectDropTarget: PropTypes.func.isRequired, index: PropTypes.number.isRequired, isDragging: PropTypes.bool.isRequired, id: PropTypes.any.isRequired, text: PropTypes.string.isRequired, moveRow: PropTypes.func.isRequired } render() { const { text, isDragging, connectDragSource, connectDropTarget } = this.props; const opacity = isDragging ? 0 : 1; let project = this.props.project let publishButton = <GreenButton title='Publish' onClick={ () => { this.props.publishButtonClick(project.id) }} /> if (!project.is_hidden) { publishButton = <OrangeButton title='Hide' onClick={ () => { this.props.hideButtonClick(project.id) }} /> } return connectDragSource(connectDropTarget( <tr key={ project.id }> <td>{ project.id }</td> <td>{ project.title }</td> <td>{ project.slug }</td> <td>{ project.position }</td> <td className='actions left'> <Link className='button blue' to={ `/projects/${project.id}` }>Show</Link> <Link className='button green' to={ `/projects/${project.id}/edit` }>Edit</Link> </td> <td className='actions left'> { publishButton } </td> </tr> )) } }
src/components/Showcase/ShowcaseEndingCard.js
ndlib/beehive
import React from 'react' import PropTypes from 'prop-types' import createReactClass from 'create-react-class' import { Paper } from '@material-ui/core' import SitePathCard from '../Collection/SitePathCard' const ShowcaseEndingCard = createReactClass({ displayName: 'Showcase Ending', propTypes: { siteObject: PropTypes.object.isRequired, }, style: function () { return { display: 'inline-block', verticalAlign: 'middle', position: 'relative', marginLeft: '150px', marginRight: '33vw', height: 'auto', cursor: 'pointer', width: '500px', overflow: 'hidden', marginTop: '12vh', backgroundColor: '#ffffff', } }, render: function () { return ( <Paper style={this.style()}> <SitePathCard siteObject={this.props.siteObject} addNextButton headerTitle='Continue to' fixedSize={false} /> </Paper> ) }, }) export default ShowcaseEndingCard
src/components/post-header.js
Dmidify/mlblog
import React, { Component } from 'react'; import { postsData } from '../sample-data.js'; class PostHeader extends Component { state = { posts: postsData } render() { return ( <header className="intro-header post"> <div className="container"> <div className="row"> <div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div className="post-heading"> <h1>{this.state.posts[0].title}</h1> <h2 className="subheading">{this.state.posts[0].subtitle}</h2> <span className="meta">Posted by <a href="#">{this.state.posts[0].username}</a> on {this.state.posts[0].datetime}</span> </div> </div> </div> </div> </header> ); } } export default PostHeader;
src/svg-icons/navigation/arrow-upward.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowUpward = (props) => ( <SvgIcon {...props}> <path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/> </SvgIcon> ); NavigationArrowUpward = pure(NavigationArrowUpward); NavigationArrowUpward.displayName = 'NavigationArrowUpward'; NavigationArrowUpward.muiName = 'SvgIcon'; export default NavigationArrowUpward;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
maxipad37/maxipad37.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'));
scripts/dashboard/components/ProjectForm/ProjectFormServiceList/view.js
vedranjukic/dockerino
import React from 'react' import { Link } from 'react-router' import { Table } from 'react-bootstrap'; function view (props, state) { if (!props.project.services || !props.project.services.length) { return ( <div> No services added. <Link to="/project/addservice">Add service to project</Link> </div> ) } return ( <div> <Table> <thead> <tr> <th>Name</th> <th>Image</th> <th>Actions</th> </tr> </thead> <tbody> { props.project.services.map( service => { return ( <tr key={service.id}> <td>{service.name}</td> <td>{service.image}</td> <td> <a href="#" className="edit">Edit</a> <a href="#" className="remove">Remove</a> </td> </tr> ) }) } </tbody> </Table> <Link to="/project/addservice">Add service to project</Link> </div> ) } export default view
src/svg-icons/communication/swap-calls.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationSwapCalls = (props) => ( <SvgIcon {...props}> <path d="M18 4l-4 4h3v7c0 1.1-.9 2-2 2s-2-.9-2-2V8c0-2.21-1.79-4-4-4S5 5.79 5 8v7H2l4 4 4-4H7V8c0-1.1.9-2 2-2s2 .9 2 2v7c0 2.21 1.79 4 4 4s4-1.79 4-4V8h3l-4-4z"/> </SvgIcon> ); CommunicationSwapCalls = pure(CommunicationSwapCalls); CommunicationSwapCalls.displayName = 'CommunicationSwapCalls'; CommunicationSwapCalls.muiName = 'SvgIcon'; export default CommunicationSwapCalls;
src/components/store_types/store-types-edit.js
Xabadu/VendOS
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import { getStoreType, updateStoreType } from '../../actions/store-types'; class StoreTypesEdit extends Component { constructor(props) { super(props); this.state = { success: false }; } componentWillMount() { this.props.getStoreType(this.props.params.id); } onSubmit(props) { this.props.updateStoreType(props, this.props.storeTypeId) .then(() => { this.setState({success: true}); window.scrollTo(0, 0); }); } _successAlert() { if(this.state.success) { return ( <div className="row"> <div className="col-md-12"> <div className="alert alert-success"> El tipo de tienda ha sido editado exitosamente. <Link to='/store_types'>Volver al listado de tipos de tienda.</Link> </div> </div> </div> ); } } render() { const { fields: { name }, handleSubmit } = this.props; return ( <div> <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <div className="page-breadcrumb"> <ol className="breadcrumb container"> <li><Link to='/'>Inicio</Link></li> <li><a href="#">Tipos de Tienda</a></li> <li className="active">Actualizar Tipo de Tienda</li> </ol> </div> <div className="page-title"> <div className="container"> <h3>Actualizar Tipo de Tienda</h3> </div> </div> <div id="main-wrapper" className="container"> {this._successAlert()} <div className="row"> <div className="col-md-6"> <div className="panel panel-white"> <div className="panel-heading clearfix"> <h4 className="panel-title">Informaci&oacute;n general</h4> </div> <div className="panel-body"> <div className="form-group"> <label for="input-Default" className="control-label">Nombre</label> <input type="text" className={`form-control ${name.touched && name.invalid ? 'b-error' : ''}`} id="input-Default" placeholder="Nombre" {...name} /> <span className="text-danger">{name.touched ? name.error : ''}</span> </div> </div> </div> </div> <div className="col-md-6"> </div> <div className="col-md-6"> </div> <div className="col-md-12"> <div className="panel panel-white"> <div className="panel-body"> <button type="submit" className="btn btn-info left">Actualizar tipo de tienda</button> </div> </div> </div> </div> </div> </form> </div> ); } } function validate(values) { const errors = {}; if(!values.name) { errors.name = 'Ingresa un nombre'; } return errors; } function mapStateToProps(state) { return { initialValues: state.storeTypes.storeTypeDetail, storeTypeId: state.storeTypes.storeTypeId }; } export default reduxForm({ form: 'EditStoreTypeForm', fields: ['name'], validate }, mapStateToProps, { getStoreType, updateStoreType })(StoreTypesEdit);
ui/js/components/ItemContext.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { loadCategory, unloadCategory } from '../actions'; import PageItem from '../pages/page/PageItem'; import EventItem from '../pages/event/EventItem'; class ItemContext extends Component { componentDidMount() { const { filter } = this.props; if (filter) { this._load(this.props); } } componentWillReceiveProps(nextProps) { const { filter } = nextProps; if (filter && (!this.props.filter || JSON.stringify(filter) !== JSON.stringify(this.props.filter))) { this._load(nextProps); } } componentWillUnmount() { const { dispatch } = this.props; dispatch(unloadCategory('pages')); dispatch(unloadCategory('events')); } _load(props) { const { dispatch, filter } = props; dispatch(loadCategory('pages', { filter: { public: true, ...filter }, select: 'name path', })); dispatch(loadCategory('events', { filter: { public: true, ...filter }, select: 'name path start stop allDay dates', })); } render() { const { align, events, pages } = this.props; const pageItems = (pages || []).map(page => ( <li key={page._id}> <PageItem align={align} item={page} /> </li> )); const eventItems = (events || []).map(event => ( <li key={event._id}> <EventItem align={align} item={event} /> </li> )); return ( <ul className="page-context list"> {pageItems} {eventItems} </ul> ); } } ItemContext.propTypes = { align: PropTypes.oneOf(['start', 'center', 'end']), dispatch: PropTypes.func.isRequired, events: PropTypes.array, filter: PropTypes.object, pages: PropTypes.array, }; ItemContext.defaultProps = { align: 'center', events: undefined, filter: undefined, pages: undefined, }; const select = state => ({ events: (state.events || {}).items, pages: (state.pages || {}).items, }); export default connect(select)(ItemContext);
lib-module-modern-browsers-dev/layout/DefaultLayout.js
turacojs/fody
var _jsxFileName = 'layout/DefaultLayout.jsx', _this = this; import React from 'react'; import { ReactElementType as _ReactElementType, LayoutPropsType as _LayoutPropsType } from '../types'; import { Html, Head, Body } from './index'; import t from 'flow-runtime'; const ReactElementType = t.tdz(function () { return _ReactElementType; }); const LayoutPropsType = t.tdz(function () { return _LayoutPropsType; }); export default (function defaultLayout(_arg) { const _returnType = t.return(t.ref(ReactElementType)); let { helmet, content } = t.ref(LayoutPropsType).assert(_arg); return _returnType.assert(React.createElement( Html, { helmet: helmet, __self: _this, __source: { fileName: _jsxFileName, lineNumber: 5 } }, React.createElement(Head, { helmet: helmet, __self: _this, __source: { fileName: _jsxFileName, lineNumber: 6 } }), React.createElement( Body, { __self: _this, __source: { fileName: _jsxFileName, lineNumber: 7 } }, React.createElement('div', { id: 'app', dangerouslySetInnerHTML: { __html: content }, __self: _this, __source: { fileName: _jsxFileName, lineNumber: 8 } }) ) )); }); //# sourceMappingURL=DefaultLayout.js.map
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
joenmarz/joenmarz-yii2-advanced-with-gulp-bootstrap-sass
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'));
src/Components/Featured.js
jsmankoo/SPATemplate
import React from 'react'; import {connect} from 'react-redux'; import MediaQuery from 'react-responsive'; import OwlCarousel from './OwlCarousel'; const Featured = ({Properties,Search})=>{ return ( <div className='Featured'> <MediaQuery maxDeviceWidth={767}> <Mobile Properties={Properties} Search={Search} options={{ dots: true, items: 2, singleItem: true, autoPlay: false, navigation: false }} /> </MediaQuery> <MediaQuery minDeviceWidth={768} maxDeviceWidth={1024}> <Tablet Properties={Properties} Search={Search} options={{ dots: true, items: 2, items : 2, itemsTablet : [1024,2], autoPlay: false, navigation: false }} /> </MediaQuery> <MediaQuery minDeviceWidth={1025}> <Desktop Properties={Properties} Search={Search} options={{ dots: true, items: 3, itemsTablet : [1200,3], autoPlay: false, navigation: false }} /> </MediaQuery> </div> ); }; const Mobile = ({Properties,Search,options})=>{ return ( <div className='Mobile'> <div className='Wrapper'> <div className='Headline'> <h2>FEATURED PROPERTIES</h2> </div> <div className='Search'> <a target='_blank' href='//google.com'>SEARCH THE MLS</a> </div> <div className='Properties'> <OwlCarousel className='owl-carousel owl-theme' {...options}> { Properties.map(({Address, Link, Photo, Price}, index)=>( <div className='item' key={index}> <a target='_blank' href={Link.value.url} className='Property'> <div className='Pic' style={{ backgroundImage: `url('${Photo.value.main.url}')`, backgroundSize: 'cover', backgroundPosition: 'center' }}> </div> <div className='Address'>{Address.value}</div> <div className='Price'>{Price.value}</div> </a> </div> )) } </OwlCarousel> </div> </div> </div> ); }; const Tablet = ({Properties,Search,options})=>{ return ( <div className='Tablet'> <div className='Wrapper'> <div className='Headline'> <h2>FEATURED PROPERTIES</h2> <a target='_blank' href={Search}>SEARCH THE MLS</a> </div> <div className='Properties'> <OwlCarousel className='owl-carousel owl-theme' {...options}> { Properties.map(({Address, Link, Photo, Price}, index)=>( <div className='item' key={index}> <a target='_blank' href={Link.value.url} className='Property'> <div className='Pic' style={{ backgroundImage: `url('${Photo.value.main.url}')`, backgroundSize: 'cover', backgroundPosition: 'center' }}> </div> <div className='Address'>{Address.value}</div> <div className='Price'>{Price.value}</div> </a> </div> )) } </OwlCarousel> </div> </div> </div> ); }; const Desktop = ({Properties,Search,options})=>{ return ( <div className='Desktop'> <div className='Wrapper'> <div className='Headline'> <h2>FEATURED PROPERTIES</h2> <a target='_blank' href={Search}>SEARCH THE MLS</a> </div> <div className='Properties'> <OwlCarousel className='owl-carousel owl-theme' {...options}> { Properties.map(({Address, Link, Photo, Price}, index)=>( <div className='item' key={index}> <a target='_blank' href={Link.value.url} className='Property'> <div className='Pic' style={{ backgroundImage: `url('${Photo.value.main.url}')`, backgroundSize: 'cover', backgroundPosition: 'center' }}> </div> <div className='Address'>{Address.value}</div> <div className='Price'>{Price.value}</div> </a> </div> )) } </OwlCarousel> </div> </div> </div> ); }; const mapStateToProps = ({Featured})=>{ return { Properties: Featured.get('Properties').toJS(), Search: Featured.get('Search') }; }; export default connect(mapStateToProps)(Featured);
app/layouts/authenticated.js
meddle0x53/react-webpack-koa-postgres-passport-example
import React, { Component } from 'react'; import { Link, RouteHandler } from 'react-router'; import { Jumbotron, Nav, Row, Col } from 'react-bootstrap'; import { NavItemLink } from 'react-router-bootstrap'; import AuthStore from '../stores/auth'; import SignIn from '../pages/signin'; export default class MainLayout extends Component { static displayName = 'MainLayout'; constructor() { super(); } static willTransitionTo(transition) { if (!AuthStore.isLoggedIn()) { SignIn.attemptedTransition = transition; transition.redirect('sign-in'); } } render() { return ( <div> <div className="container"> <Row> <Col md={2}> <h3>Links</h3> <Nav bsStyle="pills" stacked> <NavItemLink to="index">Index</NavItemLink> <NavItemLink to="null-page">Null</NavItemLink> </Nav> </Col> <Col md={10} className="well"> <RouteHandler /> </Col> </Row> </div> </div> ); } }
src/svg-icons/editor/strikethrough-s.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorStrikethroughS = (props) => ( <SvgIcon {...props}> <path d="M7.24 8.75c-.26-.48-.39-1.03-.39-1.67 0-.61.13-1.16.4-1.67.26-.5.63-.93 1.11-1.29.48-.35 1.05-.63 1.7-.83.66-.19 1.39-.29 2.18-.29.81 0 1.54.11 2.21.34.66.22 1.23.54 1.69.94.47.4.83.88 1.08 1.43.25.55.38 1.15.38 1.81h-3.01c0-.31-.05-.59-.15-.85-.09-.27-.24-.49-.44-.68-.2-.19-.45-.33-.75-.44-.3-.1-.66-.16-1.06-.16-.39 0-.74.04-1.03.13-.29.09-.53.21-.72.36-.19.16-.34.34-.44.55-.1.21-.15.43-.15.66 0 .48.25.88.74 1.21.38.25.77.48 1.41.7H7.39c-.05-.08-.11-.17-.15-.25zM21 12v-2H3v2h9.62c.18.07.4.14.55.2.37.17.66.34.87.51.21.17.35.36.43.57.07.2.11.43.11.69 0 .23-.05.45-.14.66-.09.2-.23.38-.42.53-.19.15-.42.26-.71.35-.29.08-.63.13-1.01.13-.43 0-.83-.04-1.18-.13s-.66-.23-.91-.42c-.25-.19-.45-.44-.59-.75-.14-.31-.25-.76-.25-1.21H6.4c0 .55.08 1.13.24 1.58.16.45.37.85.65 1.21.28.35.6.66.98.92.37.26.78.48 1.22.65.44.17.9.3 1.38.39.48.08.96.13 1.44.13.8 0 1.53-.09 2.18-.28s1.21-.45 1.67-.79c.46-.34.82-.77 1.07-1.27s.38-1.07.38-1.71c0-.6-.1-1.14-.31-1.61-.05-.11-.11-.23-.17-.33H21z"/> </SvgIcon> ); EditorStrikethroughS = pure(EditorStrikethroughS); EditorStrikethroughS.displayName = 'EditorStrikethroughS'; EditorStrikethroughS.muiName = 'SvgIcon'; export default EditorStrikethroughS;
src/articles/2018-09-30-Suggestions/index.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import { Link } from 'react-router-dom'; import { Zerotorescue } from 'CONTRIBUTORS'; import RegularArticle from 'interface/news/RegularArticle'; import RandomImageToMakeThisArticleLessBland from './weirdnelfandherfriend.png'; export default ( <RegularArticle title={<>What are <i>YOUR</i> suggestions?</>} publishedAt="2018-09-30" publishedBy={Zerotorescue}> <img src={RandomImageToMakeThisArticleLessBland} alt="" style={{ float: 'right', maxWidth: '50%', marginRight: -22, marginBottom: -15, }} /> We'd love to hear your suggestions. What can we do better? Do you have a grand idea? Is there a spec we should prioritize? Let us know on the new <a href="https://suggestions.wowanalyzer.com/">suggestions board</a>! There you can share your suggestions or give a vote to other people's amazing suggestions. And we'll even put a bounty on the best suggestions using the funds raised with <Link to="/premium">Premium</Link>! </RegularArticle> );
src/components/Header/Header.js
HereIsJohnny/issuetracker
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
src/interface/report/EventParser.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import ExtendableError from 'es6-error'; import { connect } from 'react-redux'; import { getBuild } from 'interface/selectors/url/report'; import sleep from 'common/sleep'; import { captureException } from 'common/errorLogger'; import EventEmitter from 'parser/core/modules/EventEmitter'; import { EventType } from 'parser/core/Events'; const BENCHMARK = false; // Picking a correct batch duration is hard. I tried various durations to get the batch sizes to 1 frame, but that results in a lot of wasted time waiting for the next frame. 30ms (33 fps) as well causes a lot of wasted time. 60ms (16fps) seem to have really low wasted time while not blocking the UI anymore than a user might expect. const MAX_BATCH_DURATION = 66.67; // ms const TIME_AVAILABLE = console.time && console.timeEnd; const bench = id => TIME_AVAILABLE && console.time(id); const benchEnd = id => TIME_AVAILABLE && console.timeEnd(id); export class EventsParseError extends ExtendableError { reason = null; constructor(reason) { super(); this.reason = reason; this.message = `An error occured while parsing events: ${reason.message}`; } } class EventParser extends React.PureComponent { static propTypes = { report: PropTypes.shape({ title: PropTypes.string.isRequired, code: PropTypes.string.isRequired, }).isRequired, fight: PropTypes.shape({ start_time: PropTypes.number.isRequired, end_time: PropTypes.number.isRequired, offset_time: PropTypes.number.isRequired, boss: PropTypes.number.isRequired, phase: PropTypes.string, }).isRequired, player: PropTypes.shape({ name: PropTypes.string.isRequired, id: PropTypes.number.isRequired, guid: PropTypes.number.isRequired, type: PropTypes.string.isRequired, }).isRequired, combatants: PropTypes.arrayOf(PropTypes.shape({ sourceID: PropTypes.number.isRequired, })), applyTimeFilter: PropTypes.func.isRequired, applyPhaseFilter: PropTypes.func.isRequired, parserClass: PropTypes.func.isRequired, build: PropTypes.object, builds: PropTypes.object, characterProfile: PropTypes.object, events: PropTypes.array.isRequired, children: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { isLoading: true, progress: 0, parser: null, }; } componentDidMount() { // noinspection JSIgnoredPromiseFromCall this.parse(); } componentDidUpdate(prevProps, prevState, prevContext) { const changed = this.props.report !== prevProps.report || this.props.fight !== prevProps.fight || this.props.player !== prevProps.player || this.props.combatants !== prevProps.combatants || this.props.parserClass !== prevProps.parserClass || this.props.characterProfile !== prevProps.characterProfile || this.props.events !== prevProps.events || this.props.build !== prevProps.build || this.props.builds !== prevProps.builds; if (changed) { this.setState({ isLoading: true, progress: 0, parser: null, }); // noinspection JSIgnoredPromiseFromCall this.parse(); } } makeParser() { const { report, fight, combatants, player, characterProfile, build, builds, parserClass } = this.props; const buildKey = builds && Object.keys(builds).find(b => builds[b].url === build); builds && Object.keys(builds).forEach(key => { builds[key].active = key === buildKey; }); //set current build to undefined if default build or non-existing build selected const parser = new parserClass(report, player, fight, combatants, characterProfile, buildKey && build, builds); parser.applyTimeFilter = this.props.applyTimeFilter; parser.applyPhaseFilter = this.props.applyPhaseFilter; this.setState({ parser, }); return parser; } makeEvents(parser) { let { events } = this.props; // The events we fetched will be all events related to the selected player. This includes the `combatantinfo` for the selected player. However we have already parsed this event when we loaded the combatants in the `initializeAnalyzers` of the CombatLogParser. Loading the selected player again could lead to bugs since it would reinitialize and overwrite the existing entity (the selected player) in the Combatants module. events = events.filter(event => event.type !== EventType.CombatantInfo); //sort now normalized events to avoid new fabricated events like "prepull" casts etc being in incorrect order with casts "kept" from before the filter events = parser.normalize(events).sort((a,b) => a.timestamp - b.timestamp); return events; } async parse() { try { bench('total parse'); bench('initialize'); const parser = this.makeParser(); const events = this.makeEvents(parser); const numEvents = events.length; const eventEmitter = parser.getModule(EventEmitter); benchEnd('initialize'); bench('events'); let eventIndex = 0; while (eventIndex < numEvents) { const start = Date.now(); while (eventIndex < numEvents) { eventEmitter.triggerEvent(events[eventIndex]); eventIndex += 1; if (!BENCHMARK && (Date.now() - start) > MAX_BATCH_DURATION) { break; } } if (!BENCHMARK) { this.setState({ progress: Math.min(1, eventIndex / numEvents), }); // Delay the next iteration until next frame so the browser doesn't appear to be frozen await sleep(0); // eslint-disable-line no-await-in-loop } } parser.finish(); benchEnd('events'); benchEnd('total parse'); this.setState({ isLoading: false, progress: 1, }); } catch (err) { captureException(err); throw new EventsParseError(err); } } render() { return this.props.children(this.state.isLoading, this.state.progress, this.state.parser); } } const mapStateToProps = (state, ownProps) => ({ // Because build comes from the URL we can't use local state build: getBuild(state), }); export default connect(mapStateToProps)(EventParser);
examples/async/containers/Root.js
leeluolee/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import configureStore from '../store/configureStore'; import AsyncApp from './AsyncApp'; const store = configureStore(); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <AsyncApp />} </Provider> ); } }
src/components/iconButton.js
Andrey11/golfmanager
'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TouchableHighlight, Image } from 'react-native'; import styles from '../styles/basestyles.js'; export default class iconButton extends Component { render () { return ( <TouchableHighlight style={this.props.touchableHighlightStyle} underlayColor={this.props.underlayColor} onPress={() => { this.props.onButtonPressed(this.props.pressedParam) }}> <Image style={this.props.imageStyle} source={this.props.iconSource} /> </TouchableHighlight> ); } } AppRegistry.registerComponent('iconButton', () => iconButton);
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
shrynx/react-super-scripts
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import tiniestCat from './assets/tiniest-cat.jpg'; export default () => <img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />;
example/src/other/SuperButton.js
b6pzeusbc54tvhw5jgpyw8pwz2x6gs/rix-loader
import React from 'react'; import StyleSheet from 'react-inline'; require('requirish')._(module); var appUtil = require('src/appUtil'); //import appUtil from 'src/appUtil'; console.log('SuperButton'); const { oneOf, bool } = React.PropTypes; class SuperButton extends React.Component { render() { return <div className={styles.default}></div>; } } SuperButton.propTypes = { size: oneOf(['large', 'small']), block: bool, busy: bool }; const rixContext = { size: 47 }; const { size } = rixContext; export default SuperButton; export { rixContext }; const styles = StyleSheet.create({ default: { padding: '6px 12px', //fontSize: size, lineHeight: 1.5, cursor: 'pointer', border: '1px solid #2e6da4', borderRadius: 4, color: '#fff', backgroundColor: '#337ab7' } });
public/components/tehtPage/tabsComponents/pohjapiirrokset/Pelastussuunnitelma.js
City-of-Vantaa-SmartLab/kupela
import React from 'react'; import SubitemWrapper from './subcontent/SubitemWrapper'; import { connect } from 'react-redux'; const Pelastussuunnitelma = (props) => <SubitemWrapper {...props} />; const mapStateToProps = ({ pelastussuunnitelmatab }) => ({ pelastussuunnitelmatab }); export default connect(mapStateToProps, null)(Pelastussuunnitelma);
docs/src/PageFooter.js
AlexKVal/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className='bs-docs-footer' role='contentinfo'> <div className='container'> <div className='bs-docs-social'> <ul className='bs-docs-social-buttons'> <li> <iframe className='github-btn' src='https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true' width={95} height={20} title='Star on GitHub' /> </li> <li> <iframe className='github-btn' src='https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true' width={92} height={20} title='Fork on GitHub' /> </li> <li> <iframe src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder='0' scrolling='no'> </iframe> </li> </ul> </div> <p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p> <ul className='bs-docs-footer-links muted'> <li>Currently v{version}</li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
example/common/components/Counter.js
modosc/react-responsive-redux
import React from 'react' import PropTypes from 'prop-types' const Counter = ({ increment, incrementIfOdd, incrementAsync, decrement, counter, }) => ( <p> Clicked: {counter} times {' '} <button onClick={increment}>+</button> {' '} <button onClick={decrement}>-</button> {' '} <button onClick={incrementIfOdd}>Increment if odd</button> {' '} <button onClick={() => incrementAsync()}>Increment async</button> </p> ) Counter.propTypes = { counter: PropTypes.number.isRequired, decrement: PropTypes.func.isRequired, increment: PropTypes.func.isRequired, incrementAsync: PropTypes.func.isRequired, incrementIfOdd: PropTypes.func.isRequired, } export default Counter
src/components/Charts/MiniBar/index.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 { Chart, Tooltip, Geom } from 'bizcharts'; import autoHeight from '../autoHeight'; import styles from '../index.less'; @autoHeight() export default class MiniBar extends React.Component { render() { const { height, forceFit = true, color = '#1890FF', data = [] } = this.props; const scale = { x: { type: 'cat', }, y: { min: 0, }, }; const padding = [36, 5, 30, 5]; const tooltip = [ 'x*y', (x, y) => ({ name: x, value: y, }), ]; // for tooltip not to be hide const chartHeight = height + 54; return ( <div className={styles.miniChart} style={{ height }}> <div className={styles.chartContent}> <Chart scale={scale} height={chartHeight} forceFit={forceFit} data={data} padding={padding} > <Tooltip showTitle={false} crosshairs={false} /> <Geom type="interval" position="x*y" color={color} tooltip={tooltip} /> </Chart> </div> </div> ); } }
src/components/Dialog/Container.js
STMU1320/dedao-demo
import React from 'react' import { VelocityComponent } from 'velocity-react' import classnames from 'classnames' import styles from './style.less' const dialogMask = 'dialog_mask' class Container extends React.PureComponent { static defaultProps = { maskClosable: true, placement: 'center', className: '', setOverflow: true, mask: 'rgba(0, 0, 0, .2)', visible: false, id: '', duration: 500, }; dialogWrap = null; timer = null; constructor (props) { super(props) this.state = { visible: props.visible, contentVisible: props.visible } } componentWillReceiveProps (nextProps) { const { visible, setOverflow, duration } = nextProps if (this.props.visible !== visible) { if (setOverflow) { document.body.style.overflow = visible ? 'hidden' : 'auto' } if (this.timer) clearTimeout(this.timer) if (visible) { this.setState({ visible: true }) } else { this.timer = setTimeout(() => { this.setState({ visible: false }) }, duration) } this.setState({ contentVisible: visible }) } } componentWillUnmount () { const { setOverflow } = this.props if (setOverflow) { document.body.style.overflow = 'auto' } if (this.timer) clearTimeout(this.timer) this.timer = null } handleWrapClick = e => { const { maskClosable, onClose, duration } = this.props if (maskClosable && e.target.dataset.tag === dialogMask) { this.setState({ contentVisible: false }) if (this.timer) clearTimeout(this.timer) this.timer = setTimeout(() => { onClose && onClose() this.setState({ visible: false }) }, duration) } }; render () { const { children, placement, mask, style, className, id, duration, } = this.props const { visible, contentVisible } = this.state let animation = { opacity: contentVisible ? 1 : 0 } switch (placement) { case 'center': animation = { opacity: contentVisible ? 1 : 0, translateX: '-50%', translateY: contentVisible ? '-50%' : '50%', } break case 'left': animation = { translateY: '-50%', translateX: contentVisible ? '0%' : '-100%', } break case 'right': animation = { translateY: '-50%', translateX: contentVisible ? '0%' : '100%', } break case 'top': animation = { translateX: '-50%', translateY: contentVisible ? '0%' : '-100%', } break case 'bottom': animation = { translateX: '-50%', translateY: contentVisible ? '0%' : '100%', } break case 'leftTop': case 'topLeft': case 'leftBottom': case 'bottomLeft': animation = { translateX: contentVisible ? '0%' : '-100%' } break case 'rightTop': case 'topRight': case 'rightBottom': case 'bottomRight': animation = { translateX: contentVisible ? '0%' : '100%' } break default: break } return ( <div id={id} onClick={this.handleWrapClick} className={classnames(styles.dialog, className)} style={{ ...style, display: visible ? null : 'none' }} > <div className={styles.mask} style={{ background: mask }} data-tag={dialogMask} /> <VelocityComponent component="" animation={duration > 0 && animation} duration={duration} > <div className={classnames(styles.content, styles[placement])}> {children} </div> </VelocityComponent> </div> ) } } export default Container
examples/server/store.js
rackt/redux-simple-router
import React from 'react' import { createStore, combineReducers, compose, applyMiddleware } from 'redux' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' import { routerReducer, routerMiddleware } from 'react-router-redux' export const DevTools = createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor theme="tomorrow" preserveScrollTop={false} /> </DockMonitor> ) export function configureStore(history, initialState) { const reducer = combineReducers({ routing: routerReducer }) let devTools = [] if (typeof document !== 'undefined') { devTools = [ DevTools.instrument() ] } const store = createStore( reducer, initialState, compose( applyMiddleware( routerMiddleware(history) ), ...devTools ) ) return store }
src/components/icons/DragHandle.js
niekert/soundify
import React from 'react'; import { string } from 'prop-types'; const DragHandle = ({ fill, ...props }) => <svg fill={fill} height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" {...props} > <defs> <path d="M0 0h24v24H0V0z" id="a" /> </defs> <clipPath id="b"> <use overflow="visible" /> </clipPath> <path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z" /> </svg>; DragHandle.propTypes = { fill: string, }; DragHandle.defaultProps = { fill: 'currentColor', }; export default DragHandle;
src/02-Properties.js
sericaia/react-msf-demos
import React from 'react'; class MyPropertiesExample extends React.Component { render() { return ( <div> <h1>Properties</h1> My favourite dish is {this.props.dish}. </div> ); } } MyPropertiesExample.defaultProps = { dish: 'shrimp with pasta' }; MyPropertiesExample.propTypes = { dish: React.PropTypes.string.isRequired }; class MyVodooComponent extends React.Component { render() { return ( <MyPropertiesExample dish="chicken"/> ); } } export default MyPropertiesExample;
test/specs/views/Item/ItemDescription-test.js
vageeshb/Semantic-UI-React
import faker from 'faker' import React from 'react' import * as common from 'test/specs/commonTests' import ItemDescription from 'src/views/Item/ItemDescription' describe('ItemDescription', () => { common.isConformant(ItemDescription) common.rendersChildren(ItemDescription) describe('content prop', () => { it('renders text', () => { const text = faker.hacker.phrase() shallow(<ItemDescription content={text} />) .should.contain.text(text) }) }) })
frontend/src/Components/Table/TableRowButton.js
geogolem/Radarr
import React from 'react'; import Link from 'Components/Link/Link'; import TableRow from './TableRow'; import styles from './TableRowButton.css'; function TableRowButton(props) { return ( <Link className={styles.row} component={TableRow} {...props} /> ); } export default TableRowButton;
src/svg-icons/communication/contact-mail.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationContactMail = (props) => ( <SvgIcon {...props}> <path d="M21 8V7l-3 2-3-2v1l3 2 3-2zm1-5H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2zM8 6c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H2v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1zm8-6h-8V6h8v6z"/> </SvgIcon> ); CommunicationContactMail = pure(CommunicationContactMail); CommunicationContactMail.displayName = 'CommunicationContactMail'; CommunicationContactMail.muiName = 'SvgIcon'; export default CommunicationContactMail;
src/pages/repos.js
geekydatamonkey/hjs-gittagger
'use strict'; import React from 'react'; export default React.createClass({ displayName: 'ReposePage', render() { return ( <main class="container"> <h1>Repos Page</h1> <a href="/"> &larr; back to Public</a> </main> ) } });
node_modules/react-native-svg/elements/Rect.js
MisterZhouZhou/ReactNativeLearing
import React from 'react'; import './Path'; // must import Path first, don`t know why. without this will throw an `Super expression must either be null or a function, not undefined` import createReactNativeComponentClass from 'react-native/Libraries/Renderer/shims/createReactNativeComponentClass.js'; import {pathProps, numberProp} from '../lib/props'; import {RectAttributes} from '../lib/attributes'; import extractProps from '../lib/extract/extractProps'; import Shape from './Shape'; export default class extends Shape { static displayName = 'Rect'; static propTypes = { ...pathProps, x: numberProp.isRequired, y: numberProp.isRequired, width: numberProp.isRequired, height: numberProp.isRequired, rx: numberProp, ry: numberProp }; static defaultProps = { x: 0, y: 0, width: 0, height: 0, rx: 0, ry: 0 }; setNativeProps = (...args) => { this.root.setNativeProps(...args); }; render() { let props = this.props; return <RNSVGRect ref={ele => {this.root = ele;}} {...extractProps({ ...props, x: null, y: null }, this)} x={props.x.toString()} y={props.y.toString()} width={props.width.toString()} height={props.height.toString()} rx={props.rx.toString()} ry={props.ry.toString()} />; } } const RNSVGRect = createReactNativeComponentClass({ validAttributes: RectAttributes, uiViewClassName: 'RNSVGRect' });
components/AddIngredient.ios.js
kkwokwai22/snacktime
import React, { Component } from 'react'; import { Text, View, Image, TextInput, ListView, TouchableHighlight, TouchableOpacity, Switch } from 'react-native'; import helpers from '../helpers/helpers.js'; import styles from '../styles.ios.js'; import FoodpairResults from './FoodpairResults.ios.js'; import AddIngredientCamera from './AddIngredientCamera.ios.js'; import { connect } from 'react-redux'; import { showSearch, rendering } from '../actions/addIngredientActions.ios.js'; import { bindActionCreators } from 'redux'; import * as addIngredient from '../actions/addIngredientActions.ios.js'; class AddIngredient extends Component { constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); const ingredients = props.currentIngredients || props.ingredients; this.state = { currentIngredients: ds.cloneWithRows(ingredients), ingredientToAdd: '' } } addIngredient() { const ingredients = []; for (let ingredient of this.state.currentIngredients._dataBlob.s1) { ingredients.push(ingredient); } ingredients.push(this.state.ingredientToAdd) const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ currentIngredients: ds.cloneWithRows(ingredients), ingredientToAdd: '' }) this.forceUpdate(); } navigateAddIngredientCamera() { this.props.navigator.push({ component: AddIngredientCamera, passProps: { currentIngredients: this.state.currentIngredients._dataBlob.s1, store: this.props.store } }) } removeIngredient(ingredient) { const ingredients = this.state.currentIngredients._dataBlob.s1; const removeIndex = ingredients.indexOf(ingredient); ingredients.splice(removeIndex, 1); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ currentIngredients: ds.cloneWithRows(ingredients) }) this.forceUpdate(); } searchMultipleFoodpairs() { this.props.actions.rendering(); helpers.foodpairing.getFoodID(this.state.currentIngredients._dataBlob.s1) .then( resp => { helpers.foodpairing.getMultipleFoodpairings(resp.data) .then( response => { this.props.actions.rendering(); const ingredients = this.state.currentIngredients._dataBlob.s1; this.props.navigator.push({ component: FoodpairResults, passProps: { foodpairs: response.data, ingredients: ingredients } }) }) .catch( error => { console.log('Error ', error); }) }) .catch( err => { console.log('Error: ', err); }) } goBack() { this.props.navigator.pop(); } render() { const { state, actions } = this.props if (state.rendering) { return ( <Image source= {{uri: 'https://media.blueapron.com/assets/loader/pot-loader-6047abec2ec57c18d848f623c036f7fe80236dce689bb48279036c4f914d0c9e.gif'}} style = {styles.loadingGif} /> ) } if (state.showSearch) { return ( <View style={styles.addIngredientsContainer}> <View style={styles.resultsTitle}> <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}> <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} /> </TouchableHighlight> <Text style={styles.resultsTitleText}>Current Ingredients</Text> </View> <ListView style={styles.addIngredientListView} dataSource={this.state.currentIngredients} renderRow={(ingredient, i) => ( <View style={styles.addIngredientListItem}> <Text style={styles.addIngredientListItemText}>{ingredient}</Text> <TouchableOpacity style={styles.removeListItem} onPress={this.removeIngredient.bind(this, ingredient)} > <Image style={styles.removeIcon} source={require('../public/removeicon.png')} /> </TouchableOpacity> </View> )} /> <TouchableOpacity style={styles.searchIconContainer} onPress={this.searchMultipleFoodpairs.bind(this)} > <Image style={styles.searchIcon} source={require('../public/searchicon.png')} /> </TouchableOpacity> <View style={styles.addMoreIngredientsContainer}> <View style={styles.searchBarPictureFrame}> <TextInput onSubmitEditing={this.addIngredient.bind(this)} style={styles.addIngredientInput} onChangeText={(ingredientToAdd) => this.setState({ingredientToAdd})} value={this.state.ingredientToAdd} placeholder={'Add ingredient'} /> </View> <Switch onValueChange={actions.showSearch} style={styles.addIngredientSwitch} value={state.showSearch} /> </View> </View> ) } else { return ( <View style={styles.addIngredientsContainer}> <View style={styles.resultsTitle}> <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}> <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} /> </TouchableHighlight> <Text style={styles.resultsTitleText}>Current Ingredients</Text> </View> <ListView style={styles.addIngredientListView} dataSource={this.state.currentIngredients} renderRow={(ingredient, i) => ( <View style={styles.addIngredientListItem}> <Text style={styles.addIngredientListItemText}>{ingredient}</Text> <TouchableOpacity style={styles.removeListItem} onPress={this.removeIngredient.bind(this, ingredient)} > <Image style={styles.removeIcon} source={require('../public/removeicon.png')} /> </TouchableOpacity> </View> )} /> <View style={styles.addMoreIngredientsContainer}> <TouchableOpacity style={styles.searchIconContainer} onPress={this.searchMultipleFoodpairs.bind(this)} > <Image style={styles.searchIcon} source={require('../public/searchicon.png')} /> </TouchableOpacity> <TouchableOpacity style={styles.buttonView} onPress={this.navigateAddIngredientCamera.bind(this)}> <Image style={[styles.takePicture]} source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}/> </TouchableOpacity> <Switch onValueChange={actions.showSearch} style={styles.addIngredientSwitch} value={state.showSearch} /> </View> </View> ) } } } export default connect(state => ({ state: state.addIngredient }), (dispatch) => ({ actions: bindActionCreators(addIngredient.default, dispatch) }) )(AddIngredient);
admin/client/App/screens/List/components/ItemsTable/ItemsTableRow.js
benkroeger/keystone
import React from 'react'; import classnames from 'classnames'; import ListControl from '../ListControl'; import { Columns } from 'FieldTypes'; import { DropTarget, DragSource } from 'react-dnd'; import { setDragBase, resetItems, reorderItems, setRowAlert, moveItem, } from '../../actions'; const ItemsRow = React.createClass({ propTypes: { columns: React.PropTypes.array, id: React.PropTypes.any, index: React.PropTypes.number, items: React.PropTypes.object, list: React.PropTypes.object, // Injected by React DnD: isDragging: React.PropTypes.bool, // eslint-disable-line react/sort-prop-types connectDragSource: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDropTarget: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDragPreview: React.PropTypes.func, // eslint-disable-line react/sort-prop-types }, renderRow (item) { const itemId = item.id; const rowClassname = classnames({ 'ItemList__row--dragging': this.props.isDragging, 'ItemList__row--selected': this.props.checkedItems[itemId], 'ItemList__row--manage': this.props.manageMode, 'ItemList__row--success': this.props.rowAlert.success === itemId, 'ItemList__row--failure': this.props.rowAlert.fail === itemId, }); // item fields var cells = this.props.columns.map((col, i) => { var ColumnType = Columns[col.type] || Columns.__unrecognised__; var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined; return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />; }); // add sortable icon when applicable if (this.props.list.sortable) { cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />); } // add delete/check icon when applicable if (!this.props.list.nodelete) { cells.unshift(this.props.manageMode ? ( <ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} /> ) : ( <ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" /> )); } var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>); if (this.props.list.sortable) { return ( // we could add a preview container/image // this.props.connectDragPreview(this.props.connectDropTarget(addRow)) this.props.connectDropTarget(addRow) ); } else { return (addRow); } }, render () { return this.renderRow(this.props.item); }, }); module.exports = exports = ItemsRow; // Expose Sortable /** * Implements drag source. */ const dragItem = { beginDrag (props) { const send = { ...props }; props.dispatch(setDragBase(props.item, props.index)); return { ...send }; }, endDrag (props, monitor, component) { if (!monitor.didDrop()) { props.dispatch(resetItems(props.id)); return; } const page = props.currentPage; const pageSize = props.pageSize; // If we were dropped onto a page change target, then droppedOn.prevSortOrder etc will be // set by that target, and we should use those values. If we were just dropped onto a new row // then we need to calculate these values ourselves. const droppedOn = monitor.getDropResult(); const prevSortOrder = droppedOn.prevSortOrder || props.sortOrder; // To explain the following line, suppose we are on page 3 and there are 10 items per page. // Previous to this page, there are (3 - 1)*10 = 20 items before us. If we have index 6 // on this page, then we're the 7th item to display (index starts from 0), and so we // want to update the display order to 20 + 7 = 27. const newSortOrder = droppedOn.newSortOrder || (page - 1) * pageSize + droppedOn.index + 1; // If we were dropped on a page change target, then droppedOn.gotToPage will be set, and we should // pass this to reorderItems, which will then change the page for the user. props.dispatch(reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage))); }, }; /** * Implements drag target. */ const dropItem = { drop (props, monitor, component) { return { ...props }; }, hover (props, monitor, component) { // reset row alerts if (props.rowAlert.success || props.rowAlert.fail) { props.dispatch(setRowAlert({ reset: true, })); } const dragged = monitor.getItem().index; const over = props.index; // self if (dragged === over) { return; } props.dispatch(moveItem(dragged, over, props)); monitor.getItem().index = over; }, }; /** * Specifies the props to inject into your component. */ function dragProps (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview(), }; } function dropProps (connect) { return { connectDropTarget: connect.dropTarget(), }; }; exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
Example/components/Launch.js
gectorat/react-native-router-flux
import React from 'react'; import {View, Text, StyleSheet} from "react-native"; import Button from "react-native-button"; import {Actions} from "react-native-router-flux"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "transparent", borderWidth: 2, borderColor: 'red', } }); class Launch extends React.Component { render(){ return ( <View {...this.props} style={styles.container}> <Text>Launch page</Text> <Button onPress={()=>Actions.login({data:"Custom data", title:"Custom title" })}>Go to Login page</Button> <Button onPress={Actions.register}>Go to Register page</Button> <Button onPress={Actions.register2}>Go to Register page without animation</Button> <Button onPress={()=>Actions.error("Error message")}>Popup error</Button> <Button onPress={Actions.tabbar}>Go to TabBar page</Button> <Button onPress={Actions.switcher}>Go to switcher page</Button> <Button onPress={Actions.pop}>back</Button> </View> ); } } module.exports = Launch;
docs/src/examples/modules/Accordion/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Advanced from './Advanced' import Types from './Types' import Variations from './Variations' import Usage from './Usage' const AccordionExamples = () => ( <div> <Types /> <Variations /> <Usage /> <Advanced /> </div> ) export default AccordionExamples
app/main.js
henrikra/gym-diary
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import promise from 'redux-promise'; import { Router } from 'react-router'; import createHistory from 'history/lib/createHashHistory'; import reducers from './reducers'; import routes from './routes'; const history = createHistory({ queryKey: false }); const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router history={history} routes={routes} /> </Provider> , document.getElementById('root') );
ui/src/main/js/components/UpdateConfig.js
thinker0/aurora
import React from 'react'; import PanelGroup, { Container, StandardPanelTitle } from 'components/Layout'; import TaskConfig from 'components/TaskConfig'; import UpdateDiff from 'components/UpdateDiff'; import { isNully } from 'utils/Common'; export default function UpdateConfig({ update }) { if (isNully(update.update.instructions.desiredState)) { return null; } else if (update.update.instructions.initialState.length > 0) { return <UpdateDiff update={update} />; } return (<Container> <PanelGroup noPadding title={<StandardPanelTitle title='Update Config' />}> <TaskConfig config={update.update.instructions.desiredState.task} /> </PanelGroup> </Container>); }
mlflow/server/js/src/model-registry/components/ModelVersionPage.js
mlflow/mlflow
import React from 'react'; import { connect } from 'react-redux'; import { getModelVersionApi, updateModelVersionApi, deleteModelVersionApi, transitionModelVersionStageApi, getModelVersionArtifactApi, parseMlModelFile, } from '../actions'; import { getRunApi } from '../../experiment-tracking/actions'; import PropTypes from 'prop-types'; import { getModelVersion, getModelVersionSchemas } from '../reducers'; import { ModelVersionView } from './ModelVersionView'; import { ActivityTypes, MODEL_VERSION_STATUS_POLL_INTERVAL as POLL_INTERVAL } from '../constants'; import Utils from '../../common/utils/Utils'; import { getRunInfo, getRunTags } from '../../experiment-tracking/reducers/Reducers'; import RequestStateWrapper, { triggerError } from '../../common/components/RequestStateWrapper'; import { ErrorView } from '../../common/components/ErrorView'; import { Spinner } from '../../common/components/Spinner'; import { getModelPageRoute, modelListPageRoute } from '../routes'; import { getProtoField } from '../utils'; import { getUUID } from '../../common/utils/ActionUtils'; import _ from 'lodash'; import { PageContainer } from '../../common/components/PageContainer'; export class ModelVersionPageImpl extends React.Component { static propTypes = { // own props history: PropTypes.object.isRequired, match: PropTypes.object.isRequired, // connected props modelName: PropTypes.string.isRequired, version: PropTypes.string.isRequired, modelVersion: PropTypes.object, runInfo: PropTypes.object, runDisplayName: PropTypes.string, getModelVersionApi: PropTypes.func.isRequired, updateModelVersionApi: PropTypes.func.isRequired, transitionModelVersionStageApi: PropTypes.func.isRequired, deleteModelVersionApi: PropTypes.func.isRequired, getRunApi: PropTypes.func.isRequired, apis: PropTypes.object.isRequired, getModelVersionArtifactApi: PropTypes.func.isRequired, parseMlModelFile: PropTypes.func.isRequired, schema: PropTypes.object, }; initGetModelVersionDetailsRequestId = getUUID(); getRunRequestId = getUUID(); updateModelVersionRequestId = getUUID(); transitionModelVersionStageRequestId = getUUID(); getModelVersionDetailsRequestId = getUUID(); initGetMlModelFileRequestId = getUUID(); state = { criticalInitialRequestIds: [ this.initGetModelVersionDetailsRequestId, this.initGetMlModelFileRequestId, ], }; pollingRelatedRequestIds = [this.getModelVersionDetailsRequestId, this.getRunRequestId]; hasPendingPollingRequest = () => this.pollingRelatedRequestIds.every((requestId) => { const request = this.props.apis[requestId]; return Boolean(request && request.active); }); loadData = (isInitialLoading) => { const promises = [this.getModelVersionDetailAndRunInfo(isInitialLoading)]; return Promise.all([promises]); }; pollData = () => { const { modelName, version, history } = this.props; if (!this.hasPendingPollingRequest() && Utils.isBrowserTabVisible()) { return this.loadData().catch((e) => { if (e.getErrorCode() === 'RESOURCE_DOES_NOT_EXIST') { Utils.logErrorAndNotifyUser(e); this.props.deleteModelVersionApi(modelName, version, undefined, true); history.push(getModelPageRoute(modelName)); } else { console.error(e); } }); } return Promise.resolve(); }; // We need to do this because currently the ModelVersionDetailed we got does not contain // experimentId. We need experimentId to construct a link to the source run. This workaround can // be removed after the availability of experimentId. getModelVersionDetailAndRunInfo(isInitialLoading) { const { modelName, version } = this.props; return this.props .getModelVersionApi( modelName, version, isInitialLoading === true ? this.initGetModelVersionDetailsRequestId : this.getModelVersionDetailsRequestId, ) .then(({ value }) => { if (value && !value[getProtoField('model_version')].run_link) { this.props.getRunApi(value[getProtoField('model_version')].run_id, this.getRunRequestId); } }); } // We need this for getting mlModel artifact file, // this will be replaced with a single backend call in the future when supported getModelVersionMlModelFile() { const { modelName, version } = this.props; this.props .getModelVersionArtifactApi(modelName, version) .then((content) => this.props.parseMlModelFile( modelName, version, content.value, this.initGetMlModelFileRequestId, ), ) .catch(() => { // Failure of this call chain should not block the page. Here we remove // `initGetMlModelFileRequestId` from `criticalInitialRequestIds` // to unblock RequestStateWrapper from rendering its content this.setState((prevState) => ({ criticalInitialRequestIds: _.without( prevState.criticalInitialRequestIds, this.initGetMlModelFileRequestId, ), })); }); } handleStageTransitionDropdownSelect = (activity, archiveExistingVersions) => { const { modelName, version } = this.props; const toStage = activity.to_stage; if (activity.type === ActivityTypes.APPLIED_TRANSITION) { this.props .transitionModelVersionStageApi( modelName, version.toString(), toStage, archiveExistingVersions, this.transitionModelVersionStageRequestId, ) .then(this.loadData) .catch(Utils.logErrorAndNotifyUser); } }; handleEditDescription = (description) => { const { modelName, version } = this.props; return this.props .updateModelVersionApi(modelName, version, description, this.updateModelVersionRequestId) .then(this.loadData) .catch(console.error); }; componentDidMount() { this.loadData(true).catch(console.error); this.pollIntervalId = setInterval(this.pollData, POLL_INTERVAL); this.getModelVersionMlModelFile(); } componentWillUnmount() { clearTimeout(this.pollIntervalId); } render() { const { modelName, version, modelVersion, runInfo, runDisplayName, history, schema, } = this.props; return ( <PageContainer> <RequestStateWrapper requestIds={this.state.criticalInitialRequestIds}> {(loading, hasError, requests) => { if (hasError) { clearInterval(this.pollIntervalId); if (Utils.shouldRender404(requests, this.state.criticalInitialRequestIds)) { return ( <ErrorView statusCode={404} subMessage={`Model ${modelName} v${version} does not exist`} fallbackHomePageReactRoute={modelListPageRoute} /> ); } // TODO(Zangr) Have a more generic boundary to handle all errors, not just 404. triggerError(requests); } else if (loading) { return <Spinner />; } else if (modelVersion) { // Null check to prevent NPE after delete operation return ( <ModelVersionView modelName={modelName} modelVersion={modelVersion} runInfo={runInfo} runDisplayName={runDisplayName} handleEditDescription={this.handleEditDescription} deleteModelVersionApi={this.props.deleteModelVersionApi} history={history} handleStageTransitionDropdownSelect={this.handleStageTransitionDropdownSelect} schema={schema} /> ); } return null; }} </RequestStateWrapper> </PageContainer> ); } } const mapStateToProps = (state, ownProps) => { const modelName = decodeURIComponent(ownProps.match.params.modelName); const { version } = ownProps.match.params; const modelVersion = getModelVersion(state, modelName, version); const schema = getModelVersionSchemas(state, modelName, version); let runInfo = null; if (modelVersion && !modelVersion.run_link) { runInfo = getRunInfo(modelVersion && modelVersion.run_id, state); } const tags = runInfo && getRunTags(runInfo.getRunUuid(), state); const runDisplayName = tags && Utils.getRunDisplayName(tags, runInfo.getRunUuid()); const { apis } = state; return { modelName, version, modelVersion, schema, runInfo, runDisplayName, apis, }; }; const mapDispatchToProps = { getModelVersionApi, updateModelVersionApi, transitionModelVersionStageApi, getModelVersionArtifactApi, parseMlModelFile, deleteModelVersionApi, getRunApi, }; export const ModelVersionPage = connect(mapStateToProps, mapDispatchToProps)(ModelVersionPageImpl);
src/NavbarBrand.js
egauci/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import tbsUtils from './utils/bootstrapUtils'; class NavbarBrand extends React.Component { render() { const {className, children, ...props} = this.props; let { $bs_navbar_bsClass: bsClass = 'navbar' } = this.context; let brandClasses = tbsUtils.prefix({ bsClass }, 'brand'); if (React.isValidElement(children)) { return React.cloneElement(children, { className: classNames( children.props.className, className, brandClasses ) }); } return ( <span {...props} className={classNames(className, brandClasses)}> {children} </span> ); } } NavbarBrand.contextTypes = { $bs_navbar_bsClass: React.PropTypes.string }; export default NavbarBrand;
admin/client/App/shared/CreateForm.js
brianjd/keystone
/** * The form that's visible when "Create <ItemName>" is clicked on either the * List screen or the Item screen */ import React from 'react'; import assign from 'object-assign'; import vkey from 'vkey'; import AlertMessages from './AlertMessages'; import { Fields } from 'FieldTypes'; import InvalidFieldType from './InvalidFieldType'; import { Button, Form, Modal } from '../elemental'; const CreateForm = React.createClass({ displayName: 'CreateForm', propTypes: { err: React.PropTypes.object, isOpen: React.PropTypes.bool, list: React.PropTypes.object, onCancel: React.PropTypes.func, onCreate: React.PropTypes.func, }, getDefaultProps () { return { err: null, isOpen: false, }; }, getInitialState () { // Set the field values to their default values when first rendering the // form. (If they have a default value, that is) var values = {}; Object.keys(this.props.list.fields).forEach(key => { var field = this.props.list.fields[key]; var FieldComponent = Fields[field.type]; values[field.path] = FieldComponent.getDefaultValue(field); }); return { values: values, alerts: {}, }; }, componentDidMount () { document.body.addEventListener('keyup', this.handleKeyPress, false); }, componentWillUnmount () { document.body.removeEventListener('keyup', this.handleKeyPress, false); }, handleKeyPress (evt) { if (vkey[evt.keyCode] === '<escape>') { this.props.onCancel(); } }, // Handle input change events handleChange (event) { var values = assign({}, this.state.values); values[event.path] = event.value; this.setState({ values: values, }); }, // Set the props of a field getFieldProps (field) { var props = assign({}, field); props.value = this.state.values[field.path]; props.values = this.state.values; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, // Create a new item when the form is submitted submitForm (event) { event.preventDefault(); const createForm = event.target; const formData = new FormData(createForm); this.props.list.createItem(formData, (err, data) => { if (data) { if (this.props.onCreate) { this.props.onCreate(data); } else { // Clear form this.setState({ values: {}, alerts: { success: { success: 'Item created', }, }, }); } } else { if (!err) { err = { error: 'connection error', }; } // If we get a database error, show the database error message // instead of only saying "Database error" if (err.error === 'database error') { err.error = err.detail.errmsg; } this.setState({ alerts: { error: err, }, }); } }); }, // Render the form itself renderForm () { if (!this.props.isOpen) return; var form = []; var list = this.props.list; var nameField = this.props.list.nameField; var focusWasSet; // If the name field is an initial one, we need to render a proper // input for it if (list.nameIsInitial) { var nameFieldProps = this.getFieldProps(nameField); nameFieldProps.autoFocus = focusWasSet = true; if (nameField.type === 'text') { nameFieldProps.className = 'item-name-field'; nameFieldProps.placeholder = nameField.label; nameFieldProps.label = ''; } form.push(React.createElement(Fields[nameField.type], nameFieldProps)); } // Render inputs for all initial fields Object.keys(list.initialFields).forEach(key => { var field = list.fields[list.initialFields[key]]; // If there's something weird passed in as field type, render the // invalid field type component if (typeof Fields[field.type] !== 'function') { form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } // Get the props for the input field var fieldProps = this.getFieldProps(field); // If there was no focusRef set previously, set the current field to // be the one to be focussed. Generally the first input field, if // there's an initial name field that takes precedence. if (!focusWasSet) { fieldProps.autoFocus = focusWasSet = true; } form.push(React.createElement(Fields[field.type], fieldProps)); }); return ( <Form layout="horizontal" onSubmit={this.submitForm}> <Modal.Header text={'Create a new ' + list.singular} showCloseButton /> <Modal.Body> <AlertMessages alerts={this.state.alerts} /> {form} </Modal.Body> <Modal.Footer> <Button color="success" type="submit" data-button-type="submit"> Create </Button> <Button variant="link" color="cancel" data-button-type="cancel" onClick={this.props.onCancel} > Cancel </Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal.Dialog isOpen={this.props.isOpen} onClose={this.props.onCancel} backdropClosesModal > {this.renderForm()} </Modal.Dialog> ); }, }); module.exports = CreateForm;