path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/js/Control.js
skratchdot/infinite-gradients
import React from 'react'; import LockIcon from './LockIcon'; module.exports = React.createClass({ getDefaultProps: function () { return { onClick: function () {}, title: '', value: '', fill: null, smallAlign: 'right', showLock: false, locked: false }; }, render: function () { var lock = null; if (this.props.showLock) { lock = ( <div className="lock-container"> <LockIcon width="100%" height="100%" locked={this.props.locked} fill={this.props.fill} /> </div> ); } return ( <div className="control" onClick={this.props.onClick}> <strong>{this.props.value}</strong> <small style={{textAlign: this.props.smallAlign}}>{this.props.title}</small> {lock} </div> ); } });
app/scripts/index.js
lukasjuhas/lukasjuhas.com_v5
import React from 'react'; import { render } from 'react-dom'; import router from './router'; router.run((Handler, state) => { render(<Handler {...state} />, document.getElementById('app')); });
examples/huge-apps/components/GlobalNav.js
kevinsimper/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); console.log(styles.link); export default GlobalNav;
frontend/src/app/public/Navbar/index.stories.js
djhi/boilerplate
import React from 'react'; import { text } from '@kadira/storybook-addon-knobs'; import storiesOf from '../../../lib/publicStoriesOf'; import Navbar from './Navbar'; storiesOf('Navbar', module, 'The main public navbar') .add('basic', () => ( <Navbar /> )) .add('active link', () => ( <Navbar pathname={text('pathname', '/articles')} /> ));
server/public/js/app/stringTools/components/App.js
fendy3002/QzStringTools
import React from 'react' import AppTemplate from '../../sharedComponents/AppTemplate.js'; import StateToolPanel from '../containers/StateToolPanel.js'; var App = function(){ return <AppTemplate> <StateToolPanel /> </AppTemplate>; }; export default App;
src/client/assets/js/nodes/processors/uibuilder/features/canvas/components/svg/Text.js
me-box/iot.red
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import {camelise} from 'nodes/processors/uibuilder/utils'; import { actionCreators as canvasActions, selector } from '../..'; import { connect } from 'react-redux'; @connect(selector, (dispatch) => { return{ actions: bindActionCreators(canvasActions, dispatch) } }) export default class Text extends Component { static defaultProps = { transform: "translate(0,0)" }; constructor(props){ super(props); this._onRotate = this._onRotate.bind(this); this._onExpand = this._onExpand.bind(this); this._onMouseDown = this._onMouseDown.bind(this); this._templateSelected = this._templateSelected.bind(this); } shouldComponentUpdate(nextProps, nextState){ return this.props.template != nextProps.template || this.props.selected != nextProps.selected; } render(){ const {id, template, selected} = this.props; const {x,y,text,style} = template; const _style = camelise(style); return <g transform={this.props.transform}> <text textAnchor="middle" x={x} y={y} style={_style} onClick={this._templateSelected} onMouseDown={this._onMouseDown}>{text}</text> </g> } _templateSelected(){ const {nid, id, template} = this.props; this.props.actions.templateSelected(nid,{path:[id], type:template.type}); } _onMouseDown(){ const {nid, id, template} = this.props; this.props.actions.onMouseDown(nid,{path:[id], type:template.type}); } _onRotate(){ const {nid, id} = this.props; this.props.actions.onRotate(nid, id); } _onExpand(){ const {nid, id} = this.props; this.props.actions.onExpand(nid,id); } }
src/routes.js
sseppola/react-redux-universal-hot-example
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
client/src/components/bios/Container.js
DjLeChuck/recalbox-manager
import React from 'react'; import PropTypes from 'prop-types'; import { translate } from 'react-i18next'; import reactStringReplace from 'react-string-replace'; import Button from 'react-bootstrap/lib/Button'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import Modal from 'react-bootstrap/lib/Modal'; import { conf, get, post } from '../../api'; import { promisifyData, cancelPromises } from '../../utils'; import Bios from './Bios'; class BiosContainer extends React.Component { static propTypes = { t: PropTypes.func.isRequired, }; constructor(props) { super(props); this.name = ''; this.state = { loaded: false, deleting: false, showModal: false, biosName: '', biosPath: '', biosList: [], stickyContent: null, stickyStyle: 'danger', }; } async componentWillMount() { const state = await promisifyData( conf(['recalbox.biosPath']), get('biosList') ); state.loaded = true; this.setState(state); } componentWillUnmount() { cancelPromises(); } onBiosUploaded = (result) => { if (result.name) { const { biosList } = this.state; let biosIndex = biosList.findIndex(x => x.name === result.name); const list = [...biosList]; list[biosIndex] = result; this.setState({ biosList: list }); } }; close = () => this.setState({ showModal: false }); open = biosName => ( this.setState({ showModal: true, biosName, }) ); delete = () => { this.setState({ deleting: true }); const { biosName, biosList } = this.state; const { t } = this.props; post('deleteBios', { file: biosName, }).then(() => { let biosData = biosList.find(x => x.name === biosName); biosData.valid = null; this.setState({ deleting: false, stickyContent: t('Votre BIOS a bien été supprimé !'), stickyStyle: 'success', biosData, }); }, () => { this.setState({ deleting: false, stickyContent: t("Il semble que votre BIOS n'ait pas été supprimé."), stickyStyle: 'danger', }); }); this.close(); }; render() { const { t } = this.props; const { biosName, showModal, deleting, ...rest } = this.state; const modalBody = reactStringReplace(t('Voulez-vous vraiment supprimer %s ?'), '%s', (match, i) => ( <strong key={i}>{biosName}</strong> )); return ( <div> <Bios {...rest} biosPath={this.state['recalbox.biosPath']} onClick={this.open} onBiosUploaded={this.onBiosUploaded} /> <Modal show={showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>{t('Attention')}</Modal.Title> </Modal.Header> <Modal.Body><p>{modalBody}</p></Modal.Body> <Modal.Footer> <Button onClick={this.close}>{t('Non')}</Button> <Button bsStyle="warning" onClick={this.delete}> {deleting && <Glyphicon glyph="refresh" className="glyphicon-spin" /> } {t('Oui')} </Button> </Modal.Footer> </Modal> </div> ); } } export default translate()(BiosContainer);
src/components/Viewer/index.js
jacobwindsor/pathway-presenter
import '../../polyfills'; import React, { Component } from 'react'; import presentations from '../../data/presentations'; import './index.css'; import Diagram from '../Diagram'; import Controls from './components/Controls'; import Loading from '../Loading'; import ErrorMessage from '../ErrorMessage'; import PropTypes from 'prop-types'; import 'roboto-fontface/css/roboto/roboto-fontface.css'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Title from '../Title'; import * as screenfull from 'screenfull'; import { cloneDeep } from 'lodash'; import Aspectral from 'react-aspectral'; class Viewer extends Component { constructor(props) { super(props); this.state = { loading: true, isFullScreen: false }; if (screenfull.enabled) { screenfull.onchange(() => { this.setState({ isFullScreen: screenfull.isFullscreen }); }); } } componentDidMount() { const { presId } = this.props; presentations .get(presId) .then(presentation => { this.addEventListeners(); const copy = cloneDeep(presentation); this.setState({ presentation: copy, loading: false, activeSlideIndex: 0 }); }) .catch(err => { this.setState({ error: { message: err.message }, loading: false }); }); } addEventListeners() { window.addEventListener('keydown', e => { switch (e.keyCode) { case 39: // right arrow this.nextSlide(); break; case 37: // Left arrow this.prevSlide(); break; default: break; } }); } nextSlide = () => { const { activeSlideIndex, presentation } = this.state; if (activeSlideIndex === presentation.slides.length - 1) return; this.setState({ activeSlideIndex: activeSlideIndex + 1 }); }; prevSlide = () => { const { activeSlideIndex } = this.state; if (activeSlideIndex === 0) return; this.setState({ activeSlideIndex: activeSlideIndex - 1 }); }; onReady = () => { this.setState({ loading: false }); }; handleToggleFullScreen = () => { if (screenfull.enabled) { screenfull.toggle(); } }; render() { const { loading, presentation, activeSlideIndex, error, isFullScreen } = this.state; if (error) { return <ErrorMessage message={error.message} />; } if (loading) return <Loading />; if (!presentation) return null; const activeSlide = presentation.slides[activeSlideIndex]; return ( <MuiThemeProvider> <div className="presentation-viewer"> {activeSlide.title ? <Title title={activeSlide.title} /> : null} <Diagram wpId={presentation.wpId} detailPanelEnabled={false} version={presentation.version} slide={activeSlide} showPanZoomControls={false} panZoomLocked onReady={this.onReady} /> <Controls onBackward={this.prevSlide} onForward={this.nextSlide} handleToggleFullScreen={this.handleToggleFullScreen} isFullScreen={isFullScreen} /> </div> </MuiThemeProvider> ); } } Viewer.propTypes = { presId: PropTypes.string.isRequired }; export default Aspectral(16, 9)(Viewer);
docs/src/IntroductionPage.js
Lucifier129/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
src/ModalFooter.js
erictherobot/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalFooter extends React.Component { render() { return ( <div {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> {this.props.children} </div> ); } } ModalFooter.propTypes = { /** * A css class applied to the Component */ modalClassName: React.PropTypes.string }; ModalFooter.defaultProps = { modalClassName: 'modal-footer' }; export default ModalFooter;
BackUp FIrebase/IQApp/components/AboutPage.js
victorditadi/IQApp
import React, { Component } from 'react'; import { Text, View, Button} from 'react-native'; import HeaderIQMail from './Faixa'; export default class AboutPage extends Component{ constructor(){ super(); } render(){ return( <View> <HeaderIQMail></HeaderIQMail> <Text>About</Text> <Button onPress={this.goToHomePage} title="Go to Home Page">Home</Button> <Text>{this.props.data}</Text> </View> ) } goToHomePage = () => { this.props.navigator.push({ name: 'Home', title: 'Home' }) } }
src/svg-icons/notification/sync-disabled.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSyncDisabled = (props) => ( <SvgIcon {...props}> <path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z"/> </SvgIcon> ); NotificationSyncDisabled = pure(NotificationSyncDisabled); NotificationSyncDisabled.displayName = 'NotificationSyncDisabled'; NotificationSyncDisabled.muiName = 'SvgIcon'; export default NotificationSyncDisabled;
src/pages/todo/components/todo-item.js
mvtnghia/web-boilerplate
// @flow import classNames from 'classnames'; import React, { Component } from 'react'; import TodoTextInput from './todo-text-input'; import type { Todo } from '../types'; export type Props = { todo: Todo, onEditTodo: Function, onDeleteTodo: Function, onToggleTodo: Function, }; type State = { editing: boolean, }; export default class TodoItem extends Component { props: Props; state: State; constructor(props: Props) { super(props); this.state = { editing: false, }; } handleDoubleClick = () => { this.setState({ editing: true }); }; handleSave = (id: number, text: string) => { if (text.length === 0) { this.props.onDeleteTodo([id]); } else { this.props.onEditTodo(id, text); } this.setState({ editing: false }); }; renderTodoEditing = (props: Props, state: State) => { return ( <TodoTextInput text={props.todo.text} editing={state.editing} onSave={text => this.handleSave(props.todo.id, text)} /> ); }; renderTodoView = (props: Props) => { return ( <div className="view"> <label htmlFor={props.todo.id} onDoubleClick={this.handleDoubleClick}> <input id={props.todo.id} className="toggle" type="checkbox" checked={props.todo.completed} onChange={() => props.onToggleTodo(props.todo)} /> {props.todo.text} </label> <button type="button" className="destroy" onClick={() => props.onDeleteTodo([props.todo.id])} /> </div> ); }; renderComponent = (props: Props, state: State) => { const cls = classNames({ completed: props.todo.completed, editing: state.editing, }); return ( <li className={cls}> {state.editing ? this.renderTodoEditing(props, state) : this.renderTodoView(props)} </li> ); }; render() { return this.renderComponent(this.props, this.state); } }
app/javascript/mastodon/components/column_back_button_slim.js
Craftodon/Craftodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = () => { if (window.history && window.history.length === 1) this.context.router.history.push('/'); else this.context.router.history.goBack(); } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
app/components/NotFound.js
SecComm/redux-blog-example
import styles from './../global.styl'; import React from 'react'; import CSSModules from 'react-css-modules'; @CSSModules(styles) export default class NotFound extends React.Component { render() { return ( <div styleName="wrapper"> <h1>Not Found</h1> </div> ); } }
src/routes/login/index.js
arolla/Arollydays
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Login from './Login'; export default { path: '/login', action() { return <Login />; }, };
src/components/History.js
SiDChik/redux-regexp-router
/** * Created by sidchik on 28.03.17. */ import React from 'react'; import { connect } from 'react-redux'; import { createHashHistory, createBrowserHistory, createMemoryHistory } from 'history'; import { _setRouting } from '../actions/routing'; const createHistory = (historyType) => { let historyCreator; switch (historyType) { case 'hash': historyCreator = createHashHistory; break; case 'browser': historyCreator = createBrowserHistory; break; case 'memory': historyCreator = createMemoryHistory; break; default: historyCreator = createHashHistory; } class History extends React.Component { history = historyCreator(); extractQuery(query) { return {}; } constructor(props) { super(props); this.state = { location: null, action: null }; props.dispatch(_setRouting({ historyType: historyType, history: this.history, location: this.history.location, query: this.extractQuery(), })); this.unlisten = this.history.listen((location, action) => { // location is an object like window.location this.setState({ location: location, action: action }, function () { props.dispatch(_setRouting({ location: this.state.location, query: this.extractQuery(), })); }); }) } componentWillMount() { } componentWillUnmount() { this.unlisten(); } render() { // # render only on ready const {routing} = this.props; if (!routing.location) return null; return React.Children.only(this.props.children); } } const mapStateToProps = (state /*, ownProps*/) => { return { routing: state.routing } }; return connect(mapStateToProps)(History); }; const HashHistory = createHistory('hash'); const BrowserHistory = createHistory('browser'); const MemoryHistory = createHistory('memory'); export { HashHistory, BrowserHistory, MemoryHistory } export default createHistory;
src/components/widgets/widgets-list.js
johnamiahford/widgets-spa
'use strict'; import React from 'react'; import WidgetsListItem from './widgets-list-item'; import Search from '../search'; class WidgetsList extends React.Component { renderWidgets() { return ( <div className={'WidgetsList ' + this.props.widgetListClass}> <table className="table"> <thead className="fixed"> <tr> <th className="text-center">ID</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> {this.renderIndividualWidgets()} </tbody> </table> </div> ); } renderIndividualWidgets() { return this.props.widgets.map(widget => { let isIntlSupported = typeof window.Intl !== 'undefined' ? new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(widget.price) : '$' + widget.price; return ( <WidgetsListItem key={widget.id} id={widget.id} name={widget.name} price={isIntlSupported} color={widget.color} inventory={widget.inventory} melts={widget.melts} /> ); }); } noWidgetsFound() { return ( <table className="table"> <tr><td>No Widgets Found</td></tr> </table> ); } render() { let {widgets, handleSearchFilter, shouldSearchFilterReset, gridClassName} = this.props; let hasWidgets = widgets.length; let isSearching = this.props.isSearching ? true : false; return ( <div className={gridClassName}> <div className="Widget widget"> <div className="widget-header">Widgets <div className="pull-right"> <Search placeholder="Search widgets..." disabled={hasWidgets || isSearching ? false : true} searchName="widgets" searchCritera="name" shouldSearchFilterReset={shouldSearchFilterReset} onChange={handleSearchFilter} /> </div> </div> <div className="table-responsive"> {hasWidgets ? this.renderWidgets() : this.noWidgetsFound()} </div> </div> </div> ); } } WidgetsList.defaultProps = { gridClassName: 'col-lg-6', widgetListClass: 'WidgetsList--notFixed' }; export default WidgetsList;
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Create/FormComponents/TextArea.js
dewmini/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; const TextArea = (props) => ( <div className="form-group"> <label className="form-label">{props.title}</label> <textarea className="form-input" style={props.resize ? null : {resize: 'none'}} name={props.name} rows={props.rows} value={props.content} onChange={props.controlFunc} placeholder={props.placeholder} /> </div> ); TextArea.propTypes = { title: React.PropTypes.string.isRequired, rows: React.PropTypes.number.isRequired, name: React.PropTypes.string.isRequired, content: React.PropTypes.string.isRequired, resize: React.PropTypes.bool, placeholder: React.PropTypes.string, controlFunc: React.PropTypes.func.isRequired }; export default TextArea;
examples/demos/timeslots.js
elationemr/react-big-calendar
import React from 'react'; import BigCalendar from 'react-big-calendar'; import events from '../events'; class Timeslots extends React.Component { render() { return ( <BigCalendar {...this.props} events={events} step={15} timeslots={8} defaultView='week' defaultDate={new Date(2015, 3, 12)} /> ) } } export default Timeslots;
docs/src/app/components/pages/components/Snackbar/ExampleAction.js
hai-cea/material-ui
import React from 'react'; import Snackbar from 'material-ui/Snackbar'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; export default class SnackbarExampleSimple extends React.Component { constructor(props) { super(props); this.state = { autoHideDuration: 4000, message: 'Event added to your calendar', open: false, }; } handleClick = () => { this.setState({ open: true, }); }; handleActionClick = () => { this.setState({ open: false, }); alert('Event removed from your calendar.'); }; handleChangeDuration = (event) => { const value = event.target.value; this.setState({ autoHideDuration: value.length > 0 ? parseInt(value) : 0, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { return ( <div> <RaisedButton onClick={this.handleClick} label="Add to my calendar" /> <br /> <TextField floatingLabelText="Auto Hide Duration in ms" value={this.state.autoHideDuration} onChange={this.handleChangeDuration} /> <Snackbar open={this.state.open} message={this.state.message} action="undo" autoHideDuration={this.state.autoHideDuration} onActionClick={this.handleActionClick} onRequestClose={this.handleRequestClose} /> </div> ); } }
test/test_helper.js
joakimremler/horse-project
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/routes.js
jlmonroy13/solvingbooks-poison
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import ObjectUtils from './utils/object'; import { setSolutionManuals } from './actions/solutionManuals'; import { getSolutionManual, setSelections } from './actions/searcher'; import { setStatusRequestTrue } from './actions/spinner'; import { App, HomePage, NotFoundPage, SearchPage, } from './components'; import { CreateSolutionManualContainer, AdminIndexContainer, SolutionManualDetailContainer } from './containers'; const onEnterPage = store => { return (nextState, replace, callback) => { const { dispatch } = store; dispatch(setSolutionManuals(callback)); }; }; const fetchSolutionManual = (store, callback, startPosition) => { const { dispatch, getState } = store; const { solutionManuals, routing: { locationBeforeTransitions: { pathname } }, pendingTasks, } = getState(); const urlName = pathname.substring(startPosition); const solutionManualsArr = ObjectUtils.toArray(solutionManuals); const book = solutionManualsArr.filter((bookItem) => urlName === bookItem.urlName); if(pendingTasks === 0) dispatch(setStatusRequestTrue()); dispatch(getSolutionManual(book[0].id, callback)); dispatch(setSelections({ bookName: book[0].name || '', chapter: '', subchapter: '', exercise: '', })); }; const onEnterSearcher = store => { return (nextState, replace, callback) => { fetchSolutionManual(store, callback, 7); }; }; const onEnterAdminDetail = store => { return (nextState, replace, callback) => { fetchSolutionManual(store, callback, 26); }; }; const routes = store => ( <Route path="/" component={App} onEnter={onEnterPage(store)}> <IndexRoute component={HomePage} /> <Route path="/libro/:bookNameUrl" component={SearchPage} onEnter={onEnterSearcher(store)} /> <Route path="/solving1213" component={AdminIndexContainer} /> <Route path="/solving1213/crear-solucionario" component={CreateSolutionManualContainer} /> <Route path="/solving1213/solucionario/:bookNameUrl" component={SolutionManualDetailContainer} onEnter={onEnterAdminDetail(store)} /> <Route path="*" component={NotFoundPage} /> </Route> ); export default routes;
lavalab/html/node_modules/react-bootstrap/es/DropdownButton.js
LavaLabUSC/usclavalab.org
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 _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import PropTypes from 'prop-types'; import Dropdown from './Dropdown'; import splitComponentProps from './utils/splitComponentProps'; var propTypes = _extends({}, Dropdown.propTypes, { // Toggle props. bsStyle: PropTypes.string, bsSize: PropTypes.string, title: PropTypes.node.isRequired, noCaret: PropTypes.bool, // Override generated docs from <Dropdown>. /** * @private */ children: PropTypes.node }); var DropdownButton = function (_React$Component) { _inherits(DropdownButton, _React$Component); function DropdownButton() { _classCallCheck(this, DropdownButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DropdownButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, children = _props.children, props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'children']); var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent), dropdownProps = _splitComponentProps[0], toggleProps = _splitComponentProps[1]; return React.createElement( Dropdown, _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Dropdown.Toggle, _extends({}, toggleProps, { bsSize: bsSize, bsStyle: bsStyle }), title ), React.createElement( Dropdown.Menu, null, children ) ); }; return DropdownButton; }(React.Component); DropdownButton.propTypes = propTypes; export default DropdownButton;
src/svg-icons/device/signal-cellular-no-sim.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularNoSim = (props) => ( <SvgIcon {...props}> <path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/> </SvgIcon> ); DeviceSignalCellularNoSim = pure(DeviceSignalCellularNoSim); DeviceSignalCellularNoSim.displayName = 'DeviceSignalCellularNoSim'; DeviceSignalCellularNoSim.muiName = 'SvgIcon'; export default DeviceSignalCellularNoSim;
BUILD/js/index.js
kevincaicedo/MyStore-Front-end
import React from 'react' import ReactDOM from 'react-dom' import ContentProduct from './components_js/content-product.js' import Footer from './components_js/foot.js' import RegisterUser from './components_js/form-user/register-user.js' import SesionUser from './components_js/form-user/sesion-user.js' // navegacion import Navegation from './components_js/navegation.js' import NavAdmin from './components_js/admin-components/nav.js' import $ from '../../components/jquery/dist/jquery.min.js' let datas = [ { imagenes: 'img/imac5k.jpg', precio: '28.666', nombre: 'Imac 5K', marca: 'Apple Computer', fecha: '2-febrero-2015', id: '1'}, { imagenes: 'img/iphone6plus.jpg', precio: '3.666', nombre: 'Iphone 6 Plus', marca: 'Apple Computer', fecha: '2-febrero-2015', id: '2'}, { imagenes: 'img/imac5k.jpg', precio: '30.666', nombre: 'Imac 5K', marca: 'Apple Computer', fecha: '2-febrero-2015', id: '3'}, { imagenes: 'img/macBook.jpg', precio: '28.666', nombre: 'MacBook Pro', marca: 'Apple Computer', fecha: '2-febrero-2015', id: '4'}, { imagenes: 'img/uhd-0.jpg', precio: '128.666', nombre: 'Smart TV UHD', marca: 'SAMSUNG', fecha: '2-febrero-2015', id: '5'}, { imagenes: 'img/gs6ed.jpg', precio: '2.666', nombre: 'Galaxy S6 edge+', marca: 'SAMSUNG', fecha: '2-febrero-2015', id: '6'} ] let dropdata = [ { hrf: '2', txt: 'phone' }, { hrf: '3', txt: 'tv Smart' }, { hrf: '1', txt: 'Computer' } ] let logoad = 'http://res.cloudinary.com/dxdq7wi7u/image/upload/v1465946875/logo64_ixkzm5.png' let datadmin = [ { usu: 'usuario', date: 'hoy', cont: 'Lorem ipsum dolor sit amet, consectetur' }, { usu: 'usuario', date: 'ayer', cont: 'Lorem ipsum dolor sit amet, consectetur' }, { usu: 'usuario', date: 'hace 2 dias', cont: 'Lorem ipsum dolor sit amet, consectetur' } ] ReactDOM.render(<ContentProduct dataproduct={datas} />, $('#list-product1')[0]) ReactDOM.render(<Footer/>, $('.wrapper-floor')[0]) ReactDOM.render(<RegisterUser/>, $('.md-registrarme')[0]) ReactDOM.render(<SesionUser/>, $('.md-iniciar-sesion')[0]) let token = localStorage.getItem('tokenAccessMystore') if(token){ ReactDOM.render(<NavAdmin logonav={logoad} message={datadmin} />, $('nav#mainNav')[0]) }else { ReactDOM.render(<Navegation logo={logoad} dropdownlist={dropdata}/>, $('nav#mainNav')[0]) } /**** Query ****/ $('#registerbtn').on('click', function(e){ console.log('entro pana') let user = $('.md-registrarme input#userf').val() let mail = $('.md-registrarme input#emailf').val() let pass = $('.md-registrarme input#passf').val() let tele = $('.md-registrarme input#telf').val() $.ajax({ url: 'http://maching-learning-cloned-pyner.c9users.io:8080/api/Usuarios', dataType:'json', type: 'POST', data: { "telefono": tele, "username": user, "password": pass, "email": mail } }).done((data)=> { console.log("succesfull") $('.md-registrarme input#userf').val('') $('.md-registrarme input#emailf').val('') $('.md-registrarme input#passf').val('') $('.md-registrarme input#telf').val('') $('.md-registrarme').modal('hide') $('.md-iniciar-sesion').modal('show') }).fail((data, error)=>{ console.log("error") }) }) // iniciar sesion $('#initbtn').on('click', function(e){ console.log('entro pana') let mail = $('.md-iniciar-sesion input#userf').val() let pass = $('.md-iniciar-sesion input#passf').val() $.ajax({ url: 'http://maching-learning-cloned-pyner.c9users.io:8080/api/Usuarios/login', dataType:'json', type: 'POST', data: { "email" : mail, "password": pass } }).done((data)=> { console.log("succesfull") $('.md-iniciar-sesion input#userf').val('') $('.md-iniciar-sesion input#passf').val('') token = data.id let iduser = data.userId localStorage.setItem("tokenAccessMystore", JSON.stringify(token)); localStorage.setItem("userIdMystore", JSON.stringify(iduser)); window.location="http://localhost/MyStore-Front-end/admin.html" }).fail((data, error)=>{ console.log("error") }) }) // logout de mystore $('#logoutmystore').on('click', function(e){ localStorage.removeItem("tokenAccessMystore") localStorage.removeItem("userIdMystore") window.location="http://localhost/MyStore-Front-end/" })
wedding_site/frontend/App.js
JeffBain/wedding-website
import React from 'react'; import AppBar from 'material-ui/AppBar'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MenuIcon from 'material-ui/svg-icons/navigation/menu'; import { Link } from 'react-router'; export default class App extends React.Component { render() { const options = { '/': 'Home', '/rsvp': 'RSVP', '/hotel': 'Hotels', '/registry': 'Registry' } const menuItems = Object.keys(options).map(key => { const link = <Link to={key}>{options[key]}</Link>; return (<MenuItem key={key} primaryText={link} />); }); const menu = ( <IconMenu children={menuItems} iconButtonElement={<IconButton><MenuIcon /></IconButton>} /> ); return ( <div> <AppBar title="Jeff and Nicole's Wedding" iconElementLeft={menu} /> { this.props.children } </div> ); } }
src/components/SinglePostArticle.js
numieco/patriot-trading
import React from 'react' import ArrowSVG from './../Svg/ArrowSVG' import { Link } from 'react-router-dom' export default class SinglePostArticle extends React.Component { constructor (props) { super (props) this.redirectUsingSlug = this.redirectUsingSlug.bind(this) } redirectUsingSlug = () => { window.location = '/post' } render () { return ( <Link to={ '/post/' + this.props.post.slug }> <div className='more-articals-element'> { this.props.post.title } <div className='arrow-svg'> <ArrowSVG /> </div> </div> </Link> ) } }
src/js/dom-components/photo-upload.js
afs35mm/Schorr-Eats
import React, { Component } from 'react'; class PhotoUpload extends Component { constructor(props) { super(props); } deleteAlreadyUploadedImg(imgName, i) { this.props.deleteAlreadyUploadedImg(imgName, i); } deleteImg(i) { this.props.removeImg(i); } handleChange(e) { const files = Array.from(e.target.files); const pFiles = files.map(file => { const reader = new FileReader(); const readerP = new Promise((resolve, reject) => { reader.onloadend = () => { resolve({ data: reader.result, file }); }; }); reader.readAsDataURL(file); return readerP; }); Promise.all(pFiles).then(imgs => { this.props.onDrop(imgs); }); } render() { const imagesDirName = this.props.existingPhotos.imagesDirName; const existingImgs = imagesDirName && this.props.existingPhotos.imgs.length ? this.props.existingPhotos.imgs.map((existingImg, i) => ( <li key={existingImg} className="item-holder"> <img className="item-image" src={`/images/${imagesDirName}/${existingImg}`} /> <svg onClick={() => { this.deleteAlreadyUploadedImg(existingImg, i); }} xlinkHref="http://www.w3.org/2000/svg" className="svg-icon" viewBox="0 0 20 20"> <path d="M10.185,1.417c-4.741,0-8.583,3.842-8.583,8.583c0,4.74,3.842,8.582,8.583,8.582S18.768,14.74,18.768,10C18.768,5.259,14.926,1.417,10.185,1.417 M10.185,17.68c-4.235,0-7.679-3.445-7.679-7.68c0-4.235,3.444-7.679,7.679-7.679S17.864,5.765,17.864,10C17.864,14.234,14.42,17.68,10.185,17.68 M10.824,10l2.842-2.844c0.178-0.176,0.178-0.46,0-0.637c-0.177-0.178-0.461-0.178-0.637,0l-2.844,2.841L7.341,6.52c-0.176-0.178-0.46-0.178-0.637,0c-0.178,0.176-0.178,0.461,0,0.637L9.546,10l-2.841,2.844c-0.178,0.176-0.178,0.461,0,0.637c0.178,0.178,0.459,0.178,0.637,0l2.844-2.841l2.844,2.841c0.178,0.178,0.459,0.178,0.637,0c0.178-0.176,0.178-0.461,0-0.637L10.824,10z" /> </svg> </li> )) : []; const imgsToUpload = this.props.imgs.length ? this.props.imgs.map((imgInfo, i) => ( <li key={i} className="item-holder"> <img className="item-image" src={imgInfo.data} /> <svg onClick={() => { this.deleteImg(i); }} xlinkHref="http://www.w3.org/2000/svg" className="svg-icon" viewBox="0 0 20 20"> <path d="M10.185,1.417c-4.741,0-8.583,3.842-8.583,8.583c0,4.74,3.842,8.582,8.583,8.582S18.768,14.74,18.768,10C18.768,5.259,14.926,1.417,10.185,1.417 M10.185,17.68c-4.235,0-7.679-3.445-7.679-7.68c0-4.235,3.444-7.679,7.679-7.679S17.864,5.765,17.864,10C17.864,14.234,14.42,17.68,10.185,17.68 M10.824,10l2.842-2.844c0.178-0.176,0.178-0.46,0-0.637c-0.177-0.178-0.461-0.178-0.637,0l-2.844,2.841L7.341,6.52c-0.176-0.178-0.46-0.178-0.637,0c-0.178,0.176-0.178,0.461,0,0.637L9.546,10l-2.841,2.844c-0.178,0.176-0.178,0.461,0,0.637c0.178,0.178,0.459,0.178,0.637,0l2.844-2.841l2.844,2.841c0.178,0.178,0.459,0.178,0.637,0c0.178-0.176,0.178-0.461,0-0.637L10.824,10z" /> </svg> </li> )) : []; const imgs = [].concat(existingImgs, imgsToUpload); return ( <div className="photo-uploader"> <div className="custom-file"> <input name="uploads[]" onChange={this.handleChange.bind(this)} type="file" className="custom-file-input" id="customFile" multiple /> <label className="custom-file-label" htmlFor="customFile"> Choose file </label> </div> <ul className="images-list"> {imgs.length ? ( imgs ) : ( <p className="no-photos">No images yet ️☹️, upload some! 😄</p> )} </ul> </div> ); } } export default PhotoUpload;
websrc/components/ScriptList.js
Ricky-Nz/gear-website
import React from 'react'; import Relay from 'relay'; import { ListGroup } from 'react-bootstrap'; import ScriptItem from './ScriptItem'; import ListSearchHeader from './ListSearchHeader'; import ListLoadMoreFooter from './ListLoadMoreFooter'; class ScriptList extends React.Component { constructor(props) { super(props); this.state = { loading: false }; } render() { const { edges, pageInfo } = this.props.user.scripts; const listItems = edges&&edges.map(({ node }, index) => <ScriptItem key={index} script={node}/>); return ( <ListGroup> <ListSearchHeader placeholder='search script' onSearch={text => this.setVariables({search}, this.onReadyStateChange.bind(this))}/> {listItems} <ListLoadMoreFooter pageInfo={pageInfo} loading={this.state.loading} onLoadMore={cursor => this.props.relay.setVariables({cursor}, this.onReadyStateChange.bind(this))}/> </ListGroup> ); } onReadyStateChange(event) { console.log(event); } } export default Relay.createContainer(ScriptList, { initialVariables: { cursor: null, search: null }, fragments: { user: () => Relay.QL` fragment on User { scripts(first: 10, after: $cursor, search: $search) { edges { node { ${ScriptItem.getFragment('script')} } } pageInfo { ${ListLoadMoreFooter.getFragment('pageInfo')} } } } ` } });
frontend/src/components/auth/LoginForm.js
technoboom/it-academy
import React, { Component } from 'react'; import { Button, Checkbox, Form, Icon, Message } from 'semantic-ui-react'; /** * Form for log in */ export default class LoginForm extends Component { render() { return ( <div> <Message attached header='Welcome to our site!' content='Fill out the form below to login to your account' /> <Form className='attached fluid segment'> <Form.Input label='Username' placeholder='Username' type='text' /> <Form.Input label='Password' type='password' /> <Button color='blue'>Login</Button> </Form> <Message attached='bottom' warning> <Icon name='help' /> Don't registered yet?&nbsp;<a href='#'>Sign-Up here</a>&nbsp;instead. </Message> </div> ) } }
src/examples/hello_world_react/hello_world_react.js
looker/custom_visualizations_v2
import Hello from './hello' import React from 'react' import ReactDOM from 'react-dom' looker.plugins.visualizations.add({ // Id and Label are legacy properties that no longer have any function besides documenting // what the visualization used to have. The properties are now set via the manifest // form within the admin/visualizations page of Looker id: "react_test", label: "React Test", options: { font_size: { type: "string", label: "Font Size", values: [ {"Large": "large"}, {"Small": "small"} ], display: "radio", default: "large" } }, // Set up the initial state of the visualization create: function(element, config) { // Insert a <style> tag with some styles we'll use later. element.innerHTML = ` <style> .hello-world-vis { /* Vertical centering */ height: 100%; display: flex; flex-direction: column; justify-content: center; text-align: center; } .hello-world-text-large { font-size: 72px; } .hello-world-text-small { font-size: 18px; } </style> `; // Create a container element to let us center the text. let container = element.appendChild(document.createElement("div")); container.className = "hello-world-vis"; // Create an element to contain the text. this._textElement = container.appendChild(document.createElement("div")); // Render to the target element this.chart = ReactDOM.render( <Hello data="loading..."/>, this._textElement ); }, // Render in response to the data or settings changing updateAsync: function(data, element, config, queryResponse, details, done) { // Clear any errors from previous updates this.clearErrors(); // Throw some errors and exit if the shape of the data isn't what this chart needs if (queryResponse.fields.dimensions.length == 0) { this.addError({title: "No Dimensions", message: "This chart requires dimensions."}); return; } // Set the size to the user-selected size if (config.font_size == "small") { this._textElement.className = "hello-world-text-small"; } else { this._textElement.className = "hello-world-text-large"; } // Grab the first cell of the data let firstRow = data[0]; const firstCell = firstRow[queryResponse.fields.dimensions[0].name].value; // Finally update the state with our new data this.chart = ReactDOM.render( <Hello data={firstCell}/>, this._textElement ); // We are done rendering! Let Looker know. done() } });
albums/src/components/Button.js
DaveWJ/LearningReact
/** * Created by david on 2/23/17. */ import React from 'react'; import {Text, TouchableOpacity} from 'react-native'; const Button = ({onPress, children}) => { const {buttonStyle, textStyle} = styles; return ( <TouchableOpacity onPress={onPress} style={buttonStyle}> <Text style={textStyle}> {children} </Text> </TouchableOpacity> ); }; const styles = { textStyle: { alignSelf: 'center', color: '#007aff', fontSize: 16, fontWeight: '600', paddingTop: 10, paddingBottom: 10 }, buttonStyle: { flex: 1, alignSelf: 'stretch', backgroundColor: '#fff', borderRadius: 5, borderWidth: 1, borderColor: '#007aff', marginLeft: 5, marginRight: 5, } }; export default Button;
actor-apps/app-web/src/app/components/Main.react.js
boneyao/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import VisibilityActionCreators from '../actions/VisibilityActionCreators'; import FaviconActionCreators from 'actions/FaviconActionCreators'; import FaviconStore from 'stores/FaviconStore'; import ActivitySection from 'components/ActivitySection.react'; import SidebarSection from 'components/SidebarSection.react'; import ToolbarSection from 'components/ToolbarSection.react'; import DialogSection from 'components/DialogSection.react'; import Favicon from 'components/common/Favicon.react'; //import AppCacheStore from 'stores/AppCacheStore'; //import AppCacheUpdateModal from 'components/modals/AppCacheUpdate.react'; const visibilitychange = 'visibilitychange'; const onVisibilityChange = () => { if (!document.hidden) { VisibilityActionCreators.createAppVisible(); FaviconActionCreators.setDefaultFavicon(); } else { VisibilityActionCreators.createAppHidden(); } }; const getStateFromStores = () => { return { faviconPath: FaviconStore.getFaviconPath() }; }; class Main extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); document.addEventListener(visibilitychange, onVisibilityChange); FaviconStore.addChangeListener(this.onChange); if (!document.hidden) { VisibilityActionCreators.createAppVisible(); } } onChange = () => { this.setState(getStateFromStores()); } render() { //let appCacheUpdateModal; //if (this.state.isAppUpdateModalOpen) { // appCacheUpdateModal = <AppCacheUpdateModal/>; //} return ( <div className="app row"> <Favicon path={this.state.faviconPath}/> <SidebarSection/> <section className="main col-xs"> <ToolbarSection/> <DialogSection/> </section> <ActivitySection/> {/*appCacheUpdateModal*/} </div> ); } } export default requireAuth(Main);
src/interface/icons/Twitter.js
yajinni/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; const Icon = ({ colored, ...other }) => ( <svg viewBox="0 0 300.00006 244.18703" className="icon" {...other}> <g transform="translate(-539.18 -568.86)"> <path d="m633.9 812.04c112.46 0 173.96-93.168 173.96-173.96 0-2.6463-0.0539-5.2806-0.1726-7.903 11.938-8.6302 22.314-19.4 30.498-31.66-10.955 4.8694-22.744 8.1474-35.111 9.6255 12.623-7.5693 22.314-19.543 26.886-33.817-11.813 7.0031-24.895 12.093-38.824 14.841-11.157-11.884-27.041-19.317-44.629-19.317-33.764 0-61.144 27.381-61.144 61.132 0 4.7978 0.5364 9.4646 1.5854 13.941-50.815-2.5569-95.874-26.886-126.03-63.88-5.2508 9.0354-8.2785 19.531-8.2785 30.73 0 21.212 10.794 39.938 27.208 50.893-10.031-0.30992-19.454-3.0635-27.69-7.6468-0.009 0.25652-0.009 0.50661-0.009 0.78077 0 29.61 21.075 54.332 49.051 59.934-5.1376 1.4006-10.543 2.1516-16.122 2.1516-3.9336 0-7.766-0.38716-11.491-1.1026 7.7838 24.293 30.355 41.971 57.115 42.465-20.926 16.402-47.287 26.171-75.937 26.171-4.929 0-9.7983-0.28036-14.584-0.84634 27.059 17.344 59.189 27.464 93.722 27.464" fill={colored ? '#1da1f2' : undefined} /> </g> </svg> ); Icon.propTypes = { colored: PropTypes.bool, }; Icon.defaultProps = { colored: false, }; export default Icon;
app/server.js
browniefed/redux-blog-example
/* eslint-env node */ import express from 'express'; import cookieParser from 'cookie-parser'; import _ from 'lodash'; import path from 'path'; import fs from 'fs'; import React from 'react'; import { Router } from 'react-router'; import Location from 'react-router/lib/Location'; import { Provider } from 'react-redux'; import routes from './routes'; import { createRedux } from './utils/redux'; import fillStore from './utils/fillStore'; import stringifyLocation from './utils/stringifyLocation'; const env = process.env.NODE_ENV || 'development'; const app = express(); app.use(cookieParser()); app.use(express.static('public')); const templatePath = path.join(__dirname, 'template.html'); const templateSource = fs.readFileSync(templatePath, { encoding: 'utf-8' }); const template = _.template(templateSource); app.use((req, res, next) => { const location = new Location(req.path, req.query); const token = req.cookies.token; const store = createRedux({ auth: { token } }); Router.run(routes(store, false), location, async (err, state, transition) => { if (err) { return next(err); } const { isCancelled, redirectInfo } = transition; if (isCancelled) { return res.redirect(stringifyLocation(redirectInfo)); } await fillStore(store, state, state.components); const html = React.renderToString( <Provider store={store}> {() => <Router {...state} />} </Provider> ); const initialState = JSON.stringify(store.getState()); if (state.params.splat) { res.status(404); } res.send(template({ html, initialState, env })); }); }); app.listen(3000);
src/TabContent.js
karote00/todo-react
require('../stylesheets/content.scss'); import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome'; import { tabStore } from './tabStore'; import { Item } from './Item'; let increament = 1; let all = JSON.parse(localStorage.getItem('ALL_LIST')); if (all[0] && all[0].length > 0) { for (var i = 0; i < all[0].length; i++) { increament = Math.max(increament, all[0][i].id); } increament++; } export class TabContent extends Component { constructor(props) { super(props); var path = (this.props.path? this.props.path: 'All').replace(/\//, ''); tabStore.dispatch({type: 'Get', path: path}); this.state = { list: tabStore.getState(), path: path, todo: '' }; } handleChange(e) { this.setState({todo: e.target.value}); } addList() { if (this.state.todo) { tabStore.dispatch({ type: 'Add', item: { todo: this.state.todo, complete: false, starred: false, id: increament }, path: this.state.path }); } increament++; this.setState({ list: tabStore.getState(), todo: '' }); this.refs.addTodo.focus(); } updateList() { this.setState({list: tabStore.getState()}); } componentDidMount() { this.refs.addTodo.focus(); } render() { var path = this.state.path; return ( <div> <div className="newTodo"> <input type="text" ref="addTodo" value={this.state.todo} onChange={this.handleChange.bind(this)} placeholder="Type something..." /> <FontAwesome name="plus" className="todo-plus" size="2x" onClick={this.addList.bind(this)} /> </div> <div> {this.state.list.map(function(item, i) { return <Item key={item.id} data={item} path={path} onUpdate={this.updateList.bind(this)} />; }.bind(this))} </div> </div> ) } }
pages/postcss.js
adjohnson916/site-gatsby
import React from 'react' import './example.css' export default class PostCSS extends React.Component { render () { return ( <div> <h1 className="the-postcss-class"> Hi PostCSSy friends </h1> <div className="postcss-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/components/series/index.js
yamalight/bpjs-electron
// npm packages import React from 'react'; import {withRouter} from 'react-router-dom'; // our packages import db from '../../db/index'; export default withRouter(({series, history}) => { const openSeriesPage = async () => { // but you can use a location instead const location = { pathname: `/series${series._id}`, state: series, }; try { const doc = await db.current.get('series'); const update = { _id: 'series', data: series, }; if (doc) { update._rev = doc._rev; } await db.current.put(update); } catch (e) { // if not found - just put new if (e.status === 404) { await db.current.put({_id: 'series', data: series}); } } history.push(location); }; return ( <div className="tile is-parent is-3"> <div className="tile is-child"> <div className="card" onClick={openSeriesPage}> <div className="card-image"> <figure className="image"> <img src={series.image} alt={series.title} /> </figure> </div> <div className="card-content"> <div className="media"> <div className="media-content"> <p className="title is-4">{series.title}</p> {series.count !== -1 && <p className="subtitle is-6">Videos count: {series.count}</p>} </div> </div> </div> </div> </div> </div> ); });
src/scripts/app/components/AppLoadingError.js
nudoru/R-Media-Player
import React from 'react'; require('!style!css!sass!../../../sass/components/loadingmessage.sass'); export default class AppLoadingError extends React.Component { render() { return ( <div id="initialization__cover"> <div className="initialization__message"> <h1>Oh no ...</h1> <h2>Something went wrong starting the application.</h2> </div> </div> ); } }
examples/create-react-app-starter/containers/App.js
jumpsuit/jumpsuit
import React from 'react' // import logo from './logo.svg' import './App.css' export default React.createClass({ render() { return ( <div className='App'> <div className='App-header'> <img src={logo} className='App-logo' alt='logo' /> <h2>Welcome to React + Jumpsuit!</h2> </div> {this.props.children} </div> ) } })
src/CarouselItem.js
HPate-Riptide/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import TransitionEvents from './utils/TransitionEvents'; // TODO: This should use a timeout instead of TransitionEvents, or else just // not wait until transition end to trigger continuing animations. const propTypes = { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, index: React.PropTypes.number, }; const defaultProps = { active: false, animateIn: false, animateOut: false, }; class CarouselItem extends React.Component { constructor(props, context) { super(props, context); this.handleAnimateOutEnd = this.handleAnimateOutEnd.bind(this); this.state = { direction: null, }; this.isUnmounted = false; } componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } } componentDidUpdate(prevProps) { const { active } = this.props; const prevActive = prevProps.active; if (!active && prevActive) { TransitionEvents.addEndEventListener( ReactDOM.findDOMNode(this), this.handleAnimateOutEnd ); } if (active !== prevActive) { setTimeout(() => this.startAnimation(), 20); } } componentWillUnmount() { this.isUnmounted = true; } handleAnimateOutEnd() { if (this.isUnmounted) { return; } if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(this.props.index); } } startAnimation() { if (this.isUnmounted) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left', }); } render() { const { direction, active, animateIn, animateOut, className, ...props } = this.props; delete props.onAnimateOutEnd; delete props.index; const classes = { item: true, active: active && !animateIn || animateOut, }; if (direction && active && animateIn) { classes[direction] = true; } if (this.state.direction && (animateIn || animateOut)) { classes[this.state.direction] = true; } return ( <div {...props} className={classNames(className, classes)} /> ); } } CarouselItem.propTypes = propTypes; CarouselItem.defaultProps = defaultProps; export default CarouselItem;
Realization/frontend/czechidm-core/src/content/task/identityRole/DynamicTaskRoleDetail.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import Helmet from 'react-helmet'; // import { connect } from 'react-redux'; import * as Basic from '../../../components/basic'; import * as Advanced from '../../../components/advanced'; import DecisionButtons from '../DecisionButtons'; import DynamicTaskDetail from '../DynamicTaskDetail'; import RoleRequestDetail from '../../requestrole/RoleRequestDetail'; /** * Custom task detail designed for use with RoleConceptTable. * Extended from DynamicTaskDetail (it is standard task detail renderer) */ class DynamicTaskRoleDetail extends DynamicTaskDetail { getContentKey() { return 'content.task.instance'; } componentDidMount() { super.componentDidMount(); } _completeTask(decision) { const formDataValues = this.refs.formData.getData(); const task = this.refs.form.getData(); const formDataConverted = this._toFormData(formDataValues, task.formData); this.setState({ showLoading: true }); const decisionReason = this.getDecisionReason(); const formData = { decision: decision.id, formData: formDataConverted, variables: {taskCompleteMessage: decisionReason} }; const { taskManager} = this.props; this.context.store.dispatch(taskManager.completeTask(task, formData, this.props.uiKey, this._afterComplete.bind(this))); } render() { const {task, canExecute} = this.props; const {showLoading, reasonRequired} = this.state; const showLoadingInternal = task ? showLoading : true; const formDataValues = this._toFormDataValues(task.formData); const decisionReasonText = task.completeTaskMessage; return ( <div> <Helmet title={this.i18n('title')} /> {this.renderDecisionConfirmation(reasonRequired)} {this.renderHeader(task)} <Basic.Panel showLoading={showLoadingInternal}> <Basic.AbstractForm className="panel-body" ref="form" data={task}> {this._getTaskInfo(task)} {this._getApplicantAndRequester(task)} <Basic.LabelWrapper ref="taskCreated" label={this.i18n('createdDate')}> <Advanced.DateValue value={task ? task.taskCreated : null} showTime/> </Basic.LabelWrapper> {this.renderDecisionReasonText(decisionReasonText)} </Basic.AbstractForm> <Basic.AbstractForm ref="formData" data={formDataValues} style={{ padding: '15px 15px 0px 15px' }}> {this._getFormDataComponents(task)} </Basic.AbstractForm> <Basic.PanelFooter> <DecisionButtons task={task} onClick={this._validateAndCompleteTask.bind(this)} readOnly={!canExecute} /> </Basic.PanelFooter> </Basic.Panel> <RoleRequestDetail ref="identityRoleConceptTable" uiKey="identity-role-concept-table" entityId={task.variables.entityEvent.content.id} showRequestDetail={false} editableInStates={['IN_PROGRESS']} canExecute={canExecute} showLoading={showLoadingInternal}/> </div> ); } } DynamicTaskRoleDetail.propTypes = { task: PropTypes.object, readOnly: PropTypes.bool, taskManager: PropTypes.object.isRequired, canExecute: PropTypes.bool }; DynamicTaskRoleDetail.defaultProps = { task: null, readOnly: false, canExecute: true }; function select(state, component) { const task = component.task; if (task) { return { _showLoading: false }; } return { _showLoading: true }; } export default connect(select, null, null, { forwardRef: true })(DynamicTaskRoleDetail);
src/script/App.js
dongseup/comms-component
import React, { Component } from 'react'; import {render} from 'react-dom'; import '../style/font.scss'; import '../style/entry.scss'; import WordContainer from './WordContainer'; render(<WordContainer />, document.getElementById('root'));
client/components/charts/in-out-chart.js
bnjbvr/kresus
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import c3 from 'c3'; import { get } from '../../store'; import { translate as $t, round2, getWellsColors } from '../../helpers'; import ChartComponent from './chart-base'; const CHART_SIZE = 600; const SUBCHART_SIZE = 100; // Initial subchart extent, in months. const SUBCHART_EXTENT = 3; function createChartPositiveNegative(chartId, operations, theme) { function datekey(op) { let d = op.budgetDate; return `${d.getFullYear()} - ${d.getMonth()}`; } const POS = 0, NEG = 1, BAL = 2; // Type -> color let colorMap = {}; // Month -> [Positive amount, Negative amount, Diff] let map = new Map(); // Datekey -> Date let dateset = new Map(); for (let i = 0; i < operations.length; i++) { let op = operations[i]; let dk = datekey(op); map.set(dk, map.get(dk) || [0, 0, 0]); let triplet = map.get(dk); triplet[POS] += op.amount > 0 ? op.amount : 0; triplet[NEG] += op.amount < 0 ? -op.amount : 0; triplet[BAL] += op.amount; dateset.set(dk, +op.budgetDate); } // Sort date in ascending order: push all pairs of (datekey, date) in an // array and sort that array by the second element. Then read that array in // ascending order. let dates = Array.from(dateset); dates.sort((a, b) => a[1] - b[1]); let series = []; function addSerie(name, mapIndex, color) { let data = []; for (let j = 0; j < dates.length; j++) { let dk = dates[j][0]; data.push(round2(map.get(dk)[mapIndex])); } let serie = [name].concat(data); series.push(serie); colorMap[name] = color; } const wellsColors = getWellsColors(theme); addSerie($t('client.charts.received'), POS, wellsColors.RECEIVED); addSerie($t('client.charts.spent'), NEG, wellsColors.SPENT); addSerie($t('client.charts.saved'), BAL, wellsColors.SAVED); let categories = []; for (let i = 0; i < dates.length; i++) { let date = new Date(dates[i][1]); // Undefined means the default locale let defaultLocale; let str = date.toLocaleDateString(defaultLocale, { year: '2-digit', month: 'short' }); categories.push(str); } // Show last ${SUBCHART_EXTENT} months in the subchart. let lowExtent = Math.max(dates.length, SUBCHART_EXTENT) - SUBCHART_EXTENT; let highExtent = dates.length; let yAxisLegend = $t('client.charts.amount'); return c3.generate({ bindto: chartId, data: { columns: series, type: 'bar', colors: colorMap }, bar: { width: { ratio: 0.5 } }, axis: { x: { type: 'category', extent: [lowExtent, highExtent], categories, tick: { fit: false } }, y: { label: yAxisLegend } }, grid: { x: { show: true }, y: { show: true, lines: [{ value: 0 }] } }, size: { height: CHART_SIZE }, subchart: { show: true, size: { height: SUBCHART_SIZE } }, zoom: { rescale: true } }); } class BarChart extends ChartComponent { redraw() { this.container = createChartPositiveNegative( `#${this.props.chartId}`, this.props.operations, this.props.theme ); } render() { return <div id={this.props.chartId} style={{ width: '100%' }} />; } } const ALL_CURRENCIES = ''; class InOutChart extends React.Component { constructor(props) { super(props); this.state = { currency: ALL_CURRENCIES }; } handleCurrencyChange = event => { this.setState({ currency: event.target.value }); }; render() { let currenciesOptions = []; let currencyCharts = []; for (let [currency, transactions] of this.props.currencyToTransactions) { currenciesOptions.push( <option key={currency} value={currency}> {currency} </option> ); if (this.state.currency !== ALL_CURRENCIES && this.state.currency !== currency) { continue; } let maybeTitle = null; if (this.state.currency === ALL_CURRENCIES) { maybeTitle = <h3>{currency}</h3>; } currencyCharts.push( <div key={currency}> {maybeTitle} <BarChart chartId={`barchart-${currency}`} operations={transactions} theme={this.props.theme} /> </div> ); } let maybeCurrencySelector = null; if (currenciesOptions.length > 1) { maybeCurrencySelector = ( <p> <select className="form-element-block" onChange={this.handleCurrencyChange} defaultValue={this.state.currency}> <option value={ALL_CURRENCIES}>{$t('client.charts.all_currencies')}</option> {currenciesOptions} </select> </p> ); } return ( <React.Fragment> {maybeCurrencySelector} {currencyCharts} </React.Fragment> ); } } InOutChart.propTypes = { // The transactions per currencies. currencyToTransactions: PropTypes.instanceOf(Map).isRequired, // The current theme. theme: PropTypes.string.isRequired }; const Export = connect((state, ownProps) => { let currentAccountIds = get.accountIdsByAccessId(state, ownProps.accessId); let currencyToTransactions = new Map(); for (let accId of currentAccountIds) { let currency = get.accountById(state, accId).currency; if (!currencyToTransactions.has(currency)) { currencyToTransactions.set(currency, []); } let transactions = get.operationsByAccountId(state, accId); currencyToTransactions.get(currency).push(...transactions); } let theme = get.setting(state, 'theme'); return { currencyToTransactions, theme }; })(InOutChart); export default Export;
src/components/voteDialog/voteDialog.js
slaweet/lisk-nano
import React from 'react'; import { authStatePrefill, authStateIsValid } from '../../utils/form'; import ActionBar from '../actionBar'; import AuthInputs from '../authInputs'; import Autocomplete from './voteAutocomplete'; import Fees from '../../constants/fees'; import InfoParagraph from '../infoParagraph'; import VoteUrlProcessor from '../voteUrlProcessor'; import styles from './voteDialog.css'; import votingConst from '../../constants/voting'; import { getTotalVotesCount, getNewVotesCount } from '../../utils/voting'; const { maxCountOfVotes, maxCountOfVotesInOneTurn } = votingConst; export default class VoteDialog extends React.Component { constructor() { super(); this.state = authStatePrefill(); } componentDidMount() { this.setState(authStatePrefill(this.props.account)); } confirm(event) { event.preventDefault(); this.props.votePlaced({ activePeer: this.props.activePeer, account: this.props.account, votes: this.props.votes, secondSecret: this.state.secondPassphrase.value, passphrase: this.state.passphrase.value, }); } handleChange(name, value, error) { this.setState({ [name]: { value, error: typeof error === 'string' ? error : null, }, }); } render() { const { votes } = this.props; const countOfVotesInOneTurn = getNewVotesCount(votes); return ( <article> <form id='voteform'> <VoteUrlProcessor /> <Autocomplete votedDelegates={this.props.delegates} votes={this.props.votes} voteToggled={this.props.voteToggled} activePeer={this.props.activePeer} /> <AuthInputs passphrase={this.state.passphrase} secondPassphrase={this.state.secondPassphrase} onChange={this.handleChange.bind(this)} /> <article className={styles.info}> <InfoParagraph> <p > {this.props.t('You can select up to {{count}} delegates in one voting turn.', { count: maxCountOfVotesInOneTurn })} </p> <p > {this.props.t('You can vote for up to {{count}} delegates in total.', { count: maxCountOfVotes })} </p> </InfoParagraph> </article> <ActionBar secondaryButton={{ onClick: this.props.closeDialog, }} primaryButton={{ label: this.props.t('Confirm'), onClick: this.confirm.bind(this), fee: Fees.vote, type: 'button', disabled: ( getTotalVotesCount(votes) > maxCountOfVotes || countOfVotesInOneTurn === 0 || countOfVotesInOneTurn > maxCountOfVotesInOneTurn || !authStateIsValid(this.state) ), }} /> </form> </article> ); } }
src/icons/StrokeClock.js
ipfs/webui
import React from 'react' const StrokeClock = props => ( <svg viewBox='0 0 100 100' {...props}> <path d='M52.42 15.92A34.08 34.08 0 1 0 86.49 50a34.12 34.12 0 0 0-34.07-34.08zm0 65.16A31.08 31.08 0 1 1 83.49 50a31.11 31.11 0 0 1-31.07 31.08z' /> <path d='M76.78 57.91A4.6 4.6 0 0 0 74.61 56l-17.83-8v.06a4.16 4.16 0 0 0-.35-.7l5.16-4.75-1-1.1L55.65 46V32.11a3.23 3.23 0 0 0-6.45 0v14.31a4.63 4.63 0 0 0-.58 6.07l-8.67 8a3.36 3.36 0 0 0-4.81 4.41l-2.5 2.29 1 1.11 2.49-2.3a3.39 3.39 0 0 0 1.57.63h.41a3.36 3.36 0 0 0 2.89-5.1l8.69-8a4.56 4.56 0 0 0 4.69.47L72 61.88a4.84 4.84 0 0 0 1.93.42 3.2 3.2 0 0 0 3-1.74 2.94 2.94 0 0 0-.15-2.65zM50.7 32.11a1.73 1.73 0 0 1 3.45 0v13.36a4.56 4.56 0 0 0-1.73-.34 4.66 4.66 0 0 0-1.72.33zM40 63.49a1.88 1.88 0 0 1-2.09 1.64A1.89 1.89 0 0 1 36.24 63a1.89 1.89 0 0 1 1.86-1.66h.23A1.88 1.88 0 0 1 40 63.49zm9.28-13.7A3.17 3.17 0 1 1 52.42 53a3.17 3.17 0 0 1-3.17-3.21zM75.59 60c-.38.85-1.75 1.11-3 .56L55.79 53a4.66 4.66 0 0 0 1.29-3.2L74 57.36a3.06 3.06 0 0 1 1.46 1.27 1.47 1.47 0 0 1 .13 1.37z' /> </svg> ) export default StrokeClock
src/layouts/CoreLayout/CoreLayout.js
traptrilliams/kings
import React from 'react'; import classes from './CoreLayout.scss'; import '../../styles/core.scss'; export const CoreLayout = ({ children }) => ( <div className={classes.mainContainer}> {children} </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
modules/RestoreWindowScroll.js
jshin49/react-router-restore-scroll
import React from 'react' import PropTypes from 'prop-types'; import createReactClass from 'create-react-class' const RestoreWindowScroll = createReactClass({ propTypes: { restoreWindow: PropTypes.func.isRequired, location: PropTypes.object.isRequired }, componentDidMount() { this.props.restoreWindow(this.props.location) }, componentDidUpdate(prevProps) { if (prevProps.location !== this.props.location) this.props.restoreWindow(this.props.location) }, render() { return React.Children.only(this.props.children) } }) export default RestoreWindowScroll
spec/javascripts/jsx/blueprint_courses/components/LockBannerSpec.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import * as enzyme from 'enzyme' import LockBanner from 'jsx/blueprint_courses/components/LockBanner' QUnit.module('LockBanner component') const defaultProps = () => ({ isLocked: true, itemLocks: { content: true, points: false, due_dates: false, availability_dates: false, }, }) test('renders an Alert when LockBanner is locked', () => { const props = defaultProps() props.isLocked = true const tree = enzyme.mount(<LockBanner {...props} />) const node = tree.find('Alert') ok(node.exists()) }) test('does not render Alert when LockBanner is locked', () => { const props = defaultProps() props.isLocked = false const tree = enzyme.mount(<LockBanner {...props} />) const node = tree.find('Alert') notOk(node.exists()) }) test('displays locked description text appropriately when one attribute is locked', () => { const props = defaultProps() const tree = enzyme.mount(<LockBanner {...props} />) const text = tree.find('Typography').at(1).text() equal(text, 'Content') }) test('displays locked description text appropriately when two attributes are locked', () => { const props = defaultProps() props.itemLocks.points = true const tree = enzyme.mount(<LockBanner {...props} />) const text = tree.find('Typography').at(1).text() equal(text, 'Content & Points') }) test('displays locked description text appropriately when more than two attributes are locked', () => { const props = defaultProps() props.itemLocks.points = true props.itemLocks.due_dates = true const tree = enzyme.mount(<LockBanner {...props} />) const text = tree.find('Typography').at(1).text() equal(text, 'Content, Points & Due Dates') })
app/javascript/mastodon/features/ui/components/columns_area.js
theoria24/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 TabsBar, { links, getIndex, getLink } from './tabs_bar'; import { Link } from 'react-router-dom'; import { disableSwiping } from 'mastodon/initial_state'; 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, BookmarkedStatuses, ListTimeline, Directory, } from '../../ui/util/async-components'; import Icon from 'mastodon/components/icon'; import ComposePanel from './compose_panel'; import NavigationPanel from './navigation_panel'; import { supportsPassiveEvents } from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'REMOTE': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'DIRECT': DirectTimeline, 'FAVOURITES': FavouritedStatuses, 'BOOKMARKS': BookmarkedStatuses, 'LIST': ListTimeline, 'DIRECTORY': Directory, }; const messages = defineMessages({ publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, }); const shouldHideFAB = path => path.match(/^\/statuses\/|^\/@[^/]+\/\d+|^\/publish|^\/explore|^\/getting-started|^\/start/); 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, }; // Corresponds to (max-width: 600px + (285px * 1) + (10px * 1)) in SCSS mediaQuery = 'matchMedia' in window && window.matchMedia('(max-width: 895px)'); state = { shouldAnimate: false, renderComposePanel: !(this.mediaQuery && this.mediaQuery.matches), } componentWillReceiveProps() { if (typeof this.pendingIndex !== 'number' && this.lastIndex !== getIndex(this.context.router.history.location.pathname)) { this.setState({ shouldAnimate: false }); } } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false); } if (this.mediaQuery) { if (this.mediaQuery.addEventListener) { this.mediaQuery.addEventListener('change', this.handleLayoutChange); } else { this.mediaQuery.addListener(this.handleLayoutChange); } this.setState({ renderComposePanel: !this.mediaQuery.matches }); } 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, supportsPassiveEvents ? { passive: true } : false); } const newIndex = getIndex(this.context.router.history.location.pathname); if (this.lastIndex !== newIndex) { this.lastIndex = newIndex; this.setState({ shouldAnimate: true }); } } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } if (this.mediaQuery) { if (this.mediaQuery.removeEventListener) { this.mediaQuery.removeEventListener('change', this.handleLayoutChange); } else { this.mediaQuery.removeListener(this.handleLayouteChange); } } } handleChildrenContentChange() { if (!this.props.singleColumn) { const modifier = this.isRtlLayout ? -1 : 1; this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier); } } handleLayoutChange = (e) => { this.setState({ renderComposePanel: !e.matches }); } 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'); if (!this.state.shouldAnimate && typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } 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 columns-area--mobile' 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, renderComposePanel } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); if (singleColumn) { const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/publish' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><Icon id='pencil' /></Link>; const content = columnIndex !== -1 ? ( <ReactSwipeableViews key='content' hysteresis={0.2} threshold={15} index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }} disabled={disableSwiping}> {links.map(this.renderView)} </ReactSwipeableViews> ) : ( <div key='content' className='columns-area columns-area--mobile'>{children}</div> ); return ( <div className='columns-area__panels'> <div className='columns-area__panels__pane columns-area__panels__pane--compositional'> <div className='columns-area__panels__pane__inner'> {renderComposePanel && <ComposePanel />} </div> </div> <div className='columns-area__panels__main'> <TabsBar key='tabs' /> {content} </div> <div className='columns-area__panels__pane columns-area__panels__pane--start columns-area__panels__pane--navigational'> <div className='columns-area__panels__pane__inner'> <NavigationPanel /> </div> </div> {floatingActionButton} </div> ); } 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/components/Input/Input.stories.js
Mojja/Gojji
import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import Input from './Input' storiesOf('Input', module).add('default', () => ( <Input label="label" placeholder="bonsoir" value="" onChange={action('onChange')} required /> ))
client/src/index.js
SillySalamanders/Reactivity
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import App from './components/app.jsx'; import NotFound from './components/NotFound.jsx'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> </Route> <Route path="*" component={NotFound} /> </Router>, document.getElementById('app'));
test/test_helper.js
RaulEscobarRivas/client
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/svg-icons/av/web.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvWeb = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/> </SvgIcon> ); AvWeb = pure(AvWeb); AvWeb.displayName = 'AvWeb'; AvWeb.muiName = 'SvgIcon'; export default AvWeb;
actor-apps/app-web/src/app/components/modals/InviteUser.react.js
VikingDen/actor-platform
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ActorClient from 'utils/ActorClient'; import { KeyCodes } from 'constants/ActorAppConstants'; import InviteUserActions from 'actions/InviteUserActions'; import InviteUserByLinkActions from 'actions/InviteUserByLinkActions'; import ContactStore from 'stores/ContactStore'; import InviteUserStore from 'stores/InviteUserStore'; import ContactItem from './invite-user/ContactItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return ({ contacts: ContactStore.getContacts(), group: InviteUserStore.getGroup(), isOpen: InviteUserStore.isModalOpen() }); }; const hasMember = (group, userId) => undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId); @ReactMixin.decorate(IntlMixin) class InviteUser extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = _.assign({ search: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); InviteUserStore.addChangeListener(this.onChange); ContactStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { InviteUserStore.removeChangeListener(this.onChange); ContactStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { InviteUserActions.hide(); }; onContactSelect = (contact) => { ActorClient.inviteMember(this.state.group.id, contact.uid); }; onInviteUrlByClick = () => { InviteUserByLinkActions.show(this.state.group); InviteUserActions.hide(); }; onKeyDown = (event) => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onSearchChange = (event) => { this.setState({search: event.target.value}); }; render() { const contacts = this.state.contacts; const isOpen = this.state.isOpen; let contactList = []; if (isOpen) { _.forEach(contacts, (contact, i) => { const name = contact.name.toLowerCase(); if (name.includes(this.state.search.toLowerCase())) { if (!hasMember(this.state.group, contact.uid)) { contactList.push( <ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/> ); } else { contactList.push( <ContactItem contact={contact} key={i} member/> ); } } }, this); } if (contactList.length === 0) { contactList.push( <li className="contacts__list__item contacts__list__item--empty text-center"> <FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/> </li> ); } return ( <Modal className="modal-new modal-new--invite contacts" closeTimeoutMS={150} isOpen={isOpen} style={{width: 400}}> <header className="modal-new__header"> <a className="modal-new__header__icon material-icons">person_add</a> <h4 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/> </h4> <div className="pull-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onClose} secondary={true} style={{marginTop: -6}}/> </div> </header> <div className="modal-new__body"> <div className="modal-new__search"> <i className="material-icons">search</i> <input className="input input--search" onChange={this.onSearchChange} placeholder={this.getIntlMessage('inviteModalSearch')} type="search" value={this.state.search}/> </div> <a className="link link--blue" onClick={this.onInviteUrlByClick}> <i className="material-icons">link</i> {this.getIntlMessage('inviteByLink')} </a> </div> <div className="contacts__body"> <ul className="contacts__list"> {contactList} </ul> </div> </Modal> ); } } export default InviteUser;
imports/ui/components/DocumentsList.js
zarazi/movies-listie
import React from 'react'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import { ListGroup, ListGroupItem, Alert } from 'react-bootstrap'; import { Meteor } from 'meteor/meteor'; import Documents from '../../api/documents/documents'; import container from '../../modules/container'; const handleNav = _id => browserHistory.push(`/documents/${_id}`); const DocumentsList = ({ documents }) => ( documents.length > 0 ? <ListGroup className="DocumentsList"> {documents.map(({ _id, title, released, rating }) => ( <ListGroupItem key={ _id } onClick={ () => handleNav(_id) }> { title } { released } [{ rating }] </ListGroupItem> ))} </ListGroup> : <Alert bsStyle="warning">No documents yet.</Alert> ); DocumentsList.propTypes = { documents: PropTypes.array, }; export default container((props, onData) => { const subscription = Meteor.subscribe('documents.list'); if (subscription.ready()) { const documents = Documents.find({},{sort:{released:-1}}).fetch(); onData(null, { documents }); } }, DocumentsList);
src/svg-icons/image/timer-10.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimer10 = (props) => ( <SvgIcon {...props}> <path d="M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 2.39.19.66.45 1.19.8 1.6.34.41.75.71 1.23.89.48.18 1.01.28 1.59.28.59 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .58.06.81.17.24.11.44.29.6.55.16.25.29.58.37.99.08.41.13.92.13 1.52v2.51z"/> </SvgIcon> ); ImageTimer10 = pure(ImageTimer10); ImageTimer10.displayName = 'ImageTimer10'; ImageTimer10.muiName = 'SvgIcon'; export default ImageTimer10;
app/javascript/mastodon/features/follow_requests/components/account_authorize.js
MastodonCloud/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Permalink from '../../../components/permalink'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ authorize: { id: 'follow_request.authorize', defaultMessage: 'Authorize' }, reject: { id: 'follow_request.reject', defaultMessage: 'Reject' }, }); @injectIntl export default class AccountAuthorize extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onAuthorize: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { intl, account, onAuthorize, onReject } = this.props; const content = { __html: account.get('note_emojified') }; return ( <div className='account-authorize__wrapper'> <div className='account-authorize'> <Permalink href={account.get('url')} to={`/accounts/${account.get('id')}`} className='detailed-status__display-name'> <div className='account-authorize__avatar'><Avatar account={account} size={48} /></div> <DisplayName account={account} /> </Permalink> <div className='account__header__content' dangerouslySetInnerHTML={content} /> </div> <div className='account--panel'> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.authorize)} icon='check' onClick={onAuthorize} /></div> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.reject)} icon='times' onClick={onReject} /></div> </div> </div> ); } }
src/ui/components/views/Core/Icon.js
scrollback/pure
/* @flow */ import React, { Component } from 'react'; import ReactNative from 'react-native'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import shallowCompare from 'react-addons-shallow-compare'; const { Text, } = ReactNative; type Props = { style?: any; } export default class Icon extends Component<void, Props, void> { static propTypes = { style: Text.propTypes.style, }; shouldComponentUpdate(nextProps: Props, nextState: any): boolean { return shallowCompare(this, nextProps, nextState); } setNativeProps(nativeProps: Props) { this._root.setNativeProps(nativeProps); } _root: Object; render() { return ( <MaterialIcons ref={c => (this._root = c)} allowFontScaling={false} {...this.props} /> ); } }
src/components/FriendsList.js
Tasemu/Simple-PGP
import React, { Component } from 'react'; import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react'; import { css, StyleSheet } from 'aphrodite'; import { Link } from 'react-router'; import { colours } from 'utils/constants'; import Friend from 'components/Friend'; import Menu from 'components/ui/Menu'; const componentStyles = StyleSheet.create({ friendsList: { width: 300, height: '100%', display: 'flex', flexDirection: 'column', borderRight: `1px solid ${colours.white}`, }, list: { margin: 0, padding: 0, flexGrow: 1, overflowY: 'auto', }, }); @inject('appStore') @observer export default class FriendsList extends Component { static propTypes = { appStore: MobxPropTypes.objectOrObservableObject.isRequired, } render() { const { friends } = this.props.appStore; const friendComponents = friends.map(f => ( <Friend key={f.id} friend={f} /> )); return ( <div className={css(componentStyles.friendsList)}> <ul className={css(componentStyles.list)}> {friendComponents} </ul> <Menu /> </div> ); } }
src/components/app.js
nicolasthy/showify-electron
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchUser } from '../actions/index'; import Header from './header'; import Sidebar from './sidebar'; import Friends from './friends/friends_list'; class App extends Component { componentWillMount(){ this.props.fetchUser(); } componentWillUpdate(nextProps) { if(this.props.user.id !== nextProps.user.id) { this.props.fetchUser(); } } render() { if(Object.keys(this.props.user).length > 0){ return ( <div> <Header /> <Sidebar /> <Friends /> {React.cloneElement(this.props.children, { user: this.props.user })} </div> ); } return <div>Loading ...</div>; } } function mapStateToProps(state){ return { user: state.user.all }; } export default connect(mapStateToProps, { fetchUser })(App);
example/src/screens/transitions/sharedElementTransitions/Masonry/Item.js
MattDavies/react-native-navigation
import React from 'react'; import { StyleSheet, View, Text, Image } from 'react-native'; import { SharedElementTransition } from 'react-native-navigation'; const SHOW_DURATION = 240; const HIDE_DURATION = 200; class Item extends React.Component { static navigatorStyle = { navBarHidden: true, drawUnderNavBar: true }; render() { return ( <View style={styles.container}> <SharedElementTransition sharedElementId={this.props.sharedImageId} showDuration={SHOW_DURATION} hideDuration={HIDE_DURATION} animateClipBounds showInterpolation={{ type: 'linear', easing: 'FastInSlowOut', }} hideInterpolation={{ type: 'linear', easing: 'FastOutSlowIn', }} > <Image style={styles.image} source={this.props.image} /> </SharedElementTransition> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffffff', justifyContent: 'center', }, image: { width: 400, height: 400, } }); export default Item;
src/components/common/svg-icons/action/zoom-in.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; ActionZoomIn.muiName = 'SvgIcon'; export default ActionZoomIn;
src/lib/subscribeTo.js
6congyao/CGB-Dashboard
/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. */ import ParseApp from 'lib/ParseApp'; import React from 'react'; import * as StoreManager from 'lib/stores/StoreManager'; export default function subscribeTo(name, prop) { return function(Component) { const store = StoreManager.getStore(name); const displayName = Component.displayName || Component.name || 'Component'; class SubscribedComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { data: store.getData(context.currentApp) }; } handleNewData(data) { if (this.state.data !== data) { this.setState({ data }); } } componentWillReceiveProps(nextProps, nextContext) { this.setState({ data: store.getData(nextContext.currentApp) }); } componentWillMount() { this.subscriptionId = store.subscribe(this.handleNewData.bind(this)); } componentWillUnmount() { store.unsubscribe(this.subscriptionId); } render() { let dispatch = (type, params={}) => { if (store.isGlobal) { return store.dispatch(type, params); } return store.dispatch(type, params, this.context.currentApp); }; let extras = { [prop]: { data: this.state.data, dispatch: dispatch, } }; return <Component {...this.props} {...extras} />; } } SubscribedComponent.displayName = `subscribeTo(${displayName})`; SubscribedComponent.contextTypes = { currentApp: React.PropTypes.instanceOf(ParseApp), generatePath: React.PropTypes.func, }; // In case you need to add static properties to the original Component SubscribedComponent.original = Component; return SubscribedComponent; } }
app/javascript/mastodon/components/regeneration_indicator.js
masto-donte-com-br/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import illustration from 'mastodon/../images/elephant_ui_working.svg'; const RegenerationIndicator = () => ( <div className='regeneration-indicator'> <div className='regeneration-indicator__figure'> <img src={illustration} alt='' /> </div> <div className='regeneration-indicator__label'> <FormattedMessage id='regeneration_indicator.label' tagName='strong' defaultMessage='Loading&hellip;' /> <FormattedMessage id='regeneration_indicator.sublabel' defaultMessage='Your home feed is being prepared!' /> </div> </div> ); export default RegenerationIndicator;
src/components/SideBar.js
numieco/patriot-trading
import React from 'react' import { Link } from 'react-router-dom' import axios from 'axios' import GooglePlay from './../Svg/GooglePlay' import ITunes from './../Svg/ITunes' import Podcasts from './../Svg/Podcasts' import YouTube from './../Svg/YouTube' import QuestionMarkLogo from './../Svg/QuestionMarkLogo' import { FacebookButton, TwitterButton } from './SocialMediaButtons' import ArrowSVG from './../Svg/ArrowSVG' import Loading from './../components/Loading' import SinglePostArticle from './SinglePostArticle' // import requestAllPosts from '../helpers/requestAllPosts' import loadBlogs from '../helpers/loadBlogs' import requestAllTags from '../helpers/requestAllTags' const moment = require('moment') const ghostSecret = require('../ghost-secret') const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] export default class SideBar extends React.Component { constructor (props) { super (props) this.state = { isArchiveTrue: window.innerWidth > 902 ? true : false, archiveMonthsElement: [], windowInnerWidth: window.innerWidth, saleScrollHeight: 0, saleStyleClass: 'shop-gold', isMounted: true, salePost: '', isLoaded: false, postWithoutLink: [] } this.handleArchiveClick = this.handleArchiveClick.bind(this) this.handleWindowScroll = this.handleWindowScroll.bind(this) this.handleWindowResize = this.handleWindowResize.bind(this) this.calculateMonths = this.calculateMonths.bind(this) } componentWillMount () { /* this.calculateMonths(this.props.posts) */ loadBlogs() .then(this.processBlogs) .catch((error) => { console.log(error) }) this.calculateMonths() window.addEventListener('resize', this.handleWindowResize) requestAllTags().then((list) => { console.log(list.tags[list.tags.length - 1]) this.setState({ salePost: list.tags[list.tags.length - 1], isLoaded: true }) document.getElementsByTagName("body")[0].style.overflow = 'scroll' }) } // componentDidMount () { // requestAllTags().then((list) => { // this.setState({ // salePost: list.tags[list.tags.length - 1], // isLoaded: true // }) // document.getElementsByTagName("body")[0].style.overflow = 'scroll' // }) // } componentWillReceiveProps (nextProps, nextState) { // this.calculateMonths(nextProps.posts) window.addEventListener('scroll', this.handleWindowScroll) this.setState({ isLoaded: true }) } componentWillUnmount () { window.removeEventListener('scroll', this.handleWindowScroll) window.removeEventListener('resize', this.handleWindowResize) } processBlogs = (result) => { let postWithoutLink = [] result.posts.map((post, i) => { if (!(window.location.pathname === '/' && i === 0) && !(window.location.pathname.slice(6) === post.slug)) { postWithoutLink.push(<SinglePostArticle post={ post } key={ i } />) } }) this.setState({ postWithoutLink }) } handleWindowResize = (event) => { this.setState({ windowInnerWidth: window.innerWidth }, () => { if (this.state.windowInnerWidth > 902) { this.setState({ isArchiveTrue: true }) } }) } handleWindowScroll = (event) => { if(document.getElementsByClassName('sidebar-container')[0] && this.state.isMounted){ this.setState({ saleScrollHeight: document.getElementsByClassName('sidebar-container')[0].getBoundingClientRect().bottom }, () => { let saleDiv = document.getElementById('sale') let saleDivHeight = saleDiv.getBoundingClientRect().bottom - saleDiv.getBoundingClientRect().top + 20 + 20 if (this.state.saleStyleClass == 'shop-gold') { if((this.state.saleScrollHeight - saleDivHeight) <= 0) { this.setState({ saleStyleClass: 'shop-gold position-top-right' }) } else { this.setState({ saleStyleClass: 'shop-gold' }) } } else { if(this.state.saleScrollHeight <= 0) { this.setState({ saleStyleClass: 'shop-gold position-top-right' }) } else { this.setState({ saleStyleClass: 'shop-gold' }) } } }) } } calculateMonths = (posts) => { let startDate = moment([2017, 5, 1]) let today = moment().startOf('month') let startMonth = startDate.startOf('month').subtract('M', 1) let archiveMonthsElement = [] while(!today.isSame(startMonth)) { archiveMonthsElement.push(<div key={today.month() + today.year()}> <Link to={ '/archive/' + months[today.month()] + today.year() } onClick={ this.handleArchiveClick } > <div className='archive-month-name' > { months[today.month()] + ' ' + today.year() } </div> </Link> </div>) today.subtract('M', 1) } this.setState({ archiveMonthsElement: archiveMonthsElement }) /* let archiveMonthsElement = posts.map((post, i) => { // if (post.id === 1) // this.setState({ salePost: post }) const date = new Date(post.published_at) if(archiveMonths.indexOf(months[date.getMonth()] + ' ' + date.getFullYear()) == -1) { archiveMonths.push(months[date.getMonth()] + ' ' + date.getFullYear()) return ( <div key={i}> <Link to={ '/archive/' + months[date.getMonth()] + date.getFullYear() } onClick={ this.handleArchiveClick } > <div className='archive-month-name' > { months[date.getMonth()] + ' ' + date.getFullYear() } </div> </Link> </div> ) } }) this.setState({ archiveMonthsElement: archiveMonthsElement }) */ } handleArchiveClick = () => { if (this.state.windowInnerWidth > 902) this.setState({ isArchiveTrue: true }) else this.setState({ isArchiveTrue: !this.state.isArchiveTrue }) } render () { return ( <div> { this.state.isLoaded ? null : <Loading /> } <div className='call-us'> <div className='contact-number'> Questions? Call us: <a className='telephone' href='tel:800-951-0592'>800-951-0592</a> </div> <div className='address'> Patriot Trading Group 2010 W. Parkside Lane Suite 154 <br/> Phoenix, AZ 85027 </div> </div> { this.state.windowInnerWidth <= 902 ? ( <div id='sale' className='shop-gold'> <a target='_blank' href={this.state.salePost.meta_description ? this.state.salePost.meta_description : ''}> <img alt='Shop Gold !' src={this.state.salePost.feature_image ? ghostSecret.domain + this.state.salePost.feature_image : ''}></img> <div className='shop-gold-text'> { this.state.salePost.name ? this.state.salePost.name : '' } </div> </a> </div> ) : null } <div className='links-container'> <div className='links-title'> <h2>Links</h2> </div> <a target='_blank' href='https://play.google.com/music/listen?u=0&pli=1#/ps/Ixismx55psqfi7w6gro5zfqzo4e' > <div className='links-element links-element-google-play'> <div className='google-play-logo'> <GooglePlay /> </div> Google Play <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <a target='_blank' href='https://itunes.apple.com/us/podcast/patriot-radio-news-hour/id1052349670?mt=2' > <div className='links-element links-element-itunes'> <div className='itunes-logo'> <ITunes /> </div> iTunes Podcast <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <a target='_blank' href='https://omny.fm/shows/patriot-radio-news-hour' > <div className='links-element links-element-podcasts'> <div className='podcasts-logo'> <Podcasts /> </div> FM Podcast <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <a target='_blank' href='https://www.youtube.com/channel/UCaiLjnohYLdbf4Lu99v6kbw' > <div className='links-element links-element-youtube'> <div className='youtube-logo'> <YouTube /> </div> { this.state.windowInnerWidth > 768 ? 'Patriot Radio News Hour - YouTube' : 'Patriot Radio - YouTube' } <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <a target='_blank' href='https://www.facebook.com/allamericangold/'> <div className='links-element like-us-on-fb'> <div className='fb-image'> <FacebookButton color="#FFFFFF" bgColor='#405A94'/> </div> Like us on Facebook <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <a target='_blank' href='https://twitter.com/PatriotTrading1'> <div className='links-element follow-on-twitter'> <div className='twitter-image'> <TwitterButton color='#00a0ef' /> </div> Follow us on Twitter <div className='arrow-svg'> <ArrowSVG /> </div> </div> </a> <Link to={'/faq'} > <div className='links-element links-element-question'> <div className='question-logo'> <QuestionMarkLogo /> </div> Frequently Asked Questions <div className='arrow-svg'> <ArrowSVG /> </div> </div> </Link> </div> <div className='more-articals-container'> <div className='more-articals-title'> <h2>More Articles</h2> </div> { this.state.postWithoutLink } </div> <div className='archive-button' onClick={ this.handleArchiveClick }> <div className='archive-button-text'> <h2>Archives</h2> </div> <div className={ this.state.isArchiveTrue ? 'arrow-svg rotate-svg' : 'arrow-svg' } > <ArrowSVG /> </div> </div> { this.state.isArchiveTrue ? ( <div className='archive-months'> { this.state.archiveMonthsElement } </div> ) : null } { this.state.windowInnerWidth > 902 ? ( <div id='sale' className={ this.state.saleStyleClass }> <a target='_blank' href={this.state.salePost.meta_description ? this.state.salePost.meta_description : ''}> <img alt='Shop Gold !' src={this.state.salePost.feature_image ? (ghostSecret.domain + this.state.salePost.feature_image) : ''}></img> <div className='shop-gold-text'> { this.state.salePost.name ? this.state.salePost.name : '' } </div> </a> </div> ) : null } </div> ) } }
src/routes/Spots/components/SpotEditForm/SchoolsField.js
ZeusTheTrueGod/WindsurfingNetwork-client
// @flow import React from 'react'; import _ from 'lodash-es'; import { type SimpleSchool } from '../../modules/spots'; import { AddSchool } from './AddSchool'; import { ListGroup, ListGroupItem, Media, Button, Glyphicon } from 'react-bootstrap'; export type Option = {| id: number, name: string, disabled: boolean |}; const getSelectedSchools = (selectedSchools: number[], allSchools: SimpleSchool[]): SimpleSchool[] => { return _.map(selectedSchools, function (id: number) { const school = _.find(allSchools, { id: id }); if (!school) { throw new Error('School not present in the list'); } return school; }); }; const getSchoolsAsOptions = (selectedSchools: number[], allSchools: SimpleSchool[]) => { return _.map(allSchools, (school: SimpleSchool) => ({ id: school.id, name: school.name, disabled: _.includes(selectedSchools, school.id), })); }; type Props = {| fields: any, schoolsList: SimpleSchool[], |}; export const SchoolsField = ({ fields, schoolsList }: Props): React$Element<any> => { const list = getSelectedSchools(fields.getAll(), schoolsList); const options = getSchoolsAsOptions(fields.getAll(), schoolsList); return ( <div> <ListGroup> {list.map((school: SimpleSchool, index: number) => ( <ListGroupItem key={index}> <Media> <Media.Left> <img width={64} height={64} src={`/api/usercontent/${school.logo}`} /> </Media.Left> <Media.Body> {school.name} </Media.Body> <Media.Right> <Button onClick={() => fields.remove(index)}><Glyphicon glyph='trash' /></Button> </Media.Right> </Media> </ListGroupItem> ))} </ListGroup> <AddSchool options={options} onAdd={(id: number) => fields.push(id)} /> </div> ); };
app/src/stories/card.js
Staffjoy/v2
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import DragDropContextMock from './mock/DragDropContextMock'; import Card from '../components/Scheduling/ShiftWeekTable/Section/Row/Card'; storiesOf('Card') .add('default', () => { return ( <DragDropContextMock> <Card columnId={'42'} timezone={'America/Los_Angeles'} shiftStart={'2016-01-01'} shiftStop={'2016-01-01'} shiftUuid={'42'} jobUuid={'42'} userUuid={'42'} viewBy={'yolo'} employees={{}} jobs={{}} deleteTeamShift={() => {}} toggleSchedulingModal={() => {}} modalFormData={() => {}} updateSchedulingModalFormData={() => {}} clearSchedulingModalFormData={() => {}} editTeamShift={() => {}} published={false} /> </DragDropContextMock> ); });
src/App.js
QuackenbushDev/reactTodo
import React, { Component } from 'react'; import TodoList from './components/TodoList'; import TodoCounter from './components/TodoCounter'; import TodoFilter from './components/TodoFilter'; import TodoClearCompleted from './components/TodoClearCompleted'; export class App extends Component { constructor(props) { super(props); this.handleTextUpdate = this.handleTextUpdate.bind(this); this.toggleTodoState = this.toggleTodoState.bind(this); this.changeTodoFilter = this.changeTodoFilter.bind(this); this.clearCompletedTodos = this.clearCompletedTodos.bind(this); } componentDidMount() { if (window.localStorage.getItem('todos')) { this.setState({ todos: JSON.parse(window.localStorage.getItem('todos')), filter: 'All' }); return; } this.init(); } init() { var todos = [ { id: 0, text: "Taste JavaScript", completed: true, editing: false }, { id: 1, text: "Buy a unicorn", completed: false, editing: false }, { id: 2, text: "Kick Roberto's arse!", completed: false, editing: true } ]; this.setState({todos: todos}); this.save(); } save() { window.localStorage.setItem('todos', JSON.stringify(this.state.todos)); } addTodo(text) { var todos = this.state.todos; todos.push({ id: Math.random * 10000, text: text, completed: false, editing: false }); this.setState({todos: todos}); this.save(); } handleTextUpdate(id, value) { } toggleTodoState(id, type) { var todos = []; this.state.todos.forEach(function(todo) { if (todo.id == id) { switch (type) { case "completed": todo.completed = !todo.completed; break; case "editing": todo.editing = !todo.editing; break; } } todos.push(todo); }); this.setState({ todos: todos }); this.save(); } changeTodoFilter(filter) { this.setState({filter: filter}); } clearCompletedTodos() { var todos = []; this.state.todos.forEach(function(todo) { if (todo !== null && !todo.completed) { todos.push(todo); } }); this.setState({todos: todos}); this.save(); } render() { return <div> <section className="todoapp"> <header className="header"> <h1>todos</h1> <input className="new-todo" placeholder="What needs to be done?" autofocus /> </header> <section className="main"> <input className="toggle-all" type="checkbox" /> <TodoList todos={this.state.todos} handleTextUpdate={this.handleTextUpdate} toggleTodoState={this.toggleTodoState} filter={this.state.filter} /> </section> <footer className="footer"> <TodoCounter todos={this.state.todos} /> <TodoFilter changeTodoFilter={this.changeTodoFilter} activeFilter={this.state.filter} /> <TodoClearCompleted clearCompletedTodos={this.clearCompletedTodos} /> </footer> </section> <footer className="info"> <p>Double-click to edit a todo</p> <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p> <p>Created by <a href="mailto:christopher@quackenbush.me">Christopher Quackenbush</a></p> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p> </footer> </div> } }
src/CalculatorLabel1/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ProgressBar from '../ProgressBar'; import LabelSmall from '../LabelSmall'; import Spacer from '../Spacer'; import Tooltip from '../Tooltip'; import Typography from '../Typography'; import styles from './styles.css'; function CalculatorLabel1(props) { const goalPosition = (props.goalValue / props.maxValue) * 100; const progressPercent = (props.value / props.maxValue) * 100; return ( <Tooltip placement="top" text={props.toolTipText} > <div className={props.size === 'wide' ? styles.wrapper_wide : styles.wrapper_standard}> <ProgressBar className={classNames(styles.progressBar)} color={props.barColor} percent={progressPercent} size={props.size || "standard"} > <div className={classNames(styles.progressWrapper)}> <Spacer size="standard" /> {props.valueDescription ? <div className={classNames(styles.metaWrapper)}> <LabelSmall className={classNames(styles.labelCurrent)} content={props.value} icon={props.iconCurrent} onclick={props.onClickCo2} /> <Typography className={classNames(styles.caption)} type="caption2Normal" > {props.valueDescription} </Typography> </div> : null } <div className={classNames(styles.goalMarkerWrapper)} style={{left: `${goalPosition}%`}} > <div className={classNames(styles.goalMarker, { [styles.goalMarkerStandard]: props.size === "standard" || !props.size, [styles.goalMarkerWide]: props.size === "wide" })} /> <Spacer size="standard" /> <LabelSmall className={classNames(styles.goalLabel)} content={props.goalValue} icon={props.iconGoal} onclick={props.onClickGoal} /> </div> </div> </ProgressBar> </div> </Tooltip> ); } CalculatorLabel1.propTypes = { barColor: PropTypes.string, goalValue: PropTypes.number, iconCurrent: PropTypes.string, iconGoal: PropTypes.string, maxValue: PropTypes.number, onClickCo2: PropTypes.func, onClickGoal: PropTypes.func, size: PropTypes.oneOf(['standard', 'wide']), toolTipText: PropTypes.string, value: PropTypes.number, valueDescription: PropTypes.string }; export default CalculatorLabel1;
internals/templates/app.js
polymattic/nnsb-calculator
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/js/components/routes/Canvas.react.js
teamUndefined/creativity
import React from 'react'; import { FloatingActionButton, ActionGrade } from 'material-ui'; var Canvas = React.createClass({ componentDidMount() { var self = this; $('#canvas').attr('width', $('.canvas-wrapper').width()); $(window).resize(function() { $('#canvas').attr('width', $('.canvas-wrapper').width()); }); this.props.socket.on('update_canvas', function(action) { // get scketch and redraw var sketch = $("#canvas").sketch(); sketch.actions.push(action); sketch.redraw(); }); this.props.socket.on('clear_canvas', function(action) { // get scketch and redraw var sketch = $("#canvas").sketch(); sketch.actions = []; sketch.redraw(); }); $('#canvas').sketch(); // limit canvas update to 24 fps var canCall = true; setInterval(function(){ canCall = true; }, 42); $('.canvas-wrapper canvas').on('mouseup touchmove mousemove touchend touchcancel', function() { var action = $(this).sketch().action; if (canCall && action) { self.props.socket.emit('server_update_canvas', action); canCall = false; } }); }, clearCanvas() { var self = this; var sketch = $("#canvas").sketch(); sketch.actions = []; sketch.redraw(); self.props.socket.emit('server_clear_canvas'); }, render() { return ( <div className="canvas-wrapper"> <canvas id="canvas" width="450" height="400"></canvas> <div className="tools"> <a href="#canvas" className="color-pill" data-color="#000000" title="Black"><span style={{backgroundColor: "#000000"}}></span></a> <a href="#canvas" className="color-pill" data-color="#1abc9c" title="Green"><span style={{backgroundColor: "#1abc9c"}}></span></a> <a href="#canvas" className="color-pill" data-color="#2980b9" title="Blue"><span style={{backgroundColor: "#2980b9"}}></span></a> <a href="#canvas" className="color-pill" data-color="#8e44ad" title="Purple"><span style={{backgroundColor: "#8e44ad"}}></span></a> <a href="#canvas" className="color-pill" data-color="#c0392b" title="Red"><span style={{backgroundColor: "#c0392b"}}></span></a> <a href="#canvas" className="color-pill" data-color="#f1c40f" title="Yellow"><span style={{backgroundColor: "#f1c40f"}}></span></a> <a href="#canvas" className="color-pill" data-color="#ffffff" title="White"><span style={{backgroundColor: "#ffffff", border: "1px solid #aaa"}}></span></a> <div className="clear-btn-wrapper"> <FloatingActionButton onClick={this.clearCanvas} mini={true}> <i className="fa fa-refresh"></i> </FloatingActionButton> </div> </div> </div> ) } }); export default Canvas;
app/javascript/mastodon/features/community_timeline/components/column_settings.js
lindwurm/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} /> </div> </div> ); } }
react-flux-mui/js/material-ui/src/svg-icons/editor/show-chart.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorShowChart = (props) => ( <SvgIcon {...props}> <path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z"/> </SvgIcon> ); EditorShowChart = pure(EditorShowChart); EditorShowChart.displayName = 'EditorShowChart'; EditorShowChart.muiName = 'SvgIcon'; export default EditorShowChart;
src/app/components/Main.js
arraqib/react-weather
import React from 'react'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import Paper from 'material-ui/Paper' import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import NavigationMenus from 'material-ui/svg-icons/navigation/menu'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Nav from './Nav'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); const Main = (props) => { let paperStyle = { width: "90%", minHeight: 600, margin: '0 auto', textAlign: 'center' } let navLink = ( <IconMenu iconButtonElement={<IconButton iconStyle={{color: '#ffffff'}}><NavigationMenus /></IconButton>}> <Nav /> </IconMenu>) return ( <MuiThemeProvider style={{paddingTop: 0}}> <div> <Paper style={paperStyle}> <AppBar style={{textAlign: 'left'}} title="Weather App" iconElementLeft={navLink}/> {props.children} </Paper> </div> </MuiThemeProvider> ) } export default Main;
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/components/AuthComponent.js
advantys/workflowgen-templates
import React, { Component } from 'react'; import { Text, Button } from 'react-native'; import PropTypes from 'prop-types'; import { Container } from '.'; import { CommonStyles } from './styles'; class AuthComponent extends Component { render () { return ( <Container style={CommonStyles.centerContent}> <Text>Native Application Example</Text> <Text>You don't seem to be connected.</Text> <Button title='Log In' onPress={this.props.onLoginButtonPress} /> </Container> ); } } AuthComponent.propTypes = { onLoginButtonPress: PropTypes.func }; AuthComponent.defaultTypes = { onLoginButtonPress: () => {} }; export default AuthComponent;
blueocean-material-icons/src/js/components/svg-icons/navigation/more-horiz.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NavigationMoreHoriz = (props) => ( <SvgIcon {...props}> <path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); NavigationMoreHoriz.displayName = 'NavigationMoreHoriz'; NavigationMoreHoriz.muiName = 'SvgIcon'; export default NavigationMoreHoriz;
src/options.js
chocolateorange/new-post.crx
// eslint-disable-next-line no-unused-vars import React from 'react'; import ReactDOM from 'react-dom'; import { combineReducers, createStore, } from 'redux'; import { Provider, } from 'react-redux'; import { loadValues, } from './modules/storage'; import { reducer as configReducer, } from './redux/config'; import { reducer as buttonReducer, } from './redux/button'; import App from './components/App'; (async function(){ const reducers = combineReducers({ button: buttonReducer, config: configReducer, }); const initialState = { config: await loadValues(), }; let devToolsEnhancer; // NOTE: don't cache condition. UglifyJSPlugin cannot eliminate module if (process.env.NODE_ENV !== 'production') { devToolsEnhancer = require('remote-redux-devtools').default; } const store = // NOTE: don't cache condition. UglifyJSPlugin cannot eliminate module (process.env.NODE_ENV === 'production') ? createStore(reducers, initialState) : createStore(reducers, initialState, devToolsEnhancer({ realtime: true, actionSanitizer(action) { // serialize Symbol return (typeof action.type === 'symbol') ? Object.assign({}, action, { type: String(action.type).slice(7, -1), }) : action; }, })); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') ); }());
src/svg-icons/editor/money-off.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMoneyOff = (props) => ( <SvgIcon {...props}> <path d="M12.5 6.9c1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-.53.12-1.03.3-1.48.54l1.47 1.47c.41-.17.91-.27 1.51-.27zM5.33 4.06L4.06 5.33 7.5 8.77c0 2.08 1.56 3.21 3.91 3.91l3.51 3.51c-.34.48-1.05.91-2.42.91-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c.96-.18 1.82-.55 2.45-1.12l2.22 2.22 1.27-1.27L5.33 4.06z"/> </SvgIcon> ); EditorMoneyOff = pure(EditorMoneyOff); EditorMoneyOff.displayName = 'EditorMoneyOff'; EditorMoneyOff.muiName = 'SvgIcon'; export default EditorMoneyOff;
client/src/Assistant/ApartmentFeatureInputs/BuildingFeatures.js
ciex/mietlimbo
// @flow import React from 'react' import { injectIntl, defineMessages, FormattedMessage } from 'react-intl' import { CardText } from 'material-ui/Card' import FeatureInput from './FeatureInput' import CheckboxInput from './CheckboxInput' import type { RangeInputProps } from './RangeSelectionGroup' import EnergyClass from './EnergyFeatures' import './Styles.css' export const EntranceCondition = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.EntranceCondition', defaultMessage: 'Das Treppenhaus bzw. der Eingangsbereich sind überwiegend in schlechtem Zustand.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="EntranceCondition" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const DoorLock = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.DoorLock', defaultMessage: 'Die Hauseingangstür ist nicht abschließbar.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="DoorLock" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const RepresentativeEntrance = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.RepresentativeEntrance', defaultMessage: 'Eingansbereich oder Treppenhaus hochwertig saniert oder repräsentativ.' }, explanation: { id: 'Building.RepresentativeEntranceExamples', defaultMessage: 'z.B. Spiegel, Marmor, exklusive Beleuchtung, hochwertiger Anstrich/Wandbelag, Läufer im gesamten Flur- und Treppenbereich' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="RepresentativeEntrance" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} > <CardText> <p> <FormattedMessage {...messages.explanation} /> </p> </CardText> </FeatureInput> }) export const WellMaintained = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.WellMaintained', defaultMessage: 'Das Gebäude, bzw. der Teil davon, in dem sich die Wohnung befindet, ist in einem überdurchschnittlichen Instandhaltungszustand (z.B. erneuerte Fassade, Dach).' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="WellMaintained" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const LowMaintenance = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.LowMaintenance', defaultMessage: 'Schlechter Instandhaltungszustand ' }, explanation: { id: 'Building.LowMaintenanceExamples', defaultMessage: 'Z.B. dauernde Durchfeuchtung des Mauerwerks - auch Keller -, große Putzschäden, erhebliche Schäden an der Dacheindeckung.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="LowMaintenance" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} > <CardText> <p> <FormattedMessage {...messages.explanation} /> </p> </CardText> </FeatureInput> }) export const NoStorageRoom = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.NoStorageRoom', defaultMessage: 'Kein Mieterkeller oder Kellerersatzraum zur alleinigen Nutzung des Mieters vorhanden' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="NoStorageRoom" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const BicycleRoom = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.BicycleRoom', defaultMessage: 'Fahrradabstellraum oder Fahrradabstellplätze' }, explanation: { id: 'Building.BicycleRoomExplanation', defaultMessage: `Ein solcher Raum muss innerhalb des Gebäudes, abschließbar und leicht zugänglich sein. Fahrradabstellplätze müssen eine Anschließmöglichkeit bieten und sich außerhalb des Gebäudes auf dem Grundstück befinden.` } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="BicycleRoom" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} > <CardText> <p> <FormattedMessage {...messages.explanation} /> </p> </CardText> </FeatureInput> }) export const CommunalSpace = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.CommunalSpace', defaultMessage: 'Es gibt zusätzliche und in angemessenem Umfang nutzbare Räume außerhalb der Wohnung in fußläufiger Entfernung (z.B. Partyraum)' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="CommunalSpace" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const SideWing = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.SideWing', defaultMessage: 'Lage im Seitenflügel oder Quergebäude bei verdichteter Bebauung.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="SideWing" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const NoLift = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.NoLift', defaultMessage: 'Die Wohnung liegt im 5. Stock oder höher und es gibt keinen Personenaufzug.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="NoLift" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const Lift = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.Lift', defaultMessage: 'Es gibt einen Personenaufzug bei weniger als fünf Obergeschossen.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="Lift" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const NoIntercom = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.NoIntercom', defaultMessage: 'Es gibt keine Gegen-/Wechselsprechanlage mit elektrischem Türöffner.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="NoIntercom" positive={false} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const IntercomVideo = injectIntl((props: RangeInputProps) => { const messages = defineMessages({ title: { id: 'Building.IntercomVideo', defaultMessage: 'Die Gegen-/Wechselsprechanlage bietet Videoübertragung und elektrischem Türöffner.' } }) return <FeatureInput title={<CheckboxInput changed={props.changed} name="IntercomVideo" positive={true} message={props.intl.formatMessage(messages.title)} value={props.value} />} /> }) export const Energy = injectIntl(EnergyClass)
Mr.Mining/MikeTheMiner/Santas_helpers/Sia_wallet/resources/app/plugins/Wallet/js/components/app.js
patel344/Mr.Miner
import React from 'react' import LockScreen from '../containers/lockscreen.js' import Wallet from '../containers/wallet.js' const WalletApp = () => ( <div className="app"> <LockScreen /> <Wallet /> </div> ) export default WalletApp
src/views/Home.js
jomarquez21/resource_center
import React, { Component } from 'react'; import {Card, CardTitle, CardText} from 'material-ui/Card'; class Home extends Component { render() { return ( <div className="container"> <div className="row"> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> </div> <div className="row"> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> <div className="col s12 m4"> <Card> <CardTitle title="Card title" subtitle="Card subtitle" /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> </div> </div> </div> ) } } export default Home
src/component/ToDoListWithFlux/TodoBody.react.js
lyc-chengzi/reactProject
/** * Created by liuyc14 on 2016/9/26. */ import React from 'react'; import TodoAction from '../../flux/actions/TodoAction'; import TodoItem from './TodoItem.react'; export default class TodoBody extends React.Component{ constructor(props){ super(props); this.toggleAllCompleteHandler = this.toggleAllCompleteHandler.bind(this); } render(){ let todos = this.props.allTodos; if(Object.keys(todos).length < 1){ return null; } let list = []; for (var key in todos) { list.push(<TodoItem key={key} todo={todos[key]} />); } return( <section id="main"> <input id="toggle-all" type="checkbox" onChange={this.toggleAllCompleteHandler} defaultChecked={this.props.areAllCompleted ? 'checked' : ''}/> <label htmlFor="toggle-all">完成所有</label> <ul id="todo-list">{list}</ul> </section> ); } toggleAllCompleteHandler(){ TodoAction.toggleCompleteAll(); } } TodoBody.propTypes = { allTodos: React.PropTypes.object.isRequired, areAllComplete: React.PropTypes.bool.isRequired };
src/server.js
kla1nfun/reduxtodo
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, {target: targetUrl}); }); app.use('/ws', (req, res) => { proxy.web(req, res, {target: targetUrl + '/ws'}); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, client); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/components/measurables.js
marcusdarmstrong/mockdraftable-web
// @flow import React from 'react'; import type { MeasurablePercentile } from '../types/graphing'; type DisplayableMeasurement = MeasurablePercentile & { display: string }; type Props = { measurements: DisplayableMeasurement[], }; export default ({ measurements }: Props) => ( <table className="table table-sm mb-0"> <thead> <tr> <th>Measurable</th> <th>Measurement</th> <th>%tile</th> </tr> </thead> <tbody> {measurements.map(m => ( <tr key={m.measurable.id}> <td>{m.measurable.name}</td> <td>{m.display}</td> <td>{m.percentile}</td> </tr> ))} </tbody> </table> );
src/pages/404.js
green-arrow/ibchamilton
import React from 'react' const NotFoundPage = () => ( <div> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </div> ) export default NotFoundPage
src/components/video_list.js
iAmNawa/ReactJS
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return ( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} /> ) }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
src/index.js
xyc/react-inspector
export { chromeLight, chromeDark } from './styles/themes'; export ObjectInspector from './object-inspector/ObjectInspector'; export TableInspector from './table-inspector/TableInspector'; export DOMInspector from './dom-inspector/DOMInspector'; export ObjectLabel from './object-inspector/ObjectLabel'; export ObjectPreview from './object-inspector/ObjectPreview'; export ObjectRootLabel from './object-inspector/ObjectRootLabel'; export ObjectValue from './object/ObjectValue'; export ObjectName from './object/ObjectName'; // Wrapping the inspectors import ObjectInspector from './object-inspector/ObjectInspector'; import TableInspector from './table-inspector/TableInspector'; import DOMInspector from './dom-inspector/DOMInspector'; import React from 'react'; import PropTypes from 'prop-types'; import isDOM from 'is-dom'; const Inspector = ({ table = false, data, ...rest }) => { if (table) { return <TableInspector data={data} {...rest} />; } if (isDOM(data)) return <DOMInspector data={data} {...rest} />; return <ObjectInspector data={data} {...rest} />; }; Inspector.propTypes = { data: PropTypes.any, name: PropTypes.string, table: PropTypes.bool, }; export { Inspector }; export default Inspector;
packages/core/src/icons/components/InlineDropdown.js
iCHEF/gypcrete
import React from 'react'; export default function SvgInlineDropdown(props) { return ( <svg width="1em" height="1em" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <path d="M0 0l28 16L0 32V0z" fill="currentColor" /> </svg> ); }
src/organisms/layout/index.js
dsmjs/components
import React from 'react'; import {string, node} from 'prop-types'; import Header from '../../molecules/header'; import Footer from '../footer'; import {fontFamily, fontSize} from '../../styles'; import layoutStyles from '../../layoutStyles.json'; export default function Layout({sponsor, location, children}) { return ( <div css={{fontFamily, fontSize, maxWidth: 1000, margin: '1em auto', backgroundColor: '#fff'}}> <Header sponsor={sponsor} location={location} /> <div css={{padding: `0 ${layoutStyles.innerGutterWidth}px`}}> {children} </div> <Footer /> </div> ); } Layout.propTypes = { sponsor: string.isRequired, location: string.isRequired, children: node };
packages/material-ui-icons/src/NotificationsPaused.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.93 6 11v5l-2 2v1h16v-1l-2-2zm-3.5-6.2l-2.8 3.4h2.8V15h-5v-1.8l2.8-3.4H9.5V8h5v1.8z" /></g> , 'NotificationsPaused');
app/js/app.js
hollandben/assets-monitor
import React from 'react'; import AssetList from './assetList'; const assetMonitor = React.createClass({ render() { return <AssetList />; } }); React.render(React.createElement(assetMonitor), document.getElementById('app'));
src/svg-icons/image/looks-one.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooksOne = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14h-2V9h-2V7h4v10z"/> </SvgIcon> ); ImageLooksOne = pure(ImageLooksOne); ImageLooksOne.displayName = 'ImageLooksOne'; ImageLooksOne.muiName = 'SvgIcon'; export default ImageLooksOne;
react-flux-mui/js/material-ui/src/svg-icons/navigation/arrow-forward.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowForward = (props) => ( <SvgIcon {...props}> <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"/> </SvgIcon> ); NavigationArrowForward = pure(NavigationArrowForward); NavigationArrowForward.displayName = 'NavigationArrowForward'; NavigationArrowForward.muiName = 'SvgIcon'; export default NavigationArrowForward;
react_demo/app/components/detail/index.js
Zhang-xiaohui/react-demo
import React from 'react' import HeaderComponent from '../common/header/header.js' import FooterComponent from '../common/footer/footer.js' export default class DetailComponent extends React.Component { constructor(props) { super(props); this.state = { data: [] } } render() { return ( <div className="main"> <HeaderComponent /> <div className="data-content"> { this.state.data.map((value, key)=>{ return ( <div className="data-content-cart" key={value.id}> <img src={value.imgSrc} /> <h3>{value.title}</h3> <p dangerouslySetInnerHTML={{__html: value.content}}></p> </div> ) }) } </div> <div>{this.props.params.id}</div> <FooterComponent /> </div> ) } componentDidMount() { let link = "article.json?id=" + this.props.params.id; fetch(link) .then((response) => response.json()) .then((json) => { let data = json.data; this.setState({ data: data }) console.log(data) }) .catch((ex) => { console.log('parsing failed', ex) }) } }
src/svg-icons/content/content-paste.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentContentPaste = (props) => ( <SvgIcon {...props}> <path d="M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z"/> </SvgIcon> ); ContentContentPaste = pure(ContentContentPaste); ContentContentPaste.displayName = 'ContentContentPaste'; ContentContentPaste.muiName = 'SvgIcon'; export default ContentContentPaste;
CounterList/Counter.js
xgrommx/elm-architecture-using-ramda-and-flyd
import React from 'react'; import R from 'ramda'; import flyd from 'flyd'; import {genActions} from '../ActionsGen/ActionsGen'; //Model const initialModel = 0; //-∆≣ type Action = Increment | Decrement //const action = { // increment() { // return { // type: 'Increment' // } // }, // decrement() { // return { // type: 'Decrement' // } // } //}; //-∆≣ type Action = Increment | Decrement const Action = genActions([['Increment'], ['Decrement']]); //-∆≣ update :: Model -> Action -> Model function update(model, action) { switch (action.type) { case 'Increment': return model + 1; case 'Decrement': return model - 1; default: return model; } } //-∆≣ init :: Integer -> Model function init(v) { return v; } //-∆≣ actions :: FlydStream Action const actions = flyd.stream(); const model = flyd.scan(update, initialModel, actions); //view should be FlydStream Action -> Model -> ReactDOM //-∆≣ view :: FlydStream Action -> Model -> React.Component class CounterView extends React.Component { shouldComponentUpdate(props){ return this.props.model !== props.model; } render() { let {stream, model} = this.props; return ( <div> <p>{model}</p> <button onClick={stream.bind(null, {type: 'Increment'})}>+</button> <button onClick={stream.bind(null, {type: 'Decrement'})}>-</button> </div> ) } } class CounterViewWithRemoveButton extends React.Component { shouldComponentUpdate(props){ return this.props.model !== props.model; } render() { let {model, context} = this.props; return ( <div> <CounterView stream={context.actions} model={model}/> <button onClick={context.remove}>Remove</button> </div> ) } } export default { init, update, model, CounterView, CounterViewWithRemoveButton }
src/components/withViewport.js
wanchopen/vida
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport} />; } handleResize(value) { this.setState({ viewport: value }); } }; } export default withViewport;