path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/components/KalturaPlayer.js
nchathu2014/canvas_react
import React from 'react'; var href=null; var KalturaPlayer = React.createClass({ propTypes:{ player_id:React.PropTypes.string.isRequired, wid:React.PropTypes.string.isRequired, uiconf_id:React.PropTypes.string.isRequired, entry_id:React.PropTypes.string.isRequired }, getIntialState:function(){ return{ kPlayer:"off" } }, componentWillMount:function() { href="http://www.kaltura.com/p/"+this.props.wid+"/sp/"+this.props.wid+"00/embedIframeJs/uiconf_id/"+this.props.uiconf_id+"/partner_id/"+this.props.wid+"?iframeembed=true&playerId="+this.props.player_id+"&entry_id="+this.props.entry_id; }, render:function(){ return( <div id="kalturaWrapper" ref="kp"> <iframe src={href} width={this.props.pl_width} height={this.props.pl_height} allowFullScreen webkitallowfullscreen mozAllowFullScreen frameBorder="0"></iframe> </div> ); }, componentDidMount:function(){ this.setState({ kPlayer:"on" }); } }); export default KalturaPlayer
src/svg-icons/device/add-alarm.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAddAlarm = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/> </SvgIcon> ); DeviceAddAlarm = pure(DeviceAddAlarm); DeviceAddAlarm.displayName = 'DeviceAddAlarm'; DeviceAddAlarm.muiName = 'SvgIcon'; export default DeviceAddAlarm;
src/components/common/orders/OrderSummary.js
ESTEBANMURUZABAL/my-ecommerce-template
/** * Imports */ import React from 'react'; import {FormattedMessage, FormattedNumber} from 'react-intl'; // Flux import IntlStore from '../../../stores/Application/IntlStore'; // Required components import Breakpoint from '../../core/Breakpoint'; import Text from '../../common/typography/Text'; // Translation data for this component import intlData from './OrderSummary.intl'; /** * Component */ class OrderSummary extends React.Component { static contextTypes = { getStore: React.PropTypes.func.isRequired }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./OrderSummary.scss'); } //*** Template ***// render() { let intlStore = this.context.getStore(IntlStore); // Process Subtotal let subTotal = {value: 0, currency: undefined}; let total = {value: 0, currency: undefined}; let anilladoProduct = false; if (this.props.checkout.cart && this.props.checkout.cart.products.length > 0) { this.props.checkout.cart.products.forEach(function (product) { if (!subTotal.currency) { subTotal.currency = product.details.pricing.currency; } if (product.details.copies && product.details.tags.indexOf('fotocopias') !== -1) { if (product.details.copies.anillado) { subTotal.value += product.details.copies.price * product.quantity; subTotal.value += 35; anilladoProduct = true; } else if (product.details.copies) { subTotal.value += product.details.copies.price * product.quantity; } } else { subTotal.value += product.details.pricing.retail * product.quantity; } }); } let anilladoDiv = () => { if (anilladoProduct) { return ( <div key={5} className="order-summary__row order-summary__item"> <div className="order-summary__list-name"> <Breakpoint point="handhelds"> <Text size="small"> {intlStore.getMessage(intlData, 'anillado')} </Text> </Breakpoint> <Breakpoint point="medium-screens"> <Text> {intlStore.getMessage(intlData, 'anillado')} </Text> </Breakpoint> <Breakpoint point="wide-screens"> <Text> {intlStore.getMessage(intlData, 'anillado')} </Text> </Breakpoint> </div> <div className="order-summary__list-quantity-price"> <Text>{1}</Text> &nbsp;x&nbsp; <Text> <FormattedNumber value={35} style="currency" currency="ARS" /> </Text> </div> <div className="order-summary__list-total"> <Text> <FormattedNumber value={35} style="currency" currency="ARS" /> </Text> </div> </div> ); } }; return ( <div className="order-summary"> <div className="order-summary__list"> <div className="order-summary__row order-summary__item-labels"> <div className="order-summary__list-name"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(intlData, 'name')} locales={intlStore.getCurrentLocale()} /> </Text> </div> <div className="order-summary__list-quantity-price"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(intlData, 'quantityAndPrice')} locales={intlStore.getCurrentLocale()} /> </Text> </div> <div className="order-summary__list-total"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(intlData, 'total')} locales={intlStore.getCurrentLocale()} /> </Text> </div> </div> {this.props.checkout.cart.products.map(function (product, idx) { return ( <div> { product.details.copies.price ? <div> <div key={idx} className="order-summary__row order-summary__item"> <div className="order-summary__list-name"> <Breakpoint point="handhelds"> <Text size="small"> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> <Breakpoint point="medium-screens"> <Text> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> <Breakpoint point="wide-screens"> <Text> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> </div> <div className="order-summary__list-quantity-price"> <Text> {product.quantity} </Text> &nbsp;x&nbsp; <Text> <FormattedNumber value={product.details.copies.price} style="currency" currency={product.details.pricing.currency} /> </Text> </div> <div className="order-summary__list-total"> <Text> <FormattedNumber value={product.quantity * product.details.copies.price} style="currency" currency={product.details.pricing.currency} /> </Text> </div> </div> {anilladoDiv()} </div> : <div> <div key={idx} className="order-summary__row order-summary__item"> <div className="order-summary__list-name"> <Breakpoint point="handhelds"> <Text size="small"> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> <Breakpoint point="medium-screens"> <Text> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> <Breakpoint point="wide-screens"> <Text> {intlStore.getMessage(product.details.name)} </Text> </Breakpoint> </div> <div className="order-summary__list-quantity-price"> <Text> {product.quantity} </Text> &nbsp;x&nbsp; <Text> <FormattedNumber value={product.details.pricing.retail} style="currency" currency={product.details.pricing.currency} /> </Text> </div> <div className="order-summary__list-total"> <Text> <FormattedNumber value={product.quantity * product.details.pricing.retail} style="currency" currency={product.details.pricing.currency} /> </Text> </div> </div> </div> } </div> ); })} </div> <div className="order-summary__totals"> <div className="order-summary__row"> <div className="order-summary__totals-label"> <Text> <FormattedMessage message={intlStore.getMessage(intlData, 'subTotal')} locales={intlStore.getCurrentLocale()} /> </Text> </div> <div className="order-summary__totals-value"> <Text> <FormattedNumber value={subTotal.value} style="currency" currency={subTotal.currency} /> </Text> </div> </div> <div className="order-summary__row"> <div className="order-summary__totals-label"> <Text> <FormattedMessage message={intlStore.getMessage(intlData, 'shipping')} locales={intlStore.getCurrentLocale()} /> </Text> </div> <div className="order-summary__totals-value"> {this.props.checkout.hasOwnProperty('shippingCost') ? <Text> <FormattedNumber value={this.props.checkout.shippingCost} style="currency" currency={this.props.checkout.currency} /> </Text> : <Text>-</Text> } </div> </div> <div className="order-summary__row"> <div className="order-summary__totals-label"> <Text weight="bold"> <FormattedMessage message={intlStore.getMessage(intlData, 'total')} locales={intlStore.getCurrentLocale()} /> </Text> </div> <div className="order-summary__totals-value"> {this.props.checkout.hasOwnProperty('shippingCost') ? <Text weight="bold"> <FormattedNumber value={subTotal.value + this.props.checkout.shippingCost} style="currency" currency={this.props.checkout.currency} /> </Text> : <Text weight="bold"> <FormattedNumber value={subTotal.value} style="currency" currency={this.props.checkout.currency} /> </Text> } </div> </div> </div> </div> ); } } /** * Exports */ export default OrderSummary;
cerberus-dashboard/src/components/ApiError/ApiError.js
Nike-Inc/cerberus-management-service
/* * 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 * as cmsUtils from '../../utils/cmsUtils' import './ApiError.scss' /** * A component to use to make API messages sent to the messenger look pretty and be html and stylable * * @prop message The Message for this app to provide context to the user for what action failed * @prop response The Axios response */ export default class ApiError extends Component { static propTypes = { message: PropTypes.string.isRequired, response: PropTypes.object.isRequired } render() { const {message, response} = this.props return ( <div className="api-error-wrapper"> <div className="api-error-header">An API error has occurred</div> <div className="api-error-message">{message}</div> <div className="api-error-server-provided-details"> <div className="status-wrapper"> <div className="api-error-server-status-label">Server Status:</div> <div className="api-error-server-status">{response.status}, {response.statusText}</div> </div> <div className="server-message-wrapper"> <div className="api-error-server-message-label">Server Message:</div> <div className="api-error-server-message">{cmsUtils.parseCMSError(response)}</div> </div> </div> </div> ) } }
components/Home/Features.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import { NavLink } from 'fluxible-router'; import {FormattedMessage, defineMessages} from 'react-intl'; import setDocumentTitle from '../../actions/setDocumentTitle'; class features extends React.Component { componentDidMount() { this.context.executeAction(setDocumentTitle, { title: this.context.intl.formatMessage({ id: 'features.title', defaultMessage: 'Discover More' }) }); } render() { return ( <div className="ui container" ref="features"> <div className="ui hidden divider"></div> <h1 className="ui header" id="main"><FormattedMessage id="features.header" defaultMessage="Discover SlideWiki"/></h1> <div className="basic container"> <p> <FormattedMessage id="features.p1" defaultMessage="The goal of SlideWiki is to revolutionise how educational materials can be authored, shared and reused. By enabling authors and students to create and share slide decks as HTML in an open platform, communities around the world can benefit from materials created by world-leading educators on a wide range of topics."/> </p> </div> <div className="ui padded stackable grid"> <div className="eight wide column"> <div className="ui attached message"> <h2 className="header"><FormattedMessage id="features.1.header" defaultMessage="Create online slide decks"/></h2> </div> <div className="ui attached fluid segment"> <div className="ui medium right floated image"> <FormattedMessage id="features.screenshot" defaultMessage="screenshot of slide editor interface."> { (alt) => <img alt={alt} src="assets/images/features/slide-edit.png"></img> } </FormattedMessage> </div> <p> <FormattedMessage id="features.1.p1" defaultMessage="Create a new deck or import existing slides from PowerPoint (*.pptx) or OpenDocument Presentation (*.odp) files. Your imported slides will be converted into HTML to allow you to continue to edit and add new content."/> </p> <p> <FormattedMessage id="features.1.p2" defaultMessage="The SlideWiki editor offers many formatting tools, including being able to add images, videos, equations and code snippet."/> </p> </div> </div> <div className="eight wide column"> <div className="ui attached message"> <h2 className="header"><FormattedMessage id="features.2.header" defaultMessage="Reusable educational content"/></h2> </div> <div className="ui attached fluid segment"> <p> <FormattedMessage id="features.2.p1" values={{ navLink: <NavLink href="/licence"><FormattedMessage id="features.2.p1.licence" defaultMessage="Creative Commons licences"/></NavLink> }} defaultMessage="SlideWiki is built on the Open Educational Resources (OER) ethos and all content is published under {navLink}. This means you can reuse and repurpose content from SlideWiki decks. SlideWiki allows you to create your own slides based on decks that have been published on SlideWiki by:" /> </p> <div className="ui relaxed list"> <div className="item"> <i className="large fork blue middle aligned icon"></i> <div className="content"> <div className="header"><FormattedMessage id="features.2.deckCopy.header" defaultMessage="Creating a copy of a deck"/></div> <div className="description"><FormattedMessage id="features.2.deckCopy.description" defaultMessage="Use the Fork feature to create your own copy of an existing deck."/></div> </div> </div> <div className="item"> <i className="large attach blue middle aligned icon " ></i> <div className="content"> <div className="header"><FormattedMessage id="features.2.appending.header" defaultMessage="Appending slides and decks to your deck"/></div> <div className="description"><FormattedMessage id="features.2.appending.description" defaultMessage="Add slides from other decks using the Append feature. Or Append a deck to embed a set of slides as a sub-deck."/></div> </div> </div> <div className="item"> <i className="large blue translate middle aligned icon"></i> <div className="content"> <div className="header"><FormattedMessage id="features.2.translating.header" defaultMessage="Translating a deck (coming soon)"/></div> <div className="description"><FormattedMessage id="features.2.translating.description" defaultMessage="Localise slides and decks by translating it into another language."/></div> </div> </div> </div> </div> </div> <div className="eight wide column"> <div className="ui attached message"> <h2 className="header"><FormattedMessage id="features.3.header" defaultMessage="Collaborative content authoring"/></h2> </div> <div className="ui attached fluid segment"> <p> <FormattedMessage id="features.3.p1" defaultMessage="SlideWiki allows authors and students to collaborate. Through managing editing rights, you can enable colleagues to edit and add to your decks.Comments and Questions (coming soon) allow students and readers to interact with your decks."/> </p> <div className="ui relaxed list"> <div className="item"> <i className="large blue users middle aligned icon"></i> <div className="content"> <div className="header"><FormattedMessage id="features.3.collaborate.header" defaultMessage="Collaborate to improve your decks"/></div> <div className="description"><FormattedMessage id="features.3.collaborate.description" defaultMessage="Use Groups to allow colleagues, peers and associates to collaborate with editing and enhancing your deck."/></div> </div> </div> <div className="item"> <i className="large exchange blue middle aligned icon"></i> <div className="content"> <div className="header"><FormattedMessage id="features.3.review.header" defaultMessage="Review and revert changes within slides and decks"/></div> <div className="description"><FormattedMessage id="features.3.review.description" defaultMessage="A sophisticated revisioning model enables you and your co-editors to review and revert changes to slides and decks."/></div> </div> </div> <div className="item"> <i className="large thumbs up blue middle aligned icon " ></i> <div className="content"> <div className="header"><FormattedMessage id="features.3.like.header" defaultMessage="Like decks and slides"/></div> <div className="description"><FormattedMessage id="features.3.like.description" defaultMessage="Encourage authors and students to see new content by liking useful decks and slides."/></div> </div> </div> <div className="item"> <i className="large circle blue play middle aligned icon"></i> <div className="content"> <div className="header"><FormattedMessage id="features.3.slideshow.header" defaultMessage="Slideshow mode"/></div> <div className="description"><FormattedMessage id="features.3.slideshow.description" defaultMessage="Use the Slideshow mode to view a deck as a slideshow. Includes a timer and speaker notes view."/></div> </div> </div> </div> </div> </div> <div className="eight wide column"> <div className="ui attached message"> <h2 className="header"><FormattedMessage id="features.4.header" defaultMessage="Supporting Knowledge Communities"/></h2> </div> <div className="ui attached fluid segment"> <p> <FormattedMessage id="features.4.description" defaultMessage="Through a range of interactive and open tools, SlideWiki aims to nurture knowledge communities around the world. Our goal is to significantly increase content available to a world-wide audience. By involve peer-educators in improving and maintaining the quality and attractiveness of your e-learning content SlideWiki can give you a platform to support knowledge communities. With SlideWiki we aim to dramatically improve the efficiency and effectiveness of the collaborative creation of rich learning material for online and offline use."/> </p> <div className="ui horizontal attached fluid segments"> <div className="ui center aligned segment"> <i className="large blue share alternate icon"></i> </div> <div className="ui center aligned segment"> <i className="large blue comment outline icon"></i> </div> <div className="ui center aligned segment"> <i className="large blue download icon"></i> </div> </div> <div className="ui list"> <div className="item"> <div className="content"> <FormattedMessage id="features.4.shareDecks" values={{ strong: <strong><FormattedMessage id="features.4.shareDescks.strong" defaultMessage="Share decks"/></strong> }} defaultMessage="{strong} via social media or email." /> </div> </div> <div className="item"> <div className="content"> <FormattedMessage id="features.4.comments" values={{ strong: <strong><FormattedMessage id="features.4.comments.strong" defaultMessage="Comments"/></strong> }} defaultMessage="Add {strong} to decks and slides to interact with other learners."/> </div> </div> <div className="item"> <div className="content"> <FormattedMessage id="features.4.download" values={{ strong: <strong><FormattedMessage id="features.4.download.strong" defaultMessage="Download"/></strong> }} defaultMessage="{strong} decks in PDF, ePub or SCORM format."/> </div> </div> </div> </div> </div> </div> <div className="ui message"> <FormattedMessage id="features.4.findMore" values={{ link: <a href="https://stable.slidewiki.org/deck/10467" target="_blank"><FormattedMessage id="features.4.findMore.link" defaultMessage="help file deck"/></a> }} defaultMessage="To find out more about how to use SlideWiki and its many features, view our {link}." /> </div> </div> ); } } features.contextTypes = { intl: PropTypes.object.isRequired, executeAction: PropTypes.func.isRequired }; export default features;
frontend/app_v2/src/common/icons/Audio.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' /** * @summary Audio * @component * * @param {object} props * * @returns {node} jsx markup */ function Audio({ styling }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}> <path d="M0 0h24v24H0z" fill="none" /> <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" /> </svg> ) } // PROPTYPES const { string } = PropTypes Audio.propTypes = { styling: string, } export default Audio
node_modules/semantic-ui-react/dist/es/views/Comment/CommentAction.js
SuperUncleCat/ServerMonitoring
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly } from '../../lib'; /** * A comment can contain an action. */ function CommentAction(props) { var active = props.active, className = props.className, children = props.children; var classes = cx(useKeyOnly(active, 'active'), className); var rest = getUnhandledProps(CommentAction, props); var ElementType = getElementType(CommentAction, props); return React.createElement( ElementType, _extends({}, rest, { className: classes }), children ); } CommentAction.handledProps = ['active', 'as', 'children', 'className']; CommentAction._meta = { name: 'CommentAction', parent: 'Comment', type: META.TYPES.VIEW }; CommentAction.defaultProps = { as: 'a' }; CommentAction.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Style as the currently active action. */ active: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string } : {}; export default CommentAction;
docs/src/pages/demos/lists/FolderList.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import List, { ListItem, ListItemText } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; import FolderIcon from 'material-ui-icons/Folder'; const styles = theme => ({ root: { width: '100%', maxWidth: 360, background: theme.palette.background.paper, }, }); function FolderList(props) { const classes = props.classes; return ( <div className={classes.root}> <List> <ListItem button> <Avatar> <FolderIcon /> </Avatar> <ListItemText primary="Photos" secondary="Jan 9, 2016" /> </ListItem> <ListItem button> <Avatar> <FolderIcon /> </Avatar> <ListItemText primary="Work" secondary="Jan 7, 2016" /> </ListItem> </List> </div> ); } FolderList.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(FolderList);
src/svg-icons/editor/bubble-chart.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBubbleChart = (props) => ( <SvgIcon {...props}> <circle cx="7.2" cy="14.4" r="3.2"/><circle cx="14.8" cy="18" r="2"/><circle cx="15.2" cy="8.8" r="4.8"/> </SvgIcon> ); EditorBubbleChart = pure(EditorBubbleChart); EditorBubbleChart.displayName = 'EditorBubbleChart'; EditorBubbleChart.muiName = 'SvgIcon'; export default EditorBubbleChart;
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1197.js
guardicore/monkey
import React from 'react'; import ReactTable from 'react-table'; import {renderMachine} from './Helpers' import MitigationsComponent from './MitigationsComponent'; class T1210 extends React.Component { constructor(props) { super(props); this.columns = [{ Header: 'Machine', id: 'machine', accessor: x => renderMachine(x), style: {'whiteSpace': 'unset'}, width: 200 }, { Header: 'Time', id: 'time', accessor: x => x.time, style: {'whiteSpace': 'unset'}, width: 170 }, { Header: 'Usage', id: 'usage', accessor: x => x.usage, style: {'whiteSpace': 'unset'} } ] } renderExploitedMachines() { if (this.props.data.bits_jobs.length === 0) { return (<div/>) } else { return (<ReactTable columns={this.columns} data={this.props.data.bits_jobs} showPagination={false} defaultPageSize={this.props.data.bits_jobs.length} />) } } render() { return ( <div className="data-table-container"> <div> <div>{this.props.data.message_html}</div> {this.props.data.bits_jobs.length > 0 ? <div>BITS jobs were used in these machines: </div> : ''} </div> <br/> {this.renderExploitedMachines()} <MitigationsComponent mitigations={this.props.data.mitigations}/> </div> ); } } export default T1210;
docs/src/HomePage.js
Sipree/react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageFooter from './PageFooter'; import Grid from '../../src/Grid'; import Alert from '../../src/Alert'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; export default class HomePage extends React.Component { render() { return ( <div> <NavMain activePage="home" /> <main className="bs-docs-masthead" id="content" role="main"> <div className="container"> <span className="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline"></span> <p className="lead">The most popular front-end framework, rebuilt for React.</p> </div> </main> <Grid> <Alert bsStyle="warning"> <p><Glyphicon glyph="bullhorn" /> We are actively working to reach a 1.0.0 release, and we would love your help to get there.</p> <p><Glyphicon glyph="check" /> Check out the <a href="https://github.com/react-bootstrap/react-bootstrap/wiki#100-roadmap">1.0.0 roadmap</a> and <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md">contributing guidelines</a> to see where you can help out.</p> <p><Glyphicon glyph="sunglasses" /> A great place to start is any <a target="_blank" href="https://github.com/react-bootstrap/react-bootstrap/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22">issue</a> with a <Label bsStyle="success">help-wanted</Label> label.</p> <p><Glyphicon glyph="ok" /> We are open to pull requests that address bugs, improve documentation, enhance accessibility, add test coverage, or bring us closer to feature parity with <a target="_blank" href="http://getbootstrap.com/">Bootstrap</a>.</p> <p><Glyphicon glyph="user" /> We actively seek to invite frequent pull request authors to join the organization. <Glyphicon glyph="thumbs-up" /></p> </Alert> <Alert bsStyle="danger"> <p><Glyphicon glyph="warning-sign" /> The project is under active development, and APIs will change. </p> <p><Glyphicon glyph="bullhorn" /> Prior to the 1.0.0 release, breaking changes should result in a minor version bump.</p> </Alert> </Grid> <PageFooter /> </div> ); } }
fields/types/name/NameField.js
davibe/keystone
import Field from '../Field'; import React from 'react'; import { FormField, FormInput, FormRow } from 'elemental'; module.exports = Field.create({ displayName: 'NameField', focusTargetRef: 'first', valueChanged: function(which, event) { this.props.value[which] = event.target.value; this.props.onChange({ path: this.props.path, value: this.props.value }); }, renderValue () { return ( <FormRow> <FormField width="one-half"> <FormInput noedit style={{ width: '100%' }}>{this.props.value.first}</FormInput> </FormField> <FormField width="one-half"> <FormInput noedit style={{ width: '100%' }}>{this.props.value.last}</FormInput> </FormField> </FormRow> ); }, renderField () { return ( <FormRow> <FormField width="one-half"> <FormInput name={this.props.paths.first} placeholder="First name" ref="first" value={this.props.value.first} onChange={this.valueChanged.bind(this, 'first')} autoComplete="off" /> </FormField> <FormField width="one-half"> <FormInput name={this.props.paths.last} placeholder="Last name" ref="last" value={this.props.value.last} onChange={this.valueChanged.bind(this, 'last')} autoComplete="off" /> </FormField> </FormRow> ); } });
examples/using-inferno/pages/about.js
kevmannn/next.js
import React from 'react' export default () => ( <div>About us</div> )
packages/cf-component-icon/src/reactsvgs/Upload.js
jroyal/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; const Upload = ({ className, label }) => ( <svg className={className} aria-label={label} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" > <path d="M13.636,7.344a2.128,2.128,0,0,0-3.28-2.588A4.246,4.246,0,0,0,2.2,6.416c0,.035,0,.069.005.1A3.455,3.455,0,0,0,3.3,13.2V13.2h3.27V10.083H4.476L8.012,6.752l3.536,3.331H9.454V13.2H13.18V13.2a2.957,2.957,0,0,0,.456-5.853Z" /> </svg> ); Upload.propTypes = { className: PropTypes.string.isRequired, label: PropTypes.string.isRequired }; export default Upload;
src/parser/warrior/arms/modules/talents/index.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import StatisticsListBox, { STATISTIC_ORDER } from 'interface/others/StatisticsListBox'; // Talents import AngerManagement from './AngerManagement'; import Skullsplitter from './Skullsplitter'; import SuddenDeath from './SuddenDeath'; import WarMachine from './WarMachine'; import StormBolt from './StormBolt'; import ImpendingVictory from './ImpendingVictory'; import FervorOfBattle from './FervorOfBattle'; import SecondWind from './SecondWind'; import Cleave from './Cleave'; import Warbreaker from './Warbreaker'; import Avatar from './Avatar'; import Ravager from './Ravager'; // Rend statistics are in '../core/Dots' class TalentStatisticBox extends Analyzer { static dependencies = { skullsplitter: Skullsplitter, suddenDeath: SuddenDeath, warMachine: WarMachine, stormBolt: StormBolt, impendingVictory: ImpendingVictory, fervorOfBattle: FervorOfBattle, secondWind: SecondWind, cleave: Cleave, warbreaker: Warbreaker, avatar: Avatar, angerManagement: AngerManagement, ravager: Ravager, }; constructor(...args) { super(...args); this.active = Object.keys(this.constructor.dependencies) .map(name => this[name].active) .includes(true); } statistic() { return ( <StatisticsListBox title="Talents" position={STATISTIC_ORDER.CORE(2)} tooltip="This provides an overview of the damage contributions of various talents. This isn't meant as a way to 1:1 evaluate talents, as some talents bring other strengths to the table than pure damage." > {Object.keys(this.constructor.dependencies).map(name => { const module = this[name]; if (!module.active) { return null; } return ( <React.Fragment key={name}> {module.subStatistic()} </React.Fragment> ); })} </StatisticsListBox> ); } } export default TalentStatisticBox;
src/components/AccountTitle/AccountTitle.js
expdevelop/d812
import React from 'react' import { Title, Link } from 'components' import { classNames } from 'helpers' import s from './AccountTitle.sass' // TODO: sidebar title integration const AccountTitle = ({ start = 'Для продолжения необходимо', firstLink = {content: 'войти', link: '?account&signin'}, end = 'или', lastLink = {content:'зарегистрироваться.', link: '?account&signup'}, children, className }) => { if (children) { return ( <Title size="5" className={classNames(s.title, s.title_child, className)}> {children} </Title> ) } return ( <Title size="5" className={s.title}> {start} <Link to={firstLink.link} inherit className={s.link}>{firstLink.content}</Link> {end} <Link to={lastLink.link} inherit className={s.link}>{lastLink.content}</Link> </Title> ) }; export default AccountTitle;
src/smif/app/src/index.js
tomalrussell/smif
import '@babel/polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { Route, BrowserRouter as Router, Switch } from 'react-router-dom' import Nav from 'containers/Nav' import Welcome from 'components/Welcome' import NotFound from 'components/ConfigForm/General/NotFound' import JobsOverview from 'containers/Configuration/Overview/JobsOverview' import JobRunner from 'containers/Simulation/JobRunner' import ProjectOverview from 'containers/Configuration/Overview/ProjectOverview' import ModelRunConfig from 'containers/Configuration/Forms/ModelRunConfig' import SosModelConfig from 'containers/Configuration/Forms/SosModelConfig' import SectorModelConfig from 'containers/Configuration/Forms/SectorModelConfig' import ScenarioConfig from 'containers/Configuration/Forms/ScenarioConfig' import store from 'store/store.js' import history from './history' import 'bootstrap/dist/css/bootstrap.min.css' import '../static/css/main.css' import 'rc-slider/assets/index.css' import 'react-table/react-table.css' render( <Provider store={store}> <Router history={history}> <div className="container-fluid"> <div className="row"> <Route path="/" component={Nav}/> <main role="main" className="col-12 col-md-9 col-xl-8 py-3 px-4"> <Switch> <Route exact path="/" component={Welcome}/> <Route exact path="/jobs/:param?" component={JobsOverview}/> <Route exact strict path="/jobs/runner/:name" component={JobRunner}/> <Route exact strict path="/configure/:name" component={ProjectOverview}/> <Route exact strict path="/configure/model-runs/:name" component={ModelRunConfig}/> <Route exact strict path="/configure/sos-models/:name" component={SosModelConfig}/> <Route exact strict path="/configure/sector-models/:name" component={SectorModelConfig}/> <Route exact strict path="/configure/scenarios/:name" component={ScenarioConfig}/> <Route component={NotFound} /> </Switch> </main> </div> </div> </Router> </Provider>, document.getElementById('root') )
docs/src/examples/switchIsGregorian.js
mberneti/react-datepicker2
import React from 'react' import momentJalaali from 'moment-jalaali' import DatePicker from '../../../src/components/DatePicker'; class component extends React.Component { constructor(props) { super(props); this.state = { value: momentJalaali(), isGregorian: true }; } render() { return <div> <DatePicker value={this.state.value} isGregorian={this.state.isGregorian} inputFormat="YYYY-M-D" inputJalaaliFormat="jYYYY-jM-jD" onChange={value => this.setState({ value })} /> <br /> <button onClick={() => this.setState({ isGregorian: !this.state.isGregorian })}> {this.state.isGregorian ? 'switch to jalaali' : 'switch to gregorian'} </button> </div> } } const title = 'Switch IsGregorian'; const code = `class component extends React.Component { constructor(props) { super(props); this.state = { value: momentJalaali(), isGregorian:true }; } render() { return <div> <DatePicker value={this.state.value} isGregorian={this.state.isGregorian} onChange={value => this.setState({ value })} /> <br /> <button onClick={() => this.setState({ isGregorian: !this.state.isGregorian })}> {this.state.isGregorian?'switch to jalaali':'switch to gregorian'} </button> </div> } } `; const SwitchIsGregorian = { component, title, code }; export default SwitchIsGregorian;
src/App/CryptoRoi.js
kgstew/whitesands
import React, { Component } from 'react'; import axios from 'axios'; import './App.css'; class AddTradeForm extends Component { constructor(props) { super(props); this.state = { coinOne: '', coinTwo: '', price: 0, quantity: 0, validEntry: true }; this.changeCoinOne = this.changeCoinOne.bind(this); this.changeCoinTwo = this.changeCoinTwo.bind(this); this.changePrice = this.changePrice.bind(this); this.changeQuantity = this.changeQuantity.bind(this); } changeCoinOne(event) { this.setState({ coinOne: event.target.value.toLowerCase(), }); } changeCoinTwo(event) { this.setState({ coinTwo: event.target.value.toLowerCase(), }); } changePrice(event) { this.setState({ price: event.target.value, }); } changeQuantity(event) { this.setState({ quantity: event.target.value, }); } handleSubmit(event) { if (!this.state.coinOne) { this.setState({validBlockValue: false}); event.preventDefault(); return; } this.props.onSubmit(this.state); this.setState({ coinOne: '', coinTwo: '', price: 0, quantity: 0 }); event.preventDefault(); } render() { return ( <div> <h2>Add New Trade</h2> <form onSubmit={this.handleSubmit}> <label> First Coin <input type="text" value={this.state.coinOne} onChange={this.changeCoinOne} /> </label> <label> Second Coin <input type="text" value={this.state.coinTwo} onChange={this.changeCoinTwo} /> </label> <label> Price <input type="text" value={this.state.price} onChange={this.changePrice} /> </label> <label> Quantity <input type="text" value={this.state.quantity} onChange={this.changeQuantity} /> </label> <br/> <input type="submit" value="Submit" /> </form> <div className="block-value-error"> {this.state.validEntry ? '' : 'You must enter a value'} </div> </div> ) } } class CryptoRoi extends Component { constructor(props) { super(props); this.state = { holdings: [], coinsTracked: [] }; } addTrade(tradeData) { this.setState({holdings: tradeData}) } recordSale(coin1, coin2, sale_price) { console.log("Ca Ching") } componentWillMount() { axios({ method:'get', url:'https://www.bittrex.com/api/v1.1/public/getmarketsummary?market=btc-neo', withCredentials: true // default }).then(res => { console.log(res) }); } render() { return ( <div className="cryptoroi-wrapper"> <h1 className="title">Crypto ROI</h1> <div className="body"> <h2>Add a Trade</h2> <AddTradeForm onSubmit={(value) => this.addTrade(value)}/> </div> </div> ); } } export default CryptoRoi;
actor-apps/app-web/src/app/utils/require-auth.js
alihalabyah/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
src/components/header.js
Andrey11/golfmanager
'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TextInput, View } from 'react-native'; import GiftedSpinner from 'react-native-gifted-spinner'; import IconButton from './iconButton'; export default class header extends Component { render(){ return ( <View style={styles.header}> { this.props.showBackButton ? <IconButton icon={require('../images/ic_arrow_back.png')} onButtonPressed={this.props.onBackButtonPressed}> </IconButton> : null } <View style={styles.header_item}> <Text style={styles.header_text}>{this.props.text}</Text> </View> { this.props.showSettingsButton ? <IconButton icon={require('../images/ic_settings.png')} onButtonPressed={this.props.onSettingsButtonPressed}> </IconButton> : null } </View> ); } } const styles = StyleSheet.create({ header: { paddingTop: 30, height: 70, flexDirection: 'row', justifyContent: 'space-between', backgroundColor: '#DDDDDD', }, header_item: { paddingLeft: 10, paddingRight: 10 }, header_text: { color: '#000', fontSize: 18 } }); AppRegistry.registerComponent('header', () => header);
app/components/Header/index.js
thuantrinh/math_is_hard
import React from 'react'; import './header.css'; import styled from 'styled-components'; const MenuItemsContainer = styled.div` display: block; ` class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function componentWillMount = () => { this.state = { showMenu: false } } toggleMenu = () => { let newState = !this.state.showMenu this.setState({ showMenu: newState }) } render() { const path = window.location.pathname.split('/'); const currentPath = path[path.length-1]; return ( <div> <nav className="navbar navbar-inverse"> <div className="navbar-header"> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false" onClick={this.toggleMenu}> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="/">math-is-hard</a> </div> <MenuItemsContainer className={"collapse navbar-collapse" + (this.state.showMenu? " menu-out" : ' menu-in')} id="menu-items"> <ul className="nav navbar-nav"> <li className={currentPath == ''? 'active': ''}><a href="/">HOME <span className="sr-only">(current)</span></a></li> <li className={currentPath === 'about'? 'active': ''}><a href="/about">ABOUT</a></li> </ul> </MenuItemsContainer> </nav> </div> ); } } export default Header;
src/components/Search/Search.js
ortonomy/flingapp-frontend
import React, { Component } from 'react'; import search from './Search.module.css'; import sidebar from '../Sidebar/Sidebar.module.css'; class Search extends Component { search() { return true; } render() { return ( <div className={search.Search}> <div className={sidebar.sectionTitle}> <i className='fa fa-search'></i> <span>Search</span> </div> <div className={search.box}> <input type="text" onClick={this.search} placeholder="find projects and freelancers" /> </div> </div> ) } } export default Search;
src/Async.js
millerized/react-select
import React from 'react'; import Select from './Select'; import stripDiacritics from './utils/stripDiacritics'; let requestId = 0; function initCache (cache) { if (cache && typeof cache !== 'object') { cache = {}; } return cache ? cache : null; } function updateCache (cache, input, data) { if (!cache) return; cache[input] = data; } function getFromCache (cache, input) { if (!cache) return; for (let i = input.length; i >= 0; --i) { let cacheKey = input.slice(0, i); if (cache[cacheKey] && (input === cacheKey || cache[cacheKey].complete)) { return cache[cacheKey]; } } } function thenPromise (promise, callback) { if (!promise || typeof promise.then !== 'function') return; return promise.then((data) => { callback(null, data); }, (err) => { callback(err); }); } const stringOrNode = React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]); const Async = React.createClass({ propTypes: { cache: React.PropTypes.any, // object to use to cache results, can be null to disable cache ignoreAccents: React.PropTypes.bool, // whether to strip diacritics when filtering (shared with Select) ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering (shared with Select) isLoading: React.PropTypes.bool, // overrides the isLoading state when set to true loadOptions: React.PropTypes.func.isRequired, // function to call to load options asynchronously loadingPlaceholder: React.PropTypes.string, // replaces the placeholder while options are loading minimumInput: React.PropTypes.number, // the minimum number of characters that trigger loadOptions noResultsText: stringOrNode, // placeholder displayed when there are no matching search results (shared with Select) onInputChange: React.PropTypes.func, // onInputChange handler: function (inputValue) {} placeholder: stringOrNode, // field placeholder, displayed when there's no value (shared with Select) searchPromptText: stringOrNode, // label to prompt for search input searchingText: React.PropTypes.string, // message to display while options are loading }, getDefaultProps () { return { cache: true, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', minimumInput: 0, searchingText: 'Searching...', searchPromptText: 'Type to search', }; }, getInitialState () { return { cache: initCache(this.props.cache), isLoading: false, options: [], }; }, componentWillMount () { this._lastInput = ''; }, componentDidMount () { this.loadOptions(''); }, componentWillReceiveProps (nextProps) { if (nextProps.cache !== this.props.cache) { this.setState({ cache: initCache(nextProps.cache), }); } }, focus () { this.refs.select.focus(); }, resetState () { this._currentRequestId = -1; this.setState({ isLoading: false, options: [], }); }, getResponseHandler (input) { let _requestId = this._currentRequestId = requestId++; return (err, data) => { if (err) throw err; if (!this.isMounted()) return; updateCache(this.state.cache, input, data); if (_requestId !== this._currentRequestId) return; this.setState({ isLoading: false, options: data && data.options || [], }); }; }, loadOptions (input) { if (this.props.onInputChange) { let nextState = this.props.onInputChange(input); // Note: != used deliberately here to catch undefined and null if (nextState != null) { input = '' + nextState; } } // if (this.props.ignoreAccents) input = stripDiacritics(input); // if (this.props.ignoreCase) input = input.toLowerCase(); this._lastInput = input; if (input.length < this.props.minimumInput) { return this.resetState(); } let cacheResult = getFromCache(this.state.cache, input); if (cacheResult) { return this.setState({ options: cacheResult.options, }); } this.setState({ isLoading: true, }); let responseHandler = this.getResponseHandler(input); let inputPromise = thenPromise(this.props.loadOptions(input, responseHandler), responseHandler); return inputPromise ? inputPromise.then(() => { return input; }) : input; }, render () { let { noResultsText } = this.props; let { isLoading, options } = this.state; if (this.props.isLoading) isLoading = true; let placeholder = isLoading ? this.props.loadingPlaceholder : this.props.placeholder; if (isLoading) { noResultsText = this.props.searchingText; } else if (!options.length && this._lastInput.length < this.props.minimumInput) { noResultsText = this.props.searchPromptText; } return ( <Select {...this.props} ref="select" isLoading={isLoading} noResultsText={noResultsText} onInputChange={this.loadOptions} options={options} placeholder={placeholder} /> ); } }); module.exports = Async;
react/src/components/dashboard/settings/settings.coindClearDataDirPanel.js
pbca26/EasyDEX-GUI
import React from 'react'; import translate from '../../../translate/translate'; import { apiClearCoindFolder, triggerToaster, } from '../../../actions/actionCreators'; import { coindList } from '../../../util/coinHelper'; import Store from '../../../store'; class CoindClearDataDirPanel extends React.Component { constructor() { super(); this.state = { coin: 'none', keepWalletDat: true, loading: false, displayYesNo: false, }; this.removeCoindData = this.removeCoindData.bind(this); this.updateInput = this.updateInput.bind(this); this.toggleKeepWalletDat = this.toggleKeepWalletDat.bind(this); this.displayYesNo = this.displayYesNo.bind(this); } displayYesNo() { this.setState({ displayYesNo: !this.state.displayYesNo, }); } removeCoindData() { const _coin = this.state.coin; this.setState({ loading: true, displayYesNo: false, }); setTimeout(() => { apiClearCoindFolder( _coin, this.state.keepWalletDat ? this.state.keepWalletDat : null ) .then((res) => { if (res.msg === 'success') { this.setState({ keepWalletDat: true, loading: false, }); Store.dispatch( triggerToaster( `${_coin} ${translate('TOASTR.DATADIR_CLEARED')}`, translate('TOASTR.WALLET_NOTIFICATION'), 'success' ) ); } else { Store.dispatch( triggerToaster( `${translate('TOASTR.DATADIR_UNABLE_TO_CLEAR')} ${_coin}`, translate('TOASTR.WALLET_NOTIFICATION'), 'error' ) ); } }); }, 100); } updateInput(e) { this.setState({ [e.target.name]: e.target.value, }); } toggleKeepWalletDat() { this.setState(Object.assign({}, this.state, { keepWalletDat: !this.state.keepWalletDat, })); } renderCoinListSelectorOptions() { let _items = []; let _nativeCoins = coindList(); _nativeCoins.sort(); _items.push( <option key="coind-clear-data-coins-none" value="none"> { translate('SETTINGS.PICK_A_COIN') } </option> ); for (let i = 0; i < _nativeCoins.length; i++) { if (_nativeCoins[i] !== 'CHIPS') { _items.push( <option key={ `coind-clear-data-coins-${ _nativeCoins[i] }` } value={ `${_nativeCoins[i]}` }> { `${_nativeCoins[i]}` } </option> ); } } return _items; } render() { return ( <div> <div className="row"> <div className="col-sm-12 padding-bottom-10"> <h4 className="col-red"> <i className="fa fa-warning"></i> { translate('SETTINGS.COIND_DATADIR_CLEAR_P1') } <br /> { translate('SETTINGS.COIND_DATADIR_CLEAR_P2') } </h4> <div> <div className="col-sm-4 no-padding-left text-center"> <select autoFocus name="coin" className="form-control form-material margin-top-20 margin-bottom-10" value={ this.state.coin } onChange={ (event) => this.updateInput(event) }> { this.renderCoinListSelectorOptions() } </select> <span className="pointer toggle margin-top-20 block text-left"> <label className="switch"> <input type="checkbox" name="settings-app-debug-toggle" value={ this.state.keepWalletDat } checked={ this.state.keepWalletDat } readOnly /> <div className="slider" onClick={ this.toggleKeepWalletDat }></div> </label> <span className="title" onClick={ this.toggleKeepWalletDat }> { translate('SETTINGS.KEEP') } wallet.dat </span> </span> { !this.state.displayYesNo && <button type="button" className="btn btn-primary waves-effect waves-light margin-top-20" disabled={ this.state.loading || this.state.coin === 'none' } onClick={ this.displayYesNo }> { this.state.loading ? translate('SETTINGS.COIND_DELETING', this.state.coin) : translate('SETTINGS.DELETE') } </button> } { this.state.displayYesNo && <div className="margin-top-20"> { translate('SETTINGS.DATADIR_DELETE_PROMPT', this.state.coin) } </div> } { this.state.displayYesNo && <button type="button" className="btn btn-primary waves-effect waves-light margin-top-20 margin-right-20" onClick={ this.removeCoindData }> { translate('SETTINGS.YES') } </button> } { this.state.displayYesNo && <button type="button" className="btn btn-primary waves-effect waves-light margin-top-20" onClick={ this.displayYesNo }> { translate('SETTINGS.NO') } </button> } </div> </div> </div> </div> </div> ); }; } export default CoindClearDataDirPanel;
src/svg-icons/content/low-priority.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentLowPriority = (props) => ( <SvgIcon {...props}> <path d="M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z"/> </SvgIcon> ); ContentLowPriority = pure(ContentLowPriority); ContentLowPriority.displayName = 'ContentLowPriority'; ContentLowPriority.muiName = 'SvgIcon'; export default ContentLowPriority;
website/src/App.js
admiraldolphin/govhack2017
import React, { Component } from 'react'; import './App.css'; import Data from './Data'; import Navbar from './Navbar'; class App extends Component { constructor(props) { super(props); this.state = { data: [ { "card": { "name": "Towers, John", "traits": [ { "key": "dc_acid", "name": "Acid", "death": true, "people_matching": 1 }, { "key": "le_convict.1840", "name": "Convicted in 1840s", "death": false, "people_matching": 0.2269315673289183 } ], "source": { "name": "Towers, John", "inquest": { "death_date": "31 Dec 1880", "death_verdict": "Natural causes", "death_causes": [ "dc_misc" ], "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1359086/one" }, "birth": {}, "immigration": {}, "convict": { "departure_date": "1 May 1846", "convict_port": "Portsmouth", "convict_ship": "Palmyra", "year": "1846", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1441273/one" }, "bankruptcy": {}, "marriage": {}, "court": {}, "health-welfare": {}, "census": {} } }, "dead": false, "completed_traits": null, "score": 0 }, { "card": { "name": "Donnelly, John", "traits": [ { "key": "dc_misc", "name": "Misc", "death": true, "people_matching": 1 }, { "key": "le_convict.1840", "name": "Convicted in 1840s", "death": false, "people_matching": 0.2269315673289183 }, { "key": "le_marriage.1880", "name": "Married in 1880s", "death": false, "people_matching": 0.09492273730684327 } ], "source": { "name": "Donnelly, John", "inquest": { "death_date": "1 Jul 1907", "death_verdict": "Accidental death", "death_causes": [ "dc_misc" ], "year": "1907", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1355327/one" }, "birth": {}, "immigration": {}, "convict": { "departure_date": "2 May 1842", "convict_port": "Dublin", "convict_ship": "Isabella Watson", "year": "1842", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1387869/one" }, "bankruptcy": {}, "marriage": { "marriage_date": "31 May 1881", "spouse_name": "Kennedy, Mary", "year": "1881", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:890357/one" }, "court": {}, "health-welfare": {}, "census": {} } }, "dead": false, "completed_traits": null, "score": 0 }, { "card": { "name": "Riseley, Edward", "traits": [ { "key": "dc_misc", "name": "Misc", "death": true, "people_matching": 1 }, { "key": "le_birth.1890", "name": "Born in 1890s", "death": false, "people_matching": 0.06181015452538632 } ], "source": { "name": "Riseley, Edward", "inquest": { "death_date": "16 Sep 1908", "death_verdict": "Accidentally killed through a rope breaking whilst he was being hauled from a shaft at Ridgeway", "death_causes": [ "dc_misc" ], "year": "1908", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1355521/one" }, "birth": { "birth_date": "21 Sep 1894", "birth_place": "Geeveston", "birth_mother": "Murrell, Mary Jane", "birth_father": "Riseley, John William", "year": "1894", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1054801/one" }, "immigration": {}, "convict": { "year": "" }, "bankruptcy": {}, "marriage": {}, "court": {}, "health-welfare": {}, "census": {} } }, "dead": false, "completed_traits": null, "score": 0 }, { "card": { "name": "Perrin, Amy Maud", "traits": [ { "key": "dc_misc", "name": "Misc", "death": true, "people_matching": 1 }, { "key": "le_birth.1870", "name": "Born in 1870s", "death": false, "people_matching": 0.06445916114790287 } ], "source": { "name": "Perrin, Amy Maud", "inquest": { "death_date": "6 Jan 1877", "death_verdict": "Accidentally drowned in a tank", "death_causes": [ "dc_misc" ], "year": "1877", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1359565/one" }, "birth": { "birth_date": "23 Feb 1873", "birth_place": "Launceston", "birth_mother": "Wilson, Henrietta Kate", "birth_father": "Perrin, Walter", "year": "1873", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:933883/one" }, "immigration": {}, "convict": { "year": "" }, "bankruptcy": {}, "marriage": {}, "court": {}, "health-welfare": {}, "census": {} } }, "dead": false, "completed_traits": null, "score": 0 }, { "card": { "name": "Lucas, Joseph", "traits": [ { "key": "dc_misc", "name": "Misc", "death": true, "people_matching": 1 }, { "key": "le_convict.1830", "name": "Convicted in 1830s", "death": false, "people_matching": 0.1403973509933775 }, { "key": "le_marriage.1840", "name": "Married in 1840s", "death": false, "people_matching": 0.08079470198675497 } ], "source": { "name": "Lucas, Joseph", "inquest": { "death_date": "12 Feb 1878", "death_verdict": "Chlorodyne overdose", "death_causes": [ "dc_misc" ], "year": "1878", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1359708/one" }, "birth": {}, "immigration": {}, "convict": { "departure_date": "2 Jun 1831", "convict_port": "London", "convict_ship": "William Glen Anderson", "year": "1831", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:1412910/one" }, "bankruptcy": {}, "marriage": { "marriage_date": "26 Aug 1841", "spouse_name": "King, Mary", "year": "1841", "permalink": "https://linctas.ent.sirsidynix.net.au/client/en_AU/all/search/detailnonmodal/ent:$002f$002fNAME_INDEXES$002f0$002fNAME_INDEXES:829446/one" }, "court": {}, "health-welfare": {}, "census": {} } }, "dead": false, "completed_traits": null, "score": 0 } ], focusId: 0 }; } componentDidMount() { this.getData() console.log(this.props.match.params.id) } isCurrentTab(id) { return this.state.focusId === id; } changeTab(id) { this.setState({focusId: id}) } getData() { fetch('http://35.197.178.221/statusz') .then((response) => response.json()) .then((response) => response.players[this.props.match.params.id].hand.people) .then(response => { this.setState({data: response}) } ) .catch(error => console.log(error)) } render() { return ( <div className="App"> <Data data={this.state.data[this.state.focusId].card.source} /> <Navbar data={this.state.data} changeTab={this.changeTab.bind(this)} isCurrent={this.isCurrentTab.bind(this)} /> </div> ); } } export default App;
admin/client/App/components/Navigation/Mobile/ListItem.js
w01fgang/keystone
/** * A list item of the mobile navigation */ import React from 'react'; import { Link } from 'react-router'; const MobileListItem = React.createClass({ displayName: 'MobileListItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, href: React.PropTypes.string.isRequired, onClick: React.PropTypes.func, }, render () { return ( <Link className={this.props.className} to={this.props.href} onClick={this.props.onClick} tabIndex="-1" > {this.props.children} </Link> ); }, }); module.exports = MobileListItem;
components/Header.js
dawnlabs/carbon
import React from 'react' import Logo from './svg/Logo' const Header = ({ enableHeroText }) => ( <header role="banner" className="header mb4"> <div className="header-content"> <a id="link-home" href="/" aria-label="Home"> <Logo /> </a> {enableHeroText ? ( <h2 className="mt3"> Create and share beautiful images of your source code. <br /> Start typing or drop a file into the text area to get started. </h2> ) : null} </div> <style jsx> {` .header { width: 656px; } .header-content { display: flex; flex-direction: column; align-items: center; } .header-content a { height: 64px; } h2 { text-align: center; } `} </style> </header> ) export default Header
packages/react/src/components/atoms/buttons/ButtonSort/index.js
massgov/mayflower
/** * ButtonSort module. * @module @massds/mayflower-react/ButtonSort * @requires module:@massds/mayflower-assets/scss/01-atoms/button-sort */ import React from 'react'; import PropTypes from 'prop-types'; const ButtonSort = (buttonSort) => { const buttonSortClass = buttonSort.direction ? ` ma__button-sort--${buttonSort.direction}` : ''; const classNames = `ma__button-sort js-button-sort${buttonSortClass}`; return( <button type="button" className={classNames}>{buttonSort.text}</button> ); }; ButtonSort.propTypes = { /** The label text of the sort button */ text: PropTypes.string.isRequired, /** An array of sort button objects */ direction: PropTypes.oneOf(['', 'asc', 'dsc']) }; export default ButtonSort;
app/user/dashboard/HomeTab.js
in42/internship-portal
import React from 'react'; import { Card, Container } from 'semantic-ui-react'; import Axios from 'axios'; import PostItem from '../../common/post/PostItem'; import Auth from '../../auth/modules/Auth'; export default class HomeTab extends React.Component { constructor() { super(); this.state = { posts: [] }; this.fetchPosts = () => { Axios.get('/api/user/posts', { headers: { Authorization: `bearer ${Auth.getToken()}`, }, }).then(resp => this.setState({ posts: resp.data })) .catch(console.error); }; } componentWillMount() { this.fetchPosts(); } render() { const postItems = this.state.posts.map(post => ( <PostItem key={post._id} post={post} id={post._id} /> )); return ( <Container text> <Card.Group> {postItems} </Card.Group> </Container> ); } }
components/news/NewsList.js
BDE-ESIEE/mobile
import React, { Component } from 'react'; import { Text, View, ListView, ActivityIndicator, StatusBar, TouchableOpacity, RefreshControl, Button } from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; import moment from 'moment'; import Icon from 'react-native-vector-icons/Ionicons'; import styles from '../styles/news.js'; import NewsCard from './NewsCard'; import { ifIphoneX } from 'react-native-iphone-x-helper' import { Actions } from "react-native-router-flux"; const loadingMessages = [ "Le chien du BDE livre les journaux...", "Ca va toujours plus vite que si t'allais voir le site." ] class NewsList extends Component { constructor (props) { super(props); this.state = { news: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, sectionHeaderHasChanged: (s1, s2) => s1 !== s2 }), page: 1, data: [], fetching: false, refreshing: false, json: {}, loading: true }; } componentWillMount() { this._fetchMore(this.state.page); } _onRefresh() { if (this.state.refreshing) { return; } this.setState({refreshing: true, page: 1}); let promise = this._fetchMore(1); if (!promise) { return; } promise.then(() => this.setState({refreshing: false})); } _fetchMore(page) { if (this.state.fetching) { return; } this.setState({fetching: true}); var rows = []; fetch('https://bde.esiee.fr/api/posts.json?page='+page+'&count=10&_format=json', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then((response) => { response.json().then((json) => { for (var i = 0; i < json.entries.length; i++) { rows.push(json.entries[i]); } new Promise((resolve, reject) => { setTimeout(() => { resolve(rows); }, 3); }) .then((rows) => { var data; if (this.state.refreshing) { data = rows; } else { data = [...this.state.data, ...rows]; } this.setState({ page: page + 1, news: this.state.news.cloneWithRows(data), data: data, fetching: false, loading: false, refreshing: false }); }); }); }); } render () { let loadingElement; let listElement; if (this.state.loading) { let loadingText = loadingMessages[Math.floor(Math.random() * loadingMessages.length)]; loadingElement = ( <View style={styles.loading}> <ActivityIndicator color="#f4373b" size="large" style={styles.loadingIndicator}/> <Text style={styles.loadingText}> {loadingText} </Text> </View> ); } else { listElement = ( <ListView dataSource={this.state.news} renderRow={(post, sectionID, rowID) => <NewsCard post={post} row={rowID} />} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} tintColor={'#f4373b'} /> } onEndReached={() => this._fetchMore(this.state.page)} /> ); } return ( <View style={styles.container}> <StatusBar translucent={true} backgroundColor="rgba(0,0,0,0.2)" barStyle="light-content"/> <View> <LinearGradient start={{x: 0.0, y: 0}} end={{x: 1, y: 1}} colors={['#f4373b', '#f4373b']} style={styles.topBar}> <TouchableOpacity activeOpacity={1}> <Icon name='ios-arrow-dropleft-outline' style={[styles.topBarButton, { opacity: 0.3 }]} /> </TouchableOpacity> <Text style={styles.topBarText}> <Text style={styles.topBarNormalText}>News</Text> </Text> <TouchableOpacity onPress={() => Actions.events()}> <Icon name='ios-arrow-dropright-outline' style={styles.topBarButton} /> </TouchableOpacity> </LinearGradient> </View> {loadingElement} {listElement} </View> ); } } module.exports = NewsList;
src/mobile/public/components/Profile/index.js
Perslu/rerebrace
import React from 'react'; import './styles.css'; import CoverPhoto from '../CoverPhoto'; import singleCoverPhoto from '../../../assets/single_cover.jpg' import AppHeader from '../AppHeader'; import AppContainer from '../AppContainer'; import AboutSection from './AboutSection'; import faker from 'faker'; const renderProfile = props => { const imgUrl = props.profile.picture.large; const username = props.profile.login.username; return ( <AppContainer> <AppHeader hasBack onBack={props.onBack}/> <CoverPhoto img={singleCoverPhoto} text={username}/> {/*<CoverPhoto img={imgUrl} text={username}/>*/} <AboutSection>{faker.fake("{{lorem.paragraph}}")}</AboutSection> </AppContainer> ) }; const renderLoading = () => <div>Loading...</div>; const Profile = (props) => { return (props.profile) ? renderProfile(props) : renderLoading() }; Profile.propTypes = { onBack : React.PropTypes.func, profile: React.PropTypes.object.isRequired, }; export default Profile
app/javascript/components/collections/landing/SearchResultsCard.js
avalonmediasystem/avalon
/* * Copyright 2011-2022, The Trustees of Indiana University and Northwestern * University. 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. * --- END LICENSE_HEADER BLOCK --- */ import React from 'react'; import PropTypes from 'prop-types'; import CollectionCardShell from '../CollectionCardShell'; import CollectionCardThumbnail from '../CollectionCardThumbnail'; import CollectionCardBody from '../CollectionCardBody'; const CardMetaData = ({ doc, fieldLabel, fieldName }) => { let metaData = null; if (Array.isArray(doc[fieldName]) && doc[fieldName].length > 1) { metaData = doc[fieldName].join(', '); } else if (typeof doc[fieldName] == 'string') { const summary = doc[fieldName].substring(0, 50); metaData = doc[fieldName].length >= 50 ? `${summary}...` : doc[fieldName]; } else { metaData = doc[fieldName]; } if (doc[fieldName]) { return ( <React.Fragment> <dt>{fieldLabel}</dt> <dd>{metaData}</dd> </React.Fragment> ); } return null; }; CardMetaData.propTypes = { doc: PropTypes.object, fieldLabel: PropTypes.string, fieldName: PropTypes.string }; const millisecondsToFormattedTime = sec_num => { let tostring = num => { return `0${num}`.slice(-2); }; let hours = Math.floor(sec_num / 3600); let minutes = Math.floor((sec_num % 3600) / 60); let seconds = sec_num - minutes * 60 - hours * 3600; return `${tostring(hours)}:${tostring(minutes)}:${tostring( seconds.toFixed(0) )}`; }; const duration = ms => { if (Number(ms) > 0) { return millisecondsToFormattedTime(ms / 1000); } }; const thumbnailSrc = (doc, props) => { if (doc['section_id_ssim']) { return `${props.baseUrl}master_files/${props.doc['section_id_ssim'][0]}/thumbnail`; } }; const SearchResultsCard = props => { const { baseUrl, index, doc } = props; return ( <CollectionCardShell> <CollectionCardThumbnail> <span className="timestamp badge badge-dark"> {duration(doc['duration_ssi'])} </span> <a href={baseUrl + 'media_objects/' + doc['id']}> {thumbnailSrc(doc, props) && ( <img className="card-img-top img-cover" src={thumbnailSrc(doc, props)} alt="Card image cap" /> )} </a> </CollectionCardThumbnail> <CollectionCardBody> <> <h4> <a href={baseUrl + 'media_objects/' + doc['id']}> { doc['title_tesi'] && doc['title_tesi'].substring(0, 50) || doc['id'] } { doc['title_tesi'] && doc['title_tesi'].length >= 50 && <span>...</span> } </a> </h4> <dl id={'card-body-' + index} className="card-text dl-horizontal"> <CardMetaData doc={doc} fieldLabel="Date" fieldName="date_ssi" /> <CardMetaData doc={doc} fieldLabel="Main Contributors" fieldName="creator_ssim" /> <CardMetaData doc={doc} fieldLabel="Summary" fieldName="summary_ssi" /> </dl> </> </CollectionCardBody> </CollectionCardShell> ); }; SearchResultsCard.propTypes = { baseUrl: PropTypes.string, index: PropTypes.number, doc: PropTypes.object }; export default SearchResultsCard;
modules/ScrollManagementMixin.js
kenwheeler/react-router
import React from 'react'; import { canUseDOM, setWindowScrollPosition } from './DOMUtils'; import NavigationTypes from './NavigationTypes'; var { func } = React.PropTypes; function getCommonAncestors(branch, otherBranch) { return branch.filter(route => otherBranch.indexOf(route) !== -1); } function shouldUpdateScrollPosition(state, prevState) { var { location, branch } = state; var { location: prevLocation, branch: prevBranch } = prevState; // When an onEnter hook uses transition.to to redirect // on the initial load prevLocation is null, so assume // we don't want to update the scroll position. if (prevLocation === null) return false; // Don't update scroll position if only the query has changed. if (location.pathname === prevLocation.pathname) return false; // Don't update scroll position if any of the ancestors // has `ignoreScrollPosition` set to `true` on the route. var sharedAncestors = getCommonAncestors(branch, prevBranch); if (sharedAncestors.some(route => route.ignoreScrollBehavior)) return false; return true; } function updateWindowScrollPosition(navigationType, scrollX, scrollY) { if (canUseDOM) { if (navigationType === NavigationTypes.POP) { setWindowScrollPosition(scrollX, scrollY); } else { setWindowScrollPosition(0, 0); } } } var ScrollManagementMixin = { propTypes: { shouldUpdateScrollPosition: func.isRequired, updateScrollPosition: func.isRequired }, getDefaultProps() { return { shouldUpdateScrollPosition, updateScrollPosition: updateWindowScrollPosition }; }, componentDidUpdate(prevProps, prevState) { var { location } = this.state; var locationState = location && location.state; if (locationState && this.props.shouldUpdateScrollPosition(this.state, prevState)) { var { scrollX, scrollY } = locationState; this.props.updateScrollPosition(location.navigationType, scrollX || 0, scrollY || 0); } } }; export default ScrollManagementMixin;
poc/src/js/dashboard/demo.js
clplain/poc
require('./demo.css'); import React from 'react'; import App from './app'; class Demo extends React.Component { render() { return ( <div className='panel panel-default'> <div className='panel-body'> <App/> </div> </div> ); } } export default Demo;
src/components/atoms/Spinner/index.stories.js
DimensionLab/narc
import React from 'react' import { storiesOf } from '@storybook/react' import Spinner from '.' storiesOf('Spinner', module) .add('default', () => ( <Spinner /> )) .add('reverse', () => ( <Spinner reverse /> )) .add('another palette', () => ( <Spinner palette="secondary" /> ))
app/javascript/flavours/glitch/components/animated_number.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'flavours/glitch/util/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
public/js/components/admin/graphs/graph.react.js
IsuruDilhan/Coupley
/** * Created by Isuru 1 on 21/02/2016 */ import React from 'react'; import { Link } from 'react-router'; import GraphActions from './../../../actions/admin/GraphActions'; import GraphStore from './../../../stores/admin/GraphStore'; const LineGraph = React.createClass({ getInitialState: function () { return { users: GraphStore.getresults(), }; }, componentDidMount: function () { GraphActions.userRegistrations(); GraphStore.addChangeListener(this._onChange); }, _onChange: function () { if (this.isMounted()) { this.setState({ users: GraphStore.getresults(), }); } }, graph: function () { var dataPoints = []; var i; for (i in this.state.users) { var count = this.state.users[i].sum; var dateTime = this.state.users[i].createdAt; var date = (dateTime.split(' ')[0]); var y = date.split('-')[0]; var m = date.split('-')[1]; var d = date.split('-')[2]; dataPoints.push({ x: new Date(y, m, d), y:parseInt(count) }); } var chart = new CanvasJS.Chart('chartContainer', { theme: 'theme2', title: { text: 'User Registrations - All the time', }, animationEnabled: true, axisX: { valueFormatString: 'DD-MMM-YYYY', interval: 1, intervalType: 'month', title:'Date', }, axisY: { includeZero: false, title:'Total Users', }, data: [ { type: 'line', dataPoints: dataPoints, }, ], }); chart.render(); }, render: function () { return ( <div> <div onLoad={this.graph()}></div> </div> ); }, }); export default LineGraph;
src/routes/Editor/components/QuestionsTab.js
athenekilta/ilmomasiina
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { Input, Checkbox, Select } from 'formsy-react-components'; import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc'; const DragHandle = SortableHandle(() => <span className="handler" />); // This can be any component you want const SortableItem = SortableElement(({ value }) => ( <div className="panel panel-default"> <DragHandle /> {value} </div> )); const SortableItems = SortableContainer(({ collection, items }) => ( <div> {items.map((value, index) => ( <SortableItem collection={collection} key={index} index={index} value={value} /> ))} </div> )); const QUESTION_TYPES = [ { value: 'text', label: 'Teksti (lyhyt)' }, { value: 'textarea', label: 'Teksti (pitkä)' }, { value: 'number', label: 'Numero' }, { value: 'select', label: 'Monivalinta (voi valita yhden)' }, { value: 'checkbox', label: 'Monivalinta (voi valita monta)' }, ]; class QuestionsTab extends React.Component { static propTypes = { onDataChange: PropTypes.func.isRequired, event: PropTypes.object, }; constructor(props) { super(props); this.addQuestion = this.addQuestion.bind(this); this.updateQuestion = this.updateQuestion.bind(this); this.updateOrder = this.updateOrder.bind(this); this.removeQuestion = this.removeQuestion.bind(this); } addQuestion() { const questions = this.props.event.questions ? this.props.event.questions : []; const newQuestions = _.concat(questions, { id: (_.max(questions.map(n => n.id)) || 0) + 1, sortId: (_.max(questions.map(n => n.sortId)) || -1) + 1, existsInDb: false, required: false, public: false, question: '', type: 'text', }); this.props.onDataChange('questions', newQuestions); } updateOrder(args) { let newQuestions = this.props.event.questions; const elementToMove = newQuestions[args.oldIndex]; newQuestions.splice(args.oldIndex, 1); newQuestions.splice(args.newIndex, 0, elementToMove); for (let index = 0; index < newQuestions.length; index++) { newQuestions[index].sortId = index } this.props.onDataChange('questions', newQuestions); } updateQuestion(itemId, field, value) { const questions = this.props.event.questions; const newQuestions = _.map(questions, (question) => { if (question.id === itemId) { if (value === "select" || value === "checkbox") { if (!question.options) { question.options = [""] } else { question.options = null } } return { ...question, [field]: value, }; } return question; }); this.props.onDataChange('questions', newQuestions); } updateQuestionOption(itemId, index, value) { const questions = this.props.event.questions; const newQuestions = _.map(questions, (question) => { if (question.id === itemId) { question.options[index] = value } return question; }); this.props.onDataChange('questions', newQuestions); } addOption(questionId) { const questions = this.props.event.questions; const newQuestions = _.map(questions, (question) => { if (question.id === questionId) { question.options.push(""); } return question }); this.props.onDataChange('questions', newQuestions); } removeQuestion(itemId) { const questions = this.props.event.questions; const newQuestions = _.filter(questions, (question) => { if (question.id === itemId) { return false; } return true; }); this.props.onDataChange('questions', newQuestions); } renderQuestionOptions(question) { if (!question.options) { return null } return ( <div> {_.map(question.options, (option, index) => ( <Input name={`question-${question.id}-question-option-${index}`} value={option} label={"Vastausvaihtoehto "} type="text" required onChange={(field, value) => this.updateQuestionOption(question.id, index, value)} /> ))} <a onClick={() => this.addOption(question.id)}>Lisää vastausvaihtoehto</a> </div>) } renderQuestions() { const q = _.map(this.props.event.questions, item => ( <div className="panel-body"> <div className="col-xs-12 col-sm-10"> <Input name={`question-${item.id}-question`} value={item.question} label="Kysymys" type="text" required onChange={(field, value) => this.updateQuestion(item.id, 'question', value)} /> <Select name={`question-${item.id}-type`} value={item.type} label="Tyyppi" options={QUESTION_TYPES} onChange={(field, value) => this.updateQuestion(item.id, 'type', value)} required /> {this.renderQuestionOptions(item)} </div> <div className="col-xs-12 col-sm-2"> <Checkbox name={`question-${item.id}-required`} value={item.required} label="Pakollinen" onChange={(field, value) => this.updateQuestion(item.id, 'required', value)} /> <Checkbox name={`question-${item.id}-public`} value={item.public} label="Julkinen" onChange={(field, value) => this.updateQuestion(item.id, 'public', value)} /> <a onClick={() => this.removeQuestion(item.id)}>Poista</a> </div> </div> )); return <SortableItems collection="questions" items={q} onSortEnd={this.updateOrder} useDragHandle />; } render() { return ( <div> <p>Kaikilta osallistujilta kerätään aina nimi ja sähköpostiosoite.</p> <div> {this.renderQuestions()} <a className="btn btn-primary pull-right" onClick={this.addQuestion}> Lisää kysymys </a> </div> </div> ); } } export default QuestionsTab;
screens/MeditationPlayerScreen.js
FuzzyHatPublishing/isleep
/** * @flow */ import React, { Component } from 'react'; import { Dimensions, Image, Modal, Platform, Slider, StyleSheet, Text, TouchableHighlight, TouchableOpacity, View } from 'react-native'; import { Icon } from 'react-native-elements'; import { MaterialIcons } from '@expo/vector-icons'; import { Asset, Audio } from 'expo'; const ICON_TRACK = require('../assets/images/line-white-thin.png'); const ICON_THUMB = require('../assets/images/dot-sm.png'); const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get('window'); const BACKGROUND_COLOR = '#000'; const DISABLED_OPACITY = 0.5; const FONT_SIZE = 14; const LOADING_STRING = '... loading ...'; // const BUFFERING_STRING = '...buffering...'; class MeditationPlayerScreen extends Component { static navigationOptions = ({ navigation }) => ({ title: 'iSleep', headerLeft: <Icon name='navigate-before' size={32} color={'white'} onPress={ () => navigation.goBack() } />, headerStyle: { marginTop: Platform.OS === 'android' ? 24: 0, backgroundColor: "#000" }, headerTitleStyle: { color: '#fff', fontSize: 22, fontWeight: 'bold', marginHorizontal: 8, alignSelf: 'center', marginLeft: Platform.OS === 'android' ? -42 : 0 } }); constructor(props) { super(props); this.playbackInstance = null; this.isSeeking = false; this.shouldPlayAtEndOfSeek = false; this.state = { meditationTrack: this.props.navigation.state.params.meditation, playbackInstanceName: LOADING_STRING, playbackInstancePosition: null, playbackInstanceDuration: null, shouldPlay: false, isPlaying: false, isLoading: true, modalVisible: false, closingMessage: '' }; } componentDidMount() { Audio.setAudioModeAsync({ allowsRecordingIOS: false, interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX, playsInSilentModeIOS: true, shouldDuckAndroid: false, interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX }); this._loadNewPlaybackInstance(false); } async _loadNewPlaybackInstance(playing) { console.log('in _loadNewPlaybackInstance') if (this.playbackInstance != null) { console.log('_loadNewPlaybackInstance is not null') await this.playbackInstance.unloadAsync(); this.playbackInstance.setOnPlaybackStatusUpdate(null); this.playbackInstance = null; } const initialStatus = { shouldPlay: playing }; const source = this.state.meditationTrack.id == 1 ? require('../assets/sounds/test-audio.mp3') : require('../assets/sounds/test-audio-2.mp3'); try { const { sound, status } = await Audio.Sound.create( source, initialStatus, this._onPlaybackStatusUpdate ) this.playbackInstance = sound; this._updateScreenForLoading(false); } catch(e) { console.log("Problem creating sound object: ", e) } } _updateScreenForLoading(isLoading) { if (isLoading) { console.log("in updateScreenForLoading-if") this.setState({ isPlaying: false, playbackInstanceName: LOADING_STRING, playbackInstanceDuration: null, playbackInstancePosition: null, isLoading: true }); } else { console.log("in updateScreenForLoading-else") this.setState({ playbackInstanceName: this.state.meditationTrack.title, isLoading: false }); } } _onPlaybackStatusUpdate = status => { if (!status.isLoaded) { // Update your UI for the unloaded state if (status.error) { console.log(`Encountered a fatal error during playback: ${status.error}`); // Send Expo team the error on Slack or the forums so we can help you debug! } } else { if (status.isLoaded) { this.setState({ playbackInstancePosition: status.positionMillis, playbackInstanceDuration: status.durationMillis, shouldPlay: status.shouldPlay, isPlaying: status.isPlaying, // isBuffering: status.isBuffering, }); if (status.didJustFinish) { console.log( `AUDIO UPDATE : Finished meditation` ); this.playbackInstance.unloadAsync() this._getRandomClosingMessage(); this._setModalVisible(!this.state.modalVisible); } } else { if (status.error) { console.log(`FATAL PLAYER ERROR: ${status.error}`); } } } }; _onPlayPausePressed = () => { if (this.playbackInstance != null) { if (this.state.isPlaying) { this.playbackInstance.pauseAsync(); } else { this.playbackInstance.playAsync(); } } }; _getSeekSliderPosition() { if ( this.playbackInstance != null && this.state.playbackInstancePosition != null && this.state.playbackInstanceDuration != null ) { if (Platform.OS === 'android' && this.state.playbackInstancePosition / this.state.playbackInstanceDuration == 1) { this.playbackInstance.unloadAsync() } else { return ( this.state.playbackInstancePosition / this.state.playbackInstanceDuration ); } } return 0; }; _onSeekSliderValueChange = value => { console.log('in _onSeekSliderValueChange') if (this.playbackInstance != null && !this.isSeeking) { console.log('in _onSeekSliderValueChange, in conditional') this.isSeeking = true; this.shouldPlayAtEndOfSeek = this.state.shouldPlay; this.playbackInstance.pauseAsync(); } }; _onSeekSliderSlidingComplete = async value => { console.log('in _onSeekSliderSlidingComplete, this.playbackInstance must be null?') if (this.playbackInstance != null) { this.isSeeking = false; const seekPosition = value * this.state.playbackInstanceDuration; if (this.shouldPlayAtEndOfSeek) { console.log('in _onSeekSliderSlidingComplete, this.shouldPlayAtEndOfSeek') this.playbackInstance.playFromPositionAsync(seekPosition); } else { this.playbackInstance.setPositionAsync(seekPosition); } } }; _getMMSSFromMillis(millis) { const totalSeconds = millis / 1000; const seconds = Math.floor(totalSeconds % 60); const minutes = Math.floor(totalSeconds / 60); const padWithZero = number => { const string = number.toString(); if (number < 10) { return '0' + string; } return string; }; // console.log('in _getMMSSFromMillis') return padWithZero(minutes) + ':' + padWithZero(seconds); } _getTimestampIncr() { if ( this.playbackInstance != null && this.state.playbackInstancePosition != null && this.state.playbackInstanceDuration != null ) { return `${this._getMMSSFromMillis( this.state.playbackInstancePosition )}`; } return ''; } _getTimestampDecr() { if ( this.playbackInstance != null && this.state.playbackInstancePosition != null && this.state.playbackInstanceDuration != null ) { return `${this._getMMSSFromMillis( this.state.playbackInstanceDuration - this.state.playbackInstancePosition )}`; } return ''; } _getRandomClosingMessage() { console.log("in _getRandomClosingMessage") let messages = require('../assets/data/closing_message_data'); let randomMessage = messages[Math.floor(Math.random()*messages.length)]; this.setState({closingMessage: randomMessage.message}); } _setModalVisible(visible) { console.log(`MODAL UPDATE : _setModalVisible`) this.setState({modalVisible: visible}); } _getImage(meditation) { return meditation.id == 1 ? require('../assets/images/sky-moon-cloud-min.jpg') : require('../assets/images/beach-meditation-min.jpg') } render() { const { goBack } = this.props.navigation; return( <View style={styles.container}> <Image source={ this._getImage(this.state.meditationTrack) } style={styles.image} resizeMode='contain' /> <Text style={styles.title}> {this.state.playbackInstanceName} </Text> <Text style={styles.title}> YOGA NIDRA </Text> <View style={styles.timestampRow}> <Text style={[ styles.text, styles.timestamp ]} > {this._getTimestampIncr()} </Text> <Slider style={styles.playbackSlider} minimumTrackTintColor={'#555555'} trackImage={ICON_TRACK.module} thumbImage={require('../assets/images/dot-white-12px.png')} value={this._getSeekSliderPosition()} onValueChange={this._onSeekSliderValueChange} onSlidingComplete={this._onSeekSliderSlidingComplete} disabled={this.state.isLoading} /> <Text style={[ styles.text, styles.timestamp ]} > {this._getTimestampDecr()} </Text> </View> <View style={styles.round}> <TouchableHighlight underlayColor={BACKGROUND_COLOR} onPress={this._onPlayPausePressed} // disabled={this.state.isLoading} > <View> {this.state.isPlaying ? ( <MaterialIcons name="pause" size={42} color="#fff" /> ) : ( <MaterialIcons name="play-arrow" size={42} color="#fff" /> )} </View> </TouchableHighlight> </View> <View> <Modal animationType="fade" transparent={false} visible={this.state.modalVisible} onRequestClose={() => { console.log("On close go to Home screen") }} > <TouchableOpacity style={styles.container} activeOpacity={1} onPressOut={() => { this._setModalVisible(false) goBack(); }} > <View style={styles.modal}> <Text style={styles.modalMessage}>{ this.state.closingMessage }</Text> </View> </TouchableOpacity> </Modal> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', paddingBottom: '10%', backgroundColor: BACKGROUND_COLOR }, image: { flex: 1, height: DEVICE_WIDTH * .6, width: DEVICE_WIDTH }, title: { color: '#fff', fontWeight: 'bold', fontSize: 20, paddingBottom: 10 // marginTop: -10 }, timestampRow: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginTop: 15, maxHeight: FONT_SIZE * 2 }, text: { color: '#fff', fontSize: 12 }, playbackSlider: { width: DEVICE_WIDTH * .6, marginHorizontal: 10 }, round: { height: 60, width: 60, borderRadius: 30, justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderColor: '#fff', marginTop: 10, backgroundColor: BACKGROUND_COLOR }, modal: { flex: 1, justifyContent: 'center', alignItems: 'center', }, modalMessage: { fontSize: 22, color: '#fff' } }); export default MeditationPlayerScreen;
public/components/MainPageAppView.js
supportivesantas/project-ipsum
import React from 'react'; import { browserHistory } from 'react-router'; import actions from '../actions/ipsumActions.js'; import { connect } from 'react-redux'; import maps from '../mappingFunctions.js'; import { Button, ButtonToolbar, Panel, Col } from 'react-bootstrap'; import barGraph from './AllAppsBarGraph'; import restHandler from '../util/restHelpers.js'; import _ from 'underscore'; class MainPageAppView extends React.Component { constructor(props) { super(props); this.state = { resizefunc: null }; } componentDidMount(id) { restHandler.post('getStats/allAppSummaries', {}, (err, res) => { if (res.status !== 401) { this.props.dispatch(actions.ADD_ALL_APP_SUMMARIES(res.body)); var apps = this.props.state.allAppSummaries || {}; var id = this.props.selected.id; var app; for (var i = 0; i < apps.length; i++) { if (+apps[i].appid === id) { app = apps[i]; break; } } if (app && app.data) { barGraph("Graph" + id, _.sortBy(app.data, (obj) => { return obj.date; })); } } else { browserHistory.push('/login'); } }); this.setState({ resizefunc: this.resizedb() }, () => { window.addEventListener('resize', this.state.resizefunc); }); } resizedb() { var resize = function () { var apps = this.props.state.allAppSummaries || {}; var id = this.props.selected.id.toString(); var app = _.findWhere(apps, {appid: id}); if (app && app.data) { barGraph("Graph" + id, _.sortBy(app.data, (obj) => { return obj.date; })); } }; return _.debounce(resize.bind(this), 500); } componentWillUnmount() { window.removeEventListener('resize', this.state.resizefunc); } getNumServers(id) { const appServers = _.filter(this.props.state.servers, (item) => { return _.pluck(item.apps, 0).indexOf(id) !== -1; }); const activeServers = _.filter(appServers, (item) => { return item.active === 'active'; }); return { active: activeServers, total: appServers }; } generateHeader(id) { var ratio = this.getNumServers(id); return ( <div onClick={this.goToApp.bind(this)} className="AppViewHeaderText"> {this.props.selected.appname} <span className="pull-right">{ratio.active.length}/{ratio.total.length} active</span> </div> ); } generateAppStats(id) { var apps = this.props.state.allAppSummaries || {}; var app; for (var i = 0; i < apps.length; i++) { if (+apps[i].appid === id) { app = apps[i]; break; } } app = app || {}; return ( <div> <h4>Total Routes Monitored: {app.totalRoute}</h4> </div> ) } goToApp() { this.props.dispatch(actions.ADD_APP_SELECTION(this.props.selected)); browserHistory.push('/myApp'); } render() { return ( <Col xs={12} sm={6} md={6}> <div className="MainPageAppView"> <Panel header={this.generateHeader(this.props.selected.id)}> <h4 style={{"textAlign":"center"}}>Load over the last week</h4> <div id={"Graph" + this.props.selected.id.toString()}> </div> {this.generateAppStats(this.props.selected.id)} </Panel> </div> </Col> ); } } MainPageAppView = connect(state => ({ state: state }))(MainPageAppView); export default MainPageAppView;
app/javascript/mastodon/components/picture_in_picture_placeholder.js
MitarashiDango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; import { removePictureInPicture } from 'mastodon/actions/picture_in_picture'; import { connect } from 'react-redux'; import { debounce } from 'lodash'; import { FormattedMessage } from 'react-intl'; export default @connect() class PictureInPicturePlaceholder extends React.PureComponent { static propTypes = { width: PropTypes.number, dispatch: PropTypes.func.isRequired, }; state = { width: this.props.width, height: this.props.width && (this.props.width / (16/9)), }; handleClick = () => { const { dispatch } = this.props; dispatch(removePictureInPicture()); } setRef = c => { this.node = c; if (this.node) { this._setDimensions(); } } _setDimensions () { const width = this.node.offsetWidth; const height = width / (16/9); this.setState({ width, height }); } componentDidMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } handleResize = debounce(() => { if (this.node) { this._setDimensions(); } }, 250, { trailing: true, }); render () { const { height } = this.state; return ( <div ref={this.setRef} className='picture-in-picture-placeholder' style={{ height }} role='button' tabIndex='0' onClick={this.handleClick}> <Icon id='window-restore' /> <FormattedMessage id='picture_in_picture.restore' defaultMessage='Put it back' /> </div> ); } }
server/sonar-web/src/main/js/components/SourceViewer/components/LineCode.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // @flow import React from 'react'; import classNames from 'classnames'; import LineIssuesList from './LineIssuesList'; import { splitByTokens, highlightSymbol, highlightIssueLocations, generateHTML } from '../helpers/highlight'; import type { Tokens } from '../helpers/highlight'; import type { SourceLine } from '../types'; import type { LinearIssueLocation, IndexedIssueLocation, IndexedIssueLocationMessage } from '../helpers/indexing'; type Props = { highlightedSymbol: string | null, issueKeys: Array<string>, issueLocations: Array<LinearIssueLocation>, line: SourceLine, onIssueSelect: (issueKey: string) => void, onLocationSelect: (flowIndex: number, locationIndex: number) => void, onSymbolClick: (symbol: string) => void, // $FlowFixMe secondaryIssueLocations: Array<IndexedIssueLocation>, secondaryIssueLocationMessages: Array<IndexedIssueLocationMessage>, selectedIssue: string | null, selectedIssueLocation: IndexedIssueLocation | null, showIssues: boolean }; type State = { tokens: Tokens }; export default class LineCode extends React.PureComponent { codeNode: HTMLElement; props: Props; state: State; symbols: NodeList<HTMLElement>; constructor(props: Props) { super(props); this.state = { tokens: splitByTokens(props.line.code || '') }; } componentDidMount() { this.attachEvents(); } componentWillReceiveProps(nextProps: Props) { if (nextProps.line.code !== this.props.line.code) { this.setState({ tokens: splitByTokens(nextProps.line.code || '') }); } } componentWillUpdate() { this.detachEvents(); } componentDidUpdate() { this.attachEvents(); } componentWillUnmount() { this.detachEvents(); } attachEvents() { this.symbols = this.codeNode.querySelectorAll('.sym'); for (const symbol of this.symbols) { symbol.addEventListener('click', this.handleSymbolClick); } } detachEvents() { if (this.symbols) { for (const symbol of this.symbols) { symbol.removeEventListener('click', this.handleSymbolClick); } } } handleSymbolClick = (e: Object) => { e.preventDefault(); const key = e.currentTarget.className.match(/sym-\d+/); if (key && key[0]) { this.props.onSymbolClick(key[0]); } }; handleLocationMessageClick = ( e: SyntheticInputEvent, flowIndex: number, locationIndex: number ) => { e.preventDefault(); this.props.onLocationSelect(flowIndex, locationIndex); }; isSecondaryIssueLocationSelected(location: IndexedIssueLocation | IndexedIssueLocationMessage) { const { selectedIssueLocation } = this.props; if (selectedIssueLocation == null) { return false; } else { return selectedIssueLocation.flowIndex === location.flowIndex && selectedIssueLocation.locationIndex === location.locationIndex; } } renderSecondaryIssueLocationMessage = (location: IndexedIssueLocationMessage) => { const className = classNames('source-viewer-issue-location', 'issue-location-message', { selected: this.isSecondaryIssueLocationSelected(location) }); const limitString = (str: string) => str.length > 30 ? str.substr(0, 30) + '...' : str; return ( <a key={`${location.flowIndex}-${location.locationIndex}`} href="#" className={className} title={location.msg} onClick={e => this.handleLocationMessageClick(e, location.flowIndex, location.locationIndex)}> {location.index && <strong>{location.index}: </strong>} {location.msg ? limitString(location.msg) : ''} </a> ); }; renderSecondaryIssueLocationMessages(locations: Array<IndexedIssueLocationMessage>) { return ( <div className="source-line-issue-locations"> {locations.map(this.renderSecondaryIssueLocationMessage)} </div> ); } render() { const { highlightedSymbol, issueKeys, issueLocations, line, onIssueSelect, secondaryIssueLocationMessages, secondaryIssueLocations, selectedIssue, selectedIssueLocation, showIssues } = this.props; let tokens = [...this.state.tokens]; if (highlightedSymbol) { tokens = highlightSymbol(tokens, highlightedSymbol); } if (issueLocations.length > 0) { tokens = highlightIssueLocations(tokens, issueLocations); } if (secondaryIssueLocations) { tokens = highlightIssueLocations(tokens, secondaryIssueLocations, 'issue-location'); if (selectedIssueLocation != null) { const x = secondaryIssueLocations.find(location => this.isSecondaryIssueLocationSelected(location)); if (x) { tokens = highlightIssueLocations(tokens, [x], 'selected'); } } } const finalCode = generateHTML(tokens); const className = classNames('source-line-code', 'code', { 'has-issues': issueKeys.length > 0 }); return ( <td className={className} data-line-number={line.line}> <div className="source-line-code-inner"> <pre ref={node => this.codeNode = node} dangerouslySetInnerHTML={{ __html: finalCode }} /> {secondaryIssueLocationMessages != null && secondaryIssueLocationMessages.length > 0 && this.renderSecondaryIssueLocationMessages(secondaryIssueLocationMessages)} </div> {showIssues && issueKeys.length > 0 && <LineIssuesList issueKeys={issueKeys} onIssueClick={onIssueSelect} selectedIssue={selectedIssue} />} </td> ); } }
node_modules/material-ui/src/hoc/selectable-enhance.js
Maxwelloff/react-football
import React from 'react'; import getMuiTheme from '../styles/getMuiTheme'; import StylePropable from '../mixins/style-propable'; import ColorManipulator from '../utils/color-manipulator'; export const SelectableContainerEnhance = (Component) => { const composed = React.createClass({ displayName: `Selectable${Component.displayName}`, propTypes: { children: React.PropTypes.node, selectedItemStyle: React.PropTypes.object, valueLink: React.PropTypes.shape({ value: React.PropTypes.any, requestChange: React.PropTypes.func, }).isRequired, }, contextTypes: { muiTheme: React.PropTypes.object, }, childContextTypes: { muiTheme: React.PropTypes.object, }, mixins: [ StylePropable, ], getInitialState() { return { muiTheme: this.context.muiTheme || getMuiTheme(), }; }, getChildContext() { return { muiTheme: this.state.muiTheme, }; }, componentWillReceiveProps(nextProps, nextContext) { let newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme; this.setState({muiTheme: newMuiTheme}); }, getValueLink: function(props) { return props.valueLink || { value: props.value, requestChange: props.onChange, }; }, extendChild(child, styles, selectedItemStyle) { if (child && child.type && child.type.displayName === 'ListItem') { let selected = this.isChildSelected(child, this.props); let selectedChildrenStyles = {}; if (selected) { selectedChildrenStyles = this.mergeStyles(styles, selectedItemStyle); } let mergedChildrenStyles = this.mergeStyles(child.props.style || {}, selectedChildrenStyles); this.keyIndex += 1; return React.cloneElement(child, { onTouchTap: (e) => { this.handleItemTouchTap(e, child); if (child.props.onTouchTap) { child.props.onTouchTap(e); } }, key: this.keyIndex, style: mergedChildrenStyles, nestedItems: child.props.nestedItems.map((child) => this.extendChild(child, styles, selectedItemStyle)), initiallyOpen: this.isInitiallyOpen(child), }); } else { return child; } }, isInitiallyOpen(child) { if (child.props.initiallyOpen) { return child.props.initiallyOpen; } return this.hasSelectedDescendant(false, child); }, hasSelectedDescendant(previousValue, child) { if (React.isValidElement(child) && child.props.nestedItems && child.props.nestedItems.length > 0) { return child.props.nestedItems.reduce(this.hasSelectedDescendant, previousValue); } return previousValue || this.isChildSelected(child, this.props); }, isChildSelected(child, props) { let itemValue = this.getValueLink(props).value; let childValue = child.props.value; return (itemValue === childValue); }, handleItemTouchTap(e, item) { let valueLink = this.getValueLink(this.props); let itemValue = item.props.value; let menuValue = valueLink.value; if ( itemValue !== menuValue) { valueLink.requestChange(e, itemValue); } }, render() { const {children, selectedItemStyle} = this.props; this.keyIndex = 0; let styles = {}; if (!selectedItemStyle) { let textColor = this.state.muiTheme.rawTheme.palette.textColor; let selectedColor = ColorManipulator.fade(textColor, 0.2); styles = { backgroundColor: selectedColor, }; } let newChildren = React.Children.map(children, (child) => this.extendChild(child, styles, selectedItemStyle)); return ( <Component {...this.props} {...this.state}> {newChildren} </Component> ); }, }); return composed; }; export default SelectableContainerEnhance;
src/svg-icons/av/fast-forward.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFastForward = (props) => ( <SvgIcon {...props}> <path d="M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z"/> </SvgIcon> ); AvFastForward = pure(AvFastForward); AvFastForward.displayName = 'AvFastForward'; AvFastForward.muiName = 'SvgIcon'; export default AvFastForward;
src/components/common/svg-icons/maps/local-post-office.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPostOffice = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/> </SvgIcon> ); MapsLocalPostOffice = pure(MapsLocalPostOffice); MapsLocalPostOffice.displayName = 'MapsLocalPostOffice'; MapsLocalPostOffice.muiName = 'SvgIcon'; export default MapsLocalPostOffice;
src/packages/@ncigdc/components/DownloadVisualizationButton.js
NCI-GDC/portal-ui
// @flow import React from 'react'; import downloadSvg from 'download-svg'; import { compose } from 'recompose'; import saveFile from '@ncigdc/utils/filesaver'; import toTsvString, { mapArrayToTsvString } from '@ncigdc/utils/toTsvString'; import DropDown from '@ncigdc/uikit/Dropdown'; import DropdownItem from '@ncigdc/uikit/DropdownItem'; import Button from '@ncigdc/uikit/Button'; import { visualizingButton } from '@ncigdc/theme/mixins'; import { withTheme } from '@ncigdc/theme'; import Download from '@ncigdc/theme/icons/Download'; import Hidden from '@ncigdc/components/Hidden'; import { Tooltip } from '@ncigdc/uikit/Tooltip'; import supportsSvgToPng from '@ncigdc/utils/supportsSvgToPng'; import { track } from '@ncigdc/utils/analytics'; function getDOMNode(el?: string | Element): ?Element { switch (typeof el) { case 'string': return document.querySelector(el); case 'function': return el(); default: return el; } } const styles = { row: theme => ({ padding: '0.6rem 1rem', cursor: 'pointer', ':hover': { backgroundColor: theme.greyScale6, }, }), }; type TProps = { svg?: any, data: Object, slug: string | string[], stylePrefix?: string, style?: Object, noText?: boolean, tsvData?: Array<Object>, theme: Object, tooltipHTML: any, disabled: boolean, }; const enhance = compose(withTheme); const DownloadVisualizationButton = ({ buttonStyle, data, disabled, noText, slug = 'export', stylePrefix, svg, theme, tooltipHTML, tsvData, ...props }: TProps) => { const isSlugArray = slug instanceof Array; return ( <DropDown button={( <Tooltip Component={tooltipHTML}> <Button disabled={disabled} leftIcon={!noText && <Download />} style={{ ...visualizingButton, ...buttonStyle, }} type="button" > {noText ? ( <span> <Download /> <Hidden>Download</Hidden> </span> ) : ( 'Download' )} </Button> </Tooltip> )} className={props.className || 'test-download-viz-button'} isDisabled={disabled} {...props} > {svg && ( <DropdownItem className="test-download-svg" key="svg" onClick={() => { if (svg instanceof Array) { svg.map((s, i) => downloadSvg({ svg: getDOMNode(s), stylePrefix, fileName: `${slug[i]}.svg`, })); track('download-viz', { type: 'svg' }); return; } downloadSvg({ svg: getDOMNode(svg), stylePrefix, fileName: `${slug}.svg`, }); track('download-viz', { type: 'svg' }); }} style={styles.row(theme)} > SVG </DropdownItem> )} {svg && ( <DropdownItem className="test-download-png" key="png" onClick={() => { if (supportsSvgToPng()) { if (svg instanceof Array) { svg.map((s, i) => downloadSvg({ svg: getDOMNode(s), stylePrefix, fileName: `${slug[i]}.png`, })); track('download-viz', { type: 'png' }); return; } downloadSvg({ svg: getDOMNode(svg), stylePrefix, fileName: `${slug}.png`, scale: 2, }); track('download-viz', { type: 'png' }); } }} style={{ ...styles.row(theme), ...(supportsSvgToPng() ? {} : { opacity: 0.5, }), }} > {supportsSvgToPng() ? ( 'PNG' ) : ( <Tooltip Component={` Download as PNG is currently unavailable in your browser. Please use the latest version of Chrome or Firefox `} > PNG </Tooltip> )} </DropdownItem> )} {data && ( <DropdownItem key="JSON" onClick={() => { saveFile(JSON.stringify(data, null, 2), 'JSON', `${isSlugArray ? slug[0] : slug}.json`); track('download-viz', { type: 'json' }); }} style={styles.row(theme)} > { isSlugArray ? 'QQ JSON' : 'JSON'} </DropdownItem> )} {tsvData && ( <DropdownItem key="TSV" onClick={() => { if (tsvData) { saveFile( tsvData[0] && tsvData[0].forEach ? mapArrayToTsvString(tsvData) : toTsvString(tsvData), 'TSV', `${isSlugArray ? slug[0] : slug}.tsv`, ); track('download-viz', { type: 'tsv' }); } }} style={styles.row(theme)} > {isSlugArray ? 'QQ TSV' : 'TSV'} </DropdownItem> )} </DropDown> ); }; export default enhance(DownloadVisualizationButton);
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js
amsardesai/react-router
import React from 'react'; class Announcement extends React.Component { //static loadProps (params, cb) { //cb(null, { //announcement: COURSES[params.courseId].announcements[params.announcementId] //}); //} render () { //var { title, body } = this.props.announcement; var { courseId, announcementId } = this.props.params; var { title, body } = COURSES[courseId].announcements[announcementId]; return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Announcement;
front/app/js/components/xAPITextArea.js
nudoru/learning-map
import React from 'react'; import PropTypes from 'prop-types'; import {curry} from 'ramda'; import {Col, Grid, Row} from "../rh-components/rh-Grid"; import {Button, SecondaryButton} from "../rh-components/rh-Button"; import {TextArea} from "../rh-components/rh-Form"; export class XAPITextArea extends React.PureComponent { static propTypes = { id : PropTypes.string, onSave : PropTypes.func, prompt : PropTypes.string, disabled : PropTypes.bool, previousResponse: PropTypes.string }; static defaultProps = {}; state = { isPrompting : true, isConfirming : false, hasResponded : false, hasEnteredText: false, responseText : '' }; _handleSaveClick = e => { this.setState({isPrompting: false, isConfirming: true}) }; _handleCancelClick = e => { this.setState({isPrompting: true, isConfirming: false}) }; _handleSubmitClick = e => { this.setState({ isPrompting : false, isConfirming: false, hasResponded: true }); // TODO send to the LRS if (this.props.onSave) { // this.context.sendLinkStatement('clicked', children, id); this.props.onSave({id: this.props.id, response: this.state.responseText}) } }; _handleInputChange = e => { const input = e.target.value; if (input.length > 1) { this.setState({hasEnteredText: true, responseText: input}); } else { this.setState({hasEnteredText: false}); } }; render() { return <Grid className='xapitextarea-group'> {this.state.isPrompting ? this._renderInputForm() : (this.state.isConfirming ? this._renderConfirmResponse() : this._renderFinalResponse())} </Grid>; } _renderInputForm() { const {prompt} = this.props; return <div> <Row> <Col> <p className='xapitextarea-prompt'>{prompt}</p> <TextArea className='xapitextarea-text-area' defaultValue={this.state.responseText} onChange={this._handleInputChange}/> </Col> </Row> <Row className='xapitextarea-buttonrow'> <Col className='text-center'> <Button hollow onClick={this._handleSaveClick} disabled={!this.state.hasEnteredText}>Save</Button> </Col> </Row> </div> } _renderConfirmResponse() { const {prompt} = this.props; return <div> <Row> <Col> <p className='xapitextarea-confirmation'>You cannot change your response once it's saved. Are you sure?</p> </Col> </Row> <Row className='margin-top margin-bottom'> <Col> <p className='xapitextarea-prompt'>{prompt}</p> <blockquote className='xapitextarea-saved-text'>{this.state.responseText}</blockquote> </Col> </Row> <Row className='xapitextarea-buttonrow'> <Col className='text-center'> <Button onClick={this._handleCancelClick} className='rh-button-text margin-right'>Edit</Button> <Button onClick={this._handleSubmitClick}>Save</Button> </Col> </Row> </div>; } _renderFinalResponse() { return <div> <Row> <Col> <p className='xapitextarea-prompt'>{this.props.prompt}</p> <blockquote className='xapitextarea-saved-text'>{this.state.responseText}</blockquote> </Col> </Row> </div>; } }
app/javascript/mastodon/features/reblogs/index.js
alarky/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchReblogs } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'reblogged_by', Number(props.params.statusId)]), }); @connect(mapStateToProps) export default class Reblogs extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchReblogs(Number(this.props.params.statusId))); } componentWillReceiveProps(nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchReblogs(Number(nextProps.params.statusId))); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='reblogs'> <div className='scrollable reblogs'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } }
mla_game/front-end/javascript/components/partials/paginator.js
WGBH/FixIt
import React from 'react'; class Paging extends React.Component{ render(){ return( <div className="pagination"> <button disabled={this.props.waiting} onClick={this.props.handleProgress.bind(this)} className='next'> <span>Next</span> <svg viewBox="0 0 200 200"> <title>Next</title> <polygon points="70, 55 70, 145 145, 100"/> </svg> </button> </div> ) } } export default Paging;
app/javascript/mastodon/features/ui/components/actions_modal.js
riku6460/chikuwagoddon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContent from '../../../components/status_content'; import Avatar from '../../../components/avatar'; import RelativeTimestamp from '../../../components/relative_timestamp'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import classNames from 'classnames'; export default class ActionsModal extends ImmutablePureComponent { static propTypes = { status: ImmutablePropTypes.map, actions: PropTypes.array, onClick: PropTypes.func, }; renderAction = (action, i) => { if (action === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { icon = null, text, meta = null, active = false, href = '#' } = action; return ( <li key={`${text}-${i}`}> <a href={href} target='_blank' rel='noopener' onClick={this.props.onClick} data-index={i} className={classNames({ active })}> {icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />} <div> <div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div> <div>{meta}</div> </div> </a> </li> ); } render () { const status = this.props.status && ( <div className='status light'> <div className='boost-modal__status-header'> <div className='boost-modal__status-time'> <a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener'> <RelativeTimestamp timestamp={this.props.status.get('created_at')} /> </a> </div> <a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'> <div className='status__avatar'> <Avatar account={this.props.status.get('account')} size={48} /> </div> <DisplayName account={this.props.status.get('account')} /> </a> </div> <StatusContent status={this.props.status} /> </div> ); return ( <div className='modal-root__modal actions-modal'> {status} <ul> {this.props.actions.map(this.renderAction)} </ul> </div> ); } }
app/components/layout/Settings/Skills.js
communicode-source/communicode
import React from 'react'; import classNames from 'classnames'; import styles from './../../../assets/css/pages/settings.scss'; import PropTypes from 'prop-types'; import {Form, FormGroup, FormControl, ControlLabel, Col} from 'react-bootstrap'; class Skills extends React.Component { constructor(props) { super(props); this.props = props; this.state = { value: '' }; } handleRemoveSkill(e) { this.props.changeSkill(e.target.innerHTML); this.props.saveSkill(); } buildSkills() { if(!this.props.skills || !this.props.skills.map) { return null; } const node = this.props.skills.map((item, index) => <p onClick={this.handleRemoveSkill.bind(this)} key={index} className={classNames(styles.button, styles.removable)}>{item}</p>); return node; } handleFormChange(e) { this.setState({value: e.target.value}); } handleSubmit(e) { e.preventDefault(); this.props.changeSkill(this.state.value); this.setState({value: ''}); this.props.saveSkill(); } render() { return ( <div> <div className={classNames(styles.btns)}> {this.buildSkills.call(this)} </div> <Form onSubmit={this.handleSubmit.bind(this)} horizontal> <FormGroup className={styles.formGroup}> <Col componentClass={ControlLabel} sm={3}> Add a skill &nbsp; <i className={classNames('fa', 'fa-pencil-square-o')} aria-hidden="true"></i> </Col> <Col sm={9}> <FormControl type="text" placeholder="i.e. Ruby on Rails, then press ENTER" value={this.state.value} onChange={this.handleFormChange.bind(this)} /> </Col> </FormGroup> </Form> <p>{this.state.value !== '' && 'Press ENTER when you are done!'}</p> </div> ); } } Skills.propTypes = { skills: PropTypes.array, changeSkill: PropTypes.func, saveSkill: PropTypes.func }; export default Skills;
packages/es-components/src/components/patterns/progress-tracker/ProgressTracker.js
jrios/es-components
import React from 'react'; import { withTheme } from 'styled-components'; import PropTypes from 'prop-types'; import { ProgressContainer, ProgressItem } from './progress-tracker-subcomponents'; const getMappedSteps = (steps, onPastStepClicked, onFutureStepClicked, showNav) => { let isPastStep = true; return steps.map((step, index) => { isPastStep = !(step.active || !isPastStep); return ( <ProgressItem /* eslint-disable react/no-array-index-key */ key={`${index}-${step.label}`} /* eslint-enable */ active={step.active} isPastStep={isPastStep} numberOfSteps={steps.length} onPastStepClicked={() => onPastStepClicked(index)} canClickFutureStep={ onFutureStepClicked !== null && onFutureStepClicked !== undefined } onFutureStepClicked={() => onFutureStepClicked(index)} label={step.label} showNav={showNav} /> ); }); }; const getIndexOfActiveStep = steps => steps.findIndex(step => step.active); function ProgressTracker({ steps, onPastStepClicked, onFutureStepClicked, showNav }) { return ( <ProgressContainer data-testid="progress-tracker" activeStepIndex={getIndexOfActiveStep(steps)} numberOfSteps={steps.length} > {getMappedSteps(steps, onPastStepClicked, onFutureStepClicked, showNav)} </ProgressContainer> ); } ProgressTracker.propTypes = { steps: PropTypes.arrayOf( PropTypes.shape({ active: PropTypes.bool, label: PropTypes.string }) ), onPastStepClicked: PropTypes.func, onFutureStepClicked: PropTypes.func, showNav: PropTypes.bool }; ProgressTracker.defaultProps = { steps: [], onPastStepClicked() {}, onFutureStepClicked: null, showNav: true }; export default withTheme(ProgressTracker);
src/components/App.js
inkatze/rfh
import React from 'react'; import Menu from './Menu'; import Content from './Content'; import Contact from './Contact'; import Footer from './Footer'; const App = (props) => { return ( <div> <Menu /> <Content /> <Contact /> <Footer /> </div> ); } export default App;
src/components/ui/toolbars/HoverToolbar.js
brancusi/lingo-client-react
import React from 'react'; import Radium from 'radium'; import Rx from 'rx'; @Radium export default class HoverToolbar extends React.Component { static propTypes = { children: React.PropTypes.array.isRequired, options: React.PropTypes.object } constructor (props) { super(props); this.state = { show:false }; } componentDidMount () { this.overs = Rx.Observable.fromEvent(this.trigger, 'mouseover'); this.outs = Rx.Observable.fromEvent(this.trigger, 'mouseout'); this.oversSub = this.overs.subscribe(() => this._show()); this.outsSub = this.outs.subscribe(() => this._hide()); } componentWillUnmount () { this.oversSub.dispose(); this.outsSub.dispose(); } _show () { TweenMax.to(this.uiContainer, 0.25, { marginTop: 0, ease: Expo.easeOut }); } _hide () { const height = this.uiContainer.offsetHeight; TweenMax.to(this.uiContainer, 0.25, { marginTop: -height, ease: Expo.easeOut }); } render () { const { options = {}, children } = this.props; const { background = 'white', width = '100%', height = '100%' } = options; const styles = { minWidth: width, minHeight: height, overflow: 'hidden' }; const uiContainer = { display: 'flex', justifyContent: 'space-between', background: background, padding: 10, marginTop: -100 }; return ( <div ref={node => this.trigger = node} style={styles}> <div ref={node => this.uiContainer = node} style={uiContainer}> {children} </div> </div> ); } }
example/components/Markdown.react.js
Neophy7e/react-bootstrap-typeahead
import cx from 'classnames'; import marked from 'marked'; import React from 'react'; const Markdown = React.createClass({ componentWillMount() { marked.setOptions({ gfm: true, tables: true, breaks: true, pedantic: false, sanitize: true, smartLists: true, smartypants: false, highlight(code) { return require('highlight.js').highlightAuto(code).value; }, }); }, render() { const html = marked.parse(this.props.children); return ( <div className={cx('markdown-body', this.props.className)} dangerouslySetInnerHTML={{__html: html}} /> ); }, }); export default Markdown;
react/YoutubeSearchApp/src/components/video-detail.js
jacobuid/learning
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return ( <div>loading...</div> ) } let videoURL = `https://www.youtube.com/embed/${video.id.videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={videoURL}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
ceraon/static/src/js/app.js
Rdbaker/Mealbound
/** * Main application initialization * */ import React from 'react' import ReactDOM from 'react-dom' import SampleComponent from './sample-component.jsx' // Initialize on Document Ready document.addEventListener('DOMContentLoaded', () => { let main = document.getElementById('main'); ReactDOM.render(<SampleComponent />, main); })
app/components/LoginPage/index.js
tomhah/containerProject
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import styles from './styles.css'; @Cerebral({ username: 'login.username', password: 'login.password' }) class LoginPage extends React.Component { render() { const {signals, username, password} = this.props; return ( <form onSubmit={() => signals.login.formSubmitted()} className={styles.wrapper}> <input onChange={(e) => signals.login.usernameChanged({value: e.target.value})} value={username} type="text" placeholder="Brukernavn"/> <input onChange={(e) => signals.login.passwordChanged({value: e.target.value})} value={password} type="password" placeholder="Passord"/> <button type="button" onClick={() => signals.login.formSubmitted()}>Logg inn</button> <div className={styles.logo}></div> </form> ); } } export default LoginPage;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
surbhishankar/Car-Ranks-App
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
react-native-life/ReactNativeLife/js/Components/ViewPagerAndroid/ViewPagerAndroid.js
CaMnter/front-end-life
/** * @author CaMnter */ import React from 'react'; import { Image, StyleSheet, Text, TouchableWithoutFeedback, TouchableOpacity, View, ViewPagerAndroid } from 'react-native'; import type {ViewPagerScrollState} from 'ViewPagerAndroid'; let PAGES = 5; let BGCOLOR = ['#fdc08e', '#fff6b9', '#99d1b7', '#dde5fe', '#f79273']; let IMAGE_URIS = [ 'https://apod.nasa.gov/apod/image/1410/20141008tleBaldridge001h990.jpg', 'https://apod.nasa.gov/apod/image/1409/volcanicpillar_vetter_960.jpg', 'https://apod.nasa.gov/apod/image/1409/m27_snyder_960.jpg', 'https://apod.nasa.gov/apod/image/1409/PupAmulti_rot0.jpg', 'https://apod.nasa.gov/apod/image/1510/lunareclipse_27Sep_beletskycrop4.jpg', ]; class LikeCount extends React.Component { state = { likes: 7, }; onClick = () => { this.setState({likes: this.state.likes + 1}); }; render() { let thumbsUp = '\uD83D\uDC4D'; return ( <View style={styles.likeContainer}> <TouchableOpacity onPress={this.onClick} style={styles.likeButton}> <Text style={styles.likesText}> {thumbsUp + ' Like'} </Text> </TouchableOpacity> <Text style={styles.likesText}> {this.state.likes + ' likes'} </Text> </View> ); } } class Button extends React.Component { _handlePress = () => { if (this.props.enabled && this.props.onPress) { this.props.onPress(); } }; render() { return ( <TouchableWithoutFeedback onPress={this._handlePress}> <View style={[styles.button, this.props.enabled ? {} : styles.buttonDisabled]}> <Text style={styles.buttonText}>{this.props.text}</Text> </View> </TouchableWithoutFeedback> ); } } class ProgressBar extends React.Component { render() { let fractionalPosition = (this.props.progress.position + this.props.progress.offset); let progressBarSize = (fractionalPosition / (PAGES - 1)) * this.props.size; return ( <View style={[styles.progressBarContainer, {width: this.props.size}]}> <View style={[styles.progressBar, {width: progressBarSize}]}/> </View> ); } } class ViewPagerAndroidExample extends React.Component { static title = '<ViewPagerAndroid>'; static description = 'Container that allows to flip left and right between child views.'; state = { page: 0, animationsAreEnabled: true, scrollEnabled: true, progress: { position: 0, offset: 0, }, }; onPageSelected = (e) => { this.setState({page: e.nativeEvent.position}); }; onPageScroll = (e) => { this.setState({progress: e.nativeEvent}); }; onPageScrollStateChanged = (state: ViewPagerScrollState) => { this.setState({scrollState: state}); }; move = (delta) => { let page = this.state.page + delta; this.go(page); }; go = (page) => { if (this.state.animationsAreEnabled) { this.viewPager.setPage(page); } else { this.viewPager.setPageWithoutAnimation(page); } this.setState({page}); }; render() { let pages = []; for (let i = 0; i < PAGES; i++) { let pageStyle = { backgroundColor: BGCOLOR[i % BGCOLOR.length], alignItems: 'center', padding: 20, }; pages.push( <View key={i} style={pageStyle} collapsable={false}> <Image style={styles.image} source={{uri: IMAGE_URIS[i % BGCOLOR.length]}} /> <LikeCount /> </View> ); } let {page, animationsAreEnabled} = this.state; return ( <View style={styles.container}> <ViewPagerAndroid style={styles.viewPager} initialPage={0} scrollEnabled={this.state.scrollEnabled} onPageScroll={this.onPageScroll} onPageSelected={this.onPageSelected} onPageScrollStateChanged={this.onPageScrollStateChanged} pageMargin={10} ref={viewPager => { this.viewPager = viewPager; }}> {pages} </ViewPagerAndroid> <View style={styles.buttons}> <Button enabled={true} text={this.state.scrollEnabled ? 'Scroll Enabled' : 'Scroll Disabled'} onPress={() => this.setState({scrollEnabled: !this.state.scrollEnabled})} /> </View> <View style={styles.buttons}> { animationsAreEnabled ? <Button text="Turn off animations" enabled={true} onPress={() => this.setState({animationsAreEnabled: false})} /> : <Button text="Turn animations back on" enabled={true} onPress={() => this.setState({animationsAreEnabled: true})} /> } <Text style={styles.scrollStateText}>ScrollState[ {this.state.scrollState} ]</Text> </View> <View style={styles.buttons}> <Button text="Start" enabled={page > 0} onPress={() => this.go(0)}/> <Button text="Prev" enabled={page > 0} onPress={() => this.move(-1)}/> <Text style={styles.buttonText}>Page {page + 1} / {PAGES}</Text> <ProgressBar size={100} progress={this.state.progress}/> <Button text="Next" enabled={page < PAGES - 1} onPress={() => this.move(1)}/> <Button text="Last" enabled={page < PAGES - 1} onPress={() => this.go(PAGES - 1)}/> </View> </View> ); } } const styles = StyleSheet.create({ buttons: { flexDirection: 'row', height: 30, backgroundColor: 'black', alignItems: 'center', justifyContent: 'space-between', }, button: { flex: 1, width: 0, margin: 5, borderColor: 'gray', borderWidth: 1, backgroundColor: 'gray', }, buttonDisabled: { backgroundColor: 'black', opacity: 0.5, }, buttonText: { color: 'white', }, scrollStateText: { color: '#99d1b7', }, container: { flex: 1, backgroundColor: 'white', }, image: { width: 300, height: 200, padding: 20, }, likeButton: { backgroundColor: 'rgba(0, 0, 0, 0.1)', borderColor: '#333333', borderWidth: 1, borderRadius: 5, flex: 1, margin: 8, padding: 8, }, likeContainer: { flexDirection: 'row', }, likesText: { flex: 1, fontSize: 18, alignSelf: 'center', }, progressBarContainer: { height: 10, margin: 10, borderColor: '#eeeeee', borderWidth: 2, }, progressBar: { alignSelf: 'flex-start', flex: 1, backgroundColor: '#eeeeee', }, viewPager: { flex: 1, }, }); module.exports = ViewPagerAndroidExample;
docs/src/app/components/pages/components/Drawer/ExampleUndocked.js
skarnecki/material-ui
import React from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import RaisedButton from 'material-ui/RaisedButton'; export default class DrawerUndockedExample extends React.Component { constructor(props) { super(props); this.state = {open: false}; } handleToggle = () => this.setState({open: !this.state.open}); handleClose = () => this.setState({open: false}); render() { return ( <div> <RaisedButton label="Open Drawer" onTouchTap={this.handleToggle} /> <Drawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({open})} > <MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem> <MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem> </Drawer> </div> ); } }
examples/with-lingui/components/withLang.js
flybayer/next.js
import React from 'react' import { I18nProvider } from '@lingui/react' export default function withLang(Component, defaultLang = 'en') { return class WithLang extends React.Component { static async getInitialProps(ctx) { const language = ctx.query.lang || defaultLang const [props, catalog] = await Promise.all([ Component.getInitialProps ? Component.getInitialProps(ctx) : {}, import(`../locale/${language}/messages.po`).then((m) => m.default), ]) return { ...props, language, catalogs: { [language]: catalog, }, } } render() { const { language, catalogs, ...restProps } = this.props return ( <I18nProvider language={language} catalogs={catalogs}> <Component {...restProps} /> </I18nProvider> ) } } }
Realization/frontend/czechidm-core/src/content/audit/EntityAuditTable.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; // import * as Utils from '../../utils'; import * as Basic from '../../components/basic'; import * as Advanced from '../../components/advanced'; import { AuditManager } from '../../redux'; import AuditModificationEnum from '../../enums/AuditModificationEnum'; const auditManager = new AuditManager(); /** * Audit for selected entity / owner. Used on entity detail. * * @author Radek Tomiška * @since 12.0.0 */ export class EntityAuditTable extends Advanced.AbstractTableContent { getContentKey() { return 'content.audit'; } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } componentDidMount() { super.componentDidMount(); // this.context.store.dispatch(auditManager.fetchAuditedEntitiesNames()); } cancelFilter(event) { if (event) { event.preventDefault(); } if (this.refs.table !== undefined) { this.refs.table.cancelFilter(this.refs.filterForm); } } /** * Method for show detail of revision, redirect to detail * * @param entityId id of revision */ showDetail(entityId) { this.context.history.push(`/audit/entities/${ entityId }/diff/`); } _getNiceLabelForOwner(ownerType, ownerCode) { if (ownerCode && ownerCode !== null && ownerCode !== 'null') { return ownerCode; } return ''; } render() { const { uiKey, auditedEntities, forceSearchParameters } = this.props; // return ( <div> <Advanced.Table ref="table" filterOpened uiKey={ uiKey } manager={ auditManager } forceSearchParameters={ forceSearchParameters } rowClass={({ rowIndex, data }) => { return Utils.Ui.getRowClass(data[rowIndex]); }} showId filter={ <Advanced.Filter onSubmit={ this.useFilter.bind(this) }> <Basic.AbstractForm ref="filterForm"> <Basic.Row> <Basic.Col lg={ 8 }> <Advanced.Filter.FilterDate ref="fromTill"/> </Basic.Col> <Basic.Col lg={ 4 } className="text-right"> <Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/> </Basic.Col> </Basic.Row> <Basic.Row> <Basic.Col lg={ 4 }> <Advanced.Filter.EnumSelectBox ref="type" searchable placeholder={ this.i18n('entity.Audit.type') } options={ auditedEntities }/> </Basic.Col> <Basic.Col lg={ 4 }> <Advanced.Filter.TextField className="pull-right" ref="modifier" placeholder={ this.i18n('content.audit.identities.modifier') } help={ this.i18n('content.audit.filter.modifier.help') }/> </Basic.Col> </Basic.Row> <Basic.Row className="last"> <Basic.Col lg={ 12 } > <Advanced.Filter.CreatableSelectBox ref="changedAttributesList" placeholder={ this.i18n('entity.Audit.changedAttributes.placeholder') } tooltip={ this.i18n('entity.Audit.changedAttributes.tooltip') }/> </Basic.Col> </Basic.Row> </Basic.AbstractForm> </Advanced.Filter> } _searchParameters={ this.getSearchParameters() }> <Advanced.Column header="" className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={ this.i18n('button.detail') } onClick={ this.showDetail.bind(this, data[rowIndex].id) }/> ); } } sort={ false }/> <Advanced.Column property="type" width={ 200 } cell={ ({ rowIndex, data, property }) => { return ( <span title={ data[rowIndex][property] }> { Utils.Ui.getSimpleJavaType(data[rowIndex][property]) } </span> ); } }/> <Advanced.Column property="entityId" header={ this.i18n('entity.Audit.entity') } cell={ /* eslint-disable react/no-multi-comp */ ({ rowIndex, data, property }) => { const value = data[rowIndex][property]; // if (data[rowIndex]._embedded && data[rowIndex]._embedded[property]) { return ( <Advanced.EntityInfo entityType={ Utils.Ui.getSimpleJavaType(data[rowIndex].type) } entityIdentifier={ value } face="popover" entity={ data[rowIndex]._embedded[property] } showEntityType={ false } showIcon/> ); } if (data[rowIndex].revisionValues) { return ( <Advanced.EntityInfo entityType={ Utils.Ui.getSimpleJavaType(data[rowIndex].type) } entityIdentifier={ value } entity={ data[rowIndex].revisionValues } face="popover" showLink={ false } showEntityType={ false } showIcon deleted/> ); } // return ( <Advanced.UuidInfo value={ value } /> ); } }/> <Advanced.Column property="subOwnerCode" face="text" cell={ ({ rowIndex, data }) => { return this._getNiceLabelForOwner(data[rowIndex].subOwnerType, data[rowIndex].subOwnerCode); } } /> <Advanced.Column property="modification" width={ 100 } sort cell={ ({ rowIndex, data, property }) => { return ( <Basic.Label level={ AuditModificationEnum.getLevel(data[rowIndex][property]) } text={ AuditModificationEnum.getNiceLabel(data[rowIndex][property]) }/> ); } }/> <Advanced.Column property="modifier" sort face="text"/> <Advanced.Column property="timestamp" header={this.i18n('entity.Audit.revisionDate')} sort face="datetime"/> <Advanced.Column hidden property="changedAttributes" cell={ ({ rowIndex, data, property }) => { return _.replace(data[rowIndex][property], ',', ', '); } } /> </Advanced.Table> </div> ); } } EntityAuditTable.propTypes = { uiKey: PropTypes.string.isRequired, /** * Selected entity force search parameters. */ forceSearchParameters: PropTypes.object.isRequired }; function select(state, component) { return { _searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey), auditedEntities: auditManager.prepareOptionsFromAuditedEntitiesNames(auditManager.getAuditedEntitiesNames(state)) }; } export default connect(select)(EntityAuditTable);
cerberus-dashboard/src/actions/versionHistoryBrowserActions.js
Nike-Inc/cerberus-management-service
/* * 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 axios from 'axios'; import * as actions from '../constants/actions'; import * as messengerActions from './messengerActions'; import ApiError from '../components/ApiError/ApiError'; import downloadjs from "downloadjs"; import log from "../utils/logger"; export function fetchVersionDataForSdb(safeDepositBodId, token) { return function (dispatch) { return axios({ url: `/v1/sdb-secret-version-paths/${safeDepositBodId}`, headers: { 'X-Cerberus-Token': token }, timeout: 60 * 1000 // 1 minute }) .then((response) => { dispatch(updatePathsWithHistory(response.data)); }) .catch(({ response }) => { let msg = 'Failed to fetch version data for sdb'; log.error(msg, response); dispatch(messengerActions.addNewMessage(<ApiError message={msg} response={response} />)); }); }; } export function updatePathsWithHistory(paths) { return { type: actions.FETCHED_VERSION_DATA_FOR_SDB, payload: paths }; } export function fetchPathVersionData(path, token, pageNumber, perPage) { return function (dispatch) { return axios({ url: `/v1/secret-versions/${path}`, params: { limit: perPage, offset: Math.ceil(pageNumber * perPage) }, headers: { 'X-Cerberus-Token': token }, timeout: 60 * 1000 // 1 minute }) .then((response) => { dispatch(updateVersionDataForPath(path, response.data)); }) .catch(({ response }) => { let msg = 'Failed to fetch path version data'; log.error(msg, response); dispatch(messengerActions.addNewMessage(<ApiError message={msg} response={response} />)); }); }; } export function updateVersionDataForPath(path, data) { return { type: actions.FETCHED_VERSION_DATA_FOR_PATH, payload: { data: data, path: path } }; } export function handleBreadCrumbHomeClick() { return { type: actions.CLEAR_VERSION_PATH_SELECTED, }; } export function updatePerPage(perPage) { return { type: actions.UPDATE_VERSION_PATHS_PER_PAGE, payload: { perPage: perPage } }; } export function updatePageNumber(pageNumber) { return { type: actions.UPDATE_VERSION_PATHS_PAGE_NUMBER, payload: { pageNumber: pageNumber } }; } export function resetVersionBrowserState() { return { type: actions.RESET_VERSION_BROWSER_STATE }; } export function fetchVersionedSecureDataForPath(path, versionId, token) { let request = { url: `/v1/secret/${path}`, headers: { 'X-Cerberus-Token': token }, timeout: 60 * 1000 // 1 minute }; if (versionId !== 'CURRENT') { request['params'] = { versionId: versionId }; } return function (dispatch) { return axios(request) .then((response) => { dispatch(updateVersionedSecureDataForPath(versionId, response.data.data)); }) .catch(({ response }) => { let msg = 'Failed to fetch versioned secure data for path'; log.error(msg, response); dispatch(messengerActions.addNewMessage(<ApiError message={msg} response={response} />)); }); }; } export function downloadSecureFileVersion(path, versionId, token) { console.log("Version ID: " + versionId); let request = { url: `/v1/secure-file/${path}`, headers: { 'X-Cerberus-Token': token, 'Accept': 'application/octet-stream' }, responseType: 'blob', timeout: 60 * 1000 // 1 minute }; if (versionId !== 'CURRENT') { request['params'] = { versionId: versionId }; } return function (dispatch) { return axios(request) .then((response) => { let reader = new window.FileReader(); reader.readAsText(response.data); reader.onload = function () { let pathParts = path.split('/'); downloadjs(reader.result, pathParts[pathParts.length - 1]); }; // dispatch(updateVersionedSecureDataForPath(versionId, new Uint8Array(response.data), 'FILE')) }) .catch(({ response }) => { let msg = 'Failed to fetch version data for secure file path'; log.error(msg, response); dispatch(messengerActions.addNewMessage(<ApiError message={msg} response={response} />)); }); }; } export function updateVersionedSecureDataForPath(versionId, secureData, type) { return { type: actions.ADD_SECURE_DATA_FOR_VERSION, payload: { type: type, versionId: versionId, secureData: secureData } }; }
docs/src/app/components/pages/components/TimePicker/Page.js
hai-cea/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import timePickerReadmeText from './README'; import TimePickerExampleSimple from './ExampleSimple'; import timePickerExampleSimpleCode from '!raw!./ExampleSimple'; import TimePickerExampleComplex from './ExampleComplex'; import timePickerExampleComplexCode from '!raw!./ExampleComplex'; import TimePickerExampleInternational from './ExampleInternational'; import timePickerExampleInternationalCode from '!raw!./ExampleInternational'; import TimePickerExampleStep from './ExampleStep'; import timePickerExampleStepCode from '!raw!./ExampleStep'; import timePickerCode from '!raw!material-ui/TimePicker/TimePicker'; const descriptions = { simple: 'Time Picker supports 12 hour and 24 hour formats. In 12 hour format the AM and PM indicators toggle the ' + 'selected time period. You can also disable the Dialog passing true to the disabled property.', controlled: '`TimePicker` can be used as a controlled component.', localised: 'The buttons can be localised using the `cancelLabel` and `okLabel` properties.', step: 'The number of minutes on each step can be configured using the `minutesStep` property.', }; const TimePickersPage = () => ( <div> <Title render={(previousTitle) => `Time Picker - ${previousTitle}`} /> <MarkdownElement text={timePickerReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={timePickerExampleSimpleCode} > <TimePickerExampleSimple /> </CodeExample> <CodeExample title="Controlled examples" description={descriptions.controlled} code={timePickerExampleComplexCode} > <TimePickerExampleComplex /> </CodeExample> <CodeExample title="Localised example" description={descriptions.localised} code={timePickerExampleInternationalCode} > <TimePickerExampleInternational /> </CodeExample> <CodeExample title="Step example" description={descriptions.step} code={timePickerExampleStepCode} > <TimePickerExampleStep /> </CodeExample> <PropTypeDescription code={timePickerCode} /> </div> ); export default TimePickersPage;
frontend/app_v2/src/components/Topics/TopicsPresentationTopic.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import useIcon from 'common/useIcon' import AudioMinimal from 'components/AudioMinimal' import { Link } from 'react-router-dom' import { useParams } from 'react-router-dom' import { WIDGET_LIST_WORD, WIDGET_LIST_PHRASE, WIDGET_LIST_SONG, WIDGET_LIST_STORY } from 'common/constants' function TopicsPresentationTopic({ topic }) { const { audio, heading, image, listCount, subheading, type, url: _url } = topic const { sitename } = useParams() const url = `${sitename}/${_url}` let typeColor let icon let textSize switch (type) { case WIDGET_LIST_WORD: typeColor = 'word' icon = 'Word' textSize = 'text-4xl lg:text-5xl' break case WIDGET_LIST_PHRASE: typeColor = 'phrase' icon = 'Phrase' textSize = 'text-3xl lg:text-4xl' break case WIDGET_LIST_SONG: typeColor = 'song' icon = 'Song' textSize = 'text-3xl lg:text-4xl' break case WIDGET_LIST_STORY: typeColor = 'story' icon = 'Story' textSize = 'text-3xl lg:text-4xl' break default: // nothing break } const conditionalClass = image ? 'bg-center bg-cover text-white' : `border-12 border-${typeColor} text-${typeColor}Text` const conditionalStyle = image ? { backgroundImage: `linear-gradient(to bottom, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.3)), url(${image})` } : {} return ( <div data-testid="TopicsPresentationTopic" style={conditionalStyle} className={`${conditionalClass} mx-2 lg:m-0 flex flex-col items-center justify-between rounded-lg p-8 w-full`} > {useIcon(icon, `${image ? '' : `text-${typeColor}`} fill-current w-7 h-7 lg:w-10 lg:h-10 xl:w-14 xl:h-14`)} {heading && ( <h1 className={`${textSize} w-48 lg:w-auto text-center font-medium my-3`}> <Link to={url}>{heading}</Link> </h1> )} {subheading && <h2 className="text-xl lg:text-2xl text-center">{subheading}</h2>} {audio && <AudioMinimal.Container src={audio} iconStyling="fill-current w-7 h-7 lg:w-8 lg:h-8 mt-3" />} {listCount > 0 && ( <div className="text-lg lg:text-xl text-center"> {listCount === 1 && `${listCount} phrase`} {listCount > 1 && `${listCount} phrases`} </div> )} </div> ) } // PROPTYPES const { string, number, shape } = PropTypes TopicsPresentationTopic.propTypes = { topic: shape({ audio: string, heading: string, image: string, listCount: number, subheading: string, type: string, url: string, }), } export default TopicsPresentationTopic
classic/src/scenes/wbfa/generated/FARInfoCircle.free.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faInfoCircle } from '@fortawesome/free-solid-svg-icons/faInfoCircle' export default class FARInfoCircle extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faInfoCircle} />) } }
src/components/Torrent/StatusButton/index.js
Secretmapper/react-transmission
import React, { Component } from 'react'; import CSSModules from 'react-css-modules'; import { observer } from 'mobx-react'; import styles from './styles/index.css'; @observer @CSSModules(styles) class StatusButton extends Component { static defaultProps = { onToggle: () => {}, } render() { return ( <button styleName={this.props.torrent.isStopped ? 'statusResume' : 'statusPause'} onClick={this.props.onToggle.bind(this, this.props.torrent.id)} /> ); } } export default StatusButton;
src/svg-icons/action/account-balance.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBalance = (props) => ( <SvgIcon {...props}> <path d="M4 10v7h3v-7H4zm6 0v7h3v-7h-3zM2 22h19v-3H2v3zm14-12v7h3v-7h-3zm-4.5-9L2 6v2h19V6l-9.5-5z"/> </SvgIcon> ); ActionAccountBalance = pure(ActionAccountBalance); ActionAccountBalance.displayName = 'ActionAccountBalance'; ActionAccountBalance.muiName = 'SvgIcon'; export default ActionAccountBalance;
tests/react_experimental/useTransition_hook.js
mroch/flow
// @flow import React from 'react'; React.useTransition(); // Ok React.useTransition({}); // Error: no arguments are expected by function type const [isPending, startTransition] = React.useTransition(); // OK (isPending: boolean); // Ok (startTransition: (() => void) => void); // Ok (isPending: (() => void) => void); // Error: boolean is incompatible with function type (startTransition: boolean); // Error: function type is incompatible with boolean startTransition(() => {}); // Ok startTransition(); // Error: function requires another argument
internals/templates/homePage.js
mclxly/react-study
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; /* eslint-disable react/prefer-stateless-function */ export default class HomePage extends React.Component { render() { return ( <h1>This is the Homepage!</h1> ); } }
weather/src/index.js
williampuk/ReduxCasts
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
stories/dialogs/app-crashed.stories.js
LN-Zap/zap-desktop
import React from 'react' import { storiesOf } from '@storybook/react' import { DialogAppCrashed } from 'components/Dialog' import { Window } from '../helpers' storiesOf('Dialogs', module) .addDecorator(story => <Window>{story()}</Window>) .add('App Crashed', () => ( <DialogAppCrashed error={{ message: 'some error', stack: 'stack trace would display here' }} isOpen onClose={() => {}} onSubmit={() => {}} /> ))
lib/head.js
callumlocke/next.js
import React from 'react' import PropTypes from 'prop-types' import sideEffect from './side-effect' class Head extends React.Component { static contextTypes = { headManager: PropTypes.object } render () { return null } } export function defaultHead () { return [<meta charSet='utf-8' className='next-head' />] } function reduceComponents (components) { return components .map((c) => c.props.children) .map((children) => React.Children.toArray(children)) .reduce((a, b) => a.concat(b), []) .reverse() .concat(...defaultHead()) .filter((c) => !!c) .filter(unique()) .reverse() .map((c) => { const className = (c.className ? c.className + ' ' : '') + 'next-head' return React.cloneElement(c, { className }) }) } function mapOnServer (head) { return head } function onStateChange (head) { if (this.context && this.context.headManager) { this.context.headManager.updateHead(head) } } const METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp', 'property'] // returns a function for filtering head child elements // which shouldn't be duplicated, like <title/>. function unique () { const keys = new Set() const tags = new Set() const metaTypes = new Set() const metaCategories = {} return (h) => { if (h.key) { if (keys.has(h.key)) return false keys.add(h.key) } switch (h.type) { case 'title': case 'base': if (tags.has(h.type)) return false tags.add(h.type) break case 'meta': for (let i = 0, len = METATYPES.length; i < len; i++) { const metatype = METATYPES[i] if (!h.props.hasOwnProperty(metatype)) continue if (metatype === 'charSet') { if (metaTypes.has(metatype)) return false metaTypes.add(metatype) } else { const category = h.props[metatype] const categories = metaCategories[metatype] || new Set() if (categories.has(category)) return false categories.add(category) metaCategories[metatype] = categories } } break } return true } } export default sideEffect(reduceComponents, onStateChange, mapOnServer)(Head)
docs/src/app/components/pages/components/Toolbar/Page.js
hwo411/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import toolbarReadmeText from './README'; import toolbarExampleSimpleCode from '!raw!./ExampleSimple'; import ToolbarExampleSimple from './ExampleSimple'; import toolbarCode from '!raw!material-ui/Toolbar/Toolbar'; import toolbarText from './Toolbar'; import toolbarGroupCode from '!raw!material-ui/Toolbar/ToolbarGroup'; import toolbarGroupText from './ToolbarGroup'; import toolbarSeparatorCode from '!raw!material-ui/Toolbar/ToolbarSeparator'; import toolbarSeparatorText from './ToolbarSeparator'; import toolbarTitleCode from '!raw!material-ui/Toolbar/ToolbarTitle'; import toolbarTitleText from './ToolbarTitle'; const description = 'An example Toolbar demonstrating the use of the available sub-components, and including a ' + 'number of other Material-UI components, such as [Drop Down Menu](/#/components/dropdown-menu), [Font Icon]' + '(/#/components/font-icon), [Icon Menu](/#/components/icon-menu) and [Raised Button](/#/components/raised-button) .'; const ToolbarPage = () => ( <div> <Title render={(previousTitle) => `Toolbar - ${previousTitle}`} /> <MarkdownElement text={toolbarReadmeText} /> <CodeExample description={description} code={toolbarExampleSimpleCode}> <ToolbarExampleSimple /> </CodeExample> <PropTypeDescription code={toolbarCode} header={toolbarText} /> <PropTypeDescription code={toolbarGroupCode} header={toolbarGroupText} /> <PropTypeDescription code={toolbarSeparatorCode} header={toolbarSeparatorText} /> <PropTypeDescription code={toolbarTitleCode} header={toolbarTitleText} /> </div> ); export default ToolbarPage;
frontend/src/Artist/Index/Overview/Options/ArtistIndexOverviewOptionsModalContent.js
lidarr/Lidarr
import _ from 'lodash'; 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 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 } from 'Helpers/Props'; const posterSizeOptions = [ { key: 'small', value: 'Small' }, { key: 'medium', value: 'Medium' }, { key: 'large', value: 'Large' } ]; class ArtistIndexOverviewOptionsModalContent extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { detailedProgressBar: props.detailedProgressBar, size: props.size, showMonitored: props.showMonitored, showQualityProfile: props.showQualityProfile, showLastAlbum: props.showLastAlbum, showAdded: props.showAdded, showAlbumCount: props.showAlbumCount, showPath: props.showPath, showSizeOnDisk: props.showSizeOnDisk, showSearchAction: props.showSearchAction }; } componentDidUpdate(prevProps) { const { detailedProgressBar, size, showMonitored, showQualityProfile, showLastAlbum, showAdded, showAlbumCount, showPath, showSizeOnDisk, showSearchAction } = this.props; const state = {}; if (detailedProgressBar !== prevProps.detailedProgressBar) { state.detailedProgressBar = detailedProgressBar; } if (size !== prevProps.size) { state.size = size; } if (showMonitored !== prevProps.showMonitored) { state.showMonitored = showMonitored; } if (showQualityProfile !== prevProps.showQualityProfile) { state.showQualityProfile = showQualityProfile; } if (showLastAlbum !== prevProps.showLastAlbum) { state.showLastAlbum = showLastAlbum; } if (showAdded !== prevProps.showAdded) { state.showAdded = showAdded; } if (showAlbumCount !== prevProps.showAlbumCount) { state.showAlbumCount = showAlbumCount; } if (showPath !== prevProps.showPath) { state.showPath = showPath; } if (showSizeOnDisk !== prevProps.showSizeOnDisk) { state.showSizeOnDisk = showSizeOnDisk; } if (showSearchAction !== prevProps.showSearchAction) { state.showSearchAction = showSearchAction; } if (!_.isEmpty(state)) { this.setState(state); } } // // Listeners onChangeOverviewOption = ({ name, value }) => { this.setState({ [name]: value }, () => { this.props.onChangeOverviewOption({ [name]: value }); }); } // // Render render() { const { onModalClose } = this.props; const { detailedProgressBar, size, showMonitored, showQualityProfile, showLastAlbum, showAdded, showAlbumCount, showPath, showSizeOnDisk, showSearchAction } = this.state; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> Overview Options </ModalHeader> <ModalBody> <Form> <FormGroup> <FormLabel>Poster Size</FormLabel> <FormInputGroup type={inputTypes.SELECT} name="size" value={size} values={posterSizeOptions} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Detailed Progress Bar</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="detailedProgressBar" value={detailedProgressBar} helpText="Show text on progess bar" onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Monitored</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showMonitored" value={showMonitored} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Quality Profile</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showQualityProfile" value={showQualityProfile} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Last Album</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showLastAlbum" value={showLastAlbum} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Date Added</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showAdded" value={showAdded} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Album Count</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showAlbumCount" value={showAlbumCount} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Path</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showPath" value={showPath} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Size on Disk</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showSizeOnDisk" value={showSizeOnDisk} onChange={this.onChangeOverviewOption} /> </FormGroup> <FormGroup> <FormLabel>Show Search</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="showSearchAction" value={showSearchAction} helpText="Show search button" onChange={this.onChangeOverviewOption} /> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button onPress={onModalClose} > Close </Button> </ModalFooter> </ModalContent> ); } } ArtistIndexOverviewOptionsModalContent.propTypes = { size: PropTypes.string.isRequired, detailedProgressBar: PropTypes.bool.isRequired, showMonitored: PropTypes.bool.isRequired, showQualityProfile: PropTypes.bool.isRequired, showLastAlbum: PropTypes.bool.isRequired, showAdded: PropTypes.bool.isRequired, showAlbumCount: PropTypes.bool.isRequired, showPath: PropTypes.bool.isRequired, showSizeOnDisk: PropTypes.bool.isRequired, showSearchAction: PropTypes.bool.isRequired, onChangeOverviewOption: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default ArtistIndexOverviewOptionsModalContent;
frontend/smart-sushi-ui/src/App.js
cyterdan/smartSushi
import React, { Component } from 'react'; import './App.css'; import $ from 'jquery'; import 'whatwg-fetch'; var createReactClass = require('create-react-class'); var MenuSelect = createReactClass({ getInitialState: function() { return { menuList: [] }; }, componentDidMount: function() { $.get(this.props.source+"menus", function(result) { var options = []; console.log(result[0]); for (var key in result[0]) { options.push(<option key={key} value={key}> {result[0][key]} </option>); } this.setState({ menuList: options }); }.bind(this)); }, handleChange(event) { var self = this; var menuId = event.target.value; $.get(this.props.source+"menu",{menuId : menuId}, function(result) { self.props.onChange(menuId,result); }); }, render() { return ( <label> <p>Choose an existing menu : </p> <select value={this.state.value} onChange={this.handleChange}> <option value="0">none</option> {this.state.menuList} </select> </label> ); } }); var Requirements = createReactClass({ render() { var inputList = [] for(var i=0;i<this.props.dishes.length;i++){ var dish = this.props.dishes[i]; inputList.push( <tr key={dish}> <td> {dish} </td> <td> <input type="number" min="0" name={dish} defaultValue="0" onChange={this.props.onChange}></input> </td> </tr> ); } return( <div className="Fleft" > Select how many you want for each dish : <br /> <table> <tbody> {inputList} </tbody> </table> </div> ); } }); class Runner extends Component{ constructor() { super(); this.state = { bonus : [], order : [], price : 0, processing : false }; } handle = (e) => { console.log("solving",this.props); this.setState({processing:true}); $.ajax({ type: "POST", url: this.props.source+"solve", data: {'menuId' : this.props.menuId,'requirements' : this.props.requirements}, dataType: "json", success: (result) => { console.log(result); var orderList = []; for(var menuItem in result.order){ orderList.push( <tr key={menuItem}> <td> {menuItem} </td> <td> {result.order[menuItem]} </td> </tr> ); } var bonusList = []; for(var bonusItem in result.bonus){ bonusList.push( <tr key={bonusItem}> <td> {bonusItem} </td> <td> {result.bonus[bonusItem]} </td> </tr> ) } this.setState({order : orderList,price : result.price, bonus : bonusList,processing:false}); } }); } render() { if(this.props.menuId){ return ( <div className="Runner"> <button disabled={this.state.processing} onClick={this.handle}>{this.state.processing?"Working... ":"Find cheapest order !"}</button> {this.state.price ? <div> <h3>Results</h3> <h4>Total cost : {Math.round(this.state.price * 100) / 100} €</h4> <h4>Order</h4> <table> <thead> <tr> <td> Menu item </td> <td> Quantity </td> </tr> </thead> <tbody> {this.state.order} </tbody> </table> {this.state.bonus.length>0? <div> <h4>Bonus dishes</h4> <table> <thead> <tr> <td> Dish </td> <td> Quantity </td> </tr> </thead> <tbody> {this.state.bonus} </tbody> </table> </div> :null} </div> :null} </div> ) } else{ return (<div></div>) } } }; class App extends Component { constructor() { super(); this.state = { dishes : [], requirements : {}, menuId : null }; } menuSelectHandler = (id,value) => { console.log("menu selected with",id,value); this.setState({ dishes : value['dishes'], menuId : id }); }; dishAddedHandler = (event) => { var reqs = this.state.requirements; reqs[event.target.name] = event.target.value; this.setState({requirements:reqs}); console.log(this.state.requirements); } render() { return ( <div> <MenuSelect source="http://localhost:8080/" onChange={this.menuSelectHandler} /> <br /> <Requirements dishes={this.state.dishes} onChange={this.dishAddedHandler}></Requirements> <Runner source="http://localhost:8080/" menuId={this.state.menuId} requirements={this.state.requirements} /> </div> ); } } export default App;
src/server.js
hirzanalhakim/testKumparan
import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import favicon from 'serve-favicon'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import httpProxy from 'http-proxy'; import path from 'path'; import VError from 'verror'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import { Provider } from 'components'; import config from 'config'; import createStore from 'redux/create'; import ApiClient from 'helpers/ApiClient'; import Html from 'helpers/Html'; import getRoutes from 'routes'; import { createApp } from 'app'; process.on('unhandledRejection', error => console.error(error)); const targetUrl = `http://${config.apiHost}:${config.apiPort}`; const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(cookieParser()); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.get('/manifest.json', (req, res) => res.sendFile(path.join(__dirname, '..', 'static', 'manifest.json'))); app.use('/dist/service-worker.js', (req, res, next) => { res.setHeader('Service-Worker-Allowed', '/'); return next(); }); app.use(express.static(path.join(__dirname, '..', 'static'))); app.use((req, res, next) => { res.setHeader('X-Forwarded-For', req.ip); return next(); }); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, { target: targetUrl }); }); app.use('/ws', (req, res) => { proxy.web(req, res, { target: `${targetUrl}/ws` }); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, { 'content-type': 'application/json' }); } const json = { error: 'proxy_error', reason: error.message }; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const providers = { client: new ApiClient(req), app: createApp(req), restApp: createApp(req) }; const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, providers); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send(`<!doctype html> ${ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store} />)}`); } if (__DISABLE_SSR__) { return hydrateOnClient(); } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { const redirect = to => { throw new VError({ name: 'RedirectError', info: { to } }); }; loadOnServer({ ...renderProps, store, helpers: { ...providers, redirect } }).then(() => { const component = ( <Provider store={store} app={providers.app} restApp={providers.restApp} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = { userAgent: req.headers['user-agent'] }; res.send(`<!doctype html> ${ReactDOM.renderToString( <Html assets={webpackIsomorphicTools.assets()} component={component} store={store} /> )}`); }).catch(mountError => { if (mountError.name === 'RedirectError') { return res.redirect(VError.info(mountError).to); } console.error('MOUNT ERROR:', pretty.render(mountError)); res.status(500); hydrateOnClient(); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, err => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/Col.js
jareth/react-materialize
import React from 'react'; import cx from 'classnames'; import constants from './constants'; class Col extends React.Component { render() { let {node, offset, className, children, ...props} = this.props; let C = node; let classes = {col: true}; constants.SIZES.forEach(s => { if (this.props[s]) { classes[s + this.props[s]] = true; } }); if (offset) { offset.split(' ').forEach(off => { classes['offset-' + off] = true; }); } return ( <C {...props} className={cx(classes, className)}> {children} </C> ); } } Col.propTypes = { /** * The node to be used for the column * @default div */ node: React.PropTypes.node.isRequired, /** * Columns for small size screens */ s: React.PropTypes.number, /** * Columns for middle size screens */ m: React.PropTypes.number, /** * Columns for large size screens */ l: React.PropTypes.number, /** * To offset, simply add s2 to the class where s signifies the screen * class-prefix (s = small, m = medium, l = large) and the number after * is the number of columns you want to offset by. */ offset: React.PropTypes.string } Col.defaultProps = {node: 'div'}; export default Col;
docs/src/components/Sidebar/Sidebar.js
abouthiroppy/scuba
import React from 'react'; import { Link } from 'react-router'; import { List, Item } from '../../../../src'; import links, { components as componentsLinks } from '../../linkslist'; import styles from './style'; const Sidebar = (props) => ( <div className={`sidebar ${styles.container}`}> <h3 style={{ margin: 0 }}><Link to={links[0].href}>{links[0].name}</Link></h3> <Link to={links[1].href}><p>{links[1].name}</p></Link> <Link to={links[2].href}><p>{links[2].name}</p></Link> <List type="none"> <Item><Link to="concept/colors">Colors</Link></Item> <Item><Link to="concept/typography">Typography</Link></Item> </List> <Link to={links[3].href}><p>{links[3].name}</p></Link> <List type="none"> { componentsLinks.map((item) => ( <Item key={item.name}> <Link to={`components/${item.href}`}>{item.name}</Link> </Item> )) } </List> </div> ); export default Sidebar;
src/js/components/form/bulk_edit_form.js
working-minds/realizejs
import React, { Component } from 'react'; import PropTypes from '../../prop_types'; import $ from 'jquery'; import { uuid } from '../../utils'; import { mixin } from '../../utils/decorators'; import { Container, Form, Input } from '../../components'; import { CssClassMixin } from '../../mixins'; @mixin(CssClassMixin) export default class BulkEditForm extends Component { static propTypes = { inputs: PropTypes.object, data: PropTypes.object, action: PropTypes.string, method: PropTypes.string, dataType: PropTypes.string, contentType: PropTypes.string, formStyle: PropTypes.string, resource: PropTypes.string, submitButton: PropTypes.object, otherButtons: PropTypes.array, isLoading: PropTypes.bool, onSubmit: PropTypes.func, onReset: PropTypes.func }; static defaultProps = { inputs: {}, data: {}, action: '', method: 'POST', dataType: undefined, contentType: undefined, submitButton: { name: 'Enviar', icon: 'send' }, otherButtons: [], isLoading: false, themeClassKey: 'form', formStyle: 'default', resource: null, onSubmit: function (event, postData) {}, onReset: function (event) {} }; constructor (props) { super(props); let disabled = []; for(var i = 0; i < this.props.inputGroups.length; i++ ) { var inputs = this.props.inputGroups[i].inputs; for(var inputId in inputs) { disabled.push(inputId); } } this.state = { disabled: disabled, inputKeys: this.generateInputIds() }; } renderChildren () { var inputComponents = []; for(var i = 0; i < this.props.inputGroups.length; i++ ) { var inputGroup = this.props.inputGroups[i]; this.generateInputs(inputComponents, inputGroup, i); } return inputComponents; } render () { var formProps = $.extend({}, this.props); delete formProps.inputGroups; return ( <Form {...formProps}> {this.renderChildren()} </Form> ); } generateInputIds (){ var idsMap = {}; for (var i = 0; i < this.props.inputGroups.length; i++ ){ var inputs = this.props.inputGroups[i].inputs; for(var inputId in inputs) idsMap[inputId] = "input_" + inputId + uuid.v4(); } return idsMap; } generateInputs (inputComponents, inputGroup, i) { var inputIndex = 0; var inputsProps = inputGroup.inputs; inputComponents.push(<h5 key={"header_" + i}>{inputGroup.label}</h5>); for (var inputId in inputsProps) { if (inputsProps.hasOwnProperty(inputId)) { var inputProps = inputsProps[inputId]; if (!inputProps.id) { inputProps.id = inputId; } inputProps.disabled = (this.state.disabled.indexOf(inputId) !== -1); var resourceName = inputGroup.resource || this.props.resource; var switchId = "enable"; if (!!resourceName) { switchId = switchId + "_" + resourceName } switchId = switchId + "_" + inputId; var switchName = "enable"; if (!!resourceName) { switchName = switchName + "[" + resourceName + "]" } switchName = switchName + "[" + inputId + "]"; if (inputId == 'ids') { inputComponents.push( <Input {...inputProps} disabled={false} data={this.props.data} resource={inputGroup.resource || this.props.resource} className="col m7 s10" key={"value_" + inputId} ref={"input_" + inputId} component='hidden' /> ); } else { inputComponents.push( <Container className="row" key={"container_" + inputId}> <InputSwitch id={switchId} name={switchName} onChange={this.handleSwitchChange} className="switch col l3 m3 s2" offLabel='' onLabel='' key={"switch_" + inputId} /> <Input {...inputProps} data={this.props.data} errors={this.props.errors} resource={inputGroup.resource || this.props.resource} formStyle={this.props.formStyle} className="input-field col offset-s1 l8 m8 s8" clearTheme={true} key={this.state.inputKeys[inputId]} ref={"input_" + inputId} /> </Container> ); inputIndex++; } } } return inputComponents; } handleSwitchChange (event) { var sw = event.target; var inputId = sw.id.replace(/^enable_/, ''); if (sw.name.indexOf('[') !== -1){ inputId = sw.name.split('[').pop().replace(']', ''); } var disabled = $.extend([], this.state.disabled); if(!sw.checked) { disabled.push(inputId); } else { disabled.splice(disabled.indexOf(inputId), 1); } var inputKeys = this.state.inputKeys; inputKeys[inputId] = "input_" + inputId + uuid.v4(); this.setState( { disabled: disabled, inputKeys: inputKeys }); } }
fields/types/relationship/RelationshipField.js
benkroeger/keystone
import async from 'async'; import Field from '../Field'; import { listsByKey } from '../../../admin/client/utils/lists'; import React from 'react'; import Select from 'react-select'; import xhr from 'xhr'; import { Button, FormInput, InlineGroup as Group, InlineGroupSection as Section, } from '../../../admin/client/App/elemental'; import _ from 'lodash'; function compareValues (current, next) { const currentLength = current ? current.length : 0; const nextLength = next ? next.length : 0; if (currentLength !== nextLength) return false; for (let i = 0; i < currentLength; i++) { if (current[i] !== next[i]) return false; } return true; } module.exports = Field.create({ displayName: 'RelationshipField', statics: { type: 'Relationship', }, getInitialState () { return { value: null, createIsOpen: false, }; }, componentDidMount () { this._itemsCache = {}; this.loadValue(this.props.value); }, componentWillReceiveProps (nextProps) { if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return; this.loadValue(nextProps.value); }, shouldCollapse () { if (this.props.many) { // many:true relationships have an Array for a value return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, buildFilters () { var filters = {}; _.forEach(this.props.filters, (value, key) => { if (typeof value === 'string' && value[0] === ':') { var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === '_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, cacheItem (item) { item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id; this._itemsCache[item.id] = item; }, loadValue (values) { if (!values) { return this.setState({ loading: false, value: null, }); }; values = Array.isArray(values) ? values : values.split(','); const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i); if (cachedValues.length === values.length) { this.setState({ loading: false, value: this.props.many ? cachedValues : cachedValues[0], }); return; } this.setState({ loading: true, value: null, }); async.map(values, (value, done) => { xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, expanded) => { if (!this.isMounted()) return; this.setState({ loading: false, value: this.props.many ? expanded : expanded[0], }); }); }, // NOTE: this seems like the wrong way to add options to the Select loadOptionsCallback: {}, loadOptions (input, callback) { // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback = callback; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading items:', err); return callback(null, []); } data.results.forEach(this.cacheItem); callback(null, { options: data.results, complete: data.results.length === data.count, }); }); }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, openCreate () { this.setState({ createIsOpen: true, }); }, closeCreate () { this.setState({ createIsOpen: false, }); }, onCreate (item) { this.cacheItem(item); if (Array.isArray(this.state.value)) { // For many relationships, append the new item to the end const values = this.state.value.map((item) => item.id); values.push(item.id); this.valueChanged(values.join(',')); } else { this.valueChanged(item.id); } // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback(null, { complete: true, options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]), }); this.closeCreate(); }, renderSelect (noedit) { return ( <div> {/* This input element fools Safari's autocorrect in certain situations that completely break react-select */} <input type="text" style={{ position: 'absolute', width: 1, height: 1, zIndex: -1, opacity: 0 }} tabIndex="-1"/> <Select.Async multi={this.props.many} disabled={noedit} loadOptions={this.loadOptions} labelKey="name" name={this.getInputName(this.props.path)} onChange={this.valueChanged} simpleValue value={this.state.value} valueKey="id" /> </div> ); }, renderInputGroup () { // TODO: find better solution // when importing the CreateForm using: import CreateForm from '../../../admin/client/App/shared/CreateForm'; // CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it: // http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native // TODO: Implement this somewhere higher in the app, it breaks the encapsulation of the RelationshipField component const CreateForm = require('../../../admin/client/App/shared/CreateForm'); return ( <Group block> <Section grow> {this.renderSelect()} </Section> <Section> <Button onClick={this.openCreate}>+</Button> </Section> <CreateForm list={listsByKey[this.props.refList.key]} isOpen={this.state.createIsOpen} onCreate={this.onCreate} onCancel={this.closeCreate} /> </Group> ); }, renderValue () { const { many } = this.props; const { value } = this.state; const props = { children: value ? value.name : null, component: value ? 'a' : 'span', href: value ? value.href : null, noedit: true, }; return many ? this.renderSelect(true) : <FormInput {...props} />; }, renderField () { if (this.props.createInline) { return this.renderInputGroup(); } else { return this.renderSelect(); } }, });
src/components/explorer/results/QueryAttentionOverTimeResultsContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import MenuItem from '@material-ui/core/MenuItem'; import Divider from '@material-ui/core/Divider'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import { fetchQuerySplitStoryCount, setSentenceDataPoint, resetSentenceDataPoint } from '../../../actions/explorerActions'; import withLoginRequired from '../../common/hocs/LoginRequiredDialog'; import withAttentionAggregation from '../../common/hocs/AttentionAggregation'; import withSummary from '../../common/hocs/SummarizedVizualization'; import withQueryResults from './QueryResultsSelector'; import AttentionOverTimeChart, { dataAsSeries } from '../../vis/AttentionOverTimeChart'; import { DownloadButton } from '../../common/IconButton'; import ActionMenu from '../../common/ActionMenu'; import { oneDayLater, solrFormat } from '../../../lib/dateUtil'; import { postToDownloadUrl, postToCombinedDownloadUrl, ACTION_MENU_ITEM_CLASS, ensureSafeResults, serializeSearchTags } from '../../../lib/explorerUtil'; import messages from '../../../resources/messages'; import { FETCH_INVALID } from '../../../lib/fetchConstants'; const localMessages = { overallSeries: { id: 'explorer.attention.series.overall', defaultMessage: 'Whole Query' }, lineChartTitle: { id: 'explorer.attention.lineChart.title', defaultMessage: 'Attention Over Time' }, descriptionIntro: { id: 'explorer.attention.lineChart.intro', defaultMessage: '<p>Compare the attention paid to your queries over time to understand how they are covered. This chart shows the number of stories that match each of your queries. Spikes in attention can reveal key events. Plateaus can reveal stable, "normal", attention levels. Click a point to see words and headlines for those dates. Use the "view options" menu to switch between story counts and a percentage.</p>' }, descriptionDetail: { id: 'explorer.attention.lineChart.detail', defaultMessage: '<p>This chart includes one line for each query in your search. Each line charts the number of stories that matched your query per day in the sources and collections you have specified.</p><p>Roll over the line chart to see the stories per day in that period of time. Click the download button in the top right to download the raw counts in a CSV spreadsheet. Click the three lines in the top right of the chart to export the chart as an image file.</p>' }, withKeywords: { id: 'explorer.attention.mode.withkeywords', defaultMessage: 'View Story Count (default)' }, withoutKeywords: { id: 'explorer.attention.mode.withoutkeywords', defaultMessage: 'View Normalized Story Percentage' }, downloadCsv: { id: 'explorer.attention.downloadCsv', defaultMessage: 'Download { name } story count over time CSV' }, downloadAllCsv: { id: 'explorer.attention.downloadAllCsv', defaultMessage: 'Download all story counts over time CSV' }, }; const VIEW_NORMALIZED = 'VIEW_NORMALIZED'; const VIEW_REGULAR = 'VIEW_REGULAR'; class QueryAttentionOverTimeResultsContainer extends React.Component { state = { view: VIEW_REGULAR, // which view to show (see view constants above) } setView = (nextView) => { this.setState({ view: nextView }); } handleDataPointClick = (startDate, endDate, evt, chartObj, point0x, point1x, pointValue) => { const { isLoggedIn, selectDataPoint, queries, onShowLoginDialog } = this.props; if (isLoggedIn) { const { name } = chartObj.series; const currentQueryOfInterest = queries.filter(qry => qry.label === name)[0]; const dayGap = 1; // TODO: harcoded for now because we are always showing daily results // date calculations for span/range const dataPoint = { q: currentQueryOfInterest.q, start_date: solrFormat(startDate), color: chartObj.series.color, dayGap, sources: currentQueryOfInterest.sources.map(s => s.media_id), collections: currentQueryOfInterest.collections.map(c => c.tags_id), searches: serializeSearchTags(currentQueryOfInterest.searches), // for each query, go prep searches }; dataPoint.end_date = solrFormat(oneDayLater(endDate), true); selectDataPoint({ dataPoint, point0x, pointValue }); } else { onShowLoginDialog(); } } downloadCsv = (query) => { postToDownloadUrl('/api/explorer/stories/split-count.csv', query); } downloadAllQueriesCsv = (queries) => { postToCombinedDownloadUrl('/api/explorer/stories/split-count-all.csv', queries); } render() { const { results, queries, selectedTimePeriod } = this.props; // stich together bubble chart data // because these results are indexed, we can merge these two arrays // we may have more results than queries b/c queries can be deleted but not executed // so we have to do the following let series = []; const safeResults = ensureSafeResults(queries, results); if (safeResults) { series = [ ...safeResults.map((query, idx) => { // add series for all the results if (query.results && (query.results.counts || query.results.normalizedCounts)) { let data; if (this.state.view === VIEW_NORMALIZED) { data = dataAsSeries(query.results.counts, 'ratio'); } else { data = dataAsSeries(query.results.counts); } return { id: idx, name: query.label, ...data, color: query.color, }; } return {}; }), ]; return ( <> <AttentionOverTimeChart series={series} height={300} backgroundColor="#f5f5f5" onDataPointClick={this.handleDataPointClick} normalizeYAxis={this.state.view === VIEW_NORMALIZED} interval={selectedTimePeriod} /> <div className="actions"> <ActionMenu actionTextMsg={messages.downloadOptions}> {safeResults.map((q, idx) => ( <MenuItem key={idx} className={ACTION_MENU_ITEM_CLASS} onClick={() => this.downloadCsv(q)} > <ListItemText> <FormattedMessage {...localMessages.downloadCsv} values={{ name: q.label }} /> </ListItemText> <ListItemIcon> <DownloadButton /> </ListItemIcon> </MenuItem> ))} <MenuItem key="all" className={ACTION_MENU_ITEM_CLASS} onClick={() => this.downloadAllQueriesCsv(queries)} > <ListItemText> <FormattedMessage {...localMessages.downloadAllCsv} /> </ListItemText> <ListItemIcon> <DownloadButton /> </ListItemIcon> </MenuItem> </ActionMenu> <ActionMenu actionTextMsg={messages.viewOptions}> <MenuItem className={ACTION_MENU_ITEM_CLASS} disabled={this.state.view === VIEW_REGULAR} onClick={() => this.setView(VIEW_REGULAR)} > <ListItemText> <FormattedMessage {...localMessages.withKeywords} /> </ListItemText> </MenuItem> <MenuItem className={ACTION_MENU_ITEM_CLASS} disabled={this.state.view === VIEW_NORMALIZED} onClick={() => this.setView(VIEW_NORMALIZED)} > <ListItemText> <FormattedMessage {...localMessages.withoutKeywords} /> </ListItemText> </MenuItem> <Divider /> {this.props.attentionAggregationMenuItems} </ActionMenu> </div> </> ); } return <div>Error</div>; } } QueryAttentionOverTimeResultsContainer.propTypes = { // from parent lastSearchTime: PropTypes.number.isRequired, queries: PropTypes.array.isRequired, isLoggedIn: PropTypes.bool.isRequired, // from hocs intl: PropTypes.object.isRequired, onShowLoginDialog: PropTypes.func.isRequired, attentionAggregationMenuItems: PropTypes.array.isRequired, selectedTimePeriod: PropTypes.string.isRequired, // from dispatch results: PropTypes.object.isRequired, daySpread: PropTypes.bool, // from state fetchStatus: PropTypes.string.isRequired, selectDataPoint: PropTypes.func.isRequired, tabSelector: PropTypes.object, selectedTabIndex: PropTypes.number, }; const mapStateToProps = state => ({ lastSearchTime: state.explorer.lastSearchTime.time, fetchStatus: state.explorer.storySplitCount.fetchStatus || FETCH_INVALID, results: state.explorer.storySplitCount.results, }); const mapDispatchToProps = dispatch => ({ selectDataPoint: (clickedDataPoint) => { dispatch(resetSentenceDataPoint()); dispatch(setSentenceDataPoint(clickedDataPoint)); }, }); function mergeProps(stateProps, dispatchProps, ownProps) { return { ...stateProps, ...dispatchProps, ...ownProps, shouldUpdate: (nextProps) => { // QueryResultsSelector needs to ask the child for internal repainting const { selectedTimePeriod } = stateProps; return nextProps.selectedTimePeriod !== selectedTimePeriod; } }; } export default injectIntl( connect(mapStateToProps, mapDispatchToProps, mergeProps)( withSummary(localMessages.lineChartTitle, localMessages.descriptionIntro, [localMessages.descriptionDetail, messages.countsVsPercentageHelp])( withAttentionAggregation( withQueryResults(fetchQuerySplitStoryCount)( withLoginRequired( QueryAttentionOverTimeResultsContainer ) ) ) ) ) );
internals/templates/notFoundPage/notFoundPage.js
itimofeev/hustledb-ui
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/sliders/VerticalSlider.js
sk1981/react-header
import React from 'react'; import SliderToggle from './SliderToggle'; /** * A vertical slide menu which spans full vertical width and slides horizontally */ class VerticalSlider extends React.Component { constructor(props) { super(props); this.state = {draw: false}; this.drawSlider = this.drawSlider.bind(this); this.handleDocumentClickEvent = this.handleDocumentClickEvent.bind(this); } /** * Gets the top bar along with the titleComponent * * In general title component should be the same as the logo * * @returns {XML} */ getTopBar(isDrawn) { return ( <div className="vertical-slider__top"> {this.props.titleComponent} <SliderToggle toggleOpen={isDrawn} onSliderToggle={this.drawSlider}/> </div> ); } /** * Gets the sub menu bar which is used for opening the submenu * * @param isDrawn * @returns {XML} */ getSubMenuBar(isDrawn) { return ( <div aria-label="Sub Menu" aria-haspopup="true" aria-pressed={`${isDrawn}`} aria-expanded={`${isDrawn}`} role="button" className="vertical-slider__title" onClick={this.drawSlider}> {this.props.title} </div> ); } /** * Toggles the slider */ drawSlider() { this.updateSliderDraw(!this.state.draw); } /** * Updates the draw state of the slider by changing the state * @param draw */ updateSliderDraw(draw) { this.setState({ draw: draw }); } /** * Handles clicks on the document * * Used for closing the slider if the click happens outside the slider container container * * @param clickEvent */ handleDocumentClickEvent(clickEvent) { if(this.state.draw) { const target = clickEvent.target; if (this.sliderElement.contains) { // If click outside slider close it if (!this.sliderElement.contains(target)) { this.updateSliderDraw(false); } else { // If a link tag is clicked, close the slider // TODO : Replace with a close event which is propagated down if(target.tagName.toLowerCase() === 'a' && target.href) { this.updateSliderDraw(false); } } } } } /** * Used for registering clicks on document body */ componentDidMount() { // Only register for the main slider to avoid extra events document.addEventListener("click", this.handleDocumentClickEvent) } /** * Used for registering clicks on document body */ componentWillUnmount() { document.removeEventListener("click", this.handleDocumentClickEvent) } /** * Gets the children present in a slider. * * All it does is adds a "Back" element to the list of children * so as to go back to the original slider. * * @param isSubSlider * @param children * @returns {*} */ getSliderChild(isSubSlider, children) { if(isSubSlider) { return [<div key="back" onClick={this.drawSlider} className="vertical-slider__back">Back</div>].concat(children) } else { return children; } } /** * * Renders a vertical slider either as a top level slider or a child level slider. * * It is a bit fragile approach - it sets the top level slider as fixes and any child level slider as absolute. * It also uses the top level fixed slider as a reference, which means all other properties between these * should have position relative. * * Ideal approach should have been to use 'fixed' for both child and parent sliders, but due to issues in * render in different browsers, had to take this approach. * * Should re-visit this later - maybe extract out child and pull all of them in one hierarchy * * @returns {XML} */ render() { const isDrawn = this.state.draw; const {isSubSlider, headerHeight, windowWidth, windowHeight} = this.props; const drawnClass = isDrawn ? 'vertical-slider--drawn' : ''; const sliderLevelClass = isSubSlider ? 'vertical-slider--sub': 'vertical-slider--main'; // Get slider width which is a particular fraction of window width upto a given max width const width = Math.min(Math.floor(windowWidth * this.props.sliderWidthFraction), this.props.sliderWidthMax); const childStyles = { transform: `translateX(${isDrawn ? '0' : `-${width}px`})`, height: `${windowHeight - headerHeight}px`, width: `${width}px`, top: isSubSlider ? 0: `${headerHeight}px` , left: 0, position: isSubSlider ? 'absolute' : 'fixed' }; return ( <div ref={(ref)=> this.sliderElement = ref} className={`vertical-slider ${drawnClass} ${sliderLevelClass}`}> {isSubSlider ? this.getSubMenuBar(isDrawn): this.getTopBar(isDrawn)} <div aria-hidden={!isDrawn} style={childStyles} className="vertical-slider--children"> {this.getSliderChild(isSubSlider, this.props.children)} </div> </div> ); } } VerticalSlider.propTypes = { titleComponent: React.PropTypes.element, title: React.PropTypes.string, children: React.PropTypes.oneOfType([ React.PropTypes.element, React.PropTypes.array ]).isRequired, windowWidth: React.PropTypes.number, windowHeight: React.PropTypes.number, headerHeight: React.PropTypes.number, /** * Width of the Vertical slider as a fraction of window width */ sliderWidthFraction: React.PropTypes.number, /** * Max width of the slider */ sliderWidthMax: React.PropTypes.number, isSubSlider: React.PropTypes.bool }; VerticalSlider.defaultProps = { sliderWidthFraction: 0.75, sliderWidthMax: 400 }; export default VerticalSlider;
app/components/layout/Navigation/MyBuilds/build.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; import styled from 'styled-components'; import Emojify from 'app/components/shared/Emojify'; import Duration from 'app/components/shared/Duration'; import PusherStore from 'app/stores/PusherStore'; import CentrifugeStore from 'app/stores/CentrifugeStore'; import BuildState from 'app/components/icons/BuildState'; import { buildStatus } from 'app/lib/builds'; import { shortMessage } from 'app/lib/commits'; import { getDateString } from 'app/lib/date'; const BuildLink = styled.a.attrs({ className: 'flex text-decoration-none dark-gray hover-lime mb2' })` &:hover .build-link-message { color: inherit; } `; class BuildsDropdownBuild extends React.PureComponent { static propTypes = { build: PropTypes.object, relay: PropTypes.object.isRequired } componentDidMount() { PusherStore.on("websocket:event", this.handleWebsocketEvent); CentrifugeStore.on("websocket:event", this.handleWebsocketEvent); } componentWillUnmount() { PusherStore.off("websocket:event", this.handleWebsocketEvent); CentrifugeStore.off("websocket:event", this.handleWebsocketEvent); } handleWebsocketEvent = (payload) => { if (payload.subevent === "build:updated" && payload.graphql.id === this.props.build.id) { this.props.relay.forceFetch(); } }; render() { const buildTime = buildStatus(this.props.build).timeValue; const buildTimeAbsolute = getDateString(buildTime); return ( <BuildLink href={this.props.build.url}> <div className="pr2 center"> <BuildState.Small className="block" state={this.props.build.state} /> </div> <div className="flex-auto"> <span className="block line-height-3 overflow-hidden overflow-ellipsis"> <Emojify className="build-link-message semi-bold black" text={shortMessage(this.props.build.message)} /> {' in '} <Emojify className="build-link-message semi-bold black" text={shortMessage(this.props.build.pipeline.name)} /> </span> <span className="block" title={buildTimeAbsolute}> <Duration.Medium from={buildTime} tabularNumerals={false} /> ago </span> </div> </BuildLink> ); } } export default Relay.createContainer(BuildsDropdownBuild, { fragments: { build: () => Relay.QL` fragment on Build { id message state createdAt canceledAt finishedAt url commit pipeline { name } } ` } });
packages/wix-style-react/src/common/FluidColumns/FluidColumns.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import { dataHooks } from './constants'; import { st, classes, vars } from './FluidColumns.st.css'; /** A fluid columns component*/ class FluidColumns extends React.PureComponent { render() { const { dataHook, className, cols, children } = this.props; return ( <div className={st(classes.root, className)} data-hook={dataHook} style={{ [vars.cols]: cols }} > {React.Children.map(children, (child, index) => { return ( <div key={index} data-hook={dataHooks.item} className={classes.item} > {child} </div> ); })} </div> ); } } FluidColumns.displayName = 'FluidColumns'; FluidColumns.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** A css class to be applied to the component's root element */ className: PropTypes.string, /** Define the number of columns. It is used for the grid in order to define how many features will be displayed in a row. The default value is 3. */ cols: PropTypes.number, /** Children to render. */ children: PropTypes.node.isRequired, }; FluidColumns.defaultProps = { cols: 3, }; export default FluidColumns;
client/components/admin/layout/nav.js
ShannChiang/USzhejiang
import React from 'react'; import {Link} from 'react-router'; export default (props) => ( <div> <div className="color-line"> </div> <div id="logo" className="light-version"> <span> {props.appName} </span> </div> <nav role="navigation"> <Link to="#" className="header-link hide-menu" onClick={(e) => props.sidebar(e)}><i className="fa fa-bars" /></Link> <div className="small-logo"> <span className="text-primary">{props.appName}</span> </div> <div className="mobile-menu"> <button type="button" className="navbar-toggle mobile-menu-toggle" data-toggle="collapse" data-target="#mobile-collapse"> <i className="fa fa-chevron-down" /> </button> <div className="collapse mobile-navbar" id="mobile-collapse"> <ul className="nav navbar-nav"> <li> <Link to="/" className="" onClick={(e) => Meteor.logout()}>退出</Link> </li> <li> <Link className="" to="/">回到主页</Link> </li> </ul> </div> </div> <div className="navbar-right"> <Link to="/" className="btn btn-info" style={{margin: '10px 20px'}}>回到主页<i className="pe-7s-upload pe-rotate-90" /></Link> </div> </nav> </div> );
components/Section.js
rickysahu/mpngen
// Container for a specific question import React from 'react' import Formsy from 'formsy-react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import Paper from 'material-ui/Paper'; import RaisedButton from 'material-ui/RaisedButton'; import MenuItem from 'material-ui/MenuItem'; import { FormsyCheckbox, FormsyCheckboxGroup, FormsyDate, FormsyRadio, FormsyRadioGroup, FormsySelect, FormsyText, FormsyTime, FormsyToggle, FormsyAutoComplete } from 'formsy-material-ui/lib'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; import AutoComplete from 'material-ui/AutoComplete'; import Checkbox from 'material-ui/Checkbox'; import ReactMarkdown from 'react-markdown'; import templates from '../fixtures/templates'; let styles = { questionHeader: { fontSize: '1.5rem', lineHeight: '2rem', color: '#3dace3' }, paperStyle: { margin: '2rem .5rem', textAlign: 'left', float: 'left', display: 'inline-block', maxWidth: 500, minWidth: 300, padding: '1rem 2rem', }, paperMDStyle: { margin: '2rem .5rem', textAlign: 'left', float: 'left', display: 'inline-block', maxWidth: 400, minWidth: 200, padding: '1rem 1rem', }, switchStyle: { marginTop: '.2rem', }, submitStyle: { marginTop: 32, }, } export default class extends React.Component { getMyData () { this.setState({formData: this.refs.form.getModel()}); } // check which questions have valid answers. // specifically needed for checkbox group which doesnt have 'required' support in formsy getInvalidQuestions (answers) { let questionValid = {} if (typeof answers === 'undefined') { return ['no questions answered'] } Object.keys(answers).map(function(input){ let qName = input.split('-')[1] let value = answers[input] if (typeof questionValid[qName] === 'undefined' || questionValid[qName] === false) { if (typeof value === 'boolean') { questionValid[qName] = value } else if (typeof value !== 'undefined' && value.trim().length > 0) { questionValid[qName] = true } else { questionValid[qName] = false } } }.bind(this)) let unansweredCheckboxes = Array.from(new Set(Object.keys(questionValid).map(function(k){if(questionValid[k] === false){return k}}))).filter(f=>f) Object.keys(answers).map(function(fieldName){ if(answers[fieldName] === '' && fieldName.indexOf('other') === -1 && fieldName.indexOf('-') === -1){ unansweredCheckboxes.push(fieldName) } }) return unansweredCheckboxes } enableButton() { this.getMyData() let invalidQuestions = this.getInvalidQuestions(this.refs.form.getModel()) // console.log(invalidQuestions) if (invalidQuestions.length === 0){ let stateForParent = {form: this.refs.form.getModel(), canSubmit: true} this.props.setParentState(this.props.id, stateForParent) this.setState({canSubmit: true, invalidQuestions: invalidQuestions}); } else { let stateForParent = {form: this.refs.form.getModel(), canSubmit: false} this.props.setParentState(this.props.id, stateForParent) this.setState({canSubmit: false, invalidQuestions: invalidQuestions}) } } disableButton() { this.getMyData() let invalidQuestions = this.getInvalidQuestions(this.refs.form.getModel()) if (this.state.canSubmit) { let stateForParent = {form: this.refs.form.getModel(), canSubmit: false} this.props.setParentState(this.props.id, stateForParent) } this.setState({ canSubmit: false, invalidQuestions: invalidQuestions }); } getColorOfField(fieldName) { // console.log(this.state.invalidQuestions) if(typeof this.state.invalidQuestions === 'undefined' || this.state.invalidQuestions.length > 3) { return '#fff' } else if (this.state.invalidQuestions.indexOf(fieldName) >= 0 && this.state.invalidQuestions.length < 3) { return '#ffdada' } else { return '#fff' } } constructor (props) { super(props) this.state = {} } changeOtherValue (e) { e.preventDefault(); let otherCheckbox = e.target.name.split('-').slice(0,-1).join('-') this.state[otherCheckbox] = e.target.value } render () { return <div style={{width: '100%', display: 'inline-block', textAlign:'center'}}> <div id={this.props.id}></div> <div> <MuiThemeProvider muiTheme={getMuiTheme({palette: {primary1Color: '#3dace3'}})}> <Formsy.Form onValid={this.enableButton.bind(this)} onInvalid={this.disableButton.bind(this)} onValidSubmit={this.submitForm} onInvalidSubmit={this.notifyFormError} style={{display: 'inline-block'}} ref="form" > <br /><br /> <div style={styles.paperStyle}> <Toolbar style={{borderRadius: '2px 2px 0px 0px',margin: '-1rem -2rem 2rem -2rem',backgroundColor: '#fff'}}> <ToolbarGroup> <ToolbarTitle text={this.props.title} style={{fontSize: '2.5rem', color: this.state.canSubmit ? '#7fda85' : '#7f7f7f'}} /> </ToolbarGroup> </Toolbar> {this.props.questions.map(function(q){ if(typeof q.showif !== 'undefined' && this.state.formData){ if(q.showif.value.indexOf(this.state.formData[q.showif.field]) === -1) { return '' } } if(["text", "email"].indexOf(q.formType) >= 0) { return <div style={{backgroundColor: this.getColorOfField(q.name), padding: '.0rem .1rem', transition: 'background 1s linear'}}> {q.header ? <div style={styles.questionHeader}><span><br />{q.header}</span></div> : <span></span> } {q.helper ? <h4 style={{marginBottom: '0px', lineHeight: '1.5rem'}}>{q.helper}</h4> : <span></span> } <FormsyText name={this.props.id + "-"+ q.name} type={q.inputType || "text"} validations={q.validations} required={q.required} validationError={q.validationError} hintText={q.hintText} fullWidth={true} multiLine={q.multiLine ? true : false} rows={q.multiLine ? 2 : 1} onKeyDown={ this.keyDownText } style={q.style} floatingLabelText={q.label} /> </div> } else if (q.formType === "autocomplete") { return <FormsyAutoComplete name={this.props.id + "-"+ q.name} type={q.inputType || "text"} required={q.required} hintText={q.hintText} dataSource={q.dataSource} fullWidth={true} openOnFocus={true} style={{backgroundColor: this.getColorOfField(q.name), padding: '.0rem .1rem', transition: 'background 1s linear'}} filter={AutoComplete.fuzzyFilter} floatingLabelText={q.label} /> } else if (q.formType === "radio") { return <div style={{backgroundColor: this.getColorOfField(q.name), padding: '0rem .1rem', transition: 'background 1s linear'}}> <div style={styles.questionHeader}>{q.header ? <span><br />{q.header}</span> : ''}</div> <h4 style={{lineHeight: '1.5rem'}}>{q.label}</h4> <FormsyRadioGroup name={this.props.id + "-"+ q.name} required label={q.label} > {q.choices.map(function(choice){ return <FormsyRadio value={choice.value} label={choice.label} style={styles.switchStyle} /> })} </FormsyRadioGroup> </div> } else if (q.formType === "checkbox") { return <div style={{backgroundColor: this.getColorOfField(q.name), padding: '0rem .1rem', transition: 'background 1s linear'}}> <div style={styles.questionHeader}>{q.header ? <span><br />{q.header}</span> : ''}</div> <h4 style={{lineHeight: '1.5rem'}}>{q.label}</h4> {q.choices.map(function(choice){ if(choice.label === 'Other'){ return <div> <span style={{display: 'inline-block', marginTop:'0rem'}}> <Checkbox checked={typeof this.state[this.props.id+"-"+q.name+"-"+choice.value] !== 'undefined' && this.state[this.props.id+"-"+q.name+"-"+choice.value].trim().length > 0} label={'Other:'} style={{ display: 'inline-block', width: '6rem' }} /> </span> <span style={{display: 'inline-block'}}> <FormsyText id={this.props.id+"-"+q.name+"-"+choice.value+"-text"} name={this.props.id+"-"+q.name+"-"+choice.value+"-text"} type={"text"} onChange={this.changeOtherValue.bind(this)} required={false} hintText={'fill in to check "other" option'} style={{position: 'relative', lineHeight:'inherit', top:'-.4rem'}} fullWidth={false} /> </span> </div> } else { return <FormsyCheckbox name={this.props.id+"-"+q.name+"-"+choice.value} label={choice.label} style={styles.switchStyle} /> } }.bind(this))} </div> } else { return <div style={styles.questionHeader}>{q.header ? <span><br />{q.header}</span> : ''}</div> } }.bind(this))} <div dangerouslySetInnerHTML={{__html: Array(120).fill(`&nbsp; `).join('')}} /> </div> </Formsy.Form> </MuiThemeProvider> <div style={{display: 'inline-block', fontSize: '.8rem'}}> <br /><br /> <MuiThemeProvider muiTheme={getMuiTheme({palette: {primary1Color: '#3dace3'}})}> <Paper style={styles.paperMDStyle}> <Toolbar style={{borderRadius: '2px 2px 0px 0px',margin: '-1rem -1rem 0rem -1rem',backgroundColor: this.state.canSubmit ? '#7fda85' : '#eee'}}> <ToolbarGroup> <ToolbarTitle text={this.props.title + ' (Preview)'} /> </ToolbarGroup> </Toolbar> <ReactMarkdown source={templates['header'].styles({})+templates[this.props.id].f(this.state.formData)}/> </Paper> </MuiThemeProvider> </div> </div> </div> } } // {JSON.stringify(this.state)}
src/index.js
BenzLeung/private-music-client-web
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; /*import loggerMiddleware from 'redux-logger';*/ import reducer from './redux/reducer'; import App from './presentation/App/App'; import 'normalize.css'; import './index.css'; let store = createStore(reducer, applyMiddleware(thunkMiddleware/*, loggerMiddleware*/)); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
examples/MenuMethodsExample.js
instea/react-native-popup-menu
import React, { Component } from 'react'; import { Text, TouchableOpacity } from 'react-native'; import Menu, { MenuProvider, MenuOptions, MenuOption, MenuTrigger, withMenuContext, } from 'react-native-popup-menu'; const Openner = (props) => ( <TouchableOpacity style={{ paddingTop: 50 }} onPress={() => props.ctx.menuActions.openMenu('menu-1')}> <Text>Open menu from context</Text> </TouchableOpacity> ); const ContextOpenner = withMenuContext(Openner); export default class ControlledExample extends Component { onOptionSelect(value) { alert(`Selected number: ${value}`); if (value === 1) { this.menu.close(); } return false; } openMenu() { this.menu.open(); } onRef = r => { this.menu = r; } render() { return ( <MenuProvider style={{flexDirection: 'column', padding: 30}}> <Menu onSelect={value => this.onOptionSelect(value)} name="menu-1" ref={this.onRef}> <MenuTrigger text='Select option'/> <MenuOptions> <MenuOption value={1} text='One' /> <MenuOption value={2} text='Two (not closing)' /> </MenuOptions> </Menu> <TouchableOpacity style={{ paddingTop: 50 }} onPress={() => this.openMenu()}> <Text>Open menu from outside</Text> </TouchableOpacity> <ContextOpenner /> </MenuProvider> ); } }
src/BootstrapMixin.js
IveWong/react-bootstrap
import React from 'react'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const BootstrapMixin = { propTypes: { /** * bootstrap className * @private */ bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES), /** * Style variants * @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")} */ bsStyle: React.PropTypes.oneOf(styleMaps.STYLES), /** * Size variants * @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")} */ bsSize: CustomPropTypes.keyOf(styleMaps.SIZES) }, getBsClassSet() { let classes = {}; let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; let prefix = bsClass + '-'; let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } if (this.props.bsStyle) { if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) { classes[prefix + this.props.bsStyle] = true; } else { classes[this.props.bsStyle] = true; } } } return classes; }, prefixClass(subClass) { return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass; } }; export default BootstrapMixin;
src/components/ApiMethod.js
evaisse/swagger-open-api-ui
import React, { Component } from 'react'; import Form from "react-jsonschema-form"; import request from 'xhr-request'; import classNames from "classnames"; import ApiTransactionReport from './ApiTransactionReport'; import jwtDecode from "jwt-decode"; class ApiMethod extends Component { constructor(props) { super(props); this.state = { method: props.method, deployed: false, response: null, error: null, xhr: null, isRunning: false, formData: {} }; } handleSchemaFormChange() { } handleSchemaFormSubmit(apiMethod, form) { var api = this.props.app.state.api; var uri = `${api.schemes[0]}://${api.host}${api.basePath}${apiMethod.path}`; var options = { dataType: 'json', responseType: 'json', cache: false, withCredentials: true, headers: { 'Authorization': `Bearer ${this.props.app.state.authInfos.state.token}`, } }; var r; this.setState({ formData: form.formData }); this.sendFetchRequest({ apiMethod: apiMethod, uri: uri, form: form, options: { dataType: 'json', responseType: 'json', cache: false, withCredentials: true, headers: { 'Authorization': `Bearer ${this.props.app.state.authInfos.state.token}`, } } }); // qwest[apiMethod.verb](uri, form.formData, options) // .then((xhr, response) => { // r = xhr; // xhr.request = { uri, data: form.formData, options }; // this.setState({ error: false, xhr, response }); // }) // .catch((error, xhr, response) => { // r = xhr; // xhr.request = { uri, data: form.formData, options }; // this.setState({ error, xhr, response }); // }) // .complete(() => { // this.setState({ isRunning: false }); // try { // if (headerAuth.match(/^Bearer\s+(.*)$/)[1] == this.props.app.state.authInfos.state.token) { // var token = r.getResponseHeader('Authorization').match(/^Bearer\s+(.*)$/)[1]; // this.props.app.state.authInfos.setState({ token }); // } // } catch (e) { // } // }); } sendFetchRequest({ apiMethod, uri, form, options }) { var fetchEvent; let data = {...form.formData}; let headers = new Headers(Object.assign({}, { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.props.app.state.authInfos.state.token}` })); let fetchInit = { method: apiMethod.verb.toUpperCase(), headers: headers, mode: 'cors', cache: 'default' }; let pathParams = uri.match(/\{\w+\}/ig) || []; pathParams.forEach((m) => { let k = m.match(/\{(\w+)\}/)[1]; uri = uri.replace(m, data[m.match(/\{(\w+)\}/)[1]]); delete data[m]; }); debugger; if (fetchInit.method.match(/GET|HEAD/)) { uri += "?" + JSON.stringify(data); } else { fetchInit.body = JSON.stringify(data); } fetchEvent = { isRunning: true, error: null, request: { uri, headers, body: fetchInit.body, data: data }, response: null }; this.setState({...fetchEvent}); fetchEvent = fetch(uri, fetchInit).then((res) => { this.setState({ ...fetchEvent, response: res, isRunning: false }); this.handleAuthorizationUpdate(res); }).catch((error) => { this.setState({ ...fetchEvent, error: error, isRunning: false }); }); console.log(fetchEvent); } handleSchemaFormErrors() { } handleAuthorizationUpdate(response) { let headerAuth = response.headers.get('authorization') || ''; console.log(headerAuth, headerAuth.match(/^Bearer\s+(.*)$/)[1] == this.props.app.state.authInfos.state.token); if (headerAuth.match(/^Bearer\s+(.*)$/)[1] != this.props.app.state.authInfos.state.token) { var token = headerAuth.match(/^Bearer\s+(.*)$/)[1]; this.props.app.state.authInfos.setState({ token }); } } render() { var m = this.state.method; return ( <div className="api method panel panel-default" key={ m.key }> <div className="panel-heading" onClick={ (e) => { this.setState({ deployed: !this.state.deployed }); }}> <span className="label label-default">{ m.verb.toUpperCase() }</span> { m.path } </div> { this.renderDetails() } </div> ); } renderDetails() { const m = this.props.method; if (!this.state.deployed) { return; } return ( <div className="panel-body"> { this.renderDescription() } { this.renderSchemaForm() } { this.renderRequestResult() } </div> ); } renderDescription() { const m = this.props.method; return ( <div>{ m.description }</div> ); } renderSchemaForm() { const m = this.props.method; const formData = this.state.formData; var schema; var additionnalParams = {}; m.parameters.forEach(function (param) { if (param.in == "body" && param.schema) { schema = param.schema; } else { additionnalParams[param.name] = param; } }); if (!schema) { return; } var properties = schema.properties; if (schema.$ref) { schema = this.props.app.state.api.definitions[schema.$ref.match(/#\/definitions\/(.*)/)[1]]; } schema.properties = {...additionnalParams, ...schema.properties}; schema.definitions = this.props.app.state.api.definitions; if ( this.props.app.state.authInfos.state.token && !formData.userHash ) { try { formData.userHash = jwtDecode(this.props.app.state.authInfos.state.token)['userHash']; } catch (e) { console.warn(e); } } return ( <div> <Form schema={ schema } formData={ formData } onChange={ this.handleSchemaFormChange.bind(this) } onSubmit={ (e) => this.handleSchemaFormSubmit(m, e) } onError={ this.handleSchemaFormErrors.bind(this) }> <button className="btn btn-primary" type="submit" disabled={ this.state.isRunning }>Submit</button> &nbsp; <button className="btn btn-danger" type="button" >Cancel</button> </Form> </div> ) } renderRequestResult() { if (this.state.isRunning) { return ( <div className="result"> <hr /> <div className="loading"></div> </div> ); } if (!this.state.response) { return; } return ( <div className="result"> <hr /> <ApiTransactionReport app={ this.state.app } request={ this.state.request } error={ this.state.error } response={ this.state.response } /> </div> ) } } export default ApiMethod;
packages/reactor-kitchensink/src/examples/Charts/Financial/Candlestick/Candlestick.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Container } from '@extjs/ext-react'; import { Cartesian } from '@extjs/ext-react-charts'; import ChartToolbar from '../../ChartToolbar'; import createData from './createData'; Ext.require([ 'Ext.chart.axis.Numeric', 'Ext.chart.axis.Time', 'Ext.chart.series.CandleStick', 'Ext.chart.interactions.Crosshair' ]); export default class CandlestickChartExample extends Component { constructor() { super(); this.refresh(); } store = Ext.create('Ext.data.Store', { fields: ['time', 'open', 'high', 'low', 'close'] }); state = { theme: 'default' }; refresh = () => { this.store.loadData(createData(1000)); } changeTheme = theme => this.setState({ theme }) toggleZoomOnPan = (zoomOnPan) => { this.toggleCrosshair(false); this.panzoom.setZoomOnPan(zoomOnPan); } toggleCrosshair = (crosshair) => { this.panzoom.setEnabled(!crosshair); this.crosshair.setEnabled(crosshair) } componentDidMount() { const chart = this.refs.chart; this.panzoom = chart.getInteraction('panzoom'); this.crosshair = chart.getInteraction('crosshair'); } render() { const { theme } = this.state; return ( <Container padding={!Ext.os.is.Phone && 10} layout="fit"> <ChartToolbar onThemeChange={this.changeTheme} onToggleZoomOnPan={this.toggleZoomOnPan} onToggleCrosshair={this.toggleCrosshair} onRefreshClick={this.refresh} theme={theme} onlyMidnight /> <Cartesian shadow ref="chart" store={this.store} theme={theme} interactions={[{ type: 'panzoom', axes: { left: { allowPan: false, allowZoom: false }, bottom: { allowPan: true, allowZoom: true } } }, { type: 'crosshair', axes: { label: { fillStyle: 'white' }, rect: { fillStyle: '#344459', opacity: 0.7, radius: 5 } } }]} series={{ type: 'candlestick', xField: 'time', openField: 'open', highField: 'high', lowField: 'low', closeField: 'close', style: { barWidth: 10, opacity: 0.9, dropStyle: { fill: 'rgb(237,123,43)', stroke: 'rgb(237,123,43)' }, raiseStyle: { fill: 'rgb(55,153,19)', stroke: 'rgb(55,153,19)' } } }} axes={[{ type: 'numeric', fields: ['open', 'high', 'low', 'close'], position: 'left', maximum: 1000, minimum: 0 }, { type: 'time', fields: ['time'], position: 'bottom', visibleRange: [0, 0.3], style: { axisLine: false } }]} /> </Container> ) } }
src/main/app/src/components/Layout/Layout.js
mbrossard/cryptonit-cloud
import React from 'react'; import PropTypes from 'prop-types' import _ from 'underscore'; class Layout extends React.Component { static propTypes = { children: PropTypes.node.isRequired }; render() { const { children, className, ...otherProps } = this.props; return ( <div id="application" className={ className } > <div className="main-wrap"> { children } </div> </div> ) } } export default Layout;
src/app/components/ColorCard.js
devgru/color
import React from 'react'; import { hcl, rgb } from 'd3-color'; import round from 'round-to-precision'; import objectMap from 'object-map'; import classNames from 'classnames'; import ClosestColor from '../domain/ClosestColor'; import ColorDescriptor from 'color-descriptor'; const cents = round(0.01); const descriptor = new ColorDescriptor(); function ColorCard(props) { const color = props.color; const cardStyle = { backgroundColor: color, }; const hclColor = hcl(color); const rgbColor = rgb(color); const colorName = ClosestColor(hclColor.hex()).name; const prettyHcl = objectMap(hclColor, cents); const prettyRgb = objectMap(rgbColor, cents); if (prettyHcl.c === "0") prettyHcl.h = 'any'; const textClasses = classNames({ 'color-card__text': true, 'color-card__text_bright': hclColor.l > 50, 'color-card__text_dark': hclColor.l <= 50, }); const description = descriptor.describe(color).join(', '); return ( <div className="color-card" style={cardStyle}> <div className={textClasses}> <div> <span className="color-card__hex">{color}</span> <span className="color-card__name"> — {colorName}</span> </div> <div className="color-card__description">{description}</div> <div className="color-card__properties"> rgb({prettyRgb.r}, {prettyRgb.g}, {prettyRgb.b}) </div> <div className="color-card__properties"> hcl({prettyHcl.h}, {prettyHcl.c}, {prettyHcl.l}) </div> </div> </div> ); } export default ColorCard;
src/index.js
amysimmons/a-guide-to-the-care-and-feeding-of-new-devs
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App/App'; ReactDOM.render(<App />, document.getElementById('root'));