path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/components/icons/PlayerClose.js
webrecorder/webrecorder
import React from 'react'; function Close() { return ( <svg width="20px" height="10px" viewBox="0 0 22 22" version="1.1" xmlns="http://www.w3.org/2000/svg"> <g id="Page-1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd" strokeLinecap="square"> <g id="About" transform="translate(-2367.000000, -280.000000)" stroke="#000000" strokeWidth="2"> <g id="New-Top-Bar" transform="translate(440.000000, 219.000000)"> <g id="Close-FAQ" transform="translate(1915.000000, 49.000000)"> <g id="Group" transform="translate(6.000000, 6.000000)"> <g id="Group-3" transform="translate(16.000000, 15.717157) rotate(45.000000) translate(-16.000000, -15.717157) translate(5.000000, 4.717157)"> <path d="M11,22 L11,-5.1159077e-13" id="Line" /> <path d="M-5.12478948e-13,11 L22,11" id="Line" /> </g> </g> </g> </g> </g> </g> </svg> ); } export default Close;
site/client.js
jgable/react-dnd
import React from 'react'; import { render } from 'react-dom'; import IndexPage from './IndexPage'; render( <IndexPage {...window.INITIAL_PROPS} />, document );
src/@ui/forms/BillingAddressForm/index.js
NewSpring/Apollos
import React from 'react'; import { View } from 'react-native'; import PropTypes from 'prop-types'; import { branch, renderComponent, compose, setPropTypes } from 'recompose'; import get from 'lodash/get'; import { withFormik } from 'formik'; import Yup from 'yup'; import withGive from '@data/withGive'; import withCheckout from '@data/withCheckout'; import { withRouter } from '@ui/NativeWebRouter'; import PaddedView from '@ui/PaddedView'; import TableView, { FormFields } from '@ui/TableView'; import ActivityIndicator from '@ui/ActivityIndicator'; import sentry from '@utils/sentry'; import * as Inputs from '@ui/inputs'; import Button from '@ui/Button'; import { withFieldValueHandler, withFieldTouchedHandler } from '../formikSetters'; import GeographicPicker from './GeographicPicker'; const enhance = compose( setPropTypes({ isLoading: PropTypes.bool, onSubmit: PropTypes.func, createFieldValueHandler: PropTypes.func, createFieldTouchedHandler: PropTypes.func, countries: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), label: PropTypes.string, }), ), states: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), label: PropTypes.string, }), ), values: PropTypes.shape({ countryId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), stateId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), street1: PropTypes.string, street2: PropTypes.string, city: PropTypes.string, zipCode: PropTypes.string, }), touched: PropTypes.shape({ countryId: PropTypes.bool, stateId: PropTypes.bool, street1: PropTypes.bool, street2: PropTypes.bool, city: PropTypes.bool, zipCode: PropTypes.bool, }), errors: PropTypes.shape({ countryId: PropTypes.string, stateId: PropTypes.string, street1: PropTypes.string, street2: PropTypes.string, city: PropTypes.string, zipCode: PropTypes.string, }), isSubmitting: PropTypes.bool, isValid: PropTypes.bool, }), branch(({ isLoading }) => isLoading, renderComponent(ActivityIndicator)), ); export const BillingAddressFormWithoutData = enhance( ({ createFieldValueHandler, createFieldTouchedHandler, handleSubmit, values = {}, countries = [], states = [], touched = {}, errors = {}, isSubmitting, isValid, }) => { const isUSOrCanada = values.countryId === 'US' || values.countryId === 'CA'; return ( <View> <TableView responsive={false}> <FormFields> <Inputs.Text label="Street Address" value={values.street1} onChangeText={createFieldValueHandler('street1')} onBlur={createFieldTouchedHandler('street1')} error={touched.street1 && errors.street1} /> <Inputs.Text label="Street Address (optional)" value={values.street2} onChangeText={createFieldValueHandler('street2')} onBlur={createFieldTouchedHandler('street2')} error={touched.street2 && errors.street2} /> <GeographicPicker label="Country" value={values.countryId} options={countries} onValueChange={createFieldValueHandler('countryId')} error={touched.countryId && errors.countryId} /> <Inputs.Text label="City" value={values.city} onChangeText={createFieldValueHandler('city')} onBlur={createFieldTouchedHandler('city')} error={touched.city && errors.city} /> {isUSOrCanada && ( <GeographicPicker label="State/Territory" value={values.stateId} options={states} onValueChange={createFieldValueHandler('stateId')} error={touched.stateId && errors.stateId} /> )} <Inputs.Text label="Zip/Postal" type="numeric" value={values.zipCode} onChangeText={createFieldValueHandler('zipCode')} onBlur={createFieldTouchedHandler('zipCode')} error={touched.zipCode && errors.zipCode} /> </FormFields> </TableView> <PaddedView> <Button onPress={handleSubmit} title="Next" disabled={!isValid} loading={isSubmitting} /> </PaddedView> </View> ); }, ); const validationSchema = Yup.object().shape({ street1: Yup.string().required('Street address is a required field'), street2: Yup.string().nullable(), city: Yup.string().required('City is a required field'), stateId: Yup.string(), countryId: Yup.string().required('Country is a required field'), zipCode: Yup.string().required('Zip Code is a required field'), }); const mapPropsToValues = props => ({ street1: get(props, 'contributions.street1') || get(props, 'person.home.street1', ''), street2: get(props, 'contributions.street2') || get(props, 'person.home.street2', ''), city: get(props, 'contributions.city') || get(props, 'person.home.city', ''), stateId: get(props, 'contributions.stateId') || get(props, 'person.home.stateId') || 'SC', countryId: get(props, 'contributions.countryId') || get(props, 'person.home.countryId') || 'US', zipCode: get(props, 'contributions.zipCode') || get(props, 'person.home.zip', ''), }); const BillingAddressForm = compose( withGive, withCheckout, withRouter, withFormik({ mapPropsToValues, validationSchema, isInitialValid(props) { return validationSchema.isValidSync(mapPropsToValues(props)); }, handleSubmit: async (formValues, { props, setSubmitting }) => { try { setSubmitting(true); props.setBillingAddress(formValues); setSubmitting(false); if (props.navigateToOnComplete) props.history.push(props.navigateToOnComplete); } catch (e) { // TODO: If there's an error, we want to stay on this page and display it. sentry.captureException(e); } }, }), withFieldValueHandler, withFieldTouchedHandler, )(BillingAddressFormWithoutData); export default BillingAddressForm;
app/containers/Account/Login/index.js
rayrw/skygear-apitable
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { push as changeRouteAction } from 'react-router-redux'; import { showNotification as showNotificationAction } from 'containers/Notification/actions'; import * as actions from './actions'; import AccountLogin from '../../../components/Account/Login'; type AccountLoginContainerProps = { attemptLogin: Function, changeRoute: Function, showNotification: Function } class AccountLoginContainer extends Component { props: AccountLoginContainerProps handleSubmit = (values) => { const email = values.get('email'); const password = values.get('password'); const { attemptLogin, changeRoute, showNotification } = this.props; return new Promise((resolve, reject) => { attemptLogin(email, password, resolve, reject); }) .then(() => changeRoute('/')) .catch(showNotification); } render() { return ( <AccountLogin onSubmit={this.handleSubmit} /> ); } } export default connect( null, { changeRoute: changeRouteAction, showNotification: showNotificationAction, ...actions, }, )(AccountLoginContainer);
src/containers/progress/Progress.js
UNumbervan/todo-shmodo
import React from 'react'; import LinearProgress from 'material-ui/LinearProgress'; import {connect} from 'react-redux'; import {createSelector} from 'reselect'; class Progress extends React.Component { render() { return ( <LinearProgress mode="determinate" value={this.props.progress}/> ); } } const progressSelector = createSelector( state => state.categories.present, state => state.todos.present, (categories, todos) => { const notCompletedTasksByCategories = {}; todos.forEach(t => { if (!t.completed) { notCompletedTasksByCategories[t.category] = true; } }); return (1 - (Object.keys(notCompletedTasksByCategories).length / categories.length)) * 100; } ); const mapStateToProps = (state) => ({ progress: progressSelector(state) }); export default connect( mapStateToProps )(Progress);
src/app.js
scotchfield/react-rpg
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link } from 'react-router' import Character from './components/Character' import Dungeon from './components/Dungeon' class App extends React.Component { render () { return ( <div className="Container"> <h1>React RPG</h1> <ul> <li><Link to={App.path}>Home</Link></li> <li><Link to={Character.path}>Character</Link></li> <li><Link to={Dungeon.path}>Dungeon</Link></li> </ul> {this.props.children} </div> ) } }; App.title = 'React RPG' App.path = '/' render(( <Router history={browserHistory}> <Route path={App.path} component={App}> <Route path={Character.path} component={Character} /> <Route path={Dungeon.path} component={Dungeon} /> </Route> </Router> ), document.getElementById('content'))
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js
NS-Kazuki/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import IconButton from '../../../components/icon_button'; import { changeComposeSensitivity } from '../../../actions/compose'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ marked: { id: 'compose_form.sensitive.marked', defaultMessage: 'Media is marked as sensitive' }, unmarked: { id: 'compose_form.sensitive.unmarked', defaultMessage: 'Media is not marked as sensitive' }, }); const mapStateToProps = state => ({ visible: state.getIn(['compose', 'media_attachments']).size > 0, active: state.getIn(['compose', 'sensitive']), disabled: state.getIn(['compose', 'spoiler']), }); const mapDispatchToProps = dispatch => ({ onClick () { dispatch(changeComposeSensitivity()); }, }); class SensitiveButton extends React.PureComponent { static propTypes = { visible: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { visible, active, disabled, onClick, intl } = this.props; return ( <Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}> {({ scale }) => { const icon = active ? 'eye-slash' : 'eye'; const className = classNames('compose-form__sensitive-button', { 'compose-form__sensitive-button--visible': visible, }); return ( <div className={className} style={{ transform: `scale(${scale})` }}> <IconButton className='compose-form__sensitive-button__icon' title={intl.formatMessage(active ? messages.marked : messages.unmarked)} icon={icon} onClick={onClick} size={18} active={active} disabled={disabled} style={{ lineHeight: null, height: null }} inverted /> </div> ); }} </Motion> ); } } export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
app/components/Footer.js
trussworks/DoDidDone
import React from 'react'; export const Footer = () => ( <div className="footer"> <p>Copyright TrussWorks, 2016</p> </div> ); export default Footer;
src/svg-icons/action/visibility-off.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionVisibilityOff = (props) => ( <SvgIcon {...props}> <path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/> </SvgIcon> ); ActionVisibilityOff = pure(ActionVisibilityOff); ActionVisibilityOff.displayName = 'ActionVisibilityOff'; ActionVisibilityOff.muiName = 'SvgIcon'; export default ActionVisibilityOff;
src/Components/Header/index.js
gronda-team/react-searchable-select
import React from 'react'; import styled from 'styled-components'; import logo from '../../../public/gronda_logo_side.png'; const styles = { wrapper: { height: 150, background: "white", margin: "0px auto", color: "#102030", marginBottom: 100, fontWeight: "bold", display: "flex", justifyContent: "center", verticalAlign: "middle" } } const ImageWrapper = styled.div` display: flex; justify-content: center; align-items: center; `; class Header extends React.Component { render(){ return ( <div style={styles.wrapper}> <ImageWrapper> <img src={logo} alt="Gronda" /> </ImageWrapper> </div> ) } } export default Header;
examples/basic-board/src/App.js
Hellenic/react-hexgrid
import React, { Component } from 'react'; import { HexGrid, Layout, Hexagon, GridGenerator } from 'react-hexgrid'; import './App.css'; class App extends Component { render() { const hexagons = GridGenerator.parallelogram(-2, 3, -2, 1); return ( <div className="App"> <h1>Basic example of HexGrid usage.</h1> <HexGrid width={1200} height={1000}> <Layout size={{ x: 7, y: 7 }}> { hexagons.map((hex, i) => <Hexagon key={i} q={hex.q} r={hex.r} s={hex.s} />) } </Layout> </HexGrid> </div> ); } } export default App;
test/test_helper.js
RedZulu/ReduxArt
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/svg-icons/device/battery-60.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery60 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h10V5.33z"/><path d="M7 11v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11H7z"/> </SvgIcon> ); DeviceBattery60 = pure(DeviceBattery60); DeviceBattery60.displayName = 'DeviceBattery60'; DeviceBattery60.muiName = 'SvgIcon'; export default DeviceBattery60;
src/containers/Block.js
zachlevy/react-playground
import React from 'react' import { connect } from 'react-redux' import Content from '../containers/Content' const mapStateToProps = (state) => ({ theme: state.theme }) const templates = [ { name: "sidebar-right", contents: 2, template: ( <div className="row"> <div className="col-xs-12 col-sm-8"> <h3>Left Content</h3> </div> <div className="col-xs-12 col-sm-4"> <h3>Right Sidebar</h3> </div> </div> ) }, { name: "sidebar-left", contents: 2, template: ( <div className="row"> <div className="col-xs-12 col-sm-4"> <h3>Left Sidebar</h3> </div> <div className="col-xs-12 col-sm-8"> <h3>Right Content</h3> </div> </div> ) } ] let Block = ({ theme }) => ( <div className={`block`}> <h2>Block</h2> <Content template={templates[0].template} /> </div> ) Block = connect( mapStateToProps )(Block) export default Block
src/routes.js
GBLin5566/BackExchange
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; import App from './components/App'; import Home from './components/Home'; import Profile from './components/Profile'; import FriendList from './components/FriendList'; import NotFound from './components/NotFound'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/profile" component={Profile} /> <Route path="/friends" component={FriendList} /> <Redirect from="/abc" to="/" /> <Route path="*" component={NotFound} /> </Route> );
client/index.js
hankthewhale/reactexpress
import React from 'react'; import ReactDOM from 'react-dom'; import App from 'components/app' ReactDOM.render(<App />, document.getElementById('app'));
src/app.js
kngroo/Kngr
import React, { Component } from 'react'; import Header from './header'; import Navbar from './navbar'; require('./styles/normalize.scss'); require('./styles/skeleton.scss'); require('./styles/app.scss'); export default class App extends Component { constructor(props) { super(props); } componentDidMount() { window.addEventListener('scroll', this.handleScroll.bind(this)); } handleScroll() { this.navOffsetTop = document.getElementById('navbar').getBoundingClientRect().top; this.hasDockedNav = document.body.classList.contains('has-docked-nav'); if (this.navOffsetTop < 0 && !this.hasDockedNav) { document.body.classList.add('has-docked-nav'); } if (this.navOffsetTop >= 0 && this.hasDockedNav) { document.body.classList.remove('has-docked-nav'); } } render() { return ( <div className="container"> <Header /> <Navbar /> {this.props.children} </div> ); } }
lib/cli/test/snapshots/react_native/storybook/stories/Button/index.ios.js
rhalff/storybook
import React from 'react'; import PropTypes from 'prop-types'; import { TouchableHighlight } from 'react-native'; export default function Button(props) { return <TouchableHighlight onPress={props.onPress}>{props.children}</TouchableHighlight>; } Button.defaultProps = { children: null, onPress: () => {}, }; Button.propTypes = { children: PropTypes.node, onPress: PropTypes.func, };
client/src/components/Loader.js
redcom/pinstery
// @flow import React from 'react'; import styled from 'styled-components'; const LoaderBox = styled.div` background: url('../../assets/loader.svg'); background-repeat: no-repeat; height: ${props => (props.type === 'small' ? '100px' : 'calc(50vh)')}; background-position: center center; `; type Props = { loading: boolean, type: string, onLoaded: Function, }; const Loader = ({ loading = true, type = '', onLoaded }: Props) => loading ? <LoaderBox type={type} /> : onLoaded(); export default Loader;
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
liruqi/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class UserProfileContactInfo extends React.Component { static propTypes = { phones: React.PropTypes.array }; constructor(props) { super(props); } render() { let phones = this.props.phones; let contactPhones = _.map(phones, (phone, i) => { return ( <li className="profile__list__item row" key={i}> <i className="material-icons">call</i> <div className="col-xs"> <span className="contact">+{phone.number}</span> <span className="title">{phone.title}</span> </div> </li> ); }); return ( <ul className="profile__list profile__list--contacts"> {contactPhones} </ul> ); } } export default UserProfileContactInfo;
react/features/large-video/components/LargeVideoBackground.web.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { connect } from '../../base/redux'; import { shouldDisplayTileView } from '../../video-layout'; /** * Constants to describe the dimensions of the video. Landscape videos * are wider than they are taller and portrait videos are taller than they * are wider. The dimensions will determine how {@code LargeVideoBackground} * will stretch to fill its container. * * @type {Object} */ export const ORIENTATION = { LANDSCAPE: 'landscape', PORTRAIT: 'portrait' }; /** * The type of the React {@code Component} props of * {@link LargeVideoBackgroundCanvas}. */ type Props = { /** * Whether or not the layout should change to support tile view mode. * * @protected * @type {boolean} */ _shouldDisplayTileView: boolean, /** * Additional CSS class names to add to the root of the component. */ className: String, /** * Whether or not the background should have its visibility hidden. */ hidden: boolean, /** * Whether or not the video should display flipped horizontally, so left * becomes right and right becomes left. */ mirror: boolean, /** * Whether the component should ensure full width of the video is displayed * (landscape) or full height (portrait). */ orientationFit: string, /** * The video stream to display. */ videoElement: Object }; /** * Implements a React Component which shows a video element intended to be used * as a background to fill the empty space of container with another video. * * @augments Component */ export class LargeVideoBackground extends Component<Props> { _canvasEl: Object; _updateCanvasInterval: *; /** * Initializes new {@code LargeVideoBackground} instance. * * @param {*} props - The read-only properties with which the new instance * is to be initialized. */ constructor(props: Props) { super(props); // Bind event handlers so they are only bound once per instance. this._setCanvasEl = this._setCanvasEl.bind(this); this._updateCanvas = this._updateCanvas.bind(this); } /** * If the canvas is not hidden, sets the initial interval to update the * image displayed in the canvas. * * @inheritdoc * @returns {void} */ componentDidMount() { const { _shouldDisplayTileView, hidden, videoElement } = this.props; if (videoElement && !hidden && !_shouldDisplayTileView) { this._updateCanvas(); this._setUpdateCanvasInterval(); } } /** * Starts or stops the interval to update the image displayed in the canvas. * * @inheritdoc */ componentDidUpdate(prevProps: Props) { const wasCanvasUpdating = !prevProps.hidden && !prevProps._shouldDisplayTileView && prevProps.videoElement; const shouldCanvasUpdating = !this.props.hidden && !this.props._shouldDisplayTileView && this.props.videoElement; if (wasCanvasUpdating !== shouldCanvasUpdating) { if (shouldCanvasUpdating) { this._clearCanvas(); this._setUpdateCanvasInterval(); } else { this._clearCanvas(); this._clearUpdateCanvasInterval(); } } } /** * Clears the interval for updating the image displayed in the canvas. * * @inheritdoc */ componentWillUnmount() { this._clearUpdateCanvasInterval(); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { hidden, mirror } = this.props; const classNames = `large-video-background ${mirror ? 'flip-x' : ''} ${hidden ? 'invisible' : ''}`; return ( <div className = { classNames }> <canvas id = 'largeVideoBackground' ref = { this._setCanvasEl } /> </div> ); } /** * Removes any image displayed on the canvas. * * @private * @returns {void} */ _clearCanvas() { const cavnasContext = this._canvasEl.getContext('2d'); cavnasContext.clearRect( 0, 0, this._canvasEl.width, this._canvasEl.height); } /** * Clears the interval for updating the image displayed in the canvas. * * @private * @returns {void} */ _clearUpdateCanvasInterval() { clearInterval(this._updateCanvasInterval); } _setCanvasEl: () => void; /** * Sets the instance variable for the component's canvas element so it can * be accessed directly for drawing on. * * @param {Object} element - The DOM element for the component's canvas. * @private * @returns {void} */ _setCanvasEl(element) { this._canvasEl = element; } /** * Starts the interval for updating the image displayed in the canvas. * * @private * @returns {void} */ _setUpdateCanvasInterval() { this._clearUpdateCanvasInterval(); this._updateCanvasInterval = setInterval(this._updateCanvas, 200); } _updateCanvas: () => void; /** * Draws the current frame of the passed in video element onto the canvas. * * @private * @returns {void} */ _updateCanvas() { // On Electron 7 there is a memory leak if we try to draw into a hidden canvas that is part of the DOM tree. // See: https://github.com/electron/electron/issues/22417 // Trying to detect all the cases when the page will be hidden because of something not in our control // (for example when the page is loaded in an iframe which is hidden due to the host page styles) to solve // the memory leak. Currently we are not handling the use case when the page is hidden with visibility:hidden // because we don't have a good way to do it. // All other cases when the canvas is not visible are handled through the component props // (hidden, _shouldDisplayTileView). if (!this._canvasEl || this._canvasEl.offsetParent === null || window.innerHeight === 0 || window.innerWidth === 0) { return; } const { videoElement } = this.props; const { videoWidth, videoHeight } = videoElement; const { height: canvasHeight, width: canvasWidth } = this._canvasEl; const cavnasContext = this._canvasEl.getContext('2d'); if (this.props.orientationFit === ORIENTATION.LANDSCAPE) { const heightScaledToFit = (canvasWidth / videoWidth) * videoHeight; cavnasContext.drawImage( videoElement, 0, 0, canvasWidth, heightScaledToFit); } else { const widthScaledToFit = (canvasHeight / videoHeight) * videoWidth; cavnasContext.drawImage( videoElement, 0, 0, widthScaledToFit, canvasHeight); } } } /** * Maps (parts of) the Redux state to the associated LargeVideoBackground props. * * @param {Object} state - The Redux state. * @private * @returns {{ * _shouldDisplayTileView: boolean * }} */ function _mapStateToProps(state) { return { _shouldDisplayTileView: shouldDisplayTileView(state) }; } export default connect(_mapStateToProps)(LargeVideoBackground);
front/app/app/rh-components/rh-Form.js
nudoru/React-Starter-2-app
import React from 'react'; import throttle from 'lodash/throttle'; import { getNextId } from '../utils/ElementIDCreator'; const NOOP = () => { }; const ONCHANGE_THROTTLE = 500; //------------------------------------------------------------------------------ // Groups //------------------------------------------------------------------------------ export const VForm = ({children}) => <form className="rh-vform">{children}</form>; export const HForm = ({children}) => <form className="rh-hform">{children}</form>; export const Fieldset = ({legend, children}) => { return ( <fieldset> {legend ? <legend>{legend}</legend> : null} {children} </fieldset> ); }; export const FormGroup = ({children}) => <div className="rh-form-group">{children}</div>; export const FormVGroup = ({children, label}) => { return (<div className="rh-form-v-group"> {label ? <Label>{label}</Label> : null} <div className="rh-form-v-group-controls">{children}</div> </div> ); }; export const FormHGroup = ({children, label}) => { return (<div className="rh-form-h-group"> {label ? <Label>{label}</Label> : null} <div className="rh-form-h-group-controls">{children}</div> </div> ); }; export const HInputGroup = ({children}) => <div className="rh-form-inline-controls">{children}</div>; export const HInputDecorator = ({icon, children}) => <div className="group-addon">{icon ? <i className={'fa fa-' + icon}/> : null}{children}</div>; export const FormHGroupRow = ({children, label}) => { let labelEl = label ? <label className="rh-form-inline-label">{label}</label> : null; return (<div className="rh-form-group"> {labelEl} <HInputGroup>{children}</HInputGroup> </div>); }; //------------------------------------------------------------------------------ // Elements //------------------------------------------------------------------------------ /* required active pristine normalized focus -> touched -> active blur -> validateFn -> error */ //https://hackernoon.com/10-react-mini-patterns-c1da92f068c5#.jnip3uvdo export const Label = ({children, htmlFor, ...other}) => <label htmlFor={htmlFor} {...other}>{children}</label>; export const Help = ({children}) => <span className="rh-form-help">{children}</span>; //------------------------------------------------------------------------------ // TODO // - set defaultValue from children prop to be consistent with TextArea export class TextInput extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; this.onElChange = throttle(this.onElChange, ONCHANGE_THROTTLE); } componentDidMount() { if(this.props.preventDefault) { this.el.addEventListener('keypress', this.nativeOnKeyPress, false); } } componentWillUnmount() { if(this.props.preventDefault) { this.el.removeEventListener('keypress', this.nativeOnKeyPress); } } nativeOnKeyPress(e) { if(e.keyCode === 13) { e.preventDefault(); } } focus () { this.el.focus(); } value () { return this.el.value; } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, help, datalist, error, className = '', ...other} = this.props; if (error) { className += ' isError'; } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div className="rh-form-control" onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> <input type='text' id={this.id} list={this.id} ref={el => { this.el = el; }} //eslint-disable-line brace-style className={className} {...other}> </input> {help ? <Help>{help}</Help> : null} </div> </div> ); } } /* Disabled {datalist ? ( <Datalist id={this.id}> {datalist.split(',').map(d => <DatalistOption value={d}/>)} </Datalist> ) : null} export const Datalist = ({children, id, ...other}) => <datalist id={id} {...other}>{children}</datalist>; export const DatalistOption = ({value, children, ...other}) => <option value={value}>{children}</option>; */ //------------------------------------------------------------------------------ export class TextArea extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; this.onElChange = throttle(this.onElChange, ONCHANGE_THROTTLE); } componentDidMount() { if(this.props.preventDefault) { this.el.addEventListener('keypress', this.nativeOnKeyPress, false); } } componentWillUnmount() { if(this.props.preventDefault) { this.el.removeEventListener('keypress', this.nativeOnKeyPress); } } nativeOnKeyPress(e) { if(e.keyCode === 13) { e.preventDefault(); } } focus () { this.el.focus(); } value () { return this.el.value; } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, children, error, className = '', help, ...other} = this.props; if (error) { className += ' isError'; } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div className="rh-form-control" onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> <textarea id={this.id} ref={el => { this.el = el; }} //eslint-disable-line brace-style className={className} defaultValue={children} {...other}> </textarea> {help ? <Help>{help}</Help> : null} </div> </div> ); } } //------------------------------------------------------------------------------ export class DropDown extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; } componentDidMount() { if(this.props.preventDefault) { this.el.addEventListener('keypress', this.nativeOnKeyPress, false); } } componentWillUnmount() { if(this.props.preventDefault) { this.el.removeEventListener('keypress', this.nativeOnKeyPress); } } nativeOnKeyPress(e) { if(e.keyCode === 13) { e.preventDefault(); } } focus () { this.el.focus(); } value () { return this.el.value; } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, children, error, className = '', help, ...other} = this.props; if (error) { className += ' isError'; } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div className="rh-form-control" onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> <select id={this.id} ref={el => { this.el = el; }} //eslint-disable-line brace-style className={className} {...other}> {children} </select> {help ? <Help>{help}</Help> : null} </div> </div> ); } } export class ListBox extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; this.options = []; } componentDidMount() { if(this.props.preventDefault) { this.el.addEventListener('keypress', this.nativeOnKeyPress, false); } } componentWillUnmount() { if(this.props.preventDefault) { this.el.removeEventListener('keypress', this.nativeOnKeyPress); } } nativeOnKeyPress(e) { if(e.keyCode === 13) { e.preventDefault(); } } focus () { this.el.focus(); } // TODO - test this.options value () { //return this.el.value; return this.props.children.reduce((acc, c, i) => { let opt = this.options[i]; if (opt.el.selected) { acc.push(opt.props.children); } return acc; }, []); } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, children, error, className = '', help, ...other} = this.props; className = 'rh-form-control-listbox ' + className; if (error) { className += ' isError'; } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div className="rh-form-control" onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> <select multiple size="3" id={this.id} ref={el => { this.options.push(el); }} //eslint-disable-line brace-style className={className} {...other}> {React.Children.map(this.props.children, (element, idx) => { return React.cloneElement(element, {ref: idx}); })} </select> {help ? <Help>{help}</Help> : null} </div> </div> ); } } export const OptionGroup = ({children, label, ...other}) => <optgroup label={label} {...other}>{children}</optgroup>; export class Option extends React.Component { constructor (props) { super(props); this.id = getNextId(); } render () { let {children, value, ...other} = this.props; return ( <option ref={el => { this.el = el; }} //eslint-disable-line brace-style value={value} id={this.id} {...other}> {children} </option> ); } } //------------------------------------------------------------------------------ export class CheckGroup extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; this.options = []; } focus () { //this.el.focus(); } value () { return this.props.children.reduce((acc, c, i) => { let cbox = this.options[i]; if (cbox.el.checked) { acc.push(cbox.props.children); } return acc; }, []); } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, children, error, className = '', help, disabled} = this.props; className = 'rh-form-label-large ' + className; if (error) { className += ' isError'; } // TODO - find an alternate way //children.forEach(c => c.props.className = className); if (disabled) { children.forEach(c => c.props.disabled = true); } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div className="rh-form-control" ref={el => { this.options.push(el); }} //eslint-disable-line brace-style onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> {React.Children.map(this.props.children, (element, idx) => { return React.cloneElement(element, {ref: idx}); })} {help ? <Help>{help}</Help> : null} </div> </div> ); } } export class Checkbox extends React.Component { constructor (props) { super(props); this.id = getNextId(); } render () { let {children, className, ...other} = this.props; return ( <Label htmlFor={this.id} className={className}> <input ref={el => { this.el = el; }} //eslint-disable-line brace-style type='checkbox' id={this.id} {...other} /> {children} </Label> ); } } //------------------------------------------------------------------------------ export class RadioGroup extends React.Component { constructor (props) { super(props); this.id = getNextId(); this.active = false; this.pristine = true; this.touched = false; this.error = false; this.options = []; } focus () { //this.el.focus(); } value () { return this.props.children.reduce((acc, c, i) => { let cbox = this.options[i]; if (cbox.el.checked) { acc = cbox.props.children; } return acc; }, ''); } onElFocus () { //console.log('focus', this.el); this.touched = true; this.active = true; } onElBlur () { //console.log('blur', this.el); this.active = false; } onElChange () { //console.log('change', this.value(), this.el); this.pristine = false; } render () { let {label, children, error, className = '', disabled, help} = this.props; className = 'rh-form-label-large ' + className; if (error) { className += ' isError'; } // TODO - find an alternate way //children.forEach(c => c.props.className = className); // Assign the same name so they group properly // TODO - find an alternate way //children.forEach(c => c.props.name = this.id); if (disabled) { children.forEach(c => c.props.disabled = true); } return (<div className="rh-form-component"> {label ? <Label htmlFor={this.id}>{label}</Label> : null } <div ref={el => { this.options.push(el); }} //eslint-disable-line brace-style className="rh-form-control" onBlur={this.onElBlur.bind(this)} onFocus={this.onElFocus.bind(this)} onChange={this.onElChange.bind(this)}> {React.Children.map(this.props.children, (element, idx) => { return React.cloneElement(element, {ref: idx}); })} {help ? <Help>{help}</Help> : null} </div> </div> ); } } export class Radio extends React.Component { constructor (props) { super(props); this.id = getNextId(); } render () { let {children, className, ...other} = this.props; return ( <Label htmlFor={this.id} className={className}> <input ref={el => { this.el = el; }} //eslint-disable-line brace-style type='radio' id={this.id} {...other} /> {children} </Label> ); } }
src/components/Project/ProjectDetails.js
taiwoabegunde/developersmap
/** * Created by Raphson on 10/8/16. */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Link } from 'react-router'; import ProjectActions from '../../actions/ProjectActions'; import ProjectStore from '../../stores/ProjectStore'; import NavBar from '../NavBar/index'; import Footer from '../Footer/Index'; import Auth from '../../utils/auth'; import marked from 'marked'; import TimeAgo from 'react-timeago'; import ReactDisqus from 'react-disqus'; export default class ProjectDetails extends Component { constructor() { super(); this.state = { project: null, } } componentDidMount() { ProjectActions.fetchProject(this.props.params.slug); ProjectStore.addChangeListener(this.handleProjectResult, 'fetchProject'); } componentWillUnmount(){ ProjectStore.removeChangeListener(this.handleProjectResult, 'fetchProject'); } handleProjectResult = () => { let result = ProjectStore.getProject(); this.setState({ project: result.data }); } shareTwitter = (e) => { e.preventDefault(); let name = this.state.project ? this.state.project.name : 'Loading..'; let url = this.state.project ? this.state.project.url : 'Loading..'; window.open( 'https://twitter.com/share?url='+encodeURIComponent(url)+'&amp;text=' + encodeURIComponent('Check Out This MERN Stack Project: ' + name) + '&amp;count=none/', 'twitter-share-dialog', 'width=626,height=436,top='+((screen.height - 436) / 2)+',left='+((screen.width - 626)/2 )); } shareFacebook = (e) => { e.preventDefault(); let name = this.state.project ? this.state.project.name : 'Loading..'; let url = this.state.project ? this.state.project.url : 'Loading..'; window.open( 'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(url) +'&amp;t=' + encodeURIComponent('Check Out This MERN Stack Project: ' + name),'facebook-share-dialog', 'width=626,height=436,top='+((screen.height - 436) / 2)+',left='+((screen.width - 626)/2 )); } render() { let desc = this.state.project ? this.state.project.description : 'Loading..'; return ( <span> <NavBar /> <div style={{minHeight: 580}} className="main-container"> <section> <div style={{backgroundColor: '#fff', padding: '60px 20px'}} className="listing"> <div data-ng-controller="ProjectController" className="row"> <div className="col-sm-8 columns project-board"> <h3 style={{textTransform: 'capitalize'}} className="header">{this.state.project ? this.state.project.name : 'Loading..'}</h3> <br /> <p dangerouslySetInnerHTML={{__html: marked(desc) }} /> <span style={{fontStyle: 'italic'}} className="postedBy"> Added by <Link to={ `/mern-developers/${this.state.project ? this.state.project.postedBy.username : 'Loading..'}`} style={{color: '#aa0036'}}> @{this.state.project ? this.state.project.postedBy.username : 'Loading..'}</Link></span> <ReactDisqus shortname="mernmap" identifier="123" /> </div> <div className="col-sm-3 columns project-sidebar"> <h6>Posted: <span className="time"><TimeAgo date={this.state.project ? new Date(this.state.project.postedOn) : new Date(1475956609492) }/> </span></h6> <br /> <h6>Website: </h6> <p><a target="_blank" href={this.state.project ? this.state.project.url : 'Loading..'}>{ this.state.project ? this.state.project.url : 'Loading..'}</a></p> <h6>Social Media Share: </h6> <br /> <p> <a href="#" className="btn btn-info btn-lg" onClick={this.shareTwitter} style={{color: '#fff', marginLeft: '-10px'}} href="#"> <i className="fa fa-twitter" /> Share on Twitter </a> </p> <p> <a href="#" className="btn btn-lg btn-primary" onClick={this.shareFacebook} style={{color: '#fff', marginLeft: '-10px'}} href="#"> <i className="fa fa-facebook" /> Share on Facebook </a> </p> </div> </div> </div> </section> </div> <Footer /> </span> ); } }
app/jsx/gradebook/default_gradebook/components/content-filters/SectionFilter.js
djbender/canvas-lms
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {arrayOf, shape, string} from 'prop-types' import I18n from 'i18n!gradebook_default_gradebook_components_content_filters_section_filter' import ContentFilter from './ContentFilter' export default function SectionFilter(props) { const {sections, selectedSectionId, ...filterProps} = props return ( <ContentFilter {...filterProps} allItemsId="0" allItemsLabel={I18n.t('All Sections')} items={sections} label={I18n.t('Section Filter')} selectedItemId={selectedSectionId} sortAlphabetically /> ) } SectionFilter.propTypes = { sections: arrayOf( shape({ id: string.isRequired, name: string.isRequired }) ).isRequired, selectedSectionId: string } SectionFilter.defaultProps = { selectedSectionId: null }
dispatch/static/manager/src/js/pages/Pages/PageIndexPage.js
ubyssey/dispatch
import React from 'react' import { connect } from 'react-redux' import ItemIndexPage from '../ItemIndexPage' import pagesActions from '../../actions/PagesActions' import { humanizeDatetime } from '../../util/helpers' const mapStateToProps = (state) => { return { token: state.app.auth.token, listItems: state.app.pages.list, entities: { listItems: state.app.entities.pages } } } const mapDispatchToProps = (dispatch) => { return { listListItems: (token, query) => { dispatch(pagesActions.list(token, query)) }, toggleListItem: (pageId) => { dispatch(pagesActions.toggle(pageId)) }, toggleAllListItems: (pageIds) => { dispatch(pagesActions.toggleAll(pageIds)) }, clearSelectedListItems: () => { dispatch(pagesActions.clearSelected()) }, clearListItems: () => { dispatch(pagesActions.clearAll()) }, deleteListItems: (token, pageIds) => { dispatch(pagesActions.deleteMany(token, pageIds)) }, searchListItems: (token, section, query) => { dispatch(pagesActions.search(section, query)) } } } function PagesPageComponent(props) { return ( <ItemIndexPage typePlural='pages' typeSingular='page' displayColumn='title' pageTitle='Pages' headers={[ 'Title', 'Updated', 'Published', 'Revisions' ]} extraColumns={[ item => item.updated_at ? humanizeDatetime(item.updated_at) : '', item => item.published_at ? humanizeDatetime(item.published_at) : 'Unpublished', item => item.latest_version + ' revisions' ]} {...props} /> ) } const PagesPage = connect( mapStateToProps, mapDispatchToProps )(PagesPageComponent) export default PagesPage
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-router/4.1.1/es/Redirect.js
JamieMason/npm-cache-benchmark
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for updating the location programatically * with a component. */ var Redirect = function (_React$Component) { _inherits(Redirect, _React$Component); function Redirect() { _classCallCheck(this, Redirect); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Redirect.prototype.isStatic = function isStatic() { return this.context.router && this.context.router.staticContext; }; Redirect.prototype.componentWillMount = function componentWillMount() { if (this.isStatic()) this.perform(); }; Redirect.prototype.componentDidMount = function componentDidMount() { if (!this.isStatic()) this.perform(); }; Redirect.prototype.perform = function perform() { var history = this.context.router.history; var _props = this.props, push = _props.push, to = _props.to; if (push) { history.push(to); } else { history.replace(to); } }; Redirect.prototype.render = function render() { return null; }; return Redirect; }(React.Component); Redirect.propTypes = { push: PropTypes.bool, from: PropTypes.string, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]) }; Redirect.defaultProps = { push: false }; Redirect.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired, staticContext: PropTypes.object }).isRequired }; export default Redirect;
src/daypicker/DayPicker.js
buildo/react-datepicker
import React from 'react'; import t from 'tcomb'; import { props } from 'tcomb-react'; import View from 'react-flexview'; import { pure, skinnable } from '../utils'; import { Value, Mode, MomentDate } from '../utils/model'; import DayPickerTop from './DayPickerTop'; import DayPickerBody from './DayPickerBody'; @pure @skinnable() @props({ changeMonth: t.Function, visibleDate: MomentDate, date: t.maybe(Value), minDate: t.maybe(Value), maxDate: t.maybe(Value), onSelectDate: t.Function, onChangeMode: t.Function, mode: Mode, fixedMode: t.maybe(t.Boolean), prevIconClassName: t.String, nextIconClassName: t.String }) export default class DayPicker extends React.Component { getLocals({ date, visibleDate, onSelectDate, minDate, maxDate, changeMonth, onChangeMode, mode, fixedMode, prevIconClassName, nextIconClassName }) { return { dayPickerTopProps: { visibleDate, changeMonth, onChangeMode, fixedMode, prevIconClassName, nextIconClassName }, dayPickerBodyProps: { date, visibleDate, minDate, maxDate, onSelectDate, mode } }; } template({ dayPickerTopProps, dayPickerBodyProps }) { return ( <View column className='react-datepicker-container day'> <DayPickerTop {...dayPickerTopProps} /> <DayPickerBody {...dayPickerBodyProps} /> </View> ); } }
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
maxipad37/maxipad37.github.io
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/layout/Sidebar.js
meetfranz/franz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactTooltip from 'react-tooltip'; import { defineMessages, intlShape } from 'react-intl'; import { observer } from 'mobx-react'; import Tabbar from '../services/tabs/Tabbar'; import { ctrlKey } from '../../environment'; import { GA_CATEGORY_WORKSPACES, workspaceStore } from '../../features/workspaces'; import { gaEvent } from '../../lib/analytics'; import { todosStore, GA_CATEGORY_TODOS } from '../../features/todos'; import { todoActions } from '../../features/todos/actions'; const messages = defineMessages({ settings: { id: 'sidebar.settings', defaultMessage: '!!!Settings', }, addNewService: { id: 'sidebar.addNewService', defaultMessage: '!!!Add new service', }, mute: { id: 'sidebar.muteApp', defaultMessage: '!!!Disable notifications & audio', }, unmute: { id: 'sidebar.unmuteApp', defaultMessage: '!!!Enable notifications & audio', }, openWorkspaceDrawer: { id: 'sidebar.openWorkspaceDrawer', defaultMessage: '!!!Open workspace drawer', }, closeWorkspaceDrawer: { id: 'sidebar.closeWorkspaceDrawer', defaultMessage: '!!!Close workspace drawer', }, openTodosDrawer: { id: 'sidebar.openTodosDrawer', defaultMessage: '!!!Open Franz Todos', }, closeTodosDrawer: { id: 'sidebar.closeTodosDrawer', defaultMessage: '!!!Close Franz Todos', }, }); export default @observer class Sidebar extends Component { static propTypes = { openSettings: PropTypes.func.isRequired, toggleMuteApp: PropTypes.func.isRequired, isAppMuted: PropTypes.bool.isRequired, isWorkspaceDrawerOpen: PropTypes.bool.isRequired, toggleWorkspaceDrawer: PropTypes.func.isRequired, isTodosServiceActive: PropTypes.bool.isRequired, }; static contextTypes = { intl: intlShape, }; state = { tooltipEnabled: true, }; componentDidUpdate() { ReactTooltip.rebuild(); } enableToolTip() { this.setState({ tooltipEnabled: true }); } disableToolTip() { this.setState({ tooltipEnabled: false }); } updateToolTip() { this.disableToolTip(); setTimeout(this.enableToolTip.bind(this)); } render() { const { openSettings, toggleMuteApp, isAppMuted, isWorkspaceDrawerOpen, toggleWorkspaceDrawer, isTodosServiceActive, } = this.props; const { intl } = this.context; const todosToggleMessage = ( todosStore.isTodosPanelVisible ? messages.closeTodosDrawer : messages.openTodosDrawer ); const workspaceToggleMessage = ( isWorkspaceDrawerOpen ? messages.closeWorkspaceDrawer : messages.openWorkspaceDrawer ); return ( <div className="sidebar"> <Tabbar {...this.props} enableToolTip={() => this.enableToolTip()} disableToolTip={() => this.disableToolTip()} /> {todosStore.isFeatureEnabled && todosStore.isFeatureEnabledByUser ? ( <button type="button" onClick={() => { todoActions.toggleTodosPanel(); this.updateToolTip(); gaEvent(GA_CATEGORY_TODOS, 'toggleDrawer', 'sidebar'); }} disabled={isTodosServiceActive} className={`sidebar__button sidebar__button--todos ${todosStore.isTodosPanelVisible ? 'is-active' : ''}`} data-tip={`${intl.formatMessage(todosToggleMessage)} (${ctrlKey}+T)`} data-for="tabs" > <i className="mdi mdi-check-all" /> </button> ) : null} {workspaceStore.isFeatureEnabled ? ( <button type="button" onClick={() => { toggleWorkspaceDrawer(); this.updateToolTip(); gaEvent(GA_CATEGORY_WORKSPACES, 'toggleDrawer', 'sidebar'); }} className={`sidebar__button sidebar__button--workspaces ${isWorkspaceDrawerOpen ? 'is-active' : ''}`} data-tip={`${intl.formatMessage(workspaceToggleMessage)} (${ctrlKey}+D)`} data-for="tabs" > <i className="mdi mdi-view-grid" /> </button> ) : null} <button type="button" onClick={() => { toggleMuteApp(); this.updateToolTip(); }} className={`sidebar__button sidebar__button--audio ${isAppMuted ? 'is-muted' : ''}`} data-tip={`${intl.formatMessage(isAppMuted ? messages.unmute : messages.mute)} (${ctrlKey}+Shift+M)`} data-for="tabs" > <i className={`mdi mdi-bell${isAppMuted ? '-off' : ''}`} /> </button> <button type="button" onClick={() => openSettings({ path: 'recipes' })} className="sidebar__button sidebar__button--new-service" data-tip={`${intl.formatMessage(messages.addNewService)} (${ctrlKey}+N)`} data-for="tabs" > <i className="mdi mdi-plus-box" /> </button> <button type="button" onClick={() => openSettings({ path: 'app' })} className="sidebar__button sidebar__button--settings" data-tip={`${intl.formatMessage(messages.settings)} (${ctrlKey}+,)`} data-for="tabs" > <i className="mdi mdi-settings" /> </button> {this.state.tooltipEnabled && ( <ReactTooltip id="tabs" place="bottom" type="dark" effect="solid" overridePosition={({ left, top }, currentEvent, currentTarget, node) => { const d = document.documentElement; left = Math.min(d.clientWidth - node.clientWidth, left); top = Math.min(currentTarget.offsetTop + currentTarget.offsetHeight, top); left = Math.max(0, left); top = Math.max(0, top); left = currentTarget.offsetLeft; return { top, left, place: 'bottom' }; }} /> )} </div> ); } }
src/svg-icons/av/featured-video.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFeaturedVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 9H3V5h9v7z"/> </SvgIcon> ); AvFeaturedVideo = pure(AvFeaturedVideo); AvFeaturedVideo.displayName = 'AvFeaturedVideo'; AvFeaturedVideo.muiName = 'SvgIcon'; export default AvFeaturedVideo;
app/components/AddMemberModal/index.js
projectcashmere/admin
/** * * AddMemberModal * */ import React from 'react'; import Modal from 'react-modal'; import colors from 'themes/colors'; import { FormattedMessage } from 'react-intl'; import { reduxForm, Field } from 'redux-form/immutable'; import CrosshairIcon from 'react-icons/lib/md/add'; import TrashIcon from 'react-icons/lib/md/delete'; import ImageFile from 'components/ImageFile'; import { validateRequired, validateEmail, validatePhoneLength, validateMinLength, } from 'utils/validators'; import { normalizePhone, normalizeName } from 'utils/normalizers'; import Header from './Header'; import Body from './Body'; import AddPhotoCard from '../AddPhotoCard'; import AddMemberDetails from './AddMemberDetails'; import AddMemberRow from './AddMemberRow'; import Footer from './Footer'; import Button from './Button'; import OpacityLayer from './OpacityLayer'; import modalStyle from './modalStyle'; import messages from './messages'; const validateMinLength2 = validateMinLength(2); function AddMemberModal({ closeModal, isOpen, handleAddMember, handlePhotoChange, handlePhotoRemove, photoUrl, dispatch, isValid, }) { return ( <Modal contentLabel="addMemberModal" isOpen={isOpen} style={modalStyle} onRequestClose={() => closeModal(dispatch)} shouldCloseOnOverlayClick > <Header> <FormattedMessage {...messages.header} /> </Header> <Body> {photoUrl ? ( <AddPhotoCard src={photoUrl}> <OpacityLayer> <TrashIcon color={colors.danger} size={20} style={{ cursor: 'pointer' }} onClick={() => handlePhotoRemove(dispatch)} /> </OpacityLayer> </AddPhotoCard> ) : ( <AddPhotoCard src={photoUrl}> <CrosshairIcon size={20} color={colors.primary} /> <ImageFile onChange={e => handlePhotoChange(e, dispatch)} type="file" accept="image/png,image/gif,image/jpeg" /> </AddPhotoCard> )} <AddMemberDetails> <Field component={AddMemberRow} labelMessage={<FormattedMessage {...messages.firstName} />} name="firstName" type="text" placeholder="eg. Jack" normalize={normalizeName} width="265px" validate={[validateRequired, validateMinLength2]} /> <Field component={AddMemberRow} labelMessage={<FormattedMessage {...messages.lastName} />} name="lastName" type="text" placeholder="eg. Bauer" width="265px" normalize={normalizeName} validate={[validateRequired, validateMinLength2]} /> <Field component={AddMemberRow} labelMessage={<FormattedMessage {...messages.emailAddress} />} name="email" type="text" placeholder="eg. [email protected]" width="265px" validate={[validateRequired, validateEmail]} /> <Field component={AddMemberRow} labelMessage={<FormattedMessage {...messages.contactNumber} />} name="phoneNumber" type="text" normalize={normalizePhone} validate={validatePhoneLength} placeholder="(optional)" width="265px" /> </AddMemberDetails> </Body> <Footer> <Button onClick={() => closeModal(dispatch)}> <FormattedMessage {...messages.cancel} /> </Button> <Button primary onClick={handleAddMember} disabled={!isValid}> <FormattedMessage {...messages.sendInvite} /> </Button> </Footer> </Modal> ); } export default reduxForm({ form: 'addMember', })(AddMemberModal);
docs/app/Examples/addons/TransitionablePortal/Usage/index.js
shengnian/shengnian-ui-react
import React from 'react' import { Link } from 'react-router-dom' import { Message } from 'shengnian-ui-react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const TransitionablePortalUsageExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Transition' description='You can use define transitions.' examplePath='addons/TransitionablePortal/Usage/TransitionablePortalExampleTransition' > <Message info> See <Link to='/modules/transition'>Transition</Link> for more examples of usage. </Message> </ComponentExample> </ExampleSection> ) export default TransitionablePortalUsageExamples
src/media/js/site/components/subnav.js
diox/marketplace-content-tools
import React from 'react'; export class Subnav extends React.Component { render() { return ( <nav className="page--subnav"> <ul> {this.props.children} </ul> </nav> ); } }
src/table-head.js
knledg/react-blur-admin
import React from 'react'; import cx from 'classnames'; export class TableHead extends React.Component { static propTypes = { blackMutedBackground: React.PropTypes.bool, } static defaultProps = { blackMutedBackground: true, } render() { const classes = cx({ 'black-muted-bg': this.props.blackMutedBackground, }); return ( <thead> <tr className={classes}> {this.props.children} </tr> </thead> ); } }
src/product/MobileProductContainer.js
eldavojohn/myRetail-practice-app
import React from 'react' import { connect } from 'react-redux' import { addToCart, pickupInStore, share, addToRegistry, addToList } from '../actions/ProductActions' import MobileProduct from './MobileProduct' let MobileProductContainer = ({ product, dispatch }) => { return ( <MobileProduct product={product} addToCart={addToCartCallback} pickupInStore={pickupInStoreCallback} share={shareCallback} addToRegistry={addToRegistryCallback} addToList={addToListCallback} /> ) function addToCartCallback(clickEvent) { clickEvent.preventDefault(); dispatch(addToCart(product)) } function pickupInStoreCallback(clickEvent) { clickEvent.preventDefault(); dispatch(pickupInStore(product)) } function shareCallback() { dispatch(share(product)) } function addToRegistryCallback() { dispatch(addToRegistry(product)) } function addToListCallback() { dispatch(addToList(product)) } } export default connect()(MobileProductContainer)
docs/src/app/components/pages/components/Tabs/ExampleSwipeable.js
skarnecki/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; // From https://github.com/oliviertassinari/react-swipeable-views import SwipeableViews from 'react-swipeable-views'; const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400, }, slide: { padding: 10, }, }; export default class TabsExampleSwipeable extends React.Component { constructor(props) { super(props); this.state = { slideIndex: 0, }; } handleChange = (value) => { this.setState({ slideIndex: value, }); }; render() { return ( <div> <Tabs onChange={this.handleChange} value={this.state.slideIndex} > <Tab label="Tab One" value={0} /> <Tab label="Tab Two" value={1} /> <Tab label="Tab Three" value={2} /> </Tabs> <SwipeableViews index={this.state.slideIndex} onChangeIndex={this.handleChange} > <div> <h2 style={styles.headline}>Tabs with slide effect</h2> Swipe to see the next slide.<br /> </div> <div style={styles.slide}> slide n°2 </div> <div style={styles.slide}> slide n°3 </div> </SwipeableViews> </div> ); } }
spec/components/checkbox.js
soyjavi/react-toolbox
import React from 'react'; import Checkbox from '../../components/checkbox'; class CheckboxTest extends React.Component { state = { checkbox_1: true, checkbox_2: false, checkbox_3: true }; handleChange = (field, value) => { this.setState({...this.state, [field]: value}); }; handleFocus = () => { console.log('Focused'); }; handleBlur = () => { console.log('Blur'); }; render () { return ( <section> <h5>Checkbox</h5> <p style={{marginBottom: '10px'}}>Lorem ipsum...</p> <Checkbox checked={this.state.checkbox_1} label="Checked checkbox" onChange={this.handleChange.bind(this, 'checkbox_1')} onFocus={this.handleFocus} onBlur={this.handleBlur} /> <Checkbox checked={this.state.checkbox_2} label="Not checked checkbox" onChange={this.handleChange.bind(this, 'checkbox_2')} onFocus={this.handleFocus} onBlur={this.handleBlur} /> <Checkbox checked={this.state.checkbox_3} label="Disabled checkbox" disabled onChange={this.handleChange.bind(this, 'checkbox_3')} onFocus={this.handleFocus} onBlur={this.handleBlur} /> </section> ); } } export default CheckboxTest;
new-lamassu-admin/src/pages/Triggers/CustomInfoRequests/WizardSplash.js
naconner/lamassu-server
import { makeStyles } from '@material-ui/core' import React from 'react' import { Button } from 'src/components/buttons' import { H1, P } from 'src/components/typography' import { ReactComponent as CustomReqLogo } from 'src/styling/icons/compliance/custom-requirement.svg' const styles = { logo: { maxHeight: 150, maxWidth: 200 }, title: { margin: [[24, 0, 32, 0]] }, text: { margin: 0 }, button: { marginTop: 'auto', marginBottom: 58 }, modalContent: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: [[0, 42]], flex: 1 } } const useStyles = makeStyles(styles) const WizardSplash = ({ onContinue }) => { const classes = useStyles() return ( <div className={classes.modalContent}> <CustomReqLogo className={classes.logo} /> <H1 className={classes.title}>Custom information request</H1> <P className={classes.text}> A custom information request allows you to have an extra option to ask specific information about your customers when adding a trigger that isn't an option on the default requirements list. </P> <P> Note that adding a custom information request isn't the same as adding triggers. You will still need to add a trigger with the new requirement to get this information from your customers. </P> <Button className={classes.button} onClick={onContinue}> Get started </Button> </div> ) } export default WizardSplash
packages/material-ui-icons/src/SettingsBluetooth.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SettingsBluetooth = props => <SvgIcon {...props}> <path d="M11 24h2v-2h-2v2zm-4 0h2v-2H7v2zm8 0h2v-2h-2v2zm2.71-18.29L12 0h-1v7.59L6.41 3 5 4.41 10.59 10 5 15.59 6.41 17 11 12.41V20h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 3.83l1.88 1.88L13 7.59V3.83zm1.88 10.46L13 16.17v-3.76l1.88 1.88z" /> </SvgIcon>; SettingsBluetooth = pure(SettingsBluetooth); SettingsBluetooth.muiName = 'SvgIcon'; export default SettingsBluetooth;
src/components/summary_title.js
dbaronov/weather-widget-react-noredux
import React, { Component } from 'react'; class SummaryTitle extends Component { render() { return ( <div className="weather-widget__results-title col-lg-12"> <div className="weather-widget__results-city"> <h2> Weather in London as follows: </h2> </div> <div className="weather-widget__results-today"></div> </div> ) } } export default SummaryTitle;
packages/material-ui-icons/src/SignalWifi2BarLockRounded.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l10.08 12.56c.8 1 2.32 1 3.12 0l1.94-2.42V14.5z" /><path d="M15.5 14.5c0-1.34.51-2.53 1.34-3.42C15.62 10.51 13.98 10 12 10c-4.1 0-6.8 2.2-7.2 2.5l5.64 7.05c.8 1 2.32 1 3.12 0l1.94-2.42V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /></React.Fragment> , 'SignalWifi2BarLockRounded');
app/components/SetNewPassword.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { confirmResetPassword } from '../actions'; import { routeActions, push } from 'react-router-redux'; import klplogo from '../css/images/KLP_logo.png'; class SetNewPasswordUI extends Component { constructor(props) { super(props); 'Props in reset password', props; this.handleSubmit = this.handleSubmit.bind(this); this.goToLoginPage = this.goToLoginPage.bind(this); } componentWillReceiveProps(nextProps) { const { dispatch, authenticated, token, error } = nextProps; 'Set new password receiving props', dispatch; if (nextProps.pwdResetConfirmed) { $('#pwdResetConfirmedModal').modal('show'); } if (nextProps.pwdResetRejected) { $('#pwdResetFailedModal').modal('show'); } } goToLoginPage() { this.props.dispatch(push('/login')); $('#pwdResetConfirmedModal').modal('hide'); } handleSubmit(event) { event.preventDefault(); const new_password = this.refs.pass.value; this.props.dispatch(confirmResetPassword(this.props.params.uid, this.props.params.token, new_password)); // const email = this.refs.email.value; // this.props.dispatch(resetPassword(email)); } render() { return ( <div id="login-page"> <nav className="main__header navbar navbar-white navbar-fixed-top"> <div id="header" className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/"> <img src={klplogo} /> </a> </div> <div id="navbar" className="navbar-collapse collapse"> <p className="app-name navbar-text pull-left">Data Entry Operations 2015-2016</p> <p className="navbar-text pull-right"> <Link to="/register" className="btn btn-primary padded-btn"> SIGN UP </Link> </p> </div> </div> </nav> <div className="container-fluid absolute-center is-responsive"> <div className="row"> <div className="col-md-12"> <span>Please enter your new password. </span> </div> </div> <div className="row"> <div className="col-sm-12 col-md-10 col-md-offset-1"> <form id="loginForm"> <div className="form-group input-group"> <span className="input-group-addon"> <label htmlFor="pass">Password:</label> </span> <input id="pass" ref="pass" className="form-control" type="password" name="password" placeholder="" /> </div> <div className="form-group input-group"> <span className="input-group-addon"> <label htmlFor="reenterpass">Confirm Password:</label> </span> <input id="reenterpass" ref="reenterpass" className="form-control" type="password" name="reenterpassword" placeholder="" /> </div> <div className="form-group text-center"> <button type="submit" className="btn btn-primary" onClick={this.handleSubmit}> Submit </button> </div> </form> </div> </div> </div> {/* Pwd reset modal */} <div className="modal fade" data-backdrop="false" id="pwdResetConfirmedModal" tabIndex="-1" role="dialog" aria-labelledby="pwdResetConfirmedModal" > <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 className="modal-title" id="changeUserNameTitle"> {' '} Password Reset </h4> </div> <div className="modal-body"> Your password has been reset successfully. Please login with your new password. </div> <div className="modal-footer"> <button type="button" className="btn btn-primary" data-dismiss="modal"> OK </button> </div> </div> </div> </div> {/* Pwd reset failed modal */} <div className="modal fade" data-backdrop="false" id="pwdResetFailedModal" tabIndex="-1" role="dialog" aria-labelledby="pwdResetConfirmedModal" > <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 className="modal-title" id="changeUserNameTitle"> {' '} Password Reset </h4> </div> <div className="modal-body"> We couldn't set your new password. Please try again or contact support. </div> <div className="modal-footer"> <button type="button" className="btn btn-primary" data-dismiss="modal"> OK </button> </div> </div> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { pwdResetConfirmed: state.passwordreset.reset_confirmed, pwdResetRejected: state.passwordreset.reset_rejected, }; }; // This will just connect it to the store const SetNewPassword = connect()(SetNewPasswordUI); export default SetNewPassword;
addons/knobs/src/components/types/Color.js
jribeiro/storybook
import { document } from 'global'; import PropTypes from 'prop-types'; import React from 'react'; import { SketchPicker } from 'react-color'; const conditionalRender = (condition, positive, negative) => (condition ? positive() : negative()); const styles = { swatch: { background: '#fff', borderRadius: '1px', border: '1px solid rgb(247, 244, 244)', display: 'inline-block', cursor: 'pointer', width: '100%', }, popover: { position: 'absolute', zIndex: '2', }, cover: { position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', }, }; class ColorType extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.onWindowMouseDown = this.onWindowMouseDown.bind(this); this.state = { displayColorPicker: false, }; } componentDidMount() { document.addEventListener('mousedown', this.onWindowMouseDown); } componentWillUnmount() { document.removeEventListener('mousedown', this.onWindowMouseDown); } onWindowMouseDown(e) { if (!this.state.displayColorPicker) return; if (this.popover.contains(e.target)) return; this.setState({ displayColorPicker: false, }); } handleClick() { this.setState({ displayColorPicker: !this.state.displayColorPicker, }); } render() { const { knob, onChange } = this.props; const { displayColorPicker } = this.state; const colorStyle = { width: 'auto', height: '20px', borderRadius: '2px', margin: 5, background: knob.value, }; return ( <div id={knob.name}> <div style={styles.swatch} onClick={this.handleClick} role="button" tabIndex="0"> <div style={colorStyle} /> </div> {conditionalRender( displayColorPicker, () => <div style={styles.popover} ref={e => { this.popover = e; }} > <SketchPicker color={knob.value} onChange={color => onChange(color.hex)} /> </div>, () => null )} </div> ); } } ColorType.propTypes = { knob: PropTypes.shape({ name: PropTypes.string, value: PropTypes.string, }), onChange: PropTypes.func, }; ColorType.defaultProps = { knob: {}, onChange: value => value, }; ColorType.serialize = value => value; ColorType.deserialize = value => value; export default ColorType;
src/documentation/Colours/ColourList.js
wfp/ui
import React from 'react'; import { List, ListItem } from '../../components/List'; import Tooltip from '../../components/Tooltip'; import { Module, ModuleBody } from '../../components/Module'; import colors from '../../globals/data/colors'; import { hex, score } from 'wcag-contrast'; import './colours.scss'; export const ColourList = ({ filter }) => { const filteredColors = Object.values(colors).filter( (ui_colors) => ui_colors.type === filter ); const list = filteredColors.map((color) => { const computedColor = getComputedStyle(document.body).getPropertyValue( `--${color.name}` ); return ( <Tooltip content={ <div> {color.description && <p>{color.description}</p>} {color.name} </div> }> <li> <Module fullHeight noMargin light className="color__item"> <div className="color__field" style={{ backgroundColor: color.hex }}> {/*<div className="color__check" style={{ backgroundColor: `var(--${color.name})` }}></div>*/} <div className="color__contrast"> <span>A</span> <div>>{score(hex(color.hex, '#000000'))}</div> </div> <div className="color__contrast color__contrast--light"> <span>A</span> <div>{score(hex(color.hex, '#FFFFFF'))}</div> </div> </div> <div style={{ flexGrow: '1', fontSize: '0.7em', lineHeight: '2em', }}> <ModuleBody> <h4>{color.name}</h4> <List colon kind="simple"> {color.shortDescription && ( <h4 className="wfp--story__sub-heading"> {color.shortDescription} </h4> )} <ListItem> <strong>Hex:</strong> {color.hex ? color.hex : computedColor} </ListItem> {color.css && ( <ListItem> <strong>CSS:</strong> {computedColor ? `--${color.name}` : color.css} </ListItem> )} </List> </ModuleBody> </div> </Module> </li> </Tooltip> ); }); return <ul className="color--list">{list}</ul>; };
src/svg-icons/image/grain.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGrain = (props) => ( <SvgIcon {...props}> <path d="M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); ImageGrain = pure(ImageGrain); ImageGrain.displayName = 'ImageGrain'; export default ImageGrain;
src/inputs/CurrencySelectors.js
gianjohansen/currency-conversion
import React from 'react'; import { findDOMNode } from 'react-dom'; import ReactSuperSelect from 'react-super-select'; import classNames from 'classnames'; require('../../vendor/react-super-select/react-super-select.scss'); require('../../www/assets/css/inputs/currency-selectors.scss'); var currencyList = require('json-loader!./Currencies.json'); var CurrencySelectors = React.createClass({ componentDidMount: function() { }, allCurrencies: function() { let items = []; items.push(<option key=""></option>); items.push(<option key="USD">USD</option>); items.push(<option key="AUD">AUD</option>); return items; }, currencyDropdownItemTemplate: function(item, search) { if (console && console.info) { // console.info('search term (%s) is provided for highlighting/modifying template output', search); } var iconClasses = classNames('grocery-icon', 'rss-grocery', 'rss-grocery-' + item.attributeName), labelMarkup = search ? _getHighlightedSearchLabel(item, search, new RegExp( search, 'i')) : item.label; return( <div key={item.label} className="currency-dropdown-template"> <span className="currency-icon"><img src={"assets/img/flags/" + item.label + ".png"}></img></span> <p className="currency-label"><strong>{labelMarkup}</strong> - {item.name}</p> </div>); }, render: function(){ return ( <div className="currency-selectors"> <div className="currency-selectors-inner"> <ReactSuperSelect placeholder="Convert from..." onChange={this.props.setCurrencyFrom} dataSource={currencyList} customOptionTemplateFunction={this.currencyDropdownItemTemplate} clearable={false} /> <ReactSuperSelect placeholder="Convert to..." onChange={this.props.setCurrencyTo} dataSource={currencyList} customOptionTemplateFunction={this.currencyDropdownItemTemplate} clearable={false} /> </div> </div> ) } }); export default CurrencySelectors;
packages/slate-react/src/components/text.js
6174/slate
import Debug from 'debug' import ImmutableTypes from 'react-immutable-proptypes' import React from 'react' import SlateTypes from 'slate-prop-types' import Types from 'prop-types' import Leaf from './leaf' /** * Debug. * * @type {Function} */ const debug = Debug('slate:node') /** * Text. * * @type {Component} */ class Text extends React.Component { /** * Property types. * * @type {Object} */ static propTypes = { block: SlateTypes.block, decorations: ImmutableTypes.list.isRequired, editor: Types.object.isRequired, node: SlateTypes.node.isRequired, parent: SlateTypes.node.isRequired, schema: SlateTypes.schema.isRequired, state: SlateTypes.state.isRequired, style: Types.object, } /** * Default prop types. * * @type {Object} */ static defaultProps = { style: null, } /** * Debug. * * @param {String} message * @param {Mixed} ...args */ debug = (message, ...args) => { const { node } = this.props const { key } = node debug(message, `${key} (text)`, ...args) } /** * Should the node update? * * @param {Object} nextProps * @param {Object} state * @return {Boolean} */ shouldComponentUpdate = (nextProps) => { const { props } = this const n = nextProps const p = props // If the node has changed, update. PERF: There are cases where it will have // changed, but it's properties will be exactly the same (eg. copy-paste) // which this won't catch. But that's rare and not a drag on performance, so // for simplicity we just let them through. if (n.node != p.node) return true // If the node parent is a block node, and it was the last child of the // block, re-render to cleanup extra `<br/>` or `\n`. if (n.parent.kind == 'block') { const pLast = p.parent.nodes.last() const nLast = n.parent.nodes.last() if (p.node == pLast && n.node != nLast) return true } // Re-render if the current decorations have changed. if (!n.decorations.equals(p.decorations)) return true // Otherwise, don't update. return false } /** * Render. * * @return {Element} */ render() { const { props } = this this.debug('render', { props }) const { decorations, node, state, style } = props const { document } = state const { key } = node const decs = decorations.filter((d) => { const { startKey, endKey } = d if (startKey == key || endKey == key) return true const startsBefore = document.areDescendantsSorted(startKey, key) const endsAfter = document.areDescendantsSorted(key, endKey) return startsBefore && endsAfter }) const leaves = node.getLeaves(decs) let offset = 0 const children = leaves.map((leaf, i) => { const child = this.renderLeaf(leaves, leaf, i, offset) offset += leaf.text.length return child }) return ( <span data-key={key} style={style}> {children} </span> ) } /** * Render a single leaf given a `leaf` and `offset`. * * @param {List<Leaf>} leaves * @param {Leaf} leaf * @param {Number} index * @param {Number} offset * @return {Element} leaf */ renderLeaf = (leaves, leaf, index, offset) => { const { block, node, parent, schema, state, editor } = this.props const { text, marks } = leaf return ( <Leaf key={`${node.key}-${index}`} block={block} editor={editor} index={index} marks={marks} node={node} offset={offset} parent={parent} leaves={leaves} schema={schema} state={state} text={text} /> ) } } /** * Export. * * @type {Component} */ export default Text
envkey-react/src/components/assoc_manager/assoc_row/invite_actions.js
envkey/envkey-app
import React from 'react' import h from "lib/ui/hyperscript_with_helpers" import SmallLoader from "components/shared/small_loader" export default function ({ assoc: {id: userId, relation: {accessStatus: {status}}}, revokeInvite, regenInvite, isRevokingInviteByUserId, isRegeneratingInviteByUserId }){ const renderRevoke = ()=> { if (status != "revoked"){ return h.a({onClick: e => revokeInvite(userId)}, "Revoke") } }, renderRegen = ()=> { return h.a({onClick: e => regenInvite(userId)}, "Regenerate") }, renderContent = ()=> { if (isRevokingInviteByUserId[userId] || isRegeneratingInviteByUserId[userId]){ return [h(SmallLoader)] } else { return [renderRevoke(), renderRegen()] } } return h.div(".invite-actions", renderContent()) }
webpack/scenes/Subscriptions/components/SubscriptionsTable/components/Table.js
mccun934/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table as PFtable } from 'patternfly-react'; import { translate as __ } from 'foremanReact/common/I18n'; import classNames from 'classnames'; import { createSubscriptionsTableSchema } from '../SubscriptionsTableSchema'; import { Table as ForemanTable, TableBody as ForemanTableBody } from '../../../../../move_to_foreman/components/common/table'; const Table = ({ emptyState, tableColumns, subscriptions, loadSubscriptions, selectionController, inlineEditController, rows, editing, groupedSubscriptions, toggleSubscriptionGroup, canManageSubscriptionAllocations, }) => { const allSubscriptionResults = subscriptions.results; let bodyMessage; if (allSubscriptionResults.length === 0 && subscriptions.searchIsActive) { bodyMessage = __('No subscriptions match your search criteria.'); } const groupingController = { isCollapseable: ({ rowData }) => // it is the first subscription in the group rowData.id === groupedSubscriptions[rowData.product_id].subscriptions[0].id && // the group contains more then one subscription groupedSubscriptions[rowData.product_id].subscriptions.length > 1, isCollapsed: ({ rowData }) => !groupedSubscriptions[rowData.product_id].open, toggle: ({ rowData }) => toggleSubscriptionGroup(rowData.product_id), }; const alwaysDisplayColumns = ['select']; const columnsDefinition = createSubscriptionsTableSchema( inlineEditController, selectionController, groupingController, canManageSubscriptionAllocations, ).filter(column => tableColumns.includes(column.property) || alwaysDisplayColumns.includes(column.property)); const onPaginationChange = (pagination) => { loadSubscriptions({ ...pagination, }); }; return ( <ForemanTable columns={columnsDefinition} emptyState={emptyState} bodyMessage={bodyMessage} rows={rows} components={{ header: { row: PFtable.TableInlineEditHeaderRow, }, }} itemCount={subscriptions.itemCount} pagination={subscriptions.pagination} onPaginationChange={onPaginationChange} inlineEdit > <PFtable.Header onRow={() => ({ role: 'row', isEditing: () => editing, onCancel: () => inlineEditController.onCancel(), onConfirm: () => inlineEditController.onConfirm(), })} /> <ForemanTableBody columns={columnsDefinition} rows={rows} rowKey="id" message={bodyMessage} onRow={rowData => ({ className: classNames({ 'open-grouped-row': !groupingController.isCollapsed({ rowData }) }), })} /> </ForemanTable> ); }; Table.propTypes = { canManageSubscriptionAllocations: PropTypes.bool, emptyState: PropTypes.shape({}).isRequired, tableColumns: PropTypes.arrayOf(PropTypes.string).isRequired, subscriptions: PropTypes.shape({ searchIsActive: PropTypes.bool, itemCount: PropTypes.number, pagination: PropTypes.shape({}), results: PropTypes.array, }).isRequired, loadSubscriptions: PropTypes.func.isRequired, toggleSubscriptionGroup: PropTypes.func.isRequired, selectionController: PropTypes.shape({}).isRequired, inlineEditController: PropTypes.shape({ onCancel: PropTypes.func, onConfirm: PropTypes.func, }).isRequired, groupedSubscriptions: PropTypes.shape({}).isRequired, editing: PropTypes.bool.isRequired, rows: PropTypes.arrayOf(PropTypes.object).isRequired, }; Table.defaultProps = { canManageSubscriptionAllocations: false, }; export default Table;
src/svg-icons/action/alarm-on.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAlarmOn = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06 3.18 3.18 6-6-1.06-1.06-4.93 4.95z"/> </SvgIcon> ); ActionAlarmOn = pure(ActionAlarmOn); ActionAlarmOn.displayName = 'ActionAlarmOn'; ActionAlarmOn.muiName = 'SvgIcon'; export default ActionAlarmOn;
src/common/components/PrimaryNav/PrimaryNav.js
BeMacized/GrimoireWeb
// @Flow import React from 'react' import PropTypes from 'prop-types' import { NavLink as RRNavLink } from 'react-router-dom' import { Container, Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Button } from 'reactstrap' import styled from 'styled-components' import MediaQuery from 'react-responsive' import FontAwesome from 'react-fontawesome' import GrimoireLogo from '../GrimoireLogo/GrimoireLogo' import { INVITE_URL } from '../../globals' const Wrapper = styled.div` min-height:80px; z-index: 100; ` const RContainer = (props) => <MediaQuery query='(max-width: 576px)'> {(matches) => <Container style={matches ? { maxWidth: '100% !important', margin: '0 !important' } : {}}> {props.children} </Container> } </MediaQuery> RContainer.propTypes = { children: PropTypes.arrayOf(PropTypes.element) } class PrimaryNav extends React.Component { constructor (props) { super(props) this.toggle = this.toggle.bind(this) this.handleScroll = this.handleScroll.bind(this) this.state = { isOpen: false, barTranslucent: false } } toggle () { this.setState(Object.assign({}, this.state, { isOpen: !this.state.isOpen })) } componentDidMount () { window.addEventListener('scroll', this.handleScroll) } componentWillUnmount () { window.removeEventListener('scroll', this.handleScroll) } handleScroll () { let scrollTop = event.srcElement.body.scrollTop if ((scrollTop > 40) !== this.state.barTranslucent) { this.setState(Object.assign({}, this.state, { barTranslucent: !this.state.barTranslucent })) } } render () { const navBarStyle = Object.assign({ backgroundColor: '#f3f3f3', transition: 'background-color 0.5s ease' }, !this.state.barTranslucent ? {} : { backgroundColor: 'rgba(255, 255, 255, 0.9)' }) const brandStyle = { background: 'linear-gradient(90deg, #f857a6, #ff5858)', backgroundClip: 'text', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' } const navItems = this.props.items.map(item => ( <NavItem key={item.text}> { item.external ? <NavLink className='navLink' href={item.link}> <MediaQuery query='screen and (min-width:768px), screen and (max-width:576px)'>{!item.icon || <FontAwesome name={item.icon} style={{paddingRight: '7px'}} />}</MediaQuery> {item.text} </NavLink> : <NavLink className='navLink' tag={RRNavLink} to={item.link}> <MediaQuery query='screen and (min-width:768px), screen and (max-width:576px)'>{!item.icon || <FontAwesome name={item.icon} style={{paddingRight: '7px'}} />}</MediaQuery> {item.text} </NavLink> } </NavItem> )) return ( <Wrapper className='animated fadeInDown'> <Navbar fixed='top' light toggleable style={navBarStyle}> <RContainer> <NavbarToggler right onClick={this.toggle} /> <NavbarBrand style={brandStyle}> <GrimoireLogo size={42} style={{ boxShadow: '0px 0px 5px 0px #f857a6' }} /> | Grimoire </NavbarBrand> <MediaQuery query='(min-width:992px)'> <a href={INVITE_URL}><Button>Add to Discord</Button></a> </MediaQuery> <Collapse isOpen={this.state.isOpen} navbar> <Nav className='ml-auto' navbar> <style jsx global>{` .navLink { color: #555 !important; padding: 10px 15px 10px 15px !important; } .navLink:hover { color: #FFF !important; background: linear-gradient(90deg, #f857a6, #ff5858); } `}</style> {navItems} </Nav> </Collapse> </RContainer> </Navbar> </Wrapper> ) } } PrimaryNav.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired, link: PropTypes.string.isRequired, external: PropTypes.bool, icon: PropTypes.string })).isRequired } export default PrimaryNav
src/server.js
fkn/ndo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import path from 'path'; import fs from 'fs'; import { URL } from 'url'; import express from 'express'; import expressSession from 'express-session'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import multer from 'multer'; import expressJwt, { UnauthorizedError as Jwt401Error } from 'express-jwt'; import { graphql } from 'graphql'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import nodeFetch from 'node-fetch'; import mimeTypes from 'mime-types'; import React from 'react'; import ReactDOM from 'react-dom/server'; import PrettyError from 'pretty-error'; import App from './components/App'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import createFetch from './createFetch'; import passport from './passport'; import router from './router'; import schema from './data/schema'; // import assets from './asset-manifest.json'; // eslint-disable-line import/no-unresolved import chunks from './chunk-manifest.json'; // eslint-disable-line import/no-unresolved import configureStore from './store/configureStore'; import config from './config'; import models, { File } from './data/models'; import sequelize from './data/sequelize'; const SequelizeStore = require('connect-session-sequelize')( expressSession.Store, ); process.on('unhandledRejection', (reason, p) => { console.error('Unhandled Rejection at:', p, 'reason:', reason); // send entire app down. Process manager will restart it process.exit(1); }); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; const app = express(); const io = require('socket.io')(app.listen(3003)); io.on('connection', socket => { socket.on('chat', data => { io.emit('chat', data); }); }); // // If you are using proxy from external machine, you can set TRUST_PROXY env // Default is to trust proxy headers only from loopback interface. // ----------------------------------------------------------------------------- app.set('trust proxy', config.trustProxy); // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.resolve(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use( expressSession({ secret: 'keyboard cat', store: new SequelizeStore({ db: sequelize }), resave: false, saveUninitialized: true, }), ); // // Authentication // ----------------------------------------------------------------------------- app.use( expressJwt({ secret: config.auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, }), ); // Error handler for express-jwt app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars if (err instanceof Jwt401Error) { console.error('[express-jwt-error]', req.cookies.id_token); // `clearCookie`, otherwise user can't use web-app until cookie expires res.clearCookie('id_token'); } next(err); }); app.use(passport.initialize()); app.use(passport.session()); if (__DEV__) { app.enable('trust proxy'); } app.post( '/register', passport.authenticate('local-signup', { successRedirect: '/', failureRedirect: '/register', }), ); app.post( '/login', passport.authenticate('local-login', { successRedirect: '/', failureRedirect: '/login', }), ); app.post('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get( '/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false, }), ); app.get( '/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false, }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, config.auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); }, ); // // Register API middleware // ----------------------------------------------------------------------------- const storage = multer.memoryStorage(); app.use('/graphql', multer({ storage }).array('upload')); app.use( '/graphql', expressGraphQL(req => ({ schema, graphiql: __DEV__, rootValue: { request: req }, pretty: __DEV__, })), ); app.get('/api/get_file/:id', async (req, res) => { try { const file = await File.findById(req.params.id); const url = new URL(file.url); const stat = fs.statSync(url); res.writeHead(200, { 'Content-Type': mimeTypes.lookup(file.internalName) || 'text/plain', 'Content-Length': stat.size, }); fs.createReadStream(url).pipe(res); } catch (e) { res.send(e); } }); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { const css = new Set(); // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader const insertCss = (...styles) => { // eslint-disable-next-line no-underscore-dangle styles.forEach(style => css.add(style._getCss())); }; // Universal HTTP client const fetch = createFetch( nodeFetch, { baseUrl: config.api.serverUrl, cookie: req.headers.cookie, schema, graphql, }, { user: req.user }, ); const initialState = { user: req.user || null, }; const store = configureStore(initialState, { fetch, // I should not use `history` on server.. but how I do redirection? follow universal-router }); // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { insertCss, fetch, // The twins below are wild, be careful! pathname: req.path, query: req.query, // You can access redux through react-redux connect store, storeSubscription: null, }; const route = await router.resolve(context); if (route.redirect) { res.redirect(route.status || 302, route.redirect); return; } const data = { ...route }; data.children = ReactDOM.renderToString( <App context={context}>{route.component}</App>, ); data.styles = [{ id: 'css', cssText: [...css].join('') }]; const scripts = new Set(); const addChunk = chunk => { if (chunks[chunk]) { chunks[chunk].forEach(asset => scripts.add(asset)); } else if (__DEV__) { throw new Error(`Chunk with name '${chunk}' cannot be found`); } }; addChunk('client'); if (route.chunk) addChunk(route.chunk); if (route.chunks) route.chunks.forEach(addChunk); data.scripts = Array.from(scripts); data.app = { apiUrl: config.api.clientUrl, state: context.store.getState(), }; const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(route.status || 200); res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); // eslint-disable-next-line no-unused-vars app.use((err, req, res, next) => { console.error(pe.render(err)); const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html>, ); res.status(err.status || 500); res.send(`<!doctype html>${html}`); }); // // Launch the server // ----------------------------------------------------------------------------- const promise = models.sync().catch(err => console.error(err.stack)); if (!module.hot) { promise.then(() => { app.listen(config.port, () => { console.info(`The server is running at http://localhost:${config.port}/`); }); }); } // // Hot Module Replacement // ----------------------------------------------------------------------------- if (module.hot) { app.hot = module.hot; module.hot.accept('./router'); } export default app;
src/server/SSR/html.js
wearepush/redux-starter
/* eslint-disable react/no-danger */ import React from 'react'; import { object, node } from 'prop-types'; import serialize from 'serialize-javascript'; import { helmetContext } from './createSSR'; import { isEnvProduction } from '../../../config/consts'; const Html = ({ assets, component, store }) => { const initialState = `window.INITIAL_STATE = ${serialize(store.getState())}`; const { helmet } = helmetContext; const jsMap = assets?.javascript; const jsList = Object.keys(jsMap); const cssMap = assets?.styles; const cssList = Object.keys(cssMap); return ( <html lang="en"> <head> {helmet?.base.toComponent()} {helmet?.title.toComponent()} {helmet?.meta.toComponent()} {helmet?.link.toComponent()} {helmet?.script.toComponent()} <meta charSet="utf-8" /> <meta name="robots" content="INDEX,FOLLOW" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" /> {/* favicons */} <link rel="icon" href="/favicons/icon-48x48.png" /> <link rel="manifest" href="/favicons/manifest.webmanifest" /> <meta name="theme-color" content="#ffffff" /> <link rel="apple-touch-icon" sizes="48x48" href="/favicons/icon-48x48.png" /> <link rel="apple-touch-icon" sizes="72x72" href="/favicons/icon-72x72.png" /> <link rel="apple-touch-icon" sizes="96x96" href="/favicons/icon-96x96.png" /> <link rel="apple-touch-icon" sizes="144x144" href="/favicons/icon-144x144.png" /> <link rel="apple-touch-icon" sizes="192x192" href="/favicons/icon-192x192.png" /> <link rel="apple-touch-icon" sizes="256x256" href="/favicons/icon-256x256.png" /> <link rel="apple-touch-icon" sizes="384x384" href="/favicons/icon-384x384.png" /> <link rel="apple-touch-icon" sizes="512x512" href="/favicons/icon-512x512.png" /> {/* <title></title> <meta name="description" content="" /> */} {/* facebook */} <meta property="author" content="wearepush" /> <meta property="og:site_name" content="wearepush.co" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:image" content="/logo.jpg" /> {/* <meta property="og:title" content="" /> <meta property="og:description" content="" /> */} {/* twitter */} <meta property="twitter:site" content="wearepush.co" /> <meta property="twitter:domain" content="wearepush.co" /> <meta property="twitter:creator" content="wearepush" /> <meta property="twitter:card" content="summary" /> <meta property="twitter:image:src" content="/logo.jpg" /> {/* <meta property="twitter:title" content="" /> <meta property="twitter:description" content="" /> */} {isEnvProduction && ( <> {cssList?.map((c) => ( <link as="style" crossOrigin="anonymous" href={cssMap[c]?.src} integrity={cssMap[c]?.integrity} key={c} rel="preload" /> ))} {jsList?.map((c) => ( <link as="script" crossOrigin="anonymous" href={jsMap[c]?.src} integrity={jsMap[c]?.integrity} key={c} rel="preload" /> ))} </> )} {cssList?.map((c) => ( <link charSet="UTF-8" crossOrigin="anonymous" href={cssMap[c]?.src} integrity={cssMap[c]?.integrity} key={c} rel="stylesheet" type="text/css" /> ))} </head> <body> <div id="root">{component}</div> <script dangerouslySetInnerHTML={{ __html: initialState }} /> {jsList?.map((c) => ( <script crossOrigin={isEnvProduction ? 'anonymous' : undefined} defer integrity={isEnvProduction ? jsMap[c]?.integrity : undefined} key={c} src={isEnvProduction ? jsMap[c]?.src : jsMap[c]} /> ))} </body> </html> ); }; Html.defaultProps = { component: null, }; Html.propTypes = { assets: object.isRequired, component: node, store: object.isRequired, }; export default Html;
client/src/component/common/link-button.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import * as UU5 from 'uu5g03'; import {browserHistory} from 'react-router'; import Utils from "../../utils.js"; import './link-button.css'; const LinkButton = React.createClass({ //@@viewOn:mixins mixins: [ UU5.Common.BaseMixin, UU5.Common.ElementaryMixin, UU5.Layout.FlcMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'Ucl.Itkpd.Configurator.Components.LinkButton', classNames: { main: 'ucl-itkpd-configurator-component-link' }, defaults: { } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { caption: React.PropTypes.string, route: React.PropTypes.string, componentId: React.PropTypes.string }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps() { return { caption: "", route: "", componentId: "" }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _onClick: function() { browserHistory.push(Utils.getRouterBaseUri() + '/' + this.props.route + '?id=' + this.props.componentId + '&project=' + Utils.getParamValue("project")) }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render() { return ( <UU5.Bricks.Link onClick={() => this._onClick()} content={this.props.caption} /> ); } //@@viewOn:render }); export default LinkButton;
docs/src/components/usage-example.js
ridixcr/nuclear-js
import React from 'react' import { Reactor, Store, toImmutable } from 'nuclear-js' import Code from './code' const storeCode = `import { Reactor, Store, toImmutable } from 'nuclear-js' import React from 'react' const reactor = new Reactor({ debug: true }); reactor.registerStores({ typeFilter: Store({ getInitialState() { return null; }, initialize() { this.on('FILTER_TYPE', (state, type) => type) } }), items: Store({ getInitialState() { return toImmutable([ { type: 'food', name: 'banana', price: 1 }, { type: 'food', name: 'doritos', price: 4 }, { type: 'clothes', name: 'shirt', price: 15 }, { type: 'clothes', name: 'pants', price: 20 }, ]) }, initialize() { this.on('ADD_ITEM', (state, item) => state.push(item)) } }) })` const getterCode = `const filteredItemsGetter = [ ['typeFilter'], ['items'], (filter, items) => { return (filter) ? items.filter(i => i.get('type') === filter) : items } ]` const componentCode = `const ItemViewer = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return { items: filteredItemsGetter } }, render() { return ( <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Price</th> </tr> </thead> <tbody> {this.state.items.map(item => { return <tr> <td>{item.get('name')}</td> <td>{item.get('type')}</td> <td>{item.get('price')}</td> </tr> })} </tbody> </table> ) } })` const dispatchCode = `const actions = { setFilter(type) { reactor.dispatch('FILTER_TYPE' type) }, addItem(name, type, price) { reactor.dispatch('ADD_ITEM', toImmutable({ name, type, price })) } } actions.addItem('computer', 'electronics', 1999) actions.setFilter('electronics')` const evaluateCode = `// Evaluate by key path var itemsList = reactor.evaluate(['items']) var item0Price = reactor.evaluate(['items', 0, 'price']) // Evaluate by getter var filteredItems = reactor.evaluate(filteredItemsGetter) // Evaluate and coerce to plain JavaScript var itemsPOJO = reactor.evaluateToJS(filteredItemsGetter) // Observation reactor.observe(filteredItemsGetter, items => { console.log(items) }) ` export default React.createClass({ render() { return ( <div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript">{storeCode}</Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Create a <code>Reactor</code> </h3> <p className="tour-section--bullet-item"> In NuclearJS the <code>reactor</code> acts as the dispatcher, maintains the application state and provides an API for data access and observation. </p> <h3 className="tour-section--bullet-title"> Register stores </h3> <p className="tour-section--bullet-item"> Stores determine the shape of your application state. Stores define two methods: </p> <p> <code>getInitialState()</code> - Returns the initial state for that stores specific key in the application state. </p> <p> <code>initialize()</code> - Sets up any action handlers, by specifying the action type and a function that transforms <pre><code>(storeState, actionPayload) => (newStoreState)</code></pre> </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {getterCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Accessing your data </h3> <p> Getters allow you to easily compose and transform your application state in a reusable way. </p> <h3 className="tour-section--bullet-title"> </h3> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {componentCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Automatic component data binding </h3> <p> Simply use the <code>reactor.ReactMixin</code> and implement the <code>getDataBindings()</code> function to automatically sync any getter to a <code>this.state</code> property on a React component. </p> <p> Since application state can only change after a dispatch then NuclearJS can be intelligent and only call <code>this.setState</code> whenever the actual value of the getter changes. Meaning less pressure on React's DOM diffing. </p> <h3 className="tour-section--bullet-title"> Framework agnostic </h3> <p> This example shows how to use NuclearJS with React, however the same concepts can be extended to any reactive UI framework. In fact, the ReactMixin code is only about 40 lines. </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {dispatchCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Dispatching actions </h3> <p> NuclearJS maintains a very non-magical approach to dispatching actions. Simply call <code>reactor.dispatch</code> with the <code>actionType</code> and <code>payload</code>. </p> <p> All action handling is done synchronously, leaving the state of the system very predictable after every action. </p> <p> Because actions are simply functions, it is very easy to compose actions together using plain JavaScript. </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {evaluateCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Reading application state </h3> <p> NuclearJS also provides imperative mechanisms for evaluating and observing state. </p> <p> In fact any getter can synchronously and imperatively evaluated or observed. The entire <code>ReactMixin</code> is built using only those two functions. </p> </div> </div> </div> ) } })
server/index-view.js
phyllisstein/shannon.camp
import {createServerRenderContext, ServerRouter} from 'react-router'; import _ from 'lodash/fp'; import {App} from 'public/server'; import {AppContainer} from 'react-hot-loader'; import co from 'co'; import React from 'react'; import {Readable} from 'stream'; import {readFileSync} from 'fs'; import {renderToString} from 'react-dom/server'; const assets = JSON.parse(readFileSync('public/.webpack-manifest.json')); const cssTags = _.flow( _.filter((a) => (/\.css$/).test(a)), _.map((a) => `<link href="${a}" onload="this.rel='stylesheet'" rel="preload">`), _.join('') )(assets); const jsTags = _.flow( _.filter((a) => (/\.js$/).test(a)), _.map((a) => `<script src="${a}"></script>`), _.join('') )(assets); class IndexView extends Readable { constructor(ctx) { super(); this.path = ctx.path; this.redirect = ctx::ctx.redirect; this.renderContext = createServerRenderContext(); co.call(this, this.render).catch(ctx::ctx.throw); // eslint-disable-line prefer-reflect } _read() {} *render() { this.push('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta content="Daniel P. Shannon, Colon, The Website" name="description"><meta content="engineering, nonfiction, developer, writer, portfolio, cv, resume" name="keywords"><title>I am big. It’s the character limits that got small. | Daniel P. Shannon</title><meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible"><meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"><link href="/favicon.png" rel="icon">'); this.push(cssTags); this.push('</head><body>'); const reactBody = yield (done) => { const getMarkup = () => { return renderToString( <AppContainer> <ServerRouter context={this.renderContext} location={this.path}> <App /> </ServerRouter> </AppContainer> ); }; let markup = getMarkup(); const result = this.renderContext.getResult(); if (result.redirect) { this.redirect(result.redirect.pathname); markup = getMarkup(); } else if (result.missed) { markup = getMarkup(); } done(null, markup); }; this.push(`<div id="root">${reactBody}</div>`); this.push(` <script> 'use strict';(function(a){var b=function(b,h,e){function d(a){if(f.body)return a();setTimeout(function(){d(a)})}function k(){c.addEventListener&&c.removeEventListener("load",k);c.media=e||"all"}var f=a.document,c=f.createElement("link"),g;if(h)g=h;else{var n=(f.body||f.getElementsByTagName("head")[0]).childNodes;g=n[n.length-1]}var p=f.styleSheets;c.rel="stylesheet";c.href=b;c.media="only x";d(function(){g.parentNode.insertBefore(c,h?g:g.nextSibling)});var l=function(a){for(var b=c.href,d=p.length;d--;)if(p[d].href=== b)return a();setTimeout(function(){l(a)})};c.addEventListener&&c.addEventListener("load",k);c.onloadcssdefined=l;l(k);return c};"undefined"!==typeof exports?exports.loadCSS=b:a.loadCSS=b})("undefined"!==typeof global?global:this); (function(a){if(a.loadCSS){var b=loadCSS.relpreload={};b.support=function(){try{return a.document.createElement("link").relList.supports("preload")}catch(b){return!1}};b.poly=function(){for(var b=a.document.getElementsByTagName("link"),e=0;e<b.length;e++){var d=b[e];"preload"===d.rel&&"style"===d.getAttribute("as")&&(a.loadCSS(d.href,d),d.rel=null)}};if(!b.support()){b.poly();var m=a.setInterval(b.poly,300);a.addEventListener&&a.addEventListener("load",function(){a.clearInterval(m)});a.attachEvent&& a.attachEvent("onload",function(){a.clearInterval(m)})}}})(this); </script> `); this.push(jsTags); this.push('</body></html>'); this.push(null); } } export default IndexView;
client/modules/SharedComponents/Security.js
tranphong001/BIGVN
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import VIP from './VIP'; import Adv from './Adv'; import { fetchCategories, setVisibleBlog, setPageHeader } from '../App/AppActions'; import { getId, getCategories, getBanners, getTopics, getVipAll } from '../App/AppReducer'; import styles from '../../main.css'; import grid from '../../grid.css'; class Security extends Component { constructor(props) { super(props); this.state = { type: 'none', alias: '', oldParams: {}, }; } render() { return ( <div className="container"> <div className={`${grid.contentWidth} col-xs-12`}> Security </div> <div className={`${styles.vipWidth} col-xs-12 ${styles.vipSection}`}> <div style={{ padding: '12px 0 25px 10px' }}> <i className={`fa fa-star ${styles.vipStar}`} aria-hidden="true" /> <span className={styles.vipTitle}>TIN VIP</span> </div> <div style={{ display: 'flex', flexFlow: 'wrap', justifyContent: 'space-between' }}> { this.props.vipAll.map((vip, index) => ( <VIP info={vip} key={`${index}Vip`} index={index} /> )) } </div> </div> <Adv banners={this.props.banners} /> </div> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { id: getId(state), categories: getCategories(state), topics: getTopics(state), banners: getBanners(state), vipAll: getVipAll(state), }; } Security.propTypes = { dispatch: PropTypes.func.isRequired, id: PropTypes.string.isRequired, categories: PropTypes.array.isRequired, topics: PropTypes.array.isRequired, banners: PropTypes.object.isRequired, location: PropTypes.object.isRequired, vipAll: PropTypes.array.isRequired, params: PropTypes.object, }; Security.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(Security);
src/scenes/home/resetPassword/setPassword/setPassword.js
tal87/operationcode_frontend
import React, { Component } from 'react'; import axios from 'axios'; import { Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import Form from 'shared/components/form/form'; import FormPassword from 'shared/components/form/formPassword/formPassword'; import FormButton from 'shared/components/form/formButton/formButton'; import config from 'config/environment'; import styles from './setPassword.css'; class RequestToken extends Component { constructor(props) { super(props); this.state = { password: '', passwordConfirm: '', passwordConfirmValid: true, error: false, isValid: true, success: false, }; } onPasswordChange = (value, valid) => { this.setState({ password: value, passwordValid: valid }); } onConfirmPasswordChange = (value, valid) => { this.setState({ passwordConfirm: value, passwordConfirmValid: valid }); } validatePasswordConfirm = value => value === '' || value === this.state.password; handleOnClick = (e) => { e.preventDefault(); if (this.isFormValid()) { axios.patch(`${config.backendHost}/users/password`, { user: { reset_password_token: this.props.resetPasswordToken, password: this.state.password } }).then(() => { this.setState({ success: true, error: null }); }).catch(() => { this.setState({ error: 'We were unable to set the password for this email' }); }); } } isFormValid = () => this.state.passwordValid && this.state.passwordConfirmValid render() { return ( <Form className={styles.setPasswordForm}> <FormPassword id="password" placeholder="Password" onChange={this.onPasswordChange} validationRegex={/^(?=.*[A-Z]).{6,}$/} validationErrorMessage="Must be 6 characters long and include a capitalized letter" /> <FormPassword id="passwordConfirm" placeholder="Confirm Password" onChange={this.onConfirmPasswordChange} validateFunc={this.validatePasswordConfirm} validationErrorMessage="Passwords must match" /> {this.state.error ? <p className={styles.errorMessage}>{this.state.error}</p> : null } {this.state.success && <Redirect to="/login" />} <FormButton className={styles.joinButton} text="Set Password" onClick={this.handleOnClick} theme="red" /> </Form> ); } } RequestToken.propTypes = { resetPasswordToken: PropTypes.string.isRequired }; export default RequestToken;
src/App.js
JamieCrisman/maru
import React, { Component } from 'react'; import './App.css'; import CircleOfFifths from './CircleOfFifths.js'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h2>Circle of Fifths</h2> </div> <CircleOfFifths /> <div className="helpText"> Enter to submit answer<br /> Type 'F' for flat <br /> Type 'S' for sharp </div> </div> ); } } export default App;
dashboard/src/components/dashboard/StatusPanel.js
leapfrogtechnology/chill
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withStatusInfo } from '../hoc/status'; import * as websocket from '../../services/websocket'; import * as statusService from '../../services/status'; import Panel from '../commons/Panel'; import ServiceList from './ServiceList'; import Spinner from '../commons/Spinner'; /** * Fetch list of services from the API and provides * to ServiceList component. */ class StatusPanel extends Component { componentDidMount() { const { handleWebSocketNotification } = this.props; this.fetchStatuses(); websocket.initialize({ onMessage: handleWebSocketNotification }); } /** * Fetch list of services. * * @returns {Promise} */ async fetchStatuses() { const { updateStatus } = this.props; updateStatus({ isLoading: true, services: [] }); try { let services = await statusService.fetchServiceStatuses(); updateStatus({ services, isLoading: false }); } catch (err) { // TODO: Show error messages } } render() { const { isLoading, services } = this.props.status; const statuses = services && services.map(service => JSON.parse(service.status)); const { className, message } = statusService.getOutageParams(statuses); if (isLoading) { return <Spinner />; } return ( <> <Panel title={message} panelClassName={className} /> <ServiceList services={services} /> </> ); } } StatusPanel.propTypes = { status: PropTypes.object, updateStatus: PropTypes.func, handleWebSocketNotification: PropTypes.func }; export default withStatusInfo(StatusPanel);
src/universalRouter.js
davidmarkclements/react-redux-universal-hot-example
import React from 'react'; import Router from 'react-router'; import createRoutes from './views/createRoutes'; import { Provider } from 'react-redux'; const getFetchData = (component = {}) => { return component.WrappedComponent ? getFetchData(component.WrappedComponent) : component.fetchData; }; export function createTransitionHook(store) { return (nextState, transition, callback) => { const { params, location: { query } } = nextState; const promises = nextState.branch .map(route => route.component) // pull out individual route components .filter((component) => getFetchData(component)) // only look at ones with a static fetchData() .map(getFetchData) // pull out fetch data methods .map(fetchData => fetchData(store, params, query || {})); // call fetch data methods and save promises Promise.all(promises) .then(() => { callback(); // can't just pass callback to then() because callback assumes first param is error }, (error) => { callback(error); }); }; } export default function universalRouter(location, history, store) { const routes = createRoutes(store); return new Promise((resolve, reject) => { Router.run(routes, location, [createTransitionHook(store)], (error, initialState, transition) => { if (error) { return reject(error); } if (transition && transition.redirectInfo) { return resolve({ transition, isRedirect: true }); } if (history) { // only on client side initialState.history = history; } const component = ( <Provider store={store} key="provider"> {() => <Router {...initialState} children={routes}/>} </Provider> ); return resolve({ component, isRedirect: false }); }); }); }
actor-apps/app-web/src/app/components/ToolbarSection.react.js
gaolichuang/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin } from 'react-intl'; import classnames from 'classnames'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import DialogStore from 'stores/DialogStore'; import ActivityStore from 'stores/ActivityStore'; const getStateFromStores = () => { return { dialogInfo: DialogStore.getSelectedDialogInfo(), isActivityOpen: ActivityStore.isOpen() }; }; @ReactMixin.decorate(IntlMixin) class ToolbarSection extends React.Component { state = { dialogInfo: null, isActivityOpen: false }; constructor(props) { super(props); DialogStore.addSelectedChangeListener(this.onChange); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeSelectedChangeListener(this.onChange); ActivityStore.removeChangeListener(this.onChange); } onClick = () => { if (!this.state.isActivityOpen) { ActivityActionCreators.show(); } else { ActivityActionCreators.hide(); } }; onChange = () => { this.setState(getStateFromStores()); }; render() { const { dialogInfo, isActivityOpen } = this.state; const infoButtonClassName = classnames('button button--icon', { 'active': isActivityOpen }); if (dialogInfo !== null) { return ( <header className="toolbar row"> <div className="toolbar__peer col-xs"> <span className="toolbar__peer__title">{dialogInfo.name}</span> <span className="toolbar__peer__presence">{dialogInfo.presence}</span> </div> <div className="toolbar__controls"> <div className="toolbar__controls__search pull-left hide"> <i className="material-icons">search</i> <input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/> </div> <div className="toolbar__controls__buttons pull-right"> <button className={infoButtonClassName} onClick={this.onClick}> <i className="material-icons">info</i> </button> <button className="button button--icon hide"> <i className="material-icons">more_vert</i> </button> </div> </div> </header> ); } else { return ( <header className="toolbar"/> ); } } } export default ToolbarSection;
test/fixtures/mjs-support/src/index.js
Timer/create-react-app
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
examples/counter/containers/CounterApp.js
wmertens/redux
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'redux/react'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; @connect(state => ({ counter: state.counter })) export default class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } }
src/index.js
chisbug/Webpack2-For-React
/* 入口文件 */ import React from 'react' import ReactDOM from 'react-dom' import { Router, Route, hashHistory } from 'react-router' import { createStore } from 'redux' import { Provider } from 'react-redux' import message from './reducers' import { sendMsg } from 'Actions' import { AppContainer } from 'react-hot-loader' /* 引入公共样式 */ import css from './common.less' /* 引入组件 */ import App from './components/App' import Info from './components/Info' /* 创建 store */ let store = createStore(message) console.log(store.getState()) /* 监听store变化, 每当dispatch发生时,此函数将被调用 */ store.subscribe(function() { console.info(store.getState()) }) /* routes */ const routes = ( <div> <Route path="/" component={App} /> <Route path="info" component={Info} /> </div> ) /* <Provider store>使组件层级中的 connect() 方法都能够获得 Redux store */ const render = (Component) => { ReactDOM.render( <AppContainer> <Provider store={store}> <Router history={hashHistory}> { routes } </Router> </Provider> </AppContainer>, document.getElementById('root') ) } render(App) /* hot module reload */ if (module.hot) { module.hot.accept('./components/App', () => { render(App) }) }
src/workflows/nwchem/nwchem-exec/components/root/NewSimulation.js
Kitware/HPCCloud
import React from 'react'; import PropTypes from 'prop-types'; import { FileUploadEntry } from '../../../../../panels/ItemEditor'; // ---------------------------------------------------------------------------- export default function newSimulation(props) { return ( <div> <FileUploadEntry name="geometry" label="Geometry file" accept=".pdb,.xyz" owner={props.owner} /> <FileUploadEntry name="nw" label="nw file" accept=".nw" owner={props.owner} /> </div> ); } // ---------------------------------------------------------------------------- newSimulation.propTypes = { owner: PropTypes.func, }; newSimulation.defaultProps = { owner: undefined, };
src/routes/contact/index.js
tlin108/chaf
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Contact from './Contact'; const title = 'Contact Us'; export default { path: '/contact', action() { return { title, component: <Layout><Contact title={title} /></Layout>, }; }, };
src/index.js
Jcook894/Blog_App
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, browserHistory } from 'react-router'; import promise from 'redux-promise'; import reducers from './reducers'; import routes from './routes'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router history={browserHistory} routes={routes}/> </Provider> , document.querySelector('.container'));
src/views/Dashboard.js
DavidSGK/plan-me
import React, { Component } from 'react'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import Paper from 'material-ui/Paper'; import ContentAdd from 'material-ui/svg-icons/content/add'; import { merge, slice } from 'ramda'; import AddEvent from '../components/AddEvent'; import { connect } from 'react-redux'; import RandomMC from 'random-material-color'; const topSpace = { paddingTop : 64, }; const fabStyle = { position : 'fixed', right : 0, bottom : 0, margin : '5%', }; const tableStyle = { position : 'absolute', margin : '3%', marginTop : '0', //border : '1 solid black', borderCollapse : 'collapse', tableLayout : 'fixed', width : '94%', } const headerTableStyle = { width : '94%', height : '5%', position : 'absolute', margin : '3%', marginBottom : '0', borderCollapse : 'collapse', tableLayout : 'fixed', } const thContents = [ 'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', ]; const emptyRow = ['', '', '', '', '', '', '']; const cellStyle = { borderTop : '1px solid #AAAAAA', borderBottom : '1px solid #AAAAAA', borderLeft : '1px solid #555555', borderRight : '1px solid #555555', borderCollapse : 'collapse', padding : 15, width : '12.5%', height : 75, fontSize : '150%', fontWeight : 100, }; const timeCellStyle = { borderRight : '3px solid #555555', borderCollapse : 'collapse', padding : 3, textAlign : 'right', verticalAlign : 'top', width : 'auto', fontSize : '75%', fontWeight : 100, } const timeList = [ '12 AM', '1 AM', '2 AM', '3 AM', '4 AM', '5 AM', '6 AM', '7 AM', '8 AM', '9 AM', '10 AM', '11 AM', '12 PM', '1 PM', '2 PM', '3 PM', '4 PM', '5 PM', '6 PM', '7 PM', '8 PM', '9 PM', '10 PM', '11 PM', ]; const calendarPane = { width : '90%', height : '80%', position : 'absolute', bottom : '7%', left : '5%', }; const calendarDiv = { width : '100%', position : 'relative', overflow : 'auto', }; const eventBlock = { //border : '1px solid white', width : '12.2%', position : 'absolute', color : 'white', fontSize : '60%', overflow : 'hidden', padding : 3, }; const weekToDays = (weekArray = Array(672).fill(null)) => { const days = new Array(7); var i, j, k; for(i = 0; i < 7; i++){ days[i] = slice(i * 96, (i+1) * 96, weekArray); for(j = 0; j < 96; j++){ if(j == 0 && days[i][0] != null && (days[i][days[i][0].duration-1] == null || days[i][0].title != days[i][days[i][0].duration-1].title)){ days[i][0].duration--; j--; continue; } else if(j == 0){ while(days[i][j] != null){ j++; days[i][j] = null; } j = 0; } if(days[i][j] != null){ if(j + days[i][j].duration <= 96){ for(k = 1; k < days[i][j].duration; k++){ days[i][j+k] = null; } } else { days[i][j].duration -= (j + days[i][j].duration - 96); j--; continue; } } } } return days; }; class Dashboard extends Component { constructor() { super(); this.state = { isOpen: false, }; this.handleOpen = this.handleOpen.bind(this); this.handleClose = this.handleClose.bind(this); } handleOpen() { this.setState({isOpen: true}); }; handleClose() { this.setState({isOpen: false}); }; render() { const days = weekToDays(this.props.calendar); return ( <div style={topSpace}> <Paper style={calendarPane}> <div style={merge(calendarDiv, {height : '13%',})}> <table style={headerTableStyle}> <tbody> <tr> <th></th> {thContents.map((thContent, i) => <th key={i} style={merge(cellStyle, {padding : 3, height : 15, borderLeft : 'none', borderTop : 'none', borderRight : 'none', borderBottom : '3px solid #555555'})}>{thContent}</th>)} </tr> </tbody> </table> </div> <div style={merge(calendarDiv, {height : '87%',})}> <table style={tableStyle}> <tbody> {timeList.map(function(a, i){ return <tr key={i}> <th key={i+200} style={timeCellStyle}>{a}</th> {emptyRow.map((emptyRow, j) => <td key={j} style={cellStyle}>{emptyRow}</td>)} </tr> })} </tbody> {days.map(function(a, i){ return days[i].map(function(b, j){ if(b !== null){ return <div key={j} style={merge(eventBlock, { height : `${b.duration * (100 / 96)}%`, top : `${j * (100 / 96)}%`, left : `${(i + 1) * 12.5 + (8 - i) / 10}%`, background : `${RandomMC.getColor()}`})} > <h5>{b.title}</h5> <br></br> <p>{b.description}</p> </div>; } else return null; }) })} </table> </div> </Paper> <FloatingActionButton style={fabStyle} onClick={this.handleOpen} > <ContentAdd /> </FloatingActionButton> <AddEvent isOpen={this.state.isOpen} handleOpen={this.handleOpen} handleClose={this.handleClose} /> </div> ); } } const mapStateToProps = state => ({ calendar: state.user.calendar, }); export default connect(mapStateToProps)(Dashboard);
src/parser/warrior/fury/modules/azerite/UnbridledFerocity.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import StatTracker from 'parser/shared/modules/StatTracker'; import { formatNumber, formatPercentage, formatThousands } from 'common/format'; import { calculateAzeriteEffects } from 'common/stats'; import calculateBonusAzeriteDamage from 'parser/core/calculateBonusAzeriteDamage'; import TraitStatisticBox from 'interface/others/TraitStatisticBox'; import SPELLS from 'common/SPELLS'; import { SELECTED_PLAYER } from 'parser/core/EventFilter'; import RAMPAGE_COEFFICIENTS from '../spells/RAMPAGE_COEFFICIENTS.js'; const RAMPAGE = [SPELLS.RAMPAGE_1, SPELLS.RAMPAGE_2, SPELLS.RAMPAGE_3, SPELLS.RAMPAGE_4]; const RECKLESSNESS_DURATION = 10000; const RECLESSNESS_DURATION_VARIANCE = 100; class UnbridledFerocity extends Analyzer { static dependencies = { statTracker: StatTracker, }; totalDamage = 0; recklessnessEvents = []; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.UNBRIDLED_FEROCITY.id); if(!this.active) { return; } this.traitBonus = this.selectedCombatant.traitsBySpellId[SPELLS.UNBRIDLED_FEROCITY.id].reduce((total, rank) => { const [ damage ] = calculateAzeriteEffects(SPELLS.UNBRIDLED_FEROCITY.id, rank); return total + damage; }, 0); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(RAMPAGE), this.onTraitDamage); this.addEventListener(Events.applybuff.to(SELECTED_PLAYER).spell(SPELLS.RECKLESSNESS), this.onBuffApply); this.addEventListener(Events.removebuff.to(SELECTED_PLAYER).spell(SPELLS.RECKLESSNESS), this.onBuffRemoved); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.RECKLESSNESS), this.onRecklessnessCast); this.addEventListener(Events.fightend, this.onFightEnd); } onTraitDamage(event) { const coefficient = RAMPAGE_COEFFICIENTS.find(r => r.id === event.ability.guid).coefficient; const [ bonusDamage ] = calculateBonusAzeriteDamage(event, [this.traitBonus], coefficient, this.statTracker.currentStrengthRating); this.totalDamage += bonusDamage; } onBuffApply(event) { this.recklessnessEvents.push({ start: event.timestamp, end: null, recklessnessCast: false, }); } onRecklessnessCast() { if (this.recklessnessEvents.length === 0) { return; } const lastIndex = this.recklessnessEvents.length - 1; this.recklessnessEvents[lastIndex].recklessnessCast = true; } onBuffRemoved(event) { if (this.recklessnessEvents.length === 0) { return; } const lastIndex = this.recklessnessEvents.length - 1; this.recklessnessEvents[lastIndex].end = event.timestamp; } onFightEnd(event) { // If Recklessness was active at the end of the fight, we need to flag it as ended as there is no buff removed event if (this.recklessnessEvents.length === 0) { return; } const lastIndex = this.recklessnessEvents.length - 1; if(!this.recklessnessEvents[lastIndex].end) { this.recklessnessEvents[lastIndex].end = event.timestamp; } } get damagePercentage() { return this.owner.getPercentageOfTotalDamageDone(this.totalDamage); } get increasedRecklessnessDuration() { // If Recklessness is active and the trait procs, the 10 seconds of buff time is increased by 4 seconds with no event. // To check for this, we need to check if recklessness lasted for more than 10 seconds, and if so, subtract those 10 seconds from the uptime to get the additional buff duration from the trait return this.recklessnessEvents.reduce((total, event) => { const duration = event.end - event.start; // Was this a recklessness cast and lasted < 10 seconds with event variance if (event.recklessnessCast && (duration < (RECKLESSNESS_DURATION - RECLESSNESS_DURATION_VARIANCE) || duration < (RECKLESSNESS_DURATION + RECLESSNESS_DURATION_VARIANCE))) { return total; } else if (duration > (RECKLESSNESS_DURATION - RECLESSNESS_DURATION_VARIANCE)) { // Was the buff longer than 10 seconds (in which case it was a proc and normal recklessness) return total + duration - RECKLESSNESS_DURATION; } else { return total + duration; } }, 0); } statistic() { return ( <TraitStatisticBox trait={SPELLS.UNBRIDLED_FEROCITY.id} value={`${formatNumber(this.increasedRecklessnessDuration / 1000)}s Recklessness`} tooltip={<>Unbridled Ferocity did <b>{formatThousands(this.totalDamage)} ({formatPercentage(this.damagePercentage)}%)</b> damage.</>} /> ); } } export default UnbridledFerocity;
src/routes/content/index.js
samerce/lampshade
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; import Content from './Content'; export default { path: '*', async action({ path }) { // eslint-disable-line react/prop-types const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: `{content(path:"${path}"){path,title,content,component}}`, }), credentials: 'include', }); if (resp.status !== 200) throw new Error(resp.statusText); const { data } = await resp.json(); if (!data || !data.content) return undefined; return { title: data.content.title, component: <Layout><Content {...data.content} /></Layout>, }; }, };
client/src/components/dashboard/profile/utils/trash-look-seven.js
mikelearning91/seeme-starter
import React, { Component } from 'react'; import Modal from 'react-modal'; import MdDelete from 'react-icons/lib/md/delete'; const cookie = require('react-cookie') const axios = require('axios'); class TrashLookSeven extends React.Component { constructor(props) { super(props); this.trashLook = this.trashLook.bind(this); } trashLook() { const user = cookie.load('user'); const emailQuery = user.email; const lookId = user.looks[5]._id; console.log(lookId) axios.put('https://seemedate.herokuapp.com/api/see/delete-look', { emailQuery: emailQuery, lookId: lookId }, { headers: { Authorization: cookie.load('token') } }) .then((response) => { cookie.save('token', response.data.token, { path: '/' }); cookie.save('user', response.data.user, { path: '/' }); this.props.remove(); }) .catch((error) => { console.log(error); }); } render() { return ( <div> <button className="trash-look" onClick={this.trashLook}><MdDelete /></button> </div> ); } } export default TrashLookSeven;
app/components/Loading/Loading.js
RcKeller/STF-Refresh
import React from 'react' import PropTypes from 'prop-types' // import _ from 'lodash' import { Spin, Alert } from 'antd' class Loading extends React.Component { static propTypes = { // Render goes through a truthiness check render: PropTypes.any.isRequired, // Component title and loading promp title: PropTypes.string, tip: PropTypes.string, // Alert type (change to error or info to change UI severity) type: PropTypes.string, // Timeout Interval timeout: PropTypes.number } static defaultProps = { render: false, tip: 'Loading...', title: 'this component', type: 'warning', timeout: 5000 } state = { error: '', info: '' } componentDidMount () { setTimeout(this.requestTimedOut, this.props.timeout) } requestTimedOut = () => { const { render } = this.props if (!render) { // throw new Error('We were unable to find data on the server.') this.setState({ error: true, info: 'We were unable to find data on the server.' }) } } componentDidCatch (error, info) { this.setState({ error, info }) } render ( { children, render, title, tip, type } = this.props, { error, info } = this.state ) { if (error) { return ( <Alert showIcon message={`Loading ${title} has failed`} description={info ? <div> <p>Try refreshing the page by pressing F5. If this error continues to occur, please notify our developer at [email protected].</p> <hr /> <pre> <small> {`{ 'ERROR AT ${window && window.location && window.location.href}': [${JSON.stringify(error)}, ${JSON.stringify(info)}] }`} </small> </pre> </div> : 'An unknown error has occured.' } type={type} /> ) } else if (!render) { return ( <div style={{ width: '100%' }}> <Spin size='large' spinning tip={tip} // delay={500} /> </div> ) } return children } } export default Loading
src/app/components/player-visual.js
pashist/soundcloud-like-player
import React from 'react'; import PlayerArtwork from './player-artwork'; import PlayerButton from './player-button'; import PlayerTitle from './player-title'; import MediaButtons from './media-buttons'; import PlayerWaveForm from './player-waveform'; import SharePanel from './share-panel'; import TracksTotal from './tracks-total'; import {connect} from 'react-redux'; import * as actions from '../actions'; import {get as getProperty} from 'lodash' @connect(state => ({ isPlaying: state.isPlaying, isPlayed: state.isPlayed, track: state.track, options: state.options, player: state.player, playlist: state.playlist, scrollValue: state.scrollValue, playlistHeight: state.playlistHeight, isSharePanelActive: state.isSharePanelActive, tracks: state.tracks })) export default class PlayerVisual extends React.Component { constructor(props) { super(props); this.onShareBtnClick = this.onShareBtnClick.bind(this); this.onWaveFormClick = this.onWaveFormClick.bind(this); this.onSeek = this.onSeek.bind(this); this.togglePlayback = this.togglePlayback.bind(this); this.mainColor = { url: '', color: [], isFetching: false }; this.defaultUrl = 'https://a1.sndcdn.com/images/default_artwork_large.png'; } componentDidUpdate() { this.detectMainColor(); } render() { const {track, playlist, player, isPlaying, isPlayed, options, isSharePanelActive} = this.props; if (!track) return null; let style = { backgroundImage: `url(${this.getBgUrl()})`, height: this.calcHeight() + 'px' }; return ( <div className="player" style={style}> <div className="sound"> <div className="sound-header"> <PlayerButton colors={options.colors} track={track} isPlaying={isPlaying} player={player} onClick={this.togglePlayback}/> <MediaButtons data={playlist || track} isPlayed={isPlayed} options={options} onShareBtnClick={this.onShareBtnClick} isSharePanelActive={isSharePanelActive}/> <PlayerTitle data={playlist|| track}/> </div> <div className="sound-footer"> {isPlayed && playlist && <PlayerArtwork track={track} showFollowButton={false}/>} {(isPlayed || !playlist) && <PlayerWaveForm onSeek={this.onSeek} onClick={this.onWaveFormClick} colors="light"/>} {!isPlayed && playlist && <TracksTotal value={this.calcTracksTotal()}/>} </div> <SharePanel isActive={isSharePanelActive} data={playlist || track}/> </div> </div> ) } togglePlayback() { this.props.dispatch(actions.toggle()); } onWaveFormClick() { this.props.dispatch(actions.play()); } onSeek(time) { this.props.dispatch(actions.setTrackCurrentTime(time)); } onShareBtnClick() { this.props.dispatch(actions.toggleSharePanel()) } getBgUrl(size = '500x500') { let url; if (this.props.playlist) { url = this.props.playlist.artwork_url || this.props.playlist.user.avatar_url; } else if(this.props.track) { url = this.props.track.artwork_url || this.props.track.user.avatar_url; } if (url) { url = url.replace(/large\./, `t${size}.`); } return url || this.defaultUrl; } detectMainColor() { const imgUrl = this.getBgUrl(); if (this.defaultUrl == imgUrl || this.mainColor.isFetching) return; if (this.mainColor.url != imgUrl || !this.mainColor.color.length) { this.mainColor.isFetching = true; this.mainColor.url = imgUrl; fetch(imgUrl) .then(response => response.blob()) .then(blob => { this.mainColor.isFetching = false; let image = new Image(); image.src = URL.createObjectURL(blob); image.onload = () => { let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0); let pixelData = context.getImageData(0, 0, image.width, image.height).data; let pixelCount = image.width*image.height; let avg = [0,0,0]; for (let i = 0, offset; i < pixelCount; i = i + 1) { offset = i * 4; avg[0] += pixelData[offset + 0]; avg[1] += pixelData[offset + 1]; avg[2] += pixelData[offset + 2]; } avg = avg.map(val => Math.round(val/pixelCount)); this.mainColor.color = avg; this.props.dispatch(actions.setMainColor(this.mainColor.color)); } }) .catch(err => { console.log('detectMainColor error:', err); this.mainColor.isFetching = false; }); } } calcHeight() { return this.props.options.height - (this.props.playlist ? this.props.playlistHeight : 0) } calcTracksTotal() { return this.props.tracks.filter(track => !track.error).length } }
src/components/tabs/Tabs.js
edgemesh/emui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM, { findDOMNode as $ } from 'react-dom'; import Radium from 'radium'; import { colors } from '../../utils/colors'; import Paper from '../paper/Paper'; import Icon from '../icon/Icon'; import View from '../view/View'; @Radium export default class Tab extends Component { static propTypes = { // Tabs configuration defaultTab: PropTypes.number, // Index of the children array tabStyles: PropTypes.object, // Pass style to all child `Tab` elements tabDisabledStyles: PropTypes.object, // Pass disabled style to all child `Tab` elements tabSelectedStyles: PropTypes.object, // Pass style to the selected `Tab` element tabContainerStyles: PropTypes.object, // Pass style to the container of the `Tab` elements depth: PropTypes.number, // Sets the depth of the outer `Paper` element of the Tabs component contentContainerStyles: PropTypes.object, // Pass style to the content container of the `Tabs` elements accent: PropTypes.string, // InkBar and active `Tab` text color contentContainerClassName: PropTypes.string, // Just here for webkit scrollbar support fixedWidthTabs: PropTypes.bool, // True: Children `Tab` elements are fixed equal width -- // False: Children `Tab` elements are auto width aligned flex-start // Event onSelect: PropTypes.func // Optional onSelect event override for all `Tab` components -- // onSelect will return value and tab index of selected tab on trigger }; static defaultProps = { defaultTab: 0, depth: 1, accent: colors.cyan500, fixedWidthTabs: true }; state = { selectedIndex: this.props.defaultTab, selectedTabWidth: 0, selectedTabLeft: 0, tabsContainerWidth: 0 }; componentWillMount() { this.resizeHandler = this._getSelectedTabWidth.bind(this, true); window.addEventListener('resize', this.resizeHandler); } componentWillUnmount() { window.removeEventListener('resize', this.resizeHandler); } componentDidMount() { let firstActiveTab = this._findFirstActiveTab(this.props.children); if (firstActiveTab !== this.props.defaultTab) { this.handleSelect(firstActiveTab); } setTimeout(()=>{ this._getSelectedTabWidth(true, this.state.selectedIndex); }) } render() { let { children, tabStyles, tabSelectedStyles, accent, onSelect, style, fixedWidthTabs, contentContainerStyles, tabContainerStyles, contentContainerClassName, tabDisabledStyles, depth } = this.props; let { selectedIndex } = this.state; let currentTabContent; let tabs = React.Children.map( children, (child, i)=>{ // Determine if Tab component via default set 'tab' prop if (child.props.tab) { // If tab is selected, set it's children as the currentTabContent if (i == selectedIndex) { currentTabContent = !child.props.disabled && child.props.children } return React.cloneElement(child, { index: i, onClick: this.handleSelect.bind(this, i), onSelect: onSelect ? onSelect : child.onSelect, // optionally override onSelect event for all Tab components selected: i == selectedIndex, // Determine if selected selectedStyles: tabSelectedStyles, style: tabStyles, fixedWidth: fixedWidthTabs, ref: `Tab-${i}`, disabledStyles: tabDisabledStyles, accent, }) } else { // If it's not a Tab component, fire a warning console.warn('Only \'Tab\' components should be direct children of a \'Tabs\' component.') } }, this) return ( <Paper style={[styles.container, style]} depth={depth}> {/* Tab Header Row - Row containing Tab components */} <Paper healLeft healRight healTop depth={1}> <View ref="tabs-container" row style={[styles.rowHeader, tabContainerStyles]}> {tabs} </View> {this._renderInkBar()} </Paper> {/* Content of the currently selected Tab */} <div className={contentContainerClassName} style={[styles.fullHeight, contentContainerStyles]}> {currentTabContent} </div> </Paper> ); } ///////////////////// // Public Methods // ///////////////////// handleSelect(index){ let { selectedTabWidth, selectedTabLeft } = this._getSelectedTabWidth(false, index); this.setState({ selectedIndex: index, selectedTabWidth, selectedTabLeft }); } ///////////////////// // Private Methods // ///////////////////// _renderInkBar(){ let { accent } = this.props; let { selectedTabWidth, selectedTabLeft, tabsContainerWidth } = this.state; // Keeping our width in percentage versus pixel value, removes the perceived lag when resizing. let width = ( selectedTabWidth/tabsContainerWidth ) * 100; let left = ( selectedTabLeft/tabsContainerWidth ) * 100; // This is mostly to handle on mount, so that the Inkbar is not stretched all the way across if (!width || width === Infinity ) { width = 0, left = 0 } width = width + '%'; left = left + '%'; let inkBarContainerStyles = { width: '100%', transform: `translateX(${left})` }; let inkBarStyles = { width, backgroundColor: accent }; return ( <div style={[ styles.inkBar, inkBarContainerStyles ]}> <div style={[styles.inkBar, inkBarStyles]}></div> </div> ); } _getSelectedTabWidth(setState, index){ let { children } = this.props; if(index !== undefined && index !== null){ if (setState) index = this.state.selectedIndex; let selectedTabWidth = $(this.refs[`Tab-${index}`]).offsetWidth; let selectedTabLeft = $(this.refs[`Tab-${index}`]).offsetLeft; let tabsContainerWidth = $(this.refs['tabs-container']).offsetWidth; if (setState) { this.setState({ selectedTabWidth, selectedTabLeft, tabsContainerWidth }); } else { return { selectedTabWidth, selectedTabLeft, tabsContainerWidth }; } } else { return { selectedTabWidth: 0, selectedTabLeft: 0, tabsContainerWidth: 0 } } } _findFirstActiveTab(children){ let firstActiveTab; let activeTab = React.Children.toArray(children).some((child, i)=>{ if (child.props.tab) { if (!child.props.disabled){ firstActiveTab = i; return true; } } }); if (!activeTab) { console.warn('You must have at least ONE `Tab` element that is not disabled!')} return firstActiveTab; } } const styles = { fullHeight: { height: '100%' }, rowHeader: { overflow: 'hidden', justifyContent: 'flex-start', alignItems: 'center' }, inkBar: { height: 2, transition: 'transform 200ms ease-out, width 200ms ease-out' } }
src/modules/etfms-profile/components/FlightProfile/Trend.js
devteamreims/4me.react
import React, { Component } from 'react'; import TrendUp from 'material-ui/svg-icons/action/trending-up'; import TrendFlat from 'material-ui/svg-icons/action/trending-flat'; import TrendDown from 'material-ui/svg-icons/action/trending-down'; import { blue500, green500, } from 'material-ui/styles/colors'; const colors = { CLIMB: blue500, CRUISE: undefined, DESCENT: green500, }; class Trend extends Component { render() { const { trend, } = this.props; const color = colors[trend]; switch(trend) { case 'CLIMB': return <TrendUp color={color} />; case 'CRUISE': return <TrendFlat color={color} />; case 'DESCENT': return <TrendDown color={color} />; } return null; } } Trend.propTypes = { trend: React.PropTypes.oneOf(['CLIMB', 'CRUISE', 'DESCENT']).isRequired, }; export default Trend;
examples/query-params/app.js
gdi2290/react-router
import React from 'react'; import HashHistory from 'react-router/lib/HashHistory'; import { Router, Route, Link } from 'react-router'; var User = React.createClass({ render() { var { query } = this.props.location; var age = query && query.showAge ? '33' : ''; var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> {age} </div> ); } }); var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/bob">Bob</Link></li> <li><Link to="/user/bob" query={{showAge: true}}>Bob With Query Params</Link></li> <li><Link to="/user/sally">Sally</Link></li> </ul> {this.props.children} </div> ); } }); React.render(( <Router history={new HashHistory}> <Route path="/" component={App}> <Route path="user/:userID" component={User}/> </Route> </Router> ), document.getElementById('example'));
stories/LogoTitle/LogoTitle.js
medialab/hyphe-browser
import './LogoTitle.styl' import React from 'react' const LogoTitle = () => { return ( <h1 className="logo-title"> <img src={ require('../../app/images/logos/hyphe.png') } /> <span>Hyphe <i>browser</i></span> </h1> ) } export default LogoTitle
node_modules/react-router/es/Redirect.js
AngeliaGong/AngeliaGong.github.io
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import warning from 'warning'; import invariant from 'invariant'; import { createLocation, locationsAreEqual } from 'history'; /** * The public API for updating the location programmatically * with a component. */ var Redirect = function (_React$Component) { _inherits(Redirect, _React$Component); function Redirect() { _classCallCheck(this, Redirect); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Redirect.prototype.isStatic = function isStatic() { return this.context.router && this.context.router.staticContext; }; Redirect.prototype.componentWillMount = function componentWillMount() { invariant(this.context.router, 'You should not use <Redirect> outside a <Router>'); if (this.isStatic()) this.perform(); }; Redirect.prototype.componentDidMount = function componentDidMount() { if (!this.isStatic()) this.perform(); }; Redirect.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var prevTo = createLocation(prevProps.to); var nextTo = createLocation(this.props.to); if (locationsAreEqual(prevTo, nextTo)) { warning(false, 'You tried to redirect to the same route you\'re currently on: ' + ('"' + nextTo.pathname + nextTo.search + '"')); return; } this.perform(); }; Redirect.prototype.perform = function perform() { var history = this.context.router.history; var _props = this.props, push = _props.push, to = _props.to; if (push) { history.push(to); } else { history.replace(to); } }; Redirect.prototype.render = function render() { return null; }; return Redirect; }(React.Component); Redirect.propTypes = { push: PropTypes.bool, from: PropTypes.string, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired }; Redirect.defaultProps = { push: false }; Redirect.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired, staticContext: PropTypes.object }).isRequired }; export default Redirect;
packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/RequiredSign/index.js
wistityhq/strapi
import React from 'react'; import styled from 'styled-components'; const Required = styled.span` color: ${({ theme }) => theme.colors.danger700}; padding-left: ${({ theme }) => theme.spaces[1]}px; `; const RequiredSign = () => <Required>*</Required>; export default RequiredSign;
client/js/components/Navbar.js
micahp0506/jeeps
'use strict'; import React from 'react'; import alt from '../utils/alt'; import {Route, Router, browserHistory, Link} from 'react-router'; import LoginStore from '../stores/LoginStore'; import SearchStore from '../stores/SearchStore'; import LoginActions from '../actions/LoginActions'; import MyPostsActions from '../actions/MyPostsActions'; import MyPostsStore from '../stores/MyPostsStore'; // Creating Navbar to handle navigation class Navbar extends React.Component{ constructor(props) { super(props); this.state = LoginStore.getState(); this.onChange = this.onChange.bind(this); this.handleLogout = this.handleLogout.bind(this); this.handleMyPosts = this.handleMyPosts.bind(this); } componentDidMount() { LoginStore.listen(this.onChange); } componentWillUnmount(){ LoginStore.unlisten(this.onChange); } onChange(state){ this.setState(state) } handleMyPosts() { let login = LoginStore.getState(); let id = login.userId; MyPostsActions.getMyPosts(id); } handleLogout() { alt.recycle(LoginStore); alt.recycle(SearchStore); toastr.success('User logged out.'); this._reactInternalInstance._context.history.push('/'); } render() { if (this.state.loginState) { return( <nav className="navbar navbar-inverse navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#">Jeepers</a> </div> <div id="navbar" className="collapse navbar-collapse"> <ul className="nav navbar-nav options"> <li><Link to={'/'}>Home</Link></li> <li><Link to={'/search'}>Search Listings</Link></li> <li><Link to={'/sale'}>Sell Your Rig</Link></li> <li><Link to={'/myposts'} onClick={this.handleMyPosts}>My Posts</Link></li> <li><a href="#" onClick={this.handleLogout}>Log Out</a></li> </ul> </div> </div> </nav> ) } else { return ( <nav className="navbar navbar-inverse navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#">Jeepers</a> </div> <div id="navbar" className="collapse navbar-collapse"> <ul className="nav navbar-nav options"> <li><Link to={'/'}>Home</Link></li> <li><Link to={'/search'}>Search Listings</Link></li> <li><Link to={'/login'}>Log In/Register</Link></li> </ul> </div> </div> </nav> ) } } }; export default Navbar;
src/Components/CoverPage.js
himanshu8426/himanshu8426.github.io
import React from 'react' import { Header, Image, Container } from 'semantic-ui-react' import photo from '../images/pp.jpg' function CoverPage() { return ( <Container style={{padding: "20px", zIndex: "1"}}> <div > <Header as='h2'> <Image circular src={photo} /> <Header.Content> Himanshu Bhagwani <Header.Subheader>Automation Engineer</Header.Subheader> </Header.Content> </Header> </div> <div> </div> </Container> ) } export default CoverPage
android/rn/src/app.js
skyujilong/native-rn
/** * 入口文件 */ import React from 'react'; import ReduxThunk from 'redux-thunk'; import {createStore,applyMiddleware} from 'redux'; import Router from './router'; import reducerM from './reducerM'; import {Provider} from 'react-redux'; import {View,Text} from 'react-native'; // let store = createStore(reducerM(),applyMiddleware(ReduxThunk)); let store; export default class App extends React.Component { constructor(){ super(); store = createStore(reducerM(),applyMiddleware(ReduxThunk)); } componentWillMount(){ console.log('will mount app.........'); } render(){ //这里可以接收到 默认初始化的props, //这里可以接收到 之后调用dispatch方法,去更改store console.log(this.props); console.log('init store.................'); console.log(store.getState()); return ( <Provider store={store}> <Router/> </Provider> ); } }
saga/P/shopping-cart/src/components/ProductItem.js
imuntil/React
import React from 'react' import PropTypes from 'prop-types' import Product from './Product' function ProductItem({product, onAddToCartClicked}) { const addToCartAction = ( <button onClick={onAddToCartClicked} disabled={product.inventory > 0 ? '' : 'disabled'} > {product.inventory > 0 ? 'Add to cart' : 'sold out'} </button> ) return ( <div style={{marginBottom: 20}}> <Product title={product.title} action={addToCartAction} price={product.price} /> </div> ) } ProductItem.propTypes = { product: PropTypes.shape({ title: PropTypes.string.isRequired, price: PropTypes.number.isRequired, inventory: PropTypes.number.isRequired }).isRequired, onAddToCartClicked: PropTypes.func.isRequired } export default ProductItem
CompositeUi/src/views/composition/Projects.js
kreta-io/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <[email protected]> * (c) Gorka Laucirica <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import {Link} from 'react-router'; import React from 'react'; import {routes} from './../../Routes'; import Advice from './../component/Advice'; import CardExtended from './../component/CardExtended'; import Section from './../component/Section'; import SectionHeader from './../component/SectionHeader'; import Table from './../component/Table'; import Thumbnail from './../component/Thumbnail'; class Projects extends React.Component { static propTypes = { organization: React.PropTypes.object.isRequired, }; noProjects() { return ( <Advice> No projects found, you may want to create the first one so, please click on "<strong>NEW PROJECT</strong>" green button. </Advice> ); } getProjects() { const {organization} = this.props; return organization._projects2TvKxM.edges.map((project, index) => { const currentProject = project.node; return ( <Link key={index} to={routes.project.show(organization.slug, currentProject.slug)} > <CardExtended subtitle={currentProject.slug} thumbnail={<Thumbnail text={currentProject.name} />} title={currentProject.name} /> </Link> ); }); } renderHeader() { return <SectionHeader title="Projects" />; } renderContent() { const {organization} = this.props; if (organization._projects2TvKxM.edges.length === 0) { return this.noProjects(); } return <Table columns={3} items={this.getProjects()} />; } render() { return ( <div className="projects"> <Section header={this.renderHeader()}> {this.renderContent()} </Section> </div> ); } } export default Projects;
src/svg-icons/image/leak-add.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLeakAdd = (props) => ( <SvgIcon {...props}> <path d="M6 3H3v3c1.66 0 3-1.34 3-3zm8 0h-2c0 4.97-4.03 9-9 9v2c6.08 0 11-4.93 11-11zm-4 0H8c0 2.76-2.24 5-5 5v2c3.87 0 7-3.13 7-7zm0 18h2c0-4.97 4.03-9 9-9v-2c-6.07 0-11 4.93-11 11zm8 0h3v-3c-1.66 0-3 1.34-3 3zm-4 0h2c0-2.76 2.24-5 5-5v-2c-3.87 0-7 3.13-7 7z"/> </SvgIcon> ); ImageLeakAdd = pure(ImageLeakAdd); ImageLeakAdd.displayName = 'ImageLeakAdd'; ImageLeakAdd.muiName = 'SvgIcon'; export default ImageLeakAdd;
client/src/containers/video-container.js
kat09kat09/GigRTC
import React, { Component } from 'react'; import StreamButtons from '../components/streamButtons'; import {connect} from 'react-redux'; import AuthenticateFacebook from '../components/auth/authenticatePage' export class VideoContainer extends Component { render() { return ( <div id="videoBig"> <video id="video" autoPlay width="640px" height="480px" poster="../../public/img/guitarist.jpg" /> <div className="video-overlay"></div> <StreamButtons startBroadcast={this.props.startBroadcast} endBroadcast={this.props.endBroadcast} startStream={this.props.startStream} currentPrivelege={this.props.currentPrivelege} watchMode={this.props.watchMode} watchVideo={this.props.watchVideo} /> </div> ); } } function mapStateToProps(state){ return { view_count : state.performance.view_count } } export default connect(mapStateToProps)(VideoContainer)
app/components/LoadingIndicator/index.js
w01fgang/react-boilerplate
import React from 'react'; import styles from './styles.css'; function LoadingIndicator() { return ( <div> <div className={styles['sk-fading-circle']}> <div className={styles.skCircle}></div> <div className={styles['sk-circle2']}></div> <div className={styles['sk-circle3']}></div> <div className={styles['sk-circle4']}></div> <div className={styles['sk-circle5']}></div> <div className={styles['sk-circle6']}></div> <div className={styles['sk-circle7']}></div> <div className={styles['sk-circle8']}></div> <div className={styles['sk-circle9']}></div> <div className={styles['sk-circle10']}></div> <div className={styles['sk-circle11']}></div> <div className={styles['sk-circle12']}></div> </div> </div> ); } export default LoadingIndicator;
app/containers/App.js
demory/marta-menu
import React from 'react' import { connect } from 'react-redux' import NavigationBar from '../components/NavigationBar' import ProjectPane from '../components/ProjectPane' import BudgetPane from '../components/BudgetPane' import MapPane from '../components/MapPane' import WelcomeModal from '../components/WelcomeModal' import { toggleProject, setProjectPercentage, setProjectHighlighted, voteForProject } from '../actions/projects' class App extends React.Component { constructor (props) { super(props) this.state = { hour: '7:00am', am: true, ons: true, hideRoutes: true, hideHeatmap: false } } componentDidMount () { } render () { return ( <div> <WelcomeModal ref='welcomeModal'/> <NavigationBar /> <ProjectPane projects={this.props.projects} sliderChanged={(value) => this.setState({hour: value})} toggleRoutes={(value) => this.setState({hideRoutes: !this.state.hideRoutes})} toggleHeatmap={(value) => this.setState({hideHeatmap: !this.state.hideHeatmap})} hideRoutes={this.state.hideRoutes} hideHeatmap={this.state.hideHeatmap} peakChanged={(value) => this.setState({am: !this.state.am})} countTypeChanged={(value) => this.setState({ons: !this.state.ons})} hour={this.state.hour} am={this.state.am} ons={this.state.ons} voteForProject={(project) => this.props.voteForProject(project)} projectToggled={(project) => this.props.projectToggled(project)} projectPercentageChanged={(project, pct) => this.props.projectPercentageChanged(project, pct)} projectHovered={(project) => this.props.projectHovered(project)} projectUnhovered={(project) => this.props.projectUnhovered(project)} /> <BudgetPane projects={this.props.projects} /> <MapPane projects={this.props.projects} hour={this.state.hour} hideRoutes={this.state.hideRoutes} hideHeatmap={this.state.hideHeatmap} am={this.state.am} ons={this.state.ons} projectToggled={(project) => this.props.projectToggled(project)} /> </div> ) } } const mapStateToProps = (state, ownProps) => { return { projects: state.projects } } const mapDispatchToProps = (dispatch, ownProps) => { return { projectToggled: (project) => { dispatch(toggleProject(project.id)) }, voteForProject: (project) => { dispatch(voteForProject(project.id)) }, projectPercentageChanged: (project, pct) => { dispatch(setProjectPercentage(project.id, pct))}, projectHovered: (project) => dispatch(setProjectHighlighted(project.id, true)), projectUnhovered: (project) => dispatch(setProjectHighlighted(project.id, false)) } } App = connect( mapStateToProps, mapDispatchToProps )(App) export default App
src/svg-icons/action/dns.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDns = (props) => ( <SvgIcon {...props}> <path d="M20 13H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zM7 19c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM20 3H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1zM7 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); ActionDns = pure(ActionDns); ActionDns.displayName = 'ActionDns'; ActionDns.muiName = 'SvgIcon'; export default ActionDns;
pages/events.js
Slava/zbt-website
import React from 'react' import { Link } from 'react-router' import DocumentTitle from 'react-document-title' import { config } from 'config' import { Row, Splash, Split, } from './_sharedComponents' import { prefixLink } from '../utils/urls.js' import CoverImg from '../static/events-cover.jpg'; import DinnerImg from '../static/dinner.jpg'; import FormalImg from '../static/formal.jpg'; import GotbImg from '../static/gotb.jpg'; export default function (props) { return ( <DocumentTitle title={"Events | " + config.siteTitle}> <div> <Splash id="events" imageUrl={CoverImg}></Splash> <div className="contents typography"> <div className="important full-size">If you are a freshman or a sophomore looking to rush ZBT, make sure to look at the <Link to={prefixLink('/rush/')}>rush page</Link> for fall events and activites.</div> <h2>Parties</h2> <p>Everyone needs a break from work, and being MIT students we know well how difficult the work can be. ZBT house is an often host of social events and parties, an opportunity for brothers to hang out with friends, relax and to have a good time.</p> <p>ZBT throws a dozen of big parties open to anyone in MIT community and friends over the duration of the school year. It is a great place to get to know the ZBT community, make new friends or show off your latest dance moves.</p> </div> <Row flipped id="formals" imageUrl={FormalImg}> <h2>Formal Events</h2> <p>Every semester brothers have an opportunity to bring a date to a semi-annual formal event. Events range from a nice special dinner to a boat cruise on the Charles River.</p> <p>Another formal event is Soiree. It is an invite-only evening at the house with fancy desserts, drinks and a karaoke night to follow.</p> </Row> <Row id="dinners" imageUrl={DinnerImg}> <h2>Dinners</h2> <p>We invite our friends to dinners at the house on weekdays. Let us delight you with a great company and a high quality dinner. Research has shown that dinners of ribs and teriyaki salmon improve friendships and strengthen bonds by 50%.</p> </Row> <Row id="gotb" flipped imageUrl={GotbImg}> <h2>Get On The Ball</h2> <p>Get On The Ball is a philantropy event that ZBT brothers organize every year in order to raise donations for Children's Miracle Network.</p> <p>During MIT's Campus Preview Weekend, our campus is filled with prospective students and their parents. Get on the Ball spreads awareness about the work of the Boston Children’s Hospital by asking students and visitors to sign a giant, rainbow-colored ball. Our sponsors pledge to donate a certain amount for every signature we collect or a lump sum to support the event. We show our appreciation for our sponsors by displaying their logos on the physical ball that we roll around for people to sign, and on Twitter, Facebook, and posters.</p> </Row> </div> </DocumentTitle> ); }
lib/components/Spike.js
Jeff-Duke/turing-fridays
import React from 'react'; import firebase from '../firebase'; import moment from 'moment'; const Spike = ({ spike, createSpike, updateCount, toggleForm, user, attending }, key, admin ) => { if (spike) { return ( <section className='SpikeCard' key={key}> <p>Title: <span>{spike.title}</span></p> <p>Description: <span>{spike.description}</span></p> <p> Spike Session Date: <span> {moment(spike.spikeDate).format('MM-DD-YYYY')}</span> </p> <p>Location: <span>{spike.location}</span></p> <p>Spike Hosts: <span>{spike.hosts}</span></p> <p>Attendees: <span>{spike.attendees ? spike.attendees.length : 0}</span></p> <button className='JoinButton' onClick={() => { updateCount(spike); }}> {attending && spike.key === attending.key ? 'Leave' : 'Join'} </button> </section> ) } else { return ( <section className='Modal'> <section id='SpikeForm'> <h1 className='FormTitle'>Submit Spike</h1> <form id='ProposalForm' name='create-spike' onSubmit={(e)=> { createSpike(e) toggleForm() }} > <label htmlFor='SpikeTitle' aria-label='Spike title' title='Spike title'> <input placeholder='Spike Title (required)' name='title' id='SpikeTitle'/> </label> <label htmlFor='SpikeHost' aria-label='Spike host' title='Spike host'> <input placeholder='Spike Host' name='hosts' id='SpikeHost'/> </label> <label htmlFor='SpikeDescription' aria-label='Spike description' title='Spike description'> <textarea placeholder='Description (required)' name='description' id='SpikeDescription' /> </label> <label htmlFor='SpikeNotes' aria-label='Spike notes' title='Spike notes'> <textarea placeholder='Notes for Staff' name='notes' id='SpikeNotes' /> </label> <label className='SpikeDate' htmlFor='date-of-spike'>Date of Spike (required) : <input className='SpikeDatePicker' type='date' name='spikeDate' min="2017-01-01" /> </label> <section className="ButtonContainer"> <button className='SubmitButton' type='submit' > Submit </button> <button className='CancelButton' onClick={(e) => { e.preventDefault(); toggleForm(e) }} > Cancel </button> </section> </form> </section> </section> ) } } export default Spike;
src/app/views/login.js
webcoding/soapee-ui
import React from 'react'; import { Link, Navigation, State } from 'react-router'; import Reflux from 'reflux'; import MediaSigninButtons from 'components/mediaSigninButtons'; import LocalLoginForm from 'components/localLoginForm'; import authStore from 'stores/auth'; export default React.createClass( { mixins: [ Navigation, State, Reflux.connect( authStore, 'auth' ) ], getInitialState() { return { errors: {} }; }, componentWillUpdate() { let path = this.getQuery().nextPath || 'profile'; if ( authStore.isAuthenticated() ) { this.replaceWith( path ); } }, render() { document.title = 'Soapee - Login'; return ( <div id="login"> <div className="jumbotron"> <h1 className="text-center">Log In</h1> <div className="row"> <div className="col-md-4 col-md-offset-4"> <LocalLoginForm /> <div className="strike"><span className="or">OR</span></div> <div className="text-center"> <Link to="forgot" className="btn btn-primary">Forgot Password</Link> </div> <div className="strike"><span className="or">OR</span></div> <MediaSigninButtons /> </div> </div> </div> </div> ); } } );
js/components/donut.js
monetario/web
import React from 'react'; import Datetime from 'react-datetime'; import Formsy from 'formsy-react'; import Moment from 'moment'; const Donut = React.createClass({ getDefaultProps() { return { }; }, componentDidMount() { Morris.Donut({ element: this.props.name, data: this.props.data, colors: this.props.colors }); }, render() { return ( <div id={this.props.name} className="tab-content no-padding"></div> ); } }); export default Donut;
src/components/viewer.js
DictumMortuum/dictum-dev
'use strict'; import React from 'react'; import Doc from './doc'; import Paper from 'material-ui/Paper'; import Type from './type'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar'; import { SearchText } from './text'; import NewDoc from './buttons/newDoc'; import { Doc as Actions } from '../redux/actions'; import PropTypes from 'prop-types'; import { propertyStatus } from './common'; const style = { overflow: 'hidden', whiteSpace: 'nowrap', flex: 4, margin: 3, height: '100%' }; class Viewer extends React.Component { render() { let { docs, term, type, onScroll } = this.props; return ( <div style={style}> <Toolbar> <ToolbarGroup firstChild={true}> <NewDoc /> </ToolbarGroup> <ToolbarGroup> <SearchText hint='Search...' value={term} /> {type && <Type />} </ToolbarGroup> </Toolbar> <Paper onScroll={onScroll} style={{overflowY: 'scroll', height: '90%'}}> {docs.map(d => (<Doc key={d._id} doc={d} />))} </Paper> </div> ); } } Viewer.propTypes = { docs: PropTypes.array, term: PropTypes.string, type: PropTypes.bool, onScroll: PropTypes.func }; const mapStateToProps = state => ({ docs: state.docs, length: state.length, filter: state.filter, search: state.search, type: state.type, config: state.config }); const mapDispatchToProps = { scroll: Actions.scroll }; const mergeProps = createSelector( state => state.docs, state => state.length, state => state.filter, state => state.search, state => state.type, state => state.config, (state, actions) => actions.scroll, (docs, length, filters, search, type, config, scroll) => { let res = search.docs.length === 0 ? docs : search.docs; return { type: propertyStatus(config.documentProperties, 'type'), term: search.term, onScroll: (event) => { if (event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight) { scroll(); } }, docs: res.filter(d => { // lang may be undefined in some documents let langs = d.lang || []; // If there are no filters, there's nothing to filter. if (filters.length === 0) { return true; } else { // Test every filter against the langs of the doc return filters.every(f => langs.indexOf(f) >= 0); } }) .filter(d => { if (type.selected.length === 0) { // If there are no types, there's nothing to filter. return true; } else { // Check that the current doc's type is in the selected ones. let temp; if (typeof d.type === 'string') { temp = [d.type]; } else { // array temp = d.type; } return temp.some(t => type.selected.includes(t)); } }) .slice(0, length) }; } ); export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(Viewer);
app/javascript/mastodon/components/status_list.js
riku6460/chikuwagoddon
import { debounce } from 'lodash'; import React from 'react'; import { FormattedMessage } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from '../containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import LoadGap from './load_gap'; import ScrollableList from './scrollable_list'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, shouldUpdateScroll: PropTypes.func, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, emptyMessage: PropTypes.node, alwaysPrepend: PropTypes.bool, timelineId: PropTypes.string, }; static defaultProps = { trackScroll: true, }; getFeaturedStatusCount = () => { return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0; } getCurrentStatusIndex = (id, featured) => { if (featured) { return this.props.featuredStatusIds.indexOf(id); } else { return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount(); } } handleMoveUp = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) - 1; this._selectChild(elementIndex); } handleMoveDown = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) + 1; this._selectChild(elementIndex); } handleLoadOlder = debounce(() => { this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined); }, 300, { leading: true }) _selectChild (index) { const element = this.node.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, shouldUpdateScroll, onLoadMore, timelineId, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return ( <div className='regeneration-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='regeneration_indicator.label' tagName='strong' defaultMessage='Loading&hellip;' /> <FormattedMessage id='regeneration_indicator.sublabel' defaultMessage='Your home feed is being prepared!' /> </div> </div> </div> ); } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map((statusId, index) => statusId === null ? ( <LoadGap key={'gap:' + statusIds.get(index + 1)} disabled={isLoading} maxId={index > 0 ? statusIds.get(index - 1) : null} onClick={onLoadMore} /> ) : ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} showThread /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} showThread /> )).concat(scrollableContent); } return ( <ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} shouldUpdateScroll={shouldUpdateScroll} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
src/components/HeaderPanel.js
olontsev/react-redux-bootcamp
import React from 'react'; import { Navbar, FormGroup, FormControl, Checkbox, Button, InputGroup, Glyphicon } from 'react-bootstrap'; class HeaderPanel extends React.Component { render() { return ( <Navbar> <Navbar.Header> <Navbar.Brand> ToDo List </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Navbar.Form pullRight> <FormGroup> <Checkbox inline checked>Show Done &nbsp; </Checkbox> {' '} <InputGroup> <FormControl type="text" placeholder="Search" /> <InputGroup.Addon> <Glyphicon glyph="remove" /> </InputGroup.Addon> </InputGroup> </FormGroup> </Navbar.Form> </Navbar.Collapse> </Navbar> ); } } export default HeaderPanel;
app/react-icons/fa/wpforms.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaWpforms extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m14.5 20.3v2.9h-5.6v-2.9h5.6z m0-5.7v2.9h-5.6v-2.9h5.6z m16.9 11.4v2.9h-7.6v-2.8h7.6z m0-5.7v2.9h-15v-2.9h15z m0-5.7v2.9h-15v-2.9h15z m3 19.2v-27.6q0-0.2-0.1-0.4t-0.3-0.1h-0.7l-8.5 5.7-4.7-3.8-4.6 3.8-8.5-5.7h-0.7q-0.2 0-0.3 0.1t-0.1 0.4v27.6q0 0.2 0.1 0.4t0.3 0.1h27.7q0.2 0 0.3-0.1t0.1-0.4z m-19.1-24.7l4.2-3.4h-9.1z m9.6 0l5-3.4h-9.1z m12.4-2.9v27.6q0 1.4-1 2.4t-2.3 0.9h-27.7q-1.4 0-2.3-0.9t-1-2.4v-27.6q0-1.4 1-2.4t2.3-0.9h27.7q1.4 0 2.3 0.9t1 2.4z"/></g> </IconBase> ); } }
client/widget.js
dmichel76/epics.js
import React from 'react' import ReactDOM from 'react-dom' import EPICSCanvas from './epicscanvas.js' import EPICSComponent from './epicscomponent.js' module.exports = class Widget extends EPICSCcomponent { constructor(props) { super(props) // property should be defined like so this.myproperty = (typeof this.props.myproperty == "undefined") ? "value" : this.props.myproperty } render(){ return ( <div > {this.props.pv} = {this.state.pvvalue} </div> ) } } module.exports = class CanvasWidget extends EPICSCanvas { constructor(props) { super(props) // property should be defined like so this.myproperty = (typeof this.props.myproperty == "undefined") ? "value" : this.props.myproperty // width and height must be defined this.width = 100 this.height = 100 } draw(pv) { // initialise the canvas calling the parent draw() method super.draw(pv) // get the Canvas context so we can draw on it after const ctx = this.getCanvasContext() // draw widget here ctx.beginPath() ctx.fillRect() // pv value is given by pv.val if (pv.val == "some value") { // do something specific } } }
src/components/InvalidSub.js
houkah26/reddit-clone
import React from 'react'; const InvalidSub = () => ( <p className="invalid-sub">subreddit not found</p> ); export default InvalidSub;