path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/tex/js/app.js
davidchang/draft-js
/** * Copyright (c) 2013-present, Facebook, Inc. All rights reserved. * * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; import 'babel/polyfill'; import TeXEditorExample from './components/TeXEditorExample'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <TeXEditorExample />, document.getElementById('target') );
src/containers/gameScreen/index.js
jiriKuba/Calculatic
import React, { Component } from 'react'; import GameScreen from '../../components/screens/gameScreen/'; export default class GameScreenContainer extends Component { render() { const { onMainScreen, onGameResultScreen } = this.props; return ( <GameScreen onMainScreen = {onMainScreen} onGameResultScreen = {onGameResultScreen} /> ); } }
src/js/components/Prompt.js
opsdroid/opsdroid-desktop
'use strict'; ////// // Imports import React from 'react'; import ReactDOM from 'react-dom'; export default class Prompt extends React.Component { constructor(props) { super(props); this.state = { input: '', showTooltip: false, } this.checkForEnter = this.checkForEnter.bind(this); this.handleInput = this.handleInput.bind(this); this.handleSend = this.handleSend.bind(this); } render() { return ( <div id="prompt"> <input type="text" ref={(input) => { this.textInput = input; }} id="input" placeholder="say something..." onChange={this.handleInput} onKeyUp={this.checkForEnter} value={this.state.input} /> <input type="submit" id="send" value="Send" onClick={this.handleSend} /> <span id="status-indicator" onClick={this.props.toggleConnectionSettings} className={this.props.connected ? "active" : "inactive"}> <span id="status-indicator-tooltip" className={this.state.showTooltip ? "active" : "inactive"}> {this.props.connected ? "connected" : "disconnected"} </span> </span> </div> ); } componentDidMount() { this.focus(); } focus() { this.textInput.focus(); } handleInput(event) { this.setState({input: event.target.value}); } handleSend() { if (this.props.connected){ this.props.sendUserMessage(this.state.input); this.setState({input: ''}); } else { this.flashTooltip(); } this.focus(); } flashTooltip(){ this.setState({showTooltip: true}); setTimeout(() => { this.setState({showTooltip: false}) }, 1000); } checkForEnter(event) { event.preventDefault(); if (event.keyCode == 13) { this.handleSend(); } } }
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
x303597316/actor-platform
import _ from 'lodash'; import Immutable from 'immutable'; import keymirror from 'keymirror'; import React from 'react'; import { Styles, TextField, FlatButton } from 'material-ui'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import ContactStore from 'stores/ContactStore'; import ContactItem from './ContactItem.react'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); const STEPS = keymirror({ NAME_INPUT: null, CONTACTS_SELECTION: null }); class CreateGroupForm extends React.Component { static displayName = 'CreateGroupForm' static childContextTypes = { muiTheme: React.PropTypes.object }; state = { step: STEPS.NAME_INPUT, selectedUserIds: new Immutable.Set() } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7' } }); } render() { let stepForm; switch (this.state.step) { case STEPS.NAME_INPUT: stepForm = ( <form className="group-name" onSubmit={this.onNameSubmit}> <div className="modal-new__body"> <TextField className="login__form__input" floatingLabelText="Group name" fullWidth onChange={this.onNameChange} value={this.state.name}/> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Add members" secondary={true} type="submit"/> </footer> </form> ); break; case STEPS.CONTACTS_SELECTION: let contactList = _.map(ContactStore.getContacts(), (contact, i) => { return ( <ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/> ); }); stepForm = ( <form className="group-members" onSubmit={this.onMembersSubmit}> <div className="count">{this.state.selectedUserIds.size} Members</div> <div className="modal-new__body"> <ul className="contacts__list"> {contactList} </ul> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Create group" secondary={true} type="submit"/> </footer> </form> ); break; } return stepForm; } onContactToggle = (contact, isSelected) => { if (isSelected) { this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)}); } else { this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)}); } } onNameChange = event => { event.preventDefault(); this.setState({name: event.target.value}); } onNameSubmit = event => { event.preventDefault(); if (this.state.name) { let name = this.state.name.trim(); if (name.length > 0) { this.setState({step: STEPS.CONTACTS_SELECTION}); } } } onMembersSubmit =event => { event.preventDefault(); CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS()); } } export default CreateGroupForm;
src/routes.js
johnnyvf24/hellochess-v2
import React from 'react'; import {Route, IndexRoute} from 'react-router'; import App from './containers/app'; import Login from './components/auth/login'; import Live from './containers/live'; import Profile from './containers/user/profile'; import RequireAuth from './components/auth/require_auth'; import Leaderboard from './containers/user/leaderboard'; import TosPrivacy from './components/terms_of_service_privacy'; import PlayerList from './containers/user/player_list'; export default ( <Route path="/" component={App} > <IndexRoute to="/" component={Login} /> <Route path="/live" component={RequireAuth(Live)} /> <Route path="/profile/:id" component={Profile} /> <Route path="/leaderboard" component={Leaderboard} /> <Route path="/tosandprivacy" component={TosPrivacy} /> <Route path="/players" component={PlayerList} /> </Route> );
src/components/Nav.js
EmilNordling/poesk
import React from 'react' import styled from 'styled-components' import { NavLink as Link } from 'react-router-dom' import { colors } from '../constants' const Nav = styled.nav` display: flex; justify-content: center; ` const NavLink = styled(Link)` margin: 0 12px; font-size: 1.8rem; text-decoration: none; color: ${colors.gray700}; &:hover, &:focus { color: ${colors.gray900}; } &.${props => props.activeClassName} { color: ${colors.gray900}; text-decoration: line-through; } ` export default () => ( <Nav> <NavLink exact to="/" activeClassName="active"> Home </NavLink> <NavLink to="/about" activeClassName="active"> About </NavLink> </Nav> )
lib/factory.js
Kitware/arctic-viewer
/* global XMLHttpRequest window */ import MagicLensImageBuilder from 'paraviewweb/src/Rendering/Image/MagicLensImageBuilder'; import PixelOperatorImageBuilder from 'paraviewweb/src/Rendering/Image/PixelOperatorImageBuilder'; import ChartViewer from 'paraviewweb/src/React/Viewers/ChartViewer'; import GenericViewer from 'paraviewweb/src/React/Viewers/ImageBuilderViewer'; import GeometryViewer from 'paraviewweb/src/React/Viewers/GeometryViewer'; import MultiViewerWidget from 'paraviewweb/src/React/Viewers/MultiLayoutViewer'; import ProbeViewerWidget from 'paraviewweb/src/React/Viewers/Probe3DViewer'; import ViewerSelector from 'paraviewweb/src/React/Widgets/ButtonSelectorWidget'; import contains from 'mout/src/array/contains'; import extractURL from 'mout/src/queryString/parse'; import merge from 'mout/src/object/merge'; import React from 'react'; import ReactDOM from 'react-dom'; import viewerBuilder from './types'; import ArcticListViewer from './viewer'; // React UI map const ReactClassMap = { ArcticListViewer, ChartViewer, GenericViewer, GeometryViewer, MultiViewerWidget, ProbeViewerWidget, ViewerSelector, }; let buildViewerForEnsemble = false; let configOverwrite = {}; // ---------------------------------------------------------------------------- export function getJSON(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); xhr.responseType = 'text'; xhr.onload = function onLoad(e) { if (this.status === 200) { callback(null, JSON.parse(xhr.response)); return; } callback(new Error(e), xhr); }; xhr.onerror = function onError(e) { callback(e, xhr); }; xhr.send(); } // ---------------------------------------------------------------------------- function createImageBuilderCallback(renderers, methodToCall) { return function callback(data, envelope) { let count = renderers.length; while (count) { count -= 1; const renderer = renderers[count]; renderer[methodToCall](data); } }; } // ---------------------------------------------------------------------------- function createQueryDataModelCallback(datasets, args) { return function callback(data, envelope) { let count = datasets.length; const argName = data.name; const argValue = data.value; const datasetToUpdate = []; if (args.indexOf(argName) !== -1) { while (count) { count -= 1; const dataset = datasets[count]; if (dataset.getValue(argName) !== argValue) { dataset.setValue(argName, argValue); datasetToUpdate.push(dataset); } } } setImmediate(() => { while (datasetToUpdate.length) { datasetToUpdate.pop().fetchData(); } }); }; } // ---------------------------------------------------------------------------- export function bindDatasets(bindConfig, renderers) { bindConfig.forEach((binding) => { const datasets = []; const rendererList = []; Object.keys(renderers).forEach((name) => { if (binding.datasets.indexOf(name) !== -1) { rendererList.push(renderers[name].builder || renderers[name].painter); if (renderers[name].builder) { datasets.push(renderers[name].builder.queryDataModel); } } }); const callbackFn = createQueryDataModelCallback( datasets, binding.arguments ); datasets.forEach((queryDataModel) => { queryDataModel.onStateChange(callbackFn); }); // Bind image builder properties if (binding.other) { binding.other.forEach((rendererBinding) => { const rendererCallback = createImageBuilderCallback( rendererList, rendererBinding.setter ); rendererList.forEach((renderer) => renderer[rendererBinding.listener](rendererCallback) ); }); } // Bind image builder models if (binding.bind) { binding.bind.forEach((modelName) => { const bindList = rendererList .map((i) => i[modelName]) .filter((i) => !!i); if (bindList.length) { bindList[0].bind(bindList); } }); } }); } // ---------------------------------------------------------------------------- export function createOperators(operatorConfig, renderers) { operatorConfig.forEach((operator) => { // Create Pixel Operator const pixelOperator = new PixelOperatorImageBuilder( operator.operation, operator.datasets ); pixelOperator.name = operator.name; // Used for pixel operator if any // Register PixelOperator renderers[operator.name] = { builder: pixelOperator, name: operator.name, }; }); // Bind each image builder after all have been created operatorConfig.forEach((operator) => { const pixelOperator = renderers[operator.name].builder; // Generic callback to push data into the PixelOperator function pushDataToPixelOperator(data, envelope) { pixelOperator.updateData(data.builder.name, data); } // Listen to all datasets that PixelOperator care about operator.datasets.forEach((name) => renderers[name].builder.onImageReady(pushDataToPixelOperator) ); }); } // ---------------------------------------------------------------------------- export function createViewer(url, callback) { const pathItems = url.split('/'); const basepath = `${pathItems.slice(0, pathItems.length - 1).join('/')}/`; getJSON('/config.json', (configErr, config_) => { let config = Object.assign({}, config_, configOverwrite); if (configErr) { config = {}; } // Merge config with URL parameters as well config = merge(config, extractURL(window.location.href)); // Update configuration if we build for ensemble if (buildViewerForEnsemble) { config.ensemble = true; } getJSON(url, (error, data) => { const dataType = data.type; let queryDataModel = null; let ready = 0; if (contains(dataType, 'ensemble-dataset')) { const renderers = {}; const expected = data.Ensemble.datasets.length; // Let the factory know to not build everything buildViewerForEnsemble = true; data.Ensemble.datasets.forEach((ds) => { createViewer(basepath + ds.data, (viewer) => { ready += 1; if (viewer.ui === 'ViewerSelector') { renderers[ds.name] = { builder: viewer.list[0].imageBuilder, name: ds.name, queryDataModel: viewer.list[0].queryDataModel, }; viewer.list[0].imageBuilder.name = ds.name; while (viewer.list.length > 1) { viewer.list.pop().destroy(); } } else { renderers[ds.name] = { builder: viewer.imageBuilder, name: ds.name, queryDataModel: viewer.queryDataModel, }; viewer.imageBuilder.name = ds.name; // Used for pixel operator if any } if (!queryDataModel) { queryDataModel = viewer.queryDataModel; } if (ready === expected) { // Apply binding if any bindDatasets(data.Ensemble.binding || [], renderers); // Create pixel operators if any createOperators(data.Ensemble.operators || [], renderers); // Ready for UI deployment callback({ renderers, queryDataModel, ui: 'MultiViewerWidget' }); } }); }); } else if (contains(dataType, 'arctic-viewer-list')) { // Show dataset listing callback({ ui: 'ArcticListViewer', list: data.list, basePath: '/data/', }); } else if (config.MagicLens && !config.ensemble) { viewerBuilder(basepath, data, config, (background) => { if (background.allowMagicLens) { viewerBuilder(basepath, data, config, (viewer) => { const defaultSynchList = ['phi', 'theta', 'n_pos', 'time']; background.imageBuilder.queryDataModel.link( viewer.imageBuilder.queryDataModel, defaultSynchList, true ); viewer.imageBuilder.queryDataModel.link( background.imageBuilder.queryDataModel, defaultSynchList, true ); viewer.imageBuilder = new MagicLensImageBuilder( viewer.imageBuilder, background.imageBuilder ); callback(viewer); }); } else { config.MagicLens = false; callback(background); } }); } else if (viewerBuilder(basepath, data, config, callback)) { // We are good to go } }); }); } // ---------------------------------------------------------------------------- export function createUI(viewer, container, callback) { if (viewer.bgColor && viewer.ui !== 'MultiViewerWidget') { container.style[ viewer.bgColor.indexOf('gradient') !== -1 ? 'background' : 'background-color' ] = viewer.bgColor; } // Make sure we trigger a render when the UI is mounted setImmediate(() => { const renderers = viewer.renderers || {}; Object.keys(renderers).forEach((name) => { if (renderers[name].builder && renderers[name].builder.update) { renderers[name].builder.update(); } }); if (viewer.imageBuilder && viewer.imageBuilder.update) { viewer.imageBuilder.update(); } }); // Unmount any previously mounted React component ReactDOM.unmountComponentAtNode(container); if (viewer.ui === 'ReactComponent') { ReactDOM.render(viewer.component, container, callback); } else { ReactDOM.render( React.createElement(ReactClassMap[viewer.ui], viewer), container, callback ); } } // ---------------------------------------------------------------------------- export function updateConfig(newConf = {}) { configOverwrite = newConf; }
build/libs/Adapter/src/lib/components/C3/ScatterPlot.js
as-me/dashboard
import React from 'react'; import C3ScatterPlot from './ScatterPlotUI'; import '../../session/ScatterPlot.js'; import 'weavecore'; //namesapce if (typeof window === 'undefined') { this.adapter = this.adapter || {}; } else { window.adapter = window.adapter || {}; } if (typeof window === 'undefined') { this.adapter.libs = this.adapter.libs || {}; } else { window.adapter.libs = window.adapter.libs || {}; } if (typeof window === 'undefined') { this.adapter.libs.c3 = this.adapter.libs.c3 || {}; } else { window.adapter.libs.c3 = window.adapter.libs.c3 || {}; } (function () { Object.defineProperty(ScatterPlot, 'NS', { value: 'adapter.libs.c3' }); Object.defineProperty(ScatterPlot, 'CLASS_NAME', { value: 'ScatterPlot' }); function ScatterPlot() { /** * @public * @property sessionable * @readOnly * @type Booloean */ Object.defineProperty(this, 'sessionable', { value: true }); /** * @public * @property ns * @readOnly * @type String */ Object.defineProperty(this, 'ns', { value: 'adapter.libs.c3' }); /** * @public * @property library * @readOnly * @type String */ Object.defineProperty(this, 'library', { value: 'c3' }); /** * @public * @property data * @readOnly * @type String */ Object.defineProperty(this, 'sessionData', { value: WeaveAPI.SessionManager.registerLinkableChild(this, new adapter.session.ScatterPlot()) }); /** * @public * @property hook * @readOnly * @type d3Chart.Scatterplot */ Object.defineProperty(this, 'hook', { value: new adapter.hook.C3Interface() }); } // Prototypes. var p = ScatterPlot.prototype; p.createUI = function (padding, size, interactions) { /** * @public * @property ui * @readOnly * @type ReactElement */ if (!this.ui) { Object.defineProperty(this, 'ui', { value: React.createElement(C3ScatterPlot, { sessionData: this.sessionData, padding: { top: padding.top, bottom: padding.bottom, left: padding.left, right: padding.right }, size: { width: size.width, height: size.height }, height: size.height, onProbe: interactions.onProbe, onSelect: interactions.onSelect, hook: this.hook }) }); } } //TO-DO: Find a way for class part of Modules // Need to save them global data in window object , as we need to create the object at runtime, we need namesapce // where as in module provide by webpack we can't get the constructor name. adapter.libs.c3.ScatterPlot = ScatterPlot; }());
src/containers/utils/Root.prod.js
hannupekka/badgenator
// @flow import React from 'react'; import { Provider } from 'react-redux'; import Routes from 'containers/utils/Routes'; const Root = ({ store, history }: { store: Object, history: Object }): ElementType => { return ( <Provider store={store}> <Routes history={history} /> </Provider> ); }; module.exports = Root;
docs/src/sections/JumbotronSection.js
jesenko/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function JumbotronSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="jumbotron">Jumbotron</Anchor> <small>Jumbotron</small> </h2> <p>A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.</p> <ReactPlayground codeText={Samples.Jumbotron} /> <h3><Anchor id="jumbotron-props">Props</Anchor></h3> <PropTable component="Jumbotron"/> </div> ); }
classic/src/scenes/wbui/SettingsListSection.js
wavebox/waveboxapp
import React from 'react' import { List, Paper } from '@material-ui/core' import shallowCompare from 'react-addons-shallow-compare' import SettingsListContainer from './SettingsListContainer' import SettingsListSectionTitle from './SettingsListSectionTitle' class SettingsListSection extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { ...SettingsListSectionTitle.propTypes } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { classes, title, icon, subtitle, children, ...passProps } = this.props return ( <SettingsListContainer {...passProps}> <SettingsListSectionTitle title={title} subtitle={subtitle} icon={icon} /> <Paper> <List dense> {children} </List> </Paper> </SettingsListContainer> ) } } export default SettingsListSection
src/docs/ComponentPage.js
ThomasBem/ps-react-thomasbem
import React from 'react'; import PropTypes from 'prop-types'; import Example from './Example'; import Props from './Props'; const ComponentPage = ({component}) => { const {name, description, props, examples} = component; return ( <div className="componentpage"> <h2>{name}</h2> <p>{description}</p> <h3>Example{examples.length > 1 && "s"}</h3> { examples.length > 0 ? examples.map( example => <Example key={example.code} example={example} componentName={name} /> ) : "No examples exist." } <h3>Props</h3> { props ? <Props props={props} /> : "This component accepts no props." } </div> ) }; ComponentPage.propTypes = { component: PropTypes.object.isRequired }; export default ComponentPage;
core/index.node.js
pawelgalazka/firestarter
import express from 'express' import React from 'react' import { renderToString, renderToStaticMarkup } from 'react-dom/server' import { match, RouterContext } from 'react-router' import { Provider } from 'react-redux' import routes from '../config/routes' import { createStore } from '../config/store' import webpackConfig from '../config/webpack/common' import IndexPage from '../config/index.html' import { prefetch } from './utils' let bundleFileName = webpackConfig.output.filename const styles = [`${webpackConfig.output.publicPath}bootstrap/css/bootstrap.min.css`] if (process.env.NODE_ENV === 'production') { const manifest = require('../build/manifest.json') bundleFileName = manifest['main.js'] styles.push(`${webpackConfig.output.publicPath}${manifest['main.css']}`) } const scripts = [`${webpackConfig.output.publicPath}${bundleFileName}`] function indexPageSanitizer (content) { return ` <!DOCTYPE html> ${content} ` } function renderView (renderProps, req, res) { const store = createStore() prefetch(renderProps, store.dispatch) .then(() => { const contentHtml = renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ) const indexPageHtml = renderToStaticMarkup( <IndexPage initialState={store.getState()} styles={styles} scripts={scripts} innerHTML={contentHtml} /> ) res.status(200).send(indexPageSanitizer(indexPageHtml)) }) .catch((err) => { console.error(err.stack) }) } function render (req, res, next) { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message) } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps) { renderView(renderProps, req, res) } else { res.status(404).send('Not found') } }) } const app = express() app.use(render) app.listen(7000, () => { console.log('Application is served at http://localhost:7000') })
js/src/dapps/dappreg/ModalUpdate/modalUpdate.js
jesuscript/parity
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import { observer } from 'mobx-react'; import DappsStore from '../dappsStore'; import ModalStore from '../modalStore'; import Button from '../Button'; import Modal from '../Modal'; import styles from '../Modal/modal.css'; const HEADERS = [ 'Error During Update', 'Confirm Application Update', 'Waiting for Signer Confirmation', 'Waiting for Transaction Receipt', 'Update Completed' ]; const STEP_ERROR = 0; const STEP_CONFIRM = 1; const STEP_SIGNER = 2; const STEP_TXRECEIPT = 3; const STEP_DONE = 4; @observer export default class ModalUpdate extends Component { dappsStore = DappsStore.instance(); modalStore = ModalStore.instance(); render () { if (!this.modalStore.showingUpdate) { return null; } return ( <Modal buttons={ this.renderButtons() } error={ this.modalStore.errorUpdate } header={ HEADERS[this.modalStore.stepUpdate] } > { this.renderStep() } </Modal> ); } renderButtons () { switch (this.modalStore.stepUpdate) { case STEP_ERROR: case STEP_DONE: return [ <Button key='close' label='Close' onClick={ this.onClickClose } /> ]; case STEP_CONFIRM: return [ <Button key='cancel' label='No, Cancel' onClick={ this.onClickClose } />, <Button key='delete' label='Yes, Update' warning onClick={ this.onClickYes } /> ]; default: return null; } } renderStep () { switch (this.modalStore.stepUpdate) { case STEP_CONFIRM: return this.renderStepConfirm(); case STEP_SIGNER: return this.renderStepWait('Waiting for transaction confirmation in the Parity secure signer'); case STEP_TXRECEIPT: return this.renderStepWait('Waiting for the transaction receipt from the network'); case STEP_DONE: return this.renderStepCompleted(); default: return null; } } renderStepCompleted () { return ( <div> <div className={ styles.section }> Your application metadata has been updated in the registry. </div> </div> ); } renderStepConfirm () { return ( <div> <div className={ styles.section }> You are about to update the application details in the registry, the details of these updates are given below. Please note that each update will generate a seperate transaction. </div> <div className={ styles.section }> <div className={ styles.heading }> Application identifier </div> <div> { this.dappsStore.wipApp.id } </div> </div> { this.renderChanges() } </div> ); } renderChanges () { return ['content', 'image', 'manifest'] .filter((type) => this.dappsStore.wipApp[`${type}Changed`]) .map((type) => { return ( <div className={ styles.section } key={ `${type}Update` }> <div className={ styles.heading }> Updates to { type } hash </div> <div> <div>{ this.dappsStore.wipApp[`${type}Hash`] || '(removed)' }</div> <div className={ styles.hint }> { this.dappsStore.wipApp[`${type}Url`] || 'current url to be removed from registry' } </div> </div> </div> ); }); } renderStepWait (waitingFor) { return ( <div> <div className={ styles.section }> { waitingFor } </div> </div> ); } onClickClose = () => { this.modalStore.hideUpdate(); } onClickYes = () => { this.modalStore.doUpdate(); } }
src/scenes/dashboard/groupprofile/index.js
PowerlineApp/powerline-rn
//This is the Group Profile Screen. Accessible by viewing tapping any group avatar or title anywhere it appears in the app, including My Groups, Standard Item Container, and Group Search //GH 46 import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import { Content, Container, Item, Input, Title, Button, Header, Body, Left, Right, Label, Icon, List, ListItem, Thumbnail, Text } from 'native-base'; import { View, RefreshControl, Alert } from 'react-native'; import styles from './styles'; const PLColors = require('PLColors'); import { getGroupDetails, inviteAllFollowers, getFollowers, unJoinGroup, getGroupPermissions } from 'PLActions'; class GroupProfile extends Component{ static propTypes = { token: React.PropTypes.string }; // The user will be asked to share the information with group owner upon joining the group //GH59 permissionsLabels = { "permissions_name":"Name", "permissions_address":"Street Address", "permissions_city":"City", "permissions_state":"State", "permissions_country":"Country", "permissions_zip_code":"Zip Code", "permissions_email":"Email", "permissions_phone":"Phone Number", "permissions_responses":"Responses" }; constructor(props){ super(props); this.state = { permissions: [], data: null, refreshing: false, refresh: false }; this.unjoin = this.unjoin.bind(this); this.join = this.join.bind(this); } componentWillMount(){ this._onRefresh(); } loadGroup(){ if(this.props.required_permissions){ this.props.required_permissions.map((value, index) => { this.state.permissions.push(this.permissionsLabels[value]); }); }else{ this.state.permissions = []; } var { token, id } = this.props; console.log('ioddd', id); getGroupDetails(token, id).then(data => { this.setState({ data: data, refreshing: false }) }) .catch(err => { }); //GH59 getGroupPermissions(token, id).then(data => { if(data.required_permissions){ data.required_permissions.map((value, index) => { this.state.permissions.push(this.permissionsLabels[value]); }); this.setState({ refresh: true }); } }).catch(err => { }); } _onRefresh(){ this.setState({ refreshing: true }); this.loadGroup(); } goToGroupMembers(){ Actions.groupmembers(this.state.data); } //This provides a user to invite all of their followers to a particular group. //This will eventually be changed to allow a user to choose 1 or more users to invite to a group instead of all invite(){ Alert.alert( 'Confirm', 'Are you sure you want to invite all of your followers to join this group?', [ { text: 'Cancel', onPress: () => { } }, { text: 'OK', onPress: () => { var { token } = this.props; getFollowers(token, 1, 10).then(data => { var users = []; for (var i = 0; i < data.payload.length; i++){ users.push(data.payload[i].username); } inviteAllFollowers(token, this.state.data.id, users).then(data => { alert("Invites sent!"); }) .catch(err => { alert("Cannot send invites at this time. Try again later."); }); }) .catch(err => { }); } } ], {cancelable: false} ); } unjoin(){ Alert.alert( 'Are you Sure', '', [ { text: 'Cancel', onPress: () => { } }, { text: 'OK', onPress: () => { var { token, id } = this.props; unJoinGroup(token, id).then(data => { this.state.data.joined = false; this.state.data.total_member = this.state.data.total_member - 1; this.setState({ refreshing: false }); }) .catch(err => { }); } } ], {cancelable: false} ); } join(){ var { id } = this.props; } render(){ return ( <Container style={styles.container}> <Header style={styles.header}> <Left> <Button transparent onPress={() => Actions.pop()} style={{width: 50, height: 50 }} > <Icon active name="arrow-back" style={{color: 'white'}}/> </Button> </Left> <Body> <Title>Group Profile</Title> </Body> <Right> <Button transparent onPress={() => this.invite()}> <Label style={{color: 'white'}}>Invite</Label> </Button> </Right> </Header> <Content padder refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } > {this.state.data? <List style={{marginLeft: 17, marginTop: 17}}> <ListItem style={{backgroundColor: 'white', marginLeft: 0, paddingLeft: 17}}> {this.state.data.avatar_file_path? <Thumbnail style={styles.avatar} square source={{uri: this.state.data.avatar_file_path+'&w=50&h=50&auto=compress,format,q=95'}}/>: <View style={styles.avatar}/> } <Body> <Text style={{color: PLColors.main}}>{this.state.data.official_name}</Text> {this.state.data.joined? <Button block style={styles.unjoinBtn} onPress={() => this.unjoin()}> <Label style={{color: 'white'}}>Unjoin</Label> </Button>: <Button block style={styles.joinBtn} onPress={() => this.join()}> <Label style={{color: 'white'}}>Join</Label> </Button> } </Body> </ListItem> {this.state.data.official_description? <ListItem style={styles.listItem}> <Text style={styles.groupDescription}>{this.state.data.official_description}</Text> </ListItem>:null} {this.state.data.joined? <ListItem style={{borderBottomWidth: 0}}> <Body> <Button block style={{backgroundColor: PLColors.main}}> <Label style={{color: 'white'}}>Manage</Label> </Button> </Body> </ListItem>: <ListItem style={{borderBottomWidth: 0, height: 40}}> <Text> </Text> </ListItem>} {this.state.data.acronym? <ListItem style={styles.listItem}> <Body> <Text style={styles.listItemTextField}>Acronym</Text> <Text style={styles.listItemValueField}>{this.state.data.acronym}</Text> </Body> </ListItem>: null} {this.state.data.membership_control? <ListItem style={styles.listItem}> <Body> <Text style={styles.listItemTextField}>Membership</Text> <Text style={styles.listItemValueField}>{this.state.data.membership_control}</Text> </Body> </ListItem>:null} {this.state.data.manager_phone? <ListItem style={styles.listItem}> <Body> <Text style={styles.listItemTextField}>Phone Number</Text> <Text style={styles.listItemValueField}>{this.state.data.manager_phone}</Text> </Body> </ListItem>: null} {this.state.data.official_state || this.state.data.official_city || this.state.data.official_address? <ListItem style={styles.listItem}> <Body> <Text style={styles.listItemTextField}>Location</Text> <Text style={styles.listItemValueField}>{this.state.data.official_address} {this.state.data.official_city},{this.state.data.official_state}</Text> </Body> </ListItem>: null} {this.state.data.total_members? <ListItem style={styles.listItem} onPress={() => this.goToGroupMembers()}> <Body> <Text style={styles.listItemTextField}>Total Members</Text> <Text style={styles.listItemValueField}>{this.state.data.total_members}</Text> </Body> </ListItem>: null} {this.state.permissions.length > 0? <ListItem style={styles.listItem}> <Body> <Text style={styles.listItemTextField}>Permissions</Text> <Text style={styles.listItemValueField}> { this.state.permissions.join(',') } </Text> </Body> </ListItem>: null} </List> : null} </Content> </Container> ) } } const mapStateToProps = state => ({ token: state.user.token }); const mapDispatchToProps = dispatch => ({ openDrawer: () => dispatch(openDrawer()) }); export default connect(mapStateToProps, mapDispatchToProps)(GroupProfile);
src/font-icon.js
joxoo/react-material
import React from 'react'; import PropTypes from 'prop-types'; import { getClassesStatic } from './addons/get-classes'; const FontIcon = (props) => ( <i className={ getClassesStatic('font-icon', props) }> { props.icon.startsWith('0x') ? String.fromCharCode(props.icon) : props.icon } </i> ); FontIcon.propTypes = { background: PropTypes.string, color: PropTypes.string, icon: PropTypes.string }; export default FontIcon;
app/components/Work/WorkSection/index.js
yasserhennawi/yasserhennawi
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'utils/styled-components'; const Wrapper = styled.div` display: flex; flex-direction: column; `; const Title = styled.h4` font-weight: normal; margin-bottom: 5px; `; const WorkSection = ({ title, children, ...props }) => ( <Wrapper {...props}> <Title>{title}</Title> {children} </Wrapper> ); WorkSection.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), title: PropTypes.string, }; export default WorkSection;
lavalab/html/node_modules/react-bootstrap/es/Row.js
LavaLabUSC/usclavalab.org
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'prop-types-extra/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Row = function (_React$Component) { _inherits(Row, _React$Component); function Row() { _classCallCheck(this, Row); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Row.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Row; }(React.Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; export default bsClass('row', Row);
docs/app/Examples/elements/Button/Variations/ButtonSocialExample.js
jcarbo/stardust
import React from 'react' import { Button, Icon } from 'stardust' const ButtonSocialExample = () => ( <div> <Button color='facebook'> <Icon name='facebook' /> Facebook </Button> <Button color='twitter'> <Icon name='twitter' /> Twitter </Button> <Button color='google plus'> <Icon name='google plus' /> Google Plus </Button> <Button color='vk'> <Icon name='vk' /> VK </Button> <Button color='linkedin'> <Icon name='linkedin' /> LinkedIn </Button> <Button color='instagram'> <Icon name='instagram' /> Instagram </Button> <Button color='youtube'> <Icon name='youtube' /> YouTube </Button> </div> ) export default ButtonSocialExample
src/containers/Asians/Registration/Institutions/StatusNotice/AcceptedInstance/index.js
westoncolemanl/tabbr-web
import React from 'react' import withStyles from 'material-ui/styles/withStyles' import Card, { CardHeader, CardContent } from 'material-ui/Card' import * as utils from 'utils' const styles = theme => ({ body: { marginBottom: theme.spacing.unit } }) export default withStyles(styles)(({ registrationInstitution, classes }) => <Card className={classes.body} > <CardHeader title={`${registrationInstitution.name} (${registrationInstitution.country})`} subheader={`${utils.constants.status[registrationInstitution.status]}`} /> <CardContent> {'Your registration is accepted. Should you want to withdraw your registration, you will need to send a request to the organizing committee.'} </CardContent> </Card> )
src/scripts/components/TodoHeader.js
fantasywind/React-Todo
import React from 'react'; import {Link} from 'react-router-component'; import CollapseControl from './CollapseControl.js'; import ToDoCreator from './ToDoCreator.js'; const styles = { wrap: { display: 'flex', height: 60, lineHeight: '60px', borderBottom: '1px solid #aaa' } }; const TodoHeader = React.createClass({ render() { return ( <div style={styles.wrap}> <CollapseControl isCollapsed={this.props.isCollapsed} toggleCollapse={this.props.toggleCollapse} /> <ToDoCreator /> </div> ) } }); module.exports = TodoHeader;
src/prisonBreak/commandProcessor.js
link1900/linkin-games
// @flow import React from 'react'; import Chance from 'chance'; import { includes, first, find, filter, intersection, isNil, tail, isEmpty } from 'lodash'; import './commandLine.css'; import CommandRef from './CommandRef'; import type { PrisonBreakStore } from './PrisonBreakReducer'; import { convertToDirection, flipDirection } from './Location'; import { createWorld, itemsAtLocation, monstersAtLocation } from './World'; import type { Location } from './Location'; import type { Entity } from './Entity'; import type { Item } from './Item'; import { equipmentTypes } from './Item'; import { getPlayerLocation, getPlayer, getPlayerScore } from './Player'; import type { Creature } from './Creature'; const chance = new Chance(); type CommandDef = { keys: Array<string>, action?: Function, hidden?: boolean, adverb?: boolean }; const commandList: Array<CommandDef> = [ { keys: ['look', 'l', 'where', 'ls'], action: look }, { keys: ['north', 'n', 'up'], action: move }, { keys: ['east', 'e', 'right'], action: move }, { keys: ['west', 'w', 'left'], action: move }, { keys: ['south', 's', 'down'], action: move }, { keys: ['move', 'go'], action: moveBy }, { keys: ['clear'], action: clear }, { keys: ['help', '?'], action: help }, { keys: ['quest', 'log', 'journal', 'goal', 'objective', 'load'], action: quest }, { keys: ['save', 'backup'], action: save }, { keys: ['restart', 'reset', 'delete'], action: restart }, { keys: ['yes', 'ok', 'agree', 'nod'], action: yes }, { keys: ['no', 'nope', 'disagree'], action: no }, { keys: ['status', 'me', 'self', 'stats'], action: status }, { keys: ['inventory'], action: inventory }, { keys: ['equipment'], action: equipment }, { keys: ['take', 'grab', 'get', 'pickup', 'collect'], action: take }, { keys: ['list'], adverb: true }, { keys: ['equip', 'wear', 'don'], action: equip }, { keys: ['unequip', 'remove', 'doff'], action: unequip }, { keys: ['open', 'unlock'], action: unlock }, { keys: ['showmap'], action: revealMap, hidden: true }, { keys: ['attack', 'kill', 'damage', 'hurt', 'stab', 'kick', 'slice', 'chop'], action: attack }, { keys: ['use', 'drink', 'consume', 'eat'], action: use } // drop //item discard // quit //game //exit ]; export function processCommand(state: PrisonBreakStore, command: string, allowedCommands?: Array<string>) { const commandWords = command.split(' '); const firstWord = first(commandWords); if (!isAllowedCommand(firstWord, allowedCommands)) { return invalidInput(state, command); } const commandDef = find(commandList, cd => includes(cd.keys, firstWord)); if (!commandDef) { return error(state, command); } if (commandDef.adverb) { const rest = tail(commandWords).join(' '); return processCommand(state, rest); } return commandDef.action(state, command); } export function logViewProcessor(logItem: any) { return logItem; } export function updateLog(state: PrisonBreakStore, command: string, value: any) { return { ...state, currentInput: '', log: state.log.concat([command]).concat([value]), history: state.history.concat([command]), historyPosition: state.history.length + 1 }; } export function updateLogDirect(state: PrisonBreakStore, value: any) { return { ...state, log: state.log.concat([value]) }; } export function clear(state: PrisonBreakStore) { return { ...state, currentInput: '', log: [] }; } export function error(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> Sorry I do not understand {command}. Try entering <CommandRef command="help" /> or <CommandRef command="?" /> to see a list of commands. </span> ); } export function look(state: PrisonBreakStore, command: string) { const playerLocation = getPlayerLocation(state); if (!playerLocation) { return updateLog(state, command, <span>You are located no where</span>); } return updateLog( state, command, <span> You are located at <b>{playerLocation.name}</b>. {playerLocation.description} <br /> Looking around you see:<br /> {possibleDirections(state, playerLocation)} {itemLook(state, playerLocation)} {monsterLook(state, playerLocation)} </span> ); } function itemLook(state: PrisonBreakStore, location: Location) { const items = itemsAtLocation(state, location); if (items.length === 0) { return null; } return ( <span> You can see the following item{items.length === 1 ? '' : 's'}: <ul> {items.map(item => (<li key={item.id}> <CommandRef command={`take ${item.name}`} label={item.name} /> </li>))} </ul> </span> ); } function monsterLook(state: PrisonBreakStore, location: Location) { const monsters = monstersAtLocation(state, location); if (monsters.length === 0) { return null; } return ( <span> You can see the following enemies: <ul> {monsters.map(monster => (<li key={monster.id}> <CommandRef command={`attack ${monster.name}`} label={monster.name} /> </li>))} </ul> </span> ); } function possibleDirections(state, location) { if (location.paths.length === 0) { return null; } return ( <span> You can move in the following direction{location.paths.length === 1 ? '' : 's'}: <ul> {location.paths.map((path) => { if (!path) return null; const newLocation = find(state.world.locations, { id: path.toLocationId }); return ( <li key={path.direction}> <CommandRef command={path.direction} /> to {newLocation.name} </li> ); })} </ul> </span> ); } export function help(state: PrisonBreakStore, command: string) { const commandKeys = commandList.filter(cl => cl.hidden !== true).map(commandDef => first(commandDef.keys)); return updateLog( state, command, <span> To play this game you enter your actions by typing in the command such as <CommandRef command="north" /> to move north or <CommandRef command="look" /> to look around.<br /> Here is the list of valid commands:<br /> <ul> {commandKeys.sort().map((key) => { return ( <li key={key}> <CommandRef command={key} /> </li> ); })} </ul> </span> ); } export function newline(state: PrisonBreakStore) { return updateLogDirect(state, <br />); } export function intro(state: PrisonBreakStore) { return updateLogDirect( state, <span> You wake up in your cell as you have done for the past few weeks, but today something is different. Your cell door is open! This is your one chance to escape this prison. I need to move <CommandRef command="south" /> and get out of this cell. </span> ); } export function move(state: PrisonBreakStore, command: string) { const direction = convertToDirection(command); if (!direction) { return updateLog(state, command, <span>You cannot move in that direction</span>); } const playerLocation = getPlayerLocation(state); const player = getPlayer(state); if (!player || !playerLocation || !playerLocation.paths) { return updateLog( state, command, <span> You cannot move <CommandRef command={direction} />, there is no path that way. </span> ); } const path = playerLocation.paths.find(p => p.direction === direction); if (!path) { return updateLog( state, command, <span> You cannot move <CommandRef command={direction} />, there is no path that way. </span> ); } if (path.locked) { return updateLog( state, command, <span> The door in that direction is locked. I will need a key to <CommandRef command="unlock" /> it. </span> ); } const monsters = monstersAtLocation(state, playerLocation); if (monsters.length > 0) { return updateLog( state, command, <span> {first(monsters).name} blocks our path. I will have to <CommandRef command={`attack ${first(monsters).name}`} label="attack" /> and defeat it first. </span> ); } let updatedState = updateEntity(state, player.id, 'locationId', path.toLocationId); const oldLocation = find(state.world.locations, { id: path.fromLocationId }); const newLocation = find(state.world.locations, { id: path.toLocationId }); updatedState = updateLocation(updatedState, newLocation.id, 'visited', true); updatedState = updateLog( updatedState, command, <span> You moved from <b>{oldLocation.name}</b> into <b>{newLocation.name}</b>.<br /> </span> ); return look(updatedState, 'look'); } export function moveBy(state: PrisonBreakStore, command: string) { const directionParts = command.split(' '); if (directionParts.length === 2) { const direction = directionParts[1]; return move(state, direction); } else { return updateLog(state, command, <span>What direction should I move in?</span>); } } export function quest(state: PrisonBreakStore, command: string) { if (state.world.quest === 'main') { return updateLog( state, command, <span> I need to <CommandRef command="look" /> around for an escape. </span> ); } if (state.world.quest === 'done') { return updateLog(state, command, <span>I am free at last.</span>); } const updatedState = { ...state, world: { ...state.world, quest: 'main' } }; return updateLog( updatedState, command, <span> You wake up in your cell as you have done for the past few weeks, but today something is different. Your cell door is open! This is your one chance to escape this prison. I need to move <CommandRef command="south" /> and get out of this cell. </span> ); } function save(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> This game auto saves all progress. If you would like to start from the beginning use the <CommandRef command="restart" /> command. </span> ); } function restart(state: PrisonBreakStore, command: string) { const updateState = { ...state, prompt: { onYes: resetWorld, onNo: (someState: PrisonBreakStore) => { const otherUpdateState = { ...someState, prompt: null }; return updateLog(otherUpdateState, command, <span>You continue on.</span>); } } }; return updateLog( updateState, command, <span> Are you sure you want to <CommandRef command="restart" /> from the beginning? All saved progress up to this point will be lost. (<CommandRef command="yes" /> /{' '} <CommandRef command="no" />) </span> ); } function resetWorld(state: PrisonBreakStore, command: string) { const updateState = { ...state, prompt: null, world: createWorld() }; return updateLog( updateState, command, <span> Save cleared. You can now <CommandRef command="load" />. </span> ); } function yes(state: PrisonBreakStore, command: string) { if (state.prompt) { return state.prompt.onYes(state, command); } else { return updateLog(state, command, <span>Yes to what?</span>); } } function no(state: PrisonBreakStore, command: string) { if (state.prompt) { return state.prompt.onNo(state, command); } else { return updateLog(state, command, <span>No to what?</span>); } } function invalidInput(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> You must answer either <CommandRef command="yes" /> or <CommandRef command="no" /> </span> ); } function isAllowedCommand(command: string, allowedCommands: ?Array<string>) { if (!allowedCommands) { return true; } const commandWords = command.split(' '); const firstWord = first(commandWords); const allowedCommandList = filter(commandList, commandDef => intersection(commandDef.keys, allowedCommands).length > 0); return !isNil(find(allowedCommandList, commandDef => includes(commandDef.keys, firstWord))); } function status(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } const stats = [ { name: 'HP', value: `${player.currentHP} / ${player.maxHP}` }, { name: 'Strength', value: player.strength }, { name: 'Resistance', value: player.resistance }, { name: 'Speed', value: player.speed }, { name: 'Attack', value: player.attack }, { name: 'Defence', value: player.defence } ]; return updateLog( state, command, <span> My current status is:<br /> {stats.map(stat => (<span key={stat.name}> {stat.name}: {` ${stat.value}`} <br /> </span>))} {playerInventory(state)} {playerEquipment(state)} </span> ); } function inventory(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } return updateLog( state, command, <span> {playerInventory(state)} </span> ); } function equipment(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } return updateLog( state, command, <span> {playerEquipment(state)} </span> ); } function playerInventory(state: PrisonBreakStore) { const playerItems = getPlayerItems(state); if (playerItems.length < 1) { return null; } return ( <p> {"I'm"} currently carrying: <br /> {playerItems.map(itemText)} </p> ); } function itemText(item: Item) { return ( <span key={item.id}> {itemName(item)} - {item.description} <br /> </span> ); } function itemName(item: Item) { const isEquipment = includes(equipmentTypes, item.type); if (isEquipment) { return <CommandRef command={`equip ${item.name}`} label={item.name} />; } else { return item.name; } } function playerEquipment(state: PrisonBreakStore) { const items = getPlayerEquipment(state); if (items.length < 1) { return null; } return ( <p> {"I'm"} currently holding: <br /> {items.map((item) => { return ( <span key={item.id}> {item.name} - {item.description} <br /> </span> ); })} </p> ); } function take(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const location = getPlayerLocation(state); const items = itemsAtLocation(state, location); const foundItem = find(items, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); const player = getPlayer(state); if (!foundItem || !player) { return updateLog( state, command, <span> Cannot find anything called {commandTail} </span> ); } let updateState = updateEntity(state, foundItem.id, 'locationId', null); updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.concat(foundItem.id)); updateState = updateLog( updateState, command, <span> You have taken {foundItem.name} </span> ); if (includes(equipmentTypes, foundItem.type)) { return equip(updateState, `equip ${foundItem.name}`); } return updateState; } export function updateEntity(state: PrisonBreakStore, id: string, field: string, value: any): PrisonBreakStore { const entity = find(state.world.entities, { id }); if (!entity) { return state; } const updatedEntity = { ...entity, [field]: value }; return updateEntityForState(state, updatedEntity); } export function updateLocation(state: PrisonBreakStore, id: string, field: string, value: any): PrisonBreakStore { const location = find(state.world.locations, { id }); if (!location) { return state; } const updateLoc = { ...location, [field]: value }; return updateLocationForState(state, updateLoc); } export function updateLocationForState(state: PrisonBreakStore, location: Location): PrisonBreakStore { return { ...state, world: { ...state.world, locations: state.world.locations.filter(e => e.id !== location.id).concat(location) } }; } export function updateEntityForState(state: PrisonBreakStore, entity: Entity): PrisonBreakStore { return { ...state, world: { ...state.world, entities: state.world.entities.filter(e => e.id !== entity.id).concat(entity) } }; } function equip(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const playerItems = getPlayerItems(state); const player = getPlayer(state); const foundItem = find(playerItems, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot equip {commandTail} as it is not in your inventory. </span> ); } if (!includes(equipmentTypes, foundItem.type)) { return updateLog( state, command, <span> {commandTail} cannot be equipped. </span> ); } let updateState = state; if (foundItem.type === 'weapon') { updateState = updateEntity(updateState, player.id, 'weaponId', foundItem.id); updateState = updateEntity(updateState, player.id, 'attack', player.attack + foundItem.attackChange); } if (foundItem.type === 'shield') { updateState = updateEntity(updateState, player.id, 'shieldId', foundItem.id); updateState = updateEntity(updateState, player.id, 'defence', player.defence + foundItem.defenceChange); } updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.filter(itemId => itemId !== foundItem.id)); return updateLog( updateState, command, <span> You have equipped {foundItem.name} </span> ); } function unequip(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const pe = getPlayerEquipment(state); const player = getPlayer(state); const foundItem = find(pe, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot un-equip {commandTail} as it is not equipped. </span> ); } let updateState = state; if (foundItem.type === 'weapon') { updateState = updateEntity(updateState, player.id, 'weaponId', null); updateState = updateEntity(updateState, player.id, 'attack', player.attack - foundItem.attackChange); } if (foundItem.type === 'shield') { updateState = updateEntity(updateState, player.id, 'shieldId', null); updateState = updateEntity(updateState, player.id, 'defence', player.defence - foundItem.defenceChange); } updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.concat(foundItem.id)); return updateLog( updateState, command, <span> You have un-equipped {foundItem.name} </span> ); } function getPlayerItems(state: PrisonBreakStore): Array<Item> { const player = getPlayer(state); if (!player) { return []; } return player.itemIds.map(itemId => find(state.world.entities, { id: itemId })); } function getPlayerEquipment(state: PrisonBreakStore): Array<Item> { const player = getPlayer(state); if (!player) { return []; } const e = []; const weapon = find(state.world.entities, { id: player.weaponId }); const shield = find(state.world.entities, { id: player.shieldId }); if (weapon) { e.push(weapon); } if (shield) { e.push(shield); } return e; } export function unlock(state: PrisonBreakStore, command: string) { const currentLocation = getPlayerLocation(state); if (!currentLocation) { return updateLog(state, command, <span>What door</span>); } const lockedPaths = currentLocation.paths.filter(p => p.locked); if (lockedPaths === 0) { return updateLog(state, command, <span>There are no locked doors here.</span>); } const connectedLocations = lockedPaths.map(p => find(state.world.locations, { id: p.toLocationId })); let allowedDirection = ''; const updatePaths = currentLocation.paths.map((p) => { if (!p.locked) { return p; } allowedDirection = flipDirection(p.direction); return { ...p, locked: false }; }); let updateState = updateLocation(state, currentLocation.id, 'paths', updatePaths); connectedLocations.forEach((loc) => { const otherPaths = loc.paths.map((poa) => { if (!poa.locked || poa.direction !== allowedDirection) { return poa; } return { ...poa, locked: false }; }); updateState = updateLocation(updateState, loc.id, 'paths', otherPaths); }); return updateLog(updateState, command, <span>You have unlocked all doors.</span>); } export function revealMap(state: PrisonBreakStore, command: string) { let updatedState = state; state.world.locations.forEach((location) => { updatedState = updateLocation(updatedState, location.id, 'visited', true); }); return updateLog(updatedState, command, <span>Map is revealed.</span>); } export function attack(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return null; } const playerLocation = getPlayerLocation(state); const monsters = monstersAtLocation(state, playerLocation); if (isEmpty(monsters)) { return updateLog(state, command, <span>There is nothing you can attack in here.</span>); } const monster = first(monsters); return battle(state, command, player, monster); } export function battle(state: PrisonBreakStore, command: string, creature1: Creature, creature2: Creature) { // fastest creature goes first const fighters = [creature1, creature2].sort((c1, c2) => (c2.speed + (c2.speed / 4)) - (c1.speed + (c1.speed / 4))); const fighter1 = fighters[0]; const fighter2 = fighters[1]; let updateState = updateLog( state, command, <span> {fighter1.name} attacks {fighter2.name} </span> ); // first attack updateState = damage(updateState, fighter1, fighter2); updateState = updateLogDirect( updateState, <span> {fighter1.name} HP: {fighter1.currentHP}/{fighter1.maxHP} vs. {fighter2.name} HP: {fighter2.currentHP}/{fighter2.maxHP} </span> ); // check for win/loss condition if (fighter2.currentHP <= 0) { return finishBattle(updateState, fighter1, fighter2); } // counter attack updateState = damage(updateState, fighter2, fighter1); // check for win/loss condition if (fighter1.currentHP <= 0) { return finishBattle(updateState, fighter2, fighter1); } // final status update return updateLogDirect( updateState, <span> {fighter1.name} HP: {fighter1.currentHP}/{fighter1.maxHP} vs. {fighter2.name} HP: {fighter2.currentHP}/{fighter2.maxHP} </span> ); } export function damage(state: PrisonBreakStore, creature1: Creature, creature2: Creature) { const attackBoost = Math.round(creature1.attack * 0.25); const att = creature1.attack + attackBoost + chance.natural({ min: 0, max: attackBoost }); const damageAmount = att - creature2.defence; creature2.currentHP -= damageAmount; if (creature2.currentHP < 0) { creature2.currentHP = 0; } const updateState = updateEntity(state, creature2.id, 'currentHP', creature2.currentHP); return updateLogDirect( updateState, <span> {creature1.name} attacked {creature2.name} for {damageAmount} damage! </span> ); } export function finishBattle(state: PrisonBreakStore, winner: Creature, loser: Creature) { if (loser.type === 'player') { const updateState = updateLogDirect( state, <span> You have no health left and die! <p style={{ fontSize: '20px' }}>GAME OVER</p> </span> ); return resetWorld(updateState, 'game over'); } winner.score += loser.maxHP; let updateState = updateEntity(state, winner.id, 'score', winner.score); updateState = updateEntity(updateState, loser.id, 'locationId', null); const vicHP = Math.min(winner.maxHP, winner.currentHP + Math.round(winner.maxHP * 0.1)); updateState = updateEntity(updateState, winner.id, 'currentHP', vicHP); updateState = updateLogDirect( updateState, <span> You defeated {loser.name}! </span> ); if (loser.name === 'Warden') { updateState = updateLogDirect( updateState, <span> <p> The Warden lays dying and says with his final words: <br /> You may have won your freedom from this prison, but you shall meet your end in the town beyond... <br /> With that the Warden breaths his last breath. <br /> You leap over his body and run up the flight of stairs finally escaping this hellish place </p> <p style={{ fontSize: '20px' }}> CONGRATULATIONS <br /> YOU ESCAPED PRISON !!! Score: {getPlayerScore(state)} </p> </span> ); return resetWorld(updateState, 'game over'); } return updateState; } export function use(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const playerItems = getPlayerItems(state); const player = getPlayer(state); const foundItem = find(playerItems, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot use {commandTail} as it is not in your inventory. </span> ); } if (includes(equipmentTypes, foundItem.type)) { return equip(state, `equip ${commandTail}`); } if (foundItem.type !== 'consumable') { return updateLog( state, command, <span> You do not know how to use {foundItem.name} </span> ); } let updateState = updateEntity(state, player.id, 'currentHP', player.maxHP); updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.filter(itemId => itemId !== foundItem.id)); return updateLog( updateState, command, <span> You have used {foundItem.name} </span> ); }
app/javascript/mastodon/features/ui/components/onboarding_modal.js
imomix/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Permalink from '../../../components/permalink'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import ComposeForm from '../../compose/components/compose_form'; import Search from '../../compose/components/search'; import NavigationBar from '../../compose/components/navigation_bar'; import ColumnHeader from './column_header'; import Immutable from 'immutable'; const noop = () => { }; const messages = defineMessages({ home_title: { id: 'column.home', defaultMessage: 'Home' }, notifications_title: { id: 'column.notifications', defaultMessage: 'Notifications' }, local_title: { id: 'column.community', defaultMessage: 'Local timeline' }, federated_title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const PageOne = ({ acct, domain }) => ( <div className='onboarding-modal__page onboarding-modal__page-one'> <div style={{ flex: '0 0 auto' }}> <div className='onboarding-modal__page-one__elephant-friend' /> </div> <div> <h1><FormattedMessage id='onboarding.page_one.welcome' defaultMessage='Welcome to Mastodon!' /></h1> <p><FormattedMessage id='onboarding.page_one.federation' defaultMessage='Mastodon is a network of independent servers joining up to make one larger social network. We call these servers instances.' /></p> <p><FormattedMessage id='onboarding.page_one.handle' defaultMessage='You are on {domain}, so your full handle is {handle}' values={{ domain, handle: <strong>{acct}@{domain}</strong> }} /></p> </div> </div> ); PageOne.propTypes = { acct: PropTypes.string.isRequired, domain: PropTypes.string.isRequired, }; const PageTwo = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-two'> <div className='figure non-interactive'> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> <ComposeForm text='Awoo! #introductions' suggestions={Immutable.List()} mentionedDomains={[]} spoiler={false} onChange={noop} onSubmit={noop} onPaste={noop} onPickEmoji={noop} onChangeSpoilerText={noop} onClearSuggestions={noop} onFetchSuggestions={noop} onSuggestionSelected={noop} showSearch /> </div> <p><FormattedMessage id='onboarding.page_two.compose' defaultMessage='Write posts from the compose column. You can upload images, change privacy settings, and add content warnings with the icons below.' /></p> </div> ); PageTwo.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageThree = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-three'> <div className='figure non-interactive'> <Search value='' onChange={noop} onSubmit={noop} onClear={noop} onShow={noop} /> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> </div> <p><FormattedMessage id='onboarding.page_three.search' defaultMessage='Use the search bar to find people and look at hashtags, such as {illustration} and {introductions}. To look for a person who is not on this instance, use their full handle.' values={{ illustration: <Permalink to='/timelines/tag/illustration' href='/tags/illustration'>#illustration</Permalink>, introductions: <Permalink to='/timelines/tag/introductions' href='/tags/introductions'>#introductions</Permalink> }} /></p> <p><FormattedMessage id='onboarding.page_three.profile' defaultMessage='Edit your profile to change your avatar, bio, and display name. There, you will also find other preferences.' /></p> </div> ); PageThree.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageFour = ({ domain, intl }) => ( <div className='onboarding-modal__page onboarding-modal__page-four'> <div className='onboarding-modal__page-four__columns'> <div className='row'> <div> <div className='figure non-interactive'><ColumnHeader icon='home' type={intl.formatMessage(messages.home_title)} /></div> <p><FormattedMessage id='onboarding.page_four.home' defaultMessage='The home timeline shows posts from people you follow.' /></p> </div> <div> <div className='figure non-interactive'><ColumnHeader icon='bell' type={intl.formatMessage(messages.notifications_title)} /></div> <p><FormattedMessage id='onboarding.page_four.notifications' defaultMessage='The notifications column shows when someone interacts with you.' /></p> </div> </div> <div className='row'> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='users' type={intl.formatMessage(messages.local_title)} /></div> </div> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='globe' type={intl.formatMessage(messages.federated_title)} /></div> </div> </div> <p><FormattedMessage id='onboarding.page_five.public_timelines' defaultMessage='The local timeline shows public posts from everyone on {domain}. The federated timeline shows public posts from everyone who people on {domain} follow. These are the Public Timelines, a great way to discover new people.' values={{ domain }} /></p> </div> </div> ); PageFour.propTypes = { domain: PropTypes.string.isRequired, intl: PropTypes.object.isRequired, }; const PageSix = ({ admin, domain }) => { let adminSection = ''; if (admin) { adminSection = ( <p> <FormattedMessage id='onboarding.page_six.admin' defaultMessage="Your instance's admin is {admin}." values={{ admin: <Permalink href={admin.get('url')} to={`/accounts/${admin.get('id')}`}>@{admin.get('acct')}</Permalink> }} /> <br /> <FormattedMessage id='onboarding.page_six.read_guidelines' defaultMessage="Please read {domain}'s {guidelines}!" values={{ domain, guidelines: <a href='/about/more' target='_blank'><FormattedMessage id='onboarding.page_six.guidelines' defaultMessage='community guidelines' /></a> }} /> </p> ); } return ( <div className='onboarding-modal__page onboarding-modal__page-six'> <h1><FormattedMessage id='onboarding.page_six.almost_done' defaultMessage='Almost done...' /></h1> {adminSection} <p><FormattedMessage id='onboarding.page_six.github' defaultMessage='Mastodon is free open-source software. You can report bugs, request features, or contribute to the code on {github}.' values={{ github: <a href='https://github.com/tootsuite/mastodon' target='_blank' rel='noopener'>GitHub</a> }} /></p> <p><FormattedMessage id='onboarding.page_six.apps_available' defaultMessage='There are {apps} available for iOS, Android and other platforms.' values={{ apps: <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' target='_blank' rel='noopener'><FormattedMessage id='onboarding.page_six.various_app' defaultMessage='mobile apps' /></a> }} /></p> <p><em><FormattedMessage id='onboarding.page_six.appetoot' defaultMessage='Bon Appetoot!' /></em></p> </div> ); }; PageSix.propTypes = { admin: ImmutablePropTypes.map, domain: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ me: state.getIn(['accounts', state.getIn(['meta', 'me'])]), admin: state.getIn(['accounts', state.getIn(['meta', 'admin'])]), domain: state.getIn(['meta', 'domain']), }); class OnboardingModal extends React.PureComponent { static propTypes = { onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, me: ImmutablePropTypes.map.isRequired, domain: PropTypes.string.isRequired, admin: ImmutablePropTypes.map, }; state = { currentIndex: 0, }; componentWillMount() { const { me, admin, domain, intl } = this.props; this.pages = [ <PageOne acct={me.get('acct')} domain={domain} />, <PageTwo me={me} />, <PageThree me={me} />, <PageFour domain={domain} intl={intl} />, <PageSix admin={admin} domain={domain} />, ]; }; componentDidMount() { window.addEventListener('keyup', this.handleKeyUp); } componentWillUnmount() { window.addEventListener('keyup', this.handleKeyUp); } handleSkip = (e) => { e.preventDefault(); this.props.onClose(); } handleDot = (e) => { const i = Number(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.setState({ currentIndex: i }); } handlePrev = () => { this.setState(({ currentIndex }) => ({ currentIndex: Math.max(0, currentIndex - 1), })); } handleNext = () => { const { pages } = this; this.setState(({ currentIndex }) => ({ currentIndex: Math.min(currentIndex + 1, pages.length - 1), })); } handleKeyUp = ({ key }) => { switch (key) { case 'ArrowLeft': this.handlePrev(); break; case 'ArrowRight': this.handleNext(); break; } } handleClose = () => { this.props.onClose(); } render () { const { pages } = this; const { currentIndex } = this.state; const hasMore = currentIndex < pages.length - 1; const nextOrDoneBtn = hasMore ? ( <button onClick={this.handleNext} className='onboarding-modal__nav onboarding-modal__next' > <FormattedMessage id='onboarding.next' defaultMessage='Next' /> </button> ) : ( <button onClick={this.handleClose} className='onboarding-modal__nav onboarding-modal__done' > <FormattedMessage id='onboarding.done' defaultMessage='Done' /> </button> ); const styles = pages.map((data, i) => ({ key: `page-${i}`, data, style: { opacity: spring(i === currentIndex ? 1 : 0), }, })); return ( <div className='modal-root__modal onboarding-modal'> <TransitionMotion styles={styles}> {interpolatedStyles => ( <div className='onboarding-modal__pager'> {interpolatedStyles.map(({ key, data, style }, i) => { const className = classNames('onboarding-modal__page__wrapper', { 'onboarding-modal__page__wrapper--active': i === currentIndex, }); return ( <div key={key} style={style} className={className}>{data}</div> ); })} </div> )} </TransitionMotion> <div className='onboarding-modal__paginator'> <div> <button onClick={this.handleSkip} className='onboarding-modal__nav onboarding-modal__skip' > <FormattedMessage id='onboarding.skip' defaultMessage='Skip' /> </button> </div> <div className='onboarding-modal__dots'> {pages.map((_, i) => { const className = classNames('onboarding-modal__dot', { active: i === currentIndex, }); return ( <div key={`dot-${i}`} role='button' tabIndex='0' data-index={i} onClick={this.handleDot} className={className} /> ); })} </div> <div> {nextOrDoneBtn} </div> </div> </div> ); } } export default connect(mapStateToProps)(injectIntl(OnboardingModal));
App/Containers/HomeContainer.js
bretth18/PresidioWallet
'use strict'; /* container binds action creators and inject state/dispatchers as props */ import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Home from '../Components/Home'; import * as HomeActions from '../Actions/homeActions'; class HomeContainer extends Component { render() { return ( <Home {...this.props} /> ); } } function mapStateToProps(state) { return { currentAddress: state.home.currentAddress, currentBTCPrice: state.home.currentBTCPrice, walletObject: state.home.walletObject, currentBalance: state.home.currentBalance, }; } function mapDispatchToProps(dispatch) { return bindActionCreators(HomeActions,dispatch); } export default connect(mapStateToProps,mapDispatchToProps)(HomeContainer);
views/blocks/Button/Button.js
AlSoEdit/team5
import React from 'react'; import './Button.css'; import b from 'b_'; const button = b.lock('button'); export default class Button extends React.Component { render() { const {disabled, text, type, inProgress, onClick} = this.props; return ( <button type={type} disabled={disabled} className={button({inProgress})} onClick={onClick} > {text} </button> ); } }
src/app/routes.js
paulawasylow/e-commerce-react-app
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import HomeContainer from './containers/HomeContainer'; import CategoryContainer from './containers/CategoryContainer'; import NotExist from './components/NotExist'; export default ( <Route path="/" component={App}> <IndexRoute component={HomeContainer} /> <Route path="/:category" component={CategoryContainer} /> <Route path="*" component={NotExist} /> </Route> )
docs/src/app/components/pages/components/RaisedButton/Page.js
skarnecki/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import raisedButtonReadmeText from './README'; import raisedButtonExampleSimpleCode from '!raw!./ExampleSimple'; import RaisedButtonExampleSimple from './ExampleSimple'; import raisedButtonExampleComplexCode from '!raw!./ExampleComplex'; import RaisedButtonExampleComplex from './ExampleComplex'; import raisedButtonExampleIconCode from '!raw!./ExampleIcon'; import RaisedButtonExampleIcon from './ExampleIcon'; import raisedButtonCode from '!raw!material-ui/lib/RaisedButton/RaisedButton'; const descriptions = { simple: '`RaisedButton` with default color, `primary`, `secondary` and and `disabled` props applied.', complex: 'The first example uses an `input` as a child component, ' + 'the next has next has an [SVG Icon](/#/components/svg-icon), with the label positioned after. ' + 'The final example uses a [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.', icon: 'Examples of Raised Buttons using an icon without a label. The first example uses an' + ' [SVG Icon](/#/components/svg-icon), and has the default color. The second example shows' + ' how the icon and background color can be changed. The final example uses a' + ' [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.', }; const RaisedButtonPage = () => ( <div> <Title render={(previousTitle) => `Raised Button - ${previousTitle}`} /> <MarkdownElement text={raisedButtonReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={raisedButtonExampleSimpleCode} > <RaisedButtonExampleSimple /> </CodeExample> <CodeExample title="Complex examples" description={descriptions.complex} code={raisedButtonExampleComplexCode} > <RaisedButtonExampleComplex /> </CodeExample> <CodeExample title="Icon examples" description={descriptions.icon} code={raisedButtonExampleIconCode} > <RaisedButtonExampleIcon /> </CodeExample> <PropTypeDescription code={raisedButtonCode} /> </div> ); export default RaisedButtonPage;
src/routes/register/Register.js
joaquingatica/git-demo
/** * 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 PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Register.css'; class Register extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Register);
assets/javascripts/kitten/components/layer/overlay/stories.js
KissKissBankBank/kitten
import React from 'react' import { Overlay } from './index' import { Button } from 'kitten' import { DocsPage } from 'storybook/docs-page' const TOGGLE_EVENT = 'event:toggle' const CLOSE_EVENT = 'event:close' const OPEN_EVENT = 'event:open' const handleToggleClick = () => window.dispatchEvent(new Event(TOGGLE_EVENT)) const handleCloseClick = () => window.dispatchEvent(new Event(CLOSE_EVENT)) const handleOpenClick = () => window.dispatchEvent(new Event(OPEN_EVENT)) export default { title: 'Layer/Overlay', component: Overlay, parameters: { docs: { page: () => <DocsPage filepath={__filename} importString="Overlay" />, }, }, decorators: [story => <div className="story-Container">{story()}</div>], args: { zIndex: -1, isActive: false, toggleEvent: TOGGLE_EVENT, closeEvent: CLOSE_EVENT, openEvent: OPEN_EVENT, position: 'absolute', }, } export const Default = args => ( <> <Overlay {...args} /> <Button onClick={handleToggleClick}>Toggle Overlay</Button> <br /> <Button onClick={handleCloseClick}>Close Overlay</Button> <br /> <Button onClick={handleOpenClick}>Open Overlay</Button> </> )
src/modules/DesignerShow/index.js
2941972057/flower-react
/** * Created by dllo on 17/8/23. */ import React from 'react' import ReactDOM from 'react-dom' import DesignerShow from './DesignerShow' ReactDOM.render( <DesignerShow />, document.getElementById('app') )
node_modules/react-bootstrap/es/ModalHeader.js
geng890518/editor-ui
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; // TODO: `aria-label` should be `closeLabel`. var propTypes = { /** * The 'aria-label' attribute provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ 'aria-label': PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: PropTypes.func }; var defaultProps = { 'aria-label': 'Close', closeButton: false }; var contextTypes = { $bs_modal: PropTypes.shape({ onHide: PropTypes.func }) }; var ModalHeader = function (_React$Component) { _inherits(ModalHeader, _React$Component); function ModalHeader() { _classCallCheck(this, ModalHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalHeader.prototype.render = function render() { var _props = this.props, label = _props['aria-label'], closeButton = _props.closeButton, onHide = _props.onHide, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'children']); var modal = this.context.$bs_modal; var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement( 'div', _extends({}, elementProps, { className: classNames(className, classes) }), closeButton && React.createElement( 'button', { type: 'button', className: 'close', 'aria-label': label, onClick: createChainedFunction(modal && modal.onHide, onHide) }, React.createElement( 'span', { 'aria-hidden': 'true' }, '\xD7' ) ), children ); }; return ModalHeader; }(React.Component); ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; ModalHeader.contextTypes = contextTypes; export default bsClass('modal-header', ModalHeader);
src/Parser/Hunter/Shared/Modules/Items/TheShadowHuntersVoodooMask.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import ItemHealingDone from 'Main/ItemHealingDone'; /** * The Shadow Hunter's Voodoo Mask * Heal for 20% of your maximum health when you activate Feign Death then heal for an additional 5% of your maximum health every sec afterwards for 10 sec while still Feigning Death. UPDATE PLEASE */ class TheShadowHuntersVoodooMask extends Analyzer { static dependencies = { combatants: Combatants, }; healing = 0; on_initialized() { this.active = this.combatants.selected.hasHead(ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.THE_SHADOW_HUNTERS_VOODOO_MASK_HEAL.id) { this.healing += event.amount; } } item() { return { item: ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK, result: <ItemHealingDone amount={this.healing} />, }; } } export default TheShadowHuntersVoodooMask;
admin/client/App/screens/Item/index.js
giovanniRodighiero/cms
/** * Item View * * This is the item view, it is rendered when users visit a page of a specific * item. This mainly renders the form to edit the item content in. */ import React from 'react'; import { Center, Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { listsByKey } from '../../../utils/lists'; import CreateForm from '../../shared/CreateForm'; import Alert from '../../elemental/Alert'; import EditForm from './components/EditForm'; import EditFormHeader from './components/EditFormHeader'; import RelatedItemsList from './components/RelatedItemsList/RelatedItemsList'; // import FlashMessages from '../../shared/FlashMessages'; import { selectItem, loadItemData, } from './actions'; import { selectList, } from '../List/actions'; var ItemView = React.createClass({ displayName: 'ItemView', contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { createIsOpen: false, }; }, componentDidMount () { // When we directly navigate to an item without coming from another client // side routed page before, we need to select the list before initializing the item // We also need to update when the list id has changed if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) { this.props.dispatch(selectList(this.props.params.listId)); } this.initializeItem(this.props.params.itemId); }, componentWillReceiveProps (nextProps) { // We've opened a new item from the client side routing, so initialize // again with the new item id if (nextProps.params.itemId !== this.props.params.itemId) { this.props.dispatch(selectList(nextProps.params.listId)); this.initializeItem(nextProps.params.itemId); } }, // Initialize an item initializeItem (itemId) { this.props.dispatch(selectItem(itemId)); this.props.dispatch(loadItemData()); }, // Called when a new item is created onCreate (item) { // Hide the create form this.toggleCreateModal(false); // Redirect to newly created item path const list = this.props.currentList; this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`); }, // Open and close the create new item modal toggleCreateModal (visible) { this.setState({ createIsOpen: visible, }); }, // Render this items relationships renderRelationships () { const { relationships } = this.props.currentList; const keys = Object.keys(relationships); if (!keys.length) return; return ( <div className="Relationships"> <Container> <h2>Relationships</h2> {keys.map(key => { const relationship = relationships[key]; const refList = listsByKey[relationship.ref]; const { currentList, params, relationshipData, drag } = this.props; return ( <RelatedItemsList key={relationship.path} list={currentList} refList={refList} relatedItemId={params.itemId} relationship={relationship} items={relationshipData[relationship.path]} dragNewSortOrder={drag.newSortOrder} dispatch={this.props.dispatch} /> ); })} </Container> </div> ); }, // Handle errors handleError (error) { const detail = error.detail; if (detail) { // Item not found if (detail.name === 'CastError' && detail.path === '_id') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> No item matching id "{this.props.routeParams.itemId}".&nbsp; <Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}> Got back to {this.props.routeParams.listId}? </Link> </Alert> </Container> ); } } if (error.message) { // Server down + possibly other errors if (error.message === 'Internal XMLHttpRequest Error') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> We encountered some network problems, please refresh. </Alert> </Container> ); } } return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> An unknown error has ocurred, please refresh. </Alert> </Container> ); }, render () { // If we don't have any data yet, show the loading indicator if (!this.props.ready) { return ( <Center height="50vh" data-screen-id="item"> <Spinner /> </Center> ); } // When we have the data, render the item view with it return ( <div data-screen-id="item"> {(this.props.error) ? this.handleError(this.props.error) : ( <div> <Container> <EditFormHeader list={this.props.currentList} data={this.props.data} toggleCreate={this.toggleCreateModal} /> <CreateForm list={this.props.currentList} isOpen={this.state.createIsOpen} onCancel={() => this.toggleCreateModal(false)} onCreate={(item) => this.onCreate(item)} /> <EditForm list={this.props.currentList} data={this.props.data} dispatch={this.props.dispatch} router={this.context.router} /> </Container> {this.renderRelationships()} </div> )} </div> ); }, }); module.exports = connect((state) => ({ data: state.item.data, loading: state.item.loading, ready: state.item.ready, error: state.item.error, currentList: state.lists.currentList, relationshipData: state.item.relationshipData, drag: state.item.drag, }))(ItemView);
react/features/settings/components/web/audio/SpeakerEntry.js
jitsi/jitsi-meet
// @flow import React, { Component } from 'react'; import logger from '../../../logger'; import AudioSettingsEntry from './AudioSettingsEntry'; import TestButton from './TestButton'; const TEST_SOUND_PATH = 'sounds/ring.wav'; /** * The type of the React {@code Component} props of {@link SpeakerEntry}. */ type Props = { /** * The text label for the entry. */ children: React$Node, /** * Flag controlling the selection state of the entry. */ isSelected: boolean, /** * Flag controlling the selection state of the entry. */ index: number, /** * Flag controlling the selection state of the entry. */ length: number, /** * The deviceId of the speaker. */ deviceId: string, /** * Click handler for the component. */ onClick: Function, listHeaderId: string }; /** * Implements a React {@link Component} which displays an audio * output settings entry. The user can click and play a test sound. * * @augments Component */ export default class SpeakerEntry extends Component<Props> { /** * A React ref to the HTML element containing the {@code audio} instance. */ audioRef: Object; /** * Initializes a new {@code SpeakerEntry} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props: Props) { super(props); this.audioRef = React.createRef(); this._onTestButtonClick = this._onTestButtonClick.bind(this); this._onClick = this._onClick.bind(this); this._onKeyPress = this._onKeyPress.bind(this); } _onClick: () => void; /** * Click handler for the entry. * * @returns {void} */ _onClick() { this.props.onClick(this.props.deviceId); } _onKeyPress: () => void; /** * Key pressed handler for the entry. * * @param {Object} e - The event. * @private * * @returns {void} */ _onKeyPress(e) { if (e.key === ' ') { e.preventDefault(); this.props.onClick(this.props.deviceId); } } _onTestButtonClick: Object => void; /** * Click handler for Test button. * Sets the current audio output id and plays a sound. * * @param {Object} e - The sythetic event. * @returns {void} */ async _onTestButtonClick(e) { e.stopPropagation(); try { await this.audioRef.current.setSinkId(this.props.deviceId); this.audioRef.current.play(); } catch (err) { logger.log('Could not set sink id', err); } } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { children, isSelected, index, deviceId, length, listHeaderId } = this.props; const deviceTextId: string = `choose_speaker${deviceId}`; const labelledby: string = `${listHeaderId} ${deviceTextId} `; return ( <li aria-checked = { isSelected } aria-labelledby = { labelledby } aria-posinset = { index } aria-setsize = { length } className = 'audio-preview-speaker' onClick = { this._onClick } onKeyPress = { this._onKeyPress } role = 'radio' tabIndex = { 0 }> <AudioSettingsEntry isSelected = { isSelected } key = { deviceId } labelId = { deviceTextId }> {children} </AudioSettingsEntry> <TestButton onClick = { this._onTestButtonClick } onKeyPress = { this._onTestButtonClick } /> <audio preload = 'auto' ref = { this.audioRef } src = { TEST_SOUND_PATH } /> </li> ); } }
src/routes/error/index.js
kevinchau321/TReactr
/** * 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 ErrorPage from './ErrorPage'; export default { path: '/error', action({ error }) { return { title: error.name, description: error.message, component: <ErrorPage error={error} />, status: error.status || 500, }; }, };
client/src/components/billing/initial-checkout.js
RajivLinkites/Starter-Skeleton
import React, { Component } from 'react'; import CheckoutForm from './checkout-form'; class InitialCheckout extends Component { render() { return ( <CheckoutForm plan={this.props.params.plan} /> ); } } export default InitialCheckout;
src/components/Button.js
colouroscope/colouroscope
import React from 'react' import classNames from 'classnames' let Button = ({ onClick, children, className }) => ( <button className={classNames('btn', 'btn-secondary', className)} onClick={onClick}>{children}</button> ) export default Button
screens/MoresScreen/index.js
nattatorn-dev/expo-with-realworld
import React from 'react' import { ScrollView, View } from 'react-native' import PropTypes from 'prop-types' import { Colors } from 'constants' import Mores from './MoresContainer' import { Search } from '@components' const MoresScreen = ( { navigation } ) => ( <ScrollView> <Mores navigation={navigation} /> </ScrollView> ) MoresScreen.navigationOptions = ( { navigation } ) => ( { header: ( <View style={{ backgroundColor: Colors.tintColor }}> <Search navigation={navigation} navOnCancel={'mores'} /> </View> ), } ) MoresScreen.propTypes = { navigation: PropTypes.object.isRequired, } export default MoresScreen
src/layouts/index.js
colsondonohue/colsondonohue.github.io
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import Container from '../components/Container'; import Header from '../components/Header'; import Footer from '../components/Footer'; import './index.css'; const propTypes = { children: PropTypes.func }; const TemplateWrapper = ({ children }) => <div> <Helmet title="Colson Donohue" meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' } ]} /> <Header /> <Container> {children()} </Container> <Footer /> </div>; TemplateWrapper.propTypes = propTypes; export default TemplateWrapper;
src/components/header/index.js
jackblackCH/zululo
import React from 'react'; import './Header.css' export default () => <header className="c-header"><a href="/"><img alt="" className="c-header__logo" src='/assets/logo.png' /></a></header>
app/packs/src/components/computed_props/Highlight.js
ComPlat/chemotion_ELN
import React from 'react'; import { ScaleUtils, AbstractSeries } from 'react-vis'; function cropDimension(loc, startLoc, minLoc, maxLoc) { if (loc < startLoc) { return { start: Math.max(loc, minLoc), stop: startLoc }; } return { stop: Math.min(loc, maxLoc), start: startLoc }; } export default class Highlight extends AbstractSeries { constructor(props) { super(props); this.state = { drawing: false, drawArea: { top: 0, right: 0, bottom: 0, left: 0 }, x_start: 0, y_start: 0, xMode: false, yMode: false, xyMode: false }; this.stopDrawing = this.stopDrawing.bind(this); this.onParentMouseDown = this.onParentMouseDown.bind(this); this.getMousePosition = this.getMousePosition.bind(this); } componentDidMount() { document.addEventListener('mouseup', this.stopDrawing); } componentWillUnmount() { document.removeEventListener('mouseup', this.stopDrawing); } getDrawArea(loc) { const { innerWidth, innerHeight } = this.props; const { drawArea, xStart, yStart, xMode, yMode, xyMode } = this.state; const { x, y } = loc; let out = drawArea; if (xMode || xyMode) { const { start, stop } = cropDimension(x, xStart, 0, innerWidth); out = { ...out, left: start, right: stop }; } if (yMode || xyMode) { const { start, stop } = cropDimension(y, yStart, 0, innerHeight); out = { ...out, top: innerHeight - start, bottom: innerHeight - stop }; } return out; } onParentMouseDown(e) { const { innerHeight, innerWidth, onBrushStart } = this.props; const { x, y } = this.getMousePosition(e); const yRect = innerHeight - y; if (x < 0 && y >= 0) { this.setState({ yMode: true, drawing: true, drawArea: { top: yRect, right: innerWidth, bottom: yRect, left: 0 }, yStart: y }); } else if (x >= 0 && y < 0) { this.setState({ xMode: true, drawing: true, drawArea: { top: innerHeight, right: x, bottom: 0, left: x }, xStart: x }); } else if (x >= 0 && y >= 0) { this.setState({ xyMode: true, drawing: true, drawArea: { top: yRect, right: x, bottom: yRect, left: x }, xStart: x, yStart: y }); } if (onBrushStart) { onBrushStart(e); } } // onParentTouchStart(e) { // e.preventDefault(); // this.onParentMouseDown(e); // } stopDrawing() { this.setState({ xMode: false, yMode: false, xyMode: false }); if (!this.state.drawing) { return; } const { onBrushEnd } = this.props; const { drawArea } = this.state; const xScale = ScaleUtils.getAttributeScale(this.props, 'x'); const yScale = ScaleUtils.getAttributeScale(this.props, 'y'); // Clear the draw area this.setState({ drawing: false, drawArea: { top: 0, right: 0, bottom: 0, left: 0 }, xStart: 0, yStart: 0 }); if (Math.abs(drawArea.right - drawArea.left) < 5) { onBrushEnd(null); return; } const domainArea = { bottom: yScale.invert(drawArea.top), right: xScale.invert(drawArea.right), top: yScale.invert(drawArea.bottom), left: xScale.invert(drawArea.left) }; if (onBrushEnd) { onBrushEnd(domainArea); } } getMousePosition(e) { const { marginLeft, marginTop, innerHeight } = this.props; const locX = e.nativeEvent.offsetX - marginLeft; const locY = (innerHeight + marginTop) - e.nativeEvent.offsetY; return { x: locX, y: locY }; } onParentMouseMove(e) { const { drawing } = this.state; if (drawing) { const pos = this.getMousePosition(e); const newDrawArea = this.getDrawArea(pos); this.setState({ drawArea: newDrawArea }); } } render() { const { marginLeft, marginTop, innerWidth, innerHeight, color, opacity } = this.props; const { drawArea: { left, right, top, bottom } } = this.state; return ( <g transform={`translate(${marginLeft}, ${marginTop})`} className="highlight-container" > <rect opacity="0" x={0} y={0} width={innerWidth} height={innerHeight} /> <rect pointerEvents="none" opacity={opacity} fill={color} x={left} y={bottom} width={right - left} height={top - bottom} /> </g> ); } } const defaultProps = { allow: 'x', color: 'rgb(77, 182, 172)', opacity: 0.3 }; Highlight.defaultProps = { ...AbstractSeries, ...defaultProps }; Highlight.displayName = 'ComputedPropsGraphHighlight';
blueprints/smart/files/__root__/containers/__name__.js
availabs/kauffman-atlas
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' type Props = { } export class <%= pascalEntityName %> extends React.Component { props: Props; render() { return ( <div></div> ) } } const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return {} } export default connect( mapStateToProps, mapDispatchToProps )(<%= pascalEntityName %>)
client/components/position-table/PositionTableContainer.js
kanehara/yostock
import React from 'react' import services from '../../services' import { PositionTable } from './PositionTable' export class PositionTableContainer extends React.Component { constructor(props) { super(props) this.state = { positions: services.PositionService.getPositions() } } render() { return ( <PositionTable positions={this.state.positions}/> ) } }
src/svg-icons/toggle/star.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStar = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ToggleStar = pure(ToggleStar); ToggleStar.displayName = 'ToggleStar'; ToggleStar.muiName = 'SvgIcon'; export default ToggleStar;
src/components/chart.js
StephanYu/modern_redux_weather_forecast
import _ from 'lodash'; import React from 'react'; import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines'; function average(data) { return _.round(_.sum(data)/data.length); } export default (props) => { return( <div> <Sparklines height={120} width={180} data={props.data}> <SparklinesLine color={props.color} /> <SparklinesReferenceLine type="avg" /> </Sparklines> <div>{average(props.data)} {props.units}</div> </div> ); }
app/components/news/category.js
sonic182/gnosisapp
import React, { Component } from 'react'; import { View, Text, StyleSheet, Platform, } from 'react-native'; import utils from '../../utils/utils'; const Touchable = utils.Touchable; export default class Category extends Component { render () { const categoryStyle = [styles.category] const categoryTextStyle = [styles.categoryText] const categoryTextSelectedStyle = [styles.categoryTextSelected] const categorySelectedStyle = [styles.categorySelected] return ( <Touchable accessibilityComponentType="button" onPress={this.props.onPress} style={styles.category}> <View style={this.props.selected ? categorySelectedStyle : categoryStyle}> <Text style={this.props.selected ? categoryTextSelectedStyle: categoryTextStyle}>{this.props.name}</Text> </View> </Touchable> ) } } const styles = StyleSheet.create({ category: { backgroundColor: 'blue', height: 40, paddingVertical: 10, paddingHorizontal: 30, }, category: Platform.select({ ios: {}, android: { elevation: 4, backgroundColor: '#ffffff', // borderRadius: 2, paddingHorizontal: 7 }, }), categorySelected: Platform.select({ ios: {}, android: { elevation: 4, backgroundColor: '#ffffff', backgroundColor: '#444', // color: '#ffffff', // borderRadius: 2, paddingHorizontal: 7 }, }), categoryText: Platform.select({ ios: { color: '#444', textAlign: 'center', padding: 8, fontSize: 18, }, android: { textAlign: 'center', color: '#444', padding: 8, fontWeight: '500', }, }), categoryTextSelected: Platform.select({ ios: { color: '#444', textAlign: 'center', padding: 8, fontSize: 18, }, android: { textAlign: 'center', color: 'white', padding: 8, fontWeight: '500', }, }), })
packages/material-ui-icons/src/AssistantPhoto.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z" /></g> , 'AssistantPhoto');
src/components/app.js
AdevaS/weather_redux
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
src/routes/post/index.js
Grusteam/spark-in-me
import React from 'react'; import Layout from '../../components/Layout'; import Post from '../../components/Post'; import request from '../../core/request'; import {sortMetatags} from '../../core/sortMetatags'; export default { path: '/post/:alias', async action(args) { const responseGlobal = await request('getBlogObjects'), responsePosts = await request('getArticleByAlias', {'articleAlias': args.params.alias}, args.params.alias), responseAuthors = await request('getAuthorByAlias', {'authorAlias': 'all-authors', 'getFullArticles': 0}), responseSimilar = await request('getSimilarArticlesByArticleAlias', {'articleAlias': args.params.alias}); if (!responseGlobal || !responsePosts || !responsePosts.response.data || !responseAuthors || !responseSimilar) { return { redirect: '/error' }; } const glogalData = responseGlobal.response.data, curPage = glogalData.globals.pages.home, postContent = responsePosts.response.data[0], pageData = { title: postContent.title, subtitle: postContent.subtitle, bg: postContent.main_picture, footer: { footerText: glogalData.globals.footer_text, soc: glogalData.social }, nav: { menu: glogalData.globals.nav_items, logo: glogalData.globals.site_title }, authors: postContent.author_info, dateP: postContent.published, back: true, post: true, leftNav: { soc: glogalData.social, authors: responseAuthors.response.data, similar: true, similarList: responseSimilar.response.data }, ldjson: JSON.stringify(postContent.ld_json), breadcrumbs: JSON.stringify(postContent.bread_crumbs) }, postContentInfo = { content: postContent.content, tags: postContent.article_tags, alias: postContent.slug, disqusUrl: postContent.disqus_article_url }; return { meta: sortMetatags(postContent.article_meta), title: postContent.title, component: <Layout data={pageData} ><Post content={postContentInfo}/></Layout>, }; }, };
platform/viewer/src/connectedComponents/ViewerLocalFileData.js
OHIF/Viewers
import React, { Component } from 'react'; import { metadata, utils } from '@ohif/core'; import ConnectedViewer from './ConnectedViewer.js'; import PropTypes from 'prop-types'; import { extensionManager } from './../App.js'; import Dropzone from 'react-dropzone'; import filesToStudies from '../lib/filesToStudies'; import './ViewerLocalFileData.css'; import { withTranslation } from 'react-i18next'; const { OHIFStudyMetadata } = metadata; const { studyMetadataManager } = utils; const dropZoneLinkDialog = (onDrop, i18n, dir) => { return ( <Dropzone onDrop={onDrop} noDrag> {({ getRootProps, getInputProps }) => ( <span {...getRootProps()} className="link-dialog"> {dir ? ( <span> {i18n('Load folders')} <input {...getInputProps()} webkitdirectory="true" mozdirectory="true" /> </span> ) : ( <span> {i18n('Load files')} <input {...getInputProps()} /> </span> )} </span> )} </Dropzone> ); }; const linksDialogMessage = (onDrop, i18n) => { return ( <> {i18n('Or click to ')} {dropZoneLinkDialog(onDrop, i18n)} {i18n(' or ')} {dropZoneLinkDialog(onDrop, i18n, true)} {i18n(' from dialog')} </> ); }; class ViewerLocalFileData extends Component { static propTypes = { studies: PropTypes.array, }; state = { studies: null, loading: false, error: null, }; updateStudies = studies => { // Render the viewer when the data is ready studyMetadataManager.purge(); // Map studies to new format, update metadata manager? const updatedStudies = studies.map(study => { const studyMetadata = new OHIFStudyMetadata( study, study.StudyInstanceUID ); const sopClassHandlerModules = extensionManager.modules['sopClassHandlerModule']; study.displaySets = study.displaySets || studyMetadata.createDisplaySets(sopClassHandlerModules); studyMetadata.forEachDisplaySet(displayset => { displayset.localFile = true; }); studyMetadataManager.add(studyMetadata); return study; }); this.setState({ studies: updatedStudies, }); }; render() { const onDrop = async acceptedFiles => { this.setState({ loading: true }); const studies = await filesToStudies(acceptedFiles); const updatedStudies = this.updateStudies(studies); if (!updatedStudies) { return; } this.setState({ studies: updatedStudies, loading: false }); }; if (this.state.error) { return <div>Error: {JSON.stringify(this.state.error)}</div>; } return ( <Dropzone onDrop={onDrop} noClick> {({ getRootProps, getInputProps }) => ( <div {...getRootProps()} style={{ width: '100%', height: '100%' }}> {this.state.studies ? ( <ConnectedViewer studies={this.state.studies} studyInstanceUIDs={ this.state.studies && this.state.studies.map(a => a.StudyInstanceUID) } /> ) : ( <div className={'drag-drop-instructions'}> <div className={'drag-drop-contents'}> {this.state.loading ? ( <h3>{this.props.t('Loading...')}</h3> ) : ( <> <h3> {this.props.t( 'Drag and Drop DICOM files here to load them in the Viewer' )} </h3> <h4>{linksDialogMessage(onDrop, this.props.t)}</h4> </> )} </div> </div> )} </div> )} </Dropzone> ); } } export default withTranslation('Common')(ViewerLocalFileData);
app/javascript/mastodon/features/favourited_statuses/index.js
pinfort/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites'; import Column from '../ui/components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import StatusList from '../../components/status_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { debounce } from 'lodash'; const messages = defineMessages({ heading: { id: 'column.favourites', defaultMessage: 'Favourites' }, }); const mapStateToProps = state => ({ statusIds: state.getIn(['status_lists', 'favourites', 'items']), isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true), hasMore: !!state.getIn(['status_lists', 'favourites', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Favourites extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, isLoading: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFavouritedStatuses()); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('FAVOURITES', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = debounce(() => { this.props.dispatch(expandFavouritedStatuses()); }, 300, { leading: true }) render () { const { intl, shouldUpdateScroll, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite toots yet. When you favourite one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}> <ColumnHeader icon='star' title={intl.formatMessage(messages.heading)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusList trackScroll={!pinned} statusIds={statusIds} scrollKey={`favourited_statuses-${columnId}`} hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} /> </Column> ); } }
packages/icons/src/md/action/Delete.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdDelete(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M12 38c0 2.21 1.79 4 4 4h16c2.21 0 4-1.79 4-4V14H12v24zM38 8h-7l-2-2H19l-2 2h-7v4h28V8z" /> </IconBase> ); } export default MdDelete;
src/components/ProfileInfo/ProfilePhone.js
dialogs/dialog-native-components
/** * Copyright 2017 dialog LLC <[email protected]> * @flow */ import type { Phone } from '@dlghq/dialog-types'; import React from 'react'; import { Text } from 'react-native'; import PhoneNumber from 'awesome-phonenumber'; type Props = { phone: Phone }; function formatPhone(phone: string) { try { return PhoneNumber('+' + phone).getNumber('international'); } catch (e) { console.error(e); return phone; } } function ProfilePhone(props: Props) { return ( <Text> {formatPhone(props.phone.number)} </Text> ); } export default ProfilePhone;
src/Heading.js
itsolutions-dev/react-styled-ui
// @flow import React from 'react'; import Heading1 from './Heading1'; import Heading2 from './Heading2'; import Heading3 from './Heading3'; import Heading4 from './Heading4'; import Heading5 from './Heading5'; import Heading6 from './Heading6'; const headings = [ Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, ]; type HeadingProps = { size: 1 | 2 | 3 | 4 | 5 | 6, }; const Heading = ({ size = 1, ...others }: HeadingProps) => { const Component = headings[size - 1]; return <Component {...others} />; }; export default Heading;
src/main/react/src/main.js
mbrossard/cryptonit-cloud
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' const browserHistory = useRouterHistory(createBrowserHistory)({ basename: '' }) const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) let render = (routerKey = null) => { const routes = require('./routes/index').default(store) ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, document.getElementById('root') ) } render();
src/components/video_detail.js
theoryNine/react-video-browser
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
shared/components/StoryItem.js
AndrewGibson27/react-fetch-boilerplate
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; const StoryItem = ({ path, data: { _id, headline } }) => ( <li> <p>{headline}</p> <NavLink to={`${path}/${_id}`}>Details</NavLink> </li> ); export default StoryItem;
docs/app/Examples/collections/Form/Shorthand/FormExampleFieldLabelElement.js
koenvg/Semantic-UI-React
import React from 'react' import { Checkbox, Form } from 'semantic-ui-react' const FormExampleFieldLabelElement = () => ( <Form> <Form.Field control={Checkbox} label={{ children: 'I agree to the Terms and Conditions' }} /> </Form> ) export default FormExampleFieldLabelElement
src/index.js
dbachrach/react-imageloader
import React from 'react'; const {PropTypes} = React; const {span} = React.DOM; const Status = { PENDING: 'pending', LOADING: 'loading', LOADED: 'loaded', FAILED: 'failed', }; export default class ImageLoader extends React.Component { static propTypes = { wrapper: PropTypes.func, className: PropTypes.string, preloader: PropTypes.func, }; static defaultProps = { wrapper: span, }; constructor(props) { super(props); this.state = {status: props.src ? Status.LOADING : Status.PENDING}; } componentDidMount() { if (this.state.status === Status.LOADING) { this.createLoader(); } } componentWillReceiveProps(nextProps) { if (this.props.src !== nextProps.src) { this.setState({ status: nextProps.src ? Status.LOADING : Status.PENDING, }); } } componentDidUpdate() { if (this.state.status === Status.LOADING && !this.img) { this.createLoader(); } } componentWillUnmount() { this.destroyLoader(); } getClassName() { let className = `imageloader ${this.state.status}`; if (this.props.className) className = `${className} ${this.props.className}`; return className; } createLoader() { this.destroyLoader(); // We can only have one loader at a time. this.img = new Image(); this.img.onload = ::this.handleLoad; this.img.onerror = ::this.handleError; this.img.src = this.props.src; } destroyLoader() { if (this.img) { this.img.onload = null; this.img.onerror = null; this.img = null; } } handleLoad(event) { this.destroyLoader(); this.setState({status: Status.LOADED}); if (this.props.onLoad) this.props.onLoad(event); } handleError(error) { this.destroyLoader(); this.setState({status: Status.FAILED}); if (this.props.onError) this.props.onError(error); } renderImg() { // Reduce props to just those not used by ImageLoader. // The assumption is that any other props are meant for the loaded image. const blacklist = Object.keys(ImageLoader.propTypes).concat('children'); let props = {}; for (let k in this.props) { if (!this.props.hasOwnProperty(k)) continue; if (blacklist.indexOf(k) >= 0) continue; props[k] = this.props[k]; } return <img {...props} />; } render() { let wrapperArgs = [{className: this.getClassName()}]; switch (this.state.status) { case Status.LOADED: wrapperArgs.push(this.renderImg()); break; case Status.FAILED: if (this.props.children) wrapperArgs.push(this.props.children); break; default: if (this.props.preloader) wrapperArgs.push(this.props.preloader()); break; } return this.props.wrapper(...wrapperArgs); } }
src/containers/PlanetsPage.js
tsahnar/swapi_proj
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import WithDataHOC from '../HOC/WithDataHOC' import List from '../components/common/List' import Planet from '../components/Planet' const PlanetsPage = ({ data: planetsData }) => { return ( <div> <h4 className="page-title text-center"> Star Wars Planets: </h4> <List list={ planetsData.results } render={ planet => <Planet key={planet.url} item={ planet } /> } /> </div> ) } PlanetsPage.propTypes = { data: PropTypes.object.isRequired, }; export default WithDataHOC('https://swapi.co/api/planets/')(PlanetsPage)
javascript/AddOn/Message.js
AppStateESS/stories
import React from 'react' import PropTypes from 'prop-types' const Message = (props) => { let icon = '' switch (props.type) { case 'danger': icon = 'fas fa-exclamation-triangle' break case 'success': icon = 'far fa-thumbs-up' break case 'info': icon = 'fas fa-info-circle' break case 'warning': icon = 'far fa-hand-paper' break } let messageType = 'alert alert-dismissible alert-' + props.type let closeButton if (props.onClose !== undefined) { closeButton = ( <button type="button" onClick={props.onClose} className="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> ) } return ( <div className={messageType} role="alert"> {closeButton} <i className={icon}></i>&nbsp; {props.children} </div> ) } Message.propTypes = { type: PropTypes.string, children: PropTypes.oneOfType([PropTypes.string, PropTypes.element,]), onClose: PropTypes.func, } Message.defaultProps = { type: 'info' } export default Message
code/workspaces/web-app/src/components/app/Segment.js
NERC-CEH/datalab
import React from 'react'; import { withStyles } from '@material-ui/core/styles'; const styles = theme => ({ segment: { padding: theme.spacing(1), }, }); const Segment = ({ classes, children }) => ( <div className={classes.segment}> {children} </div> ); export default withStyles(styles)(Segment);
src/svg-icons/notification/network-check.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationNetworkCheck = (props) => ( <SvgIcon {...props}> <path d="M15.9 5c-.17 0-.32.09-.41.23l-.07.15-5.18 11.65c-.16.29-.26.61-.26.96 0 1.11.9 2.01 2.01 2.01.96 0 1.77-.68 1.96-1.59l.01-.03L16.4 5.5c0-.28-.22-.5-.5-.5zM1 9l2 2c2.88-2.88 6.79-4.08 10.53-3.62l1.19-2.68C9.89 3.84 4.74 5.27 1 9zm20 2l2-2c-1.64-1.64-3.55-2.82-5.59-3.57l-.53 2.82c1.5.62 2.9 1.53 4.12 2.75zm-4 4l2-2c-.8-.8-1.7-1.42-2.66-1.89l-.55 2.92c.42.27.83.59 1.21.97zM5 13l2 2c1.13-1.13 2.56-1.79 4.03-2l1.28-2.88c-2.63-.08-5.3.87-7.31 2.88z"/> </SvgIcon> ); NotificationNetworkCheck = pure(NotificationNetworkCheck); NotificationNetworkCheck.displayName = 'NotificationNetworkCheck'; export default NotificationNetworkCheck;
src/viewElements/shared/radioSelection/RadioBlock.js
yasavbrain/yasav
import React from 'react'; import { ListItem, Text } from 'native-base'; import Style from 'yasav/src/styles/Shared' export class RadioBlock extends React.Component { render() { if(this.props.selected){ return ( <ListItem style={Style.radioBlockSelected} onPress={this.props.onPress}> <Text style={Style.radioBlockText}>{this.props.title}</Text> </ListItem> ) }else{ return ( <ListItem style={Style.radioBlockUnselected} onPress={this.props.onPress}> <Text style={Style.radioBlockText}>{this.props.title}</Text> </ListItem> ) } } }
src/DatePicker/DatePickerDialog.js
rscnt/material-ui
import React from 'react'; import EventListener from 'react-event-listener'; import keycode from 'keycode'; import Calendar from './Calendar'; import Dialog from '../Dialog'; import DatePickerInline from './DatePickerInline'; import FlatButton from '../FlatButton'; import {dateTimeFormat} from './dateUtils'; class DatePickerDialog extends React.Component { static propTypes = { DateTimeFormat: React.PropTypes.func, autoOk: React.PropTypes.bool, cancelLabel: React.PropTypes.node, container: React.PropTypes.oneOf(['dialog', 'inline']), disableYearSelection: React.PropTypes.bool, firstDayOfWeek: React.PropTypes.number, initialDate: React.PropTypes.object, locale: React.PropTypes.string, maxDate: React.PropTypes.object, minDate: React.PropTypes.object, mode: React.PropTypes.oneOf(['portrait', 'landscape']), okLabel: React.PropTypes.node, onAccept: React.PropTypes.func, onDismiss: React.PropTypes.func, onShow: React.PropTypes.func, shouldDisableDate: React.PropTypes.func, style: React.PropTypes.object, wordings: React.PropTypes.object, }; static defaultProps = { DateTimeFormat: dateTimeFormat, container: 'dialog', locale: 'en-US', okLabel: 'OK', cancelLabel: 'Cancel', }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; state = { open: false, }; show = () => { if (this.props.onShow && !this.state.open) this.props.onShow(); this.setState({ open: true, }); }; dismiss = () => { if (this.props.onDismiss && this.state.open) this.props.onDismiss(); this.setState({ open: false, }); } handleTouchTapDay = () => { if (this.props.autoOk) { setTimeout(this.handleTouchTapOK, 300); } }; handleTouchTapCancel = () => { this.dismiss(); }; handleRequestClose = () => { this.dismiss(); }; handleTouchTapOK = () => { if (this.props.onAccept && !this.refs.calendar.isSelectedDateDisabled()) { this.props.onAccept(this.refs.calendar.getSelectedDate()); } this.dismiss(); }; handleKeyUp = (event) => { switch (keycode(event)) { case 'enter': this.handleTouchTapOK(); break; } }; render() { const { DateTimeFormat, cancelLabel, container, initialDate, firstDayOfWeek, locale, okLabel, onAccept, // eslint-disable-line no-unused-vars style, // eslint-disable-line no-unused-vars wordings, minDate, maxDate, shouldDisableDate, mode, disableYearSelection, ...other, } = this.props; const {open} = this.state; const { datePicker: { calendarTextColor, }, } = this.context.muiTheme; const styles = { root: { fontSize: 14, color: calendarTextColor, }, dialogContent: { width: mode === 'landscape' ? 480 : 320, }, dialogBodyContent: { padding: 0, }, actions: { marginRight: 8, }, }; const actions = [ <FlatButton key={0} label={wordings ? wordings.cancel : cancelLabel} primary={true} style={styles.actions} onTouchTap={this.handleTouchTapCancel} />, ]; if (!this.props.autoOk) { actions.push( <FlatButton key={1} label={wordings ? wordings.ok : okLabel} primary={true} disabled={this.refs.calendar !== undefined && this.refs.calendar.isSelectedDateDisabled()} style={styles.actions} onTouchTap={this.handleTouchTapOK} /> ); } // will change later when Popover is available. const Container = (container === 'inline' ? DatePickerInline : Dialog); return ( <Container {...other} ref="dialog" style={styles.root} contentStyle={styles.dialogContent} bodyStyle={styles.dialogBodyContent} actions={actions} repositionOnUpdate={false} open={open} onRequestClose={this.handleRequestClose} > {open && <EventListener elementName="window" onKeyUp={this.handleKeyUp} /> } {open && <Calendar DateTimeFormat={DateTimeFormat} firstDayOfWeek={firstDayOfWeek} locale={locale} ref="calendar" onDayTouchTap={this.handleTouchTapDay} initialDate={initialDate} open={true} minDate={minDate} maxDate={maxDate} shouldDisableDate={shouldDisableDate} disableYearSelection={disableYearSelection} mode={mode} /> } </Container> ); } } export default DatePickerDialog;
app/containers/Login/index.js
projectcashmere/web-server
/* * * Login * */ import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import styled from 'styled-components'; import { login } from './actions'; import { selectNextPathName } from './selectors'; import { makeSelectCurrentUser } from '../App/selectors'; import messages from './messages'; import Button from 'components/Button' export class Login extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor (props) { super(props); this.state = { email: '', password: '' } } componentWillUpdate (nextProps) { const { currentUser } = nextProps; const { nextPath } = this.props if (currentUser && window.sessionStorage.accessToken) { return nextPath ? push(nextPath) : push('/'); } } handleLogin = () => { this.props.login(this.state) } setEmail = (e) => { this.setState({ email: e.target.value }) } setPassword = (e) => { this.setState({ password: e.target.value }) } _container () { const { handleLogin, setEmail, setPassword } = this; return ( <Container> <H1> <FormattedMessage {...messages.header} /> </H1> <Input type="text" placeholder="Email" onBlur={setEmail} /> <Input type="password" placeholder="Password" onBlur={setPassword} /> <Button wide onClick={handleLogin}> <FormattedMessage {...messages.login} /> </Button> </Container> ) } render() { return ( <Wrapper> { this._container() } </Wrapper> ); } } const Wrapper = styled.div` height: calc(100vh); display: flex; justify-content: center; align-items: center; background: black; ` const Container = styled.div` display: flex; flex-direction: column; justify-content: space-between; ` const H1 = styled.h1` color: white; margin-bottom: 30px; ` const Input = styled.input` color: white; border-bottom: thin solid white; padding: 10px 3px; margin-bottom: 30px; font-size: 16px; ` const mapStateToProps = createStructuredSelector({ nextPath: selectNextPathName(), currentUser: makeSelectCurrentUser() }); const mapDispatchToProps = (dispatch) => ({ login: (info) => dispatch(login(info)) }) export default connect(mapStateToProps, mapDispatchToProps)(Login);
src/components/Tabbar/index.js
TongChia/react-alp
import React from 'react'; import './style.styl'; export default function Tabbar({ children }) { return ( <div className="tabbar"> {children} </div> ); }
tests/Rules-isInt-spec.js
sdemjanenko/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isInt" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with a number as string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="+42"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail string with digits': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="42 is an answer"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with an int': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a float': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={Math.PI}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should fail with a float in science notation': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="-1e3"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a zero': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); } };
examples/animations/app.js
tylermcginnis/react-router
import React from 'react' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import { render } from 'react-dom' import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' import './app.css' const App = ({ children, location }) => ( <div> <ul> <li><Link to="/page1">Page 1</Link></li> <li><Link to="/page2">Page 2</Link></li> </ul> <ReactCSSTransitionGroup component="div" transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500} > {React.cloneElement(children, { key: location.pathname })} </ReactCSSTransitionGroup> </div> ) const Index = () => ( <div className="Image"> <h1>Index</h1> <p>Animations with React Router are not different than any other animation.</p> </div> ) const Page1 = () => ( <div className="Image"> <h1>Page 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) const Page2 = () => ( <div className="Image"> <h1>Page 2</h1> <p>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="page1" component={Page1} /> <Route path="page2" component={Page2} /> </Route> </Router> ), document.getElementById('example'))
examples/enzyme/CheckboxWithLabel.js
aaron-goshine/jest
// Copyright 2004-present Facebook. All Rights Reserved. import React from 'react'; export default class CheckboxWithLabel extends React.Component { constructor(props) { super(props); this.state = {isChecked: false}; // bind manually because React class components don't auto-bind // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding this.onChange = this.onChange.bind(this); } onChange() { this.setState({isChecked: !this.state.isChecked}); } render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } }
src/client/lib/menuHelper.js
andrerpena/monomock
import VNavItem from '../components/VNavItem'; import _ from 'underscore'; import React from 'react'; class MenuHelper { /** * Creates VNavItems from an Object containing nodes (each property in the nodes object represents a node) * @param nodes * @param onItemClick * @returns {*} */ createVNavItemsFromNodes(nodes, onItemClick) { if (!nodes) { return null; } return Object.keys(nodes).map((n, i) => this.createVNavItemFromNode(nodes[n], i, onItemClick)); } /** * Creates a VNavItem from a JSON node * @param node * @param key * @param onItemClick * @returns {XML} */ createVNavItemFromNode(node, key, onItemClick) { return <VNavItem key={key} node={node} onClick={onItemClick}/> } /** * Filter the given nodes. "nodes" is an object in which each property is a node * @param nodes * @param filterString */ filterNodes(nodes, filterString) { let result = {}; for (let node in nodes) { let filteredNode = this.filterNode(nodes[node], filterString); if (filteredNode) { result[node] = filteredNode; } } return result; } /** * Filters the given node and returns it. * @param node * @param filterString */ filterNode(node, filterString) { if (node.display.match(new RegExp(filterString, 'i'))) { return node; } else if (node.nodes) { let filteredChildren = this.filterNodes(node.nodes, filterString); if (Object.keys(filteredChildren).length) { node.nodes = filteredChildren; return node; } } return null; } } export default new MenuHelper();
src/svg-icons/av/library-books.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLibraryBooks = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"/> </SvgIcon> ); AvLibraryBooks = pure(AvLibraryBooks); AvLibraryBooks.displayName = 'AvLibraryBooks'; AvLibraryBooks.muiName = 'SvgIcon'; export default AvLibraryBooks;
packages/wix-style-react/src/EmptyState/test/EmptyState.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { visualize, snap, story } from 'storybook-snapper'; import EmptyState from '../EmptyState'; import ImagePlaceholder from '../../../stories/utils/ImagePlaceholder'; import { RTLWrapper } from '../../../stories/utils/RTLWrapper'; const commonProps = { title: "You don't have any items yet", subtitle: 'Create your product item in an easy & fast way to display it on your site', image: <ImagePlaceholder />, theme: 'page', }; const children = 'Consectetur tenetur enim impedit facilis assumenda Illum laborum delectus'; const tests = [ { describe: 'theme', its: [ { it: 'page', props: { theme: 'page', }, }, { it: 'page-no-border', props: { theme: 'page-no-border', }, }, { it: 'section', props: { theme: 'section', }, }, ], }, { describe: 'sanity', its: [ { it: 'no Title', props: { title: '', }, }, { it: 'no Subtitle', props: { subtitle: '', }, }, { it: 'no image', props: { image: '', }, }, ], }, { describe: 'alignment', its: [ { it: 'start', props: { align: 'start', }, }, { it: 'center', props: { align: 'center', }, }, { it: 'end', props: { align: 'end', }, }, ], }, { describe: 'with children', its: [ { it: 'start', props: { align: 'start', children, }, }, { it: 'center', props: { align: 'center', children, }, }, { it: 'end', props: { align: 'end', children, }, }, ], }, ]; const rtlTests = [ { describe: 'rtl', its: [ { it: 'start', props: { align: 'start', children, }, }, { it: 'center', props: { align: 'center', children, }, }, { it: 'end', props: { align: 'end', children, }, }, ], }, ]; export const runTests = ( { themeName, testWithTheme } = { testWithTheme: i => i }, ) => { visualize(`${themeName ? `${themeName}|` : ''}EmptyState`, () => { tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { story(describe, () => { snap(it, testWithTheme(<EmptyState {...commonProps} {...props} />)); }); }); }); rtlTests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { story(describe, () => { snap( it, testWithTheme( <RTLWrapper rtl> <EmptyState {...commonProps} {...props} /> </RTLWrapper>, ), ); }); }); }); }); };
site/components/PageBody.js
colbyr/react-dnd
import React from 'react'; import './PageBody.less'; export default class PageBody { static propTypes = { hasSidebar: React.PropTypes.bool }; render() { var {hasSidebar, html, ...props} = this.props; return ( <div className={`PageBody ${hasSidebar ? 'PageBody--hasSidebar' : ''}`}> <div className="PageBody-container"> {this.props.children} </div> </div> ); } }
www/src/@docpocalypse/gatsby-theme/components/SideNavigation.js
jquense/react-formal
import React from 'react'; import sortBy from 'lodash/sortBy'; import groupBy from 'lodash/groupBy'; import SideNavigation, { usePageData, } from '@docpocalypse/gatsby-theme/src/components/SideNavigation'; function AppSideNavigation(props) { const { api } = usePageData(); const groupedByMembers = groupBy( api, (doc) => doc.tags.find((t) => t.name === 'memberof')?.value || 'none', ); return ( <SideNavigation.Panel {...props}> <nav> <ul> <SideNavigation.Item> <SideNavigation.Link to="/getting-started"> Getting Started </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Link to="/controllables"> Controlled Components </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Link to="/migration-v2"> Migrating to v2 </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Header>API</SideNavigation.Header> <ul className="mb-4"> {sortBy(api, 'title') .filter((n) => !n.tags.find((t) => t.name === 'memberof')) .map((page) => ( <SideNavigation.Item key={page.title}> <SideNavigation.Link to={page.path}> {page.title} {groupedByMembers[page.title] && ( <ul> {sortBy(groupedByMembers[page.title], 'title').map( (sub) => ( <SideNavigation.Item key={sub.title}> <SideNavigation.Link to={sub.path}> {sub.title} </SideNavigation.Link> </SideNavigation.Item> ), )} </ul> )} </SideNavigation.Link> </SideNavigation.Item> ))} </ul> </SideNavigation.Item> </ul> </nav> </SideNavigation.Panel> ); } export default AppSideNavigation;
frontend/src/components/dialog/sysadmin-dialog/sysadmin-delete-member-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { gettext } from '../../../utils/constants'; import { seafileAPI } from '../../../utils/seafile-api'; import { Utils } from '../../../utils/utils'; import toaster from '../../toast'; const propTypes = { member: PropTypes.object.isRequired, groupID: PropTypes.string.isRequired, toggle: PropTypes.func.isRequired, onMemberChanged: PropTypes.func.isRequired }; class DeleteMemberDialog extends React.Component { constructor(props) { super(props); } deleteMember = () => { const userEmail = this.props.member.email; seafileAPI.sysAdminDeleteGroupMember(this.props.groupID, userEmail).then((res) => { if (res.data.success) { this.props.onMemberChanged(); this.props.toggle(); } }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } render() { let tipMessage = gettext('Are you sure you want to delete {placeholder} ?'); tipMessage = tipMessage.replace('{placeholder}', '<span class="op-target">' + Utils.HTMLescape(this.props.member.name) + '</span>'); return ( <Modal isOpen={true} toggle={this.props.toggle}> <ModalHeader toggle={this.props.toggle}>{gettext('Delete Member')}</ModalHeader> <ModalBody> <div dangerouslySetInnerHTML={{__html: tipMessage}}></div> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.deleteMember}>{gettext('Delete')}</Button> <Button color="secondary" onClick={this.props.toggle}>{gettext('Cancel')}</Button> </ModalFooter> </Modal> ); } } DeleteMemberDialog.propTypes = propTypes; export default DeleteMemberDialog;
node_modules/react-router/es/RouterContext.js
nockgish/gish
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import invariant from 'invariant'; import React from 'react'; import getRouteParams from './getRouteParams'; import { ContextProvider } from './ContextUtils'; import { isReactChildren } from './RouteUtils'; var _React$PropTypes = React.PropTypes, array = _React$PropTypes.array, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = React.createClass({ displayName: 'RouterContext', mixins: [ContextProvider('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
src/entypo/ThumbsDown.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--ThumbsDown'; let EntypoThumbsDown = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M6.352,12.638c0.133,0.356-3.539,3.634-1.397,6.291c0.501,0.621,2.201-2.975,4.615-4.602c1.331-0.899,4.43-2.811,4.43-3.868V3.617C14,2.346,9.086,1,5.352,1C3.983,1,2,9.576,2,10.939C2,12.306,6.221,12.282,6.352,12.638z M15,12.543c0.658,0,3-0.4,3-3.123V4.572c0-2.721-2.342-3.021-3-3.021c-0.657,0,1,0.572,1,2.26v6.373C16,11.952,14.343,12.543,15,12.543z"/> </EntypoIcon> ); export default EntypoThumbsDown;
js/jqwidgets/demos/react/app/grid/nestedgrids/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { componentDidMount() { this.refs.myGrid.showrowdetails(1); } render() { let employeesSource = { datafields: [ { name: 'FirstName' }, { name: 'LastName' }, { name: 'Title' }, { name: 'Address' }, { name: 'City' } ], root: 'Employees', record: 'Employee', id: 'EmployeeID', datatype: 'xml', async: false, url: '../sampledata/employees.xml' }; let employeesAdapter = new $.jqx.dataAdapter(employeesSource, { autoBind: true }); let ordersSource = { datafields: [ { name: 'EmployeeID', type: 'string' }, { name: 'ShipName', type: 'string' }, { name: 'ShipAddress', type: 'string' }, { name: 'ShipCity', type: 'string' }, { name: 'ShipCountry', type: 'string' }, { name: 'ShippedDate', type: 'date' } ], root: 'Orders', record: 'Order', datatype: 'xml', url: '../sampledata/orderdetails.xml', async: false }; let ordersDataAdapter = new $.jqx.dataAdapter(ordersSource, { autoBind: true }); let orders = ordersDataAdapter.records; let nestedGrids = new Array(); let rowdetailstemplate = { rowdetails: '<div id="grid" style="margin: 10px;"></div>', rowdetailsheight: 220, rowdetailshidden: true }; let initrowdetails = (index, parentElement, gridElement, record) => { let id = record.uid.toString(); let grid = $($(parentElement).children()[0]); nestedGrids[index] = grid; let filtergroup = new $.jqx.filter(); let filter_or_operator = 1; let filtervalue = id; let filtercondition = 'equal'; let filter = filtergroup.createfilter('stringfilter', filtervalue, filtercondition); // fill the orders depending on the id. let ordersbyid = []; for (let m = 0; m < orders.length; m++) { let result = filter.evaluate(orders[m]['EmployeeID']); if (result) ordersbyid.push(orders[m]); } let orderssource = { datafields: [ { name: 'EmployeeID', type: 'string' }, { name: 'ShipName', type: 'string' }, { name: 'ShipAddress', type: 'string' }, { name: 'ShipCity', type: 'string' }, { name: 'ShipCountry', type: 'string' }, { name: 'ShippedDate', type: 'date' } ], id: 'OrderID', localdata: ordersbyid } let nestedGridAdapter = new $.jqx.dataAdapter(orderssource); if (grid != null) { grid.jqxGrid({ source: nestedGridAdapter, width: 780, height: 200, columns: [ { text: 'Ship Name', datafield: 'ShipName', width: 200 }, { text: 'Ship Address', datafield: 'ShipAddress', width: 200 }, { text: 'Ship City', datafield: 'ShipCity', width: 150 }, { text: 'Ship Country', datafield: 'ShipCountry', width: 150 }, { text: 'Shipped Date', datafield: 'ShippedDate', width: 200 } ] }); } } let photosRenderer = (row, column, value) => { let records = employeesAdapter.records; let name = records[row].FirstName; let imgurl = '../images/' + name.toLowerCase() + '.png'; let img = '<div style="background: white;"><img style="margin:2px; margin-left: 10px;" width="32" height="32" src="' + imgurl + '"></div>'; return img; } let renderer = (row, column, value) => { return '<span style="margin-left: 4px; margin-top: 9px; float: left;">' + value + '</span>'; } let columns = [ { text: 'Photo', width: 50, cellsrenderer: photosRenderer }, { text: 'First Name', datafield: 'FirstName', width: 100, cellsrenderer: renderer }, { text: 'Last Name', datafield: 'LastName', width: 100, cellsrenderer: renderer }, { text: 'Title', datafield: 'Title', width: 180, cellsrenderer: renderer }, { text: 'Address', datafield: 'Address', width: 300, cellsrenderer: renderer }, { text: 'City', datafield: 'City', width: 170, cellsrenderer: renderer } ]; return ( <JqxGrid ref='myGrid' width={850} height={350} source={employeesAdapter} rowdetails={true} rowsheight={35} initrowdetails={initrowdetails} rowdetailstemplate={rowdetailstemplate} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/containers/MainPage/index.js
crp2002/e-commerce-site
/* * MainPage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import NavBar from './NavBar'; import ShirtsContainer from './ShirtsContainer'; import Bar from './Bar'; export default class MainPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { shirtCategory: 'all', sleeveType: 'all', }; } render() { return ( <div> <NavBar /> <Bar /> <ShirtsContainer /> </div> ); } }
src/LinkHandler.js
taskworld/legendary-pancake
import { isPathnameStartingWithBasename, stripBasenameFromPathname } from './PathUtils' import PropTypes from 'prop-types' import React from 'react' // # LinkHandler {#LinkHandler} // // A `<div>` tag that handles link clicks. // export class LinkHandler extends React.Component { static contextTypes = { legendaryPancake: PropTypes.object } static propTypes = { children: PropTypes.node } render () { return <div onClick={this.onClick}>{this.props.children}</div> } onClick = (e) => { if (!e.isDefaultPrevented()) { for (let element = e.target; element; element = element.parentNode) { if (element.nodeType === 1 && element.nodeName === 'A') { this.handleLinkElement(e, element) break } } } } handleLinkElement (e, a) { if (a.protocol !== window.location.protocol) return if (a.host !== window.location.host) return if (!this.context.legendaryPancake) return if (!isPathnameStartingWithBasename(a.pathname)) return const pathname = stripBasenameFromPathname(a.pathname) if (!this.context.legendaryPancake.pathnameExists(pathname)) return this.handleLink(e, pathname) } handleLink (e, pathname) { if (e.metaKey) return if (e.shiftKey) return if (e.altKey) return if (e.ctrlKey) return if (e.button !== 0) return this.context.legendaryPancake.go(pathname) e.preventDefault() } } export default LinkHandler
src/svg-icons/action/shop-two.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShopTwo = (props) => ( <SvgIcon {...props}> <path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9zm15-4V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm0 12V8l5.5 3-5.5 4z"/> </SvgIcon> ); ActionShopTwo = pure(ActionShopTwo); ActionShopTwo.displayName = 'ActionShopTwo'; ActionShopTwo.muiName = 'SvgIcon'; export default ActionShopTwo;
pages/less.js
adjohnson916/site-gatsby
import React from 'react' import './example.less' export default class Less extends React.Component { render () { return ( <div> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
src/common/components/Appbar/jsPsychInitEditor/index.js
jspsych/jsPsych-Redux-GUI
import React from 'react'; import Dialog from 'material-ui/Dialog'; import Subheader from 'material-ui/Subheader'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import TextField from 'material-ui/TextField'; import { grey800 as normalColor, cyan500 as iconHighlightColor, green500 as checkColor, blue500 as titleIconColor } from 'material-ui/styles/colors'; import InitSettingIcon from 'material-ui/svg-icons/action/build'; import CheckIcon from 'material-ui/svg-icons/toggle/radio-button-checked'; import UnCheckIcon from 'material-ui/svg-icons/toggle/radio-button-unchecked'; import CodeEditor from '../../CodeEditor'; import { renderDialogTitle } from '../../gadgets'; import { settingType } from '../../../reducers/Experiment/jsPsychInit'; import AppbarTheme from '../theme.js'; const colors = { ...AppbarTheme.colors } const style = { Icon: AppbarTheme.AppbarIcon, TitleIcon: { color: colors.primaryDeep }, TextFieldFocusStyle: { ...AppbarTheme.TextFieldFocusStyle() }, Actions: { Close: { labelStyle: { color: colors.secondaryDeep } } } } export default class jsPsychInitEditor extends React.Component { constructor(props) { super(props); this.state = { open: false } this.handleOpen = () => { this.setState({ open: true }); }; this.handleClose = () => { this.setState({ open: false }); }; this.textFieldRow = (key, type="number", unit=null) => ( <div style={{display: 'flex'}}> <div style={{padding: 15, color: 'black'}}>{key + ((unit) ? " (" + unit + ")" : "")}: </div> <TextField {...style.TextFieldFocusStyle} id={"text-field-"+key} value={this.props[key]} type={type} onChange={(e, value) => { this.props.setJsPsychInit(e, value, key); }} /> </div> ) this.toggleRow = (key) => ( <div style={{display: 'flex', width: 370, position: 'relative'}}> <div style={{padding: 15, color: 'black'}}>{key}</div> <IconButton style={{position: 'absolute', right: 0}} onClick={() => { this.props.setJsPsychInit(null, null, key); }} > {(this.props[key]) ? <CheckIcon color={checkColor} /> : <UnCheckIcon />}/> </IconButton> </div> ) this.codeRow = (key) => ( <div style={{display: 'flex', width: 370, position: 'relative'}}> <div style={{padding: 15, color: 'black'}}>{key}</div> <div style={{position: 'absolute', right: 0}}> <CodeEditor value={this.props[key].code} onlyFunction={true} onCommit={(newCode) => { this.props.setJsPsychInit(null, newCode, key); }} title={key+": "} /> </div> </div> ) } render() { const actions = [ ]; return ( <div className="jsPsych.init-editor"> <IconButton tooltip="Init Properties Setting" onClick={this.handleOpen} > <InitSettingIcon {...style.Icon}/> </IconButton> <Dialog contentStyle={{minHeight: 500}} titleStyle={{padding: 0}} title={ renderDialogTitle( <Subheader style={{maxHeight: 48}}> <div style={{display: 'flex'}}> <div style={{paddingTop: 8, paddingRight: 15}}> <InitSettingIcon {...style.TitleIcon}/> </div> <div style={{fontSize: 16,}}> jsPsych.init properties </div> </div> </Subheader>, this.handleClose, null) } actions={actions} modal={true} open={this.state.open} onRequestClose={this.handleClose} autoScrollBodyContent={true} > {this.textFieldRow(settingType.default_iti)} {this.codeRow(settingType.on_finish)} {this.codeRow(settingType.on_trial_start)} {this.codeRow(settingType.on_trial_finish)} {this.codeRow(settingType.on_data_update)} {this.codeRow(settingType.on_interaction_data_update)} {this.toggleRow(settingType.show_progress_bar)} {this.toggleRow(settingType.auto_update_progress_bar)} {this.toggleRow(settingType.show_preload_progress_bar)} <div style={{padding: 15}}>preload_audio: </div> <div style={{padding: 15}}>preload_images: </div> {this.textFieldRow(settingType.max_load_time, "number", "ms")} <div style={{padding: 15}}>Exclusions: </div> <div style={{paddingLeft: 32}}> {this.textFieldRow(settingType.min_width)} {this.textFieldRow(settingType.min_height)} {this.toggleRow(settingType.audio)} </div> </Dialog> </div> ) } }
src/svg-icons/image/flip.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlip = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z"/> </SvgIcon> ); ImageFlip = pure(ImageFlip); ImageFlip.displayName = 'ImageFlip'; ImageFlip.muiName = 'SvgIcon'; export default ImageFlip;
react-flux-mui/js/material-ui/src/svg-icons/maps/directions-railway.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsRailway = (props) => ( <SvgIcon {...props}> <path d="M4 15.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5zm8 1.5c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6-7H6V5h12v5z"/> </SvgIcon> ); MapsDirectionsRailway = pure(MapsDirectionsRailway); MapsDirectionsRailway.displayName = 'MapsDirectionsRailway'; MapsDirectionsRailway.muiName = 'SvgIcon'; export default MapsDirectionsRailway;
node_modules/react-router/es/withRouter.js
mohammed52/something.pk
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { ContextSubscriber } from './ContextUtils'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; if (!router) { return React.createElement(WrappedComponent, this.props); } var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
src/js/components/plan/EditPlan.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { connect } from 'react-redux'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import { ModalHeader, ModalTitle } from 'react-bootstrap'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import React from 'react'; import { Redirect } from 'react-router-dom'; import { CloseModalXButton, RoutedModal } from '../ui/Modals'; import { getPlan, getPlanFiles, getIsLoadingPlan } from '../../selectors/plans'; import { fetchPlanFiles, updatePlan, updatePlanFromGit, updatePlanFromTarball } from '../../actions/PlansActions'; import EditPlanForm from './EditPlanForm'; import EditPlanFormTabs from './EditPlanFormTabs'; import { Loader } from '../ui/Loader'; import { planTransitionMessages } from '../../constants/PlansConstants'; const messages = defineMessages({ cancel: { id: 'EditPlan.cancel', defaultMessage: 'Cancel' }, editPlan: { id: 'EditPlan.editPlan', defaultMessage: 'Edit {planName} plan' } }); class EditPlan extends React.Component { componentDidMount() { this.props.fetchPlanFiles(this.props.match.params.planName); } handleFormSubmit = ( { planName, planUploadType, files, tarball, gitUrl }, dispatch, props ) => { switch (planUploadType) { case 'tarball': return this.props.updatePlanFromTarball(planName, tarball); case 'directory': let planFiles = {}; files.map(({ filePath, contents }) => (planFiles[filePath] = contents)); return this.props.updatePlan(planName, planFiles); case 'git': return this.props.updatePlanFromGit(planName, gitUrl); default: return null; } }; render() { const { plan, planFiles, intl: { formatMessage }, isLoadingPlan } = this.props; return plan ? ( <RoutedModal bsSize="lg" id="EditPlan__modal" redirectPath="/plans/manage" > <ModalHeader> <CloseModalXButton /> <ModalTitle> <FormattedMessage {...messages.editPlan} values={{ planName: plan.name }} /> </ModalTitle> </ModalHeader> <Loader loaded={!isLoadingPlan} size="lg" height={60} content={formatMessage(planTransitionMessages.loading, { planName: plan.name })} > <EditPlanForm onSubmit={this.handleFormSubmit} initialValues={{ planName: plan.name, planUploadType: 'directory', files: [] }} > <EditPlanFormTabs planName={plan.name} planFiles={planFiles} /> </EditPlanForm> </Loader> </RoutedModal> ) : ( <Redirect to="/plans" /> ); } } EditPlan.propTypes = { fetchPlanFiles: PropTypes.func, intl: PropTypes.object, isLoadingPlan: PropTypes.bool.isRequired, match: PropTypes.object, plan: ImmutablePropTypes.record, planFiles: ImmutablePropTypes.set.isRequired, updatePlan: PropTypes.func.isRequired, updatePlanFromGit: PropTypes.func.isRequired, updatePlanFromTarball: PropTypes.func.isRequired }; const mapStateToProps = (state, { match: { params: { planName } } }) => ({ plan: getPlan(state, planName), planFiles: getPlanFiles(state, planName), isLoadingPlan: getIsLoadingPlan(state, planName) }); const mapDispatchToProps = (dispatch, ownProps) => ({ fetchPlanFiles: planName => { dispatch(fetchPlanFiles(planName)); }, updatePlan: (planName, files) => { dispatch(updatePlan(planName, files)); }, updatePlanFromTarball: (planName, files) => { dispatch(updatePlanFromTarball(planName, files)); }, updatePlanFromGit: (planName, gitUrl) => { dispatch(updatePlanFromGit(planName, gitUrl)); } }); export default injectIntl( connect(mapStateToProps, mapDispatchToProps)(EditPlan) );
frontend/src/components/dialog/sysadmin-dialog/sysadmin-set-org-max-user-number-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Alert, Modal, ModalHeader, ModalBody, ModalFooter, Button, Form, FormGroup, Input, InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap'; import { gettext } from '../../../utils/constants'; import { Utils } from '../../../utils/utils'; const propTypes = { toggle: PropTypes.func.isRequired, updateValue: PropTypes.func.isRequired }; class SysAdminSetOrgMaxUserNumberDialog extends React.Component { constructor(props) { super(props); this.state = { value: this.props.value, isSubmitBtnActive: false }; } toggle = () => { this.props.toggle(); } handleInputChange = (e) => { const value = e.target.value; this.setState({ value: value, isSubmitBtnActive: value.trim() != '' }); } handleKeyPress = (e) => { if (e.key == 'Enter') { this.handleSubmit(); e.preventDefault(); } } handleSubmit = () => { this.props.updateValue(this.state.value.trim()); this.toggle(); } render() { const { value, isSubmitBtnActive } = this.state; return ( <Modal isOpen={true} toggle={this.toggle}> <ModalHeader toggle={this.toggle}>{gettext('Set max number of members')}</ModalHeader> <ModalBody> <Form> <FormGroup> <Input type="text" className="form-control" value={value} onKeyPress={this.handleKeyPress} onChange={this.handleInputChange} /> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggle}>{gettext('Cancel')}</Button> <Button color="primary" onClick={this.handleSubmit} disabled={!isSubmitBtnActive}>{gettext('Submit')}</Button> </ModalFooter> </Modal> ); } } SysAdminSetOrgMaxUserNumberDialog.propTypes = propTypes; export default SysAdminSetOrgMaxUserNumberDialog;
app/containers/App/index.js
keithalpichi/NobleNote
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> <h2>Header here- Place Header Component in App Container</h2> {React.Children.toArray(this.props.children)} <h2>Footer here</h2> </div> ); } }
submissions/winstonewert/src/root.js
winstonewert/flux-challenge
import React from 'react' import ObiWanPlanetMonitor from './obi-wan-planet-monitor' import DarkJediList from './dark-jedi-list' export default class Root extends React.Component { render() { return <div className="app-container"> <div className="css-root"> <ObiWanPlanetMonitor /> <DarkJediList /> </div> </div> } }
src/components/Snake/Body.js
nataly87s/rx-snake
import React from 'react'; import glamorous from 'glamorous'; import { SOLUTO_BLUE } from '../../resources/colors'; const Circle = glamorous.circle({ opacity: 0.4, }); const BodySvg = ({ style, color = SOLUTO_BLUE }) => ( <svg x="0px" y="0px" viewBox="0 0 77 77" style={style}> <path fill="#FFFFFF" d="M27.3,72.7c-12.7,0-23-10.3-23-23V27.3c0-12.7,10.3-23,23-23h22.5c12.7,0,23,10.3,23,23v22.5 c0,12.7-10.3,23-23,23H27.3z"/> <path fill={color} d="M49.7,8.3c10.5,0,19,8.5,19,19v22.5c0,10.5-8.5,19-19,19H27.3c-10.5,0-19-8.5-19-19V27.3c0-10.5,8.5-19,19-19H49.7 M49.7,0.3H27.3c-14.9,0-27,12.2-27,27v22.5c0,14.8,12.1,27,27,27h22.5c14.8,0,27-12.2,27-27V27.3C76.7,12.4,64.6,0.3,49.7,0.3 L49.7,0.3z"/> <Circle fill={color} cx="38.5" cy="38.5" r="21.8"/> </svg> ); export default BodySvg;
app/containers/settings/index.js
7kfpun/TWAQIReactNative
import React, { Component } from 'react'; import { FlatList, Platform, StyleSheet, Text, View } from 'react-native'; import { iOSColors } from 'react-native-typography'; import Collapsible from 'react-native-collapsible'; import DeviceInfo from 'react-native-device-info'; import OneSignal from 'react-native-onesignal'; import Search from 'react-native-search-box'; import Fuse from 'fuse.js'; import AdMob from '../../components/admob'; import SettingsGroup from '../../components/settings-group'; import SettingsItem from '../../components/settings-item'; import SwipeScrollView from '../../components/swipe-scroll-view'; import SettingsDND from './components/settings-dnd'; import { countys, locations } from '../../utils/locations'; import { OneSignalGetTags } from '../../utils/onesignal'; import I18n from '../../utils/i18n'; const CHECK_INTERVAL = 60 * 1000; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, titleBlock: { paddingTop: Platform.OS === 'ios' ? 60 : 20, paddingLeft: 10, }, titleText: { fontSize: 24, color: 'black', }, permissionReminderBlock: { backgroundColor: '#3949AB', justifyContent: 'center', alignItems: 'center', padding: 1, }, permissionReminderText: { fontSize: 12, color: 'white', }, searchBlock: { padding: 10, paddingTop: 20, borderBottomColor: iOSColors.lightGray, borderBottomWidth: 1, }, list: { paddingVertical: 30, }, }); export default class SettingsView extends Component { static requestPermissions() { if (Platform.OS === 'ios') { const permissions = { alert: true, badge: true, sound: true, }; OneSignal.requestPermissions(permissions); OneSignal.registerForPushNotifications(); } } state = { isShowPermissionReminderBlock: false, searchText: '', searchResult: [], collapsed: false, }; componentDidMount() { // Request permission on start SettingsView.requestPermissions(); this.loadEnabledItems(); this.loadEnabledItemsInterval = setInterval( () => this.loadEnabledItems(), CHECK_INTERVAL, ); } componentWillUnmount() { if (this.loadEnabledItemsInterval) clearInterval(this.loadEnabledItemsInterval); if (this.checkPermissionsInterval) clearInterval(this.checkPermissionsInterval); } onChangeText = (searchText) => { const options = { shouldSort: true, threshold: 0.2, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, keys: [ 'SiteName', 'SiteEngName', 'AreaName', 'County', 'Township', 'SiteAddress', ], }; const fuse = new Fuse(locations, options); const searchResult = fuse.search(searchText); this.setState({ searchText, searchResult }); }; onCancelOrDelete = () => { this.setState({ searchText: '' }); }; checkPermissions(tags) { if ( Platform.OS === 'ios' && tags && Object.values(tags).indexOf('true') !== -1 ) { OneSignal.checkPermissions((permissions) => { console.log('checkPermissions', permissions); if (!permissions || (permissions && !permissions.alert)) { this.setState({ isShowPermissionReminderBlock: true }); } else { this.setState({ isShowPermissionReminderBlock: false }); } }); SettingsView.requestPermissions(); } } async loadEnabledItems() { const tags = await OneSignalGetTags(); if (JSON.stringify(tags) !== JSON.stringify(this.state.tags)) { this.setState({ tags, k: Math.random() }); } this.checkPermissions(tags); this.checkPermissionsInterval = setInterval( () => this.checkPermissions(tags), CHECK_INTERVAL, ); } render() { const { collapsed, isShowPermissionReminderBlock, searchResult, searchText, tags, } = this.state; return ( <View style={styles.container}> <Collapsible collapsed={collapsed}> <View style={styles.titleBlock}> <Text style={styles.titleText}>{I18n.t('notify_title')}</Text> </View> </Collapsible> <View style={[ styles.searchBlock, { marginTop: collapsed && DeviceInfo.hasNotch() ? 20 : 0 }, ]} > <Search backgroundColor={iOSColors.white} titleCancelColor={iOSColors.blue} onChangeText={this.onChangeText} onCancel={this.onCancelOrDelete} onDelete={this.onCancelOrDelete} cancelTitle={I18n.t('cancel')} placeholder={I18n.t('search')} /> </View> {isShowPermissionReminderBlock && ( <View style={styles.permissionReminderBlock}> <Text style={styles.permissionReminderText}> {I18n.t('permissions_required')} </Text> </View> )} <SwipeScrollView scrollActionOffset={80} onScrollUp={() => this.setState({ collapsed: true })} onScrollDown={() => this.setState({ collapsed: false })} > {!!searchText && ( <FlatList key={this.state.k} style={styles.list} data={searchResult} keyExtractor={(item, index) => `${index}-${item}`} renderItem={({ item }) => ( <View style={{ paddingHorizontal: 10 }}> <SettingsItem item={item} tags={tags} /> </View> )} /> )} {!searchText && ( <View key={this.state.k}> <SettingsDND tags={tags} /> <FlatList style={styles.list} data={countys} keyExtractor={(item, index) => `${index}-${item}`} renderItem={({ item }) => ( <SettingsGroup groupName={item} tags={tags} onToggle={() => this.loadEnabledItems()} /> )} /> </View> )} </SwipeScrollView> <AdMob unitId={`twaqi-${Platform.OS}-settings-footer`} /> </View> ); } }
src/svg-icons/hardware/keyboard-hide.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardHide = (props) => ( <SvgIcon {...props}> <path d="M20 3H4c-1.1 0-1.99.9-1.99 2L2 15c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 3h2v2h-2V6zm0 3h2v2h-2V9zM8 6h2v2H8V6zm0 3h2v2H8V9zm-1 2H5V9h2v2zm0-3H5V6h2v2zm9 7H8v-2h8v2zm0-4h-2V9h2v2zm0-3h-2V6h2v2zm3 3h-2V9h2v2zm0-3h-2V6h2v2zm-7 15l4-4H8l4 4z"/> </SvgIcon> ); HardwareKeyboardHide = pure(HardwareKeyboardHide); HardwareKeyboardHide.displayName = 'HardwareKeyboardHide'; export default HardwareKeyboardHide;
app/javascript/mastodon/features/ui/components/columns_area.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import { links, getIndex, getLink } from './tabs_bar'; import { Link } from 'react-router-dom'; import BundleContainer from '../containers/bundle_container'; import ColumnLoading from './column_loading'; import DrawerLoading from './drawer_loading'; import BundleColumnError from './bundle_column_error'; import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components'; import detectPassiveEvents from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'DIRECT': DirectTimeline, 'FAVOURITES': FavouritedStatuses, 'LIST': ListTimeline, }; const messages = defineMessages({ publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, }); const shouldHideFAB = path => path.match(/^\/statuses\/|^\/search|^\/getting-started/); export default @(component => injectIntl(component, { withRef: true })) class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, columns: ImmutablePropTypes.list.isRequired, isModalOpen: PropTypes.bool.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; state = { shouldAnimate: false, } componentWillReceiveProps() { this.setState({ shouldAnimate: false }); } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl'); this.setState({ shouldAnimate: true }); } componentWillUpdate(nextProps) { if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } componentDidUpdate(prevProps) { if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.setState({ shouldAnimate: true }); } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } handleChildrenContentChange() { if (!this.props.singleColumn) { const modifier = this.isRtlLayout ? -1 : 1; this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier); } } handleSwipe = (index) => { this.pendingIndex = index; const nextLinkTranslationId = links[index].props['data-preview-title-id']; const currentLinkSelector = '.tabs-bar__link.active'; const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`; // HACK: Remove the active class from the current link and set it to the next one // React-router does this for us, but too late, feeling laggy. document.querySelector(currentLinkSelector).classList.remove('active'); document.querySelector(nextLinkSelector).classList.add('active'); } handleAnimationEnd = () => { if (typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = (node) => { this.node = node; } renderView = (link, index) => { const columnIndex = getIndex(this.context.router.history.location.pathname); const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] }); const icon = link.props['data-preview-icon']; const view = (index === columnIndex) ? React.cloneElement(this.props.children) : <ColumnLoading title={title} icon={icon} />; return ( <div className='columns-area' key={index}> {view} </div> ); } renderLoading = columnId => () => { return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { columns, children, singleColumn, isModalOpen, intl } = this.props; const { shouldAnimate } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); this.pendingIndex = null; if (singleColumn) { const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><i className='fa fa-pencil' /></Link>; return columnIndex !== -1 ? [ <ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}> {links.map(this.renderView)} </ReactSwipeableViews>, floatingActionButton, ] : [ <div className='columns-area'>{children}</div>, floatingActionButton, ]; } return ( <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}> {columns.map(column => { const params = column.get('params', null) === null ? null : column.get('params').toJS(); const other = params && params.other ? params.other : {}; return ( <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}> {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />} </BundleContainer> ); })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
src/routes/Counter/components/Counter.js
codingarchitect/react-counter-pair
import React from 'react' import PropTypes from 'prop-types' import Counter from './counter.rt'; Counter.propTypes = { value : PropTypes.number.isRequired, onIncrement : PropTypes.func.isRequired, onDecrement : PropTypes.func.isRequired } export default Counter;
frontend/Views/NotFound/index.js
shoumma/ReForum
import React, { Component } from 'react'; class NotFound extends Component { render() { return ( <h3>Coudn't found the url buddy. Please check it out.</h3> ); } } export default NotFound;
components/animals/araArarauna.adult.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/araArarauna/01.jpg'), require('../../images/animals/araArarauna/02.jpg'), require('../../images/animals/araArarauna/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/araArarauna/01-thumb.jpg'), require('../../images/animals/araArarauna/02-thumb.jpg'), require('../../images/animals/araArarauna/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Tento druh papouška je asi nejznámější a nejoblíbenější ze všech arů. Má totiž velmi dobré vlastnosti pro ochočení. Je vysoce inteligentní, a pokud k&nbsp;člověku přilne, vyžaduje jeho pozornost. </AnimalText> <AnimalText> Brněnská zoologická zahrada se může pyšnit prvním odchovem ary ararauny na českém území, a to v&nbsp;roce 1963. Nyní se tito ptáci nachází v&nbsp;expozici zvané Exotárium, kde mají možnost vyžití jak venku, tak uvnitř. Tudíž pokud je nevidíte venku, jsou uvnitř a naopak. Rádi mezi těmito místy přelétávají. Momentálně zde bydlí samička Koko, její partner Pedro a ještě tu máme samečka Edu. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Papoušci ara mají nenápadné krycí zbarvení, spodní část těla je žlutá a vrchní zelenomodrá. Když se schovávají v&nbsp;korunách stromů a svítí slunce, jsou proti modré obloze téměř k&nbsp;nenalezení. Na krku mají černý pruh, okolí očí je, až na pár černých pírek, bílé a holé. Měří mezi 80–86&nbsp;centimetry, ale většinu této délky zaujímá dlouhý ocas. Pohlaví se nedá určit ani podle vnějšího zbarvení, ani podle chování, ale pouze za pomoci vyšetření. Zobák mají černý, mohutný a zahnutý. Jeho spodní část je pohyblivá. </AnimalText> <AnimalText> Díky silnému zobáku nemají problém rozlousknout jakkoli tvrdou skořápku. Jejich nejčastější potravou jsou různé druhy ořechů, plody, pupeny, mladé výhonky stromů a příležitostně hmyz. Za potravou jsou schopni létat až 25&nbsp;kilometrů daleko v&nbsp;hejnech, která vedou vždy starší a zkušenější ptáci. Pohromadě také létají ke břehům řek, kde požírají jíl kvůli neutralizaci rostlinných toxinů z&nbsp;potravy. Hledat jídlo se vydávají za úsvitu, za soumraku se pak shromažďují v&nbsp;dutinách stromů, kde tráví noc. </AnimalText> <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Samička snáší 1–3&nbsp;vejce, na kterých sedí cca 25&nbsp;dní. Mláďata se rodí holá a slepá, peří jim narůstá až za 10&nbsp;týdnů, dospívají ve 2–3&nbsp;letech. Malé ary krmí samec. Pokud se k&nbsp;hnízdu přiblíží vetřelec, oba rodiče bývají velmi agresivní. Žijí v&nbsp;monogamních párech, pokud nehnízdí, tak i&nbsp;v&nbsp;hejnech. Dožívají se asi 50&nbsp;let, v&nbsp;lidské péči až 80&nbsp;let. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
packages/core/content-type-builder/admin/src/components/TextareaEnum/index.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { useIntl } from 'react-intl'; import { Textarea } from '@strapi/design-system/Textarea'; const TextareaEnum = ({ description, disabled, error, intlLabel, labelAction, name, onChange, placeholder, value, }) => { const { formatMessage } = useIntl(); const errorMessage = error ? formatMessage({ id: error, defaultMessage: error }) : ''; const hint = description ? formatMessage( { id: description.id, defaultMessage: description.defaultMessage }, { ...description.values } ) : ''; const label = formatMessage(intlLabel); const formattedPlaceholder = placeholder ? formatMessage( { id: placeholder.id, defaultMessage: placeholder.defaultMessage }, { ...placeholder.values } ) : ''; const inputValue = Array.isArray(value) ? value.join('\n') : ''; const handleChange = e => { const arrayValue = e.target.value.split('\n'); onChange({ target: { name, value: arrayValue } }); }; return ( <Textarea disabled={disabled} error={errorMessage} label={label} labelAction={labelAction} id={name} hint={hint} name={name} onChange={handleChange} placeholder={formattedPlaceholder} value={inputValue} > {inputValue} </Textarea> ); }; TextareaEnum.defaultProps = { description: null, disabled: false, error: '', labelAction: undefined, placeholder: null, value: '', }; TextareaEnum.propTypes = { description: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), disabled: PropTypes.bool, error: PropTypes.string, intlLabel: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }).isRequired, labelAction: PropTypes.element, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, placeholder: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]), }; export default TextareaEnum;
src/templates/landing.js
gabrielcsapo/tryitout
import 'psychic.css/dist/psychic.min.css' import './landing.css' import React from 'react' import PropTypes from 'prop-types' import { render } from 'react-dom' import HTML from '../HTML' import { cleanString } from '../../lib/util' class Landing extends React.Component { render () { const { title, nav, body, footer, options } = this.props const { width } = options // Set the title of the window document.title = title return ( <div id='container' style={{ width, textAlign: 'center' }}> <div className='navbar'> <div className='container'> <div className='navbar-title'><span className='text-black'>{cleanString(title)}</span></div> <div className='nav'> {Object.keys(nav).map((k, i) => { return <a key={i} href={nav[k]} target='_blank' rel='noopener noreferrer'> {k} </a> })} </div> </div> </div> <div id='container-content'> <div style={{ margin: '0 auto' }}> <HTML value={body} /> </div> </div> <div className='footer'> <HTML value={footer} /> </div> </div> ) } } Landing.propTypes = { title: PropTypes.string, body: PropTypes.body, nav: PropTypes.array, options: PropTypes.shape({ width: PropTypes.string }), footer: PropTypes.string } Landing.defaultProps = { title: '', body: '', nav: [], options: { width: '90%' }, footer: '' } if ((window && window.config) || global.config) { const injectedConfig = (window && window.config) || global.config render(<Landing {...injectedConfig} />, document.getElementById('root')) if (injectedConfig.dev) { const hash = injectedConfig.hash setInterval(function () { const xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(xhttp.responseText) if (response.hash !== hash) { location.reload() } } } xhttp.open('GET', '/update', true) xhttp.send() }, 5000) } } else { module.exports = Landing }