path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
node_modules/native-base/Components/Widgets/Container.js
crod93/googlePlacesEx-react-native
/* @flow */ 'use strict'; import React from 'react'; import {View, Image} from 'react-native'; import ViewNB from './View'; import Header from './Header'; import Content from './Content'; import Footer from './Footer'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import _ from 'lodash'; import computeProps from '../../Utils/computeProps'; export default class Container extends NativeBaseComponent { renderHeader() { if(Array.isArray(this.props.children)) { return _.find(this.props.children, function(item) { if(item && item.type == Header) { return true; } }); } else { if(this.props.children && this.props.children.type == Header) { return this.props.children; } } } renderContent() { if(Array.isArray(this.props.children)) { return _.find(this.props.children, function(item) { if(item && (item.type == ViewNB || item.type == Content || item.type == Image || item.type == View)) { return true; } }); } else { if(this.props.children && (this.props.children.type == Content || this.props.children.type == ViewNB || this.props.children.type == View || this.props.children.type == Image)) { return this.props.children; } } } renderFooter() { if(Array.isArray(this.props.children)) { return _.find(this.props.children, function(item) { if(item && item.type == Footer) { return true; } }); } else { if(this.props.children && this.props.children.type == Footer) { return this.props.children; } } } prepareRootProps() { var type = { flex: 1 } var defaultProps = { style: type } return computeProps(this.props, defaultProps); } render() { return( <View {...this.prepareRootProps()}> <View> {this.renderHeader()} </View> <View style={{flex:1}}> {this.renderContent()} </View> <View> {this.renderFooter()} </View> </View> ); } }
js/components/addLesson/AlbumsScreen.android.js
leehyoumin/asuraCham
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, Platform } from 'react-native'; import ImagePicker from 'react-native-image-picker'; export default class App extends React.Component { onChange = (value) =>{ this.props.onChange(value); } state = { saveSource: this.props.avatarSource, avatarSource: this.props.avatarSource }; selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { var source; var source2; // You can display the image using either: //source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true}; //Or: if (Platform.OS === 'android') { source = {uri: response.uri, isStatic: true}; source2 = response.uri; } else { source = {uri: response.uri.replace('file://', ''), isStatic: true}; source2 = response.uri.replace('file://', ''); } this.setState({ avatarSource: source, saveSource: source2 }); console.log("proops",this.props.avatarSource); this.onChange(this.state.saveSource); console.log("avda",this.state.saveSource); console.log("avda",this.state.avatarSource); } }); } render() { return ( <View> <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> <View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}> { this.state.avatarSource === null ? <Text>Select a Photo</Text> : <Image style={styles.avatar} source={this.state.avatarSource} /> } </View> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF' }, avatarContainer: { borderColor: '#9B9B9B', borderWidth: 1 / PixelRatio.get(), justifyContent: 'center', alignItems: 'center' }, avatar: { width: 100, height: 100 } });
src/server.js
tpphu/react-pwa
import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import favicon from 'serve-favicon'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import httpProxy from 'http-proxy'; import path from 'path'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import { Provider } from 'components'; import config from 'config'; import createStore from 'redux/create'; import ApiClient from 'helpers/ApiClient'; import Html from 'helpers/Html'; import getRoutes from 'routes'; import { createApp } from 'app'; process.on('unhandledRejection', error => console.error(error)); const targetUrl = `http://${config.apiHost}:${config.apiPort}`; const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(cookieParser()); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.get('/manifest.json', (req, res) => res.sendFile(path.join(__dirname, '..', 'static', 'manifest.json'))); app.use('/dist/service-worker.js', (req, res, next) => { res.setHeader('Service-Worker-Allowed', '/'); return next(); }); app.use(express.static(path.join(__dirname, '..', 'static'))); app.use((req, res, next) => { res.setHeader('X-Forwarded-For', req.ip); return next(); }); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, { target: targetUrl }); }); app.use('/ws', (req, res) => { proxy.web(req, res, { target: `${targetUrl}/ws` }); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, { 'content-type': 'application/json' }); } const json = { error: 'proxy_error', reason: error.message }; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const providers = { client: new ApiClient(req), app: createApp(req), restApp: createApp(req) }; const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, providers); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send(`<!doctype html> ${ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store} />)}`); } if (__DISABLE_SSR__) { return hydrateOnClient(); } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { const redirect = ::res.redirect; loadOnServer({ ...renderProps, store, helpers: { ...providers, redirect } }).then(() => { if (res.headersSent) return; const component = ( <Provider store={store} app={providers.app} restApp={providers.restApp} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = { userAgent: req.headers['user-agent'] }; res.send(`<!doctype html> ${ReactDOM.renderToString( <Html assets={webpackIsomorphicTools.assets()} component={component} store={store} /> )}`); }).catch(mountError => { console.error('MOUNT ERROR:', pretty.render(mountError)); res.status(500); hydrateOnClient(); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, err => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/svg-icons/action/highlight-off.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHighlightOff = (props) => ( <SvgIcon {...props}> <path d="M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ActionHighlightOff = pure(ActionHighlightOff); ActionHighlightOff.displayName = 'ActionHighlightOff'; ActionHighlightOff.muiName = 'SvgIcon'; export default ActionHighlightOff;
app/components/NewsletterList/index.js
rjgreaves/finances
/** * * NewsletterList * */ import React from 'react'; import styles from './styles.css'; function NewsletterList() { return ( <div className={styles.newsletterList}> </div> ); } export default NewsletterList;
app/components/icons/React/index.js
yasserhennawi/yasserhennawi
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'utils/styled-components'; const StyledSVG = styled.svg` fill: #fff; stroke-width: 14; `; export default function ReactIcon({ onClick }) { return ( <StyledSVG onClick={onClick} width="100%" viewBox="0 0 500 500" enable-background="new 0 0 500 500" stroke="#53C1DE" stroke-width="20" > <ellipse transform="matrix(-0.866 -0.5 0.5 -0.866 342.1488 591.3323)" fill="none" stroke="#53C1DE" cx="250.3" cy="249.8" rx="81.7" ry="212.7" /> <ellipse fill="none" stroke="#53C1DE" cx="250.3" cy="250" rx="212.7" ry="81.7" /> <ellipse transform="matrix(0.866 -0.5 0.5 0.866 -91.3715 158.6236)" fill="none" stroke="#53C1DE" cx="250.3" cy="249.8" rx="81.7" ry="212.7" /> <path fill="#53C1DE" d="M250.1,207.3c23.9,0,43.2,19.3,43.2,43.2c0,23.9-19.3,43.2-43.2,43.2c-23.9,0-43.2-19.3-43.2-43.2 C206.9,226.6,226.3,207.3,250.1,207.3" /> </StyledSVG> ); } ReactIcon.propTypes = { fill: PropTypes.string, onClick: PropTypes.func, };
Libraries/Components/WebView/WebView.ios.js
formatlos/react-native
/** * 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. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var PropTypes = require('prop-types'); var ReactNative = require('ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ViewPropTypes = require('ViewPropTypes'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...ViewPropTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * A function that is invoked when the webview calls `window.postMessage`. * Setting this property will inject a `postMessage` global into your * webview, but will still call pre-existing values of `postMessage`. * * `window.postMessage` accepts one argument, `data`, which will be * available on the event object, `event.nativeEvent.data`. `data` * must be a string. */ onMessage: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: ViewPropTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to enable third party cookies in the `WebView`. Used on * Android Lollipop and above only as third party cookies are enabled by * default on Android Kitkat and below and on iOS. The default value is `true`. * @platform android */ thirdPartyCookiesEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, /** * Function that accepts a string that will be passed to the WebView and * executed immediately as JavaScript. */ injectJavaScript: PropTypes.func, /** * Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin. * * Possible values for `mixedContentMode` are: * * - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin. * - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure. * - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content. * @platform android */ mixedContentMode: PropTypes.oneOf([ 'never', 'always', 'compatibility' ]), }; static defaultProps = { scalesPageToFit: true, }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } const messagingEnabled = typeof this.props.onMessage === 'function'; var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} messagingEnabled={messagingEnabled} onMessage={this._onMessage} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * Posts a message to the web view, which will emit a `message` event. * Accepts one argument, `data`, which must be a string. * * In your webview, you'll need to something like the following. * * ```js * document.addEventListener('message', e => { document.title = e.data; }); * ``` */ postMessage = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.postMessage, [String(data)] ); }; /** * Injects a javascript string into the referenced WebView. Deliberately does not * return a response because using eval() to return a response breaks this method * on pages with a Content Security Policy that disallows eval(). If you need that * functionality, look into postMessage/onMessage. */ injectJavaScript = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.injectJavaScript, [data] ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; _onMessage = (event: Event) => { var {onMessage} = this.props; onMessage && onMessage(event); } } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, onMessage: true, messagingEnabled: PropTypes.bool, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
squealy/squealy-web/src/Utils.js
dakshgautam/squealy
import React, { Component } from 'react'; import { GOOGLE_CHART_TYPE_OPTIONS } from './Constant' /*!************************************************************************* [Utils.js] *****************************************************************************/ /* global define */ /** * Defines all the types necessary for making api calls. * module src/Utils */ /** * @module Utils * @params {String} Url - Provides the post url * @params {Object} data - The object that represents the contents of the * request being sent */ export function postApiRequest(uri, data, onSuccessCallback, onFailureCallback, callbackParmas) { data = jsonStringfy(data) apiCall(uri, data, 'POST', onSuccessCallback, onFailureCallback, callbackParmas) } export function baseUrl() { return window.location.origin + '/' } /** * @module Utils * @params {String} Url - Provides the post url * @params {Object} data - The object that represents the contents of the * request being sent */ export function getApiRequest(uri, data, onSuccessCallback, onFailureCallback, callbackParmas, interval) { let payload = data ? {payload: jsonStringfy(data)} : data apiCall(uri, payload, 'GET', onSuccessCallback, onFailureCallback, callbackParmas, interval) } /** * description: converts a JavaScript value to a JSON string * @module Utils * @params {Object} data - The object that represents the contents of the * request being sent */ function jsonStringfy(data) { return JSON.stringify(data) } /** * description: Ajax call for post/get api * Created a method to be called to get the data and * stop the interval once the promise is resolved and user receives the data * @module Utils * @params {String} Url - Provides the post url * @params {Object} data - The object that represents the contents of the * request being sent * @params {String} methodType - Defines type of request to be made * @params {Function} onSuccess - Success callback function * @params {Function} onFailure - Failure callback function * TODO: Need to add a callback function on success and failure */ export function apiCall(uri, data, methodType, onSuccess, onFailure, callbackParmas=null) { const csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!this.crossDomain) { xhr.setRequestHeader('X-CSRFToken', csrftoken); } } }); $.ajax({ url: uri, method: methodType, contentType: 'application/json', data: data, success: function (response) { if (onSuccess) { if(callbackParmas){ onSuccess(response, callbackParmas) }else { onSuccess(response) } } }, error: function (error) { if (onFailure) { onFailure(error) } } }) } function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export function getEmptyApiDefinition() { return { id: null, name: 'first chart', url: 'first-chart', query: '', parameters: [], testParameters: {}, validations: [], transformations: [], transpose: false, type: 'ColumnChart', options: {}, chartData: {}, pivotColumn: undefined, metric: undefined, columnsToMerge: undefined, newColumnName: '', apiErrorMsg: null, database: null } } export function getEmptyFilterDefinition() { return { id: null, name: '', url: '', database: '', query: '', apiErrorMsg: '', filterData: [], parameters: [] } } export function getEmptyWidgetDefinition() { return { width: 4, height: 20, top: 7, left: 1, title: 'Chart Title', chartType: GOOGLE_CHART_TYPE_OPTIONS[7].value, chartStyles: {}, api_url: '', apiParams: {} } } export function getEmptyUserInfo() { return { 'first_name': '', 'last_name': '', 'name': 'none', 'email': '', 'can_add_chart': false, 'can_delete_chart': false } } export function getEmptyParamDefinition(apiIndex) { return { name: '', order: 0, type: 1, data_type: 'string', mandatory: false, default_value: '', kwargs: { format: '' }, test_value: '', dropdown_api: '', is_parameterized: false } } function processParamDef(definitions) { let appliedDef = {} if (definitions.length) { definitions.map((data) => { appliedDef[data.name] = { type: data.type, optional: data.optional, default_value: data.default_value, isParamDefCustom: data.isParamDefCustom } if (data.hasOwnProperty('kwargs')) { appliedDef[data.name].kwargs = data.kwargs } }) } return appliedDef } // The following function loads the google charts JS files export function googleChartLoader(onSuccess, version, packages) { var options = { dataType: 'script', cache: true, url: 'https://www.gstatic.com/charts/loader.js', }; jQuery.ajax(options).done(function(){ google.charts.load(version || 'current', { packages: packages || ['corechart'], 'callback': onSuccess }); }); } function execRegexGroupedMulValues(regex, text, result) { let match = regex.exec(text), newResult = result.slice() while (match !== null) { if (newResult.indexOf(match[1]) === -1) { newResult.push(match[1]) } match = regex.exec(text) } return newResult } export function fetchQueryParamsFromQuery(text) { let regExpForParams = /{{\s*params\.([^\s}%]+)\s*}}/g, regExpForExp = /{%[^(%})]*params\.([^\s}%]+)[^({%)]*%}/g, paramsArray = [] paramsArray = execRegexGroupedMulValues(regExpForParams, text, paramsArray) paramsArray = execRegexGroupedMulValues(regExpForExp, text, paramsArray) return paramsArray } export function fetchSessionParamsFromQuery(text) { let regExpForParams = /{{\s*user\.([^\s}%]+)\s*}}/g, regExpForExp = /{%[^(%})]*user\.([^\s}%]+)[^({%)]*%}/g, paramsArray = [] paramsArray = execRegexGroupedMulValues(regExpForParams, text, paramsArray) paramsArray = execRegexGroupedMulValues(regExpForExp, text, paramsArray) return paramsArray } export function isJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } export function checkObjectAlreadyExists (data, keyName, value) { for (let i = 0; i < data.length; i++) { if (data[i].hasOwnProperty(keyName) && data[i][keyName] === value) { return i } } return -1 } export function formatTestParameters (paramDefintion, key, valueKey) { let testParams = { params: {}, user: {} } paramDefintion.map((param) => { if (param.type === 2) { testParams.user[param[key]] = param[valueKey] } else { testParams.params[param[key]] = param[valueKey] } }) return testParams } export function getUrlParams() { let pageURL = decodeURIComponent(window.location.search.substring(1)) if(pageURL === '') { return null } return JSON.parse('{"' + decodeURI(pageURL).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}') } export function setUrlParams(newParams) { let queryString = Object.keys(newParams).map(function(k) { return encodeURIComponent(k) + '=' + encodeURIComponent(newParams[k]) }).join('&') var newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + queryString; window.history.replaceState({path: newurl},'',newurl); } export function formatForDropdown(data) { let result = [] data.map((val) => { result.push({ label: val[0], value: val[0] }) }) return result } export const MainErrorMessage = ({ errorComponent }) => { return ( <div className='full-height no-charts'> <div className='col-md-6 col-md-offset-3 instructions'> <h2> No {errorComponent} to show. </h2> <h6>Add new {errorComponent} if you see the plus icon in the side menu, or ask your administrator to add one for you.</h6> </div> </div> ) }
__storybook__/stories/test-form.js
jcurtis/rcforms
import React from 'react' import {storiesOf, action} from '@kadira/storybook' import TestForm from '../test-form' storiesOf('TestForm', module) .add('empty', () => ( <TestForm onSubmit={action('onSubmit')} /> ))
web/src/modules/icons/Cinema.js
HobartMakers/DigitalWalkingTours
import React from 'react' const CinemaIcon = props => <svg width="15px" height="15px" viewBox="0 0 15 15" style={{enableBackground: 'new 0 0 15 15',}} {...props} > <path d="M14,7.5v2c0,0.2761-0.2239,0.5-0.5,0.5S13,9.7761,13,9.5c0,0,0.06-0.5-1-0.5h-1v2.5c0,0.2761-0.2239,0.5-0.5,0.5h-8 C2.2239,12,2,11.7761,2,11.5v-4C2,7.2239,2.2239,7,2.5,7h8C10.7761,7,11,7.2239,11,7.5V8h1c1.06,0,1-0.5,1-0.5 C13,7.2239,13.2239,7,13.5,7S14,7.2239,14,7.5z M4,3C2.8954,3,2,3.8954,2,5s0.8954,2,2,2s2-0.8954,2-2S5.1046,3,4,3z M4,6 C3.4477,6,3,5.5523,3,5s0.4477-1,1-1s1,0.4477,1,1S4.5523,6,4,6z M8.5,2C7.1193,2,6,3.1193,6,4.5S7.1193,7,8.5,7S11,5.8807,11,4.5 S9.8807,2,8.5,2z M8.5,6C7.6716,6,7,5.3284,7,4.5S7.6716,3,8.5,3S10,3.6716,10,4.5S9.3284,6,8.5,6z"/> </svg> export default CinemaIcon
Paths/React/05.Building Scalable React Apps/7-react-boilerplate-building-scalable-apps-m7-exercise-files/After/app/containers/LoginContainer/index.js
phiratio/Pluralsight-materials
/* * * LoginContainer * */ import React from 'react'; import { connect } from 'react-redux'; import selectLoginContainer from './selectors'; import Login from '../../components/Login'; import { login, cancelLogin } from './actions'; export class LoginContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <Login {...this.props} /> </div> ); } } const mapStateToProps = selectLoginContainer(); function mapDispatchToProps(dispatch) { return { login: (email) => dispatch(login(email)), cancelLogin: () => dispatch(cancelLogin()), }; } export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer);
nailgun/static/views/layout.js
eayunstack/fuel-web
/* * Copyright 2014 Mirantis, Inc. * * 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 $ from 'jquery'; import _ from 'underscore'; import i18n from 'i18n'; import Backbone from 'backbone'; import React from 'react'; import utils from 'utils'; import models from 'models'; import {backboneMixin, pollingMixin, dispatcherMixin} from 'component_mixins'; import {Popover} from 'views/controls'; import {ChangePasswordDialog, ShowNodeInfoDialog} from 'views/dialogs'; export var Navbar = React.createClass({ mixins: [ dispatcherMixin('updateNodeStats', 'updateNodeStats'), dispatcherMixin('updateNotifications', 'updateNotifications'), backboneMixin('user'), backboneMixin('version'), backboneMixin('statistics'), backboneMixin('notifications', 'update change:status'), pollingMixin(20) ], togglePopover(popoverName) { return _.memoize((visible) => { this.setState((previousState) => { var nextState = {}; var key = popoverName + 'PopoverVisible'; nextState[key] = _.isBoolean(visible) ? visible : !previousState[key]; return nextState; }); }); }, setActive(url) { this.setState({activeElement: url}); }, shouldDataBeFetched() { return this.props.user.get('authenticated'); }, fetchData() { return $.when(this.props.statistics.fetch(), this.props.notifications.fetch({limit: this.props.notificationsDisplayCount})); }, updateNodeStats() { return this.props.statistics.fetch(); }, updateNotifications() { return this.props.notifications.fetch({limit: this.props.notificationsDisplayCount}); }, componentDidMount() { this.props.user.on('change:authenticated', (model, value) => { if (value) { this.startPolling(); } else { this.stopPolling(); this.props.statistics.clear(); this.props.notifications.reset(); } }); }, getDefaultProps() { return { notificationsDisplayCount: 5, elements: [ {label: 'environments', url: '#clusters'}, {label: 'equipment', url: '#equipment'}, {label: 'releases', url: '#releases'}, {label: 'plugins', url: '#plugins'}, {label: 'support', url: '#support'} ] }; }, getInitialState() { return {}; }, scrollToTop() { $('html, body').animate({scrollTop: 0}, 'fast'); }, render() { var unreadNotificationsCount = this.props.notifications.where({status: 'unread'}).length; var authenticationEnabled = this.props.version.get('auth_required') && this.props.user.get('authenticated'); return ( <div className='navigation-box'> <div className='navbar-bg'></div> <nav className='navbar navbar-default' role='navigation'> <div className='row'> <div className='navbar-header col-xs-2'> <a className='navbar-logo' href='#'></a> </div> <div className='col-xs-6'> <ul className='nav navbar-nav pull-left'> {_.map(this.props.elements, (element) => { return ( <li className={utils.classNames({active: this.props.activeElement == element.url.slice(1)})} key={element.label}> <a href={element.url}> {i18n('navbar.' + element.label, {defaultValue: element.label})} </a> </li> ); })} </ul> </div> <div className='col-xs-4'> <ul className={utils.classNames({ 'nav navbar-icons pull-right': true, 'with-auth': authenticationEnabled, 'without-auth': !authenticationEnabled })}> <li key='language-icon' className='language-icon' onClick={this.togglePopover('language')} > <div className='language-text'>{i18n.getLocaleName(i18n.getCurrentLocale())}</div> </li> <li key='statistics-icon' className={'statistics-icon ' + (this.props.statistics.get('unallocated') ? '' : 'no-unallocated')} onClick={this.togglePopover('statistics')} > {!!this.props.statistics.get('unallocated') && <div className='unallocated'>{this.props.statistics.get('unallocated')}</div> } <div className='total'>{this.props.statistics.get('total')}</div> </li> {authenticationEnabled && <li key='user-icon' className='user-icon' onClick={this.togglePopover('user')} ></li> } <li key='notifications-icon' className='notifications-icon' onClick={this.togglePopover('notifications')} > <span className={utils.classNames({badge: true, visible: unreadNotificationsCount})}> {unreadNotificationsCount} </span> </li> {this.state.languagePopoverVisible && <LanguagePopover key='language-popover' toggle={this.togglePopover('language')} /> } {this.state.statisticsPopoverVisible && <StatisticsPopover key='statistics-popover' statistics={this.props.statistics} toggle={this.togglePopover('statistics')} /> } {this.state.userPopoverVisible && <UserPopover key='user-popover' user={this.props.user} toggle={this.togglePopover('user')} /> } {this.state.notificationsPopoverVisible && <NotificationsPopover key='notifications-popover' notifications={this.props.notifications} displayCount={this.props.notificationsDisplayCount} toggle={this.togglePopover('notifications')} /> } </ul> </div> </div> </nav> <div className='page-up' onClick={this.scrollToTop} /> </div> ); } }); var LanguagePopover = React.createClass({ changeLocale(locale, e) { e.preventDefault(); this.props.toggle(false); _.defer(() => { i18n.setLocale(locale); location.reload(); }); }, render() { var currentLocale = i18n.getCurrentLocale(); return ( <Popover {...this.props} className='language-popover'> <ul className='nav nav-pills nav-stacked'> {_.map(i18n.getAvailableLocales(), (locale) => { return ( <li key={locale} className={utils.classNames({active: locale == currentLocale})}> <a onClick={_.partial(this.changeLocale, locale)}> {i18n.getLanguageName(locale)} </a> </li> ); })} </ul> </Popover> ); } }); var StatisticsPopover = React.createClass({ mixins: [backboneMixin('statistics')], render() { return ( <Popover {...this.props} className='statistics-popover'> <div className='list-group'> <li className='list-group-item'> <span className='badge'>{this.props.statistics.get('unallocated')}</span> {i18n('navbar.stats.unallocated', {count: this.props.statistics.get('unallocated')})} </li> <li className='list-group-item text-success font-semibold'> <span className='badge bg-green'>{this.props.statistics.get('total')}</span> <a href='#equipment'> {i18n('navbar.stats.total', {count: this.props.statistics.get('total')})} </a> </li> </div> </Popover> ); } }); var UserPopover = React.createClass({ mixins: [backboneMixin('user')], showChangePasswordDialog() { this.props.toggle(false); ChangePasswordDialog.show(); }, logout() { this.props.toggle(false); app.logout(); }, render() { return ( <Popover {...this.props} className='user-popover'> <div className='username'>{i18n('common.username')}:</div> <h3 className='name'>{this.props.user.get('username')}</h3> <div className='clearfix'> <button className='btn btn-default btn-sm pull-left' onClick={this.showChangePasswordDialog}> <i className='glyphicon glyphicon-user'></i> {i18n('common.change_password')} </button> <button className='btn btn-info btn-sm pull-right btn-logout' onClick={this.logout}> <i className='glyphicon glyphicon-off'></i> {i18n('common.logout')} </button> </div> </Popover> ); } }); var NotificationsPopover = React.createClass({ mixins: [backboneMixin('notifications')], showNodeInfo(id) { this.props.toggle(false); var node = new models.Node({id: id}); node.fetch(); ShowNodeInfoDialog.show({node: node}); }, markAsRead() { var notificationsToMark = new models.Notifications(this.props.notifications.where({status: 'unread'})); if (notificationsToMark.length) { this.setState({unreadNotificationsIds: notificationsToMark.pluck('id')}); notificationsToMark.toJSON = function() { return notificationsToMark.map((notification) => { notification.set({status: 'read'}); return _.pick(notification.attributes, 'id', 'status'); }, this); }; Backbone.sync('update', notificationsToMark); } }, componentDidMount() { this.markAsRead(); }, getInitialState() { return {unreadNotificationsIds: []}; }, renderNotification(notification) { var topic = notification.get('topic'); var nodeId = notification.get('node_id'); var notificationClasses = { notification: true, 'text-danger': topic == 'error', 'text-warning': topic == 'warning', clickable: nodeId, unread: notification.get('status') == 'unread' || _.contains(this.state.unreadNotificationsIds, notification.id) }; var iconClass = { error: 'glyphicon-exclamation-sign', warning: 'glyphicon-warning-sign', discover: 'glyphicon-bell' }[topic] || 'glyphicon-info-sign'; return ( <div key={notification.id} className={utils.classNames(notificationClasses)}> <i className={'glyphicon ' + iconClass}></i> <p dangerouslySetInnerHTML={{__html: utils.urlify(notification.escape('message'))}} onClick={nodeId && _.partial(this.showNodeInfo, nodeId)} /> </div> ); }, render() { var showMore = Backbone.history.getHash() != 'notifications'; var notifications = this.props.notifications.take(this.props.displayCount); return ( <Popover {...this.props} className='notifications-popover'> {_.map(notifications, this.renderNotification)} {showMore && <div className='show-more'> <a href='#notifications'>{i18n('notifications_popover.view_all_button')}</a> </div> } </Popover> ); } }); export var Footer = React.createClass({ mixins: [backboneMixin('version')], render() { var version = this.props.version; return ( <div className='footer'> {_.contains(version.get('feature_groups'), 'mirantis') && [ <a key='logo' className='mirantis-logo-white' href='http://www.mirantis.com/' target='_blank'></a>, <div key='copyright'>{i18n('common.copyright')}</div> ]} <div key='version'>{i18n('common.version')}: {version.get('release')}</div> </div> ); } }); export var Breadcrumbs = React.createClass({ mixins: [ dispatcherMixin('updatePageLayout', 'refresh') ], getInitialState() { return {path: this.getBreadcrumbsPath()}; }, getBreadcrumbsPath() { var page = this.props.Page; return _.isFunction(page.breadcrumbsPath) ? page.breadcrumbsPath(this.props.pageOptions) : page.breadcrumbsPath; }, refresh() { this.setState({path: this.getBreadcrumbsPath()}); }, render() { return ( <ol className='breadcrumb'> {_.map(this.state.path, (breadcrumb, index) => { if (!_.isArray(breadcrumb)) breadcrumb = [breadcrumb, null, {active: true}]; var text = breadcrumb[0]; var link = breadcrumb[1]; var options = breadcrumb[2] || {}; if (!options.skipTranslation) { text = i18n('breadcrumbs.' + text, {defaultValue: text}); } if (options.active) { return <li key={index} className='active'>{text}</li>; } else { return <li key={index}><a href={link}>{text}</a></li>; } })} </ol> ); } }); export var DefaultPasswordWarning = React.createClass({ render() { return ( <div className='alert global-alert alert-warning'> <button className='close' onClick={this.props.close}>&times;</button> {i18n('common.default_password_warning')} </div> ); } }); export var BootstrapError = React.createClass({ render() { return ( <div className='alert global-alert alert-danger'> {this.props.text} </div> ); } });
src/parser/priest/discipline/modules/azeritetraits/EnduringLuminescence.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { calculateTraitHealing } from 'parser/shared/modules/helpers/CalculateTraitHealing'; import { calculateAzeriteEffects } from 'common/stats'; import { formatPercentage } from 'common/format'; import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import ItemHealingDone from 'interface/ItemHealingDone'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import StatTracker from 'parser/shared/modules/StatTracker'; import Events from 'parser/core/Events'; import { POWER_WORD_RADIANCE_COEFFICIENT } from '../../constants'; const ENDURING_LUMINESCENCE_BONUS_MS = 1500; const EVANGELISM_BONUS_MS = 6000; /* * Power Word: Radiance restores 1672 additional health, and applies Atonement for 70% of its normal duration. */ class EnduringLuminescense extends Analyzer { static dependencies = { statTracker: StatTracker, } _bonusFromAtonementDuration = 0; _bonusFromDirectHeal = 0; _rawBonusHealingPerHit = 0; _lastCastIsPowerWordRadiance = false; _atonementsAppliedByRadiances = []; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.ENDURING_LUMINESCENCE.id); if (!this.active) { return; } this._rawBonusHealingPerHit = this.selectedCombatant.traitsBySpellId[SPELLS.ENDURING_LUMINESCENCE.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.ENDURING_LUMINESCENCE.id, rank)[0], 0); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.EVANGELISM_TALENT), this.handleEvangelismCasts); this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.ATONEMENT_BUFF), this.handleAtonementsApplications); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.POWER_WORD_RADIANCE), this.handleRadianceHits); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.ATONEMENT_HEAL_NON_CRIT), this.handleAtonementsHits); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.ATONEMENT_HEAL_CRIT), this.handleAtonementsHits); } handleAtonementsHits(event){ //Same situation as for Depth of the Shadows //Atonements in their Enduring window are fully counted since they would not be there otherwise this._atonementsAppliedByRadiances.forEach((atonement, index) => { const lowerBound = atonement.applyBuff.timestamp + (atonement.wasExtendedByEvangelismPreDepthWindow ? EVANGELISM_BONUS_MS : 0) + SPELLS.POWER_WORD_RADIANCE.atonementDuration; const upperBound = atonement.applyBuff.timestamp + (atonement.wasExtendedByEvangelismPreDepthWindow || atonement.wasExtendedByEvangelismInDepthWindow ? EVANGELISM_BONUS_MS : 0) + SPELLS.POWER_WORD_RADIANCE.atonementDuration + ENDURING_LUMINESCENCE_BONUS_MS; if(event.targetID === atonement.applyBuff.targetID && event.timestamp > lowerBound && event.timestamp < upperBound){ this._bonusFromAtonementDuration += event.amount; this._atonementsAppliedByRadiances[index].atonementEvents.push(event); } }); } handleEvangelismCasts(event){ this._atonementsAppliedByRadiances.forEach((atonement, index) => { //Atonements in their normal duration window when Evangelism is cast if(event.timestamp > atonement.applyBuff.timestamp && event.timestamp < atonement.applyBuff.timestamp + SPELLS.POWER_WORD_RADIANCE.atonementDuration){ this._atonementsAppliedByRadiances[index].wasExtendedByEvangelismPreEnduringWindow = true; } //Atonements in their Enduring Luminescence duration window when Evangelism is cast if(event.timestamp > atonement.applyBuff.timestamp + SPELLS.POWER_WORD_RADIANCE.atonementDuration && event.timestamp < atonement.applyBuff.timestamp + SPELLS.POWER_WORD_RADIANCE.atonementDuration + ENDURING_LUMINESCENCE_BONUS_MS){ this._atonementsAppliedByRadiances[index].wasExtendedByEvangelismInEnduringWindow = true; } }); } handleAtonementsApplications(event){ //Any atonement that is applied by Power Word: Radiance will have its corresponding //applybuff event assigned a new property __modified set to true, indicating it comes from a Power Word: Radiance cast if(event.__modified !== true){ return; } this._atonementsAppliedByRadiances.push({ "applyBuff": event, "atonementEvents": [], "wasExtendedByEvangelismPreEnduringWindow": false, "wasExtendedByEvangelismInEnduringWindow": false, }); } handleRadianceHits(event){ this._bonusFromDirectHeal += calculateTraitHealing(this.statTracker.currentIntellectRating, POWER_WORD_RADIANCE_COEFFICIENT, this._rawBonusHealingPerHit, event).healing; } statistic() { const total = this._bonusFromAtonementDuration + this._bonusFromDirectHeal; const totalPct = this.owner.getPercentageOfTotalHealingDone(total); const bonusFromAtonementPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromAtonementDuration); const bonusFromDirectHealPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromDirectHeal); return ( <AzeritePowerStatistic size="small" tooltip={( <> Enduring Luminescence provided <b>{formatPercentage(totalPct)}%</b> healing. <ul> <li><b>{formatPercentage(bonusFromAtonementPct)}%</b> from extended Atonement</li> <li><b>{formatPercentage(bonusFromDirectHealPct)}%</b> from direct extra Power Word: Radiance healing</li> </ul> </> )} > <BoringSpellValueText spell={SPELLS.ENDURING_LUMINESCENCE} > <ItemHealingDone amount={total} /> </BoringSpellValueText> </AzeritePowerStatistic> ); } } export default EnduringLuminescense;
codes/chapter05/react-router-v4/basic/demo02/app/components/Topics.js
atlantis1024/react-step-by-step
import React from 'react'; class Topics extends React.PureComponent { render() { return <h2>主题</h2> } } export default Topics;
src/containers/LandingPage/LandingPage.js
Alastor4918/Heckmeck
import React, { Component } from 'react'; import { Link } from 'react-router'; import config from '../../config'; import Helmet from 'react-helmet'; export default class LandingPage extends Component { render() { const styles = require('./Landing.scss'); // require the logo image both from client and server const logoImage = require('./static/heckmeck.png'); const mainImg = require('./static/back.png'); const cucak = require('./static/cucak.png'); const skrtic = require('./static/skrtic.png'); return ( <div className={ `${styles.landing} + 'container text-center'`}> <Helmet title="Landing"/> <div className={`text-center ${styles.logo}`}> <span> <img src={ logoImage } /> </span> </div> <h3 className="text-center"> Online board game Heckmeck ! </h3> <div className={styles.text}> <p className={`${styles.description} text-justify`}> Extrémne zábavná kocková hra pre 2-6 hráčov - sliepok, ktorí majú radi grilované červíky. Hra pre celú rodinu či partiu kamarátov. Hra v ktorej sa všetko rýchlo mení a nič v nej nie je isté. Zvíťazí ten hráč, ktorému sa podarí ukoristiť najviac grilovaných červíkov. Tých získavate z hodov kociek - hádžete dokedy chcete, ale okrem šťastia treba aj rozumný odhad, kedy máte dosť. Inak prídete o všetko nahádzané a na grile sa červíci pripečú. Dávajte si pozor aj na súperov, ani červíky, ktoré raz získate, nie sú úplne v bezpečí. </p> </div> <div className={styles.vtaky}> <img src={ mainImg } /> </div> <span className={styles.image1}> <img src={ cucak } /> </span> <span className={styles.button}> <Link to="/game">PLAY NOW</Link> </span> <span className={styles.image2}> <img src={ skrtic } /> </span> </div> ); } }
docs/src/sections/CarouselSection.js
pombredanne/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function CarouselSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="carousels">Carousels</Anchor> <small>Carousel, CarouselItem</small> </h2> <h3><Anchor id="carousels-uncontrolled">Uncontrolled</Anchor></h3> <p>Allow the component to control its own state.</p> <ReactPlayground codeText={Samples.CarouselUncontrolled} exampleClassName="bs-example-tabs" /> <h3><Anchor id="carousels-controlled">Controlled</Anchor></h3> <p>Pass down the active state on render via props.</p> <ReactPlayground codeText={Samples.CarouselControlled} exampleClassName="bs-example-tabs" /> <h3><Anchor id="carousels-props">Props</Anchor></h3> <h4><Anchor id="carousels-props-carousel">Carousel</Anchor></h4> <PropTable component="Carousel"/> <h4><Anchor id="carousels-props-item">CarouselItem</Anchor></h4> <PropTable component="CarouselItem"/> </div> ); }
web/src/js/components/General/Footer.js
gladly-team/tab
import React from 'react' import PropTypes from 'prop-types' import { withStyles } from '@material-ui/core/styles' import Divider from '@material-ui/core/Divider' import Logo from 'js/components/Logo/Logo' import { adblockerWhitelistingURL, externalContactUsURL, financialsURL, jobsURL, privacyPolicyURL, homeURL, externalHelpURL, teamURL, termsOfServiceURL, } from 'js/navigation/navigation' import Link from 'js/components/General/Link' import { TAB_APP } from 'js/constants' // Styles match tab-homepage style. // Footer link component const footerLinkStyles = theme => ({ footerLink: { fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif', textDecoration: 'none', color: '#cecece', fontSize: 12, margin: 20, '&:hover': { color: '#838383', }, }, }) const FooterLinkComponent = props => { const { children, classes, ...otherProps } = props return ( <Link target="_top" {...otherProps} className={classes.footerLink}> {children} </Link> ) } FooterLinkComponent.propTypes = { children: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), classes: PropTypes.object.isRequired, } FooterLinkComponent.defaultProps = {} const FooterLink = withStyles(footerLinkStyles)(FooterLinkComponent) export { FooterLink } // Footer component const styles = theme => ({ container: { background: 'rgba(128, 128, 128, 0.04)', paddingTop: 1, paddingBottom: 20, paddingLeft: 40, paddingRight: 40, }, divider: { width: '100%', marginBottom: 20, }, contentContainer: { display: 'flex', justifyContent: 'flex-start', flexWrap: 'nowrap', alignItems: 'center', }, textLinkContainer: { marginLeft: 30, display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-start', }, }) class Footer extends React.Component { render() { const { classes, style } = this.props // Currently only for Tab for a Cause. Customize if used // for other apps. return ( <div style={style} className={classes.container}> <Divider className={classes.divider} /> <div className={classes.contentContainer}> <Link to={homeURL}> <Logo brand={TAB_APP} color={'grey'} style={{ width: 43, height: 43, }} /> </Link> <div className={classes.textLinkContainer}> <FooterLink to={externalHelpURL}>Help</FooterLink> <FooterLink to={adblockerWhitelistingURL}>Adblockers</FooterLink> <FooterLink to={financialsURL}>Financials</FooterLink> <FooterLink to={termsOfServiceURL}>Terms</FooterLink> <FooterLink to={privacyPolicyURL}>Privacy</FooterLink> <FooterLink to={teamURL}>Team</FooterLink> <FooterLink to={externalContactUsURL}>Contact</FooterLink> <FooterLink to={jobsURL}>Jobs</FooterLink> </div> </div> </div> ) } } Footer.propTypes = { style: PropTypes.object, classes: PropTypes.object.isRequired, } Footer.defaultProps = { style: {}, } export default withStyles(styles)(Footer)
src/components/SchedulePage/CalendarPanel/CalendarPanel.js
deltaidea/planning-app
import React, { Component } from 'react'; import classNames from 'classnames'; import { parseDate, formatMoment, getTodayDate } from '../../../redux/calendar'; import { ContentPanel } from '../../ContentPanel'; import './CalendarPanel.css'; import iconArrowLeft from './icon-arrow-left.png' import iconArrowRight from './icon-arrow-right.png' export default class CalendarPanel extends Component { getOtherMonth(direction) { const addOrSubtract = (direction === -1) ? 'subtract' : 'add'; return parseDate(this.getDate())[addOrSubtract](1, 'month'); } getDate() { return this.props.calendar.selectedDate; } getMonthBoundaries(date) { return { start: parseDate(date).startOf('month').startOf('week'), end: parseDate(date).startOf('month').startOf('week').add(6, 'week') }; } renderDay(day) { return ( <td onClick={() => this.props.goToDate(day)} className={classNames({ 'busy': this.props.meetings.some(x => x.date === formatMoment(day)), 'highlighted today': getTodayDate() === formatMoment(day), 'highlighted selected': this.getDate() === formatMoment(day), 'other-month': parseDate(this.getDate()).month() !== day.month() })}>{day.date()}</td> ); } renderWeek(monday) { return ( <tr key={formatMoment(monday)}> {this.renderDay(monday.clone())} {this.renderDay(monday.clone().add(1, 'day'))} {this.renderDay(monday.clone().add(2, 'day'))} {this.renderDay(monday.clone().add(3, 'day'))} {this.renderDay(monday.clone().add(4, 'day'))} {this.renderDay(monday.clone().add(5, 'day'))} {this.renderDay(monday.clone().add(6, 'day'))} </tr> ); } renderAllWeeks(boundaries) { const rows = []; let curMonday = boundaries.start.clone(); while (curMonday.isBefore(boundaries.end)) { rows.push(this.renderWeek(curMonday)); curMonday = curMonday.add(7, 'days'); } return rows; } render() { const boundaries = this.getMonthBoundaries(this.getDate()); return ( <ContentPanel> <div className="calendar-container"> <div className="month-selection"> <img src={iconArrowLeft} onClick={() => this.props.goToDate(this.getOtherMonth(-1))} className="arrow" alt="Previous month"/> <span className="current-month">{parseDate(this.getDate()).format('MMM YYYY')}</span> <img src={iconArrowRight} onClick={() => this.props.goToDate(this.getOtherMonth(1))} className="arrow" alt="Next month"/> </div> <table className="calendar"> <thead> <tr> <td>mon</td> <td>tue</td> <td>wed</td> <td>thu</td> <td>fri</td> <td>sat</td> <td>sun</td> </tr> </thead> <tbody> {this.renderAllWeeks(boundaries)} </tbody> </table> </div> </ContentPanel> ); } }
src/components/Todo.js
taion/relay-todomvc
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { createFragmentContainer, graphql } from 'react-relay'; import ChangeTodoStatusMutation from '../mutations/ChangeTodoStatusMutation'; import RemoveTodoMutation from '../mutations/RemoveTodoMutation'; import RenameTodoMutation from '../mutations/RenameTodoMutation'; import TodoTextInput from './TodoTextInput'; const propTypes = { viewer: PropTypes.object.isRequired, todo: PropTypes.object.isRequired, relay: PropTypes.object.isRequired, }; class Todo extends React.Component { constructor(props) { super(props); this.state = { isEditing: false, }; } onCompleteChange = (e) => { const { relay, viewer, todo } = this.props; const complete = e.target.checked; ChangeTodoStatusMutation.commit(relay.environment, viewer, todo, complete); }; onDestroyClick = () => { this.removeTodo(); }; onLabelDoubleClick = () => { this.setEditMode(true); }; onTextInputCancel = () => { this.setEditMode(false); }; onTextInputDelete = () => { this.setEditMode(false); this.removeTodo(); }; onTextInputSave = (text) => { const { relay, todo } = this.props; this.setEditMode(false); RenameTodoMutation.commit(relay.environment, todo, text); }; setEditMode(isEditing) { this.setState({ isEditing }); } removeTodo() { const { relay, viewer, todo } = this.props; RemoveTodoMutation.commit(relay.environment, viewer, todo); } render() { const { complete, text } = this.props.todo; const { isEditing } = this.state; /* eslint-disable jsx-a11y/control-has-associated-label, jsx-a11y/label-has-associated-control */ return ( <li className={classNames({ completed: complete, editing: isEditing, })} > <div className="view"> <input type="checkbox" checked={complete} className="toggle" onChange={this.onCompleteChange} /> <label onDoubleClick={this.onLabelDoubleClick}>{text}</label> <button type="button" className="destroy" onClick={this.onDestroyClick} /> </div> {!!this.state.isEditing && ( <TodoTextInput className="edit" commitOnBlur initialValue={this.props.todo.text} onCancel={this.onTextInputCancel} onDelete={this.onTextInputDelete} onSave={this.onTextInputSave} /> )} </li> ); /* eslint-disable jsx-a11y/control-has-associated-label, jsx-a11y/label-has-associated-control */ } } Todo.propTypes = propTypes; export default createFragmentContainer(Todo, { viewer: graphql` fragment Todo_viewer on User { id } `, todo: graphql` fragment Todo_todo on Todo { id complete text } `, });
src/components/ShareMenu/InviteControl.js
Charlie9830/pounder
import React, { Component } from 'react'; import { TextField, Button } from '@material-ui/core'; class InviteControl extends Component { constructor(props) { super(props); // State. this.state = { isValid: false, } // Refs. this.emailInputRef = React.createRef(); // Method Bindings. this.handleKeyPress = this.handleKeyPress.bind(this); } render() { return ( <React.Fragment> <TextField autoFocus={this.props.autoFocus} placeholder="Email address" inputRef={this.emailInputRef} onKeyUp={this.handleKeyPress} /> <Button style={{ marginTop: '16px' }} variant="contained" onClick={() => { this.props.onInvite(this.emailInputRef.current.value)}} disabled={!this.state.isValid}> Invite </Button> </React.Fragment> ) } handleKeyPress(e) { let value = e.target.value; if (e.key === "Enter") { if (this.isValid(value)) { this.props.onInvite(this.emailInputRef.current.value); return; } } this.setState({isValid: this.isValid(value)}); } isValid(value) { if (value === undefined) { return false; } return value.trim() !== ''; } }; export default InviteControl;
src/js/components/modals/confirm.js
kukua/farmer-weather-analytics
import React from 'react' import Modal from 'react-modal' Modal.defaultStyles = { overlay: { position : 'fixed', top : 0, left : 0, right : 0, bottom : 0, backgroundColor : 'rgba(0, 0, 0, 0.75)' }, content: { position : 'absolute', top : '60px', left : '40px', right : '40px', bottom : '40px', border : 'none', background : 'none', overflow : 'auto', WebkitOverflowScrolling : 'touch', borderRadius : '4px', outline : 'none', padding : '20px' } } export default class Confirm extends React.Component { render () { var closeLabel = (this.props.closeLabel || 'Close') var confirmLabel = (this.props.confirmLabel || 'Confirm') return ( <Modal isOpen={this.props.isOpen} onRequestClose={this.props.onClose}> <div class="modal-content col-sm-offset-3 col-sm-6"> <div class="modal-header"> <button class="close" onClick={this.props.onClose}> <span aria-hidden="true">×</span> <span class="sr-only">{closeLabel}</span> </button> {this.props.title && <h4 class="modal-title">{this.props.title}</h4> } </div> <div class="modal-body"> {this.props.children} </div> <div class="modal-footer"> <button class="btn btn-default pull-left" onClick={this.props.onClose}>{closeLabel}</button> <button class="btn btn-success pull-right" onClick={this.props.onSubmit}>{confirmLabel}</button> </div> </div> </Modal> ) } } Confirm.propTypes = { isOpen: React.PropTypes.bool, title: React.PropTypes.string, onClose: React.PropTypes.func.isRequired, onSubmit: React.PropTypes.func.isRequired, closeLabel: React.PropTypes.string, confirmLabel: React.PropTypes.string, children: React.PropTypes.element, }
src/interface/icons/WoWAnalyzer.js
yajinni/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; const Icon = ({ mainColor, arrowColor, ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="icon" {...other}> <path d="M11.4842 102.243L1.02185 84.2455L49.9996 -7.62939e-06L98.9777 84.2461L88.5199 102.236L87.2159 99.9931H62.5V81.9943H76.7519L50.0041 35.986L23.2562 81.9943H37.5V99.9931H12.7923L11.4842 102.243ZM106.771 99.9931H106.809V99.9271L106.771 99.9931Z" fill={mainColor} /> <path d="M12.7883 100H86L85.9971 99.9931H62.5V81.9943H76.7519L50.0041 35.986L23.2562 81.9943H37.5V99.9931H12.7923L12.7883 100Z" fill={arrowColor} /> </svg> ); Icon.propTypes = { mainColor: PropTypes.string, arrowColor: PropTypes.string, }; Icon.defaultProps = { mainColor: '#FAB700', arrowColor: 'transparent', }; export default Icon;
docs/app/Examples/views/Item/Content/ItemExampleImages.js
clemensw/stardust
import React from 'react' import { Item } from 'semantic-ui-react' const ItemExampleImages = () => ( <Item.Group divided> <Item> <Item.Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Item> <Item> <Item.Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Item> <Item image='http://semantic-ui.com/images/wireframe/image.png' /> </Item.Group> ) export default ItemExampleImages
src/ModalDialog.js
westonplatter/react-bootstrap
/* eslint-disable react/prop-types */ import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const ModalDialog = React.createClass({ mixins: [BootstrapMixin], propTypes: { /** * A Callback fired when the header closeButton or non-static backdrop is clicked. * @type {function} * @required */ onHide: React.PropTypes.func.isRequired, /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'modal', closeButton: true }; }, render() { let modalStyle = { display: 'block', ...this.props.style }; let bsClass = this.props.bsClass; let dialogClasses = this.getBsClassSet(); delete dialogClasses.modal; dialogClasses[`${bsClass}-dialog`] = true; return ( <div {...this.props} title={null} tabIndex="-1" role="dialog" style={modalStyle} className={classNames(this.props.className, bsClass)}> <div className={classNames(this.props.dialogClassName, dialogClasses)}> <div className={`${bsClass}-content`} role="document"> { this.props.children } </div> </div> </div> ); } }); export default ModalDialog;
src/elements/List/ListList.js
aabustamante/Semantic-UI-React
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, } from '../../lib' /** * A list can contain a sub list. */ function ListList(props) { const { children, className } = props const rest = getUnhandledProps(ListList, props) const ElementType = getElementType(ListList, props) const classes = cx( useKeyOnly(ElementType !== 'ul' && ElementType !== 'ol', 'list'), className, ) return <ElementType {...rest} className={classes}>{children}</ElementType> } ListList._meta = { name: 'ListList', parent: 'List', type: META.TYPES.ELEMENT, } ListList.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, } export default ListList
src/__tests__/fileMocks/componentNamespace/Header/Hello.js
react-cosmos/fs-playground
// @flow import React from 'react'; const Hello = () => <span />; export default Hello;
src/svg-icons/image/brightness-5.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness5 = (props) => ( <SvgIcon {...props}> <path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/> </SvgIcon> ); ImageBrightness5 = pure(ImageBrightness5); ImageBrightness5.displayName = 'ImageBrightness5'; ImageBrightness5.muiName = 'SvgIcon'; export default ImageBrightness5;
src/server/middleware/main.js
nhardy/web-scaffold
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { last } from 'lodash-es'; import { createMemoryHistory, match } from 'react-router'; import { ReduxAsyncConnect, loadOnServer } from 'redux-connect'; import { Provider } from 'react-redux'; import assetManifest from 'server/lib/assetManifest'; import createStore from 'app/redux/store'; import getRoutes from 'app/routes'; import Html from 'app/components/Html'; export default function mainMiddleware(req, res, next) { const history = createMemoryHistory(req.url); const store = createStore(); match({ history, routes: getRoutes(store), location: req.url }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(`${redirectLocation.pathname}${redirectLocation.search}`); return; } if (error) { error.status = 500; next(error); return; } if (!renderProps) { const err = new Error('No matching route defined'); err.status = 404; next(err); return; } const { status } = last(renderProps.routes); if (status) { const err = new Error(`Route defined a status code: ${status}`); err.status = status; next(err); return; } loadOnServer({ ...renderProps, store }).then(() => { const { routeError } = store.getState(); if (routeError) { const err = new Error('Route Error defined in store'); err.status = routeError.route.status; next(err); return; } const inner = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); const component = ( <Html assets={assetManifest()} component={inner} store={store} /> ); res.set({ 'Cache-Control': 'public, maxage=300', }); res.send(`<!DOCTYPE html>\n${ReactDOMServer.renderToString(component)}`); }).catch((err) => { err.status = 500; next(err); }); }); }
docs/src/pages/customization/DarkTheme.js
dsslimshaddy/material-ui
// @flow weak import React from 'react'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'; import createPalette from 'material-ui/styles/palette'; import WithTheme from './WithTheme'; const theme = createMuiTheme({ palette: createPalette({ type: 'dark', // Switching the dark mode on is a single property value change. }), }); function DarkTheme() { return ( <MuiThemeProvider theme={theme}> <WithTheme /> </MuiThemeProvider> ); } export default DarkTheme;
node_modules/rc-tabs/es/ScrollableTabBarMixin.js
ZSMingNB/react-news
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import classnames from 'classnames'; import { setTransform, isTransformSupported } from './utils'; import React from 'react'; export default { getDefaultProps: function getDefaultProps() { return { scrollAnimated: true, onPrevClick: function onPrevClick() {}, onNextClick: function onNextClick() {} }; }, getInitialState: function getInitialState() { this.offset = 0; return { next: false, prev: false }; }, componentDidMount: function componentDidMount() { this.componentDidUpdate(); }, componentDidUpdate: function componentDidUpdate(prevProps) { var props = this.props; if (prevProps && prevProps.tabBarPosition !== props.tabBarPosition) { this.setOffset(0); return; } var nextPrev = this.setNextPrev(); // wait next, prev show hide /* eslint react/no-did-update-set-state:0 */ if (this.isNextPrevShown(this.state) !== this.isNextPrevShown(nextPrev)) { this.setState({}, this.scrollToActiveTab); } else { // can not use props.activeKey if (!prevProps || props.activeKey !== prevProps.activeKey) { this.scrollToActiveTab(); } } }, setNextPrev: function setNextPrev() { var navNode = this.refs.nav; var navNodeWH = this.getOffsetWH(navNode); var navWrapNode = this.refs.navWrap; var navWrapNodeWH = this.getOffsetWH(navWrapNode); var offset = this.offset; var minOffset = navWrapNodeWH - navNodeWH; var _state = this.state, next = _state.next, prev = _state.prev; if (minOffset >= 0) { next = false; this.setOffset(0, false); offset = 0; } else if (minOffset < offset) { next = true; } else { next = false; this.setOffset(minOffset, false); offset = minOffset; } if (offset < 0) { prev = true; } else { prev = false; } this.setNext(next); this.setPrev(prev); return { next: next, prev: prev }; }, getOffsetWH: function getOffsetWH(node) { var tabBarPosition = this.props.tabBarPosition; var prop = 'offsetWidth'; if (tabBarPosition === 'left' || tabBarPosition === 'right') { prop = 'offsetHeight'; } return node[prop]; }, getOffsetLT: function getOffsetLT(node) { var tabBarPosition = this.props.tabBarPosition; var prop = 'left'; if (tabBarPosition === 'left' || tabBarPosition === 'right') { prop = 'top'; } return node.getBoundingClientRect()[prop]; }, setOffset: function setOffset(offset) { var checkNextPrev = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var target = Math.min(0, offset); if (this.offset !== target) { this.offset = target; var navOffset = {}; var tabBarPosition = this.props.tabBarPosition; var navStyle = this.refs.nav.style; var transformSupported = isTransformSupported(navStyle); if (tabBarPosition === 'left' || tabBarPosition === 'right') { if (transformSupported) { navOffset = { value: 'translate3d(0,' + target + 'px,0)' }; } else { navOffset = { name: 'top', value: target + 'px' }; } } else { if (transformSupported) { navOffset = { value: 'translate3d(' + target + 'px,0,0)' }; } else { navOffset = { name: 'left', value: target + 'px' }; } } if (transformSupported) { setTransform(navStyle, navOffset.value); } else { navStyle[navOffset.name] = navOffset.value; } if (checkNextPrev) { this.setNextPrev(); } } }, setPrev: function setPrev(v) { if (this.state.prev !== v) { this.setState({ prev: v }); } }, setNext: function setNext(v) { if (this.state.next !== v) { this.setState({ next: v }); } }, isNextPrevShown: function isNextPrevShown(state) { return state.next || state.prev; }, scrollToActiveTab: function scrollToActiveTab() { var _refs = this.refs, activeTab = _refs.activeTab, navWrap = _refs.navWrap; if (activeTab) { var activeTabWH = this.getOffsetWH(activeTab); var navWrapNodeWH = this.getOffsetWH(navWrap); var offset = this.offset; var wrapOffset = this.getOffsetLT(navWrap); var activeTabOffset = this.getOffsetLT(activeTab); if (wrapOffset > activeTabOffset) { offset += wrapOffset - activeTabOffset; this.setOffset(offset); } else if (wrapOffset + navWrapNodeWH < activeTabOffset + activeTabWH) { offset -= activeTabOffset + activeTabWH - (wrapOffset + navWrapNodeWH); this.setOffset(offset); } } }, prev: function prev(e) { this.props.onPrevClick(e); var navWrapNode = this.refs.navWrap; var navWrapNodeWH = this.getOffsetWH(navWrapNode); var offset = this.offset; this.setOffset(offset + navWrapNodeWH); }, next: function next(e) { this.props.onNextClick(e); var navWrapNode = this.refs.navWrap; var navWrapNodeWH = this.getOffsetWH(navWrapNode); var offset = this.offset; this.setOffset(offset - navWrapNodeWH); }, getScrollBarNode: function getScrollBarNode(content) { var _classnames3, _classnames4; var _state2 = this.state, next = _state2.next, prev = _state2.prev; var _props = this.props, prefixCls = _props.prefixCls, scrollAnimated = _props.scrollAnimated; var nextButton = void 0; var prevButton = void 0; var showNextPrev = prev || next; if (showNextPrev) { var _classnames, _classnames2; prevButton = React.createElement( 'span', { onClick: prev ? this.prev : null, unselectable: 'unselectable', className: classnames((_classnames = {}, _defineProperty(_classnames, prefixCls + '-tab-prev', 1), _defineProperty(_classnames, prefixCls + '-tab-btn-disabled', !prev), _classnames)) }, React.createElement('span', { className: prefixCls + '-tab-prev-icon' }) ); nextButton = React.createElement( 'span', { onClick: next ? this.next : null, unselectable: 'unselectable', className: classnames((_classnames2 = {}, _defineProperty(_classnames2, prefixCls + '-tab-next', 1), _defineProperty(_classnames2, prefixCls + '-tab-btn-disabled', !next), _classnames2)) }, React.createElement('span', { className: prefixCls + '-tab-next-icon' }) ); } var navClassName = prefixCls + '-nav'; var navClasses = classnames((_classnames3 = {}, _defineProperty(_classnames3, navClassName, true), _defineProperty(_classnames3, scrollAnimated ? navClassName + '-animated' : navClassName + '-no-animated', true), _classnames3)); return React.createElement( 'div', { className: classnames((_classnames4 = {}, _defineProperty(_classnames4, prefixCls + '-nav-container', 1), _defineProperty(_classnames4, prefixCls + '-nav-container-scrolling', showNextPrev), _classnames4)), key: 'container', ref: 'container' }, prevButton, nextButton, React.createElement( 'div', { className: prefixCls + '-nav-wrap', ref: 'navWrap' }, React.createElement( 'div', { className: prefixCls + '-nav-scroll' }, React.createElement( 'div', { className: navClasses, ref: 'nav' }, content ) ) ) ); } };
app/App.js
o10if/guido-frontend
import React from 'react'; import AppNavigator from './AppNavigator'; export default React.createClass({ render() { return <AppNavigator /> }, });
modules/dreamview/frontend/src/components/ModuleController/index.js
ycool/apollo
import React from 'react'; import { inject, observer } from 'mobx-react'; import CheckboxItem from 'components/common/CheckboxItem'; import StatusDisplay from 'components/ModuleController/StatusDisplay'; @inject('store') @observer export default class ModuleController extends React.Component { render() { const { moduleStatus, componentStatus, allMonitoredComponentSuccess, isCalibrationMode, preConditionModule, } = this.props.store.hmi; const moduleEntries = Array.from(moduleStatus.keys()).sort().map((key) => ( <CheckboxItem key={key} id={key} title={key} disabled={isCalibrationMode && (key === preConditionModule) ? !allMonitoredComponentSuccess : false} isChecked={moduleStatus.get(key)} onClick={() => { this.props.store.hmi.toggleModule(key); }} extraClasses="controller" /> )); const componentEntries = Array.from(componentStatus.keys()).sort().map((key) => ( <StatusDisplay key={key} title={key} status={componentStatus.get(key)} /> )); return ( <div className="module-controller"> <div className="card"> <div className="card-header"><span>Components</span></div> <div className="card-content-column"> {componentEntries} </div> </div> <div className="card"> <div className="card-header"><span>Modules</span></div> <div className="card-content-row"> {moduleEntries} </div> </div> </div> ); } }
docs/app/Examples/views/Feed/Types/Props.js
jamiehill/stardust
import React from 'react' import { Feed } from 'stardust' const events = [ { date: '1 Hour Ago', image: 'http://semantic-ui.com/images/avatar/small/elliot.jpg', meta: '4 Likes', summary: 'Elliot Fu added you as a friend', }, { date: '4 days ago', image: 'http://semantic-ui.com/images/avatar/small/helen.jpg', meta: '1 Like', summary: 'Helen Troy added 2 new illustrations', extraImages: [ 'http://semantic-ui.com/images/wireframe/image.png', 'http://semantic-ui.com/images/wireframe/image.png', ], }, { date: '2 Days Ago', image: 'http://semantic-ui.com/images/avatar/small/jenny.jpg', meta: '8 Likes', summary: 'Jenny Hess added you as a friend', }, { date: '3 days ago', image: 'http://semantic-ui.com/images/avatar/small/joe.jpg', meta: '8 Likes', summary: 'Joe Henderson posted on his page', extraText: [ "Ours is a life of constant reruns. We're always circling back to where we'd we started, then starting all", "over again. Even if we don't run extra laps that day, we surely will come back for more of the same another", 'day soon.', ].join(' '), }, { date: '4 days ago', image: 'http://semantic-ui.com/images/avatar/small/justen.jpg', meta: '41 Likes', summary: 'Justen Kitsune added 2 new photos of you', extraImages: [ 'http://semantic-ui.com/images/wireframe/image.png', 'http://semantic-ui.com/images/wireframe/image.png', ], }, ] const Props = () => <Feed events={events} /> export default Props
admin/client/components/PopoutList.js
stunjiturner/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; var PopoutList = React.createClass({ displayName: 'PopoutList', propTypes: { children: React.PropTypes.node.isRequired, }, render () { let className = classnames('PopoutList', this.props.className); let props = blacklist(this.props, 'className'); return <div className={className} {...props} />; } }); module.exports = PopoutList; // expose the child to the top level export module.exports.Item = require('./PopoutListItem'); module.exports.Heading = require('./PopoutListHeading');
src/components/CollectiveCardWithRedeem.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { pickLogo } from '../lib/collective.lib'; import { get } from 'lodash'; import { Link } from '../server/pages'; import { firstSentence, imagePreview } from '../lib/utils'; import { defaultBackgroundImage } from '../constants/collectives'; import Button from './Button'; class CollectiveCardWithRedeem extends React.Component { static propTypes = { collective: PropTypes.object.isRequired, }; constructor(props) { super(props); } render() { const { collective } = this.props; const logo = imagePreview(collective.image, pickLogo(collective.id), { height: 128, }); const coverStyle = { ...get(collective, 'settings.style.hero.cover') }; const backgroundImage = imagePreview( collective.backgroundImage, collective.type === 'COLLECTIVE' && defaultBackgroundImage[collective.type], { width: 400 }, ); if (!coverStyle.backgroundImage && backgroundImage) { coverStyle.backgroundImage = `url('${backgroundImage}')`; coverStyle.backgroundSize = 'cover'; coverStyle.backgroundPosition = 'center center'; } const description = (collective.description && firstSentence(collective.description, 64)) || (collective.longDescription && firstSentence(collective.longDescription, 64)); return ( <div className={`CollectiveCard ${collective.type}`}> <style jsx> {` .CollectiveCard { display: flex; flex-direction: column; justify-content: space-between; cursor: pointer; vertical-align: top; position: relative; box-sizing: border-box; width: 225px; border-radius: 10px; background-color: #ffffff; box-shadow: 0 1px 3px 0 rgba(45, 77, 97, 0.2); overflow: hidden; text-decoration: none !important; margin: 1rem 2rem 1rem 0; } .head { position: relative; overflow: hidden; width: 100%; height: 12rem; border-bottom: 5px solid #46b0ed; } .background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-size: cover; background-position: center; } .image { background-size: contain; background-repeat: no-repeat; background-position: center; position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 65%; height: 55%; margin: auto; } .body { padding: 1rem; min-height: 10rem; } .name, .description { overflow: hidden; text-overflow: ellipsis; } .name { min-height: 20px; font-size: 14px; margin: 5px; font-weight: 300; text-align: center; color: #303233; white-space: nowrap; } .description { font-weight: normal; text-align: center; color: #787d80; font-size: 1.2rem; line-height: 1.3; margin: 0 5px; } .footer { font-size: 1.1rem; width: 100%; min-height: 6rem; text-align: center; } .stats, .redeem { border-top: 1px solid #f2f2f2; padding: 1rem; color: #303233; } .stats { display: flex; width: 100%; height: 6rem; justify-content: space-around; } .value, .label { text-align: center; margin: auto; } .value { font-weight: normal; text-align: center; color: #303233; font-size: 1.4rem; margin: 3px 2px 0px; } .label { font-size: 9px; text-align: center; font-weight: 300; color: #a8afb3; text-transform: uppercase; } .redeem { min-height: 18px; font-size: 12px; font-weight: 500; line-height: 1.5; text-align: center; color: #aab0b3; text-transform: capitalize; padding: 10px 0px; } `} </style> <Link route="orderCollective" params={{ collectiveSlug: this.props.collective.slug, verb: 'donate', description: 'Gift card', amount: 50, redeem: true, }} > <div> <div className="head"> <div className="background" style={coverStyle} /> <div className="image" style={{ backgroundImage: `url(${logo})` }} /> </div> <div className="body"> <div className="name">{collective.name}</div> <div className="description">{description}</div> </div> <div className="footer"> {collective.stats && ( <div className="stats"> <div className="backers"> <div className="value">{collective.stats.backers.users}</div> <div className="label"> <FormattedMessage id="collective.stats.backers.users" values={{ n: collective.stats.backers.users }} /> </div> </div> <div className="organizations"> <div className="value">{collective.stats.backers.organizations}</div> <div className="label"> <FormattedMessage id="collective.stats.backers.organizations" values={{ n: collective.stats.backers.organizations }} /> </div> </div> </div> )} </div> <div className="redeem"> <Button className="redeem-button blue" style={{ width: '150px', height: '3rem', textAlign: 'center', letterSpacing: '0px', textTransform: 'none', borderRadius: '16px', }} > Support us! </Button> </div> </div> </Link> </div> ); } } export default CollectiveCardWithRedeem;
src/parser/shared/modules/spells/bfa/azeritetraits/TreacherousCovenant.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatNumber, formatPercentage } from 'common/format'; import { calculateAzeriteEffects } from 'common/stats'; import SpellLink from 'common/SpellLink'; import UptimeIcon from 'interface/icons/Uptime'; import PrimaryStatIcon from 'interface/icons/PrimaryStat'; import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic'; import ItemDamageTaken from 'interface/others/ItemDamageTaken'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import StatTracker from 'parser/shared/modules/StatTracker'; const treacherousCovenantStat = traits => Object.values(traits).reduce((obj, rank) => { const stat = calculateAzeriteEffects(SPELLS.TREACHEROUS_COVENANT.id, rank); obj.stat += Number(stat); return obj; }, { stat: 0, }); const DAMAGE_MODIFIER = .15; /** * Treacherous Covenant * Your primary stat is increased by 151 while you are above 50% health. You take 15% increased damage while below 20% health.. * * Example reports * Int: /report/L9AFD1kHxTrGK43t/1-Heroic+Champion+of+the+Light+-+Kill+(3:08)/20-Wiridian * Agi: /report/1YJ98MzR6qPvydGA/13-Heroic+Grong+-+Kill+(4:56)/19-Cleah * Str: /report/TMjpXkaYKVhncmfb/11-Heroic+Jadefire+Masters+-+Kill+(4:45)/11-Jhonson * * @property {StatTracker} statTracker */ class TreacherousCovenant extends Analyzer { static dependencies = { statTracker: StatTracker, }; statModifier = 0; debuffActive = false; extraDamageTaken = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.TREACHEROUS_COVENANT.id); if (!this.active) { return; } const { stat } = treacherousCovenantStat(this.selectedCombatant.traitsBySpellId[SPELLS.TREACHEROUS_COVENANT.id]); this.statModifier = stat; this.addEventListener(Events.applydebuff.to(SELECTED_PLAYER).spell(SPELLS.TREACHEROUS_COVENANT_DEBUFF), this._applyDebuff); this.addEventListener(Events.removedebuff.to(SELECTED_PLAYER).spell(SPELLS.TREACHEROUS_COVENANT_DEBUFF), this._removeDebuff); this.addEventListener(Events.damage.to(SELECTED_PLAYER), this._takeDamage); this.statTracker.add(SPELLS.TREACHEROUS_COVENANT_BUFF.id, { strength: this.statModifier, intellect: this.statModifier, agility: this.statModifier, }); } _applyDebuff(event) { this.debuffActive = true; } _removeDebuff(event) { this.debuffActive = false; } _takeDamage(event) { if (this.debuffActive) { this.extraDamageTaken += (event.amount || 0) * DAMAGE_MODIFIER; } } get debuffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.TREACHEROUS_COVENANT_DEBUFF.id) / this.owner.fightDuration; } get buffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.TREACHEROUS_COVENANT_BUFF.id) / this.owner.fightDuration; } get averageStatModifier() { return this.buffUptime * this.statModifier; } statistic() { return ( <AzeritePowerStatistic size="flexible" tooltip={( <> Grants <b>{this.statModifier} {this.selectedCombatant.spec.primaryStat}</b> while above 50% health.<br /> Extra damage taken: {formatNumber(this.extraDamageTaken)}. </> )} > <div className="pad"> <label><SpellLink id={SPELLS.TREACHEROUS_COVENANT.id} /></label> <div className="value"> <UptimeIcon /> {formatPercentage(this.buffUptime)}% <small>buff uptime</small><br /> <PrimaryStatIcon stat={this.selectedCombatant.spec.primaryStat} /> {formatNumber(this.averageStatModifier)} <small>average {this.selectedCombatant.spec.primaryStat} gained</small><br /> <UptimeIcon /> {formatPercentage(this.debuffUptime)}% <small>debuff uptime</small><br /> <ItemDamageTaken amount={this.extraDamageTaken} /> </div> </div> </AzeritePowerStatistic> ); } } export default TreacherousCovenant;
src-client/scripts/app.js
PaulRSwift/iLuggit
import Backbone from 'backbone' import React from 'react' import ReactDOM from 'react-dom' import $ from 'jquery' import PackAuthView from './pack-auth-view.js' import LuggAuthView from './lugg-auth-view.js' import HomeView from './home-page.js' import AppController from './lugg-view-controller.js' import CargoDisplay from './display-cargo-details.js' import CreateLugg from './create-lugg.js' import {LuggProfile, LuggView} from './lugg-list.js' import showReviews from './reviews.js' import Sandbox from './sandbox.js' import TruckInfo from './truckinfo.js' import showWhatWeDo from './whatwedo.js' const AppRouter = Backbone.Router.extend({ routes: { "sandbox" : "showSandbox", "user-login" : "showPackAuthView", "truck-login" : "showLuggAuthView", "cargo/:cargoId" : "showDisplayCargo", "lugg-list" : "showLuggList", "create-lugg" : "showCreateLugg", "truck-info" : "showTruckInfo", "whatwedo" : "showWhatWeDo", "reviews" : "showReviews", "" : "showHomeView" }, showCreateLugg: function(){ ReactDOM.render(<AppController routedFrom = "CreateLugg" />, document.querySelector('#app-container')) }, showPackAuthView: function(){ ReactDOM.render(<AppController routedFrom = "PackAuthView" />, document.querySelector('#app-container')) }, showLuggAuthView: function(){ ReactDOM.render(<AppController routedFrom = "LuggAuthView" />, document.querySelector('#app-container')) }, showDisplayCargo: function(cargoId){ ReactDOM.render(<AppController routedFrom = "CargoDisplay" modelId={cargoId} />, document.querySelector('#app-container')) }, showLuggList: function(){ ReactDOM.render(<AppController routedFrom = "LuggProfile" />, document.querySelector('#app-container')) }, showHomeView: function(){ ReactDOM.render(<AppController routedFrom = "HomeView" />, document.querySelector('#app-container')) }, showSandbox: function(){ ReactDOM.render(<AppController routedFrom = "Sandbox" />, document.querySelector('#app-container')) }, showTruckInfo: function(){ ReactDOM.render(<AppController routedFrom = "TruckInfo" />, document.querySelector('#app-container')) }, showWhatWeDo: function(){ ReactDOM.render(<AppController routedFrom = "WhatWeDo" />, document.querySelector('#app-container')) }, showReviews: function(){ ReactDOM.render(<AppController routedFrom = "Reviews" />, document.querySelector('#app-container')) }, initialize: function(){ Backbone.history.start(); } }) const app = new AppRouter()
client/src/Game/Prototype01/FPScounter.js
hold-the-door-game/Prototypes
import React from 'react'; import bind from 'react-autobind'; class FPSCounter extends React.Component { constructor(props) { super(props); this.fpsCounter = new window.PIXI.Text(props.fps); this.fpsCounter.anchor.set(0); this.fpsCounter.style = { fill: props.color }; bind(this); } componentDidMount() { const app = this.props.app; app.stage.addChild(this.fpsCounter); } setPosition(x, y) { this.fpsCounter.x = x; this.fpsCounter.y = y; } setScale(scale) { this.fpsCounter.scale.x = scale; this.fpsCounter.scale.y = scale; } updateFPS(fps) { this.fpsCounter.text = fps; } render() { const x = this.props.position.x; const y = this.props.position.y; const scale = this.props.scale; const fps = this.props.fps; this.setPosition(x, y); this.setScale(scale); this.updateFPS(fps) return null; } } export default FPSCounter;
src/components/googleMaps.js
joakimremler/horse-project
import React, { Component } from 'react'; class GoogleMap extends Component { componentDidMount() { var map; map = new google.maps.Map(this.refs.map, { zoom: 12, center: new google.maps.LatLng(57.7087, 11.9751), mapTypeId: 'roadmap' }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { info: { icon: '../data/stall.png' } }; var features = [ { position: new google.maps.LatLng(57.746558, 11.897127), type: 'info' }, { position: new google.maps.LatLng(57.741731, 12.059479), type: 'info' }, { position: new google.maps.LatLng(57.662842, 11.900722), type: 'info' }, { position: new google.maps.LatLng(57.706762, 12.025603), type: 'info' } ]; // Create markers. features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: map }); }); } render() { return <div ref="map" id="googleMap" />; } } export default GoogleMap;
src/isomorphic/components/Topics/index.js
hzhu/react-universal
import React from 'react' import Topic from '../Topic' import { Route, Link } from 'react-router-dom' const Topics = ({ match }) => ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/rendering`}> Rendering with React </Link> </li> <li> <Link to={`${match.url}/components`}> components </Link> </li> <li> <Link to={`${match.url}/props-v-state`}> Props v. State </Link> </li> </ul> <Route path={`${match.url}/:topicId`} component={Topic} /> <Route exact path={match.url} render={() => (<h3>Please select a topic.</h3>)} /> </div> ) export default Topics
src/layouts/CoreLayout/CoreLayout.js
okmttdhr/aupa
import React from 'react' import Header from '../../components/Header' import classes from './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className={classes.mainContainer}> {children} </div> </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
step8-unittest/node_modules/react-router/es6/Redirect.js
jintoppy/react-training
'use strict'; import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { formatPattern } from './PatternUtils'; import { falsy } from './PropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ var Redirect = React.createClass({ displayName: 'Redirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element) { var route = _createRouteFromReactElement(element); if (route.from) route.path = route.from; route.onEnter = function (nextState, replace) { var location = nextState.location; var params = nextState.params; var pathname = undefined; if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params); } else if (!route.to) { pathname = location.pathname; } else { var routeIndex = nextState.routes.indexOf(route); var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1); var pattern = parentPattern.replace(/\/*$/, '/') + route.to; pathname = formatPattern(pattern, params); } replace({ pathname: pathname, query: route.query || location.query, state: route.state || location.state }); }; return route; }, getRoutePattern: function getRoutePattern(routes, routeIndex) { var parentPattern = ''; for (var i = routeIndex; i >= 0; i--) { var route = routes[i]; var pattern = route.path || ''; parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; if (pattern.indexOf('/') === 0) break; } return '/' + parentPattern; } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; } }); export default Redirect;
react/features/device-selection/components/AudioOutputPreview.js
KalinduDN/kalindudn.github.io
import React, { Component } from 'react'; import { translate } from '../../base/i18n'; const TEST_SOUND_PATH = 'sounds/ring.wav'; /** * React component for playing a test sound through a specified audio device. * * @extends Component */ class AudioOutputPreview extends Component { /** * AudioOutputPreview component's property types. * * @static */ static propTypes = { /** * The device id of the audio output device to use. */ deviceId: React.PropTypes.string, /** * Invoked to obtain translated strings. */ t: React.PropTypes.func }; /** * Initializes a new AudioOutputPreview instance. * * @param {Object} props - The read-only React Component props with which * the new instance is to be initialized. */ constructor(props) { super(props); this._audioElement = null; this._onClick = this._onClick.bind(this); this._setAudioElement = this._setAudioElement.bind(this); } /** * Sets the target output device on the component's audio element after * initial render. * * @inheritdoc * @returns {void} */ componentDidMount() { this._setAudioSink(); } /** * Updates the audio element when the target output device changes and the * audio element has re-rendered. * * @inheritdoc * @returns {void} */ componentDidUpdate() { this._setAudioSink(); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <div className = 'audio-output-preview'> <a onClick = { this._onClick }> { this.props.t('deviceSelection.testAudio') } </a> <audio preload = 'auto' ref = { this._setAudioElement } src = { TEST_SOUND_PATH } /> </div> ); } /** * Plays a test sound. * * @private * @returns {void} */ _onClick() { this._audioElement && this._audioElement.play(); } /** * Sets the instance variable for the component's audio element so it can be * accessed directly. * * @param {Object} element - The DOM element for the component's audio. * @private * @returns {void} */ _setAudioElement(element) { this._audioElement = element; } /** * Updates the target output device for playing the test sound. * * @private * @returns {void} */ _setAudioSink() { this._audioElement && this._audioElement.setSinkId(this.props.deviceId); } } export default translate(AudioOutputPreview);
src/components/spinner/stories.js
LiskHQ/lisk-nano
import React from 'react'; import { storiesOf } from '@storybook/react'; import Spinner from './'; storiesOf('Spinner', module) .add('default', () => ( <Spinner/> ));
thesishub-ui/src/views/NoMatch.js
StudentHubCZ/thesishub
import React from 'react'; const NoMatch = ({ location }) => ( <div> <h2>Page not Found</h2> </div> ) export default NoMatch
web/src/index.js
nokia/LearningStore
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/page/CarouselPage.js
jerryshew/react-uikits
import React, { Component } from 'react'; import {CN, TitleBlock} from '../util/tools'; import {Carousel} from '../component'; import CodeView from './CodeView'; const src = ['ambition-morty', 'awkward-morty', 'despise', 'pride-morty', 'surprise-morty']; const prefix = 'https://raw.githubusercontent.com/jerryshew/design/master/png'; const getImgs = function(){ return src.map(i => { return ( <img key={i} src={`${prefix}/${i}.png`} style={{'width': '100%'}}/> ) }) }; const imgNodes = getImgs(); export class CarouselPage extends Component { render() { return ( <section> {TitleBlock('跑马灯')} <br/> <h4>默认跑马灯</h4> <CodeView component={<Carousel>{imgNodes}</Carousel>}> { `<Carousel> <img src="../img0.png" key="0" /> <img src="../img1.png" key="1" /> <img src="../img2.png" key="2" /> ... </Carousel> `} </CodeView> <h4>自动播放跑马灯</h4> <CodeView component={<Carousel autoPlay={true} delay={2000} >{imgNodes}</Carousel>}> { `<Carousel autoPlay={true} delay={2000}> <img src="../img0.png" key="0" /> <img src="../img1.png" key="1" /> <img src="../img2.png" key="2" /> ... </Carousel> `} </CodeView> <h4>带左右切换的跑马灯</h4> <CodeView component={<Carousel showArrow={true} >{imgNodes}</Carousel>}> { `<Carousel showArrow={true}> <img src="../img0.png" key="0" /> <img src="../img1.png" key="1" /> <img src="../img2.png" key="2" /> ... </Carousel> `} </CodeView> <h4>自定义切换按钮</h4> <CodeView component={ <Carousel prev={<i className="dot icon">chevron_left</i>} next={<i className="dot icon">chevron_right</i>} showArrow={true} > {imgNodes} </Carousel>}> { `<Carousel showArrow={true} prev={<i className="dot icon">chevron_left</i>} next={<i className="dot icon">chevron_right</i>}> <img src="../img0.png" key="0" /> <img src="../img1.png" key="1" /> <img src="../img2.png" key="2" /> ... </Carousel> `} </CodeView> <br/> <h4>属性</h4> <table className="dot table"> <thead> <tr> <th>名称</th> <th>描述</th> <th>类型</th> <th>默认值</th> <th>Required</th> </tr> </thead> <tbody> <tr> <td>autoPlay</td> <td>是否自动播放</td> <td>Boolean</td> <td>false</td> <td>否</td> </tr> <tr> <td>delay</td> <td>自动播放延迟(毫秒)</td> <td>Number</td> <td>5000</td> <td>否</td> </tr> <tr> <td>showArrow</td> <td>是否显示切换按钮</td> <td>Boolean</td> <td>false</td> <td>否</td> </tr> <tr> <td>prev</td> <td>左箭头</td> <td>jsx</td> <td>{`<span>prev</span>`}</td> <td>否</td> </tr> <tr> <td>next</td> <td>右箭头</td> <td>jsx</td> <td>{`<span>next</span>`}</td> <td>否</td> </tr> </tbody> </table> </section> ); } }
admin/client/App/screens/Item/components/EditFormHeader.js
w01fgang/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { connect } from 'react-redux'; import Toolbar from './Toolbar'; import ToolbarSection from './Toolbar/ToolbarSection'; import EditFormHeaderSearch from './EditFormHeaderSearch'; import { Link } from 'react-router'; import Drilldown from './Drilldown'; import { GlyphButton, ResponsiveText } from '../../../elemental'; export const EditFormHeader = React.createClass({ displayName: 'EditFormHeader', propTypes: { data: React.PropTypes.object, list: React.PropTypes.object, toggleCreate: React.PropTypes.func, }, getInitialState () { return { searchString: '', }; }, toggleCreate (visible) { this.props.toggleCreate(visible); }, searchStringChanged (event) { this.setState({ searchString: event.target.value, }); }, handleEscapeKey (event) { const escapeKeyCode = 27; if (event.which === escapeKeyCode) { findDOMNode(this.refs.searchField).blur(); } }, renderDrilldown () { return ( <ToolbarSection left> {this.renderDrilldownItems()} {this.renderSearch()} </ToolbarSection> ); }, renderDrilldownItems () { const { data, list } = this.props; const items = data.drilldown ? data.drilldown.items : []; let backPath = `${Keystone.adminPath}/${list.path}`; const backStyles = { paddingLeft: 0, paddingRight: 0 }; // Link to the list page the user came from if (this.props.listActivePage && this.props.listActivePage > 1) { backPath = `${backPath}?page=${this.props.listActivePage}`; } // return a single back button when no drilldown exists if (!items.length) { return ( <GlyphButton component={Link} data-e2e-editform-header-back glyph="chevron-left" position="left" style={backStyles} to={backPath} variant="link" > {list.plural} </GlyphButton> ); } // prepare the drilldown elements const drilldown = []; items.forEach((item, idx) => { // FIXME @jedwatson // we used to support relationships of type MANY where items were // represented as siblings inside a single list item; this got a // bit messy... item.items.forEach(link => { drilldown.push({ href: link.href, label: link.label, title: item.list.singular, }); }); }); // add the current list to the drilldown drilldown.push({ href: backPath, label: list.plural, }); return ( <Drilldown items={drilldown} /> ); }, renderSearch () { var list = this.props.list; return ( <form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search"> <EditFormHeaderSearch value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} /> {/* <GlyphField glyphColor="#999" glyph="search"> <FormInput ref="searchField" type="search" name="search" value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} placeholder="Search" style={{ paddingLeft: '2.3em' }} /> </GlyphField> */} </form> ); }, renderInfo () { return ( <ToolbarSection right> {this.renderCreateButton()} </ToolbarSection> ); }, renderCreateButton () { const { nocreate, autocreate, singular } = this.props.list; if (nocreate) return null; let props = {}; if (autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => { this.toggleCreate(true); }; } return ( <GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" {...props}> <ResponsiveText hiddenXS={`New ${singular}`} visibleXS="Create" /> </GlyphButton> ); }, render () { return ( <Toolbar> {this.renderDrilldown()} {this.renderInfo()} </Toolbar> ); }, }); export default connect((state) => ({ listActivePage: state.lists.page.index, }))(EditFormHeader);
client/components/Header/index.js
dimitri-a/wp2_budget
import React from 'react'; export default ()=> { return ( <header> <h1>Budget</h1> </header> ); };
src/components/Page/index.js
unibras/unibras-website
import React, { Component } from 'react'; import './styles.css'; import ImageSlider from '../../components/ImageSlider'; import PageBody from '../../components/PageBody'; import PageGallery from '../../components/PageGallery'; import Contact from '../../components/Contact'; import classnames from 'classnames'; import PropTypes from 'prop-types'; function findCurrentPage(path, pages) { return pages.find(page => (page.id === path || (page.position === 1 && !path))); } function findCurrentSubPage(subpath, page) { if (!page || !subpath) return; return page.subsections.find(page => (page.id === subpath)); } class Page extends Component { static propTypes = { siteMap: PropTypes.array.isRequired } render() { const { pathname, subpathname, siteMap } = this.props; const page = findCurrentPage(pathname, siteMap); const subpage = findCurrentSubPage(subpathname, page); return ( <div className={classnames(this.props.className, 'Page')}> {page.slider && <ImageSlider images={page.slider} />} {page.body && <PageBody page={subpage || page} />} {page.gallery && <PageGallery page={subpage || page} />} {page.contact && <Contact page={page} />} </div> ); } } export default Page;
src/main/app/scripts/core/App.js
ondrejhudek/hudy-app
import React from 'react' import ReactDOM from 'react-dom' import { browserHistory } from 'react-router' import routes from '../routes' import Root from '../containers/Root' import store from '../store/configureStore' ReactDOM.render( <Root history={browserHistory} routes={routes} store={store}/>, document.getElementById('app') )
app/components/Home.js
meryt/wordcount-react
import React from 'react'; import { connect } from 'react-redux' import Messages from './Messages'; import DatePicker from 'react-bootstrap-date-picker'; import { FormGroup, ControlLabel, HelpBlock } from 'react-bootstrap'; // for DatePicker import { SplitButton, MenuItem } from 'react-bootstrap'; class HelloMessage extends React.Component { render() { return <div>Hello {this.props.name}</div>; } } class MyDatePicker extends React.Component { constructor(props) { super(props); this.state = { value : new Date().toISOString() }; this.handleChange = this.handleChange.bind(this); }; handleChange (value, formattedValue) { this.setState({ value: value, formattedValue: formattedValue }); } componentDidUpdate() { console.log(this.state.value); } render() { return <FormGroup> <ControlLabel>Date</ControlLabel> <DatePicker id="example-datepicker" value={this.state.value} dateFormat="YYYY-MM-DD" onChange={this.handleChange} /> <HelpBlock>Help</HelpBlock> </FormGroup>; } } class ProjectPicker extends React.Component { constructor(props) { super(props); this.state = { value : "Red Boots" }; this.handleChange = this.handleChange.bind(this); }; // This is not working, still need to figure out how to update title/value based on change events for these // buttons. handleChange (event) { /** this.setState({ value: event.target.value }); */ console.log(JSON.stringify(event)); } render() { return <SplitButton id="project-select" title={this.state.value}> <MenuItem onClick={this.handleChange}>Red Boots</MenuItem> <MenuItem onClick={this.handleChange}>Ohio</MenuItem> <MenuItem divider /> <MenuItem>Add new...</MenuItem> </SplitButton>; } } class Home extends React.Component { render() { return ( <div className="container-fluid"> <Messages messages={this.props.messages}/> <div className="row"> <div className="col-sm-12"> <div className="panel"> <div className="panel-body"> <h3>Heading</h3> <HelloMessage name="Jenny" /> <MyDatePicker /> <ProjectPicker /> <div id="date-picker-container" /> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p> <a href="#" role="button" className="btn btn-default">View details</a> </div> </div> </div> </div> <div className="row"> <div className="col-sm-6"> <div className="panel"> <div className="panel-body"> <h3>Heading</h3> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p> <a href="#" role="button" className="btn btn-default">View details</a> </div> </div> </div> <div className="col-sm-6"> <div className="panel"> <div className="panel-body"> <h3>Heading</h3> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p> <a href="#" role="button" className="btn btn-default">View details</a> </div> </div> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { messages: state.messages }; }; export default connect(mapStateToProps)(Home);
src/shared/components/header/NavBar.js
Grace951/ReactAU
import { NavLink , Link} from 'react-router-dom'; import React from 'react'; import { navData } from '../../Data/RouteData'; // const parentActive = (match, location) => { // console.log(match, location); // if (!match) { // return false // } // return true; // } const AtomNavLink = (props) => (<li> <NavLink to={props.a.link} activeClassName={props.activeClassName} /*isActive={parentActive}*/ onClick={()=>props.SmNavCtrl()}> {props.a.desc} </NavLink></li>); AtomNavLink.propTypes = { a: React.PropTypes.object, SmNavCtrl: React.PropTypes.func.isRequired, activeClassName: React.PropTypes.string }; const AtomLink = (props) => (<li> <Link to={props.a.link} onClick={()=>props.SmNavCtrl()}> {props.a.desc} </Link></li>); AtomLink.propTypes = { a: React.PropTypes.object, SmNavCtrl: React.PropTypes.func.isRequired, }; const ParentLink = (props) => { if ( props.item.sub && props.item.sub.length > 0) { return ( <li> <Link to={props.item.link} onClick={()=>props.SmNavCtrl()}> {props.item.desc} <i className="fa fa-caret-right"/></Link> <ul className="dropdown-menu"> { props.item.sub.map((item, id) => { return (<ParentLink key={id} item={item} SmNavCtrl={props.SmNavCtrl}/>); }) } </ul> </li> ); }else{ return (<AtomLink a={{link:props.item.link, desc:props.item.desc}} SmNavCtrl={props.SmNavCtrl} activeClass={props.activeClassName} />); } }; ParentLink.propTypes = { item: React.PropTypes.object, SmNavCtrl: React.PropTypes.func.isRequired, activeClassName: React.PropTypes.string }; const TopParentLink = (props) => { return ( <li> <div className="parent"> <NavLink to={props.item.link} activeClassName={props.activeClassName} onClick={()=>props.SmNavCtrl()}> {props.item.desc} </NavLink><span className="caret" /> </div> <ul className="dropdown-menu"> { props.item.sub.map((item, id) => { return (<ParentLink key={id} item={item} SmNavCtrl={props.SmNavCtrl}/>);}) } </ul> </li> ); }; TopParentLink.propTypes = { item: React.PropTypes.object, SmNavCtrl: React.PropTypes.func.isRequired, activeClassName: React.PropTypes.string }; let NavBar = class NavBar extends React.Component{ constructor(props) { super(props); this.SmNavCtrl = this.SmNavCtrl.bind(this); } SmNavCtrl(){ this.props.SmNavCtrl(false); } render() { let {showSmNav, SmNavCtrl, activeClass} = this.props; return ( <div id="cctv-nav" className={`cctv-nav ${showSmNav?'show-xs-nav':''}`} > <ul> <h3 id="XX" onClick={this.SmNavCtrl}> <i className="fa fa-times" /></h3> { navData.map && navData.map( (item, id) => { return (item.sub && item.sub.length > 0) ? (<TopParentLink key={id} item={item} activeClassName={activeClass} SmNavCtrl={SmNavCtrl}/> ) : (<AtomNavLink key={id} a={{link:item.link, desc:item.desc}} activeClassName={activeClass} SmNavCtrl={SmNavCtrl}/>); }) } </ul> </div> ); } }; NavBar.propTypes = { activeClass: React.PropTypes.string, showSmNav: React.PropTypes.bool, SmNavCtrl: React.PropTypes.func, }; export default NavBar;
src/components/books/preview/BookPreviewBody.js
great-design-and-systems/cataloguing-app
import { FormGroup, Img, Loading, StarRating } from '../../common/'; import { LABEL_AUTHOR, LABEL_ISBN_10, LABEL_ISBN_13, LABEL_NA, LABEL_NUMBER_OF_PAGES, LABEL_PUBLISHED_DATE, LABEL_PUBLISHER, LABEL_SUB_TITLE, LABEL_SUMMARY, LABEL_TITLE } from '../../../labels/'; import { Book } from '../../../api/books/'; import PropTypes from 'prop-types'; import React from 'react'; export const BookPreviewBody = ({ bookPreview, ajaxGlobal }) => { return (<div className="book-preview page books clearfix"> {ajaxGlobal.started && <Loading />} {!ajaxGlobal.started && <div> <div className="col-sm-2 "> <div className="book"> <Img className="book-image" src={bookPreview[Book.IMAGE_URL]} /> </div> <div className="padding-left-15px"> <StarRating value={bookPreview[Book.TITLE_POINTS]} starCount={4} /> </div> </div> <div className="col-sm-10"> <div className="col-sm-6 col-sm-offset-1"> <FormGroup label={LABEL_TITLE} name={Book.TITLE}> <span>{bookPreview[Book.TITLE] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_ISBN_10} name={Book.ISBN10}> <span>{bookPreview[Book.ISBN10] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_ISBN_13} name={Book.ISBN13}> <span>{bookPreview[Book.ISBN13] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_PUBLISHER} name={Book.PUBLISHER}> <span>{bookPreview[Book.PUBLISHER] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_AUTHOR} name={Book.AUTHOR}> <span>{bookPreview[Book.AUTHOR] || LABEL_NA}</span> </FormGroup> </div> <div className="col-sm-5"> <FormGroup label={LABEL_PUBLISHED_DATE}> <span>{bookPreview[Book.PUBLISHED_DATE] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_SUB_TITLE}> <span>{bookPreview[Book.SUB_TITLE] || LABEL_NA}</span> </FormGroup> <FormGroup label={LABEL_NUMBER_OF_PAGES}> <span>{bookPreview[Book.NUMBER_OF_PAGES] || LABEL_NA}</span> </FormGroup> </div> </div> <div className="col-sm-12"> <FormGroup label={LABEL_SUMMARY} name={Book.SUMMARY}> <p>{bookPreview[Book.SUMMARY] || LABEL_NA}</p> </FormGroup> </div> </div>} </div>); }; BookPreviewBody.propTypes = { bookPreview: PropTypes.object.isRequired, ajaxGlobal: PropTypes.object.isRequired };
src/svg-icons/image/crop-16-9.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop169 = (props) => ( <SvgIcon {...props}> <path d="M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z"/> </SvgIcon> ); ImageCrop169 = pure(ImageCrop169); ImageCrop169.displayName = 'ImageCrop169'; ImageCrop169.muiName = 'SvgIcon'; export default ImageCrop169;
Js/Ui/Components/Icon/index.js
Webiny/Webiny
import React from 'react'; import _ from 'lodash'; import Webiny from 'webiny'; import styles from './styles.css'; class Icon extends Webiny.Ui.Component { } Icon.defaultProps = { icon: null, className: null, element: 'span', // span || i type: 'default', size: 'default', renderer() { const {styles, icon, className, element, onClick} = this.props; let iconSet = 'icon'; if (_.includes(icon, 'fa-')) { iconSet = 'fa icon'; } const typeClasses = { default: '', danger: styles.danger, success: styles.success, info: styles.info, warning: styles.warning, }; const sizeClasses = { default: '', '2x': styles.size2x, '3x': styles.size3x, '4x': styles.size4x }; const classes = this.classSet(iconSet, icon, className, sizeClasses[this.props.size], typeClasses[this.props.type]); return React.createElement(element, {className: classes, onClick}); } }; export default Webiny.createComponent(Icon, {styles});
src/svg-icons/editor/format-textdirection-r-to-l.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatTextdirectionRToL = (props) => ( <SvgIcon {...props}> <path d="M10 10v5h2V4h2v11h2V4h2V2h-8C7.79 2 6 3.79 6 6s1.79 4 4 4zm-2 7v-3l-4 4 4 4v-3h12v-2H8z"/> </SvgIcon> ); EditorFormatTextdirectionRToL = pure(EditorFormatTextdirectionRToL); EditorFormatTextdirectionRToL.displayName = 'EditorFormatTextdirectionRToL'; export default EditorFormatTextdirectionRToL;
app/src/components/index.js
open-austin/budgetparty
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { IntlProvider, addLocaleData } from 'react-intl'; import en from 'react-intl/locale-data/en'; import es from 'react-intl/locale-data/es'; import { Route, Router, Redirect, Switch } from 'react-router-dom'; import ReactGA from 'react-ga'; import createHistory from 'history/createBrowserHistory'; import Home from './Home'; import Intro from './Intro'; import DashboardContainer from '../containers/Dashboard'; import ServiceContainer from '../containers/Service'; import DepartmentContainer from '../containers/Department'; import LearnMore from './Department/LearnMore'; import ExplainContainer from '../containers/Explain'; import SubmitContainer from '../containers/Submit'; import User from './User'; import Done from './Done'; import Admin from './Admin/Index'; import { firebaseAuth } from '../config/constants'; import { logout } from '../helpers/auth'; import Landing from './Landing'; import store from '../store'; // Google Analytics ReactGA.initialize('UA-64394324-4'); const history = createHistory(); history.listen((location) => { ReactGA.set({ page: location.pathname }); ReactGA.pageview(location.pathname); }); // Internationalization 🌎 addLocaleData([...en, ...es]); const language = (navigator.languages && navigator.languages[0]) || navigator.language || navigator.userLanguage; export default class App extends Component { constructor(props) { super(props); this.state = { authed: false, loading: true, user: {}, }; } componentDidMount() { this.removeListener = firebaseAuth().onAuthStateChanged(user => this.updateAuthState(user)); } componentWillUnmount() { this.removeListener(); } updateAuthState(user) { if (user) { this.setState({ authed: true, loading: false, user, }); } else { this.setState({ loading: false, }); } } handleLogout() { const warning = window.confirm('Are you sure you want to log out?'); if (warning) { console.log('LOGGED OUT'); logout(); this.setState({ authed: false }); } } render() { console.log('😈'); const { authed, user, loading } = this.state; return loading === true ? ( <h1>Loading</h1> ) : ( <IntlProvider locale={language}> <Provider store={store}> <Router history={history}> <div className="container"> <div className="row"> <Switch className="row"> <Route path="/" exact render={() => { return authed ? <Redirect to="/dashboard" /> : <Redirect to="/home" />; }} /> <Route path="/home"> <Landing /> </Route> <Route path="/login" isAuthed={authed} render={() => { return authed ? <Redirect to="/intro/1" /> : <Home />; }} /> <Route path="/intro/:id" render={props => <Intro {...props} />} /> <Route path="/dashboard" render={props => <DashboardContainer {...props} user={user} />} /> <Route path="/service/:id" exact render={props => <ServiceContainer {...props} />} /> <Route path="/service/:service_id/department/:id" exact render={props => <DepartmentContainer {...props} user={user} />} /> <Route path="/service/:service_id/department/:id/learn-more" render={props => <LearnMore {...props} />} /> <Route path="/service/:service_id/department/:id/explain" render={props => <ExplainContainer {...props} />} /> <Route path="/user" render={() => { return ( <User isAuthed={authed} handleLogout={this.handleLogout.bind(this)} user={user} /> ); }} /> <Route path="/submit" render={(props) => { return <SubmitContainer {...props} user={user} />; }} /> <Route path="/done" render={(props) => { return <Done {...props} />; }} /> <Route path="/results" render={(props) => { return <Admin {...props} />; }} /> <Route render={() => ( <h3> 404, you ain&apos;t supposed to be here. <a href="/">Go back.</a> </h3> )} /> </Switch> </div> </div> </Router> </Provider> </IntlProvider> ); } }
src/routes/Error/error.js
Mesamo/dva-admin
import React from 'react' import { Icon } from 'antd' import styles from './error.less' class Error extends React.Component { render() { return ( <div className="content-inner"> <div className={styles.error}> <Icon type="frown-o" style={{ fontSize: 40 }} /> <h1>404 Not Found</h1> </div> </div> ) } } export default Error
components/animals/varanKomodsky.adult.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/varanKomodsky/01.jpg'), require('../../images/animals/varanKomodsky/02.jpg'), require('../../images/animals/varanKomodsky/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/varanKomodsky/01-thumb.jpg'), require('../../images/animals/varanKomodsky/02-thumb.jpg'), require('../../images/animals/varanKomodsky/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Varan komodský, latinsky <Text style={styles.italic}>Varanus komodoensis</Text>, je nejmohutnější ještěr na světě, dožívající se 30&nbsp;let a opředený mnoha legendami. Tyto legendy vychází především z&nbsp;jeho jedovatosti a tělesných rozměrů. Dospělý samec totiž může přesahovat 3&nbsp;m a vážit i&nbsp;přes 100&nbsp;kg. Nejvíce však strašlivé příběhy o&nbsp;komodském drakovi podpořil fakt, že až donedávna se o&nbsp;něm téměř nic nevědělo. </AnimalText> <AnimalText> Teprve ve 20.&nbsp;století se pomalu začaly rozplétat dohady o&nbsp;tomto predátorovi ze skupiny ještěrů. Do té doby nebyl varan komodský chován v&nbsp;zajetí. I&nbsp;dnes patří k&nbsp;nejvzácnějším zvířatům chovaným v&nbsp;zoologických zahradách – smyslem péče o&nbsp;něj je především zachování ohroženého druhu, který v&nbsp;současné době ve volné přírodě čítá kolem 3&nbsp;500&nbsp;jedinců. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Vedle pohlavního rozmnožování je u&nbsp;varanů komodských možné i&nbsp;rozmnožování partenogenezí, na což se přišlo až v&nbsp;roce&nbsp;2006. Partenogeneze je vývin jedince z&nbsp;vajíčka neoplozeného samčí pohlavní buňkou. Tímto způsobem se vždy vyvine samec, který má velmi podobnou genetickou výbavu jako jeho matka. Stejným způsobem se v&nbsp;roce&nbsp;2011 narodil i&nbsp;náš samec Rototom. Jeho matka, legendární Aranka z&nbsp;pražské zoo, je světovou rekordmankou mezi samicemi tohoto druhu chovanými v&nbsp;zajetí: na svém kontě má již 47&nbsp;mláďat! A to je přitom rozmnožení tohoto druhu v&nbsp;zajetí považováno za výjimečnou událost, odhadem je toho schopných pouze pět samic. </AnimalText> <AnimalText> Varan komodský obývá lesy i&nbsp;travnaté oblasti indonéského ostrova Komodo, po kterém je nazván, vyskytuje se ale i&nbsp;na okolních ostrovech, např.&nbsp;na Floresu. Aktivní je nejvíce ve dne. Občas se živí mršinami vyvrženými z&nbsp;moře, je však i&nbsp;zdatný lovec. Loví ptáky, plazy i&nbsp;savce – ani buvol pro něj není nezdolatelnou překážkou. Na svou kořist číhá, ve vhodném okamžiku se do ní zakousne ostrými pilovitými zuby a z&nbsp;jedových žláz v dolní čelisti vypustí do těla oběti jed. Ten snižuje srážlivost krve a vyvolává pokles krevního tlaku, obsahuje též neurotoxin působící jako sedativum. Takto napadená oběť těžce krvácí a brzy upadá do šoku. Velké zvíře, jako je např.&nbsp;buvol, může však také dlouho umírat následkem otravy bakteriemi. Takto velká zvířata jsou pak konzumována hromadně varany z&nbsp;širého okolí. Po jednorázovém nasycení asi měsíc nepřijímají žádnou další potravu. </AnimalText> <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> U&nbsp;varanů je též silně rozvinutý kanibalismus. Z&nbsp;tohoto důvodu žijí mláďata až do dvou let věku v&nbsp;korunách stromů, kde unikají loveckým choutkám dospělých jedinců, kteří na strom vylézt neumí. </AnimalText> <AnimalText> Indonésie považuje varany za národní poklad, podobně jako Čína pandy velké. Vývoz ze země je umožněn jen výjimečně, a to formou státního daru. První varani komodští se do Česka dostali v&nbsp;roce&nbsp;1997 jako dar prezidentu Václavu Havlovi. Tento pár byl umístěn v&nbsp;Zoo Plzeň. Brněnská zoo se stala teprve třetí zoologickou zahradou v&nbsp;republice (po Plzni a Praze), kde mohou návštěvníci obdivovat draka z&nbsp;Komoda. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
src/front-end/js/components/helpers/Waiter.js
aleksey-gonchar/iamamaze.me
import React from 'react' import { Icon } from './FontAwesome.js' export default class Waiter extends React.Component { render () { return ( <div data-class='Waiter'> <div className='waiter-content'> <Icon name='circle-o-notch' spin /> </div> </div> ) } }
frontend/src/Components/Table/VirtualTable.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Grid, WindowScroller } from 'react-virtualized'; import Measure from 'Components/Measure'; import Scroller from 'Components/Scroller/Scroller'; import { scrollDirections } from 'Helpers/Props'; import hasDifferentItemsOrOrder from 'Utilities/Object/hasDifferentItemsOrOrder'; import styles from './VirtualTable.css'; const ROW_HEIGHT = 38; function overscanIndicesGetter(options) { const { cellCount, overscanCellsCount, startIndex, stopIndex } = options; // The default getter takes the scroll direction into account, // but that can cause issues. Ignore the scroll direction and // always over return more items. const overscanStartIndex = startIndex - overscanCellsCount; const overscanStopIndex = stopIndex + overscanCellsCount; return { overscanStartIndex: Math.max(0, overscanStartIndex), overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex) }; } class VirtualTable extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { width: 0, scrollRestored: false }; this._grid = null; } componentDidUpdate(prevProps, prevState) { const { items, scrollIndex, scrollTop } = this.props; const { width, scrollRestored } = this.state; if (this._grid && (prevState.width !== width || hasDifferentItemsOrOrder(prevProps.items, items))) { // recomputeGridSize also forces Grid to discard its cache of rendered cells this._grid.recomputeGridSize(); } if (scrollIndex != null && scrollIndex !== prevProps.scrollIndex) { this._grid.scrollToCell({ rowIndex: scrollIndex, columnIndex: 0 }); } if (this._grid && scrollTop !== undefined && scrollTop !== 0 && !scrollRestored) { this.setState({ scrollRestored: true }); this._grid.scrollToPosition({ scrollTop }); } } // // Control setGridRef = (ref) => { this._grid = ref; }; // // Listeners onMeasure = ({ width }) => { this.setState({ width }); }; // // Render render() { const { isSmallScreen, className, items, scroller, focusScroller, scrollTop: ignored, header, headerHeight, rowRenderer, ...otherProps } = this.props; const { width } = this.state; const gridStyle = { boxSizing: undefined, direction: undefined, height: undefined, position: undefined, willChange: undefined, overflow: undefined, width: undefined }; const containerStyle = { position: undefined }; return ( <WindowScroller scrollElement={isSmallScreen ? undefined : scroller} > {({ height, registerChild, onChildScroll, scrollTop }) => { if (!height) { return null; } return ( <Measure whitelist={['width']} onMeasure={this.onMeasure} > <Scroller className={className} scrollDirection={scrollDirections.HORIZONTAL} autoFocus={focusScroller} > {header} <div ref={registerChild}> <Grid ref={this.setGridRef} autoContainerWidth={true} autoHeight={true} autoWidth={true} width={width} height={height} headerHeight={height - headerHeight} rowHeight={ROW_HEIGHT} rowCount={items.length} columnCount={1} columnWidth={width} scrollTop={scrollTop} onScroll={onChildScroll} overscanRowCount={2} cellRenderer={rowRenderer} overscanIndicesGetter={overscanIndicesGetter} scrollToAlignment={'start'} isScrollingOptout={true} className={styles.tableBodyContainer} style={gridStyle} containerStyle={containerStyle} {...otherProps} /> </div> </Scroller> </Measure> ); } } </WindowScroller> ); } } VirtualTable.propTypes = { isSmallScreen: PropTypes.bool.isRequired, className: PropTypes.string.isRequired, items: PropTypes.arrayOf(PropTypes.object).isRequired, scrollIndex: PropTypes.number, scrollTop: PropTypes.number, scroller: PropTypes.instanceOf(Element).isRequired, focusScroller: PropTypes.bool.isRequired, header: PropTypes.node.isRequired, headerHeight: PropTypes.number.isRequired, rowRenderer: PropTypes.func.isRequired }; VirtualTable.defaultProps = { className: styles.tableContainer, headerHeight: 38, focusScroller: true }; export default VirtualTable;
src/Shared/utils.js
NativeForms/framework-src
import React from 'react'; import { injectIntl as inject } from 'react-intl'; import syntaxHighlighter from 'react-native-syntax-highlighter'; import { github } from 'react-syntax-highlighter/dist/styles'; import { Iterable } from 'immutable'; export const SchemaViewer = (props) => syntaxHighlighter( Object.assign({}, syntaxHighlighter.defaultProps, { language: 'javascript', style: github, codeTagProps: { alwaysBounceVertical: false } }, props)); /** * Decorator to inject React Intl API * @param {Object} options - React Intl Options */ export const injectIntl = options => target => inject(target, options); /** Decorator to convert ImmutableJS props to JavaScript props */ export const toJS = () => WrappedComponent => wrappedComponentProps => { const KEY = 0; const VALUE = 1; const propsJS = Object.entries(wrappedComponentProps) .reduce((newProps, wrappedComponentProp) => { /* eslint no-param-reassign:0 */ newProps[wrappedComponentProp[KEY]] = Iterable.isIterable(wrappedComponentProp[VALUE]) ? wrappedComponentProp[VALUE].toJS() : wrappedComponentProp[VALUE]; return newProps; }, {}); return <WrappedComponent {...propsJS} />; }; /** Get default Locale from platform - TODO */ export function getLocale() { return 'en'; }
packages/bonde-admin/src/components/data-grid/hocs/row-hoc.js
ourcities/rebu-client
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' export default (WrappedComponent) => { class PP extends React.Component { render () { const { data, onSelectRow, rowIndex, actived, className, children } = this.props const rowProps = { className: classnames( 'flex', className, { 'active': actived } ), data: WrappedComponent !== 'div' ? data : null, rowIndex: WrappedComponent !== 'div' ? rowIndex : null, onSelectRow } return ( <WrappedComponent {...rowProps}> {children && children({ data, rowIndex })} </WrappedComponent> ) } } PP.propTypes = { data: PropTypes.oneOf([ PropTypes.string, PropTypes.number, PropTypes.object ]) } return PP }
fixtures/ssr/src/components/Chrome.js
AlmeroSteyn/react
import React, { Component } from 'react'; import './Chrome.css'; export default class Chrome extends Component { render() { const assets = this.props.assets; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" href="favicon.ico" /> <link rel="stylesheet" href={assets['main.css']} /> <title>{this.props.title}</title> </head> <body> {this.props.children} <script dangerouslySetInnerHTML={{ __html: `assetManifest = ${JSON.stringify(assets)};` }} /> <script src={assets['main.js']} /> </body> </html> ); } }
boilerplates/basic/src/components/droids/droid.js
goncalvesjoao/react-to-commonJS
import React from 'react'; const defaultProps = { name: true, }; class Droid extends React.Component { renderName() { if (!this.props.name) { return <noscript />; } return ( <p className="text-center"> <span name="droid-name" className="label label-info"> { this.props.droid.name } </span> </p> ); } render() { return ( <li> <img className="img-circle" style={{ width: '80px' }} src={ this.props.droid.avatar } /> <span>{ this.renderName() }</span> </li> ); } } Droid.defaultProps = defaultProps; export default Droid;
example/src/pages/EnlargedImageContainerDimensions.js
ethanselzer/react-image-magnify
import React, { Component } from 'react'; import { Col, Grid, Jumbotron, Row } from 'react-bootstrap'; import Helmet from 'react-helmet'; import Header from '../components/Header'; import EnlargedImageContainerDimensions from '../components/EnlargedImageContainerDimensions'; import 'bootstrap/dist/css/bootstrap.css'; import '../styles/app.css'; export default class extends Component { render() { return ( <div> <Helmet title="React Image Magnify" /> <Header {...this.props}/> <Jumbotron> <Grid> <Row> <Col sm={12}> </Col> </Row> </Grid> </Jumbotron> <Grid> <Row> <Col sm={12}> <EnlargedImageContainerDimensions /> </Col> </Row> </Grid> </div> ); } }
app/containers/Root/Root.prod.js
ryanwashburne/react-skeleton
import PropTypes from 'prop-types'; import React from 'react'; import { Provider } from 'react-redux'; import { Route } from 'react-router-dom'; import { ConnectedRouter } from 'react-router-redux'; import App from '../App'; export default function Root({store, history}) { return ( <Provider store={store}> <div> <ConnectedRouter history={history}> <Route path="/" component={App}/> </ConnectedRouter> </div> </Provider> ); } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired };
example/js/app.js
ConciergeAuctions/relay-cache-manager
import 'babel-polyfill'; import App from './components/App'; import AppHomeRoute from './routes/AppHomeRoute'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import CacheManager from 'relay-cache-manager'; const cacheManager = new CacheManager(); Relay.Store.getStoreData().injectCacheManager(cacheManager); ReactDOM.render( <Relay.Renderer environment={Relay.Store} Container={App} queryConfig={new AppHomeRoute()} />, document.getElementById('root') );
node_modules/react-router/es6/IndexRedirect.js
Shwrndasink/btholt-react-tutorial
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import Redirect from './Redirect'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ var IndexRedirect = React.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRedirect;
EvergreenApp/components/Garden/GardenScreen.js
tr3v0r5/evergreen
import React, { Component } from 'react'; import {Text, View, Alert, ScrollView, TouchableOpacity, Animated,AsyncStorage } from 'react-native'; import {Button, Icon} from 'react-native-elements'; import Svg, { G, Path } from 'react-native-svg' import * as firebase from 'firebase'; import GardenZoneComponent from './GardenZoneComponent.js'; import AddZoneScreen from './AddZoneScreen.js'; import styles from '../../Styles/gardenStyles.js'; export class GardenScreen extends Component{ static navigationOptions = { header:null, } constructor(props){ super(props); this.state = { zonesArray:[], loaded:false, timer:'something', //used to make the end of fade in animation fadeAnim: new Animated.Value(1),//opacity value for splashscreen fadeAnim2: new Animated.Value(0),//opacity value for gardenscreem userID: '', modal: <AddZoneScreen/> }; }//constructor async initZones(){ //intalizes the gardenZones try { const UID = await AsyncStorage.getItem('UID'); this.setState({ userID: UID }); } catch (error) { // Error retrieving data console.log(error); } var zoneRef = firebase.database().ref('/Users/' + this.state.userID + '/GardenZones'); zoneRef.on('value', (snapshot) => { var zones = []; snapshot.forEach((child) => { zones.push({ name: child.val().Name, imageSource: child.val().ImageSource, keyRef: child.key }); }); this.setState({ zonesArray:zones, loaded:true, timer:null }); }); }//initZones componentDidMount(){ Animated.timing( this.state.fadeAnim,{ toValue:0, duration:2000 } ).start()//decrease splashscreen opacity from 1 to 0 setTimeout(()=>{ Animated.timing( this.state.fadeAnim2,{ toValue:1, duration:1000 } ).start()//increase gardenscreen opacity from 0 to 1 this.initZones();//preloads the gardenzones when component mounts },2000);//delays actual garden screen }//componentDidMount setModalVisible(visible) { this.setState({modalVisible: visible}); }//setModalVisible makeZones(navigation){ var userID= this.state.userID; var list= this.state.userSensors; //console.warn(list); return this.state.zonesArray.map(function(zone,i){ var nameVal = zone.name; var imageVal = zone.imageSource; var keyVal = zone.keyRef return( <GardenZoneComponent key = {i} name = {nameVal} keyRef = {keyVal} imageSource = {imageVal} navi = {navigation} userID = {userID} /> ); }); }//makeZones /*render() { if(this.state.timer!=null){ return( <Animated.View style={{alignItems:'center',backgroundColor:'white',justifyContent: 'center', padding: 10,opacity: this.state.fadeAnim}}> <Svg width='560' height='681' preserveAspectRatio="xMidYMid meet"> <G translate='100,520' scale=".065,-.065" > <Path fill='green' d="M5438 6707 c-175 -174 -379 -312 -613 -413 -224 -97 -393 -138 -1015 -249 -505 -89 -624 -113 -875 -171 -1097 -253 -1887 -655 -2327 -1185 -302 -364 -443 -728 -530 -1373 -20 -140 -23 -206 -23 -506 0 -302 3 -366 23 -510 81 -599 266 -1154 547 -1646 93 -161 256 -400 362 -529 l98 -120 365 -2 365 -2 -77 29 c-196 73 -387 197 -522 341 -185 196 -364 543 -470 906 -135 468 -182 982 -135 1488 18 191 102 472 198 664 267 529 780 1000 1446 1326 286 139 553 240 944 355 261 76 487 152 614 206 98 41 133 44 148 10 8 -16 8 -29 1 -43 -20 -36 -334 -192 -592 -293 -802 -314 -1002 -407 -1300 -605 -195 -129 -371 -276 -570 -475 -163 -163 -249 -274 -332 -427 -167 -308 -268 -764 -268 -1215 l0 -167 43 -34 c133 -108 333 -168 607 -183 116 -6 136 -4 284 26 454 91 884 248 1258 458 1166 654 1991 1886 2376 3552 72 310 132 672 132 797 0 61 -3 74 -19 83 -11 5 -24 10 -30 10 -6 0 -57 -46 -113 -103z"/> </G> </Svg> </Animated.View> ); }else{ if(this.state.loaded){ return( <Animated.View style={[styles.containerGarden,{opacity:this.state.fadeAnim2 }]}> <ScrollView style = {{backgroundColor:'white'}}> {this.state.modal} <View> <View style = {styles.gardenHeader}> <Text style = {[styles.gardenText,{textAlign:'center',marginTop:20}]}>Sage Smart Garden</Text> </View> <View style = {styles.gardenGrid}> {this.makeZones(this.props.navigation)} <TouchableOpacity onPress={() => this.setState({ modal: <AddZoneScreen userID = {this.state.userID} modalVisible={true}/> })} style={{padding:10}} > <View style={[styles.zoneContainer,{borderColor:'black',borderStyle:'dotted',borderWidth:2,alignItems:'center',justifyContent:'center',padding:10}]}> <Icon name='plus' type='material-community' color='#27ae60' /> </View> </TouchableOpacity> </View> </View> </ScrollView> </Animated.View> ); } } }//render the ole render with add zones*/ render() { if(this.state.timer!=null){ return( <Animated.View style={{alignItems:'center',backgroundColor:'white',justifyContent: 'center', padding: 10,opacity: this.state.fadeAnim}}> <Svg width='560' height='681' preserveAspectRatio="xMidYMid meet"> <G translate='100,520' scale=".065,-.065" > <Path fill='green' d="M5438 6707 c-175 -174 -379 -312 -613 -413 -224 -97 -393 -138 -1015 -249 -505 -89 -624 -113 -875 -171 -1097 -253 -1887 -655 -2327 -1185 -302 -364 -443 -728 -530 -1373 -20 -140 -23 -206 -23 -506 0 -302 3 -366 23 -510 81 -599 266 -1154 547 -1646 93 -161 256 -400 362 -529 l98 -120 365 -2 365 -2 -77 29 c-196 73 -387 197 -522 341 -185 196 -364 543 -470 906 -135 468 -182 982 -135 1488 18 191 102 472 198 664 267 529 780 1000 1446 1326 286 139 553 240 944 355 261 76 487 152 614 206 98 41 133 44 148 10 8 -16 8 -29 1 -43 -20 -36 -334 -192 -592 -293 -802 -314 -1002 -407 -1300 -605 -195 -129 -371 -276 -570 -475 -163 -163 -249 -274 -332 -427 -167 -308 -268 -764 -268 -1215 l0 -167 43 -34 c133 -108 333 -168 607 -183 116 -6 136 -4 284 26 454 91 884 248 1258 458 1166 654 1991 1886 2376 3552 72 310 132 672 132 797 0 61 -3 74 -19 83 -11 5 -24 10 -30 10 -6 0 -57 -46 -113 -103z"/> </G> </Svg> </Animated.View> ); }else{ if(this.state.loaded){ return( <Animated.View style={[styles.containerGarden,{opacity:this.state.fadeAnim2,backgroundColor:'white' }]}> <View style = {{backgroundColor:'white'}}> <View> <View style = {styles.gardenHeader}> <Text style = {[styles.gardenText,{textAlign:'center',marginTop:20}]}>Sage Smart Garden</Text> </View> <View style={[styles.gardenGrid,{backgroundColor:'white'}]}> <GardenZoneComponent name = "My Garden" keyRef = "My Garden" imageSource = "image1" navi = {this.props.navigation} userID = {this.state.userID} /> </View> </View> </View> </Animated.View> ); } } }//render } module.exports = GardenScreen;
.storybook/config.js
delmaroi/tododemo
import React from 'react'; import { configure, addDecorator } from '@kadira/storybook'; import { IntlProvider } from 'react-intl'; // import translation messages import { translationMessages } from '../app/i18n'; // add a decorator to wrap stories rendering into IntlProvider const DEFAULT_LOCALE = 'en'; addDecorator((story) => ( <IntlProvider locale={DEFAULT_LOCALE} messages={translationMessages[DEFAULT_LOCALE]}> { story() } </IntlProvider> )); // stories loader const req = require.context('../app', true, /.stories.js$/); function loadStories() { req.keys().forEach((filename) => req(filename)); } // initialize react-storybook configure(loadStories, module);
priv/static/widget.js
kittoframework/kitto
import ReactDOM from 'react-dom'; import React from 'react'; import Helpers from './helpers'; class Widget extends React.Component { constructor(props) { super(props); this.state = {}; this.source = (this.props.source || this.constructor.name).toLowerCase(); Widget.listen(this, this.source); } static events() { if (this._events) { return this._events; } this._events = new EventSource(`/events?topics=${this.sources().join()}`); this._events.addEventListener('error', (e) => { let state = e.currentTarget.readyState; if (state === EventSource.CONNECTING || state === EventSource.CLOSED) { // Restart the dashboard setTimeout((() => window.location.reload()), 5 * 60 * 1000) } }); this.bindInternalEvents(); return this._events; } static sources() { return Array.prototype.map .call(document.querySelectorAll('[data-source]'), (el) => el.dataset.source); } static bindInternalEvents() { this._events.addEventListener('_kitto', (event) => { let data = JSON.parse(event.data); switch (data.message.event) { case 'reload': if (data.message.dashboard === '*' || document.location.pathname.endsWith(data.message.dashboard)) { document.location.reload() } break; } }); } static listen(component, source) { this.events().addEventListener((source.toLowerCase() || 'messages'), (event) => { component.setState(JSON.parse(event.data).message); }); } static mount(component) { const widgets = document.querySelectorAll(`[data-widget="${component.name}"]`) Array.prototype.forEach.call(widgets, (el) => { var dataset = el.dataset; dataset.className = `${el.className} widget-${component.name.toLowerCase()} widget`; ReactDOM.render(React.createElement(component, dataset), el.parentNode); }); } } for (var k in Helpers) { Widget.prototype[k] = Helpers[k]; } export default Widget;
pages/about.js
creeperyang/react-static-boilerplate
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>About Us</h1> <p>Coming soon.</p> </div> ); } }
node_modules/semantic-ui-react/src/views/Item/ItemContent.js
mowbell/clickdelivery-fed-test
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, SUI, useVerticalAlignProp, } from '../../lib' import ItemHeader from './ItemHeader' import ItemDescription from './ItemDescription' import ItemExtra from './ItemExtra' import ItemMeta from './ItemMeta' /** * An item can contain content. */ function ItemContent(props) { const { children, className, content, description, extra, header, meta, verticalAlign, } = props const classes = cx( useVerticalAlignProp(verticalAlign), 'content', className, ) const rest = getUnhandledProps(ItemContent, props) const ElementType = getElementType(ItemContent, props) if (!_.isNil(children)) { return <ElementType {...rest} className={classes}>{children}</ElementType> } return ( <ElementType {...rest} className={classes}> {ItemHeader.create(header)} {ItemMeta.create(meta)} {ItemDescription.create(description)} {ItemExtra.create(extra)} {content} </ElementType> ) } ItemContent._meta = { name: 'ItemContent', parent: 'Item', type: META.TYPES.VIEW, } ItemContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Shorthand for ItemDescription component. */ description: customPropTypes.itemShorthand, /** Shorthand for ItemExtra component. */ extra: customPropTypes.itemShorthand, /** Shorthand for ItemHeader component. */ header: customPropTypes.itemShorthand, /** Shorthand for ItemMeta component. */ meta: customPropTypes.itemShorthand, /** Content can specify its vertical alignment. */ verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS), } export default ItemContent
src/js/components/Cursor.js
jhsu/spears-vr
import {Animation, Entity} from 'aframe-react'; import React from 'react'; export default props => { const geometry = { primitive: 'ring', radiusInner: 0.01, radiusOuter: 0.016 }; const material = { color: props.color, shader: 'flat', opacity: props.opacity || 0.9, transparent: true }; return ( <Entity cursor={props} geometry={geometry} material={material} position="0 0 -1"> <Animation attribute="scale" begin="click" dur="150" fill="backwards" to="0 0 0"/> </Entity> ); }
src/components/video_list.js
johncpatterson/Learning-React
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return ( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} /> ); }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
src/app/components/media/MediaCreatedBy.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage, intlShape } from 'react-intl'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import CheckChannels from '../../CheckChannels'; const useStyles = makeStyles(() => ({ createdBy: { fontSize: '9px', }, })); const messages = defineMessages({ import: { id: 'mediaAnalysis.import', defaultMessage: 'Import', description: 'Creator that refers to items created via Fetch or Zapier.', }, tipline: { id: 'mediaAnalysis.tipline', defaultMessage: 'Tipline', description: 'Creator that refers to items created via tiplines.', }, webform: { id: 'mediaAnalysis.webForm', defaultMessage: 'Web Form', description: 'Creator that refers to items created via web forms.', }, shareddatabase: { id: 'mediaAnalysis.sharedDatabase', defaultMessage: 'Shared Database', description: 'Creator that refers to items created from the shared database.', }, }); const MediaCreatedBy = ({ projectMedia, intl }) => { const { creator_name: creatorName, user_id: userId, channel, } = projectMedia; const classes = useStyles(); const showUserName = [CheckChannels.MANUAL, CheckChannels.BROWSER_EXTENSION].indexOf(channel.toString()) !== -1; const channelNameKey = creatorName.replace(/[ _-]+/g, '').toLocaleLowerCase(); const formattedChannelName = Object.keys(messages).includes(channelNameKey) ? intl.formatMessage(messages[channelNameKey]) : creatorName; return ( <Typography className={classes.createdBy} variant="body" component="div"> <FormattedMessage id="mediaCreatedBy.createdBy" defaultMessage="Item created by {name}" values={{ name: showUserName ? <a href={`/check/user/${userId}`}>{creatorName}</a> : formattedChannelName, }} /> </Typography> ); }; MediaCreatedBy.propTypes = { projectMedia: PropTypes.shape({ user_id: PropTypes.number.isRequired, creator_name: PropTypes.string.isRequired, channel: PropTypes.string.isRequired, }).isRequired, intl: intlShape.isRequired, }; export default injectIntl(MediaCreatedBy);
src/components/ui/InputGroup.js
ntxcode/react-base
import React from 'react'; import { Field } from 'redux-form'; import './InputGroup.css'; const InputGroup = props => <div className="InputGroup"> {props.icon} <Field className="FormInput" name={props.name} component="input" type={props.type} placeholder={props.placeholder} /> <label htmlFor={props.name} className="FormLabel">{props.label}</label> </div>; export default InputGroup;
src/svg-icons/notification/vibration.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationVibration = (props) => ( <SvgIcon {...props}> <path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/> </SvgIcon> ); NotificationVibration = pure(NotificationVibration); NotificationVibration.displayName = 'NotificationVibration'; NotificationVibration.muiName = 'SvgIcon'; export default NotificationVibration;
client/components/Pages/DbTest/TasksMain.js
Extra-lightwill/gql-sequelize-ver01
import React from 'react'; import Relay from 'react-relay'; import addTaskMutation from './addTaskMutation'; const ENTER_KEY_CODE = 13; const ESC_KEY_CODE = 27; class TasksMain extends React.Component { constructor( props ) { super( props ); this.state = { viewer: this.props.viewer, tasks: this.props.viewer.tasks, isEditing: false, text: this.props.initialValue || '', }; this._onNewTaskSave = this._onNewTaskSave.bind(this); this._handleTextInputCancel = this._handleTextInputCancel.bind(this); this._commitChanges = this._commitChanges.bind(this); } _onNewTaskSave = (text) => { this.props.relay.commitUpdate( new addTaskMutation({ viewer: this.props.viewer, text }) ); }; /*_onTextInputSave = (text) => { const { relay, task } = this.props; this.setEditMode(false); relay.commitUpdate( new RenameTodoMutation({ task, text }) ); };*/ _setEditMode(isEditing) { this.setState({ isEditing }); } renderTasks() { const { viewer, tasks } = this.props; return viewer.tasks.edges.map(({ node }) => ( <div key={node.id} viewer={viewer} task={node} /> )); } onKeyDown = (e) => { if (this._handleTextInputCancel && e.keyCode === ESC_KEY_CODE) { this._handleTextInputCancel(); } else if (e.keyCode === ENTER_KEY_CODE) { this._commitChanges(); } }; onChange = (e) => { this.setState({ text: e.target.value }); }; onBlur = () => { if (this.props.commitOnBlur) { this._onNewTaskSave(); } }; _commitChanges() { const newText = this.state.text.trim(); if (newText !== '') { this.setState({ text: '' }); } } /*else if (newText !== '') { this.props.onSave(newText); this.setState({text: ''}) */ /*_handleTextInputSave = (text) => { this._setEditMode(false); this.props.relay.commitUpdate( new RenameTodoMutation({tasks: this.props.todo, text}) );*/ _handleTextInputCancel = () => { this._setEditMode(false); }; render () { const { viewer, children, relay, text } = this.props; return ( <div> <button onClick={this._onNewTaskSave}>Add new task!</button> <button>Edit task</button> <br /> <br /> <input //{...this.props} placeholder="add a new task here" onKeyDown={this.onKeyDown} onChange={this.onChange} onBlur={this.onBlur} value={this.state.text} /> <br /> <br /> <div> I am a list of tasks: <br /> <br /> {this.renderTasks()} </div> <div> TOTAL COUNT (TASKS): </div> </div> ) } } export default Relay.createContainer( TasksMain, { fragments: { viewer: () => Relay.QL` fragment on User { tasks ( first: 2147483647 ) { edges }, ${addTaskMutation.getFragment('viewer')} }` }, }); /* {this.renderTasks()} */
admin/client/App/shared/Portal.js
brianjd/keystone
/** * Used by the Popout component and the Lightbox component of the fields for * popouts. Renders a non-react DOM node. */ import React from 'react'; import ReactDOM from 'react-dom'; module.exports = React.createClass({ displayName: 'Portal', portalElement: null, // eslint-disable-line react/sort-comp componentDidMount () { const el = document.createElement('div'); document.body.appendChild(el); this.portalElement = el; this.componentDidUpdate(); }, componentWillUnmount () { document.body.removeChild(this.portalElement); }, componentDidUpdate () { ReactDOM.render(<div {...this.props} />, this.portalElement); }, getPortalDOMNode () { return this.portalElement; }, render () { return null; }, });
rio/assets/components/app.js
soasme/rio
import React from 'react' export default function App() { return <div>I am App!</div> }
client/lib/alert.js
pradel/octon
import React, { Component } from 'react'; import Button from 'material-ui/Button'; import Dialog, { DialogActions, DialogContent, DialogContentText, DialogTitle, } from 'material-ui/Dialog'; class Alert extends Component { constructor(props) { super(props); this.state = { isOpen: false, text: '', title: '', }; global.octonConfirm = this.showConfirm; } close = () => this.setState({ isOpen: false }); confirm = () => { this.close(); this.resolve(true); }; cancel = () => { this.close(); this.resolve(false); }; showConfirm = (title, text) => new Promise((resolve, reject) => { this.setState({ isOpen: true, isConfirm: true, text, title }); this.resolve = resolve; this.reject = reject; }); render() { const { isOpen, title, text } = this.state; return ( <Dialog open={isOpen} onRequestClose={this.handleRequestClose}> <DialogTitle>{title}</DialogTitle> <DialogContent> <DialogContentText>{text}</DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.confirm} color="accent">Confirm</Button> <Button onClick={this.cancel}>Cancel</Button> </DialogActions> </Dialog> ); } } export default Alert;
client/util/react-intl-test-helper.js
Investnaira/in
/** * Components using the react-intl module require access to the intl context. * This is not available when mounting single components in Enzyme. * These helper functions aim to address that and wrap a valid, * English-locale intl context around them. */ import React from 'react'; import { IntlProvider, intlShape } from 'react-intl'; import { mount, shallow } from 'enzyme'; // You can pass your messages to the IntlProvider. Optional: remove if unneeded. const messages = require('../../Intl/localizationData/en'); // Create the IntlProvider to retrieve context for wrapping around. const intlProvider = new IntlProvider({ locale: 'en', messages }, {}); export const { intl } = intlProvider.getChildContext(); /** * When using React-Intl `injectIntl` on components, props.intl is required. */ const nodeWithIntlProp = node => { return React.cloneElement(node, { intl }); }; export const shallowWithIntl = node => { return shallow(nodeWithIntlProp(node), { context: { intl } }); }; export const mountWithIntl = node => { return mount(nodeWithIntlProp(node), { context: { intl }, childContextTypes: { intl: intlShape }, }); };
src/Row.js
zerkms/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;
examples/with-rtlcss/src/App.js
suitejs/suite
import React from 'react'; import Button from 'rsuite/es/Button'; import ButtonToolbar from 'rsuite/es/ButtonToolbar'; import Progress from 'rsuite/es/Progress'; import Slider from 'rsuite/es/Slider'; import IntlProvider from 'rsuite/es/IntlProvider'; import { writeDirection } from './utils'; function App() { const [direction, setDirection] = React.useState(false); const onChangeDirection = dir => { setDirection(dir); writeDirection(dir); }; return ( <div style={{ padding: 100 }}> <IntlProvider rtl={direction === 'rtl'}> <ButtonToolbar> <Progress.Line percent={30} status="active" /> <hr /> <Slider /> <hr /> <Button onClick={() => { onChangeDirection('rtl'); }} > Right to Left </Button> <Button onClick={() => { onChangeDirection('ltr'); }} > Left to Right </Button> </ButtonToolbar> </IntlProvider> </div> ); } export default App;
fields/types/location/LocationColumn.js
brianjd/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country']; var LocationColumn = React.createClass({ displayName: 'LocationColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return null; const output = []; SUB_FIELDS.map((i) => { if (value[i]) { output.push(value[i]); } }); return ( <ItemsTableValue field={this.props.col.type} title={output.join(', ')}> {output.join(', ')} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = LocationColumn;
app-reflux/test/test-pm.js
Orientsoft/borgnix-cloud-ide
import React from 'react' import projectActions from '../actions/project-actions' class TestPM extends React.Component { constructor(props) { super(props) this.state = { projects: this.props.projects , activeProjectName: this.props.activeProjectName , activeFileName: this.props.activeFileName } } componentWillUpdate() { console.log('will update') // console.log(this.state) } componentWillReceiveProps(props) { // console.log(a) this.setState(props) } _getProjectsTree() { let self = this return this.state.projects.map((project)=>{ return ( <div> <button style={{ backgroundColor: ( project.name === self.state.activeProjectName ? 'red' : 'white' ) }} onClick={ projectActions.switchProject.bind(null, project.name) }> {project.name} </button> <ul> { project.files.map((file)=>{ return ( <li> <button style={{ backgroundColor: this.state.activeFileName === file.name ? 'red' : 'white' }} onClick={ projectActions.switchFile.bind(null, file.name) }> {file.name} </button> </li> ) }) } </ul> </div> ) }) } render() { return ( <div> {this._getProjectsTree()} </div> ) } } TestPM.propTypes = { activeFileName: React.PropTypes.String , activeProjectName: React.PropTypes.String , projects: React.PropTypes.Array } TestPM.defaultProps = { activeFileName: '' , activeProjectName: '' , projects: [] } export default TestPM
src/index.js
dhorelik/my-locations
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { Router, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import configureStore from './store/configureStore' import routes from './routes' const store = configureStore() const history = syncHistoryWithStore(browserHistory, store) render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('app') )
src/pages/HomePage.js
belaczek/BeerCheese-client
import React, { Component } from 'react'; import { Row, Col, Button, Nav, NavItem, NavLink, NavbarBrand } from 'reactstrap'; import ProductList from '../components/product/ProductList'; import localizedTexts from '../text_localization/LocalizedStrings'; import FontAwesome from 'react-fontawesome'; import { categoriesApi } from '../actions/categories'; import { Link } from 'react-router'; import Loading from '../components/images/Loading'; import { connect } from 'react-redux'; class HomePage extends Component { state = { expandedCategory: null }; componentWillMount() { // get products this.props.categoriesApi(); } renderSubNav(parent) { const categories = this.props.categories; const expandedCategory = this.state.expandedCategory; return categories.categories.map(category => { category = category.category; if ( category.mainCategory === parent.links.self && expandedCategory !== null && expandedCategory.id === parent.id ) { return ( <NavItem key={category.id} style={{ marginLeft: '20px' }}> <NavLink tag={Link} to={'/?category=' + category.id}> {category.name} </NavLink> </NavItem> ); } else { return null; } }); } renderNav() { const categories = this.props.categories; if (categories.isFetching || categories.categories === null) { return <Loading />; } return categories.categories.map(category => { category = category.category; if (typeof category.mainCategory === 'undefined') { return ( <div key={category.id}> <NavItem> <NavLink onClick={() => this.setState({ expandedCategory: category })} tag={Link} to={'/?category=' + category.id} > {category.name} </NavLink> </NavItem> {this.renderSubNav(category)} </div> ); } else { return null; } }); } render() { return ( <Row> <Col md="12"> <h2 className="text-center mt-3 mb-5"> {localizedTexts.HomePage.welcomeMessage} </h2> </Col> <Col xl="3" lg="3" md="4" sm="12" xs="12" className="mb-3"> <Nav pills vertical> <NavbarBrand>{localizedTexts.HomePage.categories}</NavbarBrand> {this.renderNav()} <NavItem> <Link to="/create-package"> <Button color="secondary" size="lg"> {localizedTexts.HomePage.createPackage} {' '} <FontAwesome style={{ fontSize: '25px' }} name="gift" /> </Button> </Link> </NavItem> </Nav> </Col> <Col xl="9" lg="9" md="8" sm="12" xs="12"> <ProductList itemSize="250" categoryId={ typeof this.props.location.query.category === 'undefined' ? null : this.props.location.query.category } /> </Col> </Row> ); } } const mapSateToProps = state => ({ categories: state.categories }); export default connect(mapSateToProps, { categoriesApi })(HomePage);
actor-apps/app-web/src/app/components/common/Banner.react.js
Dreezydraig/actor-platform
import React from 'react'; import BannerActionCreators from 'actions/BannerActionCreators'; class Banner extends React.Component { constructor(props) { super(props); if (window.localStorage.getItem('banner_jump') === null) { BannerActionCreators.show(); } } onClose = () => { BannerActionCreators.hide(); }; onJump = (os) => { BannerActionCreators.jump(os); this.onClose(); }; render() { return ( <section className="banner"> <p> Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps! </p> <a className="banner__hide" onClick={this.onClose}> <i className="material-icons">close</i> </a> </section> ); } } export default Banner;
packages/material-ui-icons/legacy/SignalCellular3BarSharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M2 22h20V2L2 22z" /><path d="M17 7L2 22h15V7z" /></React.Fragment> , 'SignalCellular3BarSharp');
app/HomeTab/views/detailPage.js
hakale/bestCarRent
import React, { Component } from 'react'; import { StyleSheet, Text, View, ScrollView, Image, TouchableOpacity } from 'react-native'; import {hostip} from '../../config' import BannerLite from 'react-native-banner-lite'; import { List , Button, Divider } from 'react-native-elements'; export default class DetailPage extends Component { static navigationOptions = ({ navigation, screenProps }) => ({ title: "Detail", }); constructor(props) { super(props) this.state = { carImagList : [ { title: "", subtitle: "", imageURL: "", }, { title: "", subtitle: "", imageURL: "", }, { title: "", subtitle: "", imageURL: "", }, ] } console.log('Pare fetch') // fetch(hostip + '/api/post/car_detail', { // method: 'POST', // headers: { // 'Accept': 'application/json', // 'Content-Type': 'application/json', // }, // body: JSON.stringify({ // car_id: this.props.navigation.state.params.carID // }) // }) // .then((response) => { // return response.json()}) // .then((responseJson) => { // console.log('Json', responseJson) // if (responseJson.MESSAGE == 'SUCCESS') { // this.setState( // () =>{ // return { // carImagList: responseJson.DATA.imagelist, // // } // } // ) // } // else { // ToastAndroid.showWithGravity( // responseJson.MESSAGE, // ToastAndroid.SHORT, ToastAndroid.CENTER // ) // } // }) // .catch((error) => { // console.error(error); // ToastAndroid.showWithGravity( // '网络开小差了,稍后重试', // ToastAndroid.SHORT, ToastAndroid.CENTER // ) // }); } onRentButtonPress = (carID) => { this.props.navigation.navigate('CHECK_OUT', carID); } render() { const { carName, } = this.props.navigation.state.params; return ( <ScrollView> <View style={{height:150}}> <BannerLite items={this.state.carImagList} /> </View> <View style={{ paddingHorizontal: 15 }}> <Text style={styles.textStyle}>Tuck</Text> </View> <View style={{flexDirection: 'row', paddingHorizontal: 15, marginVertical: 10,justifyContent: 'space-between'}}> <Text style={styles.textStyle}>Price</Text> <Button title='租车' raised icon={{name: 'local-grocery-store', }} onPress={() => this.onRentButtonPress({carID: 3})}/> </View> <Divider style={{ backgroundColor: 'blue' }} /> </ScrollView> ); } } const styles = StyleSheet.create({ wrapper: { // flex: 1 height: 100 }, textStyle: { fontSize: 20 } })
admin/client/views/signin.js
suryagh/keystone
'use strict'; import classnames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import SessionStore from '../stores/SessionStore'; import { Alert, Button, Form, FormField, FormInput } from 'elemental'; import { createHistory } from 'history'; var history = createHistory(); var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout', }; }, componentDidMount () { if (this.state.signedOut && window.history.replace) { history.replace({}, window.location.pathname); } if (this.refs.email) { ReactDOM.findDOMNode(this.refs.email).select(); } }, handleInputChange (e) { const newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } SessionStore.signin({ email: this.state.email, password: this.state.password, }, (err, data) => { if (err || data && data.error) { this.displayError('The email and password you entered are not valid.'); } else { top.location.href = this.props.from ? this.props.from : Keystone.adminPath; } }); }, displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message, }); setTimeout(this.finishAnimation, 750); }, finishAnimation () { if (!this.isMounted()) return; if (this.refs.email) { ReactDOM.findDOMNode(this.refs.email).select(); } this.setState({ isAnimating: false, }); }, renderBrand () { let logo = { src: `${Keystone.adminPath}/images/logo.png`, width: 205, height: 68 }; if (this.props.logo) { logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo; // TODO: Deprecate this if (Array.isArray(logo)) { logo = { src: logo[0], width: logo[1], height: logo[2] }; } } return ( <div className="auth-box__col"> <div className="auth-box__brand"> <a href="/" className="auth-box__brand__logo"> <img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} /> </a> </div> </div> ); }, renderUserInfo () { if (!this.props.user) return null; const openKeystoneButton = this.props.userCanAccessKeystone ? <Button href={Keystone.adminPath} type="primary">Open Keystone</Button> : null; return ( <div className="auth-box__col"> <p>Hi {this.props.user.name.first},</p> <p>You're already signed in.</p> {openKeystoneButton} <Button href={`${Keystone.adminPath}/signout`} type="link-cancel">Sign Out</Button> </div> ); }, renderAlert () { if (this.state.isInvalid) { return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>; } else if (this.state.signedOut) { return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>; } else { /* eslint-disable react/self-closing-comp */ // TODO: This probably isn't the best way to do this, we // shouldn't be using Elemental classNames instead of components return <div key="fake" className="Alert Alert--placeholder">&nbsp;</div>; /* eslint-enable */ } }, renderForm () { if (this.props.user) return null; return ( <div className="auth-box__col"> <Form method="post" onSubmit={this.handleSubmit} noValidate> <FormField label="Email" htmlFor="email"> <FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" /> </FormField> <FormField label="Password" htmlFor="password"> <FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" /> </FormField> <Button disabled={this.state.animating} type="primary" submit>Sign In</Button> {/* <Button disabled={this.state.animating} type="link-text">Forgot Password?</Button> */} </Form> </div> ); }, render () { const boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating, }); return ( <div className="auth-wrapper"> {this.renderAlert()} <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> {this.renderBrand()} {this.renderUserInfo()} {this.renderForm()} </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); }, }); ReactDOM.render( <SigninView brand={Keystone.brand} from={Keystone.from} logo={Keystone.logo} user={Keystone.user} userCanAccessKeystone={Keystone.userCanAccessKeystone} />, document.getElementById('signin-view') );
src/Application.js
TheEvilCorp/OverReact
import React, { Component } from 'react'; import Gui from './Gui'; import Options from './Options'; export default class Application extends Component { shouldComponentUpdate = (nextProps, nextState) => { return this.props !== nextProps; }; render() { return ( <div className='appContainer' id='application-section'> <Gui className='appChild'/> <Options className='appChild' submit={this.props.submit}/> </div> ) }; };
client/src/components/forms/Security.js
DjLeChuck/recalbox-manager
import React from 'react'; import PropTypes from 'prop-types'; import { translate } from 'react-i18next'; import { Form } from 'react-form'; import BootstrapForm from 'react-bootstrap/lib/Form'; import Panel from 'react-bootstrap/lib/Panel'; import { getDefaultValues } from './utils'; import FormActions from './FormActions'; import SwitchInput from './inputs/Switch'; import SimpleInput from './inputs/Simple'; const SecurityForm = ({ t, saving, onSubmit, defaultValues }) => ( <Form onSubmit={values => onSubmit(values)} defaultValues={getDefaultValues(defaultValues)} validate={({ needAuth, login, password }) => { return { login: needAuth && !login ? t("L'identifiant est obligatoire.") : undefined, password: needAuth && !password ? t("Le mot de passe est obligatoire.") : undefined, }; }} > {({ submitForm, resetForm }) => ( <BootstrapForm onSubmit={submitForm} horizontal> <Panel header={<h3>{t('Authentification requise')}</h3>}> <SwitchInput id="needAuth" field="needAuth" /> </Panel> <Panel header={<h3>{t('Identifiants de connexion')}</h3>}> <SimpleInput id="login" field="login" label={t('Identifiant')} /> <SimpleInput type="password" id="password" field="password" label={t('Mot de passe')} warning={t("Le mot de passe n'est pas visible pour des raisons de sécurité.")} /> </Panel> <FormActions resetForm={resetForm} saving={saving} /> </BootstrapForm> )} </Form> ); SecurityForm.propTypes = { t: PropTypes.func.isRequired, saving: PropTypes.bool.isRequired, onSubmit: PropTypes.func.isRequired, defaultValues: PropTypes.object, }; export default translate()(SecurityForm);
app/javascript/mastodon/features/home_timeline/index.js
h3zjp/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { expandHomeTimeline } from '../../actions/timelines'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { Link } from 'react-router-dom'; import { fetchAnnouncements, toggleShowAnnouncements } from 'mastodon/actions/announcements'; import AnnouncementsContainer from 'mastodon/features/getting_started/containers/announcements_container'; import classNames from 'classnames'; import IconWithBadge from 'mastodon/components/icon_with_badge'; const messages = defineMessages({ title: { id: 'column.home', defaultMessage: 'Home' }, show_announcements: { id: 'home.show_announcements', defaultMessage: 'Show announcements' }, hide_announcements: { id: 'home.hide_announcements', defaultMessage: 'Hide announcements' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0, isPartial: state.getIn(['timelines', 'home', 'isPartial']), hasAnnouncements: !state.getIn(['announcements', 'items']).isEmpty(), unreadAnnouncements: state.getIn(['announcements', 'items']).count(item => !item.get('read')), showAnnouncements: state.getIn(['announcements', 'show']), }); export default @connect(mapStateToProps) @injectIntl class HomeTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, isPartial: PropTypes.bool, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasAnnouncements: PropTypes.bool, unreadAnnouncements: PropTypes.number, showAnnouncements: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HOME', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { this.props.dispatch(expandHomeTimeline({ maxId })); } componentDidMount () { this.props.dispatch(fetchAnnouncements()); this._checkIfReloadNeeded(false, this.props.isPartial); } componentDidUpdate (prevProps) { this._checkIfReloadNeeded(prevProps.isPartial, this.props.isPartial); } componentWillUnmount () { this._stopPolling(); } _checkIfReloadNeeded (wasPartial, isPartial) { const { dispatch } = this.props; if (wasPartial === isPartial) { return; } else if (!wasPartial && isPartial) { this.polling = setInterval(() => { dispatch(expandHomeTimeline()); }, 3000); } else if (wasPartial && !isPartial) { this._stopPolling(); } } _stopPolling () { if (this.polling) { clearInterval(this.polling); this.polling = null; } } handleToggleAnnouncementsClick = (e) => { e.stopPropagation(); this.props.dispatch(toggleShowAnnouncements()); } render () { const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn, hasAnnouncements, unreadAnnouncements, showAnnouncements } = this.props; const pinned = !!columnId; let announcementsButton = null; if (hasAnnouncements) { announcementsButton = ( <button className={classNames('column-header__button', { 'active': showAnnouncements })} title={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)} aria-label={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)} aria-pressed={showAnnouncements ? 'true' : 'false'} onClick={this.handleToggleAnnouncementsClick} > <IconWithBadge id='bullhorn' count={unreadAnnouncements} /> </button> ); } return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='home' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} extraButton={announcementsButton} appendContent={hasAnnouncements && showAnnouncements && <AnnouncementsContainer />} > <ColumnSettingsContainer /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`home_timeline-${columnId}`} onLoadMore={this.handleLoadMore} timelineId='home' emptyMessage={<FormattedMessage id='empty_column.home' defaultMessage='Your home timeline is empty! Visit {public} or use search to get started and meet other users.' values={{ public: <Link to='/timelines/public'><FormattedMessage id='empty_column.home.public_timeline' defaultMessage='the public timeline' /></Link> }} />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
app/javascript/mastodon/features/getting_started/components/trends.js
yi0713/mastodon
import React from 'react'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag'; import { FormattedMessage } from 'react-intl'; export default class Trends extends ImmutablePureComponent { static defaultProps = { loading: false, }; static propTypes = { trends: ImmutablePropTypes.list, fetchTrends: PropTypes.func.isRequired, }; componentDidMount () { this.props.fetchTrends(); this.refreshInterval = setInterval(() => this.props.fetchTrends(), 900 * 1000); } componentWillUnmount () { if (this.refreshInterval) { clearInterval(this.refreshInterval); } } render () { const { trends } = this.props; if (!trends || trends.isEmpty()) { return null; } return ( <div className='getting-started__trends'> <h4><FormattedMessage id='trends.trending_now' defaultMessage='Trending now' /></h4> {trends.take(3).map(hashtag => <Hashtag key={hashtag.get('name')} hashtag={hashtag} />)} </div> ); } }
src/@ui/Icon/icons/LikeSolid.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import { Svg } from '../../Svg'; import makeIcon from './makeIcon'; const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( <Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}> <Svg.Path d="M10.8 4.03l-.03.03h.1c.4.3.8.64 1.13 1.03.33-.4.72-.75 1.14-1.05h.1c-.02 0-.03-.02-.04-.03.97-.66 2.13-1.03 3.3-1.03C19.6 3 22 5.4 22 8.47c0 3.8-3.4 6.88-8.6 11.46l-1.4 1.4-1.4-1.4C5.4 15.36 2 12.27 2 8.48 2 5.38 4.4 3 7.5 3c1.17 0 2.33.37 3.3 1.03z" fill={fill} /> </Svg> )); Icon.propTypes = { size: PropTypes.number, fill: PropTypes.string, }; export default Icon;