path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/subjects/BookSubjectIndex.js
great-design-and-systems/cataloguing-app
import { BookSubjectList } from './BookSubjectList'; import PropTypes from 'prop-types'; import React from 'react'; export const BookSubjectIndex = ({ removeSubject, managedBook, subjects }) => { return (<div className="subjects"> <BookSubjectList removeSubject={removeSubject} subjects={subjects} managedBook={managedBook} /> </div>); }; BookSubjectIndex.propTypes = { removeSubject: PropTypes.func.isRequired, managedBook: PropTypes.object.isRequired, subjects: PropTypes.array.isRequired };
app/App.js
munir7/react
import React from 'react'; import Router from 'react-router'; import routes from './config/routes'; Router.run(routes, (Root, state) => { React.render(<Root {...state} />, document.getElementById('app')); });
src/Input.js
collinwu/react-bootstrap
import React from 'react'; import InputBase from './InputBase'; import * as FormControls from './FormControls'; import deprecationWarning from './utils/deprecationWarning'; class Input extends InputBase { render() { if (this.props.type === 'static') { deprecationWarning('Input type=static', 'StaticText'); return <FormControls.Static {...this.props} />; } return super.render(); } } Input.propTypes = { type: React.PropTypes.string }; export default Input;
benchmarks/src/index.js
rofrischmann/fela
import App from './app/App' import impl from './impl' import Tree from './cases/Tree' import SierpinskiTriangle from './cases/SierpinskiTriangle' import React from 'react' import ReactDOM from 'react-dom' const implementations = impl const packageNames = Object.keys(implementations) const createTestBlock = (fn) => { return packageNames.reduce((testSetups, packageName) => { const { name, components, version } = implementations[packageName] const { Component, getComponentProps, sampleCount, Provider, benchmarkType, } = fn(components) testSetups[packageName] = { Component, getComponentProps, sampleCount, Provider, benchmarkType, version, name, } return testSetups }, {}) } const tests = { 'Mount deep tree': createTestBlock((components) => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 2, components, depth: 7, id: 0, wrap: 1, }), Provider: components.Provider, sampleCount: 200, })), 'Mount wide tree': createTestBlock((components) => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 6, components, depth: 3, id: 0, wrap: 2, }), Provider: components.Provider, sampleCount: 200, })), 'Update dynamic styles': createTestBlock((components) => ({ benchmarkType: 'update', Component: SierpinskiTriangle, getComponentProps: ({ cycle }) => { return { components, s: 200, renderCount: cycle, x: 0, y: 0 } }, Provider: components.Provider, sampleCount: 300, })), } ReactDOM.render(<App tests={tests} />, document.querySelector('.root'))
src/ElevationCatalog.js
material-components/material-components-web-catalog
import React, { Component } from 'react'; import ComponentCatalogPanel from './ComponentCatalogPanel.js'; import './styles/ElevationCatalog.scss'; const MAX_ELEVATION_LEVELS = 24; const ElevationCatalog = () => { const description = 'Elevation is the relative depth, or distance, between two surfaces along the z-axis.'; return ( <ComponentCatalogPanel hero={<ElevationHero />} title='Elevation' description={description} designLink='https://material.io/go/design-elevation' docsLink='https://material.io/components/web/catalog/elevation/' sourceLink='https://github.com/material-components/material-components-web/tree/master/packages/mdc-elevation' demos={<ElevationDemos />} /> ); }; export class ElevationHero extends Component { render() { return ( <div className='elevation-hero'> <div className='elevation-demo-surface mdc-elevation--z0'> Flat 0dp </div> <div className='elevation-demo-surface mdc-elevation--z8'> Raised 8dp </div> <div className='elevation-demo-surface mdc-elevation--z16'> Raised 16dp </div> </div> ); } } class ElevationDemos extends Component { render() { return ( <div className='elevation-demo-container'> {this.getElevationDemos()} </div> ); } getElevationDemos() { let demos = []; for(let x = 0; x <= MAX_ELEVATION_LEVELS; x++) { demos.push( <div key={'elevation' + x} className={'elevation-demo-surface mdc-elevation--z' + x}> {x}dp </div>); } return demos; } } export default ElevationCatalog;
assets/js/components/Item.js
scottocorp/react-todos
import React from 'react'; var createReactClass = require('create-react-class'); const Item = createReactClass({ handleOnChange(e) { const content = e.target.value; this.props.updateTodo(this.props.todo.id, content); }, handleKeyUp(e) { if (e.keyCode == 13) { this.close(e.target.value); } }, handleOnBlur(e) { this.close(e.target.value); }, close(value) { if (!value) { this.props.removeTodo(this.props.todo.id) } else { this.props.viewTodo(this.props.todo.id) } }, componentDidUpdate() { if (this.props.todo.editing){ this.refs.input.focus(); } }, render() { const { todo, i } = this.props; var style = (todo.editing) ? "editing" : ""; style = (todo.completed) ? style + " completed" : style; style = style.trim(); return ( <li className={style} onDoubleClick={this.props.editTodo.bind(null, todo.id)} > <div className="view"> <input className="toggle" checked={ todo.completed } type="checkbox" onClick={this.props.toggleComplete.bind(null, todo.id)} /> <label>{ todo.content }</label> <button className="destroy" onClick={this.props.removeTodo.bind(null, todo.id)}></button> </div> <input type="text" name="content" className="edit" ref="input" value={ todo.content } onChange={this.handleOnChange} onKeyUp={this.handleKeyUp} onBlur={this.handleOnBlur} /> </li> ) } }); export default Item;
src/svg-icons/notification/confirmation-number.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
js/components/Nav.react.js
Karaja-Naji/frontEndMusic
/** * * Nav.react.js * * This component renders the navigation bar * */ import React, { Component } from 'react'; import { Link } from 'react-router'; import { logout } from '../actions/AppActions'; import LoadingButton from './LoadingButton.react'; class Nav extends Component { render() { // Render either the Log In and register buttons, or the logout button // based on the current authentication state. const navButtons = this.props.loggedIn ? ( <div> <Link to="/dashboard" className="btn btn--dash btn--nav">Dashboard</Link> {this.props.currentlySending ? ( <LoadingButton className="btn--nav" /> ) : ( <a href="#" className="btn btn--login btn--nav" onClick={::this._logout}>Logout</a> )} </div> ) : ( <div> <Link to="/register" className="btn btn--login btn--nav">Register</Link> <Link to="/login" className="btn btn--login btn--nav">Login</Link> </div> ); return( <div className="nav"> <div className="nav__wrapper"> <Link to="/" className="nav__logo-wrapper"><h1 className="nav__logo">Login&nbsp;Flow</h1></Link> <Link to="/blogs" className="btn btn--login btn--nav">Blogs</Link> <Link to="/products" className="btn btn--login btn--nav">Products</Link> { navButtons } </div> </div> ); } _logout() { this.props.dispatch(logout()); } } Nav.propTypes = { loggedIn: React.PropTypes.bool.isRequired, currentlySending: React.PropTypes.bool.isRequired } export default Nav;
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-slider.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import Environment from '../environment/environment.js'; import {BaseMixin, ElementaryMixin, ContentMixin, Tools} from './../common/common.js'; import {Glyphicon, Slider} from './../bricks/bricks.js'; import InputMixin from './input-mixin.js'; import Number from './number.js'; import './slider.less'; export default React.createClass({ mixins: [ BaseMixin, ElementaryMixin, ContentMixin, InputMixin ], statics: { tagName: 'UU5.Forms.Slider', classNames: { main: 'uu5-forms-slider', inputGroup: 'uu5-forms-slider-input-group', slider: 'uu5-forms-slider-slider', number: 'uu5-forms-slider-number' } }, propTypes: { colorSchema: React.PropTypes.oneOf(Environment.colorSchema), // TODO //position: React.PropTypes.oneOf(['horizontal', 'vertical']), min: React.PropTypes.number, max: React.PropTypes.number, step: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func, onChanged: React.PropTypes.func }, // Setting defaults getDefaultProps: function () { return { colorSchema: 'primary', //position: 'horizontal', min: 0, max: 10, step: 1, value: null, onChanged: null }; }, componentWillMount: function () { this.setState({ value: typeof this.props.value === 'number' ? this.props.value : this.props.min }); }, // Interface // Overriding Functions setValue_: function (value, setStateCallback, options) { options = options || {}; options.feedback = options.feedback || 'initial'; options.message = options.message || ''; options.value = value; this.setState(options, setStateCallback); return this; }, // Component Specific Helpers // _onChange: function (e) { // if (!this.isDisabled()) { // var value = !this.getValue(); // var newState = this._validateValue(value); // // if (newState) { // this.setState(newState); // } else { // if (this.props.onChange) { // this.props.onChange({ value: value, input: this, event: e }); // } else { // this.setState({ value: value }); // } // } // } // return this; // }, _getMainAttrs: function () { return this.getInputMainAttrs(); }, _getInputGroupAttrs: function () { return { className: this.getClassName().inputGroup }; }, _getSliderProps: function () { return { name: this.getName(), className: this.getClassName().slider, colorSchema: this.props.colorSchema, //position: 'horizontal', min: this.props.min, max: this.props.max, step: this.props.step, value: this.getValue() === null ? this.props.min : this.getValue(), content: this.getContent(), onChange: this._onChange, onChanged: this.props.onChanged, disabled: this.isDisabled() }; }, _getNumberProps: function () { var value = this.getValue(); value = value > this.props.max ? this.props.max : (value < this.props.min) ? this.props.min : value; return { className: this.getClassName().number, min: this.props.min, max: this.props.max, value: this.getValue(), onChange: this._onChange, onBlur: function (opt) { if (this.getValue() < this.props.min) { opt.component.setValue(this.props.min); } else if (this.getValue() > this.props.max) { opt.component.setValue(this.props.max); } }.bind(this), disabled: this.isDisabled(), onChangeFeedback: this._onChangeNumberFeedback }; }, _getOnChanged: function (value, e) { var onChanged; if (typeof this.props.onChanged === 'function') { var slider = this; onChanged = function () { slider.props.onChanged({ value: value, component: slider, event: e }); }; } return onChanged; }, _onChange: function (opt) { if (!this.isDisabled()) { if (typeof this.props.onChange == 'function') { this.props.onChange(Tools.merge({}, opt, { component: this })); } else { this.setFeedback('initial', '', opt.value, this._getOnChanged(opt.value, opt.event)); } } return this; }, _onChangeNumberFeedback: function (opt) { this.setValue(opt.value ? +opt.value : null, opt.callback); //this.setFeedback(opt.feedback, opt.message, opt.value ? +opt.value : null, opt.callback); return this; }, // Render render: function () { return ( <div {...this._getMainAttrs()}> {this.getLabelChild()} <div {...this.getInputWrapperAttrs()}> <div {...this._getInputGroupAttrs()}> <Slider {...this._getSliderProps()}> {this.props.children && React.Children.toArray(this.props.children)} </Slider> <Number {...this._getNumberProps()} /> </div> {this.getMessageChild()} </div> </div> ); } });
packages/editor/src/components/Controls/FontFamily/FontFamilyLayout.js
boldr/boldr
/* eslint-disable react/no-array-index-key */ /* @flow */ import React from 'react'; import type { Node } from 'react'; import cn from 'classnames'; import { Dropdown, DropdownOption } from '../../Dropdown'; import type { FontFamilyConfig } from '../../../core/config'; export type Props = { expanded: boolean, onExpandEvent: Function, doExpand: Function, doCollapse: Function, onChange: Function, config: FontFamilyConfig, currentState: any, }; type State = { defaultFontFamily: string, }; class FontFamilyLayout extends React.Component<Props, State> { state = { defaultFontFamily: undefined, }; componentDidMount(): void { const editorElm = document.getElementsByClassName('DraftEditor-root'); if (editorElm && editorElm.length > 0) { const styles = window.getComputedStyle(editorElm[0]); const defaultFontFamily = styles.getPropertyValue('font-family'); this.setDefaultFam(defaultFontFamily); } } setDefaultFam = defaultFont => { this.setState({ defaultFontFamily: defaultFont, }); }; props: Props; render(): Node { const { defaultFontFamily } = this.state; const { config: { options, title }, onChange, expanded, doCollapse, onExpandEvent, doExpand, } = this.props; let { currentState: { fontFamily: currentFontFamily } } = this.props; currentFontFamily = currentFontFamily || (options && defaultFontFamily && options.some(opt => opt.toLowerCase() === defaultFontFamily.toLowerCase()) && defaultFontFamily); return ( <div className={cn('be-ctrl__group')} aria-label="be-fontfamily-control"> <Dropdown onChange={onChange} expanded={expanded} doExpand={doExpand} ariaLabel="be-dropdown-fontfamily-control" doCollapse={doCollapse} onExpandEvent={onExpandEvent} title={title}> <span className={cn('be-fontfamily__ph')}>{currentFontFamily || 'Font Family'}</span> {options.map((family, index) => ( <DropdownOption active={currentFontFamily === family} value={family} key={index}> {family} </DropdownOption> ))} </Dropdown> </div> ); } } export default FontFamilyLayout;
docs/app/Examples/modules/Accordion/Usage/AccordionExamplePanelsPropWithCustomTitleAndContent.js
aabustamante/Semantic-UI-React
import React from 'react' import { Accordion, Label, Message } from 'semantic-ui-react' import faker from 'faker' import _ from 'lodash' const panels = _.times(3, i => ({ key: `panel-${i}`, title: <Label color='blue' content={faker.lorem.sentence()} />, content: ( <Message info header={faker.lorem.sentence()} content={faker.lorem.paragraph()} /> ), })) const AccordionExamplePanelsPropWithCustomTitleAndContent = () => ( <Accordion panels={panels} /> ) export default AccordionExamplePanelsPropWithCustomTitleAndContent
node_modules/npm/docs/src/components/DocLinks.js
giovannic/giovannic.github.com
import React from 'react' import styled from 'styled-components' import {StaticQuery, graphql} from 'gatsby' import {Flex} from 'rebass' import {SidebarLink} from './links' import Accordion from './Accordion' const LinkDesc = styled.span` font-size: 11px; line-height: 1.5; text-transform: lowercase; display: block; font-weight: 400; color: ${(props) => props.theme.colors.darkGray}; ` const DocLinks = ({data}) => { const linkInfo = data.allMarkdownRemark.nodes const sections = ['cli-commands', 'configuring-npm', 'using-npm'] let sortedData = {} sections.map((section) => ( sortedData[section] = linkInfo.filter(function (item) { return item.frontmatter.section === section }) )) return sections.map((section, index) => ( <Accordion key={index} section={section}> {sortedData[section].map((linkData, index) => { const title = section === 'cli-commands' ? linkData.frontmatter.title.replace(/(npm-)+([a-zA-Z\\.-]*)/, 'npm $2') : linkData.frontmatter.title return ( <Flex flexDirection='column' key={index}> <SidebarLink to={`${linkData.fields.slug}`} activeClassName='active-sidebar-link' > {title} <LinkDesc>{linkData.frontmatter.description}</LinkDesc> </SidebarLink> </Flex> ) }) } </Accordion> )) } export default props => ( <StaticQuery query={graphql` query sortedLinkData { allMarkdownRemark(sort: {fields: frontmatter___title}) { nodes { fields { slug } frontmatter { description section title } } } } `} render={data => <DocLinks data={data} {...props} />} /> )
app/components/shared/filtersControl.js
nypl-registry/browse
import React from 'react' import { Link } from 'react-router' import { stringify } from 'qs' const FiltersControl = React.createClass({ propTypes () { return { } }, queryStringWithoutFilter (field, value) { // copy query & filters: var newQuery = Object.assign({}, this.props.query) newQuery.filters = Object.assign({}, this.props.query.filters) // If filter is an array of values: if (typeof newQuery.filters[field] === 'object') { // Remove value from array: newQuery.filters[field] = newQuery.filters[field].filter((otherValue) => otherValue !== value) // Remove field entirely if array empty: if (newQuery.filters[field].length === 0) delete newQuery.filters[field] } else { // Remove field entirely delete newQuery.filters[field] } return newQuery }, render () { var links = [] Object.keys(this.props.query.filters).forEach((field, fieldIndex) => { // var query = Object.assign({ filters: {} }, this.props.query) var values = [] if ((typeof this.props.query.filters[field]) === 'object') values = this.props.query.filters[field] else values = [this.props.query.filters[field]] values.forEach((v, i) => { var newQuery = this.queryStringWithoutFilter(field, v) var url = [this.props.basePath, '?', stringify(newQuery)].join('') links.push(<li key={[fieldIndex, i].join('-')}><Link to={url}><span className='nypl-icon-circle-x'/>{field}: {v}</Link></li>) }) }) return ( <ul className='filters-control'> {links} </ul> ) } }) export default FiltersControl
admin/client/components/PopoutBody.js
nickhsine/keystone
import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutBody = React.createClass({ displayName: 'PopoutBody', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, scrollable: React.PropTypes.bool, }, render () { let className = classnames('Popout__body', { 'Popout__scrollable-area': this.props.scrollable, }, this.props.className); let props = blacklist(this.props, 'className', 'scrollable'); return <div className={className} {...props} />; }, }); module.exports = PopoutBody;
examples/todomvc/containers/App.js
bloodyowl/redux-devtools
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers, compose } from 'redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import { Provider } from 'react-redux'; import * as reducers from '../reducers'; const finalCreateStore = compose( devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)), createStore ); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <TodoApp /> } </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div> ); } }
hello_world/src/components/Geocities.react.js
rpearce/react-form-steps-example
import React, { Component } from 'react'; class Geocities extends Component { render() { return ( <div> <div style={ { textAlign: 'center', marginTop: '50px' } }> <img src="http://www.wonder-tonic.com/geocitiesizer/images/genie.gif" /> <img src="http://www.wonder-tonic.com/geocitiesizer/images/dancingbaby.gif" /> </div> <marquee> <h1>Welcome to the Internet</h1> </marquee> <marquee> <h2>I will be your guide</h2> </marquee> <div style={ { textAlign: 'center', fontSize: '24px' } }> @RobertWPearce<br /><br /> The Iron Yard.com </div> <div dangerouslySetInnerHTML={ this.nyanCat() }></div> </div> ); } nyanCat() { return { __html: '<marquee direction="right"><img src="https://38.media.tumblr.com/8210fd413c5ce209678ef82d65731443/tumblr_mjphnqLpNy1s5jjtzo1_400.gif" /></marquee>' }; } } export default Geocities;
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js
acalabano/get-committed
// TODO: This module should be ElementChildren, and should use named exports. import React from 'react'; /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return React.Children.map(children, function (child) { if (!React.isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ function forEach(children, func, context) { var index = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; React.Children.forEach(children, function (child) { if (!result) { return; } if (!React.isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } result.push(child); }); return result; } export default { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray };
src/routes/admin/index.js
zsu13579/whatsgoinontonight
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; const title = 'Admin Page'; const isAdmin = false; export default { path: '/admin', async action() { if (!isAdmin) { return { redirect: '/login' }; } const Admin = await require.ensure([], require => require('./Admin').default, 'admin'); return { title, chunk: 'admin', component: <Layout><Admin title={title} /></Layout>, }; }, };
app/static/src/diagnostic/TestTypeResultForm_modules/PolymerisationDegreeTestForm.js
vsilent/Vision
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import Button from 'react-bootstrap/lib/Button'; import Panel from 'react-bootstrap/lib/Panel'; import {findDOMNode} from 'react-dom'; import {hashHistory} from 'react-router'; import {Link} from 'react-router'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import {NotificationContainer, NotificationManager} from 'react-notifications'; const TextField = React.createClass({ render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; return ( <FormGroup validationState={this.props.errors[name] ? 'error' : null}> <FormControl type="text" placeholder={label} name={name} value={value} data-type={this.props["data-type"]} data-len={this.props["data-len"]} /> <HelpBlock className="warning">{this.props.errors[name]}</HelpBlock> <FormControl.Feedback /> </FormGroup> ); } }); const CheckBox = React.createClass({ render: function () { var name = (this.props.name != null) ? this.props.name : ""; return ( <Checkbox name={name}> <span className="glyphicon glyphicon-menu-left"> </span> </Checkbox> ); } }); var PolymerisationDegreeTestForm = React.createClass({ getInitialState: function () { return { loading: false, errors: {}, fields: [ 'phase_a1', 'phase_a2', 'phase_a3', 'phase_b1', 'phase_b2', 'phase_b3', 'phase_c1', 'phase_c2', 'phase_c3', 'lead_a', 'lead_b', 'lead_c', 'lead_n', 'winding' ] } }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId; this.serverRequest = $.authorizedGet(source, function (result) { var res = (result['result']); if (res.length > 0) { var fields = this.state.fields; fields.push('id'); var data = res[0]; var state = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; if (data.hasOwnProperty(key)) { state[key] = data[key]; } } this.setState(state); } }.bind(this), 'json'); }, _create: function () { var fields = this.state.fields; var data = {test_result_id: this.props.testResultId}; var url = '/api/v1.0/' + this.props.tableName + '/'; for (var i = 0; i < fields.length; i++) { var key = fields[i]; data[key] = this.state[key]; } if ('id' in this.state) { url += this.state['id']; delete data.id; } return $.authorizedAjax({ url: url, type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _onSubmit: function (e) { e.preventDefault(); // Do not propagate the submit event of the main form e.stopPropagation(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); e.stopPropagation(); return false; } var xhr = this._create(); xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading) }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { // this.setState(this.getInitialState()); NotificationManager.success('Test values have been saved successfully.'); if ($.isNumeric(data.result)) { this.setState({id: data.result}); } }, _onError: function (data) { var message = "Failed to create"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { // We get list of errors if (data.status >= 500) { message = res.error.join(". "); } else if (res.error instanceof Object){ // We get object of errors with field names as key for (var field in res.error) { var errorMessage = res.error[field]; if (Array.isArray(errorMessage)) { errorMessage = errorMessage.join(". "); } res.error[field] = errorMessage; } this.setState({ errors: res.error }); } else { message = res.error; } } NotificationManager.error(message); }, _onChange: function (e) { var state = {}; if (e.target.type == 'checkbox') { state[e.target.name] = e.target.checked; } else if (e.target.type == 'select-one') { state[e.target.name] = e.target.value; } else { state[e.target.name] = e.target.value; } var errors = this._validate(e); state = this._updateFieldErrors(e.target.name, state, errors); this.setState(state); }, _validate: function (e) { var errors = []; var error; error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type")); if (error){ errors.push(error); } error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len")); if (error){ errors.push(error); } return errors; }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/ }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, _validateFieldLength: function (value, length){ var error = ""; if (value && length){ if (value.length > length){ error = "Value should be maximum " + length + " characters long" } } return error; }, _updateFieldErrors: function (fieldName, state, errors){ // Clear existing errors related to the current field as it has been edited state.errors = this.state.errors; delete state.errors[fieldName]; // Update errors with new ones, if present if (Object.keys(errors).length){ state.errors[fieldName] = errors.join(". "); } return state; }, is_valid: function () { return (Object.keys(this.state.errors).length <= 0); }, _formGroupClass: function (field) { var className = "form-group "; if (field) { className += " has-error" } return className; }, render: function () { return ( <div className="form-container"> <form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}> <div className="row"> <div className="col-md-3 col-md-offset-3"> <Panel header="Primary"> </Panel> </div> <div className="col-md-3"> <Panel header="Secondary"> </Panel> </div> <div className="col-md-3"> <Panel header="Connection"> </Panel> </div> </div> <div className="row"> <div className="col-md-2 col-md-offset-1"> <b>Phase A</b> </div> <div className="col-md-3"> <TextField label="phase_a1" name="phase_a1" value={this.state.phase_a1} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_a2" name="phase_a2" value={this.state.phase_a2} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_a3" name="phase_a3" value={this.state.phase_a3} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2 col-md-offset-1"> <b>Phase B</b> </div> <div className="col-md-3"> <TextField label="phase_b1" name="phase_b1" value={this.state.phase_b1} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_b2" name="phase_b2" value={this.state.phase_b2} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_b3" name="phase_b3" value={this.state.phase_b3} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2 col-md-offset-1"> <b>Phase C</b> </div> <div className="col-md-3"> <TextField label="phase_c1" name="phase_c1" value={this.state.phase_c1} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_c2" name="phase_c2" value={this.state.phase_c2} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-3"> <TextField label="phase_c3" name="phase_c3" value={this.state.phase_c3} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-12 "> <Panel header="Lead & Winding"> </Panel> </div> </div> <div className="row"> <div className="col-md-1"> <b>Lead A</b> </div> <div className="col-md-2"> <TextField label="lead_a" name="lead_a" value={this.state.lead_a} errors={this.state.errors} data-type="float" data-len="4"/> </div> <div className="col-md-1"> <b>Lead B</b> </div> <div className="col-md-2"> <TextField label="lead_b" name="lead_b" value={this.state.lead_b} errors={this.state.errors} data-type="float" data-len="4"/> </div> <div className="col-md-1"> <b>Lead C</b> </div> <div className="col-md-2"> <TextField label="lead_c" name="lead_c" value={this.state.lead_c} errors={this.state.errors} data-type="float" data-len="4"/> </div> <div className="col-md-1"> <b>Lead N</b> </div> <div className="col-md-2"> <TextField label="lead_n" name="lead_n" value={this.state.lead_n} errors={this.state.errors} data-type="float" data-len="4"/> </div> </div> <div className="row"> <div className="col-md-3 pull-right"> <b>Winding</b> <TextField label="winding" name="winding" value={this.state.winding} errors={this.state.errors} data-type="float" data-len="4"/> </div> </div> <div className="row"> <div className="col-md-12 "> <Button bsStyle="success" className="pull-right" type="submit">Save</Button> &nbsp; <Button bsStyle="danger" className="pull-right margin-right-xs" onClick={this.props.handleClose} >Cancel</Button> </div> </div> </form> </div> ); } }); export default PolymerisationDegreeTestForm;
examples/real-world/containers/DevTools.js
javascriptjedi/redux-select
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> )
client/src/components/dataset/index.js
OpenChemistry/materialsdatabank
import React, { Component } from 'react'; import Button from '@material-ui/core/Button'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import IconButton from '@material-ui/core/IconButton'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableRow from '@material-ui/core/TableRow'; import Typography from '@material-ui/core/Typography'; import EditIcon from '@material-ui/icons/Edit'; import DoneIcon from '@material-ui/icons/Done'; import DownloadIcon from '@material-ui/icons/CloudDownload'; import DeleteIcon from '@material-ui/icons/Delete'; import PropTypes from 'prop-types'; import { connect } from 'react-redux' import _ from 'lodash' import selectors from '../../redux/selectors'; import { symbols } from '../../elements' import StructureContainer from '../../containers/structure' import { approveDataSet } from '../../redux/ducks/upload'; import { setProgress } from '../../redux/ducks/app'; import { deleteDataset } from '../../redux/ducks/datasets'; import PageHead from '../page-head'; import PageBody from '../page-body'; import ValidateTable from './validate'; import EditToggle from './editToggle'; import { generalInformationFields, dataCollectionFields, reconstructionFields } from '../deposit/fields' import './index.css' import { CardActions } from '@material-ui/core'; import { push } from 'connected-react-router'; import moment from 'moment'; const tableLabelStyle = { fontSize: '18px', color: '#9E9E9E' } const tableStyle = { fontSize: '18px' } const curatorCardStyle = { marginTop: '2rem' } class Dataset extends Component { constructor(props) { super(props); this.state = { approving: false, reconstructionMenu: { anchor: null, open: false }, structureMenu: { anchor: null, open: false }, projectionMenu: { anchor: null, open: false }, } } approve = () => { this.props.dispatch(setProgress(true)); this.props.dispatch(approveDataSet(this.props._id)); this.setState({ approving: true }) } edit = () => { this.props.dispatch(push(`/dataset/${this.props._id}/edit`)); } remove = () => { new Promise((resolve, reject) => { this.props.dispatch(deleteDataset(this.props.dataset._id, resolve, reject)); }).then((dataSet) =>{ this.props.dispatch(push('/search')); }) } componentWillReceiveProps = (nextProps) => { if (nextProps.public && this.state.approving) { this.props.dispatch(setProgress(false)); this.setState({ approving: false }); } } handleClick = (key, anchor) => { this.setState({[key]: {anchor: anchor}}); }; handleClose = () => { this.setState( { reconstructionMenu:{anchor: null}, structureMenu: {anchor: null}, projectionMenu: {anchor: null} } ); }; render = () => { const species = this.props.atomicSpecies.map((an) => symbols[an]).join(', '); const authors = this.props.authors.join(' and '); const mdbId = this.props.mdbId; const deposited = this.props.deposited; const released = this.props.released; const validation = this.props.validation; let r1 = 'N/A'; if (!_.isNil(validation)) { r1 = this.props.validation.r1; } let isPublic = this.props.public; let { structure, reconstruction, projection, title, isCurator, doi, _id, editable, isOwner } = this.props; editable = _.isNil(editable) ? false : editable; let numberOfAtoms = -1; let structureUrl = ''; if (!_.isNil(structure)) { structureUrl = `${window.location.origin}/api/v1/mdb/datasets/_/structures/${structure._id}`; numberOfAtoms = structure.numberOfAtoms; } let reconEmdUrl = ''; let reconTiffUrl = ''; if (!_.isNil(reconstruction)) { reconEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/emd?updated=${this.props.updated}` reconTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/tiff?updated=${this.props.updated}` } let projEmdUrl = ''; let projTiffUrl = ''; if (!_.isNil(projection)) { projEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/emd?updated=${this.props.updated}` projTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/tiff?updated=${this.props.updated}` } // Prepare report data let jsonReportData = null; if (!_.isNil(projection) && !_.isNil(reconstruction)) { // Filter the ones we want const dataSetProps = _.pick(this.props, Object.keys(generalInformationFields())); const projectionProps = _.pick(projection, Object.keys(dataCollectionFields())); const reconstructionProps = _.pick(reconstruction, Object.keys(reconstructionFields())); // Combine and encode const data = {...dataSetProps, ...projectionProps, ...reconstructionProps}; const jsonReport = encodeURIComponent(JSON.stringify(data, null, 2)); jsonReportData = `text/json;charset=utf-8, ${jsonReport}`; } return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> {title} </Typography> <Typography variant="subheading" paragraph color="inherit"> {authors} </Typography> </PageHead> <PageBody> <Card> <CardContent> <Table> <TableBody> <TableRow> <TableCell style={{...tableLabelStyle}}> MDB ID </TableCell> <TableCell style={{...tableStyle}}> {mdbId} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Name of the structure </TableCell> <TableCell style={{...tableStyle}}> {title} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Total number of atoms </TableCell> { numberOfAtoms !== -1 && <TableCell style={{...tableStyle}}> {numberOfAtoms} </TableCell> } </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> R<sub>1</sub> factor </TableCell> <TableCell style={{...tableStyle}}> {r1} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Atomic Species </TableCell> <TableCell style={{...tableStyle}}> {species} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> DOI </TableCell> <TableCell style={{...tableStyle}}> {_.isNil(doi) ? ( 'N/A' ) : ( <a href={`https://dx.doi.org/${doi}`}> {doi} </a> )} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Deposition author(s) </TableCell> <TableCell style={{...tableStyle}}> {authors} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Deposited </TableCell> <TableCell style={{...tableStyle}}> {_.isNil(deposited) ? ( 'N/A' ) : ( moment(deposited).calendar() )} </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Released </TableCell> <TableCell style={{...tableStyle}}> {_.isNil(released) ? ( 'N/A' ) : ( moment(released).calendar() )} </TableCell> </TableRow> { ( !_.isNil(projection) && (!_.isNil(projection.tiffFileId) || !_.isNil(projection.emdFileId)) ) && <TableRow> <TableCell style={{...tableLabelStyle}}> Tilt series file </TableCell> <TableCell style={{...tableStyle}}> <IconButton aria-label="More" aria-owns={this.state.projectionMenu.anchor ? 'projection-menu' : null} aria-haspopup="true" onClick={(e) => {this.handleClick('projectionMenu', e.currentTarget)}} > <DownloadIcon /> </IconButton> <Menu id="projection-menu" anchorEl={this.state.projectionMenu.anchor} open={Boolean(this.state.projectionMenu.anchor)} onClose={this.handleClose} > { !_.isNil(projection.tiffFileId) && <MenuItem value="tiff" onClick={this.handleClose} > <a href={projTiffUrl}>TIFF</a> </MenuItem> } { !_.isNil(projection.emdFileId) && <MenuItem value="emd" onClick={this.handleClose} > <a href={projEmdUrl}>EMD</a> </MenuItem> } </Menu> </TableCell> </TableRow> } { ( !_.isNil(reconstruction) && (!_.isNil(reconstruction.tiffFileId) || !_.isNil(reconstruction.emdFileId)) ) && <TableRow> <TableCell style={{...tableLabelStyle}}> 3D reconstruction file </TableCell> <TableCell style={{...tableStyle}}> <IconButton aria-label="More" aria-owns={this.state.reconstructionMenu.anchor ? 'reconstruction-menu' : null} aria-haspopup="true" onClick={(e) => {this.handleClick('reconstructionMenu', e.currentTarget)}} > <DownloadIcon /> </IconButton> <Menu id="reconstruction-menu" anchorEl={this.state.reconstructionMenu.anchor} open={Boolean(this.state.reconstructionMenu.anchor)} onClose={this.handleClose} > { !_.isNil(reconstruction.tiffFileId) && <MenuItem value="tiff" onClick={this.handleClose} > <a href={reconTiffUrl}>TIFF</a> </MenuItem> } { !_.isNil(reconstruction.emdFileId) && <MenuItem value="emd" onClick={this.handleClose} > <a href={reconEmdUrl}>EMD</a> </MenuItem> } </Menu> </TableCell> </TableRow> } <TableRow> <TableCell style={{...tableLabelStyle}}> 3D atomic structure file </TableCell> <TableCell style={{...tableStyle}}> <IconButton aria-label="More" aria-owns={this.state.structureMenu.anchor ? 'structure-menu' : null} aria-haspopup="true" onClick={(e) => {this.handleClick('structureMenu', e.currentTarget)}} > <DownloadIcon /> </IconButton> <Menu id="structure-menu" anchorEl={this.state.structureMenu.anchor} open={Boolean(this.state.structureMenu.anchor)} onClose={this.handleClose} > <MenuItem value="xyz" onClick={this.handleClose} > <a href={`${structureUrl}/xyz?updated=${this.props.updated}`}>XYZ</a> </MenuItem> <MenuItem value="cjson" onClick={this.handleClose} > <a href={`${structureUrl}/cjson?updated=${this.props.updated}`}>CJSON</a> </MenuItem> <MenuItem value="cml" onClick={this.handleClose} > <a href={`${structureUrl}/cml?updated=${this.props.updated}`}>CML</a> </MenuItem> </Menu> </TableCell> </TableRow> <TableRow> <TableCell style={{...tableLabelStyle}}> Full report (MatData) </TableCell> <TableCell style={{...tableStyle}}> <a href={`data:' + ${jsonReportData}`} download={`${mdbId}.json`}> <IconButton> <DownloadIcon /> </IconButton> </a> </TableCell> </TableRow> </TableBody> </Table> <div style={{width: '100%', height: '30rem'}}> <StructureContainer _id={_id}/> </div> { !isPublic && <Typography color="textSecondary" style={{flexGrow: 1}}>* This dataset is awaiting approval.</Typography> } </CardContent> { (isCurator || isOwner) && <CardActions style={{display: 'flex'}}> <div style={{marginLeft: 'auto'}}> <Button variant="contained" color="primary" disabled={!editable && !isCurator} onClick={() => this.edit()} > <EditIcon/> Edit </Button> <Button style={{marginLeft: '0.5rem'}} variant="contained" color="secondary" disabled={!editable && !isCurator} onClick={() => this.remove()} > <DeleteIcon/> Delete </Button> </div> </CardActions> } </Card> { isCurator && <div style={curatorCardStyle}> <Card> <CardContent> <ValidateTable _id={_id} /> <EditToggle _id={_id} /> </CardContent> <CardActions style={{display: 'flex'}}> { !isPublic && <Button style={{marginLeft: 'auto'}} variant="contained" color="primary" disabled={this.state.approving} onClick={() => this.approve()} > <DoneIcon/> Approve </Button> } </CardActions> </Card> </div> } </PageBody> </div> ); } } Dataset.propTypes = { _id: PropTypes.string, userId: PropTypes.string, title: PropTypes.string, authors: PropTypes.array, imageFileId: PropTypes.string, doi: PropTypes.string, isCurator: PropTypes.bool, public: PropTypes.bool, reconstruction:PropTypes.object, projection:PropTypes.object, isOwner: PropTypes.bool } Dataset.defaultProps = { title: '', userId: null, authors: [], imageFileId: null, atomicSpecies: [], doi: null, isCurator: false, public: false, reconstruction: {}, projection: {}, isOwner: false } function mapStateToProps(state, ownProps) { let props = {}; if (!_.isNull(ownProps._id)) { let structures = selectors.structures.getStructuresById(state); if (_.has(structures, ownProps._id)) { // For now we only have a single structure, so just pick the first. const structure = structures[ownProps._id][0]; props = { structure, public: structure.public } } let reconstructions = selectors.reconstructions.getReconstructionsById(state); if (_.has(reconstructions, ownProps._id)) { // For now we only have a single reconstruction, so just pick the first. const reconstruction = reconstructions[ownProps._id][0]; props = {...props, reconstruction } if (_.has(reconstruction, 'emdFileId')) { props['emdFileId'] = reconstruction.emdFileId } if (_.has(reconstruction, 'tiffFileId')) { props['tiffFileId'] = reconstruction.tiffFileId } } let projections = selectors.projections.getProjectionsById(state); if (_.has(projections, ownProps._id)) { // For now we only have a single projection, so just pick the first. const projection = projections[ownProps._id][0]; props = {...props, projection } if (_.has(projection, 'emdFileId')) { props['emdFileId'] = projection.emdFileId } if (_.has(projection, 'tiffFileId')) { props['tiffFileId'] = projection.tiffFileId } } const dataset = selectors.datasets.getDatasetById(state, ownProps._id); props['dataset'] = dataset; } const me = selectors.girder.getMe(state); const curatorGroup = selectors.girder.getCuratorGroup(state); if (!_.isNil(curatorGroup)) { if (!_.isNil(me)) { props['isCurator'] = _.includes(me.groups, curatorGroup['_id']) } } if (!_.isNil(me)) { if (me._id === ownProps.userId) { props['isOwner'] = true; } } return props; } export default connect(mapStateToProps)(Dataset)
docs/app/Examples/collections/Table/States/TableExampleWarningShorthand.js
vageeshb/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const tableData = [ { name: undefined, status: undefined, notes: undefined }, { name: 'Jimmy', status: 'Requires Action', notes: undefined }, { name: 'Jamie', status: undefined, notes: 'Hostile' }, { name: 'Jill', status: undefined, notes: undefined }, ] const headerRow = [ 'Name', 'Status', 'Notes', ] const renderBodyRow = ({ name, status, notes }) => ({ warning: !!(status && status.match('Requires Action')), cells: [ name || 'No name specified', status ? { icon: 'attention', content: status } : 'Unknown', notes ? { icon: 'attention', content: notes, warning: true } : 'None', ], }) const TableExampleWarningShorthand = () => ( <Table celled headerRow={headerRow} renderBodyRow={renderBodyRow} tableData={tableData} /> ) export default TableExampleWarningShorthand
classic/src/scenes/mailboxes/src/Scenes/BookmarkScene/BookmarkEditScene/BookmarkEditScene.js
wavebox/waveboxapp
import React from 'react' import shallowCompare from 'react-addons-shallow-compare' import { RouterDialog, RouterDialogStateProvider } from 'wbui/RouterDialog' import BookmarkEditSceneContent from './BookmarkEditSceneContent' class BookmarkEditScene extends React.Component { /* **************************************************************************/ // User Interaction /* **************************************************************************/ /** * Closes the modal */ handleClose = () => { window.location.hash = '/' } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { routeName } = this.props return ( <RouterDialog routeName={routeName} disableEnforceFocus onClose={this.handleClose}> <RouterDialogStateProvider routeName={routeName} Component={BookmarkEditSceneContent} /> </RouterDialog> ) } } export default BookmarkEditScene
src/js/main.js
goadapp/goad-site
import React from 'react'; import ReactDOM from 'react-dom'; import Downloads from './components/downloads.jsx'; var smoothScroll = require('smoothscroll'); function ready(fn) { if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } window.React = React; window.ReactDOM = ReactDOM; const binaries = [ { os: "macOS", architecture: 64, url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-osx-x86-64.zip" }, { os: "Linux", architecture: 32, url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-linux-x86.zip" }, { os: "Linux", architecture: 64, url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-linux-x86-64.zip" }, { os: "Windows", architecture: 32, url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-windows-x86.zip" }, { os: "Windows", architecture: 64, url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-windows-x86-64.zip" }, ]; ReactDOM.render(<Downloads binaries={binaries} />, document.getElementById("downloads")); ready(function(){ var tryEl = document.getElementById("try-link"); var tryDestination = document.getElementById("demo"); tryEl.addEventListener("click", event => { event.preventDefault() smoothScroll(tryDestination) }) var installEl = document.getElementById("install-link"); var installDestination = document.getElementById("install"); installEl.addEventListener("click", event => { event.preventDefault() smoothScroll(installDestination) }) })
openex-front/src/private/components/exercises/injects/InjectPopover.js
Luatix/OpenEx
import React, { Component } from 'react'; import * as PropTypes from 'prop-types'; import { connect } from 'react-redux'; import * as R from 'ramda'; import Dialog from '@mui/material/Dialog'; import DialogTitle from '@mui/material/DialogTitle'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogActions from '@mui/material/DialogActions'; import Button from '@mui/material/Button'; import IconButton from '@mui/material/IconButton'; import Slide from '@mui/material/Slide'; import { MoreVert } from '@mui/icons-material'; import Menu from '@mui/material/Menu'; import MenuItem from '@mui/material/MenuItem'; import Alert from '@mui/material/Alert'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableRow from '@mui/material/TableRow'; import TableCell from '@mui/material/TableCell'; import withStyles from '@mui/styles/withStyles'; import { updateInject, deleteInject, tryInject, updateInjectActivation, injectDone, } from '../../../../actions/Inject'; import InjectForm from './InjectForm'; import inject18n from '../../../../components/i18n'; import { splitDuration } from '../../../../utils/Time'; import { isExerciseReadOnly } from '../../../../utils/Exercise'; import { tagsConverter } from '../../../../actions/Schema'; const Transition = React.forwardRef((props, ref) => ( <Slide direction="up" ref={ref} {...props} /> )); Transition.displayName = 'TransitionSlide'; const styles = () => ({ tableHeader: { borderBottom: '1px solid rgba(255, 255, 255, 0.15)', }, tableCell: { borderTop: '1px solid rgba(255, 255, 255, 0.15)', borderBottom: '1px solid rgba(255, 255, 255, 0.15)', }, }); class InjectPopover extends Component { constructor(props) { super(props); this.state = { openDelete: false, openEdit: false, openPopover: false, openTry: false, openCopy: false, openEnable: false, openDisable: false, openDone: false, openResult: false, injectResult: null, }; } handlePopoverOpen(event) { event.stopPropagation(); this.setState({ anchorEl: event.currentTarget }); } handlePopoverClose() { this.setState({ anchorEl: null }); } handleOpenEdit() { this.setState({ openEdit: true }); this.handlePopoverClose(); } handleCloseEdit() { this.setState({ openEdit: false }); } onSubmitEdit(data) { const inputValues = R.pipe( R.assoc( 'inject_depends_duration', data.inject_depends_duration_days * 3600 * 24 + data.inject_depends_duration_hours * 3600 + data.inject_depends_duration_minutes * 60, ), R.assoc('inject_contract', data.inject_contract.id), R.assoc('inject_tags', R.pluck('id', data.inject_tags)), R.dissoc('inject_depends_duration_days'), R.dissoc('inject_depends_duration_hours'), R.dissoc('inject_depends_duration_minutes'), )(data); return this.props .updateInject( this.props.exerciseId, this.props.inject.inject_id, inputValues, ) .then(() => this.handleCloseEdit()); } handleOpenDelete() { this.setState({ openDelete: true }); this.handlePopoverClose(); } handleCloseDelete() { this.setState({ openDelete: false }); } submitDelete() { this.props.deleteInject(this.props.exerciseId, this.props.inject.inject_id); this.handleCloseDelete(); } handleOpenTry() { this.setState({ openTry: true, }); this.handlePopoverClose(); } handleCloseTry() { this.setState({ openTry: false, }); } handleCloseResult() { this.setState({ openResult: false, injectResult: null, }); } submitTry() { this.props.tryInject(this.props.inject.inject_id).then((payload) => { this.setState({ injectResult: payload, openResult: true }); }); this.handleCloseTry(); } handleOpenEnable() { this.setState({ openEnable: true, }); this.handlePopoverClose(); } handleCloseEnable() { this.setState({ openEnable: false, }); } submitEnable() { this.props.updateInjectActivation( this.props.exerciseId, this.props.inject.inject_id, { inject_enabled: true }, ); this.handleCloseEnable(); } handleOpenDisable() { this.setState({ openDisable: true, }); this.handlePopoverClose(); } handleCloseDisable() { this.setState({ openDisable: false, }); } submitDisable() { this.props.updateInjectActivation( this.props.exerciseId, this.props.inject.inject_id, { inject_enabled: false }, ); this.handleCloseDisable(); } handleOpenDone() { this.setState({ openDone: true, }); this.handlePopoverClose(); } handleCloseDone() { this.setState({ openDone: false, }); } submitDone() { this.props.injectDone( this.props.exercise.exercise_id, this.props.inject.inject_id, ); this.handleCloseDone(); } handleOpenEditContent() { this.props.setSelectedInject(this.props.inject.inject_id); this.handlePopoverClose(); } render() { const { t, inject, injectTypesMap, exercise, setSelectedInject, tagsMap, isDisabled, classes, } = this.props; const injectTags = tagsConverter(inject.inject_tags, tagsMap); const duration = splitDuration(inject.inject_depends_duration || 0); const initialValues = R.pipe( R.assoc('inject_tags', injectTags), R.pick([ 'inject_title', 'inject_contract', 'inject_description', 'inject_tags', 'inject_content', 'inject_audiences', 'inject_all_audiences', 'inject_country', 'inject_city', ]), R.assoc('inject_depends_duration_days', duration.days), R.assoc('inject_depends_duration_hours', duration.hours), R.assoc('inject_depends_duration_minutes', duration.minutes), )(inject); return ( <div> <IconButton onClick={this.handlePopoverOpen.bind(this)} aria-haspopup="true" size="large" > <MoreVert /> </IconButton> <Menu anchorEl={this.state.anchorEl} open={Boolean(this.state.anchorEl)} onClose={this.handlePopoverClose.bind(this)} > <MenuItem onClick={this.handleOpenEdit.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Update')} </MenuItem> {setSelectedInject && ( <MenuItem onClick={this.handleOpenEditContent.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Manage content')} </MenuItem> )} {!inject.inject_status && ( <MenuItem onClick={this.handleOpenDone.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Mark as done')} </MenuItem> )} {inject.inject_type !== 'openex_manual' && ( <MenuItem onClick={this.handleOpenTry.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Try the inject')} </MenuItem> )} {inject.inject_enabled ? ( <MenuItem onClick={this.handleOpenDisable.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Disable')} </MenuItem> ) : ( <MenuItem onClick={this.handleOpenEnable.bind(this)} disabled={isExerciseReadOnly(exercise) || isDisabled} > {t('Enable')} </MenuItem> )} <MenuItem onClick={this.handleOpenDelete.bind(this)} disabled={isExerciseReadOnly(exercise)} > {t('Delete')} </MenuItem> </Menu> <Dialog open={this.state.openDelete} TransitionComponent={Transition} onClose={this.handleCloseDelete.bind(this)} PaperProps={{ elevation: 1 }} > <DialogContent> <DialogContentText> {t('Do you want to delete this inject?')} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCloseDelete.bind(this)}> {t('Cancel')} </Button> <Button color="secondary" onClick={this.submitDelete.bind(this)}> {t('Delete')} </Button> </DialogActions> </Dialog> <Dialog TransitionComponent={Transition} open={this.state.openEdit} onClose={this.handleCloseEdit.bind(this)} fullWidth={true} maxWidth="md" PaperProps={{ elevation: 1 }} > <DialogTitle>{t('Update the inject')}</DialogTitle> <DialogContent> <InjectForm initialValues={initialValues} editing={true} injectTypesMap={injectTypesMap} onSubmit={this.onSubmitEdit.bind(this)} handleClose={this.handleCloseEdit.bind(this)} /> </DialogContent> </Dialog> <Dialog TransitionComponent={Transition} open={this.state.openTry} onClose={this.handleCloseTry.bind(this)} PaperProps={{ elevation: 1 }} > <DialogContent> <DialogContentText> <p>{t('Do you want to try this inject?')}</p> <Alert severity="info"> {t('The inject will only be sent to you.')} </Alert> </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCloseTry.bind(this)}> {t('Cancel')} </Button> <Button color="secondary" onClick={this.submitTry.bind(this)}> {t('Try')} </Button> </DialogActions> </Dialog> <Dialog TransitionComponent={Transition} open={this.state.openEnable} onClose={this.handleCloseEnable.bind(this)} PaperProps={{ elevation: 1 }} > <DialogContent> <DialogContentText> {t('Do you want to enable this inject?')} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCloseEnable.bind(this)}> {t('Cancel')} </Button> <Button color="secondary" onClick={this.submitEnable.bind(this)}> {t('Enable')} </Button> </DialogActions> </Dialog> <Dialog TransitionComponent={Transition} open={this.state.openDisable} onClose={this.handleCloseDisable.bind(this)} PaperProps={{ elevation: 1 }} > <DialogContent> <DialogContentText> {t('Do you want to disable this inject?')} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCloseDisable.bind(this)}> {t('Cancel')} </Button> <Button color="secondary" onClick={this.submitDisable.bind(this)}> {t('Disable')} </Button> </DialogActions> </Dialog> <Dialog TransitionComponent={Transition} open={this.state.openDone} onClose={this.handleCloseDone.bind(this)} PaperProps={{ elevation: 1 }} > <DialogContent> <DialogContentText> {t('Do you want to mark this inject as done?')} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCloseDone.bind(this)}> {t('Cancel')} </Button> <Button color="secondary" onClick={this.submitDone.bind(this)}> {t('Mark')} </Button> </DialogActions> </Dialog> <Dialog open={this.state.openResult} TransitionComponent={Transition} onClose={this.handleCloseResult.bind(this)} fullWidth={true} maxWidth="md" PaperProps={{ elevation: 1 }} > <DialogContent> <Table selectable={false} size="small"> <TableBody displayRowCheckbox={false}> {this.state.injectResult && Object.entries(this.state.injectResult.status_reporting).map( ([key, value]) => { if (key === 'execution_traces') { return ( <TableRow key={key}> <TableCell classes={{ root: classes.tableCell }}> {key} </TableCell> <TableCell classes={{ root: classes.tableCell }}> <Table selectable={false} size="small" key={key}> <TableBody displayRowCheckbox={false}> {value.map((trace) => ( <TableRow key={trace.trace_identifier}> <TableCell classes={{ root: classes.tableCell }} > {trace.trace_message} </TableCell> <TableCell classes={{ root: classes.tableCell }} > {trace.trace_status} </TableCell> <TableCell classes={{ root: classes.tableCell }} > {trace.trace_time} </TableCell> </TableRow> ))} </TableBody> </Table> </TableCell> </TableRow> ); } return ( <TableRow key={key}> <TableCell classes={{ root: classes.tableCell }}> {key} </TableCell> <TableCell classes={{ root: classes.tableCell }}> {value} </TableCell> </TableRow> ); }, )} </TableBody> </Table> </DialogContent> <DialogActions> <Button onClick={this.handleCloseResult.bind(this)}> {t('Close')} </Button> </DialogActions> </Dialog> </div> ); } } InjectPopover.propTypes = { t: PropTypes.func, exerciseId: PropTypes.string, exercise: PropTypes.object, tagsMap: PropTypes.object, inject: PropTypes.object, updateInject: PropTypes.func, deleteInject: PropTypes.func, injectTypesMap: PropTypes.object, updateInjectActivation: PropTypes.func, injectDone: PropTypes.func, setSelectedInject: PropTypes.func, isDisabled: PropTypes.bool, }; export default R.compose( connect(null, { updateInject, deleteInject, tryInject, updateInjectActivation, injectDone, }), inject18n, withStyles(styles), )(InjectPopover);
tests/react/useLayoutEffect_hook.js
mroch/flow
// @flow import React from 'react'; { React.useLayoutEffect(); // Error: function requires another argument. } { // Ok variants without cleanup functions React.useLayoutEffect(() => {}); React.useLayoutEffect(() => {}, []); React.useLayoutEffect(() => {}, [1, 2, 3]); // Ok variants with cleanup functions React.useLayoutEffect(() => () => {}); React.useLayoutEffect(() => () => {}, []); React.useLayoutEffect(() => () => {}, [1, 2, 3]); } { React.useLayoutEffect(1); // Error: number is incompatible with function type React.useLayoutEffect(() => {}, 1); // Error: number is incompatible with function react-only array React.useLayoutEffect(async () => {}) // Error: promise is incompatible with function return type React.useLayoutEffect(() => () => 123) // Error: cleanup function should not return a value }
components/Home/FeaturedOn/index.js
parkerproject/conceptionarts
import React from 'react'; export default() => ( <div className="featured_on"> <div className="container"> <div className="row-eq-height featured_on_resp"> <div className="featured_on_title col-xl-2 col-lg-3 col-md-4 col-sm-12"> <span> As featured on: </span> </div> <div className="featured_on_img col-xl-10 col-lg-9 col-md-8 col-sm-12"> <img src="/static/img/brand.jpg" alt="" /> </div> </div> </div> </div> );
step7-flux/node_modules/react-router/modules/IndexRedirect.js
jintoppy/react-training
import React from 'react' import warning from './routerWarning' import invariant from 'invariant' import Redirect from './Redirect' import { falsy } from './PropTypes' const { string, object } = React.PropTypes /** * An <IndexRedirect> is used to redirect from an indexRoute. */ const IndexRedirect = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element) } else { warning( false, 'An <IndexRedirect> does not make sense at the root of your route config' ) } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<IndexRedirect> elements are for router configuration only and should not be rendered' ) } }) export default IndexRedirect
app/components/Theme/Theme.js
zchen9/DonutTab
import React from 'react'; require('./Theme.scss'); const LIGHT_ICON = ( <span className="theme-icon theme-light"> <i className="fa fa-sun-o"></i> </span> ); const DARK_ICON = ( <span className="theme-icon theme-dark"> <i className="fa fa-moon-o"></i> </span> ); const LIGHT_STYLE = { background: 'linear-gradient(to bottom, rgba(255, 255, 255, .15) 0, rgba(255, 255, 255, .3), rgba(255, 255, 255, .15) 100%)' } const DARK_STYLE = { background: 'linear-gradient(to bottom, rgba(0, 0, 0, .35) 0, rgba(0, 0, 0, .1), rgba(0, 0, 0, .35) 100%)' } export default class Theme extends React.Component { constructor(props) { super(props); this.state = { isDark: JSON.parse(localStorage.getItem('curIsDark')) ? true : false } } handleClick(ev) { var isDark = this.state.isDark; // change icon this.setState({ isDark: !isDark }); // set local localStorage.setItem('curIsDark', !isDark); this.props.onChangeTheme(!isDark); } render() { var isDark = this.state.isDark, themeStyle = isDark ? DARK_STYLE : LIGHT_STYLE, themeIcon = isDark ? DARK_ICON : LIGHT_ICON; return ( <div className="theme-container" style={themeStyle}> <div onClick={this.handleClick.bind(this)}>{themeIcon}</div> </div> ); } }
src/components/ImagePicker/ImagePicker.js
ahthamrin/kbri-admin2
import React from 'react' import { IndexLink, Link } from 'react-router' console.log('ImagePicker') var thisUpCanvas = document.createElement('canvas') var thisUpImage = new Image() class ImagePicker extends React.Component { constructor(props) { super(props); console.log('ImagePicker:constructor'); } renderValidation() { // TODO: change materialize CSS code for (var elemId in this.dataset) { try { let elem = document.querySelector('label[for='+elemId+']').dataset; if (this.dataset[elemId].error) { elem.error = this.dataset[elemId].error; document.getElementById(elemId).classList.add('invalid') document.getElementById(elemId).classList.remove('valid') } else { delete elem.error ; document.getElementById(elemId).classList.add('valid') document.getElementById(elemId).classList.remove('invalid') } // console.log('elem', elemId, this.dataset[elemId]); } catch(e) {} } } componentDidMount() { console.log('ImagePicker:componentDidMount'); } componentDidUpdate() { } state = { dialogOpen : null, } handleOpenDialog = (name) => { this.setState({dialogOpen: name}); } handleCloseDialog = () => { this.setState({dialogOpen: null}); } handleFiles = (e) => { // console.log('handleFiles', e.target.files); const files = []; for (let i = 0; i < e.target.files.length; i++) { // Convert to Array. files.push(e.target.files[i]); } // Build Promise List, each promise resolved by FileReader.onload. Promise.all(files.map(file => new Promise((resolve, reject) => { let reader = new FileReader(); reader.onload = (ref) => { // Resolve both the FileReader result and its original file. resolve(ref.target.result); }; // Read the file with format based on this.props.as. switch ((this.props.as || 'url').toLowerCase()) { case 'binary': { reader.readAsBinaryString(file); break; } case 'buffer': { reader.readAsArrayBuffer(file); break; } case 'text': { reader.readAsText(file); break; } case 'url': { reader.readAsDataURL(file); break; } } }))) .then(zippedResults => { // Run the callback after all files have been read. console.log('res', zippedResults); const MAX_SIZE = 800; var upImage = thisUpImage //new Image(); var upCanvas = thisUpCanvas // document.createElement('canvas'); var ctx = upCanvas.getContext('2d'); upImage.onload = () => { // Make a smaller image from input // console.log('drawImage', upImage.width, upImage.height, zippedResults[0].length); const hwRatio = upImage.height/upImage.width; const maxDimRatio = MAX_SIZE/Math.max(upImage.height, upImage.width); upCanvas.height = upImage.height; upCanvas.width = upImage.width; if (maxDimRatio < 1) { upCanvas.height = maxDimRatio*upImage.height; upCanvas.width = maxDimRatio*upImage.width; } // console.log('drawImage', upImage.width, upImage.height, zippedResults[0].length); ctx.drawImage(upImage, 0, 0, upCanvas.width, upCanvas.height); var dataUrl = upCanvas.toDataURL('image/jpeg', 0.9) ctx.clearRect(0, 0, upCanvas.width, upCanvas.height) upCanvas.height = 1 upCanvas.width = 1 upImage.src = null; zippedResults[0] = '' zippedResults = null // this.props.onChange(null, dataUrl); this.props.onChange({target:{value:dataUrl}}); } upImage.src = zippedResults[0]; }); } render() { return ( <div style={{display:'inline-block'}}> <label className='active'>{this.props.label}</label> <div className='btn' style={{overflow:'hidden',position:'relative'}}> <span><i className='material-icons'>add_a_photo</i></span> <input name={'fileinput-'+this.props.name} type='file' accept='image/*;capture=camera' onChange={this.handleFiles} style={{display:'block', cursor: 'inherit', position: 'absolute', opacity: 0, top:0, bottom:0, left:0, right:0}}/> </div> </div> ) } } // <label className='active'>{this.props.label}</label> // <div className='btn' > // <span>Unggah<i className='material-icons'>add_a_photo</i></span> // <input type='file' accept='image/*;capture=camera' onChange={this.handleFiles} style={{position: 'absolute', opacity:1, top:0, bottom:0, left:0, right:0}}/> // </div> export default ImagePicker
ui/src/components/PostImage.js
nateinaction/nateanddanielle.love
import React from 'react'; import PropTypes from 'prop-types'; import LinearProgress from '@material-ui/core/LinearProgress'; import CardMedia from '@material-ui/core/CardMedia'; import './PostImage.css'; const srcSize = (imageType, maxWidth, imageDetails) => { // Apparently GIFs are no longer animated after WP scales them so we always serve full size let response = { featured: imageDetails.sizes.full.source_url, src: imageDetails.sizes.full.source_url, }; if (imageType !== 'image/gif') { // find available sizes for a given image const availableSizes = [200, 400, 600, 800, 1200, 1400, 1600, 1800, 2000].filter(size => (typeof imageDetails.sizes[size] !== 'undefined')); // grab the size of the featured image and deliver other sizes to srcset const featuredSize = availableSizes.find(size => maxWidth <= size) || 'full'; const srcset = availableSizes.map(size => `${imageDetails.sizes[size].source_url} ${size}w`); // create response response = { featured: imageDetails.sizes[featuredSize].source_url, src: imageDetails.sizes.full.source_url, srcset, }; } return response; }; const PostImage = (props) => { // if fetching show loading bar if (props.media.fetching) { return ( <LinearProgress className="fetching" /> ); } // else get image object and return const media = { type: props.media.mime_type, maxWidth: props.width, details: props.media.media_details, }; const image = srcSize(media.type, media.maxWidth, media.details); return ( <div> <CardMedia title={props.media.alt_text} src={image.featured} component="img" /> </div> ); }; PostImage.propTypes = { media: PropTypes.shape({ fetching: PropTypes.bool, alt_text: PropTypes.string, media_details: PropTypes.object, mime_type: PropTypes.string, }).isRequired, width: PropTypes.number, }; PostImage.defaultProps = { width: 0, }; export default PostImage;
node_modules/rc-dialog/es/Modal.js
yhx0634/foodshopfront
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import { View, Modal, Animated, TouchableWithoutFeedback, StyleSheet, Dimensions, Easing } from 'react-native'; var styles = StyleSheet.create({ wrap: { flex: 1, backgroundColor: 'rgba(0,0,0,0)' }, mask: { backgroundColor: 'black', opacity: .5 }, content: { backgroundColor: 'white' }, absolute: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 } }); var screen = Dimensions.get('window'); var RCModal = function (_React$Component) { _inherits(RCModal, _React$Component); function RCModal(props) { _classCallCheck(this, RCModal); var _this = _possibleConstructorReturn(this, (RCModal.__proto__ || Object.getPrototypeOf(RCModal)).call(this, props)); _this.animateMask = function (visible) { _this.stopMaskAnim(); _this.state.opacity.setValue(_this.getOpacity(!visible)); _this.animMask = Animated.timing(_this.state.opacity, { toValue: _this.getOpacity(visible), duration: _this.props.animationDuration }); _this.animMask.start(function () { _this.animMask = null; }); }; _this.stopMaskAnim = function () { if (_this.animMask) { _this.animMask.stop(); _this.animMask = null; } }; _this.stopDialogAnim = function () { if (_this.animDialog) { _this.animDialog.stop(); _this.animDialog = null; } }; _this.animateDialog = function (visible) { _this.stopDialogAnim(); _this.animateMask(visible); var animationType = _this.props.animationType; if (animationType !== 'none') { if (animationType === 'slide-up' || animationType === 'slide-down') { _this.state.position.setValue(_this.getPosition(!visible)); _this.animDialog = Animated.timing(_this.state.position, { toValue: _this.getPosition(visible), duration: _this.props.animationDuration, easing: visible ? Easing.elastic(0.8) : undefined }); } else if (animationType === 'fade') { _this.animDialog = Animated.parallel([Animated.timing(_this.state.opacity, { toValue: _this.getOpacity(visible), duration: _this.props.animationDuration, easing: visible ? Easing.elastic(0.8) : undefined }), Animated.spring(_this.state.scale, { toValue: _this.getScale(visible), duration: _this.props.animationDuration, easing: visible ? Easing.elastic(0.8) : undefined })]); } _this.animDialog.start(function () { _this.animDialog = null; if (!visible) { _this.setState({ modalVisible: false }); } _this.props.onAnimationEnd(visible); }); } else { if (!visible) { _this.setState({ modalVisible: false }); } } }; _this.close = function () { _this.animateDialog(false); }; _this.onMaskClose = function () { if (_this.props.maskClosable) { _this.props.onClose(); } }; _this.getPosition = function (visible) { if (visible) { return 0; } return _this.props.animationType === 'slide-down' ? -screen.height : screen.height; }; _this.getScale = function (visible) { return visible ? 1 : 1.05; }; _this.getOpacity = function (visible) { return visible ? 1 : 0; }; var visible = props.visible; _this.state = { position: new Animated.Value(_this.getPosition(visible)), scale: new Animated.Value(_this.getScale(visible)), opacity: new Animated.Value(_this.getOpacity(visible)), modalVisible: visible }; return _this; } _createClass(RCModal, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.shouldComponentUpdate(nextProps)) { this.setState({ modalVisible: true }); } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { if (this.props.visible || this.props.visible !== nextProps.visible) { return true; } if (nextState) { if (nextState.modalVisible !== this.state.modalVisible) { return true; } } return false; } }, { key: 'componentDidMount', value: function componentDidMount() { if (this.props.animateAppear && this.props.animationType !== 'none') { this.componentDidUpdate({}); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var props = this.props; if (prevProps.visible !== props.visible) { this.animateDialog(props.visible); } } }, { key: 'render', value: function render() { var props = this.props; if (!this.state.modalVisible) { return null; } var animationStyleMap = { none: {}, 'slide-up': { transform: [{ translateY: this.state.position }] }, 'slide-down': { transform: [{ translateY: this.state.position }] }, fade: { transform: [{ scale: this.state.scale }], opacity: this.state.opacity } }; return React.createElement(Modal, { visible: true, transparent: true, onRequestClose: this.props.onClose, supportedOrientations: ['portrait', 'landscape'] }, React.createElement(View, { style: [styles.wrap, props.wrapStyle] }, React.createElement(TouchableWithoutFeedback, { onPress: this.onMaskClose }, React.createElement(Animated.View, { style: [styles.absolute, { opacity: this.state.opacity }] }, React.createElement(View, { style: [styles.absolute, props.maskStyle] }))), React.createElement(Animated.View, { style: [styles.content, props.style, animationStyleMap[props.animationType]] }, this.props.children))); } }]); return RCModal; }(React.Component); export default RCModal; RCModal.defaultProps = { wrapStyle: styles.wrap, maskStyle: styles.mask, animationType: 'slide-up', animateAppear: false, animationDuration: 300, visible: false, maskClosable: true, onClose: function onClose() {}, onAnimationEnd: function onAnimationEnd(_visible) {} };
client/my-sites/invites/utils.js
mmmavis/mofo-calypso
/** * Internal dependencies */ import React from 'react'; import get from 'lodash/object/get' /** * Internal dependencies */ import i18n from 'lib/mixins/i18n'; export default { acceptedNotice( invite, displayOnNextPage = true ) { let takeATour = ( <p className="invite-message__intro"> { i18n.translate( 'Since you\'re new, you might like to {{docsLink}}take a tour{{/docsLink}}.', { components: { docsLink: <a href="https://learn.wordpress.com/" target="_blank" /> } } ) } </p> ); let site = ( <a href={ get( invite, 'site.URL' ) } className="invite-accept__notice-site-link"> { get( invite, 'site.title' ) } </a> ); switch ( get( invite, 'role' ) ) { case 'follower': return [ i18n.translate( 'You are now following {{site/}}', { components: { site } } ), { button: i18n.translate( 'Visit Site' ), href: get( invite, 'site.URL' ), displayOnNextPage } ]; break; case 'viewer': return [ i18n.translate( 'You are now a viewer of: {{site/}}', { components: { site } } ), { button: i18n.translate( 'Visit Site' ), href: get( invite, 'site.URL' ), displayOnNextPage } ]; break; case 'administrator': return [ <div> <h3 className="invite-message__title"> { i18n.translate( 'You\'re now an Administrator of: {{site/}}', { components: { site } } ) } </h3> <p className="invite-message__intro"> { i18n.translate( 'This is your site dashboard where you will be able to manage all aspects of %(site)s', { args: { site: get( invite, 'site.title' ) } } ) } </p> { takeATour } </div>, { displayOnNextPage } ]; break; case 'editor': return [ <div> <h3 className="invite-message__title"> { i18n.translate( 'You\'re now an Editor of: {{site/}}', { components: { site } } ) } </h3> <p className="invite-message__intro"> { i18n.translate( 'This is your site dashboard where you can publish and manage your own posts and the posts of others, as well as upload media.' ) } </p> { takeATour } </div>, { displayOnNextPage } ]; break; case 'author': return [ <div> <h3 className="invite-message__title"> { i18n.translate( 'You\'re now an Author of: {{site/}}', { components: { site } } ) } </h3> <p className="invite-message__intro"> { i18n.translate( 'This is your site dashboard where you can publish and edit your own posts as well as upload media.' ) } </p> { takeATour } </div>, { displayOnNextPage } ]; break; case 'contributor': return [ <div> <h3 className="invite-message__title"> { i18n.translate( 'You\'re now a Contributor of: {{site/}}', { components: { site } } ) } </h3> <p className="invite-message__intro"> { i18n.translate( 'This is your site dashboard where you can write and manage your own posts.' ) } </p> { takeATour } </div>, { displayOnNextPage } ]; break; case 'subscriber': return [ i18n.translate( 'You\'re now a Subscriber of: {{site/}}', { components: { site } } ), { displayOnNextPage } ]; break; } }, getRedirectAfterAccept( invite ) { switch ( invite.role ) { case 'viewer': case 'follower': return '/'; break; default: return '/posts/' + invite.site.ID; } } };
app/javascript/mastodon/features/compose/components/poll_button.js
dunn/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ add_poll: { id: 'poll_button.add_poll', defaultMessage: 'Add a poll' }, remove_poll: { id: 'poll_button.remove_poll', defaultMessage: 'Remove poll' }, }); const iconStyle = { height: null, lineHeight: '27px', }; export default @injectIntl class PollButton extends React.PureComponent { static propTypes = { disabled: PropTypes.bool, unavailable: PropTypes.bool, active: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleClick = () => { this.props.onClick(); } render () { const { intl, active, unavailable, disabled } = this.props; if (unavailable) { return null; } return ( <div className='compose-form__poll-button'> <IconButton icon='tasks' title={intl.formatMessage(active ? messages.remove_poll : messages.add_poll)} disabled={disabled} onClick={this.handleClick} className={`compose-form__poll-button-icon ${active ? 'active' : ''}`} size={18} inverted style={iconStyle} /> </div> ); } }
src/components/users/UserAvatar.js
secretin/secretin-app
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import User from 'models/User'; const COLORS = [ 'emerland', 'nephritis', 'belize-hole', 'wisteria', 'midnight-blue', 'sun-flower', 'pumpkin', 'pomegranate', 'silver', 'asbestos', ]; function getInitials(fullName) { const names = fullName.split(' '); if (names.length > 1) { return `${names[0][0]}${names[1][0]}`.toUpperCase(); } return fullName.substring(0, 2).toUpperCase(); } function getAvatarColor(fullName) { const colorIndex = fullName .split('') .reduce((sum, letter) => sum + letter.charCodeAt(), 0); return COLORS[colorIndex % COLORS.length]; } const propTypes = { user: PropTypes.instanceOf(User), size: PropTypes.oneOf(['base', 'large']), }; const defaultProps = { size: 'base', }; function UserAvatar({ user, size }) { const color = getAvatarColor(user.username); const className = classNames( 'user-avatar', `user-avatar--color-${color}`, `user-avatar--size-${size}` ); return ( <div className={className} title={user.username}> {getInitials(user.username)} </div> ); } UserAvatar.propTypes = propTypes; UserAvatar.defaultProps = defaultProps; export default UserAvatar;
src/browser/extension/popup/index.js
UrgBenri/UrgBenriWeb
import React from 'react'; import { render } from 'react-dom'; import Root from 'app/containers/Root'; chrome.runtime.getBackgroundPage(background => { const { store, unsubscribe } = background.getStore(); render( <Root store={store} />, document.getElementById('root') ); addEventListener('unload', unsubscribe, true); });
src/js/components/icons/base/Camera.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-camera`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'camera'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,21 L1,7 L6,7 L8,3 L16,3 L18,7 L23,7 L23,21 L1,21 Z M12,18 C14.7614237,18 17,15.7614237 17,13 C17,10.2385763 14.7614237,8 12,8 C9.23857625,8 7,10.2385763 7,13 C7,15.7614237 9.23857625,18 12,18 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Camera'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
docs/src/app/components/pages/components/Menu/ExampleSimple.js
manchesergit/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; const style = { display: 'inline-block', margin: '16px 32px 16px 0', }; const MenuExampleSimple = () => ( <div> <Paper style={style}> <Menu> <MenuItem primaryText="Maps" /> <MenuItem primaryText="Books" /> <MenuItem primaryText="Flights" /> <MenuItem primaryText="Apps" /> </Menu> </Paper> <Paper style={style}> <Menu> <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help &amp; feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Sign out" /> </Menu> </Paper> </div> ); export default MenuExampleSimple;
src/widgets/Anchor.js
xiaofan2406/react-starter-kit
import React from 'react'; import PropTypes from 'prop-types'; const Anchor = ({ href, children, ...rest }) => ( <a rel="noopener noreferrer" target="_blank" href={href} {...rest}> {children} </a> ); Anchor.propTypes = { href: PropTypes.string.isRequired, children: PropTypes.node.isRequired, }; export default Anchor;
ui/components/loading.js
danjac/podbaby
import React from 'react'; import Icon from './icon'; export default function () { return ( <div className="text-center" style={{ marginTop: 50 }}> <h1 style={{ fontFamily: 'GoodDog' }}><Icon icon="spinner" spin /> loading...</h1> </div> ); }
src/js/pages/ResetPasswordPage.js
MichaelFKogan/project3
import React from 'react'; import DocumentTitle from 'react-document-title'; import { ResetPasswordForm } from 'react-stormpath'; export default class ResetPasswordPage extends React.Component { render() { return ( <DocumentTitle title={`Login`}> <div className="container"> <div className="row"> <div className="col-xs-12"> <h3>Forgot Password</h3> <hr /> </div> </div> <ResetPasswordForm /> </div> </DocumentTitle> ); } }
app/javascript/mastodon/features/notifications/index.js
Toootim/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandNotifications, scrollTopNotifications } from '../../actions/notifications'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import NotificationContainer from './containers/notification_container'; import { ScrollContainer } from 'react-router-scroll'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { createSelector } from 'reselect'; import Immutable from 'immutable'; import LoadMore from '../../components/load_more'; import { debounce } from 'lodash'; const messages = defineMessages({ title: { id: 'column.notifications', defaultMessage: 'Notifications' }, }); const getNotifications = createSelector([ state => Immutable.List(state.getIn(['settings', 'notifications', 'shows']).filter(item => !item).keys()), state => state.getIn(['notifications', 'items']), ], (excludedTypes, notifications) => notifications.filterNot(item => excludedTypes.includes(item.get('type')))); const mapStateToProps = state => ({ notifications: getNotifications(state), isLoading: state.getIn(['notifications', 'isLoading'], true), isUnread: state.getIn(['notifications', 'unread']) > 0, hasMore: !!state.getIn(['notifications', 'next']), }); @connect(mapStateToProps) @injectIntl export default class Notifications extends React.PureComponent { static propTypes = { columnId: PropTypes.string, notifications: ImmutablePropTypes.list.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, isLoading: PropTypes.bool, isUnread: PropTypes.bool, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, }; static defaultProps = { trackScroll: true, }; dispatchExpandNotifications = debounce(() => { this.props.dispatch(expandNotifications()); }, 300, { leading: true }); dispatchScrollToTop = debounce((top) => { this.props.dispatch(scrollTopNotifications(top)); }, 100); handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; const offset = scrollHeight - scrollTop - clientHeight; this._oldScrollPosition = scrollHeight - scrollTop; if (250 > offset && this.props.hasMore && !this.props.isLoading) { this.dispatchExpandNotifications(); } if (scrollTop < 100) { this.dispatchScrollToTop(true); } else { this.dispatchScrollToTop(false); } } componentDidUpdate (prevProps) { if (this.node.scrollTop > 0 && (prevProps.notifications.size < this.props.notifications.size && prevProps.notifications.first() !== this.props.notifications.first() && !!this._oldScrollPosition)) { this.node.scrollTop = this.node.scrollHeight - this._oldScrollPosition; } } handleLoadMore = (e) => { e.preventDefault(); this.dispatchExpandNotifications(); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('NOTIFICATIONS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = (c) => { this.node = c; } setColumnRef = c => { this.column = c; } render () { const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore } = this.props; const pinned = !!columnId; let loadMore = ''; let scrollableArea = ''; let unread = ''; let scrollContainer = ''; if (!isLoading && notifications.size > 0 && hasMore) { loadMore = <LoadMore onClick={this.handleLoadMore} />; } if (isUnread) { unread = <div className='notifications__unread-indicator' />; } if (isLoading && this.scrollableArea) { scrollableArea = this.scrollableArea; } else if (notifications.size > 0) { scrollableArea = ( <div className='scrollable' onScroll={this.handleScroll} ref={this.setRef}> {unread} <div> {notifications.map(item => <NotificationContainer key={item.get('id')} notification={item} accountId={item.get('account')} />)} {loadMore} </div> </div> ); } else { scrollableArea = ( <div className='empty-column-indicator' ref={this.setRef}> <FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." /> </div> ); } if (pinned) { scrollContainer = scrollableArea; } else { scrollContainer = ( <ScrollContainer scrollKey={`notifications-${columnId}`} shouldUpdateScroll={shouldUpdateScroll}> {scrollableArea} </ScrollContainer> ); } this.scrollableArea = scrollableArea; return ( <Column ref={this.setColumnRef}> <ColumnHeader icon='bell' active={isUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer /> </ColumnHeader> {scrollContainer} </Column> ); } }
client/src/signup/Form.js
petertrotman/adventurelookup
import React from 'react'; import { connect } from 'react-redux'; import { signupEmail } from './actions'; @connect( state => ({ signup: state.signup }), dispatch => ({ submitEmail: (email, validity) => ( dispatch(signupEmail(email, validity)) ) }), ) class SignupForm extends React.Component { constructor(props) { super(props); this.state = { email: this.props.signup.email, validity: {} }; this.changeHandler = this.changeHandler.bind(this); this.clickHandler = this.clickHandler.bind(this); } changeHandler(e) { e.preventDefault(); this.setState({ email: e.target.value, validity: e.target.validity, }); } clickHandler(e) { e.preventDefault(); this.props.submitEmail(this.state.email, this.state.validity); } render() { return ( <div className="signup-form"> <form> <input type="email" value={this.state.email || ''} onChange={this.changeHandler} /> <button type="submit" onClick={this.clickHandler} > Sign Up </button> </form> <div> { this.props.signup.isValid ? null : <span className="warning">Not a valid e-mail address.</span> } { this.props.signup.completed ? <span className="success">You have successfully signed up!</span> : null } </div> </div> ); } } SignupForm.propTypes = { signup: React.PropTypes.object, submitEmail: React.PropTypes.func, }; export default SignupForm;
client/src/containers/FileListPage.js
RiddleMan/giant-privacy-spy
import React, { Component } from 'react'; import Paper from 'material-ui/Paper'; import { GridList } from 'material-ui/GridList'; import { GridFilePreview } from '../components/layout'; import { connect } from 'react-redux'; import { routeActions } from 'react-router-redux'; import { clear, getNextUnboxed, setGeoHash } from '../actions/list'; import { findDOMNode } from 'react-dom'; import CircularProgress from 'material-ui/CircularProgress'; /* eslint-disable */ const styles = { gridList: { overflowY: 'scroll' }, }; /* eslint-enable */ class FileListPage extends Component { constructor(props) { super(props); this.onResize = this.onResize.bind(this); this.onScroll = this.onScroll.bind(this); this.state = { columnsCount: this.noOfColumns }; this.onFileSelect = this.onFileSelect.bind(this); } onFileSelect(file) { this.props.goToFile(file._id); } onScroll() { const { getNextUnboxed } = this.props; if(this.scroller.scrollTop + this.scroller.offsetHeight >= this.scroller.scrollHeight - 50) getNextUnboxed(); } onResize() { if(this.state.columnsCount !== this.noOfColumns) this.setState({ columnsCount: this.noOfColumns }); } get noOfColumns() { if(window.matchMedia('(min-width: 1200px)').matches) return 5; if(window.matchMedia('(min-width: 768px)').matches) return 4; if(window.matchMedia('(min-width: 480px)').matches) return 3; return 2; } componentDidMount() { const { setGeoHash, params: { id }, getNextUnboxed } = this.props; setGeoHash(id); getNextUnboxed(); window.addEventListener('resize', this.onResize); this.scroller.addEventListener('wheel', this.onScroll); } componentWillUpdate(nextProps) { if(nextProps.params.id !== this.props.params.id) { const { setGeoHash, clear, getNextUnboxed } = this.props; const { params: { id } } = nextProps; clear(); setGeoHash(id); getNextUnboxed(); } } componentWillUnmount() { const { clear } = this.props; clear(); window.removeEventListener('resize', this.onResize); if(this.scroller) this.scroller.removeEventListener('wheel', this.onScroll); } shouldComponentUpdate(nextProps) { return this.props.list.isFetching !== nextProps.list.isFetching || this.props.list.files !== nextProps.list.files || this.props.params.id !== nextProps.params.id; } render() { const { list } = this.props; const { isFetching } = list; const { columnsCount } = this.state; return ( <Paper className='mainPage__overlay'> <GridList ref={(r) => this.scroller = findDOMNode(r)} cols={columnsCount} cellHeight={200} style={styles.gridList}> {list.files.map(file => <GridFilePreview onSelect={this.onFileSelect} key={file.fileId} file={file} {...file}/>)} </GridList> { isFetching && <CircularProgress style={{ position: 'fixed', bottom: 10, left: '50%', transform: 'translateX(-50%)' }} size={50}/> } </Paper>); } } const mapStateToProps = (state) => { const { list } = state; return { list }; }; export default connect(mapStateToProps, { setGeoHash, getNextUnboxed, clear, goToFile: (fileId) => routeActions.push(`/file/${fileId}`) })(FileListPage);
frontend/src/DiscoverMovie/DiscoverMovieFooterLabel.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import SpinnerIcon from 'Components/SpinnerIcon'; import { icons } from 'Helpers/Props'; import styles from './DiscoverMovieFooterLabel.css'; function DiscoverMovieFooterLabel(props) { const { className, label, isSaving } = props; return ( <div className={className}> {label} { isSaving && <SpinnerIcon className={styles.savingIcon} name={icons.SPINNER} isSpinning={true} /> } </div> ); } DiscoverMovieFooterLabel.propTypes = { className: PropTypes.string.isRequired, label: PropTypes.string.isRequired, isSaving: PropTypes.bool.isRequired }; DiscoverMovieFooterLabel.defaultProps = { className: styles.label }; export default DiscoverMovieFooterLabel;
app/components/resources/resourcePage.js
nypl-registry/browse
import React from 'react' import ReactDOM from 'react-dom' import { Link } from 'react-router' import { connect } from 'react-redux' import { resourceOverview, resourceByOwi } from '../../utils.js' require('core-js/fn/object/entries') import HeaderNav from '../shared/header_nav.js' import Hero from '../shared/hero.js' import Footer from '../shared/footer.js' import { fetchResourceIfNeeded } from '../../actions' const ResourcePage = React.createClass({ componentDidMount: function () { const { dispatch, params } = this.props dispatch(fetchResourceIfNeeded(params.id)) /* var self = this resourceOverview(this.props.params.id, function (results) { self.setState({data: results.data}) }) */ }, shouldComponentUpdate: function (nextProps, nextState) { return true }, componentDidUpdate () { ReactDOM.findDOMNode(this).scrollIntoView() }, componentWillReceiveProps: function (nextProps) { /* resourceOverview(nextProps.params.id, function (results) { this.setState({data: results.data}) }.bind(this)) */ }, renderEntry (entry) { // counter++ var d = entry // console.log('entry: ', entry) var key = entry[0] var values = entry[1] if (key === '@context') return null if (!Array.isArray(values)) values = [values] entry.push([]) values.forEach((v) => { if (v['@id'] && v['@id'].search('terms:') > -1) { v = v['prefLabel'] } if (typeof v === 'object') { v['@id'] = v['@id'].replace(':', '/') v['@id'] = v['@id'].replace('resourcetypes/', 'http://id.loc.gov/vocabulary/resourceTypes/') v['@id'] = v['@id'].replace('language/', 'http://id.loc.gov/vocabulary/languages/') v['@id'] = v['@id'].replace('res/', '/resources/') if (v.title) v.prefLabel = v.title if (!v.filename) v.filename = [] if (d[0].search('roles:') === -1) { if (v.filename.length > 0) { v.filename.forEach((c) => { d[2].push(<Link to={v['@id']}><img src={`http://images.nypl.org/index.php?t=t&id=${c}`}/></Link>) }) } else { if (v['@id'].search('vocabulary/resourceTypes') > -1 || v['@id'].search('vocabulary/languages') > -1) { d[2].push(<a href={`${v['@id']}`}>{v.prefLabel}</a>) } else { d[2].push(<Link to={v['@id']}>{v.prefLabel}</Link>) } } } else { d[0] = v.note d[2].push(<Link to={v['@id']}>{v.prefLabel}</Link>) } } else { if (d[0] === 'idBnum') { if (this.state.data.suppressed) { d[2].push(<span key={`link-${v}`}>{v} (SUPPRESSED)</span>) } else { d[2].push(<a key={`link-${v}`} href={`http://catalog.nypl.org/record=${v}`}>{v}</a>) } } else if (d[0] === 'idMssColl') { d[2].push(<a key={`link-${v}`} href={`http://archives.nypl.org/${v}`}>{v}</a>) } else if (d[0] === 'idMss') { d[2].push(<a key={`link-${v}`} href={`http://archives.nypl.org/detail/${v}`}>{v}</a>) } else if (d[0] === 'idOclc' || d[0] === 'idOclcExact') { d[2].push(<a key={`link-${v}`} href={`http://worldcat.org/oclc/${v}`}>{v}</a>) } else if (d[0] === 'idOwi') { d[2].push(<a key={`link-${v}`} href={`http://classify.oclc.org/classify2/ClassifyDemo?owi=${v}`}>{v}</a>) d[2].push(<OWILinks id={this.props.params.id} owi={v} />) } else if (d[0] === 'idLccCoarse') { d[2].push(<a key={`link-${v}`} href={`http://billi.nypl.org/classmark/${v}`}>{v}</a>) } else if (d[0] === 'idMmsDb') { if (this.state.data['@type'].indexOf('nypl:Item') > -1) { d[2].push(<a key={`link-${v}`} href={`http://metadata.nypl.org/items/show/${v}`}>{v}</a>) } if (this.state.data['@type'].indexOf('nypl:Collection') > -1) { d[2].push(<a key={`link-${v}`} href={`http://metadata.nypl.org/collection/${v}`}>{v}</a>) } } else { d[2].push(<span key={`span-${v.toString()}`}>{v.toString()}<br/><br/></span>) } } }) return ( <div key={key} className='resource-item-fields'> <div key={key} style={(d[1].length === 0) ? { color: 'lightgrey' } : {}} className='resource-item-fields-label'>{d[0]}</div> {d[2].map((v, ind) => { return <div key={`${key}.${ind}`} className='resource-item-fields-value'>{v}</div> })} </div> ) }, render () { if (this.props.isFetching) { return ( <div> <HeaderNav title='data.nypl / Resources' link='/' /> <Hero image={false} textUpper='' textMiddle='Loading...' textLower='' /> </div> ) } else { // console.log(this.state.data.idBnum[0], '$%^&#$') var textMiddle = '' var textLower = '' var imageUrl = {} var textMiddleClass = 'agent-hero-middle-text' var textLowerClass = 'agent-hero-lower-text' if (this.props.item) { // imageUrl = this.state.data.agent.depiction textMiddle = this.props.item.title[0] imageUrl = false imageUrl = (this.props.item && this.props.item.idBnum && this.props.item.idBnum[0]) ? { idBnum: this.props.item.idBnum[0] } : false // textLower = <span>{this.state.data.agent.description}</span> // if (this.state.data.agent.name) if (this.state.data.agent.topFiveRoles.length>0){ // textLower = <span>{this.state.data.agent.description}<br/>{this.state.data.agent.topFiveRoles.join(", ")}</span> // } // console.log() } var entries = this.props.item ? Object.entries(this.props.item).map(this.renderEntry) : null return ( <div> <HeaderNav title='data.nypl / Resources' link='/' /> <Hero textMiddleClass={textMiddleClass} textLowerClass={textLowerClass} image={{ url: imageUrl, title: '', link: '' }} textUpper='' textMiddle={textMiddle} textLower={textLower} /> <div className='container'> <div className='row'> <div className='three columns'> <div> </div> </div> <div className='seven columns'> <div> {entries} </div> </div> <div className='two columns resource-data-links'> <a href={`/resources/${this.props.params.id}/jsonld`}>JSON-LD</a> <br/> <br/> <a href={`/resources/${this.props.params.id}/nt`}>N-Triples</a> </div> </div> </div> <Footer /> </div> ) } } }) const OWILinks = React.createClass({ componentDidMount: function () { var self = this if (this.props.owi) { resourceByOwi(this.props.owi, function (results) { self.setState({data: results.data}) }) } }, shouldComponentUpdate: function (nextProps, nextState) { return true }, componentWillReceiveProps: function (nextProps) { if (this.props.owi) { resourceByOwi(nextProps.owi, function (results) { this.setState({data: results.data}) }.bind(this)) } }, render () { var id = this.props.id var hasRelated = false var realtedEd = this.state.data.itemListElement.map((owi) => { if (parseInt(id) === parseInt(owi.result['@id'].replace('res:', ''))) return <span/> if (owi.result && owi.result.dateStart && owi.result.title) { hasRelated = true return <span key={owi.result['@id']}><Link to={owi.result['@id'].replace('res:', 'resources/')}> ({owi.result.dateStart}) {owi.result.title} </Link><br/></span> } else if (owi.result && owi.result.title) { hasRelated = true return <span key={owi.result['@id']}><Link to={owi.result['@id'].replace('res:', 'resources/')}> {owi.result.title} </Link><br/></span> } else { return <span key={owi.result['@id']} /> } }) if (hasRelated) { return ( <div className='resource-owi-box'> <span>Related Editions:</span> <br/> {realtedEd} </div> ) } else { return ( <span/> ) } } }) function mapStateToProps (state) { const { resource } = state const { uri, isFetching, item } = resource || { isFetching: true, item: null } return { uri, item, isFetching } } export default connect(mapStateToProps)(ResourcePage)
browser/modules/layerTree/controls/SelectControl.js
mapcentia/vidi
/* * @author Alexander Shumilov * @copyright 2013-2019 MapCentia ApS * @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3 */ import React from 'react'; import PropTypes from 'prop-types'; /** * Select control component */ class SelectControl extends React.Component { constructor(props) { super(props); } render() { let options = []; options.push(<option key={`option_null`} value="">{__(`Select`)}</option>) this.props.restriction.map((option, index) => { options.push(<option key={`option_${index}`} value={option.value}>{option.alias}</option>) }); return (<select id={this.props.id} value={this.props.value} className="form-control" onChange={(event) => { this.props.onChange(event.target.value) }}> {options} </select>); } } SelectControl.propTypes = { id: PropTypes.string.isRequired, value: PropTypes.string.isRequired, restriction: PropTypes.array.isRequired, onChange: PropTypes.func.isRequired, }; export { SelectControl };
src/js/Components/BackgroundPane/ImageBackgroundView.js
mattgordils/DropSplash
import React, { Component } from 'react'; import Button from 'Components/Common/Button'; import PlusIcon from 'assets/icons/plus-icon'; import InlineSVG from 'svg-inline-react/lib'; import ColorPicker from 'Components/Common/ColorPicker/ColorPicker'; import 'sass/components/common/inputs'; export default class App extends Component { render () { return ( <div className="has-button" key="view1"> <div className="content pane-padded"> <div className="ds-empty-content light">Upload Image</div> <input type="file" className="hidden" /> </div> <div className="pane-view-actions"> <Button buttonClass="medium hollow" label="Add Color Overlay" clickEvent={this.props.clickHandler} /> </div> </div> ); } }
docs/app/Examples/elements/Image/Variations/ImageAvatarExample.js
jcarbo/stardust
import React from 'react' import { Image } from 'stardust' const src = 'http://semantic-ui.com/images/wireframe/square-image.png' const ImageAvatarExample = () => ( <div> <Image src={src} avatar /> <span>Username</span> </div> ) export default ImageAvatarExample
src/parser/paladin/protection/CONFIG.js
sMteX/WoWAnalyzer
import React from 'react'; import { emallson } from 'CONTRIBUTORS'; import SPECS from 'game/SPECS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { TooltipElement } from 'common/Tooltip'; import retryingPromise from 'common/retryingPromise'; import Warning from 'interface/common/Alert/Warning'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [emallson], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.1', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Hello, and welcome to the Protection Paladin Analyzer! This analyzer is maintained by <a href="//raider.io/characters/us/arthas/Akromah"><code>emallson</code></a>, a Brewmaster main and Paladin fan, with assistance from the Protection theorycraft team.<br /><br /> If you are new to the spec, focus first on hitting the targets in the Checklist and Suggestions tabs. The statistics below provide further insight both into your performance and into the effectiveness of your gear and stats.<br /><br /> If you have questions about the output, please ask in the <code>#protection-questions</code> channel of the <a href="https://discord.gg/0dvRDgpa5xZHFfnD">Hammer of Wrath</a>. If you have theorycrafting questions or want to contribute, feel free to ask in <code>#protection</code>.<br /><br /> <Warning> Because <SpellLink id={SPELLS.GRAND_CRUSADER.id} /> <TooltipElement content="The combatlog does not contain any events for random cooldown resets.">can't be tracked</TooltipElement> properly without the <SpellLink id={SPELLS.INSPIRING_VANGUARD.id} /> trait, any cooldown information of <SpellLink id={SPELLS.AVENGERS_SHIELD.id} /> should be treated as <TooltipElement content="Whenever Avenger's Shield would be cast before its cooldown would have expired normally, the cooldown expiry will be set back to the last possible trigger of Grand Crusade. This may lead to higher times on cooldown than you actually experienced in-game.">educated guesses</TooltipElement> (unless you have the trait). </Warning> </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/8-Athenríl', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.PROTECTION_PALADIN, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "ProtectionPaladin" */).then(exports => exports.default)), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
tests/Rules-isExisty-spec.js
aesopwolf/formsy
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isExisty" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with a string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should fail with null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a zero': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); } };
client/views/setupWizard/SideBar.stories.js
Sing-Li/Rocket.Chat
import { select } from '@storybook/addon-knobs'; import React from 'react'; import SideBar from './SideBar'; export default { title: 'views/setupWizard/SideBar', component: SideBar, }; export const _default = () => <SideBar logoSrc='https://open.rocket.chat/images/logo/logo.svg' steps={[ { step: 1, title: 'Define the problem', }, { step: 2, title: 'Generate alternative solutions', }, { step: 3, title: 'Select an alternative', }, { step: 4, title: 'Implement the solution', }, ]} currentStep={select('currentStep', [1, 2, 3, 4])} />; export const atSomeStep = () => <SideBar logoSrc='https://open.rocket.chat/images/logo/logo.svg' steps={[ { step: 1, title: 'Define the problem', }, { step: 2, title: 'Generate alternative solutions', }, { step: 3, title: 'Select an alternative', }, { step: 4, title: 'Implement the solution', }, ]} currentStep={2} />;
app/javascript/mastodon/features/ui/util/reduced_motion.js
pso2club/mastodon
// Like react-motion's Motion, but reduces all animations to cross-fades // for the benefit of users with motion sickness. import React from 'react'; import Motion from 'react-motion/lib/Motion'; import PropTypes from 'prop-types'; const stylesToKeep = ['opacity', 'backgroundOpacity']; const extractValue = (value) => { // This is either an object with a "val" property or it's a number return (typeof value === 'object' && value && 'val' in value) ? value.val : value; }; class ReducedMotion extends React.Component { static propTypes = { defaultStyle: PropTypes.object, style: PropTypes.object, children: PropTypes.func, } render() { const { style, defaultStyle, children } = this.props; Object.keys(style).forEach(key => { if (stylesToKeep.includes(key)) { return; } // If it's setting an x or height or scale or some other value, we need // to preserve the end-state value without actually animating it style[key] = defaultStyle[key] = extractValue(style[key]); }); return ( <Motion style={style} defaultStyle={defaultStyle}> {children} </Motion> ); } } export default ReducedMotion;
frontend/src/components/eois/details/applications/applicationSummary/applicationSummaryHeader.js
unicef/un-partner-portal
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import R from 'ramda'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import Typography from 'material-ui/Typography'; import HeaderNavigation from '../../../../common/headerNavigation'; import { selectApplication, selectApplicationStatus, isUserAFocalPoint, isUserAReviewer, selectReview, selectAssessment, isCfeiCompleted, isCfeiDeadlinePassed, selectCfeiStatus, isUserACreator, } from '../../../../../store'; import ApplicationStatusText from '../applicationStatusText'; import GridRow from '../../../../common/grid/gridRow'; import EditReviewModalButton from './reviewContent/editReviewModalButton'; import AddReviewModalButton from './reviewContent/addReviewModalButton'; import WithdrawApplicationButton from '../../../buttons/withdrawApplicationButton'; import { APPLICATION_STATUSES, PROJECT_STATUSES } from '../../../../../helpers/constants'; import { checkPermission, AGENCY_PERMISSIONS, isRoleOffice, AGENCY_ROLES } from '../../../../../helpers/permissions'; const messages = { header: 'Application from:', noCfei: 'Sorry but this application doesn\'t exist', retracted: 'Retracted', }; class ApplicationSummaryHeader extends Component { constructor(props) { super(props); this.isAssessActionAllowed = this.isAssessActionAllowed.bind(this); this.isReatractAllowed = this.isReatractAllowed.bind(this); } isReatractAllowed() { const { hasRetractPermission, isAdvEd, isMFT, isCreator, isFocalPoint } = this.props; return ((hasRetractPermission && isAdvEd && (isCreator || isFocalPoint)) || (hasRetractPermission && isMFT && isFocalPoint)); } isAssessActionAllowed(hasActionPermission) { const { isAdvEd, isPAM, isBasEd, isMFT, isReviewer, isCreator, isFocalPoint } = this.props; return ((hasActionPermission && isAdvEd && isReviewer) || (hasActionPermission && isBasEd && isReviewer) || (hasActionPermission && isMFT && isFocalPoint) || (hasActionPermission && isPAM && isCreator)); } renderActionButton() { const { loading, reviews, user, status, getAssessment, params: { applicationId }, didWin, didWithdraw, hasAssessPermission, isCompleted, isDeadlinePassed, cfeiStatus, } = this.props; const disabled = loading || status !== APPLICATION_STATUSES.PRE || cfeiStatus !== PROJECT_STATUSES.CLO; if (loading || isCompleted || status !== APPLICATION_STATUSES.PRE) return <div />; const assessment = getAssessment(reviews && reviews[user]); if (assessment && assessment.completed) { if (didWin) { if (didWithdraw) { return <Button disabled>{messages.retracted}</Button>; } return (this.isReatractAllowed() && <WithdrawApplicationButton raised applicationId={applicationId} />); } } else if (hasAssessPermission) { if (R.prop(user, reviews) && this.isAssessActionAllowed(hasAssessPermission)) { const assessment = getAssessment(reviews[user]); return (!assessment.completed ? <EditReviewModalButton assessmentId={reviews[user]} scores={getAssessment(reviews[user])} reviewer={`${user}`} disabled={disabled} /> : null); } else if (this.isAssessActionAllowed(hasAssessPermission) && isDeadlinePassed) { return (<AddReviewModalButton raised reviewer={`${user}`} />); } } return <div />; } renderContent() { const { partner, status, applicationStatus, children, error, params: { id }, } = this.props; if (error.notFound) { return <Typography >{messages.noApplication}</Typography>; } else if (error.message) { return <Typography >{error.message}</Typography>; } return (<HeaderNavigation title={`${messages.header} ${partner}`} header={<GridRow alignItems="center"> {status && <ApplicationStatusText status={status} applicationStatus={applicationStatus} />} {this.renderActionButton()} </GridRow> } backButton defaultReturn={`/cfei/open/${id}/preselected`} > {children} </HeaderNavigation>); } render() { return ( <Grid item> {this.renderContent()} </Grid> ); } } ApplicationSummaryHeader.propTypes = { partner: PropTypes.string, status: PropTypes.string, children: PropTypes.node, params: PropTypes.object, error: PropTypes.object, loading: PropTypes.bool, user: PropTypes.number, isFocalPoint: PropTypes.bool, isReviewer: PropTypes.bool, isCreator: PropTypes.bool, reviews: PropTypes.object, getAssessment: PropTypes.func, hasAssessPermission: PropTypes.bool, hasRetractPermission: PropTypes.bool, didWin: PropTypes.bool, didWithdraw: PropTypes.bool, cfeiStatus: PropTypes.string, applicationStatus: PropTypes.string, isAdvEd: PropTypes.bool, isMFT: PropTypes.bool, isPAM: PropTypes.bool, isBasEd: PropTypes.bool, isCompleted: PropTypes.bool, isDeadlinePassed: PropTypes.bool, }; const mapStateToProps = (state, ownProps) => { const application = selectApplication(state, ownProps.params.applicationId) || {}; const reviews = selectReview(state, ownProps.params.applicationId) || {}; const { eoi, did_win, did_withdraw, assessments_is_completed = false, application_status, partner: { legal_name, partner_additional: { flagging_status: { red: redFlags = 0, } = {}, is_verified: isVerified, } = {}, } = {}, } = application; return { isAdvEd: isRoleOffice(AGENCY_ROLES.EDITOR_ADVANCED, state), isMFT: isRoleOffice(AGENCY_ROLES.MFT_USER, state), isPAM: isRoleOffice(AGENCY_ROLES.PAM_USER, state), isBasEd: isRoleOffice(AGENCY_ROLES.EDITOR_BASIC, state), status: selectApplicationStatus(state, ownProps.params.applicationId), applicationStatus: application_status, partner: legal_name, getAssessment: id => selectAssessment(state, id), loading: state.applicationDetails.status.loading, error: state.applicationDetails.status.error, isFocalPoint: isUserAFocalPoint(state, eoi), isCreator: isUserACreator(state, eoi), cfeiStatus: selectCfeiStatus(state, eoi), isReviewer: isUserAReviewer(state, eoi), hasAssessPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_REVIEW_APPLICATIONS, state), hasRetractPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_DESELECT_PARTNER, state), reviews, user: state.session.userId, didWin: did_win, didWithdraw: did_withdraw, isCompleted: isCfeiCompleted(state, eoi), isDeadlinePassed: isCfeiDeadlinePassed(state, eoi), }; }; export default R.compose( withRouter, connect(mapStateToProps), )(ApplicationSummaryHeader);
src/client/components/hoc/AdressBar/withHistory.hoc.js
DBCDK/content-first
import React from 'react'; import {connect} from 'react-redux'; import { HISTORY_PUSH, HISTORY_PUSH_FORCE_REFRESH, HISTORY_REPLACE } from '../../../redux/middleware'; /** * A HOC that enhance the wrapped component with a number of reducers * with which the History can be accessed * * @param {React.Component} WrappedComponent The component to be enhanced * @returns {React.Component} The enhanced component * */ const withHistory = WrappedComponent => { const Wrapped = class extends React.Component { render() { return <WrappedComponent {...this.props} />; } }; const mapStateToProps = state => ({router: state.routerReducer}); const mapDispatchToProps = dispatch => ({ historyPush: (path, params) => { dispatch({ type: HISTORY_PUSH, path: path, params: params }); }, historyPushForceRefresh: (path, params) => { dispatch({ type: HISTORY_PUSH_FORCE_REFRESH, path: path, params: params }); }, historyReplace: (path, params) => { dispatch({ type: HISTORY_REPLACE, path: path, params: params }); } }); return connect(mapStateToProps, mapDispatchToProps)(Wrapped); }; export default withHistory;
src/decorators/requireVerifiedEmail.js
orionsoft/parts
import React from 'react' import autobind from 'autobind-decorator' import PropTypes from 'prop-types' import Button from '../components/Button' import isPlainObject from 'lodash/isPlainObject' const styles = { container: { textAlign: 'center', padding: 20 }, notAllowed: { fontSize: 20, fontWeight: 'bold', color: 'red' }, needVerify: { fontSize: 14, marginTop: 10, color: '#5c5c5c' }, buttonContainer: { marginTop: 10 }, email: { marginTop: 10, fontSize: 13, color: '#5c5c5c' } } const getDecorator = function(options) { return function(ComposedComponent) { class WithRoles extends React.Component { static contextTypes = { me: PropTypes.object, resendVerificationEmail: PropTypes.func } state = {} @autobind async sendVerificationEmail() { if (this.state.sending) return const me = this.context.me || {} const emails = me.emails || [] const email = emails[0] || {} this.setState({sending: true}) await this.context.resendVerificationEmail({email: email.address}) } renderNotAllowed() { const me = this.context.me || {} const emails = me.emails || [] const email = emails[0] || {} return ( <div style={styles.container}> <div style={styles.notAllowed}>{options.title}</div> <div style={styles.needVerify}> {this.state.sending ? options.checkYourInbox : options.youNeedToVerify} </div> <div style={styles.buttonContainer}> <Button loading={this.state.sending} onClick={this.sendVerificationEmail}> {options.buttonText} </Button> </div> <div style={styles.email}>{email.address}</div> </div> ) } render() { const me = this.context.me || {} const emails = me.emails || [] const email = emails[0] || {} const verified = email.verified || false if (verified) { return <ComposedComponent email={email.address} {...this.props} /> } else { return this.renderNotAllowed() } } } return WithRoles } } export default function(passedOptions) { const defaultOptions = { title: 'Not allowed', checkYourInbox: 'Check your inbox', youNeedToVerify: 'You need to verify your email', buttonText: 'Send verification email' } if (isPlainObject(passedOptions)) { const options = { ...defaultOptions, ...passedOptions } return getDecorator(options) } else { return getDecorator(defaultOptions)(passedOptions) } }
react-youtube-adaptive-loading/src/containers/Comments/Comments.js
GoogleChromeLabs/adaptive-loading
import React from 'react'; import {CommentsHeader} from "./CommentsHeader/CommentsHeader"; import {Comment} from './Comment/Comment'; import {AddComment} from './AddComment/AddComment'; export class Comments extends React.Component { render() { if (!this.props.comments) { return <div/>; } const comments = this.props.comments.map((comment) => { return <Comment comment={comment} key={comment.id}/> }); return( <div> <CommentsHeader amountComments={this.props.amountComments}/> <AddComment key='add-comment'/> {comments} </div> ); } }
src/parser/hunter/shared/modules/talents/AMurderOfCrows.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import Abilities from 'parser/core/modules/Abilities'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; /** * Summons a flock of crows to attack your target over the next 15 sec. If the target dies while under attack, A Murder of Crows' cooldown is reset. * * Example log: https://www.warcraftlogs.com/reports/8jJqDcrGK1xM3Wn6#fight=2&type=damage-done */ const CROWS_TICK_RATE = 1000; const MS_BUFFER = 100; const CROWS_DURATION = 15000; const debug = false; class AMurderOfCrows extends Analyzer { static dependencies = { spellUsable: SpellUsable, abilities: Abilities, }; damage = 0; casts = 0; applicationTimestamp = null; lastDamageTick = null; crowsEndingTimestamp = null; maxCasts = 0; resets = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.A_MURDER_OF_CROWS_TALENT.id); if (!this.active) { return; } this.abilities.add({ spell: SPELLS.A_MURDER_OF_CROWS_TALENT, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, cooldown: 60, gcd: { base: 1500, }, castEfficiency: { suggestion: true, recommendedEfficiency: 0.85, maxCasts: () => this.maxCasts, }, ...this.constructor.extraAbilityInfo, }); } checkForReset(event) { // Checks if we've had atleast 1 damage tick of the currently applied crows, and checks that crows is in fact on cooldown. if (this.lastDamageTick && this.spellUsable.isOnCooldown(SPELLS.A_MURDER_OF_CROWS_TALENT.id) // Checks whether the current damage event happened while the time passed since crows application is less than the crows duration && this.applicationTimestamp && event.timestamp < this.crowsEndingTimestamp // Checks to see if more than 1 second has passed since last tick && event.timestamp > this.lastDamageTick + CROWS_TICK_RATE + MS_BUFFER) { // If more than 1 second has passed and less than the duration has elapsed, we can assume that crows has been reset, and thus we reset the CD. this.spellUsable.endCooldown(SPELLS.A_MURDER_OF_CROWS_TALENT.id, event.timestamp); this.maxCasts += 1; this.resets += 1; debug && this.log('Crows was reset'); } } on_byPlayer_cast(event) { const spellId = event.ability.guid; this.checkForReset(event); if (spellId !== SPELLS.A_MURDER_OF_CROWS_TALENT.id) { return; } this.casts++; this.applicationTimestamp = null; this.lastDamageTick = null; } on_byPlayer_energize(event) { this.checkForReset(event); } on_byPlayer_applybuff(event) { this.checkForReset(event); } on_byPlayer_removebuff(event) { this.checkForReset(event); } on_byPlayer_applybuffstack(event) { this.checkForReset(event); } on_byPlayerPet_damage(event) { this.checkForReset(event); } on_byPlayer_damage(event) { const spellId = event.ability.guid; this.checkForReset(event); if (spellId !== SPELLS.A_MURDER_OF_CROWS_DEBUFF.id) { return; } if (this.casts === 0) { this.casts++; this.spellUsable.beginCooldown(SPELLS.A_MURDER_OF_CROWS_TALENT.id, { timestamp: this.owner.fight.start_time, }); this.applicationTimestamp = this.owner.fight.start_time; } //This accounts for the travel time of crows, since the first damage marks the time where the crows debuff is applied if (!this.lastDamageTick && !this.applicationTimestamp) { this.applicationTimestamp = event.timestamp; this.crowsEndingTimestamp = this.applicationTimestamp + CROWS_DURATION; } this.lastDamageTick = event.timestamp; this.damage += event.amount + (event.absorbed || 0); } on_fightend() { this.maxCasts += Math.ceil(this.owner.fightDuration / 60000); } statistic() { return ( <TalentStatisticBox talent={SPELLS.A_MURDER_OF_CROWS_TALENT.id} value={( <> <ItemDamageDone amount={this.damage} /><br /> {this.resets} <small>resets</small> </> )} /> ); } } export default AMurderOfCrows;
src/routes/topicPage/index.js
xugy0926/shuoriyu
import React from 'react'; import TopicPage from './TopicPage'; import fetch from '../../core/fetch'; import { host } from '../../config'; import * as topicService from '../../services/topicService'; export default { path: '/topic/:tid', async action(context, {tid}) { return <TopicPage topicId={tid}/>; }, };
src/Router.js
thethirddan/pocket_axe
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/IncredibleOffers/IncredibleOfferContainer.js
mamal72/dgkala-web
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { GridLoader } from 'halogen'; import IncredibleOffers from './IncredibleOffers'; const mapStateToProps = (state, props) => { return { offers: state.incredibleOffers.data, errors: state.incredibleOffers.errors, isLoading: state.incredibleOffers.isLoading, } }; class IncredibleOfferContainer extends Component { render() { const {offers, errors, isLoading, filter} = this.props; if (isLoading) { return ( <div className="spinner"> <GridLoader color={'#999'}/> </div> ); } return ( <IncredibleOffers filter={filter} errors={errors} offers={offers}/> ); } } export default connect(mapStateToProps)(IncredibleOfferContainer);
src/icons/Close.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Close extends React.Component { render() { if(this.props.bare) { return <g> <path d="M443.6,387.1L312.4,255.4l131.5-130c5.4-5.4,5.4-14.2,0-19.6l-37.4-37.6c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4 L256,197.8L124.9,68.3c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4L68,105.9c-5.4,5.4-5.4,14.2,0,19.6l131.5,130L68.4,387.1 c-2.6,2.6-4.1,6.1-4.1,9.8c0,3.7,1.4,7.2,4.1,9.8l37.4,37.6c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1L256,313.1l130.7,131.1 c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1l37.4-37.6c2.6-2.6,4.1-6.1,4.1-9.8C447.7,393.2,446.2,389.7,443.6,387.1z"></path> </g>; } return <IconBase> <path d="M443.6,387.1L312.4,255.4l131.5-130c5.4-5.4,5.4-14.2,0-19.6l-37.4-37.6c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4 L256,197.8L124.9,68.3c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4L68,105.9c-5.4,5.4-5.4,14.2,0,19.6l131.5,130L68.4,387.1 c-2.6,2.6-4.1,6.1-4.1,9.8c0,3.7,1.4,7.2,4.1,9.8l37.4,37.6c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1L256,313.1l130.7,131.1 c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1l37.4-37.6c2.6-2.6,4.1-6.1,4.1-9.8C447.7,393.2,446.2,389.7,443.6,387.1z"></path> </IconBase>; } };Close.defaultProps = {bare: false}
src/containers/weather_list.js
nobodyislame/weatherApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map'; class WeatherList extends Component{ renderWeather(cityData){ const name = cityData.city.name; const temperatures = cityData.list.map(weather=> weather.main.temp); const pressures = cityData.list.map(weather=>weather.main.pressure); const humidities = cityData.list.map(weather=>weather.main.humidity); const lon = cityData.city.coord.lon; const lat = cityData.city.coord.lat; return( <tr key={ name }> <td> <GoogleMap lon={lon} lat={lat} /> </td> <td><Chart color="red" data={temperatures} units="K"/></td> <td><Chart color="green" data={pressures} units="hPa"/></td> <td><Chart color="blue" data={humidities} units="%"/></td> </tr> ) } render(){ return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (K)</th> <th>Pressure (hPa)</th> <th>Humidity (%) </th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } const mapStateToProps = ({ weather })=>{ //accesing state.weather return { weather } //{ weather : weather } } export default connect(mapStateToProps)(WeatherList);
app/javascript/mastodon/features/picture_in_picture/components/footer.js
ashfurrow/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import classNames from 'classnames'; import { me, boostModal } from 'mastodon/initial_state'; import { defineMessages, injectIntl } from 'react-intl'; import { replyCompose } from 'mastodon/actions/compose'; import { reblog, favourite, unreblog, unfavourite } from 'mastodon/actions/interactions'; import { makeGetStatus } from 'mastodon/selectors'; import { initBoostModal } from 'mastodon/actions/boosts'; import { openModal } from 'mastodon/actions/modal'; const messages = defineMessages({ reply: { id: 'status.reply', defaultMessage: 'Reply' }, replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost with original visibility' }, cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' }, replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' }, open: { id: 'status.open', defaultMessage: 'Expand this status' }, }); const makeMapStateToProps = () => { const getStatus = makeGetStatus(); const mapStateToProps = (state, { statusId }) => ({ status: getStatus(state, { id: statusId }), askReplyConfirmation: state.getIn(['compose', 'text']).trim().length !== 0, }); return mapStateToProps; }; export default @connect(makeMapStateToProps) @injectIntl class Footer extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { statusId: PropTypes.string.isRequired, status: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, askReplyConfirmation: PropTypes.bool, withOpenButton: PropTypes.bool, onClose: PropTypes.func, }; _performReply = () => { const { dispatch, status, onClose } = this.props; const { router } = this.context; if (onClose) { onClose(true); } dispatch(replyCompose(status, router.history)); }; handleReplyClick = () => { const { dispatch, askReplyConfirmation, intl } = this.props; if (askReplyConfirmation) { dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.replyMessage), confirm: intl.formatMessage(messages.replyConfirm), onConfirm: this._performReply, })); } else { this._performReply(); } }; handleFavouriteClick = () => { const { dispatch, status } = this.props; if (status.get('favourited')) { dispatch(unfavourite(status)); } else { dispatch(favourite(status)); } }; _performReblog = (status, privacy) => { const { dispatch } = this.props; dispatch(reblog(status, privacy)); } handleReblogClick = e => { const { dispatch, status } = this.props; if (status.get('reblogged')) { dispatch(unreblog(status)); } else if ((e && e.shiftKey) || !boostModal) { this._performReblog(status); } else { dispatch(initBoostModal({ status, onReblog: this._performReblog })); } }; handleOpenClick = e => { const { router } = this.context; if (e.button !== 0 || !router) { return; } const { status, onClose } = this.props; if (onClose) { onClose(); } router.history.push(`/@${status.getIn(['account', 'acct'])}/${status.get('id')}`); } render () { const { status, intl, withOpenButton } = this.props; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const reblogPrivate = status.getIn(['account', 'id']) === me && status.get('visibility') === 'private'; let replyIcon, replyTitle; if (status.get('in_reply_to_id', null) === null) { replyIcon = 'reply'; replyTitle = intl.formatMessage(messages.reply); } else { replyIcon = 'reply-all'; replyTitle = intl.formatMessage(messages.replyAll); } let reblogTitle = ''; if (status.get('reblogged')) { reblogTitle = intl.formatMessage(messages.cancel_reblog_private); } else if (publicStatus) { reblogTitle = intl.formatMessage(messages.reblog); } else if (reblogPrivate) { reblogTitle = intl.formatMessage(messages.reblog_private); } else { reblogTitle = intl.formatMessage(messages.cannot_reblog); } return ( <div className='picture-in-picture__footer'> <IconButton className='status__action-bar-button' title={replyTitle} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} counter={status.get('replies_count')} obfuscateCount /> <IconButton className={classNames('status__action-bar-button', { reblogPrivate })} disabled={!publicStatus && !reblogPrivate} active={status.get('reblogged')} pressed={status.get('reblogged')} title={reblogTitle} icon='retweet' onClick={this.handleReblogClick} counter={status.get('reblogs_count')} /> <IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} pressed={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} counter={status.get('favourites_count')} /> {withOpenButton && <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.open)} icon='external-link' onClick={this.handleOpenClick} href={status.get('url')} />} </div> ); } }
packages/dante2/src/editor/components/blocks/embed.js
michelson/Dante
import React from 'react' import axios from "axios" import { updateDataOfBlock, addNewBlockAt , resetBlockWithType} from '../../model/index.js' import { EditorBlock } from 'draft-js' import {embed} from '../icons' export default class EmbedBlock extends React.Component { constructor(props) { super(props) this.state = { embed_data: this.defaultData(), error: "" } } defaultData =() =>{ const existing_data = this.props.block.getData().toJS() return existing_data.embed_data || {} } // will update block state updateData =() =>{ const { block, blockProps } = this.props const { getEditorState, setEditorState } = blockProps const data = block.getData() const newData = data.merge(this.state) return setEditorState(updateDataOfBlock(getEditorState(), block, newData)) } deleteSelf = (e)=>{ e.preventDefault() const { block, blockProps } = this.props const { getEditorState, setEditorState } = blockProps const data = block.getData() const newData = data.merge(this.state) return setEditorState(resetBlockWithType(getEditorState(), 'unstyled', {})) } dataForUpdate =()=> { return this.props.blockProps.data.toJS() } componentDidMount() { if (!this.props.blockProps.data) { return } // ensure data isnt already loaded // unless @dataForUpdate().endpoint or @dataForUpdate().provisory_text if (!this.dataForUpdate().endpoint && !this.dataForUpdate().provisory_text) { //debugger return } return axios({ method: 'get', url: `${ this.dataForUpdate().endpoint }${ this.dataForUpdate().provisory_text }&scheme=https` }).then(result => { return this.setState({ embed_data: result.data } //JSON.parse(data.responseText) , this.updateData) }).catch(error => { this.setState({ error: error.response.data.error_message }) return console.log("TODO: error") }) } classForImage = ()=> { if (this.picture()) { return "" } else { return "mixtapeImage--empty u-ignoreBlock" } } //if @state.embed_data.thumbnail_url then "" else "mixtapeImage--empty u-ignoreBlock" picture =()=> { if (this.state.embed_data.images && this.state.embed_data.images.length > 0) { return this.state.embed_data.images[0].url } else if (this.state.embed_data.thumbnail_url ){ return this.state.embed_data.thumbnail_url } else if (this.state.embed_data.image ){ return this.state.embed_data.image } else { return null } } handleClick = (e)=>{ if(!this.props.blockProps.getEditor().props.read_only){ e.preventDefault() } } render() { return ( <span> { this.picture() ? <a target='_blank' className={ `js-mixtapeImage mixtapeImage ${ this.classForImage() }` } href={ this.state.embed_data.url } style={ { backgroundImage: `url('${ this.picture() }')` } } /> : undefined } { this.state.error ? <h2>{ this.state.error }</h2> : undefined } { !this.props.blockProps.getEditor().props.read_only ? <a href="#" className={"graf--media-embed-close"} onClick={this.deleteSelf}> x </a> : null } <a className='markup--anchor markup--mixtapeEmbed-anchor' target='_blank' href={ this.state.embed_data.url } onClick={this.handleClick} contentEditable={false}> <strong className='markup--strong markup--mixtapeEmbed-strong'> { this.state.embed_data.title } </strong> <em className='markup--em markup--mixtapeEmbed-em'> { this.state.embed_data.description } </em> </a> <span contentEditable={false}> { this.state.embed_data.provider_url || this.state.embed_data.url } </span> </span> ) } } export const EmbedBlockConfig = (options={})=>{ let config = { title: 'insert embed', type: 'embed', block: EmbedBlock, icon: embed, editable: true, renderable: true, breakOnContinuous: true, wrapper_class: "graf graf--mixtapeEmbed", selected_class: "is-selected is-mediaFocused", widget_options: { displayOnInlineTooltip: true, insertion: "placeholder", insert_block: "embed" }, options: { endpoint: '//noembed.com/embed?url=', placeholder: 'Paste a link to embed content from another site (e.g. Twitter) and press Enter' }, handleEnterWithoutText(ctx, block) { const { editorState } = ctx.state return ctx.onChange(addNewBlockAt(editorState, block.getKey())) }, handleEnterWithText(ctx, block) { const { editorState } = ctx.state return ctx.onChange(addNewBlockAt(editorState, block.getKey())) } } return Object.assign(config, options) }
node_modules/semantic-ui-react/dist/es/views/Item/ItemMeta.js
SuperUncleCat/ServerMonitoring
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * An item can contain content metadata. */ function ItemMeta(props) { var children = props.children, className = props.className, content = props.content; var classes = cx('meta', className); var rest = getUnhandledProps(ItemMeta, props); var ElementType = getElementType(ItemMeta, props); return React.createElement( ElementType, _extends({}, rest, { className: classes }), childrenUtils.isNil(children) ? content : children ); } ItemMeta.handledProps = ['as', 'children', 'className', 'content']; ItemMeta._meta = { name: 'ItemMeta', parent: 'Item', type: META.TYPES.VIEW }; ItemMeta.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand } : {}; ItemMeta.create = createShorthandFactory(ItemMeta, function (content) { return { content: content }; }); export default ItemMeta;
src/components/Tabs/components/ScrollableTabBar.js
zhangjianguo1500/f01
import React from 'react'; import ScrollableTabBarMixin from './ScrollableTabBarMixin'; import TabBarMixin from './TabBarMixin'; const ScrollableTabBar = React.createClass({ mixins: [TabBarMixin, ScrollableTabBarMixin], render() { const inkBarNode = this.getInkBarNode(); const tabs = this.getTabs(); const scrollbarNode = this.getScrollBarNode([inkBarNode, tabs]); return this.getRootNode(scrollbarNode); }, }); export default ScrollableTabBar;
src/javascripts/container.js
bensmithett/webpack-css-example
import React from 'react' import Header from 'javascripts/header' import Footer from 'javascripts/footer' import 'stylesheets/modules/container' const Container = React.createClass({ render () { return ( <div className='container'> <Header /> <Footer /> </div> ) } }) export default Container
src/routes/nba/index.js
kyleaclark/ballcruncher
/** * 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 Layout from '../../components/layout'; import Nba from './nba'; import fetch from '../../core/fetch'; export default { path: '/nba', async action({ store, path }) { return { title: 'NBA', component: <Layout><Nba /></Layout>, }; }, };
src/server.js
vk92kokil/My-react-boilerplate
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ /* eslint-disable */ import 'babel/polyfill'; import _ from 'lodash'; import fs from 'fs'; import path from 'path'; import express from 'express'; import React from 'react'; import './core/Dispatcher'; import './stores/AppStore'; import db from './core/Database'; import App from './components/App'; const server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/query', require('./api/query')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- // The top-level React component + HTML template for it const templateFile = path.join(__dirname, 'templates/index.html'); const template = _.template(fs.readFileSync(templateFile, 'utf8')); server.get('*', async (req, res, next) => { try { let uri = req.path; let notFound = false; let css = []; let data = {description: ''}; //let app = <App // path={req.path} // context={{ // onInsertCss: value => css.push(value), // onSetTitle: value => data.title = value, // onSetMeta: (key, value) => data[key] = value, // onPageNotFound: () => notFound = true // }} />; //await db.getPage(uri); data.title = "dekorate"; data.body = ""; data.css = css.join(''); let html = template(data); if (notFound) { res.status(404); } res.send(html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { if (process.send) { process.send('online'); } else { console.log('The server is running at http://localhost:' + server.get('port')); } });
client/src/components/ElementActions/ArchiveAction.js
dnadesign/silverstripe-elemental
/* global window */ import React from 'react'; import { compose } from 'redux'; import AbstractAction from 'components/ElementActions/AbstractAction'; import archiveBlockMutation from 'state/editor/archiveBlockMutation'; import i18n from 'i18n'; /** * Adds the elemental menu action to archive a block of any state */ const ArchiveAction = (MenuComponent) => (props) => { const handleClick = (event) => { event.stopPropagation(); const { element: { id }, isPublished, actions: { handleArchiveBlock } } = props; let archiveMessage = i18n._t( 'ElementArchiveAction.CONFIRM_DELETE', 'Are you sure you want to send this block to the archive?' ); if (isPublished) { archiveMessage = i18n._t( 'ElementArchiveAction.CONFIRM_DELETE_AND_UNPUBLISH', 'Warning: This block will be unpublished before being sent to the archive. Are you sure you want to proceed?' ); } // eslint-disable-next-line no-alert if (handleArchiveBlock && window.confirm(archiveMessage)) { handleArchiveBlock(id).then(() => { const preview = window.jQuery('.cms-preview'); preview.entwine('ss.preview')._loadUrl(preview.find('iframe').attr('src')); }); } }; const newProps = { title: i18n._t('ElementArchiveAction.ARCHIVE', 'Archive'), className: 'element-editor__actions-archive', onClick: handleClick, toggle: props.toggle, }; return ( <MenuComponent {...props}> {props.children} <AbstractAction {...newProps} /> </MenuComponent> ); }; export { ArchiveAction as Component }; export default compose(archiveBlockMutation, ArchiveAction);
src/browser/home/HomePage.react.js
vacuumlabs/este
import Component from 'react-pure-render/component'; import Helmet from 'react-helmet'; import React from 'react'; import linksMessages from '../../common/app/linksMessages'; import { FormattedHTMLMessage, defineMessages, injectIntl, intlShape } from 'react-intl'; const messages = defineMessages({ intro: { defaultMessage: ` <p> Ahoy, this is the <a target="_blank" href="https://github.com/este/este">Este</a> dev stack. </p> `, id: 'home.intro' } }); class HomePage extends Component { static propTypes = { intl: intlShape.isRequired }; render() { const { intl } = this.props; const title = intl.formatMessage(linksMessages.home); return ( <div className="home-page"> <Helmet title={title} /> <FormattedHTMLMessage {...messages.intro} /> {/* Use require for assets. It's super useful for CDN. */} <img alt="50x50 placeholder" src={require('./50x50.png')} /> </div> ); } } export default injectIntl(HomePage);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/TemplateInterpolation.js
Antontsyk/react_vk
import React from 'react' function load(name) { return [ { id: 1, name: `${name}1` }, { id: 2, name: `${name}2` }, { id: 3, name: `${name}3` }, { id: 4, name: `${name}4` } ]; } export default class extends React.Component { constructor(props) { super(props); this.done = () => {}; this.props.setCallWhenDone && this.props.setCallWhenDone((done) => { this.done = done; }); this.state = { users: [] }; } async componentDidMount() { const users = load('user_'); this.setState({ users }, () => this.done()); } render() { return ( <div id="feature-template-interpolation"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
src/shared/components/linkButton/linkButton.js
tskuse/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { Link as ScrollLink, Events as ScrollEvent } from 'react-scroll'; import ReactGA from 'react-ga'; import styles from './linkButton.css'; const LinkButton = ({ link, text, theme, scrollLink, isExternal, ...otherProps }) => { /* ******************** */ /* SCROLL LINK BUTTON */ /* ******************** */ if (scrollLink) { // Report scroll link button clicks to Google Analytics if (process.env.NODE_ENV === 'production') { ScrollEvent.scrollEvent.register('begin', () => { ReactGA.event({ category: 'Scroll Button Clicked', action: `Clicked to view ${link} from ${window.location.pathname}`, }); }); } return ( <ScrollLink className={`${styles.linkButton} ${styles[theme]}`} to={link} smooth duration={400} {...otherProps} > {text} </ScrollLink> ); } /* ******************** */ /* EXTERNAL LINK BUTTON */ /* ******************** */ if (isExternal) { if (process.env.NODE_ENV === 'production') { return ( <ReactGA.OutboundLink to={link} eventLabel={`OUTBOUND [${text} Button Click] to ${link} from ${window .location.pathname}`} target="_blank" rel="noopener noreferrer" className={`${styles.linkButton} ${styles[theme]}`} > {text} </ReactGA.OutboundLink> ); } return ( <a href={link} target="_blank" rel="noopener noreferrer" className={`${styles.linkButton} ${styles[theme]}`} > {text} </a> ); } /* ******************** */ /* INTERNAL LINK BUTTON */ /* ******************** */ return ( <Link className={`${styles.linkButton} ${styles[theme]}`} to={link} {...otherProps} > {text} </Link> ); }; LinkButton.propTypes = { link: PropTypes.string.isRequired, text: PropTypes.string.isRequired, theme: PropTypes.string, scrollLink: PropTypes.bool, isExternal: PropTypes.bool, }; LinkButton.defaultProps = { theme: 'blue', scrollLink: false, isExternal: false, }; export default LinkButton;
js/App/Components/Schedule/Summary.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { ScrollView, } from 'react-native'; import { injectIntl } from 'react-intl'; import { CommonActions, } from '@react-navigation/native'; import { FloatingButton, View, } from '../../../BaseComponents'; import { ScheduleProps } from './ScheduleScreen'; import { getSelectedDays, getDeviceActionIcon, prepareVisibleTabs, } from '../../Lib'; import { ActionRow, DaysRow, DeviceRow, TimeRow, AdvancedSettingsBlock } from './SubViews'; import Theme from '../../Theme'; import i18n from '../../Translations/common'; interface Props extends ScheduleProps { paddingRight: number, devices: Object, intl: Object, } type State = { isLoading: boolean, }; class Summary extends View<null, Props, State> { state: State; onToggleAdvanced: (boolean) => void; setRefScroll: (any) => void; scrollView: any; constructor(props: Props) { super(props); const { schedule, intl } = this.props; this.state = { isLoading: false, }; let { formatMessage } = intl; this.h1 = formatMessage(i18n.summary); this.h2 = formatMessage(i18n.posterSummary); this.messageOnAdd = formatMessage(i18n.addScheduleSuccess); this.device = this._getDeviceById(schedule.deviceId); this.onToggleAdvanced = this.onToggleAdvanced.bind(this); this.setRefScroll = this.setRefScroll.bind(this); this.scrollView = null; this.messageOnUpdateFail = formatMessage(i18n.updateScheduleFailure); } componentDidMount() { const { h1, h2 } = this; this.props.onDidMount(h1, h2); } shouldComponentUpdate(nextProps: Object, nextState: Object): boolean { return nextProps.currentScreen === 'Summary'; } saveSchedule = () => { this.setState({ isLoading: true, }); let options = this.props.actions.getScheduleOptions(this.props.schedule); this.props.actions.saveSchedule(options).then((response: Object) => { this.setState({ isLoading: false, }); this.props.actions.getJobs(); this.props.actions.showToast(this.messageOnAdd, 'LONG'); this.resetNavigation(); }).catch((error: Object) => { this.setState({ isLoading: false, }); let message = error.message ? error.message : this.messageOnUpdateFail; this.openDialogueBox({ text: message, }); }); }; openDialogueBox(otherDialogueConfs?: Object = {}) { const { toggleDialogueBox } = this.props; const dialogueData = { ...otherDialogueConfs, show: true, showHeader: true, showPositive: true, closeOnPressPositive: true, }; toggleDialogueBox(dialogueData); } resetNavigation = () => { const { navigation, schedule, route, hiddenTabsCurrentUser, } = this.props; const { params = {}, } = route; const { visibleTabs = [], tabToCheckOrVeryNextIndex, } = prepareVisibleTabs(hiddenTabsCurrentUser, 'Scheduler'); let routes = [ { name: 'Tabs', key: 'Tabs', state: { index: tabToCheckOrVeryNextIndex, routes: visibleTabs.map((vt: string): Object => { return {'name': vt}; }), }, }, ]; if (params.origin === 'DeviceDetails_SchedulesTab') { routes = [ { name: 'Tabs', key: 'Tabs', state: { index: 1, routes: [ { name: 'Dashboard', }, { name: 'Devices', }, { name: 'Sensors', }, { name: 'Scheduler', }, ], }, }, { name: 'DeviceDetails', key: 'DeviceDetails', params: {id: schedule.deviceId}, state: { index: 3, routes: [ { name: 'Overview', }, { name: 'History', }, { name: 'Settings', }, { name: 'SchedulesTab', }, ], }, }, ]; } routes.push({ name: 'InfoScreen', key: 'InfoScreen', params: { ...params, info: 'add_schedule_another', deviceId: schedule.deviceId, }, }); const resetAction = CommonActions.reset({ index: routes.length - 1, routes, }); navigation.dispatch(resetAction); } onToggleAdvanced(state: boolean) { if (state && this.scrollView) { this.scrollView.scrollToEnd({animated: true}); } } setRefScroll(ref: any) { this.scrollView = ref; } render(): React$Element<any> { const { schedule, paddingRight, appLayout, intl, actions, toggleDialogueBox } = this.props; const { formatDate } = intl; const { method, methodValue, weekdays } = schedule; const { container, row, iconSize, buttonStyle, iconStyle, iconContainerStyle, } = this._getStyle(appLayout); const selectedDays = getSelectedDays(weekdays, formatDate); const { deviceType, supportedMethods = {} } = this.device; const actionIcons = getDeviceActionIcon(deviceType, null, supportedMethods); const { retries = 0, retryInterval = 0, reps = 0 } = schedule; return ( <ScrollView ref={this.setRefScroll} keyboardShouldPersistTaps={'always'} style={{flex: 1}} contentContainerStyle={{flexGrow: 1}}> <View style={container}> <DeviceRow row={this.device} containerStyle={row} appLayout={appLayout} intl={intl}/> <ActionRow method={method} actionIcons={actionIcons} showValue={true} methodValue={methodValue} containerStyle={row} iconContainerStyle={iconContainerStyle} appLayout={appLayout} intl={intl} /> <TimeRow schedule={schedule} device={this.device} containerStyle={row} appLayout={appLayout} intl={intl} getSuntime={actions.getSuntime} /> <DaysRow selectedDays={selectedDays} appLayout={appLayout} intl={intl}/> <AdvancedSettingsBlock appLayout={appLayout} intl={intl} onPressInfo={toggleDialogueBox} onDoneEditAdvanced={actions.setAdvancedSettings} retries={retries} retryInterval={retryInterval} reps={reps} onToggleAdvanced={this.onToggleAdvanced}/> </View> <FloatingButton buttonStyle={buttonStyle} iconStyle={iconStyle} onPress={this.saveSchedule} iconName={this.state.isLoading ? false : 'checkmark'} iconSize={iconSize} paddingRight={paddingRight - 2} showThrobber={this.state.isLoading} accessibilityLabel={`${intl.formatMessage(i18n.confirmButton)}, ${intl.formatMessage(i18n.defaultDescriptionButton)}`} /> </ScrollView> ); } _getDeviceById = (deviceId: number): Object => { // TODO: use device description return Object.assign({}, this.props.devices.byId[deviceId], { description: '' }); }; _getStyle = (appLayout: Object): Object => { const { paddingFactor, maxSizeFloatingButton } = Theme.Core; const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const padding = deviceWidth * paddingFactor; let buttonSize = deviceWidth * 0.134666667; buttonSize = buttonSize > maxSizeFloatingButton ? maxSizeFloatingButton : buttonSize; let buttonBottom = deviceWidth * 0.066666667; return { container: { flex: 1, marginBottom: (buttonSize / 2) + buttonBottom, paddingVertical: padding - (padding / 4), }, row: { marginBottom: padding / 4, }, iconSize: deviceWidth * 0.050666667, buttonStyle: { elevation: 4, shadowOpacity: 0.50, }, iconStyle: { fontSize: deviceWidth * 0.050666667, color: '#fff', }, iconContainerStyle: { width: deviceWidth * 0.226666667, }, }; }; } export default (injectIntl(Summary): Object);
node_modules/react-native/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js
odapplications/WebView-with-Lower-Tab-Menu
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, Image, ListView, Platform, StyleSheet, View, } from 'react-native'; import ListItem from '../../components/ListItem'; import Backend from '../../lib/Backend'; export default class ChatListScreen extends Component { static navigationOptions = { title: 'Chats', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./chat-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { isLoading: true, dataSource: ds, }; } async componentDidMount() { const chatList = await Backend.fetchChatList(); this.setState((prevState) => ({ dataSource: prevState.dataSource.cloneWithRows(chatList), isLoading: false, })); } // Binding the function so it can be passed to ListView below // and 'this' works properly inside renderRow renderRow = (name) => { return ( <ListItem label={name} onPress={() => { // Start fetching in parallel with animating this.props.navigation.navigate('Chat', { name: name, }); }} /> ); } render() { if (this.state.isLoading) { return ( <View style={styles.loadingScreen}> <ActivityIndicator /> </View> ); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} style={styles.listView} /> ); } } const styles = StyleSheet.create({ loadingScreen: { backgroundColor: 'white', paddingTop: 8, flex: 1, }, listView: { backgroundColor: 'white', }, icon: { width: 30, height: 26, }, });
src/svg-icons/image/panorama-horizontal.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePanoramaHorizontal = (props) => ( <SvgIcon {...props}> <path d="M20 6.54v10.91c-2.6-.77-5.28-1.16-8-1.16-2.72 0-5.4.39-8 1.16V6.54c2.6.77 5.28 1.16 8 1.16 2.72.01 5.4-.38 8-1.16M21.43 4c-.1 0-.2.02-.31.06C18.18 5.16 15.09 5.7 12 5.7c-3.09 0-6.18-.55-9.12-1.64-.11-.04-.22-.06-.31-.06-.34 0-.57.23-.57.63v14.75c0 .39.23.62.57.62.1 0 .2-.02.31-.06 2.94-1.1 6.03-1.64 9.12-1.64 3.09 0 6.18.55 9.12 1.64.11.04.21.06.31.06.33 0 .57-.23.57-.63V4.63c0-.4-.24-.63-.57-.63z"/> </SvgIcon> ); ImagePanoramaHorizontal = pure(ImagePanoramaHorizontal); ImagePanoramaHorizontal.displayName = 'ImagePanoramaHorizontal'; ImagePanoramaHorizontal.muiName = 'SvgIcon'; export default ImagePanoramaHorizontal;
examples/src/homeRoute.js
HBM/md-components
import React from 'react' import {Icon} from 'md-components' export default class HomeRoute extends React.Component { render () { return ( <div className='Home'> <div className='Hero'> <div className='Hero-logo'> <h1> <span>md</span> <span>components</span> </h1> </div> <h4 className='Hero-sponsor'>powered by <a href='https://www.hbm.com'><Icon.Logo fill='#333' /></a></h4> <div className='Hero-tagline'> Material Design components for React </div> <div className='Hero-links'> <iframe title='GitHub buttons' src='https://ghbtns.com/github-btn.html?user=hbm&repo=md-components&type=star&count=true&size=large' frameBorder='0' scrolling='0' height='30px' width='130px' /> </div> </div> </div> ) } }
pootle/static/js/admin/general/staticpages.js
Finntack/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import ReactDOM from 'react-dom'; import LiveEditor from './components/LiveEditor'; const staticpages = { init(opts) { ReactDOM.render( <LiveEditor initialValue={opts.initialValue} markup={opts.markup} name={opts.htmlName} />, document.querySelector('.js-staticpage-editor') ); }, }; export default staticpages;
frontend/src/components/TransactionEmptyState.js
OpenCollective/opencollective-website
import React from 'react'; export default ({i18n}) => { return ( <div className='center'> <div className='Collective-emptyState-image flex items-center justify-center'> <img width='134' height='120' src='/public/images/collectives/activities-empty-state-image.jpg' srcSet='/public/images/collectives/[email protected] 2x'/> </div> <p className='h3 -fw-bold'>{i18n.getString('transactionsPlaceholderTitle')}</p> <p className='h5 muted'>{i18n.getString('transactionsPlaceholderText')}</p> </div> ); }
src/main.js
nchathu2014/todo-redux
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <App/>, document.getElementById('container') );
src/components/term.js
RexSkz/drone-ui
import React from 'react'; import Status from './status'; import TermRow from './term_row'; import './term.less'; export default class Term extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { const {proc, open} = this.props; if (this.props.onClick) { e.preventDefault(); this.props.onClick({ data: { proc: proc, open: !open } }); } } render() { const {proc, lines, open} = this.props; let rows = []; for (var i=0;i < lines.length; i++) { let line = lines[i]; rows.push(<TermRow line={line} key={i} />); } if (proc.end_time && proc.end_time != 0) { rows.push( <div className="term-row term-row-exit-code" key="exit"> <div>exit code {proc.exit_code}</div> </div> ); } var attrs = {'open': open}; return ( <details className="term" {...attrs}> <summary onClick={this.handleClick}> <span>{proc.name}</span> <Status state={proc.state} /> </summary> <div>{rows}</div> </details> ); } }
src/containers/protected/agencies_edit.js
hisarkaya/polinsur
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import { fetchAgency, updateAgency, setNavigation } from '../actions'; import localization from '../helpers/localization'; import Content from '../components/templates/content'; import ContentHeader from '../components/templates/content_header'; import ContentBody from '../components/templates/content_body'; import AgencyForm from '../components/forms/agency_form'; class AgenciesEdit extends Component { constructor(props) { super(props); } componentDidMount() { const {id} = this.props.match.params; this.props.fetchAgency(id); this.props.setNavigation('agencies', 'agencies/agencyDetail/editAgency', 'user'); } onSubmit(values) { const {id} = this.props.match.params; values.updateDate = { '.sv': 'timestamp' }; values.name = values.name.toUpperCase(); values.surname = values.surname.toUpperCase(); if(values.insuranceCompanies && values.insuranceCompanies.length > 0) { this.props.updateAgency(values, id, () => { this.props.history.push(`/agencies/${id}`); }); } else { this.props.history.push(`/agencies/edit/${id}`); } } render() { const {handleSubmit, match: { params: { id } }} = this.props; const {name, surname} = this.props.initialValues; const title = `${localization.edit}: ${name} ${surname}`; return( <Content> <ContentHeader title={title} icon="pencil"> </ContentHeader> <ContentBody> <AgencyForm onSubmit={this.onSubmit.bind(this)} handleSubmit={handleSubmit} cancel={`/agencies/${id}`} /> </ContentBody> </Content> ) } } function mapStateToProps(state, ownProps) { return { initialValues: state.agencies[ownProps.match.params.id] } } AgenciesEdit = reduxForm({form: 'AgenciesEditForm'})(AgenciesEdit); AgenciesEdit = connect(mapStateToProps, {fetchAgency, updateAgency, setNavigation})(AgenciesEdit); export default AgenciesEdit;
docs/src/examples/elements/Image/States/ImageExampleHidden.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Image } from 'semantic-ui-react' const ImageExampleHidden = () => ( <Image src='/images/wireframe/image.png' size='small' hidden /> ) export default ImageExampleHidden
packages/app/app/components/Dashboard/BestNewMusicTab/BestNewMusicMenu/index.js
nukeop/nuclear
import React from 'react'; import PropTypes from 'prop-types'; import { Menu } from 'semantic-ui-react'; import { useTranslation } from 'react-i18next'; import BestNewMusicCardContainer from '../../../../containers/BestNewMusicCardContainer'; import BestNewMusicCard, { bestNewItemShape } from './BestNewMusicCard'; import styles from './styles.scss'; const BestNewMusicMenu = ({ albums, setActiveItem, tracks }) => { const { t } = useTranslation('dashboard'); return ( <div className={styles.best_new_music_menu}> <Menu vertical size='large'> <Menu.Item className={styles.best_new_music_menu_header} link > {t('best-new-albums')} </Menu.Item> { albums && albums.map(album => { return ( <Menu.Item link key={album.title}> <BestNewMusicCard item={album} onClick={() => setActiveItem(album)} /> </Menu.Item> ); }) } <Menu.Item className={styles.best_new_music_menu_header} link > {t('best-new-tracks')} </Menu.Item> { tracks && tracks.map(track => { return ( <Menu.Item link key={track.title}> <BestNewMusicCardContainer item={track} onClick={() => setActiveItem(track)} withFavoriteButton /> </Menu.Item> ); }) } </Menu> </div> ); }; BestNewMusicMenu.propTypes = { albums: PropTypes.arrayOf(bestNewItemShape), tracks: PropTypes.arrayOf(bestNewItemShape), setActiveItem: PropTypes.func }; export default BestNewMusicMenu;
src/svg-icons/hardware/dock.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDock = (props) => ( <SvgIcon {...props}> <path d="M8 23h8v-2H8v2zm8-21.99L8 1c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM16 15H8V5h8v10z"/> </SvgIcon> ); HardwareDock = pure(HardwareDock); HardwareDock.displayName = 'HardwareDock'; export default HardwareDock;
src/client/index.js
avantgrogg/avantcasts
import React from 'react'; import { generateStore } from './store'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; import $ from 'jquery'; import "babel-polyfill"; import '../scss/main.scss'; import 'bulma'; import { Route, BrowserRouter as Router, browserHistory } from 'react-router-dom'; import createHistory from 'history/createBrowserHistory'; const history = createHistory(); import { SearchContainer as Search } from './containers/searchContainer'; import { PodcastsContainer as Podcasts } from './containers/podcastsContainer'; import { PodcastContainer as Podcast } from './containers/podcastContainer'; import { PlayerContainer as Player } from './containers/playerContainer'; let store = generateStore(); window.__store = store; render( <Provider store={store}> <div> <Router> <div className="columns"> <div className="column is-2"> <Podcasts/> </div> <div className="column"> <Route path="/search" component={Search}/> <Route path="/podcast/:id" component={Podcast}/> </div> <div className="column is-3"> <Player/> </div> </div> </Router> </div> </Provider>, $('#root')[0] );
examples/05 Customize/Drop Effects/Container.js
numso/react-dnd
import React, { Component } from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd/modules/backends/HTML5'; import SourceBox from './SourceBox'; import TargetBox from './TargetBox'; @DragDropContext(HTML5Backend) export default class Container extends Component { render() { return ( <div style={{ overflow: 'hidden', clear: 'both', marginTop: '1.5rem' }}> <div style={{ float: 'left' }}> <SourceBox showCopyIcon /> <SourceBox /> </div> <div style={{ float: 'left' }}> <TargetBox /> </div> </div> ); } }
src/GovernmentMemberModal.js
escabc/members-search-app
import React from 'react' import Modal from 'react-modal' import ModalSection from './ModalSection' import CorporateAvatar from './CorporateAvatar' import Button from './Button' import MemberName from './MemberName' import MemberDetailsItem from './MemberDetailsItem' import theme from './theme' const styles = { root: { display: 'flex', color: theme.colors.grey.darker, fontSize: 18, fontWeight: 'bold', cursor: 'pointer', }, modal: { overlay: { overflowY: 'scroll', backgroundColor: 'rgba(44, 62, 80, 0.6)', }, content: { width: 600, bottom: 'initial', padding: 0, margin: '0 auto 0 auto', borderRadius: 6, borderColor: '#FFFFFF', }, }, header: { root: { display: 'flex', alignItems: 'center', }, leftColumn: { padding: 24, width: 185, backgroundColor: '#FAFAFA', }, rightColumn: { paddingLeft: 20, }, }, body: { root: { display: 'flex', borderBottom: 'solid 1px #E7ECF1', }, leftColumn: { paddingLeft: 24, flex: '0 0 185px', backgroundColor: '#FAFAFA', }, rightColumn: { paddingLeft: 20, }, }, name: { fontSize: 18, fontWeight: 'bold', color: '#2C3E50', }, description: { marginTop: 20, color: '#5E738B', fontSize: 13, lineHeight: '18px', }, region: { marginTop: 10, fontSize: 16, color: '#5E738B', }, link: { color: '#526825', textDecoration: 'none', }, footer: { padding: '20px 40px', display: 'flex', justifyContent: 'flex-end', }, } const GovernmentMemberModal = ({ open, member, onClose }) => { const { name, description, avatar, expired, regions = [], email, phone, fax, website, location = {}, contact = {}, program = {}, } = member return ( <Modal style={styles.modal} shouldCloseOnOverlayClick contentLabel="Government Member Modal" isOpen={open} onRequestClose={onClose} > <div style={styles.header.root}> <div style={styles.header.leftColumn}> <CorporateAvatar image={avatar} /> </div> <div style={styles.header.rightColumn}> <MemberName value={name} expired={expired} /> <div style={styles.region}>{regions[0]}</div> </div> </div> <div style={styles.body.root}> <div style={styles.body.leftColumn} /> <div style={styles.body.rightColumn}> <ModalSection title="Contact Info"> {location ? <MemberDetailsItem icon="map-marker"> <div>{location.address} {location.city}</div> <div>{location.province}, {location.country} {location.postalCode}</div> </MemberDetailsItem> : null } {phone ? <MemberDetailsItem icon="phone">{phone}</MemberDetailsItem> : null} {fax ? <MemberDetailsItem icon="fax">{fax}</MemberDetailsItem> : null} {website ? <MemberDetailsItem icon="link"><a style={styles.link} href={website} target="_blank" rel="noopener noreferrer">Visit Website</a></MemberDetailsItem> : null} {email ? <MemberDetailsItem icon="envelope">{email}</MemberDetailsItem> : null} </ModalSection> <ModalSection title="ESC Contact"> {contact.name ? <MemberDetailsItem icon="user">{contact.name}</MemberDetailsItem> : null} {contact.department ? <MemberDetailsItem icon="briefcase">{contact.department}</MemberDetailsItem> : null} {contact.phone ? <MemberDetailsItem icon="phone">{contact.phone}</MemberDetailsItem> : null} {contact.email ? <MemberDetailsItem icon="envelope">{contact.email}</MemberDetailsItem> : null} </ModalSection> <ModalSection title="ESC Program Information"> {program.website ? <MemberDetailsItem icon="link"><a style={styles.link} href={program.website} target="_blank" rel="noopener noreferrer">Visit Website</a></MemberDetailsItem> : null} {program.rainfallLink ? <MemberDetailsItem icon="tint"><a style={styles.link} href={program.rainfallLink} target="_blank" rel="noopener noreferrer">Check Rainfall Information</a></MemberDetailsItem> : null} </ModalSection> {description ? <div style={styles.description}>{description}</div> : null} </div> </div> <div style={styles.footer}> <Button onClick={onClose}>Close</Button> {expired ? <Button styleType="warning" style={{ marginLeft: 20 }} onClick={() => (window.location.href = 'https://escabc.site-ym.com/login.aspx?returl=/default.asp?')}>Renew Membership</Button> : null} </div> </Modal> ) } GovernmentMemberModal.propTypes = {} GovernmentMemberModal.defaultProps = { member: {}, } export default GovernmentMemberModal
src/svg-icons/editor/multiline-chart.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMultilineChart = (props) => ( <SvgIcon {...props}> <path d="M22 6.92l-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z"/> </SvgIcon> ); EditorMultilineChart = pure(EditorMultilineChart); EditorMultilineChart.displayName = 'EditorMultilineChart'; EditorMultilineChart.muiName = 'SvgIcon'; export default EditorMultilineChart;
components/NormalLayout.js
isogon/styled-mdl-website
import React from 'react' import styled from 'styled-components' import Layout from './Layout' const Content = styled.div` display: flex; flex-grow: 1; flex-direction: column; margin: 74px auto 60px; padding-left: 24px; padding-right: 24px; @media (min-width: 1032px) { padding-left: 90px; padding-right: 90px; max-width: 1260px; } ` const NormalLayout = (props) => ( <Layout> <Content>{props.children}</Content> </Layout> ) export default NormalLayout
src/Checkbox.js
networknt/react-schema-form
/** * Created by steve on 20/09/15. */ import React from 'react' import Checkbox from '@mui/material/Checkbox' import FormGroup from '@mui/material/FormGroup' import FormControlLabel from '@mui/material/FormControlLabel' import ComposedComponent from './ComposedComponent' function FormCheckbox(props) { const { model, form, value, setDefault, localization: { getLocalizedString }, onChangeValidate } = props const { key } = form setDefault(key, model, form, value) return ( <FormGroup row> <FormControlLabel className={form.className} label={form.title && getLocalizedString(form.title)} control={ <Checkbox name={form.key.slice(-1)[0]} value={form.key.slice(-1)[0]} checked={value || false} disabled={form.readonly} onChange={onChangeValidate} /> } {...form.otherProps} /> </FormGroup> ) } export default ComposedComponent(FormCheckbox)
packages/react-dom/src/shared/checkReact.js
rricard/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import invariant from 'shared/invariant'; invariant( React, 'ReactDOM was loaded before React. Make sure you load ' + 'the React package before loading ReactDOM.', );
src/svg-icons/maps/local-phone.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPhone = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); MapsLocalPhone = pure(MapsLocalPhone); MapsLocalPhone.displayName = 'MapsLocalPhone'; MapsLocalPhone.muiName = 'SvgIcon'; export default MapsLocalPhone;
packages/react-scripts/template/src/index.js
sigmacomputing/create-react-app
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
js/rendererjs/pluginapi.js
NebulousLabs/Sia-UI
// pluginapi.js: Sia-UI plugin API interface exposed to all plugins. // This is injected into every plugin's global namespace. import * as Siad from 'sia.js' import { remote } from 'electron' import React from 'react' import DisabledPlugin from './disabledplugin.js' import Path from 'path' const dialog = remote.dialog const mainWindow = remote.getCurrentWindow() const config = remote.getGlobal('config') const siadConfig = config.siad const fs = remote.require('fs') let disabled = false const sleep = (ms = 0) => new Promise(r => setTimeout(r, ms)) window.onload = async function () { // ReactDOM needs a DOM in order to be imported, // but the DOM is not available until the plugin has loaded. // therefore, we have to global require it inside the window.onload event. /* eslint-disable global-require */ const ReactDOM = require('react-dom') /* eslint-enable global-require */ let startSiad = () => {} const renderSiadCrashlog = () => { // load the error log and display it in the disabled plugin let errorMsg = 'Siad exited unexpectedly for an unknown reason.' try { errorMsg = fs.readFileSync( Path.join(siadConfig.datadir, 'siad-output.log'), { encoding: 'utf-8' } ) } catch (e) { console.error('error reading error log: ' + e.toString()) } document.body.innerHTML = '<div style="width:100%;height:100%;" id="crashdiv"></div>' ReactDOM.render( <DisabledPlugin errorMsg={errorMsg} startSiad={startSiad} />, document.getElementById('crashdiv') ) } startSiad = () => { const siadProcess = Siad.launch(siadConfig.path, { 'sia-directory': siadConfig.datadir, 'rpc-addr': siadConfig.rpcaddr, 'host-addr': siadConfig.hostaddr, 'api-addr': siadConfig.address, modules: 'cghrtw' }) siadProcess.on('error', renderSiadCrashlog) siadProcess.on('close', renderSiadCrashlog) siadProcess.on('exit', renderSiadCrashlog) window.siadProcess = siadProcess } // Continuously check (every 2000ms) if siad is running. // If siad is not running, disable the plugin by mounting // the `DisabledPlugin` component in the DOM's body. // If siad is running and the plugin has been disabled, // reload the plugin. while (true) { const running = await Siad.isRunning(siadConfig.address) if (running && disabled) { disabled = false window.location.reload() } if (!running && !disabled) { disabled = true renderSiadCrashlog() } await sleep(2000) } } window.SiaAPI = { call: function (url, callback) { Siad.call(siadConfig.address, url) .then(res => callback(null, res)) .catch(err => callback(err, null)) }, config: config, hastingsToSiacoins: Siad.hastingsToSiacoins, siacoinsToHastings: Siad.siacoinsToHastings, openFile: options => dialog.showOpenDialog(mainWindow, options), saveFile: options => dialog.showSaveDialog(mainWindow, options), showMessage: options => dialog.showMessageBox(mainWindow, options), showError: options => dialog.showErrorBox(options.title, options.content) }
app/components/Footer.js
madeleinehuish/awesomeVideoApp
import React from 'react'; const Footer = () => { return ( <div style={styles.footer}> <div className="container"> <p style={styles.footerText}> &#169; MH & CK</p> </div> </div> ) }; export default Footer; const styles = { footer: { backgroundColor: '#4C4E60' }, footerText: { fontFamily: 'Overpass Mono', color: '#D9DAE0', padding: '.5em', fontSize: '14px' } }
docs/src/pages/ParallaxPage.js
chris-gooley/react-materialize
import React from 'react'; import Row from 'Row'; import Col from 'Col'; import ReactPlayground from './ReactPlayground'; import PropTable from './PropTable'; import Samples from './Samples'; import parallax from '../../../examples/Parallax'; import parallaxCode from '!raw-loader!Parallax'; const ParallaxPage = () => ( <Row> <Col m={9} s={12} l={10}> <p className='caption'> Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling. Check out the demo to get a better idea of it. </p> <Col s={12}> <ReactPlayground code={Samples.parallax}> {parallax} </ReactPlayground> </Col> <Col s={12}> <PropTable component={parallaxCode} header='Parallax' /> </Col> </Col> </Row> ); export default ParallaxPage;
src/parser/warlock/demonology/modules/talents/InnerDemons.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatThousands } from 'common/format'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import DemoPets from '../pets/DemoPets'; import PETS from '../pets/PETS'; import { isRandomPet } from '../pets/helpers'; class InnerDemons extends Analyzer { static dependencies = { demoPets: DemoPets, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.INNER_DEMONS_TALENT.id); } get damage() { const wildImps = this.demoPets.getPetDamage(PETS.WILD_IMP_INNER_DEMONS.guid); const otherPetsSummonedByID = this.demoPets.timeline.filter(pet => isRandomPet(pet.guid) && pet.summonedBy === SPELLS.INNER_DEMONS_TALENT.id); const other = otherPetsSummonedByID .map(pet => this.demoPets.getPetDamage(pet.guid, pet.instance)) .reduce((total, current) => total + current, 0); return wildImps + other; } subStatistic() { const damage = this.damage; return ( <StatisticListBoxItem title={<><SpellLink id={SPELLS.INNER_DEMONS_TALENT.id} /> dmg</>} value={this.owner.formatItemDamageDone(damage)} valueTooltip={( <> {formatThousands(damage)} damage<br /> Note that this only counts the direct damage from them, not Implosion damage (if used) from Wild Imps </> )} /> ); } } export default InnerDemons;
content/gocms/src/admin/containers/adminPages/dashboardPage/dashboardPage.container.js
gocms-io/gocms
'use strict'; import React from 'react'; import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup' import {connect} from 'react-redux' class DashboardPage extends React.Component { constructor(props) { super(props); this.state = { }; } componentWillMount() { } componentDidMount() { } render() { return ( <h1>dashboard</h1> ); } } function mapStateToProps(state) { return {} } export default connect(mapStateToProps, { })(DashboardPage);