path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/scenes/home/informationForm/formComponents/militaryInfo.js
miaket/operationcode_frontend
import React, { Component } from 'react'; import { Line } from 'rc-progress'; import Form from 'shared/components/form/form'; import PropTypes from 'prop-types'; import FormSelect from 'shared/components/form/formSelect/formSelect'; import { MILSTATUS, BRANCH, BRANCH_PROMPT } from 'shared/constants/status'; import styles from './formComponents.css'; class MilitaryInfo extends Component { constructor(props) { super(props); this.state = { branchPrompt: BRANCH_PROMPT.other }; } onChange = (e) => { this.props.update(e, e.target.value); if (e.target.value === 'spouse') { this.setState({ branchPrompt: BRANCH_PROMPT.spouse }); } else { this.setState({ branchPrompt: BRANCH_PROMPT.other }); } }; render() { return ( <Form className={styles.signup}> <h3>Progress = {this.props.percent}%</h3> <Line percent={this.props.percent} strokeWidth="4" strokeColor="green" /> <FormSelect id="militaryStatus" options={MILSTATUS} prompt="Current Military Status" onChange={e => this.onChange(e)} /> <FormSelect id="branch" options={BRANCH} prompt={this.state.branchPrompt} onChange={e => this.props.update(e, e.target.value)} /> </Form> ); } } MilitaryInfo.propTypes = { update: PropTypes.func, percent: PropTypes.string }; MilitaryInfo.defaultProps = { update: null, percent: '0' }; export default MilitaryInfo;
docs/components/Docs/Content/index.js
enjoylife/storybook
import React from 'react'; import PropTypes from 'prop-types'; import 'highlight.js/styles/github-gist.css'; import Highlight from '../../Highlight'; import './style.css'; const DocsContent = ({ title, content, editUrl }) => <div id="docs-content"> <div className="content"> <h2 className="title">{title}</h2> <p> <a className="edit-link" href={editUrl} target="_blank" rel="noopener noreferrer"> Edit this page </a> </p> <div className="markdown"> <Highlight> {content} </Highlight> </div> </div> </div>; DocsContent.propTypes = { title: PropTypes.string.isRequired, content: PropTypes.string.isRequired, editUrl: PropTypes.string.isRequired, }; export { DocsContent as default };
archimate-frontend/src/main/javascript/components/view/nodes/model_b/businessFunction.js
zhuj/mentha-web-archimate
import React from 'react' import _ from 'lodash' import { ModelNodeWidget } from '../BaseNodeWidget' export const TYPE='businessFunction'; export class BusinessFunctionWidget extends ModelNodeWidget { getClassName(node) { return 'a-node model_b businessFunction'; } }
admin/client/App/shared/CreateForm.js
Adam14Four/keystone
/** * The form that's visible when "Create <ItemName>" is clicked on either the * List screen or the Item screen */ import React from 'react'; import assign from 'object-assign'; import vkey from 'vkey'; import AlertMessages from './AlertMessages'; import { Fields } from 'FieldTypes'; import InvalidFieldType from './InvalidFieldType'; import { Button, Form, Modal } from 'elemental'; const CreateForm = React.createClass({ displayName: 'CreateForm', propTypes: { err: React.PropTypes.object, isOpen: React.PropTypes.bool, list: React.PropTypes.object, onCancel: React.PropTypes.func, onCreate: React.PropTypes.func, }, getDefaultProps () { return { err: null, isOpen: false, }; }, getInitialState () { // Set the field values to their default values when first rendering the // form. (If they have a default value, that is) var values = {}; Object.keys(this.props.list.fields).forEach(key => { var field = this.props.list.fields[key]; var FieldComponent = Fields[field.type]; values[field.path] = FieldComponent.getDefaultValue(field); }); return { values: values, alerts: {}, }; }, componentDidMount () { document.body.addEventListener('keyup', this.handleKeyPress, false); }, componentWillUnmount () { document.body.removeEventListener('keyup', this.handleKeyPress, false); }, handleKeyPress (evt) { if (vkey[evt.keyCode] === '<escape>') { this.props.onCancel(); } }, // Handle input change events handleChange (event) { var values = assign({}, this.state.values); values[event.path] = event.value; this.setState({ values: values, }); }, // Set the props of a field getFieldProps (field) { var props = assign({}, field); props.value = this.state.values[field.path]; props.values = this.state.values; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, // Create a new item when the form is submitted submitForm (event) { event.preventDefault(); const createForm = event.target; const formData = new FormData(createForm); this.props.list.createItem(formData, (err, data) => { if (data) { if (this.props.onCreate) { this.props.onCreate(data); } else { // Clear form this.setState({ values: {}, alerts: { success: { success: 'Item created', }, }, }); } } else { if (!err) { err = { error: 'connection error', }; } // If we get a database error, show the database error message // instead of only saying "Database error" if (err.error === 'database error') { err.error = err.detail.errmsg; } this.setState({ alerts: { error: err, }, }); } }); }, // Render the form itself renderForm () { if (!this.props.isOpen) return; var form = []; var list = this.props.list; var nameField = this.props.list.nameField; var focusWasSet; // If the name field is an initial one, we need to render a proper // input for it if (list.nameIsInitial) { var nameFieldProps = this.getFieldProps(nameField); nameFieldProps.autoFocus = focusWasSet = true; if (nameField.type === 'text') { nameFieldProps.className = 'item-name-field'; nameFieldProps.placeholder = nameField.label; nameFieldProps.label = ''; } form.push(React.createElement(Fields[nameField.type], nameFieldProps)); } // Render inputs for all initial fields Object.keys(list.initialFields).forEach(key => { var field = list.fields[list.initialFields[key]]; // If there's something weird passed in as field type, render the // invalid field type component if (typeof Fields[field.type] !== 'function') { form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } // Get the props for the input field var fieldProps = this.getFieldProps(field); // If there was no focusRef set previously, set the current field to // be the one to be focussed. Generally the first input field, if // there's an initial name field that takes precedence. if (!focusWasSet) { fieldProps.autoFocus = focusWasSet = true; } form.push(React.createElement(Fields[field.type], fieldProps)); }); return ( <Form type="horizontal" onSubmit={this.submitForm} className="create-form" > <Modal.Header text={'Create a new ' + list.singular} onClose={this.props.onCancel} showCloseButton /> <Modal.Body> <AlertMessages alerts={this.state.alerts} /> {form} </Modal.Body> <Modal.Footer> <Button type="success" submit>Create</Button> <Button type="link-cancel" onClick={this.props.onCancel} > Cancel </Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal isOpen={this.props.isOpen} onCancel={this.props.onCancel} backdropClosesModal > {this.renderForm()} </Modal> ); }, }); module.exports = CreateForm;
step7-unittest/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
src/components/keyshortcuts/TableFilterContextShortcuts.js
metasfresh/metasfresh-webui-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { updateKeymap, updateHotkeys } from '../../actions/AppActions'; import { Shortcut } from '../keyshortcuts'; class TableFilterContextShortcuts extends Component { constructor() { super(); this.state = { shortcutsExtended: false, }; } componentDidMount() { const { shortcutActions, dispatch } = this.props; const updatedKeymap = {}; const updatedHotkeys = {}; shortcutActions.forEach((action) => { updatedKeymap[action.name] = action.shortcut; updatedHotkeys[action.shortcut.toUpperCase()] = []; }); dispatch(updateHotkeys(updatedHotkeys)); dispatch(updateKeymap(updatedKeymap)); this.setState({ shortcutsExtended: true, }); } render() { const { shortcutActions } = this.props; const { shortcutsExtended } = this.state; if (shortcutsExtended) { return shortcutActions.map((shortcut) => ( <Shortcut key={shortcut.shortcut} name={shortcut.name} handler={shortcut.handler} /> )); } return null; } } TableFilterContextShortcuts.propTypes = { shortcutActions: PropTypes.array, dispatch: PropTypes.func, }; const mapStateToProps = () => ({}); export default connect(mapStateToProps)(TableFilterContextShortcuts);
examples/js/components/GettingStarted.js
powerhome/react-bootstrap-table
import React from 'react'; class GettingStarted extends React.Component { render() { return ( <div> <h1>Getting started</h1> <code>npm i react-bootstrap-table --save</code> </div> ); } } export default GettingStarted;
src/svg-icons/notification/personal-video.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPersonalVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12z"/> </SvgIcon> ); NotificationPersonalVideo = pure(NotificationPersonalVideo); NotificationPersonalVideo.displayName = 'NotificationPersonalVideo'; NotificationPersonalVideo.muiName = 'SvgIcon'; export default NotificationPersonalVideo;
src/routes/error/ErrorPage.js
langpavel/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './ErrorPage.css'; class ErrorPage extends React.Component { static propTypes = { error: PropTypes.shape({ name: PropTypes.string.isRequired, message: PropTypes.string.isRequired, stack: PropTypes.string.isRequired, }), }; static defaultProps = { error: null, }; render() { if (__DEV__ && this.props.error) { return ( <div> <h1>{this.props.error.name}</h1> <pre>{this.props.error.stack}</pre> </div> ); } return ( <div> <h1>Error</h1> <p>Sorry, a critical error occurred on this page.</p> </div> ); } } export { ErrorPage as ErrorPageWithoutStyle }; export default withStyles(s)(ErrorPage);
src/svg-icons/action/perm-phone-msg.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermPhoneMsg = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/> </SvgIcon> ); ActionPermPhoneMsg = pure(ActionPermPhoneMsg); ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg'; ActionPermPhoneMsg.muiName = 'SvgIcon'; export default ActionPermPhoneMsg;
src/svg-icons/communication/speaker-phone.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationSpeakerPhone = (props) => ( <SvgIcon {...props}> <path d="M7 7.07L8.43 8.5c.91-.91 2.18-1.48 3.57-1.48s2.66.57 3.57 1.48L17 7.07C15.72 5.79 13.95 5 12 5s-3.72.79-5 2.07zM12 1C8.98 1 6.24 2.23 4.25 4.21l1.41 1.41C7.28 4 9.53 3 12 3s4.72 1 6.34 2.62l1.41-1.41C17.76 2.23 15.02 1 12 1zm2.86 9.01L9.14 10C8.51 10 8 10.51 8 11.14v9.71c0 .63.51 1.14 1.14 1.14h5.71c.63 0 1.14-.51 1.14-1.14v-9.71c.01-.63-.5-1.13-1.13-1.13zM15 20H9v-8h6v8z"/> </SvgIcon> ); CommunicationSpeakerPhone = pure(CommunicationSpeakerPhone); CommunicationSpeakerPhone.displayName = 'CommunicationSpeakerPhone'; export default CommunicationSpeakerPhone;
client/src/components/OptionsetField/OptionsetField.js
silverstripe/silverstripe-admin
import React, { Component } from 'react'; import OptionField from 'components/OptionsetField/OptionField'; import fieldHolder from 'components/FieldHolder/FieldHolder'; import PropTypes from 'prop-types'; class OptionsetField extends Component { constructor(props) { super(props); this.getItemKey = this.getItemKey.bind(this); this.getOptionProps = this.getOptionProps.bind(this); this.handleChange = this.handleChange.bind(this); } /** * Generates a unique key for an item * * @param {object} item * @param {int} index * @returns {string} key */ getItemKey(item, index) { const value = item.value || `empty${index}`; return `${this.props.id}-${value}`; } /** * Fetches the properties for the individual fields. * * @param {object} item * @param {int} index * @returns {object} properties */ getOptionProps(item, index) { const key = this.getItemKey(item, index); return { key, id: key, name: this.props.name, className: `${this.props.itemClass} option-val--${item.value}`, disabled: item.disabled || this.props.disabled, readOnly: this.props.readOnly, onChange: this.handleChange, value: `${this.props.value}` === `${item.value}`, title: item.title, type: 'radio', }; } /** * Handler for sorting what the value of the field will be * * @param {Event} event * @param {object} field */ handleChange(event, field) { if (typeof this.props.onChange === 'function') { if (field.value === 1) { const sourceItem = this.props.source .find((item, index) => this.getItemKey(item, index) === field.id); this.props.onChange(event, { id: this.props.id, value: sourceItem.value }); } } } render() { if (!this.props.source) { return null; } return ( <div> { this.props.source.map((item, index) => ( <OptionField {...this.getOptionProps(item, index)} hideLabels /> )) } </div> ); } } OptionsetField.propTypes = { extraClass: PropTypes.string, itemClass: PropTypes.string, id: PropTypes.string, name: PropTypes.string.isRequired, source: PropTypes.arrayOf(PropTypes.shape({ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), title: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disabled: PropTypes.bool, })), onChange: PropTypes.func, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), readOnly: PropTypes.bool, disabled: PropTypes.bool, }; OptionsetField.defaultProps = { // React considers "undefined" as an uncontrolled component. extraClass: '', className: '', itemClass: '', }; export { OptionsetField as Component }; export default fieldHolder(OptionsetField);
frontend/src/MovieFile/Edit/FileEditModalContent.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Form from 'Components/Form/Form'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import Button from 'Components/Link/Button'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { inputTypes, kinds } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; class FileEditModalContent extends Component { // // Lifecycle constructor(props, context) { super(props, context); const { qualityId, languageIds, indexerFlags, proper, real, edition, releaseGroup } = props; this.state = { qualityId, languageIds, indexerFlags, proper, real, edition, releaseGroup }; } // // Listeners onQualityChange = ({ value }) => { this.setState({ qualityId: parseInt(value) }); } onInputChange = ({ name, value }) => { this.setState({ [name]: value }); } onSaveInputs = () => { this.props.onSaveInputs(this.state); } // // Render render() { const { isFetching, isPopulated, error, qualities, languages, relativePath, onModalClose } = this.props; const { qualityId, languageIds, indexerFlags, proper, real, edition, releaseGroup } = this.state; const qualityOptions = qualities.map(({ id, name }) => { return { key: id, value: name }; }); const languageOptions = languages.map(({ id, name }) => { return { key: id, value: name }; }); return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> {translate('EditMovieFile')} - {relativePath} </ModalHeader> <ModalBody> { isFetching && <LoadingIndicator /> } { !isFetching && !!error && <div> {translate('UnableToLoadQualities')} </div> } { isPopulated && !error && <Form> <FormGroup> <FormLabel>{translate('Quality')}</FormLabel> <FormInputGroup type={inputTypes.SELECT} name="quality" value={qualityId} values={qualityOptions} onChange={this.onQualityChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Proper')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="proper" value={proper} onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Real')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="real" value={real} onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Languages')}</FormLabel> <FormInputGroup type={inputTypes.LANGUAGE_SELECT} name="languageIds" value={languageIds} values={languageOptions} onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('IndexerFlags')}</FormLabel> <FormInputGroup type={inputTypes.INDEXER_FLAGS_SELECT} name="indexerFlags" indexerFlags={indexerFlags} onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('Edition')}</FormLabel> <FormInputGroup type={inputTypes.TEXT} name="edition" value={edition} onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('ReleaseGroup')}</FormLabel> <FormInputGroup type={inputTypes.TEXT} name="releaseGroup" value={releaseGroup} onChange={this.onInputChange} /> </FormGroup> </Form> } </ModalBody> <ModalFooter> <Button onPress={onModalClose}> {translate('Cancel')} </Button> <Button kind={kinds.SUCCESS} onPress={this.onSaveInputs} > {translate('Save')} </Button> </ModalFooter> </ModalContent> ); } } FileEditModalContent.propTypes = { qualityId: PropTypes.number.isRequired, proper: PropTypes.bool.isRequired, real: PropTypes.bool.isRequired, relativePath: PropTypes.string.isRequired, edition: PropTypes.string.isRequired, releaseGroup: PropTypes.string.isRequired, languageIds: PropTypes.arrayOf(PropTypes.number).isRequired, languages: PropTypes.arrayOf(PropTypes.object).isRequired, indexerFlags: PropTypes.number.isRequired, isFetching: PropTypes.bool.isRequired, isPopulated: PropTypes.bool.isRequired, error: PropTypes.object, qualities: PropTypes.arrayOf(PropTypes.object).isRequired, onSaveInputs: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default FileEditModalContent;
src/interface/icons/Scroll.js
sMteX/WoWAnalyzer
import React from 'react'; // https://thenounproject.com/search/?q=scroll&i=1219367 // Created by jngll from the Noun Project const Icon = ({ ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="icon" {...other}> <path d="M80.64,11.87l-.52,0-.26,0H30.64A10.24,10.24,0,0,0,20.42,21.94s0,.05,0,.08V67.66H18.77a2,2,0,0,0-.44.05,10.23,10.23,0,0,0,0,20.36,2,2,0,0,0,.44.05h45.4A10.25,10.25,0,0,0,74.41,77.9V32.34h6.23a10.23,10.23,0,0,0,0-20.47Zm-67.52,66a6.24,6.24,0,0,1,6.23-6.23H56.08a10.16,10.16,0,0,0,0,12.47H19.36A6.24,6.24,0,0,1,13.12,77.9Zm57.28,0a6.23,6.23,0,1,1-6.23-6.23,2,2,0,0,0,0-4H24.41V22.1a6.24,6.24,0,0,1,6.23-6.23h41.9a10.17,10.17,0,0,0-2.13,6.07s0,.05,0,.08ZM80.64,28.34H74.41V22.1a6.23,6.23,0,1,1,6.23,6.23Z" /> <rect x="30.33" y="53.67" width="6" height="4" /> <rect x="43.33" y="53.67" width="20" height="4" /> <rect x="30.33" y="41.67" width="6" height="4" /> <rect x="43.33" y="41.67" width="20" height="4" /> <rect x="30.33" y="29.67" width="6" height="4" /> <rect x="43.33" y="29.67" width="20" height="4" /> </svg> ); export default Icon;
packages/icons/src/md/alert/Error.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdError(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 4c11.04 0 20 8.95 20 20s-8.96 20-20 20S4 35.05 4 24 12.96 4 24 4zm2 30v-4h-4v4h4zm0-8V14h-4v12h4z" /> </IconBase> ); } export default MdError;
examples/dyno/app.js
orokos/react-tabs
import React from 'react'; import Modal from 'react-modal'; import { Tab, Tabs, TabList, TabPanel } from '../../lib/main'; Modal.setAppElement(document.getElementById('example')); Modal.injectCSS(); const App = React.createClass({ getInitialState() { return { isModalOpen: false, tabs: [ {label: 'Foo', content: 'This is foo'}, {label: 'Bar', content: 'This is bar'}, {label: 'Baz', content: 'This is baz'}, {label: 'Zap', content: 'This is zap'} ] }; }, render() { return ( <div style={{padding: 50}}> <p> <button onClick={this.openModal}>+ Add</button> </p> <Tabs> <TabList> {this.state.tabs.map((tab, i) => { return ( <Tab key={i}> {tab.label} <a href="#" onClick={this.removeTab.bind(this, i)}>✕</a> </Tab> ); })} </TabList> {this.state.tabs.map((tab, i) => { return <TabPanel key={i}>{tab.content}</TabPanel>; })} </Tabs> <Modal isOpen={this.state.isModalOpen} onRequestClose={this.closeModal} style={{width: 400, height: 350, margin: '0 auto'}} > <h2>Add a Tab</h2> <label htmlFor="label">Label:</label><br/> <input id="label" type="text" ref="label"/><br/><br/> <label htmlFor="content">Content:</label><br/> <textarea id="content" ref="content" rows="10" cols="50"></textarea><br/><br/> <button onClick={this.addTab}>OK</button>{' '} <button onClick={this.closeModal}>Cancel</button> </Modal> </div> ); }, openModal() { this.setState({ isModalOpen: true }); }, closeModal() { this.setState({ isModalOpen: false }); }, addTab() { const label = this.refs.label.getDOMNode().value; const content = this.refs.content.getDOMNode().value; this.state.tabs.push({ label: label, content: content }); this.closeModal(); }, removeTab(index) { this.state.tabs.splice(index, 1); this.forceUpdate(); } }); React.render(<App/>, document.getElementById('example'));
src/containers/Home/Home.js
leifdalan/vega-june
import React, { Component } from 'react'; import throttle from 'lodash/throttle'; import { Post } from 'components'; import Infinite from 'react-infinite'; import { connect } from 'react-redux'; import { asyncConnect } from 'redux-async-connect'; import Helmet from 'react-helmet'; import reduce from 'lodash/reduce'; import { window } from 'utils/lib'; import { mapStateToProps, actions, propTypes } from './HomeSelectors'; import { CENTER_STYLE } from './Home.styles'; import { POST_CONTAINER, PICTURE_STYLE, } from 'components/Post/Post.styles'; import VideoPost from 'components/VideoPost/VideoPost'; @asyncConnect([{ promise: ({ store: { dispatch } }) => dispatch(actions.loadRemaining()), }]) @connect(mapStateToProps, actions) export default class Home extends Component { static propTypes = propTypes componentDidMount() { window.addEventListener('resize', this.throttledCalculateContainerWidth); this.calculateContainerWidth(); } componentDidUpdate() { // this.calculateContainerWidth(); } componentWillUnmount() { window.removeEventListener('resize', this.throttledCalculateContainerWidth); } getPostHeight = index => { const { allPosts, imageRatios, containerWidth } = this.props; const post = allPosts[index]; let photoHeight = imageRatios[index] * containerWidth; if (post.type === 'photo' && post.photos.length === 2) { photoHeight = photoHeight / 2; } return photoHeight + ( // Add 20 for summary post.summary ? 20 : 0 ) + ( // Add 20 for tags !!(post.tags && post.tags.length) ? 20 : 0 ) + // and all the padding/margin POST_CONTAINER.marginBottom + POST_CONTAINER.paddingBottom + PICTURE_STYLE.marginBottom; } calculateContainerWidth = () => this .props .setContainerWidth( this.container.getBoundingClientRect().width ) throttledCalculateContainerWidth = () => throttle(this.calculateContainerWidth, 500)() containerRef = el => this.container = el // eslint-disable-line no-return-assign render() { const { getPostHeight, containerRef, props: { posts, children, imageRatios, containerWidth, allPosts, }, } = this; const { postElements, elementHeights } = reduce(allPosts, (out, post, index) => ({ postElements: [ ...out.postElements, post.type === 'youtube' ? <VideoPost post={post} containerWidth={containerWidth} /> : <Post post={post} key={index} index={index} containerWidth={containerWidth} imageRatio={imageRatios[index]} /> ], elementHeights: [ ...out.elementHeights, getPostHeight(index) ] }), { postElements: [], elementHeights: [] }); let feed; if (__CLIENT__) { feed = ( <Infinite useWindowAsScrollContainer elementHeight={elementHeights} > {postElements} </Infinite> ); } else { feed = ( <div> {postElements.slice(0, 20)} </div> ); } return ( <div className="center" ref={containerRef} style={{ padding: 15, maxWidth: '600px', marginLeft: 'auto', marginRight: 'auto', }} > <Helmet title="Home" /> <div> <h1 style={CENTER_STYLE}>VEGA JUNE</h1> <p style={{ ...CENTER_STYLE, textTransform: 'none', }} > I'm a baby </p> {feed} {/* This is for the gallery */} {children && React.cloneElement(children, { slides: posts .filter(post => post.type === 'photo') .map(post => ({ url: post.photos[0].original_size.url, ratio: post.photos[0].original_size.height / post.photos[0].original_size.width, id: post.id, summary: post.summary }) ) })} </div> </div> ); } }
components/common/nav.js
dbow/89-steps
import React from 'react'; import { NavLink } from 'fluxible-router'; if (process.env.BROWSER) { require('./nav.scss'); } class Nav extends React.Component { render() { const selected = this.props.selected; const links = this.props.links; const linkHTML = Object.keys(links).map((name) => { var className = ''; var link = links[name]; if (selected === name) { className = 'pure-menu-selected'; } // TODO(dbow): Remove - this is just a demo of NavLink with params. var navParams = {}; if (link.page === 'street') { navParams = {frame: '5'}; } return ( <li className={className} key={link.path}> <NavLink routeName={link.page} navParams={navParams} activeStyle={{backgroundColor: '#eee'}}>{link.title}</NavLink> </li> ); }); return ( <ul className="pure-menu pure-menu-open pure-menu-horizontal"> {linkHTML} </ul> ); } } Nav.defaultProps = { selected: 'intro', links: {}, }; export default Nav;
project/src/components/App/App.js
boldr/boldr
/* eslint-disable no-unused-vars, import/max-dependencies */ /* @flow */ import React from 'react'; import type { Element } from 'react'; import Helmet from 'react-helmet'; // internal import '../../styles/main.scss'; // Start routes import boldrNotificationsFactory, { Notif } from '../Notifications'; import Root from '../Root'; const NotificationContainer = boldrNotificationsFactory(Notif); const App = () => ( <div className="boldr"> <Helmet titleTemplate="%s - Powered by Boldr" defaultTitle="Boldr: Modern Content Management Framework"> <html lang="en" /> <meta name="application-name" content="Boldr" /> <meta name="description" content="A modern, bold take on a cms" /> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#2b2b2b" /> <link rel="icon" sizes="16x16 32x32" href="/favicons/favicon.ico" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/favicons/apple-touch-icon-144x144.png" /> <meta name="msapplication-TileColor" content="#2b2b2b" /> <meta name="msapplication-TileImage" content="/favicons/mstile-144x144.png" /> </Helmet> <Root /> <NotificationContainer /> </div> ); export default App;
react_components/BreakView.js
AdeleD/react-paginate
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; const BreakView = (props) => { const { breakLabel, breakClassName, breakLinkClassName, breakHandler, getEventListener, } = props; const className = breakClassName || 'break'; return ( <li className={className}> <a className={breakLinkClassName} role="button" tabIndex="0" onKeyPress={breakHandler} {...getEventListener(breakHandler)} > {breakLabel} </a> </li> ); }; BreakView.propTypes = { breakLabel: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), breakClassName: PropTypes.string, breakLinkClassName: PropTypes.string, breakHandler: PropTypes.func.isRequired, getEventListener: PropTypes.func.isRequired, }; export default BreakView;
voting-client/src/components/Voting.js
mrwizard82d1/full-stack-redux-tutorial
/** * Created by larryjones on 6/17/17. */ import React from 'react'; import { connect } from 'react-redux'; import Vote from './Vote'; import Winner from './Winner'; export function Voting(props) { return ( <div> { props.winner ? <Winner winner={props.winner} /> : <Vote {...props} /> } </div> ) } function mapStateToProps(state) { console.log('State to `Voting`: ', state); return { pair: state.getIn(['vote', 'pair']), winner: state.get('winner'), }; } export default connect(mapStateToProps)(Voting);
src/server.js
keshavnandan/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ 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 { // TODO: Temporary fix #159 if (['/', '/about', '/privacy'].indexOf(req.path) !== -1) { await db.getPage(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 }} />); data.body = React.renderToString(app); 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')); } });
src/svg-icons/image/crop-3-2.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop32 = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H5V6h14v12z"/> </SvgIcon> ); ImageCrop32 = pure(ImageCrop32); ImageCrop32.displayName = 'ImageCrop32'; ImageCrop32.muiName = 'SvgIcon'; export default ImageCrop32;
examples/website/src/components/LoadingIndicator.js
w-y/ecma262-jison
import PropTypes from 'prop-types'; import React from 'react'; export default function LoadingIndicator(props) { return props.visible ? <div className="loadingIndicator cover"> <div> <i className="fa fa-lg fa-spinner fa-pulse"></i> </div> </div> : null; } LoadingIndicator.propTypes = { visible: PropTypes.bool, };
app/components/Console.js
shaunstanislaus/fil
import _ from 'underscore'; import React from 'react'; import OutputLine from 'components/OutputLine'; import ConsoleToolbar from 'components/ConsoleToolbar'; import ErrorLine from 'components/ErrorLine'; export default class Console extends React.Component { renderLine(line, i) { return <OutputLine output={line} key={i} /> } render() { var block = "console", error = this.props.error; return ( <div className={block}> <ConsoleToolbar className={block + "__toolbar"} onRun={this.props.onRun} /> <div className={block + "__output"}> {this.props.lines.map(this.renderLine.bind(this))} </div> {error && <ErrorLine error={error} />} </div> ); } }
client/src/components/PasswordForget/index.js
stanographer/aloft
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { withFirebase } from '../Firebase'; import * as ROUTES from '../../constants/routes'; const PasswordForgetPage = () => ( <div> <h1>PasswordForget</h1> <PasswordForgetForm /> </div> ); const INITIAL_STATE = { email: '', error: null, }; class PasswordForgetFormBase extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } onSubmit = event => { const { email } = this.state; this.props.firebase .doPasswordReset(email) .then(() => { this.setState({ ...INITIAL_STATE }); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; render() { const { email, error } = this.state; const isInvalid = email === ''; return ( <form onSubmit={this.onSubmit}> <input name="email" value={this.state.email} onChange={this.onChange} type="text" placeholder="Email Address" /> <button disabled={isInvalid} type="submit"> Reset My Password </button> {error && <p>{error.message}</p>} </form> ); } } const PasswordForgetLink = () => ( <p> <Link to={ROUTES.PASSWORD_FORGET}>Forgot Password?</Link> </p> ); export default PasswordForgetPage; const PasswordForgetForm = withFirebase(PasswordForgetFormBase); export { PasswordForgetForm, PasswordForgetLink };
apps/marketplace/components/BuyerATM/BuyerATMIntroductionStage.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import PropTypes from 'prop-types' import { Form } from 'react-redux-form' import AUheadings from '@gov.au/headings/lib/js/react.js' import { AUcallout } from '@gov.au/callout/lib/js/react.js' import { rootPath } from 'marketplace/routes' import styles from './BuyerATMIntroductionStage.scss' const BuyerATMIntroductionStage = props => ( <Form model={props.model} onSubmit={props.onSubmit}> <AUheadings level="1" size="xl"> Ask the market </AUheadings> <AUcallout description="" className={styles.noticeBar}> This approach is for expressions of interest or requests for information. Sellers submit up to 500 words to each criteria you provide. If you need proposals, use{' '} <a href={`${rootPath}/outcome-choice`}>seek proposals and quotes</a>. </AUcallout> <AUheadings level="2" size="lg"> Before you start </AUheadings> <ul> <li> You can{' '} <a href="/api/2/r/ask-market-questions-template.docx" rel="noopener noreferrer" target="_blank"> download the list of questions (DOCX 87KB) </a>{' '} to prepare offline before publishing. </li> <li> Read the{' '} <a href="https://www.buyict.gov.au/sp?id=resources_and_policies&kb=KB0010683" rel="external noopener noreferrer" target="_blank" > Digital Sourcing Framework&apos;s mandatory policies </a>{' '} because they may apply to you. To keep a record of your compliance, complete and save your: <ul> <li> <a href="https://www.buyict.gov.au/sp?id=resources_and_policies&kb=KB0010637" rel="external noopener noreferrer" target="_blank" > Consider First Policy document </a> </li> <li> <a href="https://www.buyict.gov.au/sp?id=resources_and_policies&kb=KB0010639&kb_parent=KB0010683#fair-criteria-checklist" rel="external noopener noreferrer" target="_blank" > Fair Criteria Checklist </a> </li> </ul> </li> <li>You should consider approaching multiple sellers wherever possible.</li> <li> Remember to request that sellers provide an offer of discount(s) and to seek better rates for longer-term contracts. </li> </ul> <AUheadings level="2" size="lg"> Getting help </AUheadings> <p> <a href="https://marketplace1.zendesk.com/hc/en-gb/articles/360000575036" rel="noopener noreferrer" target="_blank" > View support article </a> <br /> <a href="/contact-us" rel="noopener noreferrer" target="_blank"> Contact us </a> </p> <p>All fields are mandatory unless marked optional.</p> {props.formButtons} </Form> ) BuyerATMIntroductionStage.defaultProps = { onSubmit: () => {} } BuyerATMIntroductionStage.propTypes = { model: PropTypes.string.isRequired, formButtons: PropTypes.node.isRequired, onSubmit: PropTypes.func } export default BuyerATMIntroductionStage
app/javascript/mastodon/features/notifications/components/column_settings.js
vahnj/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ClearColumnButton from './clear_column_button'; import SettingToggle from './setting_toggle'; export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, pushSettings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; onPushChange = (path, checked) => { this.props.onChange(['push', ...path], checked); } render () { const { settings, pushSettings, onChange, onClear } = this.props; const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />; const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />; const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />; const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed'); const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />; const pushMeta = showPushSettings && <FormattedMessage id='notifications.column_settings.push_meta' defaultMessage='This device' />; return ( <div> <div className='column-settings__row'> <ClearColumnButton onClick={onClear} /> </div> <div role='group' aria-labelledby='notifications-follow'> <span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-favourite'> <span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-mention'> <span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-reblog'> <span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} /> </div> </div> </div> ); } }
fields/types/geopoint/GeoPointField.js
naustudio/keystone
import Field from '../Field'; import React from 'react'; import { FormInput, Grid, } from '../../../admin/client/App/elemental'; module.exports = Field.create({ displayName: 'GeopointField', statics: { type: 'Geopoint', }, focusTargetRef: 'lat', handleLat (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [value[0], newVal], }); }, handleLong (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [newVal, value[1]], }); }, renderValue () { const { value } = this.props; if (value && value[1] && value[0]) { return <FormInput noedit>{value[1]}, {value[0]}</FormInput>; // eslint-disable-line comma-spacing } return <FormInput noedit>(not set)</FormInput>; }, renderField () { const { value = [], path } = this.props; return ( <Grid.Row xsmall="one-half" gutter={10}> <Grid.Col> <FormInput autoComplete="off" name={this.getInputName(path + '[1]')} onChange={this.handleLat} placeholder="Latitude" ref="lat" value={value[1]} /> </Grid.Col> <Grid.Col width="one-half"> <FormInput autoComplete="off" name={this.getInputName(path + '[0]')} onChange={this.handleLong} placeholder="Longitude" ref="lng" value={value[0]} /> </Grid.Col> </Grid.Row> ); }, });
src/components/demo/DemoMenuIntroduction.js
cismet/wupp-geoportal3-powerboats
import React from 'react'; import { Link } from 'react-scroll'; const DemoMenuIntroduction = ({ uiStateActions }) => { return ( <span> Über{' '} <Link to="settings" containerId="myMenu" smooth={true} delay={100} onClick={() => uiStateActions.setApplicationMenuActiveKey('settings')} > Einstellungen </Link>{' '} können Sie die Darstellung der Hintergrundkarte und der Kitas an Ihre Vorlieben anpassen. Wählen Sie{' '} <Link to="help" containerId="myMenu" smooth={true} delay={100} onClick={() => uiStateActions.setApplicationMenuActiveKey('help')} > Kompaktanleitung </Link>{' '} für detailliertere Bedienungsinformationen. </span> ); }; export default DemoMenuIntroduction;
cerberus-dashboard/src/components/AddButton/AddButton.js
Nike-Inc/cerberus
/* * Copyright (c) 2020 Nike, inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react' import { Component } from 'react' import PropTypes from 'prop-types' import './AddButton.scss' import '../../assets/images/add-green.svg' /** * Component for an Add Button (a button with a plus and a message) */ export default class AddButton extends Component { static propTypes = { handleClick: PropTypes.func.isRequired, message: PropTypes.string.isRequired } render() { const {handleClick, message} = this.props return ( <div className='permissions-add-new-permission-button-container btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase' onClick={() => { handleClick() }}> <div className='permissions-add-new-permission-add-icon ncss-glyph-plus-lg'></div> <div className='permissions-add-new-permission-add-label'>{message}</div> </div> ) } }
src/util/localizers.js
thuringia/react-widgets
import invariant from 'invariant'; import { has } from './_'; import React from 'react'; const localePropType = React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.func ]) const REQUIRED_NUMBER_FORMATS = [ 'default' ]; const REQUIRED_DATE_FORMATS = [ 'default', 'date', 'time', 'header', 'footer', 'dayOfMonth', 'month', 'year', 'decade', 'century' ]; function _format(localizer, formatter, value, format, culture) { let result = typeof format === 'function' ? format(value, culture, localizer) : formatter.call(localizer, value, format, culture) invariant(result == null || typeof result === 'string' , '`localizer format(..)` must return a string, null, or undefined') return result } function checkFormats(requiredFormats, formats){ if( process.env.NODE_ENV !== 'production' ) requiredFormats.forEach( f => invariant(has(formats, f), 'localizer missing required format: `%s`', f )) } let _numberLocalizer = createWrapper('NumberPicker') export function setNumber({ format, parse, precision = () => null, formats, propType }) { invariant(typeof format === 'function' , 'number localizer `format(..)` must be a function') invariant(typeof parse === 'function' , 'number localizer `parse(..)` must be a function') checkFormats(REQUIRED_NUMBER_FORMATS, formats) _numberLocalizer = { formats, precision, propType: propType || localePropType, format(value, str, culture){ return _format(this, format, value, str, culture) }, parse(value, culture) { let result = parse.call(this, value, culture) invariant(result == null || typeof result === 'number' , 'number localizer `parse(..)` must return a number, null, or undefined') return result } } } let _dateLocalizer = createWrapper('DateTimePicker') export function setDate(spec) { invariant(typeof spec.format === 'function' , 'date localizer `format(..)` must be a function') invariant(typeof spec.parse === 'function' , 'date localizer `parse(..)` must be a function') invariant(typeof spec.firstOfWeek === 'function' , 'date localizer `firstOfWeek(..)` must be a function') checkFormats(REQUIRED_DATE_FORMATS, spec.formats) _dateLocalizer = { formats: spec.formats, propType: spec.propType || localePropType, startOfWeek: spec.firstOfWeek, format(value, str, culture){ return _format(this, spec.format, value, str, culture) }, parse(value, culture) { let result = spec.parse.call(this, value, culture) invariant(result == null || (result instanceof Date && !isNaN(result.getTime())) , 'date localizer `parse(..)` must return a valid Date, null, or undefined') return result } } } export let number = { propType(...args){ return _numberLocalizer.propType(...args) }, getFormat(key, format){ return format || _numberLocalizer.formats[key] }, parse(...args){ return _numberLocalizer.parse(...args) }, format(...args){ return _numberLocalizer.format(...args) }, precision(...args){ return _numberLocalizer.precision(...args) } } export let date = { propType(...args){ return _dateLocalizer.propType(...args) }, getFormat(key, format){ return format || _dateLocalizer.formats[key] }, parse(...args){ return _dateLocalizer.parse(...args) }, format(...args){ return _dateLocalizer.format(...args) }, startOfWeek(...args){ return _dateLocalizer.startOfWeek(...args) } } export default { number, date } function createWrapper(){ let dummy = {}; ['formats', 'parse', 'format', 'firstOfWeek', 'precision'] .forEach(name => Object.defineProperty(dummy, name, { enumerable: true, get(){ throw new Error( '[React Widgets] You are attempting to use a widget that requires localization ' + '(Calendar, DateTimePicker, NumberPicker). ' + 'However there is no localizer set. Please configure a localizer. \n\n' + 'see http://jquense.github.io/react-widgets/docs/#/i18n for more info.') } })) return dummy }
client/containers/Index/index.js
juliandavidmr/FE-Visibilidad
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import IndexComponent from '../../components/Index'; import * as SemilleroActions from '../../actions/semilleros'; import * as NoticiasActions from '../../actions/noticia'; import './style.css'; class Index extends Component { constructor(props) { super(props); this.state = { list_semilleros: [], list_noticias: [] }; } componentWillMount() { const { actions_semilleros, actions_noticias } = this.props; // Semilleros actions_semilleros.listar().then(() => { var l = this.props.semilleros.semillero.toJS(); if (l.data_list_semilleros) { console.log('fetchSemilleros =>', l.data_list_semilleros); this.setState({ list_semilleros: l.data_list_semilleros }); } }); // Noticias actions_noticias.listar().then(() => { var n = this.props.noticias.noticia.toJS(); if (n.data_list_noticias) { console.log('fetchNoticias =>', n.data_list_noticias); this.setState({ list_noticias: n.data_list_noticias }); } }); } render() { return <IndexComponent />; } } function mapStateToProps(state) { // console.log("==mapStateToProps: ", state); return { semilleros: state.semilleros, noticias: state.noticia }; } function mapDispatchToProps(dispatch) { return { actions_semilleros: bindActionCreators(SemilleroActions, dispatch), actions_noticias: bindActionCreators(NoticiasActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(Index);
ui/src/components/table/row/row.js
gchatterjee/cit-gened-finder
import React from 'react' import PropTypes from 'prop-types' import { format } from '../table.action' export default class Row extends React.Component { render() { const { row, order, columns } = this.props return ( <tr key={row}> {order.map(index => { const column = columns[index] return <td key={row[column]}>{format(column, row[column])}</td> })} </tr> ) } } Row.propTypes = { order: PropTypes.array.isRequired, columns: PropTypes.array.isRequired, row: PropTypes.object.isRequired }
src/js/pages/GiftDetailsPage.js
vbence86/giftassistant-client
import React, { Component } from 'react'; import { StyleSheet, View, Linking } from 'react-native'; import { Button, Text } from 'react-native-elements'; import Favourites from '../helpers/Favourites'; import GiftDetailsView from '../components/GiftDetailsView'; const styles = StyleSheet.create({ container: { backgroundColor: '#fff', flex: 1, justifyContent: 'center', alignItems: 'center' } }); export default class GiftDetailsPage extends React.Component { constructor(props) { super(props); this.gift = this.props.data; this.onRemove = this.onRemove.bind(this); this.onBuy = this.onBuy.bind(this); this.onBack = this.onBack.bind(this); this.favourites = Favourites.getInstance(); } onBack() { this.navigateBack(); } onRemove() { this.favourites.remove(this.gift); this.navigateBack(); } onBuy() { const webUrl = this.gift.amazonURL; const urlWithoutProtocol = this.gift.amazonURL.replace('https://', ''); const appUrl = `com.amazon.mobile.shopping://${urlWithoutProtocol}`; let url = appUrl; Linking.canOpenURL(url).then(supported => { if (!supported) { url = webUrl; } return Linking.openURL(url); }).catch(err => console.error('An error occurred', err)); } navigateBack() { this.props.navigator.pop(); } render() { return ( <View style={styles.container}> <GiftDetailsView data={this.gift} onBack={this.onBack} onRemove={this.onRemove} onBuy={this.onBuy}/> </View> ); } }
src/components/FileDetail.js
msalem07/LectureRecorder
import React from 'react'; import { Image, Text, View, Linking } from 'react-native'; import Card from './common/Card'; import CardSection from './common/CardSection'; import Button from './common/Button'; export default function FileDetail(props){ const { title, artist, thumbnail_image, image, url } = props.file; const { thumbnailStyle, thumbnailContainerStyle, headerContentStyle, headerTextStyle, imageStyle} = styles; return ( <Card> <CardSection> <View style={thumbnailContainerStyle}> <Image style={thumbnailStyle} source={{uri: thumbnail_image}}/> </View> <View style={headerContentStyle}> <Text style={headerTextStyle}>{title}</Text> <Text style={headerTextStyle}>{artist}</Text> </View> </CardSection> {/* We won't need the image below for the files, however we can reuse the buttons by modifying the styling of it*/} <CardSection> <Image style={imageStyle} source={{uri: image}} /> </CardSection> <CardSection> <Button onPress={()=>Linking.openURL(url)}> Buy Now </Button> </CardSection> </Card> ) }; const styles = { headerContentStyle:{ flexDirection: "column", justifyContent: "space-around" }, headerTextStyle:{ fontSize: 18 }, thumbnailStyle: { height: 70, width: 70, }, thumbnailContainerStyle: { justifyContent: 'center', alignContent: 'center', marginLeft: 8, marginRight: 8 }, imageStyle: { height: 300, flex: 1, width: null } };
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js
lolaent/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import logo from './assets/logo.svg'; export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
Pioneer/Setting.js
Hank860502/Pioneer
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, Navigator, TouchableOpacity, TextInput, Picker, } from 'react-native'; class Setting extends Component { constructor(props){ super(props); this.state = { category: "", radius: "", newPlace: "", showCancel: false, showCancel2: false, } } submit(){ this.props.navigator.push({ title: 'Pioneer', radius: this.state.radius, category: this.state.category, }); } render(){ return( <View style={styles.container}> <View> <Picker selectedValue={this.state.radius} onValueChange={(radius) => this.setState({radius: radius})}> <Picker.Item label="30 miles" value="30" /> <Picker.Item label="20 miles" value="20" /> <Picker.Item label="10 miles" value="10" /> <Picker.Item label="5 miles" value="5" /> <Picker.Item label="1 miles" value="1" /> </Picker> </View> <Text style={styles.text1}>Radius</Text> <Text style={styles.text2}>Categories</Text> <View> <Picker selectedValue={this.state.category} onValueChange={(category) => this.setState({category: category})} mode="dialog"> <Picker.Item label="Popular" value="tourist_destination" /> <Picker.Item label="Restaurant" value="restaurant" /> <Picker.Item label="Aquarium" value="aquarium" /> <Picker.Item label="Casino" value="casino" /> <Picker.Item label="Museum" value="museum" /> <Picker.Item label="Night Life" value="night_club" /> <Picker.Item label="Park" value="park" /> <Picker.Item label="Zoo" value="zoo" /> <Picker.Item label="Attractions" value="place_of_interset" /> </Picker> </View> <TouchableOpacity onPress={()=>this.submit()} style={styles.button} underlayColor= 'white'> <Text style={styles.text}> Submit </Text> </TouchableOpacity> </View> ) } }; const styles = StyleSheet.create({ container: { flex: 1, height: 300, backgroundColor: 'white', }, text: { fontSize: 23, color: 'white' }, text1: { position: 'absolute', top: 98, left: 18, height: 38, fontSize: 23, }, text2: { position: 'absolute', top: 312, left: 10, height: 38, fontSize: 23, }, button: { position: 'absolute', left: 150, top: 540, padding: 10, flexDirection: 'row', backgroundColor: '#30ABBD', borderRadius: 6, opacity: 0.85, marginTop: 5, }, }) export default Setting;
app/javascript/mastodon/components/column_back_button.js
abcang/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; import { createPortal } from 'react-dom'; export default class ColumnBackButton extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { multiColumn: PropTypes.bool, }; handleClick = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } render () { const { multiColumn } = this.props; const component = ( <button onClick={this.handleClick} className='column-back-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); if (multiColumn) { return component; } else { // The portal container and the component may be rendered to the DOM in // the same React render pass, so the container might not be available at // the time `render()` is called. const container = document.getElementById('tabs-bar__portal'); if (container === null) { // The container wasn't available, force a re-render so that the // component can eventually be inserted in the container and not scroll // with the rest of the area. this.forceUpdate(); return component; } else { return createPortal(component, container); } } } }
src/client/app/page_list_sidebar/sub_components/AutoSuggestPage.js
raghuveerkancherla/yata
import Autosuggest from 'react-autosuggest'; import React from 'react'; import dateUtils from '../../utils/dateUtils'; import _ from 'lodash'; import AutoSuggestionStyles from './autosugestionstyles.less'; const AutoSuggestPageInput = React.createClass({ propTypes: { customPages: React.PropTypes.array, }, getInitialState: function () { return { value: '', suggestions: [], userChoseAddPage: false, matchedSuggestion: null }; }, onChange: function(event, { newValue, method }) { if (newValue != 'AddPage' && method == 'type') { this.setState({ value: newValue }); } }, onSuggestionsFetchRequested: function({ value }) { var suggestionsToShow; if (value.length == 0) { // get default suggestions to show suggestionsToShow = _.union( this.props.customPages, dateUtils.getDefaultDateSuggestions()); } else { var suggestionList = _.union( this.props.customPages, dateUtils.getWeekDaySuggestions(), dateUtils.getDateSuggestionsFromNL(value) ); const filteredSuggestions = this._filterSuggestionsByValue(value, suggestionList); suggestionsToShow = _.union(filteredSuggestions, this._getAddPageSuggestion()); } this.setState({ suggestions: suggestionsToShow }); }, onSuggestionsClearRequested: function () { this.setState({ suggestions: this._getAddPageSuggestion() }); }, onSuggestionSelected: function (e, {suggestion, suggestionValue, suggestionIndex, sectionIndex, method}) { if (suggestion.pageKey == 'AddPage'){ this.setState({userChoseAddPage: true}); } else { this.setState({ matchedSuggestion: suggestion }); } }, getSuggestionValue: function(suggestion) { return suggestion.pageKey; }, _filterSuggestionsByValue: function (value, suggestionList) { const inputValue = value.trim().toLowerCase(); const inputLength = inputValue.length; return inputLength === 0 ? []: suggestionList.filter(suggestion => suggestion.pageKey.toLowerCase().indexOf(inputValue) > -1 || suggestion.displayName.toLowerCase().indexOf(inputValue) > -1 || suggestion.searchText && suggestion.searchText.toLowerCase().indexOf(inputValue) > -1 ); }, _getAddPageSuggestion: function () { return [{ 'pageKey': 'AddPage', 'displayName': '+ Add new page' }]; }, renderSuggestion: function (suggestion) { return ( <span>{suggestion.displayName}</span> ); }, render: function() { const { value, suggestions } = this.state; const inputProps = { id: 'page-autosuggest-input', placeholder: '', value, onChange: this.onChange, autoFocus: true }; return ( <Autosuggest theme={AutoSuggestionStyles} suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} getSuggestionValue={this.getSuggestionValue} renderSuggestion={this.renderSuggestion} inputProps={inputProps} alwaysRenderSuggestions={true} /> ); } }); export default AutoSuggestPageInput;
examples/todomvc/index.js
koistya/redux
import 'babel/polyfill'; import React from 'react'; import Root from './containers/Root'; import 'todomvc-app-css/index.css'; React.render( <Root />, document.getElementById('root') );
RNTester/js/ActivityIndicatorExample.js
mironiasty/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule ActivityIndicatorExample */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
client/src/AlertDialog.js
jghibiki/Doc
import React from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; class AlertDialog extends React.Component { constructor(props){ super(props); this.state = { open: false, }; var dummy = () => {} this.onOk = props.onOk || dummy; this.onCancel = props.onCancel || dummy; } handleClickOpen = () => { this.setState({ open: true }); }; handleOk = () => { this.setState({ open: false }); this.onOk(); }; handleCancel = () => { this.setState({ open: false }); this.onCancel(); }; render() { const { title, message, control } = this.props; return ( <div> <div onClick={this.handleClickOpen}> {control} </div> <Dialog open={this.state.open} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{title}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> {message} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleCancel} color="primary"> Cancel </Button> <Button onClick={this.handleOk} color="primary" autoFocus> Ok </Button> </DialogActions> </Dialog> </div> ); } } export default AlertDialog;
app/javascript/mastodon/features/compose/components/upload_form.js
pinfort/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import UploadProgressContainer from '../containers/upload_progress_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import UploadContainer from '../containers/upload_container'; import SensitiveButtonContainer from '../containers/sensitive_button_container'; import { FormattedMessage } from 'react-intl'; export default class UploadForm extends ImmutablePureComponent { static propTypes = { mediaIds: ImmutablePropTypes.list.isRequired, }; render () { const { mediaIds } = this.props; return ( <div className='compose-form__upload-wrapper'> <UploadProgressContainer icon='upload' message={<FormattedMessage id='upload_progress.label' defaultMessage='Uploading…' />} /> <div className='compose-form__uploads-wrapper'> {mediaIds.map(id => ( <UploadContainer id={id} key={id} /> ))} </div> {!mediaIds.isEmpty() && <SensitiveButtonContainer />} </div> ); } }
src/components/ListItem.js
leonardoelias/social-media-profile
import React from 'react'; import { Box, Media, MediaLeft, MediaContent, Content, Image } from 're-bulma'; const ListItem = ({ user, picture, text }) => { return ( <Box> <Media> <MediaLeft> <Image src={ picture } size='is48X48' /> </MediaLeft> <MediaContent> <Content> <p> <strong>{ user }</strong> <small></small> <br /> { text } </p> </Content> </MediaContent> </Media> </Box> ) } export default ListItem;
src/widgets/PrescriptionCartRow.js
sussol/mobile
/* eslint-disable react/forbid-prop-types */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { View, StyleSheet } from 'react-native'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import currency from '../localization/currency'; import { CircleButton } from './CircleButton'; import { DropdownRow } from './DropdownRow'; import { DetailRow } from './DetailRow'; import { StepperRow } from './StepperRow'; import { CloseIcon } from './icons'; import { Separator } from './Separator'; import { TouchableNoFeedback } from './DataTable'; import { UIDatabase } from '../database'; import { PrescriptionActions } from '../actions/PrescriptionActions'; import { generalStrings, dispensingStrings } from '../localization'; /** * Renders a row in the PrescriptionCart consisting of a `StepperRow`, `DropdownRow`, * `DetailsRow` and a close button. * * Is passed all details needed as this is a simple layout and presentation component. * * @prop {Bool} isDisabled Indicator whether this line is disabled. * @prop {String} itemName The underlying Item's name for this line. * @prop {String} itemCode The underlying Item's code for this line. * @prop {String} id The underlying TransactionItem id for this line. * @prop {String} note This lines note/direction. * @prop {Object} price String representation of this items price. * @prop {Object} item Underlying Item object for this line. * @prop {Number} totalQuantity Total quantity of this item in the prescription. * @prop {Number} availableQuantity Total available quantity for the underlying item. * @prop {Func} onChangeQuantity Callback for editing the quantity for this item. * @prop {Func} onRemoveItem Callback for removing an item from the cart. * @prop {Func} onChangeText Callback for typing directions in the TextInput. * @prop {Func} onDirectionSelect Callback for selecting a direction from the dropdown. * @prop {Func} usingPayments Indicator if the current store is using the payments module. */ const PrescriptionCartRowComponent = ({ isDisabled, itemName, itemCode, id, note, price, item, totalQuantity, availableQuantity, onChangeQuantity, onRemoveItem, onChangeText, onDirectionSelect, usingPayments, }) => { const itemDetails = React.useMemo(() => { const details = [{ label: generalStrings.code, text: itemCode }]; if (usingPayments) details.push({ label: generalStrings.total_price, text: price }); return details; }, [itemCode, price]); const defaultDirections = React.useMemo(() => item.getDirectionExpansions(UIDatabase), [id]); return ( <> <TouchableNoFeedback style={localStyles.flexRow}> <View style={localStyles.largeFlexRow}> <StepperRow text={itemName} quantity={totalQuantity} onChangeValue={onChangeQuantity} isDisabled={isDisabled} upperLimit={availableQuantity} /> <DetailRow details={itemDetails} /> <View style={{ height: 10 }} /> <DropdownRow isDisabled={isDisabled} currentOptionText={note} options={defaultDirections} onChangeText={onChangeText} onSelection={onDirectionSelect} dropdownTitle={dispensingStrings.directions} placeholder={dispensingStrings.usage_directions} /> </View> <View style={localStyles.flexOne} /> <CircleButton size="small" IconComponent={CloseIcon} onPress={isDisabled ? null : onRemoveItem} /> </TouchableNoFeedback> <Separator /> </> ); }; PrescriptionCartRowComponent.defaultProps = { isDisabled: false, note: '', }; PrescriptionCartRowComponent.propTypes = { onChangeQuantity: PropTypes.func.isRequired, onRemoveItem: PropTypes.func.isRequired, onChangeText: PropTypes.func.isRequired, onDirectionSelect: PropTypes.func.isRequired, isDisabled: PropTypes.bool, itemName: PropTypes.string.isRequired, totalQuantity: PropTypes.number.isRequired, itemCode: PropTypes.string.isRequired, price: PropTypes.string.isRequired, id: PropTypes.string.isRequired, note: PropTypes.string, item: PropTypes.object.isRequired, availableQuantity: PropTypes.number.isRequired, usingPayments: PropTypes.bool.isRequired, }; const localStyles = StyleSheet.create({ flexRow: { flex: 1, flexDirection: 'row' }, largeFlexRow: { flex: 10 }, flexOne: { flex: 1 }, centerFlex: { flex: 1, justifyContent: 'center' }, closeContainerStyle: { flexDirection: 'column', justifyContent: 'center', alignItems: 'center', flex: 1, }, }); const mapStateToProps = (state, ownProps) => { const { transactionItem } = ownProps; const { modules } = state; const { usingPayments } = modules; const { itemName, totalQuantity, itemCode, totalPrice, note, item, availableQuantity, id, } = transactionItem; return { usingPayments, itemName, totalQuantity, itemCode, availableQuantity, price: currency(totalPrice).format(), note, item, id, }; }; const mapStateToDispatch = (dispatch, ownProps) => { const { transactionItem } = ownProps; const { id } = transactionItem; const onChangeQuantity = quantity => dispatch(PrescriptionActions.editQuantity(id, quantity)); const onRemoveItem = () => dispatch(PrescriptionActions.removeItem(id)); const onChangeText = direction => dispatch(PrescriptionActions.updateDirection(id, direction)); const onDirectionSelect = direction => dispatch(PrescriptionActions.appendDirection(id, direction)); return { onChangeQuantity, onRemoveItem, onChangeText, onDirectionSelect }; }; export const PrescriptionCartRow = connect( mapStateToProps, mapStateToDispatch )(PrescriptionCartRowComponent);
src/js/components/search/app-search.js
TheFixers/node-honeypot-client
/** * Filename: 'app-search.js' * Author: JMW <rabbitfighter@cryptolab.net> * App search area component */ import React from 'react' import AppStore from '../../stores/app-store' import AppActions from '../../actions/app-actions' import StoreWatchMixin from '../../mixins/StoreWatchMixin' import SearchTypes from '../../static/SearchTypes' const getSearchParams = () => { return Object.assign({ search: AppStore.getSearchParams(), data: AppStore.getServerData() }) } const updateSearchType = ( event ) => { let type = event.target.options[event.target.selectedIndex].dataset.field AppActions.updateSearchType( type ) AppActions.jumpToPage( 0 ) } const updateSearchTerm = ( event ) => { let term = event.target.value AppActions.updateSearchTerm( term ) } const AppSearch = ( props ) => { var styles = { width: '150px', background: 'transparent', height: '30px', margin: '5px', marginTop: '20px', padding: '5px', border: 'solid 1px #666', borderRadius: '3px' } let type = props.search.type let term = props.search.term let options = Object.keys(SearchTypes).map( ( item, index ) => { let searchItem = SearchTypes[item] return <option key={ index } index={ searchItem.index } data-field={ searchItem.field } data-display={ searchItem.display }> { searchItem.display } </option> }) let input = null if ( type !== null && type !== 'ALL') { input = <input className='input' type="text" placeholder='Search for...' style={ styles } onChange={ updateSearchTerm }> </input> } return ( <div className='search-area text-right'> <i className="glyphicon glyphicon-search"></i> <select className='select' style={ styles } defaultValue="ALL" onChange={ updateSearchType }> <option value='title' disabled>Search by</option> { options } </select> { input } <br/> </div> ) } export default StoreWatchMixin( AppSearch, getSearchParams )
dev/react-subjects/subjects/JSONTable/solution.js
AlanWarren/dotfiles
//////////////////////////////////////////////////////////////////////////////// // Requirements // // - fetch the src with getJSON((error, payload) => {}) // - render the content of the th's from the field names (hint: use // the field names from the first record) // - render each result as a row in <tbody> import 'purecss/build/pure.css' import React from 'react' import { render } from 'react-dom' import getJSON from './lib/getJSON' function isURL(content) { return (/^https?:\/\//).test(content) } function isImageURL(content) { return isURL(content) && (/\.(jpe?g|gif|png)$/).test(content) } const JSONTable = React.createClass({ propTypes: { src: React.PropTypes.string.isRequired, getData: React.PropTypes.func.isRequired, getKey: React.PropTypes.func.isRequired }, getDefaultProps() { return { getKey: (item) => item.id } }, getInitialState() { return { data: null } }, componentDidMount() { getJSON(this.props.src, (error, payload) => { this.setState({ data: this.props.getData(payload) }) }) }, formatContent(content) { if (Array.isArray(content)) return content.map(this.formatContent) if (isImageURL(content)) return <p><img key={content} height="64" src={content}/></p> if (isURL(content)) return <p><a key={content} href={content}>{content}</a></p> return content }, render() { const { data } = this.state if (data == null || data.length === 0) return null const fields = Object.keys(data[0]) return ( <table className="pure-table pure-table-striped"> <thead> <tr> {fields.map(field => <th key={field}>{field}</th>)} </tr> </thead> <tbody> {data.map(item => ( <tr key={this.props.getKey(item)}> {fields.map(field => ( <td key={field}>{this.formatContent(item[field])}</td> ))} </tr> ))} </tbody> </table> ) } }) const App = React.createClass({ render() { return ( <div> <h1>JSONTable</h1> <JSONTable src="https://addressbook-api.herokuapp.com/contacts" getData={payload => payload.contacts} /> {/* <JSONTable src="http://swapi.co/api/people/" getData={payload => payload.results} getKey={item => item.url} /> */} </div> ) } }) render(<App/>, document.getElementById('app'))
mobile/src/index.js
lnmx/goread
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'material-design-lite/dist/material.css'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); ReactDOM.render( <App />, document.getElementById('root') );
src/svg-icons/communication/present-to-all.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPresentToAll = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z"/> </SvgIcon> ); CommunicationPresentToAll = pure(CommunicationPresentToAll); CommunicationPresentToAll.displayName = 'CommunicationPresentToAll'; CommunicationPresentToAll.muiName = 'SvgIcon'; export default CommunicationPresentToAll;
Realization/frontend/czechidm-core/src/components/basic/Loading/Loading.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import $ from 'jquery'; import ReactResizeDetector from 'react-resize-detector'; // import { withStyles } from '@material-ui/core/styles'; // import AbstractComponent from '../AbstractComponent/AbstractComponent'; import AbstractContextComponent from '../AbstractContextComponent/AbstractContextComponent'; const styles = theme => ({ root: { backgroundColor: theme.palette.action.loading, '& .loading-logo div': { backgroundColor: theme.palette.primary.light } } }); /** * Loading indicator. * * ! Be careful: prevent to use Basic.Div inside => cicrular reference. * * @author Radek Tomiška */ class Loading extends AbstractContextComponent { constructor(props, context) { super(props, context); // this.containerRef = React.createRef(); } componentDidMount() { this._resize(); } componentDidUpdate() { this._resize(); } _showLoading() { const { showLoading, show } = this.props; // return showLoading || show; } _resize() { const showLoading = this._showLoading(); if (!showLoading) { return; } const panel = $(this.containerRef.current); const loading = panel.find('.loading'); if (loading.hasClass('global') || loading.hasClass('static')) { // we don't want resize loading container return; } loading.css({ top: panel.position().top, left: panel.position().left, width: panel.outerWidth(), height: panel.outerHeight() }); } render() { const { rendered, className, containerClassName, showAnimation, isStatic, loadingTitle, style, containerTitle, onClick, classes, ...others } = this.props; // if (!rendered) { return null; } const showLoading = this._showLoading(); // // Loading is used as standard div => wee need to render css even if loading is not active const _containerClassNames = classNames( 'loader-container', containerClassName ); const loaderClassNames = classNames( className, 'loading', { hidden: !showLoading }, { static: isStatic }, classes ? classes.root : null ); // onClick required props others.onClick = onClick; others.tabIndex = others.tabIndex || (onClick ? 0 : null); others.role = others.role || (onClick ? 'button' : null); // return ( <div ref={ this.containerRef } className={ _containerClassNames } style={ style } title={ containerTitle } { ...others }> { showLoading ? <div className={ loaderClassNames }> <div className="loading-wave-top" /> { showAnimation ? <div className="loading-wave-container" title={ loadingTitle }> <div className="loading-wave hidden"> <div/><div/><div/><div/><div/> </div> <div className="loading-logo"> <div/><div/><div/><div/><div/><div/><div/><div/><div/> </div> </div> : null } <div className="title hidden">{ loadingTitle }</div> </div> : null } { this.props.children } </div> ); } } class ResizeLoading extends AbstractComponent { render() { const { rendered, ...others } = this.props; if (!rendered) { return null; } if (global.TEST_PROFILE === true) { // fully initialize DOM is required for ReactResizeDetector => not available in tests return ( <Loading { ...others } /> ); } // return ( <ReactResizeDetector handleHeight render={ ({ height }) => ( <Loading height={ height } { ...others } /> )}/> ); } } Loading.propTypes = { ...AbstractContextComponent.propTypes, /** * Shows loading overlay (showLoadin alias) */ show: PropTypes.bool, /** * when loading is visible, then show animation too */ showAnimation: PropTypes.bool, /** * static loading without overlay */ isStatic: PropTypes.bool, /** * Loading title */ loadingTitle: PropTypes.string, /** * Title - static container (div wrapper). */ containerTitle: PropTypes.string, /** * Css - static container (div wrapper). */ containerClassName: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]) }; Loading.defaultProps = { ...AbstractContextComponent.defaultProps, show: false, showAnimation: true, isStatic: false, loadingTitle: 'Zpracovávám ...' // TODO: localization or undefined ? }; export default withStyles(styles, { withTheme: true })(ResizeLoading);
docs/src/sections/LabelSection.js
egauci/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function LabelSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="labels">Labels</Anchor> <small>Label</small> </h2> <p>Create a <code>{"<Label>label</Label>"}</code> to highlight information</p> <ReactPlayground codeText={Samples.Label} /> <h3><Anchor id="labels-variations">Available variations</Anchor></h3> <p>Add any of the below mentioned modifier classes to change the appearance of a label.</p> <ReactPlayground codeText={Samples.LabelVariations} /> <h3><Anchor id="label-props">Props</Anchor></h3> <PropTable component="Label"/> </div> ); }
monkey/monkey_island/cc/ui/src/components/pages/RunMonkeyPage/utils/InterfaceSelection.js
guardicore/monkey
import React from 'react'; import InlineSelection from '../../../ui-components/inline-selection/InlineSelection'; import LocalManualRunOptions from '../RunManually/LocalManualRunOptions'; function InterfaceSelection(props) { return InlineSelection(getContents, props, LocalManualRunOptions) } const getContents = (props) => { const ips = props.ips.map((ip) => <div key={ip}>{ip}</div> ); return (<div>{ips}</div>); } export default InterfaceSelection;
examples/with-segment-analytics/components/Page.js
BlancheXu/test
import React from 'react' import Router from 'next/router' import Header from './Header' // Track client-side page views with Segment Router.events.on('routeChangeComplete', url => { window.analytics.page(url) }) const Page = ({ children }) => ( <div> <Header /> {children} </div> ) export default Page
src/fields/select.js
fermuch/simple-react-form-bootstrap
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'underscore'; // import TextField from 'material-ui/TextField'; import {FormControl, FormGroup, ControlLabel, HelpBlock} from 'react-bootstrap'; const propTypes = { /** * The options for the select input. Each item must have label and value. */ options: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string.isRequired, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, })) }; const defaultProps = {}; class SelectFieldComponent extends React.Component { constructor(props) { super(props); this.state = { value: props.value }; } componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value }); } onChange(event) { this.setState({ value: event.target.value }); this.props.onChange(event.target.value); } renderItems() { let options = null; if (this.props.options) { options = this.props.options; } else if (this.props.fieldSchema && this.props.fieldSchema.allowedValues) { let allowedValues = this.props.fieldSchema.allowedValues; if (typeof allowedValues === 'function') { allowedValues = this.props.fieldSchema.allowedValues(); } options = _.map(allowedValues, function (allowedValue) { return { label: allowedValue, value: allowedValue, }; }); } else { throw new Error('You must set the options for the select field'); } return options.map((item) => { return <option key={item.value} value={item.value}>{item.label}</option>; }); } render() { var fieldType = this.props.fieldType || this.type; return ( <FormGroup validationState={this.props.errorMessage ? 'error' : undefined} > { this.props.label ? <ControlLabel>{this.props.label}</ControlLabel> : null } <FormControl ref='input' value={this.state.value || ''} type={fieldType} placeholder={this.props.placeholder || this.props.passProps.placeholder} disabled={this.props.disabled} onChange={this.onChange.bind(this)} onBlur={() => this.props.onChange(this.state.value)} componentClass="select" {...this.props.passProps} > {this.renderItems()} </FormControl> {this.props.errorMessage && <HelpBlock>{this.props.errorMessage}</HelpBlock> } </FormGroup> ); } } SelectFieldComponent.propTypes = propTypes; SelectFieldComponent.defaultProps = defaultProps; export { SelectFieldComponent as SelectField };
src/app/internal/pcard_compliance/PCardDaysTable.js
cityofasheville/simplicity2
import React from 'react'; import AccessibleReactTable from 'accessible-react-table'; import expandingRows from '../../../shared/react_table_hoc/ExpandingRows'; const mainDataColumns = [ { Header: 'Division', accessor: 'name', width: 250, }, { Header: '0-30', accessor: 'under30', width: 80, headerStyle: { background: '#4575b4', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under30 > 0 ? '#4575b4' : '#d1dded', textAlign: 'right', }, }), }, { Header: '31-60', accessor: 'under60', width: 80, headerStyle: { background: '#fdae61', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under60 > 0 ? '#fdae61' : '#ffdebf', textAlign: 'right', }, }), }, { Header: '61-90', accessor: 'under90', width: 80, headerStyle: { background: '#f46d43', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under_90 > 0 ? '#f46d43' : '#ffa98f69', textAlign: 'right', }, }), }, { Header: '> 90', accessor: 'over90', width: 80, headerStyle: { background: '#d73027', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.over_90 > 0 ? '#d73027' : '#ce524b69', textAlign: 'right', }, }), }, ]; const innerDataColumns = [ { Header: 'Cardholder', accessor: 'cardholder', width: 250, }, { Header: '0-30', accessor: 'under30', width: 80, headerStyle: { background: '#4575b4', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under30 > 0 ? '#4575b4' : '#d1dded', textAlign: 'right', }, }), }, { Header: '31-60', accessor: 'under60', width: 80, headerStyle: { background: '#fdae61', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under60 > 0 ? '#fdae61' : '#ffdebf', textAlign: 'right', }, }), }, { Header: '61-90', accessor: 'under90', width: 80, headerStyle: { background: '#f46d43', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.under_90 > 0 ? '#f46d43' : '#ffa98f69', textAlign: 'right', }, }), }, { Header: '> 90', accessor: 'over90', width: 80, headerStyle: { background: '#d73027', borderBottom: '1px solid white', }, getProps: (state, rowInfo) => ({ style: { backgroundColor: rowInfo.row.over90 > 0 ? '#d73027' : '#ce524b69', textAlign: 'right', }, }), }, ]; // const innerDataColumns2 = [ // { // Header: 'Invoiced date', // accessor: 'invoice_date', // getProps: () => ({ // role: 'rowheader', // }), // }, // { // Header: 'Reconciled date', // accessor: 'reconciled_date', // }, { // Header: 'Statement status', // accessor: 'statement_status', // }, { // Header: 'Statement id', // accessor: 'statement_id', // }, { // Header: 'Statement code', // accessor: 'statement_code', // }, // ]; const ExpandableAccessibleReactTable = expandingRows(AccessibleReactTable); const PCardDaysTable = (props) => { const tdProps = () => ({ style: { whiteSpace: 'normal', }, }); const trProps = () => ({ style: { cursor: 'pointer', }, }); return ( <div alt="Table of days to reconcile" > <h2 id="pcard-compliance-days-to-reconcile-label">Table of days to reconcile</h2> <ExpandableAccessibleReactTable data={props.data} columns={mainDataColumns} pageSize={props.data.length} showPagination={false} getTdProps={tdProps} getTrProps={trProps} tableId="table-1" ariaLabelledBy="pcard-compliance-days-to-reconcile-label" SubComponent={innerRow1 => ( <div style={{ paddingLeft: '34px', marginTop: '15px' }}> <AccessibleReactTable data={props.data[innerRow1.index].children} columns={innerDataColumns} defaultPageSize={props.data[innerRow1.index].children.length <= 5 ? props.data[innerRow1.index].children.length : 5} showPagination={props.data[innerRow1.index].children.length > 5} getTdProps={tdProps} getTrProps={trProps} tableId="table-2" ariaLabel="Cardholders subtable" // SubComponent={innerRow2 => ( // <div style={{ paddingLeft: '34px', marginTop: '15px' }}> // <ExpandableAccessibleReactTable // data={props.data[innerRow1.index].children[innerRow2.index].statements} // columns={innerDataColumns2} // defaultPageSize={props.data[innerRow1.index].children[innerRow2.index].statements.length <= 5 ? props.data[innerRow1.index].children[innerRow2.index].statements.length : 5} // showPagination={props.data[innerRow1.index].children[innerRow2.index].statements.length > 5} // getTdProps={tdProps} // getTrProps={trProps} // tableId="table-2" // ariaLabel="Statements subtable" // /> // </div> // )} /> </div> ) } /> </div> ); }; export default PCardDaysTable;
react-chat/src/components/ChatBox/ChatBox.js
renesansz/presentations
import React from 'react'; import ChatBoxControls from './ChatBoxControls/ChatBoxControls'; import ChatBoxCard from './ChatBoxCard/ChatBoxCard'; import './ChatBox.css'; class ChatBox extends React.Component { render() { const messages = this.props.messages.map((message) => <ChatBoxCard key={ message.id } author={ message.author } isUserAuthor={ (this.props.user === message.author) ? true : false } message={ message.content } /> ); return ( <div className="ChatBox"> <div className="content"> <h4>Chat Box</h4> <div className="messages"> { messages } </div> <ChatBoxControls sendMessage={ this.props.sendMessage } isLoggedIn={ (this.props.user) ? true : false } /> </div> </div> ); }; } export default ChatBox;
src/svg-icons/action/perm-device-information.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermDeviceInformation = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/> </SvgIcon> ); ActionPermDeviceInformation = pure(ActionPermDeviceInformation); ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation'; ActionPermDeviceInformation.muiName = 'SvgIcon'; export default ActionPermDeviceInformation;
packages/components/src/HeaderBar/HeaderBar.stories.js
Talend/ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import { makeDecorator } from '@storybook/addons'; import Immutable from 'immutable'; // eslint-disable-line import/no-extraneous-dependencies import Icon from '../Icon'; import HeaderBar from './HeaderBar.component'; import AppSwitcher from '../AppSwitcher'; import Layout from '../Layout'; const props = { brand: { id: 'header-brand', label: 'Example App Name', onClick: action('onApplicationNameClick'), }, logo: { id: 'header-logo', onClick: action('onLogoClick'), }, help: { id: 'header-help', icon: 'talend-question-circle', onClick: action('onHelpClick'), }, user: { id: 'header-user', items: [ { id: 'settings', icon: 'talend-cog', label: 'Settings', onClick: action('onSettingsClick'), }, ], name: 'John Doe', firstName: 'John', lastName: 'Doe', }, products: { items: [ { icon: 'talend-tdp-colored', key: 'tdp', label: 'Data Preparation', }, { icon: 'talend-tic-colored', key: 'tic', label: 'Integration Cloud', }, { icon: 'talend-tmc-colored', key: 'tmc', label: 'Management Console', }, ], onSelect: action('onProductClick'), }, }; const infoStyle = stylesheet => ({ ...stylesheet, button: { ...stylesheet.button, topRight: { ...stylesheet.button.topRight, top: '48px', }, }, }); function AppSwitcherComponent() { return <AppSwitcher {...props.brand} />; } function IntercomComponent() { const style = { color: 'white', margin: '0 10px', width: '3.2rem', height: '3.2rem', borderRadius: '50%', background: 'green', display: 'flex', alignItems: 'center', justifyContent: 'center', }; return ( <div style={style}> <Icon name="talend-bubbles" /> </div> ); } const withIcons = makeDecorator({ name: 'withIcons', wrapper: (getStory, context) => { const story = getStory(context); return ( <div> {story} <div className="container" style={{ paddingTop: 40 }} /> </div> ); }, }); export default { title: 'Navigation/HeaderBar', }; export const Default = () => { const headerProps = Immutable.fromJS(props).toJS(); return <HeaderBar {...headerProps} />; }; Default.story = { name: 'default', parameters: { info: { styles: infoStyle } }, }; export const WithFullLogo = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.logo.isFull = true; return <HeaderBar {...headerProps} />; }; WithFullLogo.story = { name: 'with full logo', parameters: { info: { styles: infoStyle } }, }; export const WithoutProducts = () => { const headerProps = Immutable.fromJS({ ...props, products: null, }).toJS(); headerProps.logo.isFull = true; return <HeaderBar {...headerProps} />; }; WithoutProducts.story = { name: 'without products', parameters: { info: { styles: infoStyle } }, }; export const WithEnvironmentDropdown = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.env = { id: 'header-environment', items: [ { label: 'Runtime Environment', onClick: action('onEnvClick'), }, ], label: 'Default', }; return <HeaderBar {...headerProps} />; }; WithEnvironmentDropdown.story = { name: 'with environment dropdown', parameters: { info: { styles: infoStyle } }, }; export const WithUnreadNotifications = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.notification = { hasUnread: true, }; return <HeaderBar {...headerProps} />; }; WithUnreadNotifications.story = { name: 'with unread notifications', parameters: { info: { styles: infoStyle } }, }; export const WithReadNotifications = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.notification = { hasUnread: false, }; return <HeaderBar {...headerProps} />; }; WithReadNotifications.story = { name: 'with read notifications', parameters: { info: { styles: infoStyle } }, }; export const WithHelpSplitDropdown = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.help.items = [ { icon: 'talend-board', label: 'Onboarding', onClick: action('onOnboardingClick'), }, { icon: 'talend-cog', label: 'About', onClick: action('onAboutClick'), }, ]; return <HeaderBar {...headerProps} />; }; WithHelpSplitDropdown.story = { name: 'with help split dropdown', parameters: { info: { styles: infoStyle } }, }; export const WithCallToAction = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.callToAction = { id: 'header-call-to-action', bsStyle: 'info', className: 'btn-inverse', label: 'Subscribe now', onClick: action('onActionClick'), }; return <HeaderBar {...headerProps} />; }; WithCallToAction.story = { name: 'with callToAction', parameters: { info: { styles: infoStyle } }, }; export const WithoutUserAndWithInformation = () => { const headerProps = Immutable.fromJS(props).toJS(); headerProps.user = null; headerProps.information = { id: 'header-info', bsStyle: 'link', icon: 'talend-info-circle', label: 'Information', hideLabel: true, pullRight: true, noCaret: true, tooltipPlacement: 'bottom', items: [ { label: 'Guided tour', onClick: action('onOnboardingClick'), }, { divider: true, }, { label: 'Community', target: '_blank', href: 'https://community.talend.com/', }, { label: 'Support', target: '_blank', href: 'https://www.talend.com/services/technical-support/', }, ], }; return <HeaderBar {...headerProps} />; }; WithoutUserAndWithInformation.story = { name: 'without user and with information', parameters: { info: { styles: infoStyle } }, }; export const _Intercom = () => ( <HeaderBar logo={props.logo} brand={props.brand} {...props} intercom={{ id: 'intercom', config: { app_id: 'j9pqsz4w', email: 'toto@gmail.com' } }} /> ); _Intercom.story = { name: 'intercom', parameters: { info: { styles: infoStyle } }, }; export const Barebone = () => <HeaderBar />; Barebone.story = { name: 'barebone', parameters: { info: { styles: infoStyle } }, }; export const CustomAppSwitcher = () => <HeaderBar AppSwitcher={AppSwitcherComponent} />; CustomAppSwitcher.story = { name: 'Custom AppSwitcher', parameters: { info: { styles: infoStyle }, }, }; export const CustomIntercom = () => <HeaderBar Intercom={IntercomComponent} />; CustomIntercom.story = { parameters: { info: { styles: infoStyle }, }, };
src/components/form.js
dbyers24/randomize-students
import React from 'react' class Form extends React.Component { constructor(props) { super(props); this.state = { output: 'student output will appear here', studentInput : '', } } handleSubmit(e) { console.log('Hit HandleSubmit, ', ) } handleAddStudent(e) { console.log('Hit handleAddStudent ', e) e.preventDefault() this.setState({ output: this.state.studentInput, studentInput: '', }) } handleInputChange(studentInput) { this.setState({studentInput}) console.log(this.state.studentInput) } render() { return ( <main> <h3>This will be a form</h3> <label> Add Student: <input id="add-student-input" value={this.state.studentInput} onChange={e => this.handleInputChange(e.target.value)} /> </label> <button id="add-student-button" onClick={e => this.handleAddStudent(e)} > {' '} +{' '} </button> <form> <label> # of groups <input id="number-groups-input" type="number" /> </label> <label> Group Size: <input id="size-groups-input" type="number" /> </label> <button id="submit-button" onClick={this.handleSubmit}> {' '} SUBMIT{' '} </button> </form> <textarea id="output-box" value={this.state.output}/> </main> ) } } export default Form
src/Administrator.js
OCMC-Translation-Projects/ioc-liturgical-react
import React from 'react'; import PropTypes from 'prop-types'; import axios from 'axios'; import { get } from 'lodash'; import IdManager from './helpers/IdManager'; import server from './helpers/Server'; import Button from './helpers/Button'; import Spinner from './helpers/Spinner'; import MessageIcons from './helpers/MessageIcons'; import FontAwesome from 'react-fontawesome'; import {Col, Grid, Row, Well} from 'react-bootstrap'; import ResourceSelector from './modules/ReactSelector'; import Form from "react-jsonschema-form"; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; import User from "./classes/User"; class Administrator extends React.Component { constructor(props) { super(props); this.state = this.setTheState(props, this.state); this.handleDelete = this.handleDelete.bind(this); this.setPath = this.setPath.bind(this); this.setItemDetails = this.setItemDetails.bind(this); this.onSubmit = this.onSubmit.bind(this); this.setMessage = this.setMessage.bind(this); this.getAdminGrid = this.getAdminGrid.bind(this); this.getResources = this.getResources.bind(this); this.getResourceItems = this.getResourceItems.bind(this); this.handleRowSelect = this.handleRowSelect.bind(this); this.getAdminContent = this.getAdminContent.bind(this); } componentWillMount = () => { this.getResources(); }; componentWillReceiveProps = (nextProps) => { this.state = this.setTheState(nextProps, this.state); }; setTheState = (props, currentState) => { let action = 'GET'; let path = 'users/statistics'; let item = {id: "", uiSchema: {}, schema: {}, value: {}}; let itemSelected = false; let resources = []; let submitButtonHidden = false; let centerDivVisible = false; let submitIsAPost = false; if (currentState) { if (currentState.action && currentState.action !== action) { action = currentState.action; } if (currentState.path && currentState.path !== path) { path = currentState.path; } if (currentState.item && currentState.item.id.length >0) { currentState.item = item; } if (currentState.itemSelected) { itemSelected = currentState.itemSelected; } if (currentState.resources && currentState.resources.length > 0) { resources = currentState.resources; } if (currentState.submitButtonHidden) { submitButtonHidden = currentState.submitButtonHidden; } if (currentState.centerDivVisible) { centerDivVisible = currentState.centerDivVisible; } if (currentState.submitIsAPost) { submitIsAPost = currentState.submitIsAPost; } } let userInfo = {}; if (props.session && props.session.userInfo) { userInfo = new User( props.session.userInfo.username , props.session.userInfo.password , props.session.userInfo.domain , props.session.userInfo.email , props.session.userInfo.firstname , props.session.userInfo.lastname , props.session.userInfo.title , props.session.userInfo.authenticated , props.session.userInfo.domains ); } return ( { labels: { thisClass: props.session.labels[props.session.labelTopics.AgesEditor] , messages: props.session.labels[props.session.labelTopics.messages] , liturgicalAcronyms: props.session.labels[props.session.labelTopics.liturgicalAcronyms] } , session: { userInfo: userInfo } , messageIcons: MessageIcons.getMessageIcons() , messageIcon: MessageIcons.getMessageIcons().info , message: props.session.labels[props.session.labelTopics.messages].initial , action: action , path: path , item: item , itemSelected: itemSelected , resources: resources , submitButtonHidden: submitButtonHidden , deleteButtonVisible: get(currentState,"deleteButtonVisible", true) , centerDivVisible: centerDivVisible , submitIsAPost: submitIsAPost , options: { sizePerPage: 10 , sizePerPageList: [5, 15, 30] , onSizePerPageList: this.onSizePerPageList , hideSizePerPage: true , paginationShowsTotal: true } , selectRow: { mode: 'radio' , clickToSelect: true , onSelect: this.handleRowSelect , hideSelectColumn: true } } ) }; setMessage(message) { this.setState({ message: message }); } setPath(newPath, updateMessage) { if (newPath) { var path = (newPath.value ? newPath.value : newPath); this.setState({ path: path , centerDivVisible: false , submitIsAPost: path.includes("new/forms") }, this.fetchData(path, updateMessage)); ; } } setItemDetails(id, uiSchema, schema, value) { let hidden = false; let deleteVisible = ! id.includes("~new~"); if (uiSchema["ui:readonly"]) { hidden = true; } this.setState({ item: { id: id, uiSchema: uiSchema, schema: schema, value: value} , itemSelected: true , submitButtonHidden: hidden , deleteButtonVisible: deleteVisible , centerDivVisible: true }); } handleRowSelect = (row, isSelected, e) => { this.setItemDetails( row._id, this.state.data.valueSchemas[row._valueSchemaId].uiSchema , this.state.data.valueSchemas[row._valueSchemaId].schema , row.value ); }; fetchData(path, updateMessage) { var config = { auth: { username: this.state.session.userInfo.username , password: this.state.session.userInfo.password } }; axios.get( this.props.session.restServer + server.getWsServerAdminApi() + path , config ) .then(response => { this.setState( { data: response.data } ); if (updateMessage) { this.setState( { message: "found " + (response.data.valueCount ? response.data.valueCount : "") + " docs for " + IdManager.padPath(path) , messageIcon: this.state.messageIcons.info } ); } }) .catch( (error) => { var message = error.message; var messageIcon = this.state.messageIcons.error; if (error && error.response && error.response.status === 404) { message = "no docs found"; messageIcon = this.state.messageIcons.warning; } this.setState( { data: message, message: message, messageIcon: messageIcon }); }); } // /delete/user handleDelete() { let config = { auth: { username: this.state.session.userInfo.username , password: this.state.session.userInfo.password } }; axios.delete( this.props.session.restServer + server.getWsServerAdminApi() + IdManager.idToPath(this.state.item.id) , config ) .then(response => { this.setState({ message: "deleted " + IdManager.idToPaddedPath(this.state.item.id) }); this.setPath(this.state.path); this.setState({centerDivVisible: true, submitIsDelete: false}); }) .catch( (error) => { var message = error.response.data.userMessage; var messageIcon = this.state.messageIcons.error; this.setState( { data: message, message: message, messageIcon: messageIcon }); }); } handlePost(formData) { var config = { auth: { username: this.state.session.userInfo.username , password: this.state.session.userInfo.password } }; axios.post( this.props.session.restServer + server.getWsServerAdminApi() + IdManager.idToPath(this.state.item.id) , formData.formData , config ) .then(response => { this.setState({ message: "updated " + IdManager.idToPaddedPath(this.state.item.id), item: { id: this.state.item.id, uiSchema: this.state.item.uiSchema, schema: this.state.item.schema, value: formData.formData} }); this.setPath(this.state.path); this.setState({centerDivVisible: true}); }) .catch( (error) => { var message = error.response.data.userMessage; var messageIcon = this.state.messageIcons.error; this.setState( { data: message, message: message, messageIcon: messageIcon }); }); } handlePut(formData) { var config = { auth: { username: this.state.session.userInfo.username , password: this.state.session.userInfo.password } }; let path = IdManager.idToPath(this.state.item.id); let message = ""; if (path.startsWith("misc/utilities")) { this.setState({ message: "This will take a few minutes" }); } axios.put( this.props.session.restServer + server.getWsServerAdminApi() + path , formData.formData , config ) .then(response => { message = "updated " + path; if (path.startsWith("misc/utilities")) { message = path + ": " + response.data.userMessage; } if (formData.formData && formData.formData.password) { if (formData.formData.username === this.props.session.userInfo.username) { this.state.session.userInfo.password = formData.formData.password; } } this.setState({ message: message , item: { id: this.state.item.id , uiSchema: this.state.item.uiSchema , schema: this.state.item.schema , value: formData.formData } }); this.setPath(this.state.path); this.setState({centerDivVisible: true}); }) .catch( (error) => { var message = error.message; var messageIcon = this.state.messageIcons.error; this.setState( { data: message, message: message, messageIcon: messageIcon }); }); } onSubmit(formData) { if (this.state.submitIsAPost) { this.handlePost(formData); } else { this.handlePut(formData); } } getResources = () => { var config = { auth: { username: this.state.session.userInfo.username , password: this.state.session.userInfo.password } }; axios.get( this.props.session.restServer + server.getWsServerAdminApi() + "resources" , config ) .then(response => { this.setState({ resources: response.data.resources }, this.fetchData("users/statistics", true) ); }) .catch( (error) => { this.setState({ resources: [] }); }); }; getResourceItems = () => { if (this.state.data) { if (this.state.data === 'no docs found') { return ("") } else { return ( <div> <Well> <div className="control-label">Select an item...</div> <BootstrapTable data={this.state.data.values} trClassName={"App-data-tr"} striped hover pagination options={ this.state.options } selectRow={this.state.selectRow} search > <TableHeaderColumn isKey dataField='_id' dataSort={ true } >ID</TableHeaderColumn> </BootstrapTable> </Well> </div> ) } } else { return ( "" ) } }; getAdminGrid = () => { return ( <Grid> <Row className="show-grid"> <Col sm={5} md={5}> <Well> <ResourceSelector initialValue={this.state.path} resources={this.state.resources} changeHandler={this.setPath} multiSelect={false} title="Select a resource:" /> </Well> {this.getResourceItems()} </Col> <Col sm={7} md={7}> {this.state.itemSelected && this.state.centerDivVisible && <div className="App-form-container"> <Well> <h3>ID: {IdManager.idToPaddedPath(this.state.item.id)}</h3> <Form schema={this.state.item.schema} uiSchema={this.state.item.uiSchema} formData={this.state.item.value} onSubmit={this.onSubmit}> <div> <Button label="Submit" hidden={this.state.submitButtonHidden}/> {this.state.deleteButtonVisible && <button type="button" className="App-Form-Delete-Button" onClick={this.handleDelete} >Delete </button> } </div> </Form> </Well> </div> } </Col> <Col sm={0} md={0}></Col> </Row> </Grid> ) }; getAdminContent = () => { if (this.state.resources) { return ( <div className="App-administrator"> <Grid> <Row className="show-grid"> <Col sm={3} md={3}> </Col> <Col sm={6} md={6}> <div className="App App-message"><FontAwesome name={this.state.messageIcon} />{this.state.message}</div> </Col> <Col sm={3} md={3}></Col> </Row> </Grid> {this.getAdminGrid()} </div> ); } else { return ( <div className="App-administrator"> <Spinner message={this.state.labels.messages.retrieving}/> </div> ); } }; render() { return ( <div> <div>{this.getAdminContent()}</div> </div> ) } } Administrator.propTypes = { session: PropTypes.object.isRequired }; Administrator.defaultProps = { }; export default Administrator;
src/interface/icons/UpArrow.js
fyruna/WoWAnalyzer
import React from 'react'; const Icon = ({ ...other }) => ( <svg viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg" className="icon" {...other}><path d="M0 25L25 0l25 25H37.4v25h-25V25H0z" /></svg> ); export default Icon;
Realization/frontend/czechidm-core/src/content/audit/event/EntityStates.js
bcvsolutions/CzechIdMng
import React from 'react'; import {connect} from 'react-redux'; import * as Basic from '../../../components/basic'; import EntityStateTable from './EntityStateTable'; /** * Audit of entity events state. * * @author artem * @author Radek Tomiška */ class EntityStates extends Basic.AbstractContent { getNavigationKey() { return 'entity-states'; } getContentKey() { return 'content.entityStates'; } render() { return ( <Basic.Div> { this.renderPageHeader() } <Basic.Panel> <EntityStateTable uiKey="entity-states-table" filterOpened showRowSelection/> </Basic.Panel> </Basic.Div> ); } } export default connect()(EntityStates);
client/result_set.js
golmansax/funnel
import React from 'react'; import FilterList from './filter_list'; import styles from './result_set.css'; import Link from './link'; export default class ResultSet extends React.Component { constructor(props) { super(props); this._renderParentResult = this._renderParentResult.bind(this); this._renderChildResultList = this._renderChildResultList.bind(this); this._renderFilters = this._renderFilters.bind(this); } render() { return ( <div className={styles.resultSet}> {this._renderParentResult()} {this._renderChildResultList()} {this._renderFilters(this.props.parentResult.filters)} </div> ); } _renderParentResult() { const parentResult = this.props.parentResult; return ( <Link className={styles.parentResult} href={parentResult.url}> {parentResult.displayText} {this._renderPath(parentResult.path)} </Link> ); } _renderPath(path) { if (!path) { return null; } return <div className={styles.path}>in {path}</div>; } _renderChildResultList() { if (!this.props.childResults || this.props.childResults.length <= 0) { return null; } return this.props.childResults.slice(0, 3).map(this._renderChildResult); } _renderFilters(filters) { if (!filters || filters.length <= 0) { return null; } return ( <FilterList categoryName={this.props.parentResult.displayText} filters={filters} /> ); } _renderChildResult(result, index) { return ( <Link className={styles.childResult} key={index} href={result.url}> {result.displayText} </Link> ); } }
app/components/ToggleOption/index.js
Frai/Events
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
src/galaxy/store/hover.js
ryanwsmith/pm
import React from 'react'; import eventify from 'ngraph.events'; import appEvents from '../service/appEvents.js'; import scene from './scene.js'; import getBaseNodeViewModel from './baseNodeViewModel.js'; export default hoverStore(); function hoverStore() { var store = {}; eventify(store); appEvents.nodeHover.on(prepareViewModelAndNotifyConsumers); return store; function prepareViewModelAndNotifyConsumers(hoverDetails) { var hoverTemplate = null; if (hoverDetails.nodeIndex !== undefined) { var viewModel = createViewModel(hoverDetails); hoverTemplate = createDefaultTemplate(viewModel); } store.fire('changed', hoverTemplate); } function createViewModel(model) { if (model === null) throw new Error('Model is not expected to be null'); var hoverViewModel = getBaseNodeViewModel(model.nodeIndex); hoverViewModel.left = model.mouseInfo.x; hoverViewModel.top = model.mouseInfo.y; return hoverViewModel; } } function createDefaultTemplate(viewModel) { var style = { left: viewModel.left + 20, top: viewModel.top - 35 }; return ( <div style={style} className='node-hover-tooltip'> {viewModel.name} <span className='in-degree'>{viewModel.inDegree}</span> <span className='out-degree'>{viewModel.outDegree}</span> </div> ); }
src/index.js
andreiamlm/ReactVideoPlayer
import _ from 'lodash'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar' import VideoList from './components/video_list' import VideoDetail from './components/video_detail' const API_KEY = 'AIzaSyAV7gzAuLHy-Dq-LEu6oZUz2lu0eE0oi6I'; class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('surfboards'); } videoSearch(term) { YTSearch({key: API_KEY, term: term }, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => {this.videoSearch(term) }, 300); return ( <div> <SearchBar onSearchTermChange={term => this.videoSearch(term)} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo}) } videos={this.state.videos} /> </div> ); } } ReactDOM.render(<App />, document.querySelector('.container'));
react/features/chat/components/web/ChatPrivacyDialog.js
jitsi/jitsi-meet
/* @flow */ import React from 'react'; import { Dialog } from '../../../base/dialog'; import { translate } from '../../../base/i18n'; import { connect } from '../../../base/redux'; import { AbstractChatPrivacyDialog, _mapDispatchToProps, _mapStateToProps } from '../AbstractChatPrivacyDialog'; /** * Implements a component for the dialog displayed to avoid mis-sending private messages. */ class ChatPrivacyDialog extends AbstractChatPrivacyDialog { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <Dialog cancelKey = 'dialog.sendPrivateMessageCancel' okKey = 'dialog.sendPrivateMessageOk' onCancel = { this._onSendGroupMessage } onSubmit = { this._onSendPrivateMessage } titleKey = 'dialog.sendPrivateMessageTitle' width = 'small'> <div> { this.props.t('dialog.sendPrivateMessage') } </div> </Dialog> ); } _onSendGroupMessage: () => boolean; _onSendPrivateMessage: () => boolean; } export default translate(connect(_mapStateToProps, _mapDispatchToProps)(ChatPrivacyDialog));
modules/IndexLink.js
mozillo/react-router
import React from 'react' import Link from './Link' const IndexLink = React.createClass({ render() { return <Link {...this.props} onlyActiveOnIndex={true} /> } }) export default IndexLink
src/layout/sliderBar/index.js
SmiletoSUN/react-redux-demo
import React from 'react'; import { Layout, Menu, Icon } from 'antd'; import { Link } from 'react-router-dom'; const { Sider } = Layout; const { SubMenu } = Menu; export default class SiderCustomer extends React.Component { state = { collapsed: false, mode: 'inline', openKey: 'key', selectedKey: '', }; componentWillMount() { const path = this.props.location.pathname.split('/'); this.setState({ openKey: path[2], selectedKey: this.props.location.pathname, }); } onCollapse = (collapsed) => { this.setState({ collapsed, mode: collapsed ? 'vertical' : 'inline', }); }; menuClick = (e) => { this.setState({ selectedKey: e.key, }); }; openMenu = (v) => { this.setState({ openKey: v[v.length - 1] }); }; renderMenu = (MenuData) => { const subMenu = MenuData.map((item) => { if (item.subMenu) { return ( <SubMenu key={item.name} title={ <span> <Icon type="scan" /> <span className="nav-text">{item.name}</span> </span> } > {item.subMenu.map(subMenuItem => ( <Menu.Item key={subMenuItem.url}> <Link to={subMenuItem.url}>{subMenuItem.name}</Link> </Menu.Item> ))} </SubMenu> ); } return ( <Menu.Item key={item.url}> <Link to={item.url}>{item.name}</Link> </Menu.Item> ); }); return ( <Menu onClick={this.menuClick} theme="dark" mode={this.state.mode} selectedKeys={[this.state.selectedKey]} openKeys={[this.state.openKey]} onOpenChange={this.openMenu} > {subMenu} </Menu> ); }; render() { const { MenuData } = this.props; const { collapsed } = this.state; return ( <Sider className={this.props.className} trigger={null} breakpoint="lg" collapsed={collapsed}> <div className="logo" /> {this.renderMenu(MenuData)} </Sider> ); } }
src/svg-icons/av/video-label.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLabel = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 13H3V5h18v11z"/> </SvgIcon> ); AvVideoLabel = pure(AvVideoLabel); AvVideoLabel.displayName = 'AvVideoLabel'; AvVideoLabel.muiName = 'SvgIcon'; export default AvVideoLabel;
demo/src/components/button-views/flat-button-view.js
tuantle/hypertoxin
'use strict'; // eslint-disable-line import { Ht } from 'hypertoxin'; import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import PropTypes from 'prop-types'; import DefaultTheme from '../../themes/default-theme'; const { RowLayout, ColumnLayout, HeadlineText, InfoText, CaptionText, FlatButton, IconImage, HorizontalDivider } = Ht; export default class FlatButtonView extends React.Component { static propTypes = { Theme: PropTypes.object, shade: PropTypes.oneOf([ `light`, `dark` ]) } static defaultProps = { Theme: DefaultTheme, shade: `light` } constructor (props) { super(props); this.headerScreenRef = null; this.state = { badgeCount: 0 }; } render () { const component = this; const { shade } = component.props; const { badgeCount } = component.state; return ( <RowLayout shade = { shade } roomAlignment = 'center' contentTopRoomAlignment = 'center' > <HeadlineText room = 'content-top' > Flat Buttons </HeadlineText> <CaptionText room = 'content-top' size = 'large' > With color themes </CaptionText> <ColumnLayout room = 'content-top' roomAlignment = 'start' margin = { 10 } > <FlatButton room = 'content-left' overlay = 'opaque' label = 'BUTTON' color = 'default' /> <FlatButton room = 'content-left' overlay = 'opaque' label = 'BUTTON' color = 'primary' /> <FlatButton room = 'content-middle' overlay = 'opaque' label = 'BUTTON' color = 'secondary' /> <FlatButton room = 'content-right' overlay = 'opaque' label = 'BUTTON' color = 'accent' /> </ColumnLayout> <CaptionText room = 'content-top' size = 'large' > With corner styles </CaptionText> <ColumnLayout room = 'content-top' roomAlignment = 'start' margin = { 10 } > <FlatButton room = 'content-left' overlay = 'opaque' label = 'BUTTON' color = 'primary' corner = 'sharp' /> <FlatButton room = 'content-middle' overlay = 'opaque' label = 'BUTTON' color = 'secondary' corner = 'round' /> <FlatButton room = 'content-right' overlay = 'opaque' label = 'BUTTON' color = 'accent' corner = 'circular' /> </ColumnLayout> <CaptionText room = 'content-top' size = 'large' > With 3 sizes & icon to the left </CaptionText> <ColumnLayout room = 'content-top' roomAlignment = 'center' margin = { 10 } > <FlatButton room = 'content-middle' overlay = 'opaque' size = 'small' label = 'SMALL' color = 'primary' > <IconImage room = 'content-left' source = 'home' /> </FlatButton> <FlatButton room = 'content-middle' overlay = 'opaque' size = 'normal' label = 'NORMAL' color = 'secondary' > <IconImage room = 'content-left' source = 'home' /> </FlatButton> <FlatButton room = 'content-middle' overlay = 'opaque' size = 'large' label = 'LARGE' color = 'accent' > <IconImage room = 'content-left' source = 'home' /> </FlatButton> </ColumnLayout> <CaptionText room = 'content-top' size = 'large' > With 3 sizes & icon to the right </CaptionText> <ColumnLayout room = 'content-top' roomAlignment = 'center' margin = { 10 } > <FlatButton room = 'content-middle' overlay = 'opaque' size = 'small' label = 'SMALL' color = 'primary' > <IconImage room = 'content-right' source = 'profile' /> </FlatButton> <FlatButton room = 'content-middle' overlay = 'opaque' size = 'normal' label = 'NORMAL' color = 'secondary' > <IconImage room = 'content-right' source = 'profile' /> </FlatButton> <FlatButton room = 'content-middle' overlay = 'opaque' size = 'large' label = 'LARGE' color = 'accent' > <IconImage room = 'content-right' source = 'profile' /> </FlatButton> </ColumnLayout> <CaptionText room = 'content-top' size = 'large' > With badges </CaptionText> <FlatButton room = 'content-top' overlay = 'opaque' size = 'normal' label = 'BUTTON' onPress = {() => { component.setState((prevState) => { return { badgeCount: prevState.badgeCount < 10 ? prevState.badgeCount + 1 : 0 }; }); }} > <IconImage room = 'content-left' source = 'home' /> <InfoText room = 'badge' exclusions = {[ `color` ]} color = 'white' >{ badgeCount }</InfoText> </FlatButton> <CaptionText room = 'content-top' size = 'large' > Disabled button </CaptionText> <FlatButton room = 'content-top' overlay = 'opaque' size = 'normal' label = 'DISABLED' disabled = { true } > <IconImage room = 'content-left' source = 'home' /> </FlatButton> <HorizontalDivider room = 'content-middle' edgeToEdge = { true }/> <HeadlineText room = 'content-middle' > Flat Outlined Buttons </HeadlineText> <CaptionText room = 'content-middle' size = 'large' > With different sizes & stylings </CaptionText> <ColumnLayout room = 'content-middle' roomAlignment = 'start' margin = { 10 } > <FlatButton room = 'content-left' overlay = 'transparent-outline' size = 'small' label = 'BUTTON' color = 'primary' corner = 'sharp' > <IconImage room = 'content-left' source = 'star' /> </FlatButton> <FlatButton room = 'content-middle' overlay = 'transparent-outline' size = 'normal' label = 'BUTTON' color = 'secondary' corner = 'round' > <IconImage room = 'content-right' source = 'star' /> </FlatButton> <FlatButton room = 'content-right' overlay = 'transparent-outline' size = 'large' label = 'BUTTON' color = 'accent' corner = 'circular' /> </ColumnLayout> </RowLayout> ); } }
clients/components/ProSettings/ProFreeTrial/ProFreeTrial.js
Desertsnowman/Caldera-Forms
import React from 'react'; import propTypes from 'prop-types'; import classNames from 'classnames'; import {Button} from 'react'; /** * Create the ProFreeTrial UI * @param {Object} props * @return {*} * @constructor */ export const ProFreeTrial = (props) => { const documentationHref = `https://calderaforms.com/doc/caldera-forms-pro-getting-started/?utm_source=wp-admin&utm_campaign=pro-screen&utm_term=not-connected`; const trialHref = `https://calderaforms.com/checkout?edd_action=add_to_cart&download_id=64101&edd_options[price_id]=1?utm_source=wp-admin&utm_campaign=pro-screen&utm_term=not-connected`; return( <div className={classNames(props.className,ProFreeTrial.classNames.wrapper)} > <p>Ready to try Caldera Forms Pro? Plans start at just 14.99/ month with a 7 day free trial.</p> <div> <a href={documentationHref} target={'_blank'} className={'button'} > Documentation </a> <a target={'_blank'} href={trialHref} className={'button button-primary'} > Start Free Trial </a> </div> </div> ) }; /** * Prop types for the ProFreeTrial component * @type {{}} */ ProFreeTrial.propTypes = { classNames: propTypes.string }; /** * Class names used in ProFreeTrial component * @type {{wrapper: string}} */ ProFreeTrial.classNames = { wrapper: 'caldera-forms-pro-free-trial' }
src/packages/@ncigdc/components/Modals/ControlledAccess/CAIconMessage.js
NCI-GDC/portal-ui
// @flow import React from 'react'; const CAIconMessage = ({ children, faClass, }) => ( <span> <i className={`fa ${faClass}`} style={{ color: '#773388' }} /> {' '} {children} </span> ); export default CAIconMessage;
app/javascript/mastodon/features/compose/components/autosuggest_account.js
Arukas/mastodon
import React from 'react'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class AutosuggestAccount extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const { account } = this.props; return ( <div className='autosuggest-account'> <div className='autosuggest-account-icon'><Avatar account={account} size={18} /></div> <DisplayName account={account} /> </div> ); } }
src/svg-icons/av/playlist-add-check.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPlaylistAddCheck = (props) => ( <SvgIcon {...props}> <path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zM2 16h8v-2H2v2zm19.5-4.5L23 13l-6.99 7-4.51-4.5L13 14l3.01 3 5.49-5.5z"/> </SvgIcon> ); AvPlaylistAddCheck = pure(AvPlaylistAddCheck); AvPlaylistAddCheck.displayName = 'AvPlaylistAddCheck'; AvPlaylistAddCheck.muiName = 'SvgIcon'; export default AvPlaylistAddCheck;
src/components/PaperComponents/sections/Work.js
tuomotlaine/portfolio
import React, { Component } from 'react'; import TypeWriter from '../../TypeWriter'; import RenderComputer from '../../RenderComputer'; import Prompt from '../Prompt'; class Work extends Component { constructor(props){ super(props); this.state = { renderComputerCounter: 0 } } renderComputer(){ let rcc = this.state.renderComputerCounter + 1; this.setState({ renderComputerCounter: rcc }); } componentDidUpdate(){ //document.body.scrollTop = document.body.scrollHeight; } render() { return( <RenderComputer renderChild={this.state.renderComputerCounter}> <div className="row" style={{marginTop: '40px'}}> <div className="col-xs-12"> <TypeWriter speed={20} input="My latest work <br/> ----------------" onReady={this.renderComputer.bind(this)} fontSize="1.1rem" /> </div> </div> <div className="row" style={{marginTop: '24px'}}> <div className="col-xs-12"> <TypeWriter speed={20} input="Lately I've been working on two main projects: Mobile Electric and Rentle, which we operate under a company I co-founded called <a href='http://www.vitrine-digital.fi' target='_blank'>Vitrine Digital</a>. I just re-designed and coded the website for ME and Vitrine Digital. Also writing my thesis is taking a bit of my time. The working title is 'How service creation tools &amp; methods help inexperienced pre-seed start ups reach problem-solution fit?'" onReady={this.renderComputer.bind(this)} /> </div> </div> <div className="row" style={{marginTop: '24px'}}> <div className="col-xs-12 col-md-4" style={{paddingBottom: '20px'}}> <img className="img-fluid center-block rounded" src="assets/images/mobe_black.png" alt="Mobile Electric Logo"/> <figcaption className="text-xs-center">Mobile electric</figcaption> </div> <div className="col-xs-12 col-md-8"> <TypeWriter speed={20} input="<a href='https://www.mobileelectric.fi' target='_blank'>Mobile Electric</a> <br /> ----- <br /> Mobile Electric aims to solve the mobile charging problems of consumers in shopping centers, hotels, bars, events and cities in general. We have done all the code, designs and imported&amp;modified the used power banks. I've contributed on pretty much everything since we were a team of 2 people." onReady={this.renderComputer.bind(this)}/> </div> </div> <Prompt userSelected={(args) => {this.props.nextSection(args)}} prompts={{ WorkMore: 'Tell me about the other projects.', Who: 'Actually, tell me who you are?', WhoMore: 'Tell me more about you ', Photos: 'Show me some of the photos you have taken', Contact: 'How can I contact you?' }} /> </RenderComputer> ); } } export { Work };
src/svg-icons/editor/format-shapes.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatShapes = (props) => ( <SvgIcon {...props}> <path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/> </SvgIcon> ); EditorFormatShapes = pure(EditorFormatShapes); EditorFormatShapes.displayName = 'EditorFormatShapes'; EditorFormatShapes.muiName = 'SvgIcon'; export default EditorFormatShapes;
.core/app/routes.js
suranartnc/graphql-blogs-app
import React from 'react' import { Route, IndexRoute } from 'react-router' import App from 'core/app/pages/App' import Homepage from 'core/app/pages/Homepage' import ErrorPage from 'core/app/pages/ErrorPage' import getCustomRoutes from 'app/routes' export default function getRoutes (store = null) { return ( <Route path="/" component={App}> {getCustomRoutes()} <Route path="*" component={ErrorPage} status="404" /> </Route> ) }
src/client/moderator.js
davidbstein/moderator
import React from 'react' import {connect} from 'react-redux' import Question from './client-views/question' import Event from './client-views/event' import Org from './client-views/org' export default connect( storeState => storeState )( class Moderator extends React.Component { render() { switch (this.props.viewState.page) { case "org": return <Org org_domain={this.props.viewState.state.org_domain} /> case "event": return <Event lookup_id={this.props.viewState.state.lookup_id} /> // case "question": // const question = this.props.viewState.state.question // return <QuestionPage // question={question} // /> default: return <div> error :( </div> } } } );
web/src/js/components/General/withUser.js
gladly-team/tab
import React from 'react' import { onAuthStateChanged } from 'js/authentication/user' import { createAnonymousUserIfPossible, redirectToAuthIfNeeded, } from 'js/authentication/helpers' import logger from 'js/utils/logger' import { makePromiseCancelable } from 'js/utils/utils' import { SEARCH_APP, TAB_APP } from 'js/constants' import { isReactSnapClient } from 'js/utils/search-utils' // https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component' } /** * Adds an "authUser" prop, an AuthUser object from our authentication, to * the wrapped child component. Optionally, it attempts to create a user if * one does not exist and redirects to the authentication page if the user * is not fully authenticated. * @param {Object} options * @param {String} options.app - One of "search" or "tab". This determines * app-specific behavior, like the redirect URL. Defaults to "tab". * @param {Boolean} options.renderIfNoUser - If true, we will render the * children after we determine the user is not signed in. * Defaults to false. * @param {Boolean} options.renderWhileDeterminingAuthState - If true, * we will render the children before we know whether the user is authed * or not. This is helpful for pages that need to load particularly quickly * or pages we prerender at build time. Typically, renderIfNoUser should also * be set to true if this is true. Defaults to false. * @param {Boolean} options.createUserIfPossible - If true, when a user does * not exist, we will create a new anonymous user both in our auth service * and in our database. We might not always create a new user, depending on * our anonymous user restrictions. Defaults to true. * @param {Boolean} options.redirectToAuthIfIncomplete - If true, when a user * is not authenticated or has not completed sign-up (e.g. does not have a * user ID), we will redirect to the appropriate authentication page. * our anonymous user restrictions. It should be false when using withUser * in a page where authentication is optional. Defaults to true. * @param {Boolean} options.setNullUserWhenPrerendering - If true, we will * not test auth state during build-time prerendering. Instead, we will * set the authUser value to null. Defaults to true. * @return {Function} A higher-order component. */ const withUser = (options = {}) => WrappedComponent => { class CompWithUser extends React.Component { constructor(props) { super(props) this.state = { authUser: null, authStateLoaded: false, userCreationInProgress: false, } this.authListenerUnsubscribe = null this.userCreatePromise = null this.mounted = false } componentDidMount() { this.mounted = true // Check the auth state. Optionally, when prerendering, just // immediately set a null user value. const { setNullUserWhenPrerendering = true } = options if (setNullUserWhenPrerendering && isReactSnapClient()) { this.setState({ authUser: null, authStateLoaded: true, }) } else { // Store unsubscribe function. // https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged this.authListenerUnsubscribe = onAuthStateChanged(user => { this.determineAuthState(user) }) } } componentWillUnmount() { if (typeof this.authListenerUnsubscribe === 'function') { this.authListenerUnsubscribe() } if (this.userCreatePromise && this.userCreatePromise.cancel) { this.userCreatePromise.cancel() } this.mounted = false } async determineAuthState(user) { const { app = TAB_APP, createUserIfPossible = true, redirectToAuthIfIncomplete = true, } = options let authUser = user // If the user doesn't exist, create one if possible. // IMPORTANT: this logic only works for Tab for a Cause, not Search. if (!(user && user.id) && createUserIfPossible) { // If options.app === 'search', warn that we don't support this // logic and don't do anything. if (app === SEARCH_APP) { console.warn( 'Anonymous user creation is not yet supported in the Search app.' ) } else { // Mark that user creation is in process so that we don't // don't render child components after the user is authed // but before the user exists in our database. this.setState({ userCreationInProgress: true, }) try { this.userCreatePromise = makePromiseCancelable( createAnonymousUserIfPossible() ) authUser = await this.userCreatePromise.promise } catch (e) { // If the component already unmounted, don't do anything with // the returned data. if (e && e.isCanceled) { return } logger.error(e) } // This is an antipattern, and canceling our promises on unmount // should handle the problem. However, in practice, the component // sometimes unmounts between the userCreatePromise resolving and // this point, causing an error when we try to update state on the // unmounted component. It shouldn't cause a memory leak, as we've // canceled the promise and unsubscribed the auth listener. // Note that this might be an error in our code, but it's not a // priority to investigate. if (!this.mounted) { return } this.setState({ userCreationInProgress: false, }) } } let redirected = false if (redirectToAuthIfIncomplete) { try { const urlParams = { app: app } redirected = redirectToAuthIfNeeded({ authUser, urlParams }) } catch (e) { logger.error(e) } } if (!redirected && this.mounted) { this.setState({ authUser: authUser, authStateLoaded: true, }) } } render() { const { renderWhileDeterminingAuthState = false, renderIfNoUser = false, } = options const { authUser, authStateLoaded, userCreationInProgress } = this.state // By default, don't render the children until we've determined the // auth state. if ( !renderWhileDeterminingAuthState && (!authStateLoaded || userCreationInProgress) ) { return null } // Return null if the user is not authenticated and the children require // an authenticated user. if (!authUser && !renderIfNoUser) { return null } return <WrappedComponent authUser={authUser} {...this.props} /> } } CompWithUser.displayName = `withUser(${getDisplayName(WrappedComponent)})` return CompWithUser } export default withUser
src/images/Icons/bag.js
sourabh-garg/react-starter-kit
import React from 'react'; export default function bag(props) { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="48px" height="48px" viewBox="0 0 48 48" enableBackground="new 0 0 48 48" xmlSpace="preserve" {...props}> <g transform="translate(0, 0)"> <path fill="#adaaaa" d="M40,13h-7l0-2.682c0-4.789-3.605-8.977-8.383-9.297C19.377,0.669,15,4.834,15,10v3H8c-1.105,0-2,0.895-2,2 v30c0,1.105,0.895,2,2,2h32c1.105,0,2-0.895,2-2V15C42,13.895,41.105,13,40,13z M17,10c0-3.86,3.14-7,7-7s7,3.14,7,7v3H17V10z" /> </g> </svg> ); }
src/svg-icons/notification/ondemand-video.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationOndemandVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-6l-7 4V7z"/> </SvgIcon> ); NotificationOndemandVideo = pure(NotificationOndemandVideo); NotificationOndemandVideo.displayName = 'NotificationOndemandVideo'; export default NotificationOndemandVideo;
pages/index.js
whatever555/countries
import React, { Component } from 'react'; import dynamic from 'next/dynamic'; import HomeScreen from '../components/HomeScreen'; import data from '../static/json/data'; import info from '../static/json/info'; import { urlBase64ToUint8Array, makeid } from '../helpers/utils'; import Timer from '../components/Timer'; import { Toast, Warning, Header, Score, SubHeader } from '../components/Header'; import Portal from 'react-minimalist-portal'; import Icon from '../components/Icon'; import styled from 'styled-components'; import { allDifficulties, allContinents, allGameModes, Themes, } from '../common/consts'; import { BID } from '../common/BID'; import { MainWrapper, HomeButton } from '../common/styles'; import Head from 'next/head'; import ReactGA from 'react-ga'; const CommonSprite = dynamic(() => import('../components/CommonSprite'), { loading: () => <></>, }); const MapSprite = dynamic(() => import('../components/MapSprite'), { loading: () => <></>, }); const FlagSprite = dynamic(() => import('../components/FlagSprite'), { loading: () => <></>, }); const selectedTheme = 0; //Math.floor(Math.random() * Themes.length); const NoScriptHomeLink = styled.a` display: inline; color: white; position: absolute; `; const StatsLink = styled.a` display: inline; color: white; font-weight:bold; `; import { Menu, FlagGame, PopulationsGame, MapGame, TriviaGame, BordersGame, CapitalsGame, EndGame, StartScreen, CountDown, CountryInfo, } from '../components/Modes/'; import { populateMyData, updateLocalStorage, updateMyDay, getMyData, getMyName, setMyName, } from '../helpers/LocalStorageHelper'; import { createStaticUrl, encrypt, decrypt } from '../helpers/encrypt'; import { getCountryByAlpha2Code, generatePageTitle, generateBasicTitle, } from '../helpers/utils'; import { getFreshQuestion } from '../helpers/questions'; const TOTAL_QUESTIONS = 9; const SitemapLink = styled.a` color: #ededec; cursor: pointer; position: absolute; top: 10px; right: 0px; padding: 5px; background: rgba(23, 23, 23, 0.23); z-index: 200; `; const StyledMap = styled.div` opacity: ${props => (props.opacity ? props.opacity : '0.6')}; width: 100%; height: 100%; max-height: 1110px; position: fixed !important; top: 0px; left: 0px; z-index: 0; transition: opacity ease-in ${Themes[selectedTheme].speed}s; &::after { content: ''; opacity: ${props => (props.opacity ? props.opacity : '0.6')}; position: absolute; width: 100%; height: 70px; bottom: 0px; left: 0px; background: linear-gradient( to bottom, rgba(255, 255, 255, 0) 0%, ${props => props.selectedTheme ? Themes[props.selectedTheme].color : Themes[selectedTheme].color} 100% ); } `; const Wrapper = styled.div` opacity: 0.98; min-height: 100%; position: absolute; top: 0; left: 0; background-color: ${props => props.selectedTheme ? Themes[props.selectedTheme].color : Themes[selectedTheme].color}; z-index: 1; min-height: 100%; /* will cover the 100% of viewport */ applications/overflow: hidden; display: block; margin: 0; padding: 0; position: absolute; width: 100%; @media screen and (max-height: 650px) { padding-bottom: 0px; /* height of your footer */ } `; const createUrl = state => { if (['HOME', 'ENDGAME', 'AWAIT_SCREEN'].indexOf(state.gameStatus) !== -1) { return ''; } let { gameModes, continents, gameStatus, difficulty, currentQuestion, locale, } = state; if (gameStatus === 'INFO') { delete currentQuestion.answers; delete currentQuestion.gameMode; } if (['START_SCREEN', 'HOME', 'ENDGAME', 'AWAIT_SCREEN'].indexOf(state.gameStatus) !== -1) { currentQuestion = null; } let urlData = { gameStatus, continents, gameModes }; if (currentQuestion !== null) { urlData = { gameStatus }; delete currentQuestion.continents; delete currentQuestion.answer.lnglat; if(currentQuestion.answer.name === currentQuestion.answer.population){ delete currentQuestion.answer.poulation; } if (currentQuestion.gameMode && currentQuestion.gameMode != "Trivia"){ delete currentQuestion.answer.trivia; } if (difficulty !== 'Basic') { urlData.difficulty = difficulty; } urlData.currentQuestion = currentQuestion; } if (locale) { urlData.locale = locale; } const solidState = encrypt(JSON.stringify(urlData)); const url = solidState; return url; }; const createCanonicalUrl = state => { if (['HOME', 'ENDGAME', 'AWAIT_SCREEN'].indexOf(state.gameStatus) !== -1) { return ''; } let { gameModes, continents, gameStatus, currentQuestion } = state; if (['INGAME', 'INFO', 'LEARN'].indexOf(state.gameStatus) === -1) { currentQuestion = null; } if (gameStatus === 'INFO') { delete currentQuestion.answers; delete currentQuestion.gameMode; } const solidState = encrypt( JSON.stringify({ gameModes, continents, gameStatus, currentQuestion, }), ); const url = solidState; return url; }; const createGameUrl = state => { const { gameModes, continents, gameStatus, difficulty, myRoomId } = state; if (gameStatus === 'INFO') { delete currentQuestion.answers; delete currentQuestion.gameMode; } const solidState = encrypt( JSON.stringify({ gameModes, continents, gameStatus, difficulty, myRoomId, }), ); const url = solidState; return url; }; function removeFromArray(array, element) { const index = array.indexOf(element); array.splice(index, 1); } let timerLength = 30; let socket = null; let mapboxgl = null; let map = null; let referrer = null; class Index extends Component { static async getInitialProps({ query }) { let { solidState } = query; solidState = solidState && solidState.length > 12 ? JSON.parse(decrypt(solidState)) : false; let { startPoint = 0, gameModes = [allGameModes[0].toString()], gameStatus = 'HOME', continents = allContinents, difficulty = allDifficulties[0], currentQuestion = null, questionNum = 0, pageTitle = 'Countries of the World Game. Offline mode, Flags, borders, populations, trivia and maps', myRoomId = null, multiPlayerMaster = false, testMode = false, locale = false, // default false for english } = solidState; if (gameStatus === 'INFO') { questionNum = 0; } return { startPoint, gameModes, gameStatus: gameStatus === 'START_SCREEN' || currentQuestion || startPoint ? gameStatus : gameStatus === 'INGAME' && startPoint === 0 ? 'START_SCREEN' : 'HOME', continents, currentQuestion: startPoint === 1 && currentQuestion === null ? getFreshQuestion( data, continents, gameModes, difficulty, [], 0, null, locale, ) : currentQuestion, difficulty, questionNum: questionNum == -1 ? -1 : questionNum ? 1 : 0, pageTitle, myRoomId, multiPlayerMaster, testMode, locale, }; } constructor(props) { super(props); const { startPoint, gameModes, gameStatus, continents, difficulty, currentQuestion, questionNum, pageTitle, myRoomId, testMode, multiPlayerMaster, locale, } = this.props; this.state = { locale, startPoint, score: 0, questionNum, myData: {}, gameModes, gameStatus, continents, myData: [], difficulty, clientSide: false, gameHistory: { wrong: [], right: [] }, weakList: [], currentQuestion, menuOpen: false, selectedTheme, backgroundColor: '#000', myRoomId, inRoom: false, timerActive: false, awaitTimer: 0, rightWrongMessage: null, toastMessage: null, myName: null, testMode, currentUrl: null, multiGameData: { currentQuestionAnswerCount: 0, currentQuestionAnswerWrongCount: 0, readyCount: 0, playerCount: 1, finalScores: [], active: false, }, multiPlayerMaster: multiPlayerMaster ? multiPlayerMaster : myRoomId === null, pageTitle: generatePageTitle( questionNum, gameStatus, gameModes, continents, currentQuestion, ), }; this.onUnload = this.onUnload.bind(this); // if you need to bind callback to this } setMyName = myName => { this.setState({ myName }, () => { setMyName(myName); }); }; getMyName = myName => { this.setState({ myName: getMyName() }); }; displayBasicNotification = message => { if (Notification.permission !== 'granted') Notification.requestPermission(); else { var notification = new Notification('Challenger accepted!', { body: message, icon: '/static/images/icon.png', vibrate: [100, 50, 100], }); notification.onclick = function() { parent.focus(); window.focus(); //just in case, older browsers this.close(); }; } }; subscribeForPushNotification = async registration => { const that = this; if ( typeof Notification !== 'undefined' && Notification.permission === 'granted' ) { const subscribeOptions = { userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array( 'BL4B8s-4H7hoNQt_CIawMJD29p4JSpocdg_L_d91X7gG6Tjf13WghXaT0fZbQoylD8wwOhIIs25MrpED2SO_mpI', ), }; return registration.pushManager .subscribe(subscribeOptions) .then(function(pushSubscription) { that.sendSubscriptionToBackEnd(pushSubscription); ReactGA.pageview('activate subscription notification'); return; }); } else { } }; sendSubscriptionToBackEnd = async subscription => { return await fetch('/save-subscription/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ subscription: subscription, data: this.state.myData, }), }); }; registerServiceWorker = async () => { if (typeof navigator.serviceWorker !== 'undefined') { const that = this; navigator.serviceWorker .register('/service-worker.js', { scope: '/' }) .then( function(reg) { var serviceWorker; if (reg.installing) { serviceWorker = reg.installing; } else if (reg.waiting) { serviceWorker = reg.waiting; } else if (reg.active) { serviceWorker = reg.active; } if (serviceWorker) { if (serviceWorker.state == 'activated') { //If push subscription wasnt done yet have to do here that.subscribeForPushNotification(reg); } serviceWorker.addEventListener('statechange', function(e) { if (e.target.state == 'activated') { //reg.showNotification(title, options); // use pushManger for subscribing here. that.subscribeForPushNotification(reg); } }); } }, function(err) { //console.error("unsuccessful registration with ", workerFileName, err); }, ); } }; askPermission = async () => { const that = this; if (typeof Notification !== 'undefined') { return new Promise(function(resolve, reject) { const permissionResult = Notification.requestPermission(function( result, ) { resolve(result); }); if (permissionResult) { permissionResult.then(resolve, reject); } }).then(function(permissionResult) { if (permissionResult !== 'granted') { //console.log("no permission this time"); } else { that.registerServiceWorker(); } }); } ReactGA.pageview('ask subscription notification permission'); return false; }; goBack = () => { var x = document.referrer; if ( ['INGAME', 'INFO', 'LEARN', 'ENDGAME'].indexOf(this.state.gameStatus) > -1 ) { confirm('Do you want to return to the homepage?') ? this.goHome() : null; } else if (this.state.gameStatus === 'HOME') { confirm('Do you want to leave this site?') ? (window.location = document.referrer.length ? document.referrer : 'https://google.com') : null; } }; becomeMaster = () => { this.setState({ multiPlayerMaster: true }); }; joinGame = myRoomId => { if (this.state.myRoomId !== null && this.state.inRoom === true) { this.leaveRoom(this.state.myRoomId); } if (myRoomId === null) { myRoomId = makeid(); } socket = null; this.initSocket(); const that = this; socket.emit('joinRoom', myRoomId); that.setState({ inRoom: true, }); socket.emit( 'action', { myRoomId: this.state.myRoomId, myName: this.state.myName }, 'playerJoined', ); this.trackGA('JOIN_ROOM'); this.forceUpdate(); }; leaveRoom = myRoomId => { if (this.state.inRoom) { this.setState({ inRoom: false, }); if (socket !== null) { socket.emit('leaveRoom', myRoomId); if (this.state.multiPlayerMaster) { //TODO pass master baton on to next user instead socket.emit( 'action', { myRoomId: this.state.myRoomId, myName: this.state.myName }, 'masterLeft', ); } else { socket.emit( 'action', { myRoomId: this.state.myRoomId, myName: this.state.myName }, 'playerLeft', ); } } this.trackGA('LEAVE_ROOM'); } }; componentWillUnmount() { window.removeEventListener('beforeunload', this.onUnload); if (this.state.myRoomId) { this.leaveRoom(this.state.myRoomId); } } initSocket = () => { socket = io.connect( process.env.NODE_ENV !== 'production' ? 'http://localhost:3001' : 'https://geogee.me', { path: '/socks/socks/socks/', //transports: ['websocket', 'polling'], }, ); socket.on('action', (playerName, action) => { if (action === 'playerJoined') { let multiGameData = this.state.multiGameData; multiGameData.playerCount++; multiGameData.active = true; this.setState({ multiGameData }); socket.emit('gameData', this.state.myRoomId, multiGameData); this.displayBasicNotification('challenger has joined game'); } if (action === 'masterLeft') { if (this.state.multiPlayerMaster === false) { this.openToaster(`Host has left the game`); this.leaveRoom(this.state.myRoomId); let multiGameData = this.state.multiGameData; multiGameData.playerCount = 1; this.setState({ multiGameData }, () => { this.goHome(); }); } } if (action === 'playerLeft') { let multiGameData = this.state.multiGameData; multiGameData.playerCount--; multiGameData.active = multiGameData.playerCount > 1; this.setState({ multiGameData }, () => { //TODO can this cause a race condition socket.emit('gameData', this.state.myRoomId, multiGameData); if (multiGameData.playerCount <= 1) { this.leaveRoom(this.state.myRoomId); this.openToaster('All other players have left the game'); this.goHome(); } else { if (playerName) { this.openToaster(playerName + ' has left the game'); } else { this.openToaster('A player has left the game'); } } }); } if (action === 'readyToPlay') { let multiGameData = this.state.multiGameData; multiGameData.readyCount++; multiGameData.active = true; this.setState({ multiGameData }); //TODO can this cause a race condition socket.emit('gameData', this.state.myRoomId, multiGameData); if (multiGameData.readyCount < multiGameData.playerCount) { this.openToaster( [ `${playerName ? playerName + ' is ready to play! ' : ''}`, `${multiGameData.readyCount} out of ${multiGameData.playerCount} players are waiting!`, ], 1300, ); } } if (action === 'endGame' && this.state.gameStatus !== 'ENDGAME') { this.endGame(); } this.forceUpdate(); }); socket.on('gameData', multiGameData => { this.setState({ multiGameData }); this.forceUpdate(); }); socket.on('finalScore', (playerName, score) => { let multiGameData = this.state.multiGameData; multiGameData.finalScores.push({ name: playerName, score: score }); this.setState({ multiGameData }, () => { if (multiGameData.finalScores.length >= multiGameData.playerCount - 1) { multiGameData.finalScores.push({ name: this.state.myName, score: this.state.score, }); multiGameData.finalScores.sort(function(a, b) { return b.score - a.score; }); let messages = []; let winners = []; let result = 'Draw'; let topScore = 0; messages.push('____'); messages.push('Scores:'); messages.push('--'); for (let i = 0; i < multiGameData.finalScores.length; i++) { const name = multiGameData.finalScores[i].name; const score = multiGameData.finalScores[i].score; messages.push(name + ': ' + score); if (score === topScore) { winners.push(name); } else if (score > topScore) { winners = [name]; topScore = score; } } if (winners.length === 1 && winners[0] === this.state.myName) { result = 'Win'; messages.unshift('You Won! Congrats!'); } else if ( winners.length > 1 && winners.indexOf(this.state.myName) != -1 ) { messages.unshift( 'You drew with ' + winners.join(', ').replace(/,([^,]*)$/, ' and$1'), ); result = 'Draw'; } else { result = 'Lose'; messages.unshift('You Lost'); } this.openToaster(messages, 12000); } }); }); socket.on('setQuestion', (qTime, currentQuestion) => { let multiGameData = this.state.multiGameData; multiGameData.currentQuestionAnswerCount = 0; multiGameData.currentQuestionAnswerWrongCount = 0; this.setState({ multiGameData }, () => { socket.emit('gameData', this.state.myRoomId, multiGameData); this.refreshQuestion(currentQuestion, qTime); }); this.forceUpdate(); }); socket.on('questionAnswered', (playerName, correct) => { let multiGameData = this.state.multiGameData; multiGameData.currentQuestionAnswerCount++; this.setState({ multiGameData }, () => { if (correct) { this.setState({ rightWrongMessage: playerName + ' answered correctly', }); this.answerQuestion(false, false, true); } else { multiGameData.currentQuestionAnswerWrongCount++; this.openToaster(playerName + ' got it wrong!', 1000); if ( this.state.multiPlayerMaster && multiGameData.currentQuestionAnswerWrongCount >= multiGameData.playerCount && this.state.currentQuestion && this.state.currentQuestion.answer && this.state.currentQuestion.answer.result == 'wrong' ) { this.refreshQuestion(); } } }); this.forceUpdate(); }); }; onUnload(event) { this.leaveRoom(this.state.myRoomId); } getSTime = async () => { const f = await fetch('/time/', { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); const ret = await f.json(); return ret.success; }; getS = async () => { return await this.getSTime(); }; componentDidMount() { this.getMyName(); window.addEventListener('beforeunload', this.onUnload); if (this.state.myRoomId) { this.joinGame(this.state.myRoomId); } referrer = window.referrer; window.addEventListener('popstate', () => this.goBack()); const { gameStatus, currentQuestion } = this.state; let myData = getMyData(); myData = populateMyData(data, myData); this.setState( { pageTitle: generatePageTitle( this.state.questionNum, this.state.gameStatus, this.state.gameModes, this.state.continents, this.state.currentQuestion, this.state.startPoint, ), startPoint: 0, myData, clientSide: true, myRoomId: this.state.myRoomId !== null ? this.state.myRoomId : makeid(), }, () => { if (this.state.selectedTheme) { this.showMap(this.state.gameStatus, this.state.currentQuestion); } this.initAnalytics(); this.registerServiceWorker(); }, ); } initAnalytics = () => { ReactGA.initialize( process.env.NODE_ENV === 'production' ? 'UA-126838170-1' : 'UA-00000000', { debug: process.env.NODE_ENV !== 'production' ? false : false, }, ); ReactGA.pageview(window.location.pathname); ReactGA.event({ category: 'Nav', action: 'Mount', label: this.state.gameStatus, }); }; trackGA = pageView => { ReactGA.pageview(pageView); }; initMap = () => { mapboxgl = require('mapbox-gl/dist/mapbox-gl.js'); mapboxgl.accessToken = 'pk.eyJ1Ijoid2hhdGV2ZXIiLCJhIjoiY2l0MjVyMDE5MHNiejMwcXB1N3pjdzJ0eSJ9.9WWbR0M7icSR2915gks5kQ'; }; showMap = gameStatus => { document.getElementById('body').style.backgroundColor = Themes[this.state.selectedTheme].color; if (this.state.selectedTheme) { //mapboxgl = null; //map =null; if (mapboxgl == null) { this.initMap(); } if (map) { map.setStyle(Themes[this.state.selectedTheme].url); } else { map = new mapboxgl.Map({ container: 'map', center: gameStatus === 'INFO' ? this.state.currentQuestion.answer.lnglat : [0, 0], animate: true, minZoom: 5, interactive: false, fadeDuration: 1100, style: Themes[this.state.selectedTheme].url, }); } } else { map.remove(); map.stop(); map = null; } }; changeDifficulty = difficulty => { this.setState({ difficulty }); }; changeTheme = selectedTheme => { this.setState({ selectedTheme }, () => this.showMap()); }; setLng = locale => { this.setState({ locale }); }; toggleGameMode = mode => { let gameModes = this.state.gameModes; if (gameModes.indexOf(mode) > -1) { removeFromArray(gameModes, mode); } else { gameModes.push(mode); } this.setState({ gameModes }); }; toggleContinent = cont => { let continents = this.state.continents; if (continents.indexOf(cont) > -1) { removeFromArray(continents, cont); } else { continents.push(cont); } this.setState({ continents }); }; componentDidUpdate(prevProps, prevState) { if ( this.state.gameModes !== prevState.gameModes || this.state.continents !== prevState.continents || this.state.gameStatus !== prevState.gameStatus || this.state.difficulty !== prevState.difficulty || this.state.currentQuestion !== prevState.currentQuestion ) { this.updateUrl(); } updateLocalStorage(this.state.myData); ReactGA.pageview(window.location.pathname); } updateUrl = () => { if (['HOME', 'ENDGAME'].indexOf(this.state.gameStatus) == -1) { // Current URL is "/" const currentUrl = createUrl(this.state); this.setState({ currentUrl }); window.history.pushState('', '', currentUrl); } else { this.setState({ currentUrl: 'https://geogee.me' }); window.history.pushState('', '', '/'); } }; getInfo = answer => { return info[0][answer.alpha2Code] ? info[0][answer.alpha2Code].info : 'Sorry, no information right now on ' + answer.name; }; goHome = (message = null) => { if (this.state.inRoom && this.state.multiGameData.playerCount > 1) { if (confirm('Are you sure you want to leave this game?')) { this.leaveRoom(this.state.myRoomId); } else { return false; } } this.setState( { multiGameData: { currentQuestionAnswerCount: 0, currentQuestionAnswerWrongCount: 0, readyCount: 0, playerCount: 1, finalScores: [], active: false, }, score: 0, questionNum: 0, multiPlayerMaster: true, currentQuestion: null, gameStatus: 'HOME', message, myRoomId: makeid(), }, () => { this.scrollToTop(); ReactGA.event({ category: 'Nav', action: 'GO_HOME', label: this.state.gameStatus, }); }, ); }; startNewGame = () => { this.setState( { weakList: [], shouldAskPermission: typeof Notification !== 'undefined' && ['granted', 'denied'].indexOf(Notification.permission) === -1, gameHistory: { right: [], wrong: [] }, score: 0, gameStatus: 'START_SCREEN', pageTitle: generateBasicTitle( this.state.gameModes, this.state.continents, ), questionNum: 0, myRoomId: this.state.myRoomId !== null ? this.state.myRoomId : makeid(), multiGameData: { currentQuestionAnswerCount: 0, currentQuestionAnswerWrongCount: 0, finalScores: [], readyCount: this.state.multiGameData.readyCount, playerCount: this.state.multiGameData.playerCount, active: this.state.multiGameData.active, }, }, () => { ReactGA.event({ category: 'Nav', action: 'START_NEW_GAME', label: this.state.gameStatus, }); }, ); }; startQuestions = () => { this.setState( { multiGameData: { currentQuestionAnswerCount: 0, currentQuestionAnswerWrongCount: 0, finalScores: [], readyCount: this.state.multiGameData.readyCount, playerCount: this.state.multiGameData.playerCount, active: this.state.multiGameData.active, }, }, () => { if (this.state.multiGameData.active) { this.trackGA('MULTIPLAYER_GAME_BEGIN'); socket.emit( 'gameData', this.state.myRoomId, this.state.multiGameData, ); } else { this.trackGA('SINGLEPLAYER_GAME_BEGIN'); } this.refreshQuestion(); ReactGA.event({ category: 'Nav', action: 'BEGIN_QUESTIONS', label: this.state.gameStatus, }); }, ); }; endGame = () => { if (this.state.gameStatus === 'ENDGAME') { return false; } let { gameHistory, weakList } = this.state; if (gameHistory.wrong.length > 0 && !this.state.multiGameData.active) { const currentQuestion = gameHistory.wrong.shift(); weakList.unshift(currentQuestion.answer.name); this.setState( { weakList, currentQuestion, gameHistory, gameStatus: 'LEARN', pageTitle: generatePageTitle( 99, 'LEARN', this.state.gameModes, this.state.continents, currentQuestion, ), }, () => {}, ); } else { this.setState( { weakList, gameStatus: 'ENDGAME', pageTitle: generatePageTitle( 99, 'ENDGAME', this.state.gameModes, this.state.continents, this.state.currentQuestion, ), multiGameData: { currentQuestionAnswerCount: 0, currentQuestionAnswerWrongCount: 0, finalScores: this.state.multiGameData.finalScores, readyCount: 0, playerCount: this.state.multiGameData.playerCount, active: this.state.multiGameData.active, }, }, () => { if (this.state.multiGameData.active) { socket.emit( 'gameStatus', this.state.myRoomId, this.state.multiGameData, ); socket.emit('finalScore', { myName: this.state.myName, myRoomId: this.state.myRoomId, score: this.state.score, }); socket.emit( 'action', { myRoomId: this.state.myRoomId, myName: this.state.myName }, 'endGame', ); } ReactGA.event({ category: 'Nav', action: 'END_GAME', }); }, ); if (this.state.multiGameData.active === true) { this.trackGA('MULTIPLAYER_GAME_END'); } else { this.trackGA('SINGLEPLAYER_GAME_END'); } } }; refreshQuestion = async (currentQuestion = null, qTime = null) => { const shouldEmit = this.state.multiGameData.active === true && currentQuestion === null; if (this.state.questionNum >= TOTAL_QUESTIONS) { this.endGame(); return false; } const { gameModes, continents, difficulty, gameHistory } = this.state; if ( !gameModes || gameModes.length == 0 || !continents || continents.length == 0 ) { alert('Please select a game mode and continent to begin'); this.openMenu(); } else { if (currentQuestion === null) { currentQuestion = getFreshQuestion( data, continents, gameModes, difficulty, gameHistory, 0, null, this.state.locale, ); } if (currentQuestion && currentQuestion.message) this.goHome(currentQuestion); else { let multiGameData = this.state.multiGameData; multiGameData.currentQuestionAnswerCount = 0; multiGameData.currentQuestionAnswerWrongCount = 0; this.setState( { currentQuestion, questionNum: this.state.questionNum + 1, pageTitle: generatePageTitle( this.state.questionNum, 'INGAME', this.state.gameModes, this.state.continents, currentQuestion, ), multiGameData, timerActive: this.state.multiGameData.active, gameStatus: this.state.multiGameData.active ? 'AWAIT_SCREEN' : 'INGAME', rightWrongMessage: null, }, () => { this.scrollToTop(); ReactGA.event({ category: 'Nav', action: 'NEW_QUESTION', label: this.state.gameStatus, }); }, ); } } if (qTime === null) { let timeN = await this.getSTime(); qTime = timeN + 5000; } if (shouldEmit) { socket.emit( 'setQuestion', { myRoomId: this.state.myRoomId, qTime: qTime }, currentQuestion, ); } if (this.state.multiGameData.active) { this.displayDelay(qTime); } }; displayDelay = async qTime => { let timeN = await this.getSTime(); this.setState({ awaitTimer: Math.ceil((qTime - timeN) / 1000) }); let delay = 1000 - (timeN % 1000); this.displayDelayTimeout(delay, qTime, timeN); }; displayDelayTimeout = (delay, qTime, timeN) => { let that = this; setTimeout(function() { timeN += delay; delay = 1000; if (Math.ceil((qTime - timeN) / 1000) < that.state.awaitTimer) { that.setState({ awaitTimer: Math.ceil((qTime - timeN) / 1000) }); } const dt = new Date(); if (timeN >= qTime) { if (that.state.multiGameData.active) { that.setState({ gameStatus: 'INGAME' }); if (that.state.timerActive) { that.runTimer(timerLength); } } } else { that.displayDelayTimeout(delay, qTime, timeN); } }, delay); }; runTimer = timerLength => { const that = this; let timeleft = timerLength; let questionTimer = setInterval(function() { timeleft--; if ( !that.state.currentQuestion || that.state.currentQuestion.answer.result || that.state.gameStatus !== 'INGAME' ) { that.setState({ timerActive: false }); clearInterval(questionTimer); } if ( that.state.gameStatus == 'INGAME' && timeleft <= 0 && that.state.multiGameData.active ) { that.setState({ timerActive: false, rightWrongMessage: 'Too slow!' }); that.answerQuestion(false, true, true); clearInterval(questionTimer); timeleft = timerLength; } }, 1000); }; answerQuestion = (correct, timeUp = false, dontEmit = false) => { let myData = this.state.myData; let score = this.state.score; let { currentQuestion, gameHistory, gameStatus } = this.state; if (!currentQuestion.answer.result) { if (this.state.multiGameData.active && dontEmit == false) { socket.emit( 'questionAnswered', { myRoomId: this.state.myRoomId, myName: this.state.myName }, correct, ); } const q = JSON.parse(JSON.stringify(currentQuestion)); if (!correct) { currentQuestion.answer.result = 'wrong'; if (q.answer.result) { delete q.answer.result; } gameHistory.wrong.push(q); } else { currentQuestion.answer.result = 'correct'; gameHistory.right.push(q.answer.alpha2Code); if (this.state.selectedTheme && map) { map.jumpTo({ center: currentQuestion.answer.lnglat }); const elements = document.getElementsByClassName( 'mapboxgl-control-container', ); while (elements.length > 0) elements[0].remove(); } } if (!myData[q.gameMode]) { myData[q.gameMode] = []; } if (!myData[q.gameMode][q.answer.alpha2Code]) { myData[q.gameMode][q.answer.alpha2Code] = { score: 0, continent: getCountryByAlpha2Code(data, q.answer.alpha2Code) .continent, }; } myData = updateMyDay(correct); if (correct && gameStatus == 'INGAME') { score++; try { myData[q.gameMode][q.answer.alpha2Code].score += 1; myData[q.gameMode][q.answer.alpha2Code].date = Date.now() / 1000; } catch (e) {} } else if (!correct) { try { myData[q.gameMode][q.answer.alpha2Code].score -= 1; } catch (e) {} } this.setState( { gameHistory, currentQuestion, myData, score, }, () => this.scrollToTop(), ); const { gameModes, continents } = this.state; const that = this; if (!this.state.multiGameData.active && correct) { setTimeout(function() { if (currentQuestion.answer.result) { delete currentQuestion.answer.result; } that.setState({ gameStatus: 'INFO', pageTitle: generatePageTitle( 99, 'INFO', gameModes, continents, currentQuestion, ), }); }, 2000); } else { if ( !this.state.multiGameData.active || (this.state.multiGameData.active && this.state.multiPlayerMaster && timeUp) || (this.state.multiGameData.active && correct === true) || (this.state.multiGameData.currentQuestionAnswerWrongCount >= this.state.multiGameData.playerCount - 1 && this.state.currentQuestion && this.state.currentQuestion.answer && this.state.currentQuestion.answer.result == 'wrong') ) { setTimeout(function() { if (currentQuestion.answer.result) { delete currentQuestion.answer.result; } if (that.state.questionNum) { that.refreshQuestion(); } else { that.goHome(); } }, 2000); } } } ReactGA.pageview( (correct ? 'CORRECT_ANSWER' : 'WRONG_ANSWER') + ',DIF=' + this.state.difficulty + ',GAME_MODE=' + this.state.currentQuestion.gameMode + ',ANSWER=' + this.state.currentQuestion.answer.alpha2Code, ); }; setOptions = (op, event) => { event.preventDefault(); this.setState( { startPoint: 1, gameModes: op.gameModes.slice(0), continents: op.continents.slice(0), }, () => this.startNewGame(), ); }; closeMessage = () => { this.setState({ message: null }); }; closeToast = () => { this.setState({ toastMessage: null }); }; openToaster = (message, duration = 7000) => { this.setState({ toastMessage: message }); const that = this; setTimeout(function() { that.setState({ toastMessage: null }); }, duration); }; openMenu = () => { this.setState({ openMenu: true }, () => { this.scrollToTop(); ReactGA.pageview('OpenMenu'); }); }; closeMenu = beginNewGame => { this.setState({ openMenu: false }, () => { beginNewGame && this.startNewGame(); !beginNewGame && ReactGA.pageview('CloseMenu'); }); }; scrollToTop = () => { window.scrollTo(0, 0); }; render() { const { score, gameModes, difficulty, continents, myData, message, clientSide, gameStatus, gameHistory, shouldAskPermission, currentQuestion, myRoomId, openMenu, pageTitle, questionNum, selectedTheme, weakList, timerActive, rightWrongMessage, multiGameData, multiPlayerMaster, myName, toastMessage, testMode, locale, } = this.state; const infoLink = createStaticUrl({ gameModes, continents, currentQuestion, gameStatus: 'INFO', questionNum, }); const nextQuestionLink = createStaticUrl({ gameModes, continents, currentQuestion: getFreshQuestion( data, continents, gameModes, difficulty, gameHistory, 0, null, this.state.locale, ), gameStatus: 'INGAME', questionNum: 1, startPoint: 1, }); return ( <div> <Head> <link rel="manifest" href="/manifest.json" /> <meta name="theme-color" content="#440000" /> <link rel="canonical" href={'https://geogee.me/' + createCanonicalUrl(this.state)} /> <meta name="msvalidate.01" content="6DCFD5719854ED2FC6236496B3CBEA22" /> <meta name="google-site-verification" content="mvWZvVgzpoUJN9J1PLJOAaB6D776CBtCipw6iGy73bg" /> <link rel="icon" type="image/png" href="/static/favicon.png" /> <meta name="description" content={`Geogee! Countries of the world game. ${ pageTitle ? pageTitle : this.props.pageTitle ? this.props.pageTitle : '' }. Multiplayer and single player.`} /> <title> {pageTitle ? pageTitle : this.props.pageTitle ? this.props.pageTitle : 'te'} </title> </Head> <CommonSprite /> {currentQuestion && currentQuestion.answer && !currentQuestion.answer.result && timerActive && gameStatus == 'INGAME' && <Timer timerLength={timerLength} />} {openMenu && ( <Menu setLng={this.setLng} lng={locale} toggleGameMode={this.toggleGameMode} toggleContinent={this.toggleContinent} changeDifficulty={this.changeDifficulty} changeTheme={this.changeTheme} difficulty={difficulty} gameModes={gameModes} continents={continents} openMenu={this.openMenu} selectedTheme={selectedTheme} closeMenu={this.closeMenu} /> )} <Wrapper selectedTheme={selectedTheme}> {toastMessage !== null && ( <Portal> <Toast message={toastMessage} closeToast={this.closeToast} /> </Portal> )} {this.state.gameStatus !== 'START_SCREEN' && !this.state.multiGameData.active && ( <Header openMenu={this.openMenu} /> )} <SubHeader lng={locale} totalQuestions={TOTAL_QUESTIONS} gameStatus={gameStatus} questionNum={questionNum} currentQuestion={currentQuestion} /> <SitemapLink href="/sitemap/sitemap">Sitemap</SitemapLink> <MainWrapper gameStatus={gameStatus}> <Score gameStatus={gameStatus} score={score} /> <Score score={score} /> {gameStatus !== 'HOME' && ( <> <noscript> <NoScriptHomeLink href="/">home</NoScriptHomeLink> </noscript> <HomeButton onClick={() => this.goHome()}> <Icon iconName={'home'} /> </HomeButton> </> )} {message && message.message && message.message.length > 0 && ( <Warning message={message.message} type={message.type} closeMessage={this.closeMessage} /> )} {gameStatus === 'HOME' && ( <HomeScreen lng={locale} askPermission={this.askPermission} clientSide={clientSide} setOptions={this.setOptions} myData={myData} /> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Flags' && ( <> <FlagGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} countries={currentQuestion.answers} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> <FlagSprite /> </> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Populations' && ( <> <PopulationsGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} countries={currentQuestion.answers} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> <FlagSprite /> </> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Maps' && ( <> <MapGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} countries={currentQuestion.answers} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> <MapSprite /> </> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Trivia' && ( <TriviaGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} countries={currentQuestion.answers} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Capitals' && ( <> <CapitalsGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} cities={currentQuestion.answers} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> <FlagSprite /> </> )} {currentQuestion && currentQuestion.answers && ['INGAME', 'LEARN'].indexOf(gameStatus) > -1 && currentQuestion.gameMode && currentQuestion.gameMode === 'Borders' && ( <BordersGame lng={locale} rightWrongMessage={rightWrongMessage} answer={currentQuestion.answer} ansFunc={this.answerQuestion} countries={currentQuestion.answers} questionCountry={currentQuestion.questionCountry} score={score} maxScore={TOTAL_QUESTIONS} infoLink={infoLink} nextQuestionLink={nextQuestionLink} /> )} {currentQuestion && currentQuestion.answer && gameStatus === 'INFO' && ( <> <CountryInfo lng={locale} country={currentQuestion.answer} clickAction={ questionNum != 0 ? () => this.refreshQuestion() : this.goHome } countryInfo={this.getInfo(currentQuestion.answer)} nextQuestionLink={nextQuestionLink} /> <FlagSprite /> </> )} {gameStatus === 'ENDGAME' && ( <EndGame lng={locale} startNewGame={this.startNewGame} goHome={this.goHome} gameHistory={gameHistory} weakList={weakList} score={score} totalQuestions={TOTAL_QUESTIONS} shouldAskPermission={shouldAskPermission} askPermission={this.askPermission} nextQuestionLink={nextQuestionLink} hideMessages={multiGameData.active} /> )} {gameStatus === 'AWAIT_SCREEN' && ( <CountDown count={this.state.awaitTimer} /> )} {gameStatus === 'START_SCREEN' && ( <> <StartScreen lng={locale} testMode={testMode} trackGA={this.trackGA} becomeMaster={this.becomeMaster} myName={myName} setMyName={this.setMyName} multiPlayerMaster={multiPlayerMaster} socket={socket} myRoomId={myRoomId} joinGame={this.joinGame} pageTitle={generateBasicTitle( this.state.gameModes, this.state.continents, )} gameUrl={createGameUrl(this.state)} myRoomId={myRoomId} startQuestions={this.startQuestions} nextQuestionLink={nextQuestionLink} multiGameData={multiGameData} openToaster={this.openToaster} /> <FlagSprite /> <MapSprite /> </> )} {['START_SCREEN', 'HOME', 'ENDGAME'].indexOf(gameStatus) !== -1 && ( <center><br/><StatsLink href="/statistics/all/" target="_blank">Stats</StatsLink></center> )} </MainWrapper> <StyledMap id="map" selectedTheme={selectedTheme} opacity={ gameStatus === 'INFO' || (currentQuestion && currentQuestion.answer && currentQuestion.answer.result === 'correct') ? '1' : '.6' } /> </Wrapper> </div> ); } } export default Index;
docs/app/Examples/elements/Header/Variations/index.js
koenvg/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const HeaderVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Dividing' description='A header can be formatted to divide itself from the content below it.' examplePath='elements/Header/Variations/HeaderExampleDividing' /> <ComponentExample title='Block' description='A header can be formatted to appear inside a content block.' examplePath='elements/Header/Variations/HeaderExampleBlock' /> <ComponentExample title='Attached' description='A header can be attached to other content, like a segment.' examplePath='elements/Header/Variations/HeaderExampleAttached' /> <ComponentExample title='Floating' description='A header can sit to the left or right of other content.' examplePath='elements/Header/Variations/HeaderExampleFloating' /> <ComponentExample title='Text Alignment' description='A header can have its text aligned to a side.' examplePath='elements/Header/Variations/HeaderExampleTextAlignment' /> <ComponentExample title='Colored' description='A header can be formatted with different colors.' examplePath='elements/Header/Variations/HeaderExampleColored' /> <ComponentExample title='Inverted' description='A header can have its colors inverted for contrast.' examplePath='elements/Header/Variations/HeaderExampleInverted' > <Message warning> Inverted headers use modified light versions of the site color scheme. </Message> </ComponentExample> </ExampleSection> ) export default HeaderVariationsExamples
src/svg-icons/alert/warning.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertWarning = (props) => ( <SvgIcon {...props}> <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/> </SvgIcon> ); AlertWarning = pure(AlertWarning); AlertWarning.displayName = 'AlertWarning'; export default AlertWarning;
examples/todos/src/components/TodoList.js
DreamAndDead/redux-copier
import React from 'react' import PropTypes from 'prop-types' import Todo from './Todo' const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ) TodoList.propTypes = { todos: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired }).isRequired).isRequired, onTodoClick: PropTypes.func.isRequired } export default TodoList
fields/types/number/NumberFilter.js
dvdcastro/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { FormField, FormInput, FormRow, FormSelect } from 'elemental'; const MODE_OPTIONS = [ { label: 'Exactly', value: 'equals' }, { label: 'Greater Than', value: 'gt' }, { label: 'Less Than', value: 'lt' }, { label: 'Between', value: 'between' }, ]; function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, value: '', }; } var NumberFilter = React.createClass({ statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, componentDidMount () { // focus the text input findDOMNode(this.refs.focusTarget).focus(); }, handleChangeBuilder (type) { const self = this; return function handleChange (e) { const { filter, onChange } = self.props; switch (type) { case 'minValue': onChange({ mode: filter.mode, value: { min: e.target.value, max: filter.value.max, }, }); break; case 'maxValue': onChange({ mode: filter.mode, value: { min: filter.value.min, max: e.target.value, }, }); break; case 'value': onChange({ mode: filter.mode, value: e.target.value, }); } }; }, // Update the props with this.props.onChange updateFilter (changedProp) { this.props.onChange({ ...this.props.filter, ...changedProp }); }, // Update the filter mode selectMode (mode) { this.updateFilter({ mode }); // focus on next tick setTimeout(() => { findDOMNode(this.refs.focusTarget).focus(); }, 0); }, renderControls (mode) { let controls; const { field } = this.props; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; if (mode.value === 'between') { controls = ( <FormRow> <FormField width="one-half" style={{ marginBottom: 0 }}> <FormInput onChange={this.handleChangeBuilder('minValue')} placeholder="Min." ref="focusTarget" type="number" /> </FormField> <FormField width="one-half" style={{ marginBottom: 0 }}> <FormInput onChange={this.handleChangeBuilder('maxValue')} placeholder="Max." type="number" /> </FormField> </FormRow> ); } else { controls = ( <FormField> <FormInput onChange={this.handleChangeBuilder('value')} placeholder={placeholder} ref="focusTarget" type="number" /> </FormField> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; return ( <div> <FormSelect onChange={this.selectMode} options={MODE_OPTIONS} value={mode.value} /> {this.renderControls(mode)} </div> ); }, }); module.exports = NumberFilter;
client/src/App.js
kaushiksahoo2000/react-apollo-graphql-rethinkdb-starter
import React, { Component } from 'react'; import { BrowserRouter, Link, Route, Switch, } from 'react-router-dom'; import './App.css'; import PeopleList from './components/PeopleList' import NotFound from './components/NotFound'; import { ApolloClient, ApolloProvider, createNetworkInterface, toIdValue, } from 'react-apollo'; import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'; const networkInterface = createNetworkInterface({ uri: 'http://localhost:4000/graphql' }); networkInterface.use([{ applyMiddleware(req, next) { setTimeout(next, 500); }, }]); const wsClient = new SubscriptionClient(`ws://localhost:4000/subscriptions`, { reconnect: true }); const networkInterfaceWithSubscriptions = addGraphQLSubscriptions( networkInterface, wsClient ); const client = new ApolloClient({ networkInterface: networkInterfaceWithSubscriptions, customResolvers: {}, }); class App extends Component { render() { return ( <ApolloProvider client={client}> <BrowserRouter> <div className="App"> <Link to="/" className="navbar">React - GraphQL - Apollo - RethinkDB - Express Starter</Link> <Switch> <Route exact path="/" component={PeopleList}/> <Route component={ NotFound }/> </Switch> </div> </BrowserRouter> </ApolloProvider> ); } } export default App;
docs/app/Examples/collections/Menu/States/MenuExampleDisabled.js
aabustamante/Semantic-UI-React
import React from 'react' import { Menu } from 'semantic-ui-react' const MenuExampleDisabled = () => { return ( <Menu compact> <Menu.Item disabled> Link </Menu.Item> </Menu> ) } export default MenuExampleDisabled
docs/index.js
tiseny/rt-tree
import React from 'react'; import { render } from 'react-dom'; import TreeExample from './src/TreeExample'; import TreeSelectExample from './src/TreeSelectExample'; import '../src/less/rt-select.less' import './app.less' class App extends React.Component { render() { return ( <main className="main"> <section className="section"> <h3>TreeSelect examples.</h3> <TreeSelectExample /> </section> <section className="section"> <h3>Tree examples.</h3> <TreeExample /> </section> </main> ) } } render(<App />, document.getElementById('root'));
src/svg-icons/maps/streetview.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsStreetview = (props) => ( <SvgIcon {...props}> <path d="M12.56 14.33c-.34.27-.56.7-.56 1.17V21h7c1.1 0 2-.9 2-2v-5.98c-.94-.33-1.95-.52-3-.52-2.03 0-3.93.7-5.44 1.83z"/><circle cx="18" cy="6" r="5"/><path d="M11.5 6c0-1.08.27-2.1.74-3H5c-1.1 0-2 .9-2 2v14c0 .55.23 1.05.59 1.41l9.82-9.82C12.23 9.42 11.5 7.8 11.5 6z"/> </SvgIcon> ); MapsStreetview = pure(MapsStreetview); MapsStreetview.displayName = 'MapsStreetview'; MapsStreetview.muiName = 'SvgIcon'; export default MapsStreetview;
app/javascript/mastodon/components/status_content.js
hyuki0000/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { isRtl } from '../rtl'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, '').toLowerCase(); if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) { return; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const directionStyle = { direction: 'ltr' }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, }); if (isRtl(status.get('search_index'))) { directionStyle.direction = 'rtl'; } if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' aria-label={status.get('search_index')} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} /> {' '} <button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden && 0} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} /> </div> ); } else if (this.props.onClick) { return ( <div ref={this.setRef} tabIndex='0' aria-label={status.get('search_index')} className={classNames} style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} dangerouslySetInnerHTML={content} /> ); } else { return ( <div tabIndex='0' aria-label={status.get('search_index')} ref={this.setRef} className='status__content' style={directionStyle} dangerouslySetInnerHTML={content} /> ); } } }
jenkins-design-language/src/js/components/material-ui/svg-icons/notification/phone-locked.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NotificationPhoneLocked = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM20 4v-.5C20 2.12 18.88 1 17.5 1S15 2.12 15 3.5V4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm-.8 0h-3.4v-.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V4z"/> </SvgIcon> ); NotificationPhoneLocked.displayName = 'NotificationPhoneLocked'; NotificationPhoneLocked.muiName = 'SvgIcon'; export default NotificationPhoneLocked;
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js
tsdl2013/actor-platform
import React from 'react'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import GroupStore from 'stores/GroupStore'; import InviteUserActions from 'actions/InviteUserActions'; import AvatarItem from 'components/common/AvatarItem.react'; import InviteUser from 'components/modals/InviteUser.react'; import GroupProfileMembers from 'components/activity/GroupProfileMembers.react'; const getStateFromStores = (groupId) => { const thisPeer = PeerStore.getGroupPeer(groupId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer), integrationToken: GroupStore.getIntegrationToken() }; }; class GroupProfile extends React.Component { static propTypes = { group: React.PropTypes.object.isRequired }; componentWillUnmount() { DialogStore.removeNotificationsListener(this.onChange); GroupStore.addChangeListener(this.onChange); } componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.group.id)); } constructor(props) { super(props); DialogStore.addNotificationsListener(this.onChange); GroupStore.addChangeListener(this.onChange); this.state = getStateFromStores(props.group.id); } onAddMemberClick = group => { InviteUserActions.modalOpen(group); } onLeaveGroupClick = groupId => { DialogActionCreators.leaveGroup(groupId); } onNotificationChange = event => { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); } onChange = () => { this.setState(getStateFromStores(this.props.group.id)); }; render() { const group = this.props.group; const myId = LoginStore.getMyId(); const isNotificationsEnabled = this.state.isNotificationsEnabled; const integrationToken = this.state.integrationToken; let memberArea; let adminControls; if (group.adminId === myId) { adminControls = ( <li className="profile__list__item"> <a className="red">Delete group</a> </li> ); } if (DialogStore.isGroupMember(group)) { memberArea = ( <div> <div className="notifications"> <label htmlFor="notifications">Enable Notifications</label> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange.bind(this)} type="checkbox"/> <label htmlFor="notifications"></label> </div> </div> <GroupProfileMembers groupId={group.id} members={group.members}/> <ul className="profile__list profile__list--controls"> <li className="profile__list__item"> <a className="link__blue" onClick={this.onAddMemberClick.bind(this, group)}>Add member</a> </li> <li className="profile__list__item"> <a className="link__red" onClick={this.onLeaveGroupClick.bind(this, group.id)}>Leave group</a> </li> {adminControls} </ul> <InviteUser/> </div> ); } return ( <div className="activity__body profile"> <div className="profile__name"> <AvatarItem image={group.bigAvatar} placeholder={group.placeholder} size="medium" title={group.name}/> <h3>{group.name}</h3> </div> {memberArea} {integrationToken} </div> ); } } export default GroupProfile;
components/Tabs/stories.js
insane-ux/rebulma
// @flow import React from 'react' import { withState } from 'recompose' import { storiesOf } from '@kadira/storybook' import Tabs from './' const items = [ { icon: 'fa-th-large', label: 'Grid', }, { icon: 'fa-table', label: 'Table', }, { icon: 'fa-list', label: 'List', }, ] const MyTabs = withState('selected', 'select', 0)( ({ className, selected, select, }: { className?: string, selected: number, select: (selected: number) => void, }) => ( <Tabs className={className} selected={selected} select={select} items={items} /> ), ) storiesOf('Tabs', module) .add('default', () => ( <div> <div className="heading">Default</div> <MyTabs /> <div className="heading">Small & center</div> <MyTabs className="is-small is-centered" /> <div className="heading">Toggled</div> <MyTabs className="is-toggle" /> </div> ))
NavBar.js
harish2704/react-native-simple-redux-router
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; /** * NavBar * * NavBar component * Can have any no of childrens also * * @param {Style} style - Style of container View Component * @param {Component} titleComponent - Title Component * @param {String} title - Title String * @param {Object} titleParams - Params passed to title Text Component * @param {Component} navLeft - NavLeft Component * @param {Object} navLeftIcon - eg: { name: 'chevron-back', size:30, color: '#FFFFFF' } passed to Icon Component of 'react-native-vector-icons/MaterialIcons' * @param {Function} onNavLeftPress - Handler for Navleft press. * @returns {undefined} */ export default class NavBar extends Component { renderTitle(){ let props = this.props; if( props.titleComponent ){ return props.titleComponent; } return ( <Text style={styles.navTitle} containerStyle={ styles.titleContainer} {...props.titleParams} >{ props.title }</Text> ) } renderLeftSide(){ let props = this.props; if( props.navLeft ){ return props.navLeft; } if( props.navLeftIcon ){ return ( <Icon {...props.navLeftIcon} /> ) } return ( <Icon onPress={props.onNavLeftPress} name="navigate-before" size={45} color="#FFFFFF" style={styles.navLeft} /> ) } renderBody(){ return [ this.renderLeftSide(), this.renderTitle(), ...(this.props.children || []) ].map((v, i) => { return <View key={'rnsrr-navbarItem-' + i} style={[styles.item, v.props.containerStyle]} >{v}</View> }); } render(){ let props = this.props; return ( <View style={ [ styles.navBar, props.style ] }> {this.renderBody()} </View> ); } } const styles = StyleSheet.create({ navBar: { flexDirection: 'row', justifyContent: 'space-between', alignSelf: 'stretch', alignItems: 'center', backgroundColor: '#ED1C26', height: 48, }, navTitle: { color: '#FFFFFF', fontWeight: '500', fontSize: 17, alignSelf: 'center', }, titleContainer:{ // borderStyle: 'solid', borderWidth: 2, borderColor: '#009900', alignSelf: 'stretch', flexDirection: 'column', justifyContent: 'center', flex: 1, }, item:{ padding: 2, alignSelf: 'center', } });
packages/material-ui-icons/src/Settings.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Settings = props => <SvgIcon {...props}> <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" /> </SvgIcon>; Settings = pure(Settings); Settings.muiName = 'SvgIcon'; export default Settings;
src/progress-bar/index.js
aruberto/react-foundation-components
import PropTypes from 'prop-types'; import React from 'react'; import cx from 'classnames'; import cxBinder from 'classnames/bind'; import includes from 'lodash/includes'; import { COMPONENT_COLORS } from '../util/constants'; import styles from './_styles.scss'; const cxStyles = cxBinder.bind(styles); export const ProgressBar = ({ className, color, labelFormatter, max, meterClassName, meterStyle, meterTextClassName, meterTextStyle, min, value, ...restProps, }) => { const classNames = cx(className, cxStyles('progress', { [color]: includes(COMPONENT_COLORS, color) })); const meterClassNames = cx(meterClassName, cxStyles('progress-meter')); const boundedValue = Math.min(Math.max(min, value), max); const percent = (boundedValue - min) / (max - min); const width = Math.round((percent * 100) * 1000) / 1000; let label = null; if (labelFormatter) { const meterTextClassNames = cx(meterTextClassName, cxStyles('progress-meter-text')); label = ( <span className={meterTextClassNames} style={meterTextStyle}> {labelFormatter(percent, boundedValue, min, max)} </span> ); } return ( <div {...restProps} aria-valuemax={max} aria-valuemin={min} aria-valuenow={boundedValue} aria-valuetext={label} className={classNames} role="progressbar" > <span className={meterClassNames} style={{ ...meterStyle, width: `${width}%` }}> {label} </span> </div> ); }; ProgressBar.propTypes = { className: PropTypes.string, color: PropTypes.oneOf(COMPONENT_COLORS), labelFormatter: PropTypes.func, max: PropTypes.number, meterClassName: PropTypes.string, meterStyle: PropTypes.object, meterTextClassName: PropTypes.string, meterTextStyle: PropTypes.object, min: PropTypes.number, value: PropTypes.number, }; ProgressBar.defaultProps = { max: 100, min: 0, value: 0, }; export default ProgressBar;
src/ListItem/ListItem.js
react-fabric/react-fabric
import React from 'react' import elementType from 'react-prop-types/lib/elementType' import cx from 'classnames' import isFunction from 'lodash.isfunction' import ListItemAction from './ListItemAction.js' import fabricComponent from '../fabricComponent' import style from './ListItem.scss' const handleSelectionTargetClick = (onChange, checked) => ( isFunction(onChange) ? onChange.bind(null, !checked) : undefined ) const ListItem = ({ checked, children, componentClass: Component, image, itemIcon, metaText, onChange, primaryText, secondaryText, selectable, tertiaryText, type, ...props }) => ( <Component data-fabric="ListItem" {...props} styleName={cx('ms-ListItem', { [`ms-ListItem--${type}`]: !!type, 'is-selectable': selectable, 'is-selected': !!checked })}> { image && <div styleName="ms-ListItem-image">{ image }</div> } { primaryText && <span styleName="ms-ListItem-primaryText">{ primaryText }</span> } { secondaryText && <span styleName="ms-ListItem-secondaryText">{ secondaryText }</span> } { tertiaryText && <span styleName="ms-ListItem-tertiaryText">{ tertiaryText }</span> } { metaText && <span styleName="ms-ListItem-metaText">{ metaText }</span> } { itemIcon && <div styleName="ms-ListItem-itemIcon">{ itemIcon }</div> } { selectable && <div styleName="ms-ListItem-selectionTarget" onClick={handleSelectionTargetClick(onChange, checked)} /> } { children && React.Children.count(children) > 0 && <div styleName="ms-ListItem-actions"> { children } </div> } </Component> ) ListItem.displayName = 'ListItem' ListItem.propTypes = { children: React.PropTypes.node, // TODO Array of ListItemActions // children: React.PropTypes.oneOfType([ // React.PropTypes.instanceOf(ListItemAction), // React.PropTypes.arrayOf(React.PropTypes.instanceOf(ListItemAction)) // ]), componentClass: elementType, image: React.PropTypes.node, itemIcon: React.PropTypes.node, metaText: React.PropTypes.node, onChange: React.PropTypes.func, primaryText: React.PropTypes.node, secondaryText: React.PropTypes.node, selectable: React.PropTypes.bool, checked: React.PropTypes.bool, tertiaryText: React.PropTypes.node, type: React.PropTypes.oneOf([ 'document' ]) } ListItem.defaultProps = { componentClass: 'li' } ListItem.Action = ListItemAction export default fabricComponent(ListItem, style)