path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/Main/Home.js
mwwscott0/WoWAnalyzer
import React, { Component } from 'react'; import SPECS from 'common/SPECS'; import AVAILABLE_CONFIGS from 'Parser/AVAILABLE_CONFIGS'; import PatreonButton from './PatreonButton'; import Changelog from './Changelog'; import MasteryRadiusImage from './Images/mastery-radius.png'; import ItemsImage from './Images/items.png'; import SuggestionsImage from './Images/suggestions.png'; import ImportantMetricsImage from './Images/important-metrics.png'; import CooldownUsagesImage from './Images/cooldownusages.png'; import ManaBreakdownImage from './Images/mana-breakdown.png'; import OpenSourceImage from './Images/open-source.png'; import OkHandImage from './Images/ok_hand.png'; class Home extends Component { render() { return ( <div> <div className="row"> <div className="col-lg-8 col-md-7"> <div className="panel"> <div className="panel-heading"> <h2>The World of Warcraft Analyzer</h2> </div> <div className="panel-body"> <img src={MasteryRadiusImage} alt="Mastery radius" className="pull-right" style={{ margin: 15 }} /> Use this tool to analyze your performance based on important metrics for the spec.<br /><br /> You will need a Warcraft Logs report with advanced combat logging enabled to start. Private logs can not be used, if your guild has private logs you will have to {' '}<a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to the {' '}<i>unlisted</i> privacy option instead.<br /><br /> Feature requests (<dfn data-tip="Provided that you're not using one of Microsoft's browsers.">and bug reports*</dfn>) are welcome! On <a href="https://discord.gg/AxphPxU">Discord</a> or create an issue <a href={'https://github.com/MartijnHols/WoWAnalyzer/issues'}>here</a>. </div> </div> <div className="panel"> <div className="panel-heading"> <h2>Features</h2> </div> <div className="panel-body text-muted"> <div className="row"> <div className="col-md-6 text-center"> <img src={ItemsImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Item performance breakdowns" /><br /> Item performance breakdowns </div> <div className="col-md-6 text-center"> <img src={SuggestionsImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Suggestions for improvement" /><br /> Suggestions for improvement </div> </div> <div className="row" style={{ marginTop: 15 }}> <div className="col-md-6 text-center"> <img src={ImportantMetricsImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Important metrics" /><br /> Important spec specific metrics </div> <div className="col-md-6 text-center"> <img src={CooldownUsagesImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Cooldown usages" /><br /> Cooldown usage details </div> </div> <div className="row" style={{ marginTop: 15 }}> <div className="col-md-6 text-center"> <img src={ManaBreakdownImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Mana breakdown" /><br /> Mana breakdown </div> <div className="col-md-6 text-center"> <img src={OpenSourceImage} style={{ maxWidth: '100%', border: '1px solid black', borderRadius: 5 }} alt="Open source" /><br /> Open source </div> </div><br /> Full source is available on <a href="https://github.com/MartijnHols/WoWAnalyzer">GitHub</a>. Contributions are extremely welcome! Add your own module or spec if you want to be able to analyze something not yet available. The repository contains information on how to contribute, if you need any more information please join our Discord (link further below). </div> </div> <div className="panel"> <div className="panel-heading"> <h2>Changes</h2> </div> <div className="panel-body text-muted"> <Changelog /> </div> </div> </div> <div className="col-lg-4 col-md-5"> <div className="panel"> <div className="panel-heading"> <h2>Available specs</h2> </div> <div className="panel-body text-muted"> <ul className="list-unstyled"> {Object.keys(SPECS) .filter(key => isNaN(key)) .map(key => SPECS[key]) .sort((a, b) => { if (a.className < b.className) { return -1; } else if (a.className > b.className) { return 1; } return a.id - b.id; }) .map((spec) => { const className = spec.className.replace(/ /g, ''); const config = AVAILABLE_CONFIGS.find(config => config.spec === spec); return ( <li key={spec.id} style={{ marginBottom: 3 }}> <img src={`/specs/${className}-${spec.specName.replace(' ', '')}.jpg`} alt="Spec logo" style={{ height: '1.6em', marginRight: 10 }} />{' '} <span className={className}>{spec.specName} {spec.className}</span>{' '} {config ? ( <span>maintained by <span style={{ color: '#fff' }}>{config.maintainer}</span></span> ) : ( <span>isn't available yet. <a href="https://github.com/MartijnHols/WoWAnalyzer/blob/master/CONTRIBUTING.md">Add it!</a></span> )} </li> ); })} </ul> If your spec isn't in the list it's not yet supported. Specs are added by enthusiastic players of the spec themselves. Adding specs is easy if you're familiar with JavaScript, find out more on <a href="https://github.com/MartijnHols/WoWAnalyzer/blob/master/CONTRIBUTING.md">GitHub</a> or <a href="https://discord.gg/AxphPxU" target="_blank" rel="noopener noreferrer">join the WoW Analyzer Discord</a> for additional help.<br /><br /> If you're looking to help out in other ways please consider donating.<br /> <PatreonButton text="Become a Patron" /> </div> </div> <div className="panel"> <div className="panel-heading"> <h2>Discord</h2> </div> <div className="panel-body text-muted"> I believe it's important to keep class discussion as much in class Discords as possible, so if you have spec specific questions and/or suggestions please try to discuss them in your class Discord (class Discords mods approve of this message <img src={OkHandImage} alt=":ok_hand:" style={{ height: '1.5em' }} />). The WoW Analyzer Discord is for more general questions and developers looking to contribute.<br /><br /> <iframe src="https://discordapp.com/widget?id=316864121536512000&theme=dark" width="100%" height="300" allowTransparency="true" frameBorder="0" title="Discord Widget" /> </div> </div> </div> </div> </div> ); } } export default Home;
src/app/static/ApiDocs/ApiDocs.js
JoeKarlsson1/bechdel-test
import React from 'react'; const ApiDocs = () => ( <div className="container"> <h1>api documentation</h1> </div> ); export default ApiDocs;
src/Grid.js
roderickwang/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Grid = React.createClass({ propTypes: { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: React.PropTypes.bool, /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div', fluid: false }; }, render() { let ComponentClass = this.props.componentClass; let className = this.props.fluid ? 'container-fluid' : 'container'; return ( <ComponentClass {...this.props} className={classNames(this.props.className, className)}> {this.props.children} </ComponentClass> ); } }); export default Grid;
packages/docs/components/Examples/image/AddImageEditor/ImageAdd/index.js
draft-js-plugins/draft-js-plugins
import React, { Component } from 'react'; import styles from './styles.module.css'; export default class ImageAdd extends Component { // Start the popover closed state = { url: '', open: false, }; // When the popover is open and users click anywhere on the page, // the popover should close componentDidMount() { document.addEventListener('click', this.closePopover); } componentWillUnmount() { document.removeEventListener('click', this.closePopover); } // Note: make sure whenever a click happens within the popover it is not closed onPopoverClick = () => { this.preventNextClose = true; }; openPopover = () => { if (!this.state.open) { this.preventNextClose = true; this.setState({ open: true, }); } }; closePopover = () => { if (!this.preventNextClose && this.state.open) { this.setState({ open: false, }); } this.preventNextClose = false; }; addImage = () => { const { editorState, onChange } = this.props; onChange(this.props.modifier(editorState, this.state.url)); }; changeUrl = (evt) => { this.setState({ url: evt.target.value }); }; render() { const popoverClassName = this.state.open ? styles.addImagePopover : styles.addImageClosedPopover; const buttonClassName = this.state.open ? styles.addImagePressedButton : styles.addImageButton; return ( <div className={styles.addImage}> <button className={buttonClassName} onMouseUp={this.openPopover} type="button" > + </button> <div className={popoverClassName} onClick={this.onPopoverClick}> <input type="text" placeholder="Paste the image url …" className={styles.addImageInput} onChange={this.changeUrl} value={this.state.url} /> <button className={styles.addImageConfirmButton} type="button" onClick={this.addImage} > Add </button> </div> </div> ); } }
app/javascript/mastodon/features/compose/components/upload_form.js
kirakiratter/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import UploadProgressContainer from '../containers/upload_progress_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import UploadContainer from '../containers/upload_container'; import SensitiveButtonContainer from '../containers/sensitive_button_container'; import { FormattedMessage } from 'react-intl'; export default class UploadForm extends ImmutablePureComponent { static propTypes = { mediaIds: ImmutablePropTypes.list.isRequired, }; render () { const { mediaIds } = this.props; return ( <div className='compose-form__upload-wrapper'> <UploadProgressContainer icon='upload' message={<FormattedMessage id='upload_progress.label' defaultMessage='Uploading…' />} /> <div className='compose-form__uploads-wrapper'> {mediaIds.map(id => ( <UploadContainer id={id} key={id} /> ))} </div> {!mediaIds.isEmpty() && <SensitiveButtonContainer />} </div> ); } }
src/components/loading-indicators/loading-repository-profile.component.js
gitpoint/git-point
// @flow import React, { Component } from 'react'; import { View, Animated } from 'react-native'; import { Icon } from 'react-native-elements'; import styled from 'styled-components'; import { colors, fonts, normalize } from 'config'; import { loadingAnimation, t } from 'utils'; const Container = styled.View` flex: 1; align-items: center; justify-content: center; `; const Profile = styled.View` flex: 2; margin-top: 50; align-items: center; justify-content: center; `; const OctIcon = styled(Icon).attrs({ name: 'repo', type: 'octicon', size: 45, color: colors.greyLight, containerStyle: { marginLeft: 10, paddingBottom: 20, }, })``; const Details = styled.View` flex: 1; flex-direction: row; justify-content: space-around; min-width: 300; `; const Unit = styled.View` flex: 1; `; const UnitText = styled.Text` text-align: center; color: ${colors.white}; font-size: ${normalize(10)}; ${fonts.fontPrimary}; `; export class LoadingRepositoryProfile extends Component { props: { locale: string, }; state: { fadeAnimValue: Animated, }; constructor(props) { super(props); this.state = { fadeAnimValue: new Animated.Value(0), }; } componentDidMount() { loadingAnimation(this.state.fadeAnimValue).start(); } render() { const { locale } = this.props; return ( <Container> <View> <Profile> <OctIcon /> </Profile> <Details> <Unit> <UnitText>{t('Stars', locale)}</UnitText> </Unit> <Unit> <UnitText>{t('Forks', locale)}</UnitText> </Unit> </Details> </View> </Container> ); } }
src/svg-icons/av/mic-none.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMicNone = (props) => ( <SvgIcon {...props}> <path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1.2-9.1c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2l-.01 6.2c0 .66-.53 1.2-1.19 1.2-.66 0-1.2-.54-1.2-1.2V4.9zm6.5 6.1c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/> </SvgIcon> ); AvMicNone = pure(AvMicNone); AvMicNone.displayName = 'AvMicNone'; AvMicNone.muiName = 'SvgIcon'; export default AvMicNone;
src/svg-icons/editor/wrap-text.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorWrapText = (props) => ( <SvgIcon {...props}> <path d="M4 19h6v-2H4v2zM20 5H4v2h16V5zm-3 6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4z"/> </SvgIcon> ); EditorWrapText = pure(EditorWrapText); EditorWrapText.displayName = 'EditorWrapText'; EditorWrapText.muiName = 'SvgIcon'; export default EditorWrapText;
docs/src/app/pages/components/InlineEdit/ExampleInlineEditEmpty.js
GetAmbassador/react-ions
import React from 'react' import InlineEdit from 'react-ions/lib/components/InlineEdit' import styles from './styles' class ExampleInlineEditEmpty extends React.Component { constructor(props) { super(props) } state = { inlineValue: null } handleSave = event => { if (event.target.name === 'test') { this.setState({ inlineValue: event.target.value }) } } render = () => { return ( <div> <InlineEdit name='test' value={this.state.inlineValue} changeCallback={this.handleSave} /> <code>The Inline Edit value is '{this.state.inlineValue}'.</code> </div> ) } } export default ExampleInlineEditEmpty
src/components/control-strip-defaults-component.js
davidkpiano/redux-simple-form
import React, { Component } from 'react'; import PropTypes from 'prop-types'; // Prevents the defaultValue/defaultChecked fields from rendering with value/checked class ComponentWrapper extends Component { render() { /* eslint-disable no-unused-vars */ const { defaultValue, defaultChecked, component, getRef, ...otherProps, } = this.props; /* eslint-enable */ if (getRef) { otherProps.ref = getRef; } const WrappedComponent = component; return <WrappedComponent {...otherProps} />; } } ComponentWrapper.propTypes = { component: PropTypes.any, defaultValue: PropTypes.any, defaultChecked: PropTypes.any, getRef: PropTypes.func, }; export default ComponentWrapper;
KayaCMS-Admin/frontend/src/App.js
abono/Kaya-CMS
import React from 'react'; import './App.css'; import { UserProvider } from './context/UserContext' import Template from './pages/Template'; function App() { return ( <UserProvider> <Template /> </UserProvider> ); } export default App;
src/app/components/blocks/_loader.js
mazahell/eve-react-app
import React from 'react' import img from '../../../assets/img/ajax.gif' const Loader = () => { return <div className="loader" id="ajax_loader"><img src={img} alt="loader" /></div> } export default Loader
src/components/icon/components/refresh.js
fmsouza/wcode
import React from 'react'; // Icon taken from: https://github.com/spiffcode/ghedit export const Refresh = (props) => ( <svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' {...props}> <path d='M13.451 5.609l-.579-.939-1.068.812-.076.094c-.335.415-.927 1.341-1.124 2.876l-.021.165.033.163.071.345c0 1.654-1.346 3-3 3a2.98 2.98 0 0 1-2.107-.868 2.98 2.98 0 0 1-.873-2.111 3.004 3.004 0 0 1 2.351-2.929v2.926s2.528-2.087 2.984-2.461h.012L13.115 4.1 8.196 0H7.059v2.404A6.759 6.759 0 0 0 .938 9.125c0 1.809.707 3.508 1.986 4.782a6.707 6.707 0 0 0 4.784 1.988 6.758 6.758 0 0 0 6.75-6.75 6.741 6.741 0 0 0-1.007-3.536z' fill='#2D2D30'/> <path d='M12.6 6.134l-.094.071c-.269.333-.746 1.096-.91 2.375.057.277.092.495.092.545 0 2.206-1.794 4-4 4a3.986 3.986 0 0 1-2.817-1.164 3.987 3.987 0 0 1-1.163-2.815c0-2.206 1.794-4 4-4l.351.025v1.85S9.685 5.679 9.69 5.682l1.869-1.577-3.5-2.917v2.218l-.371-.03a5.75 5.75 0 0 0-4.055 9.826 5.75 5.75 0 0 0 9.826-4.056 5.725 5.725 0 0 0-.859-3.012z' fill='#C5C5C5'/> </svg> );
src/parser/shaman/enhancement/modules/talents/LightningShield.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import SpellIcon from 'common/SpellIcon'; import { formatNumber, formatPercentage } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import StatisticBox from 'interface/others/StatisticBox'; class LightningShield extends Analyzer { damageGained=0; overchargeCount=0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.LIGHTNING_SHIELD_TALENT.id); } on_byPlayer_damage(event) { if (event.ability.guid!==SPELLS.LIGHTNING_SHIELD_TALENT.id) { return; } this.damageGained += event.amount; } on_byPlayer_energize(event) { if (event.ability.guid!==SPELLS.LIGHTNING_SHIELD_OVERCHARGE.id) { return; } this.maelstromGained += event.amount; } on_byPlayer_buffapply(event) { if (event.ability.guid!==SPELLS.LIGHTNING_SHIELD_OVERCHARGE.id) { return; } this.overchargeCount += 1; } get damagePercent() { return this.owner.getPercentageOfTotalDamageDone(this.damageGained); } get damagePerSecond() { return this.damageGained / (this.owner.fightDuration / 1000); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.LIGHTNING_SHIELD_TALENT.id} />} value={`${formatPercentage(this.damagePercent)} %`} label="Of total damage" tooltip={`Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage).`} /> ); } } export default LightningShield;
src/components/menu.js
eh3rrera/react-horizon
import React, { Component } from 'react'; import { Link, IndexLink } from 'react-router'; import Horizon from '../horizon-container'; export default class Menu extends Component { logout = (e) => { e.preventDefault(); Horizon.clearAuthTokens(); this.context.router.push("/") } render() { var menu = Horizon.get().hasAuthToken() ? <div className={'menu'}> <IndexLink to="/" className={'menu-option'} activeClassName="active">Home</IndexLink> <Link to="/messages" className={'menu-option'} activeClassName="active">Messages</Link> <a href="#" className={'menu-option'} onClick={this.logout}>Logout</a> </div> : <div className={'menu'}> <IndexLink to="/" className={'menu-option'} activeClassName="active">Home</IndexLink> <Link to="/login" className={'menu-option'} activeClassName="active">Login</Link> </div>; return ( menu ); } } Menu.contextTypes = { router: React.PropTypes.object };
src/components/TextInputBEM/TextInputBEM.js
abhiisheek/ps-react-abhiisheek
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInputBEM({ htmlId, name, label, type = 'text', required = false, onChange, placeholder, value, error, children, ...props }) { return ( <div className='textInput'> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} className={error && 'textInput__input--state-error'} {...props} /> {children} {error && ( <div className="textInput--error"> {error} </div> )} </div> ); } TextInputBEM.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInputBEM;
src/svg-icons/notification/airline-seat-legroom-reduced.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomReduced = (props) => ( <SvgIcon {...props}> <path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"/> </SvgIcon> ); NotificationAirlineSeatLegroomReduced = pure(NotificationAirlineSeatLegroomReduced); NotificationAirlineSeatLegroomReduced.displayName = 'NotificationAirlineSeatLegroomReduced'; NotificationAirlineSeatLegroomReduced.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomReduced;
examples/with-react-router-v3/src/index.js
lwhitlock/grow-tracker
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, IndexRoute, Route, browserHistory } from 'react-router'; import WebFontLoader from 'webfontloader'; WebFontLoader.load({ google: { families: ['Roboto:300,400,500,700', 'Material Icons'], }, }); import './index.css'; import App from './App'; import Home from './Home'; import Page1 from './Page1'; import Page2 from './Page2'; import Page3 from './Page3'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="page-1" component={Page1} /> <Route path="page-2" component={Page2} /> <Route path="page-3" component={Page3} /> </Route> </Router>, document.getElementById('root') );
src/pages/404.js
brickandgreens/bricks-and-greens-gatsby
import React from 'react' const NotFoundPage = () => ( <div> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </div> ) export default NotFoundPage
imports/ui/components/Orders/Invoices/ViewInvoice.js
haraneesh/mydev
import React from 'react'; import { Row, Col, Panel, PanelGroup } from 'react-bootstrap'; import PropTypes from 'prop-types'; import { formatMoney } from 'accounting-js'; import { accountSettings } from '../../../../modules/settings'; import { displayUnitOfSale } from '../../../../modules/helpers'; const DisplayOrderProducts = ({ products, total }) => ( <PanelGroup className="order-details-products"> <Panel> <Row> <Col xs={4}> <strong> Name </strong></Col> <Col xs={3} className="text-right-xs"> <strong> Rate </strong></Col> <Col xs={2} className="text-right-xs"> <strong> Qty </strong></Col> <Col xs={3} className="text-right"> <strong> Value </strong></Col> </Row> </Panel> {products.map((product) => { if (product.item_total > 0) { return ( <Panel key={product.item_id}> <Row> <Col xs={4}> {`${product.name}, ${product.unit}`}<br /> </Col> <Col xs={3} className="text-right-xs"> {`${formatMoney(product.rate, accountSettings)}`} </Col> <Col xs={2} className="text-right-xs"> {`${displayUnitOfSale(product.quantity, product.unit)}`} </Col> <Col xs={3} className="text-right"> {formatMoney( product.rate * product.quantity, accountSettings, )} </Col> </Row> </Panel> ); } })} <Panel> <Row> <Col xs={12} className="text-right"> Amount: <strong> {' '} {formatMoney(total, accountSettings)} {' '}</strong></Col> </Row> </Panel> </PanelGroup> ); const ViewInvoice = ({ invoice }) => ( <div className="orderDetails"> <Row> <Col xs={12}> <h4> {invoice.invoice_number} - <span className="text-muted"> {invoice.status} </span> </h4> { invoice.line_items && <DisplayOrderProducts products={invoice.line_items} total={invoice.total} /> } </Col> </Row> <div> {invoice.balance > 0 && <div className="panel-footer"> <Row className="text-right"> <Col xs={12}> <strong> {`Pending : ${formatMoney(invoice.balance, accountSettings)}`} </strong> </Col> </Row> </div>} </div> </div> ); ViewInvoice.propTypes = { invoice: PropTypes.object.isRequired, }; export default ViewInvoice;
app/javascript/mastodon/features/ui/components/column_link.js
pinfort/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import Icon from 'mastodon/components/icon'; const ColumnLink = ({ icon, text, to, href, method, badge }) => { const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null; if (href) { return ( <a href={href} className='column-link' data-method={method}> <Icon id={icon} fixedWidth className='column-link__icon' /> {text} {badgeElement} </a> ); } else { return ( <Link to={to} className='column-link'> <Icon id={icon} fixedWidth className='column-link__icon' /> {text} {badgeElement} </Link> ); } }; ColumnLink.propTypes = { icon: PropTypes.string.isRequired, text: PropTypes.string.isRequired, to: PropTypes.string, href: PropTypes.string, method: PropTypes.string, badge: PropTypes.node, }; export default ColumnLink;
docs/app/Examples/modules/Accordion/Variations/index.js
aabustamante/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const AccordionTypesExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Fluid' description='An accordion can take up the width of its container.' examplePath='modules/Accordion/Variations/AccordionExampleFluid' /> <ComponentExample title='Inverted' description='An accordion can be formatted to appear on dark backgrounds.' examplePath='modules/Accordion/Variations/AccordionExampleInverted' /> <ComponentExample title='Exclusive' description='An accordion can have multiple panels open at the same time.' examplePath='modules/Accordion/Variations/AccordionExampleExclusive' /> </ExampleSection> ) export default AccordionTypesExamples
sandbox/scripts/create_sandbox.js
pivotal-cf/pivotal-ui
const fs = require('fs'); const path = require('path'); const sandboxFilePath = path.resolve(__dirname, '../sandbox.js'); const sandboxStarterContent = ` import React from 'react'; import {DefaultButton} from 'pivotal-ui/react/buttons'; export default () => { return <DefaultButton>Hello!</DefaultButton> }; `.trim(); if (fs.existsSync(sandboxFilePath)) { console.log('Your sandbox.js file already exists!\n\nUse "yarn start" to start the dev server.'); process.exit(); } else { console.log('Creating "sandbox.js" file...'); } fs.writeFileSync(sandboxFilePath, sandboxStarterContent); console.log('Wrote "sandbox.js"!\n\nUse "yarn start" to start the dev server.');
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/Popover.js
OpenKGB/webcode
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Title content */ title: PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: 'arrow', style: arrowStyle }), title && React.createElement( 'h3', { className: prefix(bsProps, 'title') }, title ), React.createElement( 'div', { className: prefix(bsProps, 'content') }, children ) ); }; return Popover; }(React.Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);
pages/index.js
keithk/cfa-dance
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; import Submit from '../components/Submit/Submit.js'; import List from '../components/List/List.js'; export default class extends Component { render() { return ( <div> <h1>CfA Dance Party</h1> <Submit /> <List /> </div> ); } }
src/components/NewChallenge.js
quintel/etmobile
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; import injectIntl from '../utils/injectIntl'; import Header from './Header'; import authenticate from '../utils/authenticate'; import randomId from '../utils/randomId'; import challengeExpiry from '../utils/challengeExpiry'; /** * Given the "expiry time" select box, determines the timestamp at which the * challenge will close. */ const expiryFromSelect = field => challengeExpiry[field.value]().getTime(); /** * Retrieves a formatted error message by ID. */ class NewChallenge extends React.Component { constructor() { super(); this.state = { challengeId: null, name: null, errors: [] }; this.onSubmit = this.onSubmit.bind(this); } onSubmit(event) { event.preventDefault(); const name = `${this.nameField.value}`.trim(); if (name.length) { const challengeId = randomId(); const expires = expiryFromSelect(this.expiresField); const mode = this.difficultyField.value; authenticate(this.props.base, () => { this.props.base.post( `challenges/${challengeId}`, { data: { name, expires, mode } } ).then( () => this.setState({ challengeId, name }), () => this.setState(this.errorFor('challenges.errors.starting')) ); }); } else { this.setState(this.errorFor('challenges.errors.missingName')); } } errorFor(id) { return { errors: [this.context.intl.formatMessage({ id })] }; } render() { if (this.state.challengeId) { // When the visitor has created and saved their challenge, redirect to // the play page. return <Redirect to={`/play/${this.state.challengeId}`} />; } let errors; if (this.state.errors.length) { errors = ( <ul className="errors"> {this.state.errors.map((msg, index) => <li key={`error-${index}`}>{msg}</li> )} </ul> ); } return ( <div> <Header /> <div className="new-challenge-wrapper"> <h1><FormattedMessage id="challenges.form.title" /></h1> <form disabled={this.state.challengeId != null} onSubmit={this.onSubmit} id="new-challenge" > <div className="field-wrapper"> <label htmlFor="new-challenge-name"> <FormattedMessage id="challenges.form.name.title" /> <span className="description"> <FormattedMessage id="challenges.form.name.description" /> </span> </label> <div className="field"> <input ref={(input) => { this.nameField = input; }} type="text" placeholder={ `${this.context.intl.formatMessage({ id: 'challenges.form.name.placeholder' })}…` } id="new-challenge-name" name="name" defaultValue={this.props.defaultName} /> </div> </div> <div className="field-wrapper"> <label htmlFor="new-challenge-expires"> <FormattedMessage id="challenges.form.expires.title" />&hellip; <span className="description"> <FormattedMessage id="challenges.form.expires.description" /> </span> </label> <div className="field"> <select ref={(select) => { this.expiresField = select; }} id="new-challenge-expires" name="expires" defaultValue="1d" > <option value="4h"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.4h' })} </option> <option value="8h"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.8h' })} </option> <option value="1d"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.1d' })} </option> <option value="3d"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.3d' })} </option> <option value="1w"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.1w' })} </option> <option value="2w"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.2w' })} </option> <option value="1m"> {this.context.intl.formatMessage({ id: 'challenges.form.expires.options.1m' })} </option> </select> </div> </div> <div className="field-wrapper"> <label htmlFor="new-challenge-difficulty"> <FormattedMessage id="challenges.form.difficulty.title" /> <span className="description"> <FormattedMessage id="challenges.form.difficulty.description" /> </span> </label> <div className="field"> <select ref={(select) => { this.difficultyField = select; }} id="new-challenge-difficulty" name="difficulty" defaultValue="easy" > <option value="easy"> {this.context.intl.formatMessage({ id: 'game.difficultyEasy' })} </option> <option value="medium"> {this.context.intl.formatMessage({ id: 'game.difficultyMedium' })} </option> <option value="hard"> {this.context.intl.formatMessage({ id: 'game.difficultyHard' })} </option> </select> </div> </div> {errors} <div className="field-wrapper buttons"> <button> <FormattedMessage id="challenges.form.submit" />{' '} <span className="arrows">&raquo;</span> </button> </div> </form> </div> </div> ); } } NewChallenge.propTypes = { base: PropTypes.shape({ post: PropTypes.func.isRequired }).isRequired, defaultName: PropTypes.string }; export default injectIntl(NewChallenge);
packages/create-subscription/src/createSubscription.js
chenglou/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import invariant from 'shared/invariant'; import warningWithoutStack from 'shared/warningWithoutStack'; type Unsubscribe = () => void; export function createSubscription<Property, Value>( config: $ReadOnly<{| // Synchronously gets the value for the subscribed property. // Return undefined if the subscribable value is undefined, // Or does not support synchronous reading (e.g. native Promise). getCurrentValue: (source: Property) => Value | void, // Setup a subscription for the subscribable value in props, and return an unsubscribe function. // Return empty function if the property cannot be unsubscribed from (e.g. native Promises). // Due to the variety of change event types, subscribers should provide their own handlers. // Those handlers should not attempt to update state though; // They should call the callback() instead when a subscription changes. subscribe: ( source: Property, callback: (value: Value | void) => void, ) => Unsubscribe, |}>, ): React$ComponentType<{ children: (value: Value | void) => React$Node, source: Property, }> { const {getCurrentValue, subscribe} = config; warningWithoutStack( typeof getCurrentValue === 'function', 'Subscription must specify a getCurrentValue function', ); warningWithoutStack( typeof subscribe === 'function', 'Subscription must specify a subscribe function', ); type Props = { children: (value: Value) => React$Element<any>, source: Property, }; type State = { source: Property, value: Value | void, }; // Reference: https://gist.github.com/bvaughn/d569177d70b50b58bff69c3c4a5353f3 class Subscription extends React.Component<Props, State> { state: State = { source: this.props.source, value: this.props.source != null ? getCurrentValue(this.props.source) : undefined, }; _hasUnmounted: boolean = false; _unsubscribe: Unsubscribe | null = null; static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.source !== prevState.source) { return { source: nextProps.source, value: nextProps.source != null ? getCurrentValue(nextProps.source) : undefined, }; } return null; } componentDidMount() { this.subscribe(); } componentDidUpdate(prevProps, prevState) { if (this.state.source !== prevState.source) { this.unsubscribe(); this.subscribe(); } } componentWillUnmount() { this.unsubscribe(); // Track mounted to avoid calling setState after unmounting // For source like Promises that can't be unsubscribed from. this._hasUnmounted = true; } render() { return this.props.children(this.state.value); } subscribe() { const {source} = this.state; if (source != null) { const callback = (value: Value | void) => { if (this._hasUnmounted) { return; } this.setState(state => { // If the value is the same, skip the unnecessary state update. if (value === state.value) { return null; } // If this event belongs to an old or uncommitted data source, ignore it. if (source !== state.source) { return null; } return {value}; }); }; // Store the unsubscribe method for later (in case the subscribable prop changes). const unsubscribe = subscribe(source, callback); invariant( typeof unsubscribe === 'function', 'A subscription must return an unsubscribe function.', ); // It's safe to store unsubscribe on the instance because // We only read or write that property during the "commit" phase. this._unsubscribe = unsubscribe; // External values could change between render and mount, // In some cases it may be important to handle this case. const value = getCurrentValue(this.props.source); if (value !== this.state.value) { this.setState({value}); } } } unsubscribe() { if (typeof this._unsubscribe === 'function') { this._unsubscribe(); } this._unsubscribe = null; } } return Subscription; }
examples/fiber/debugger/src/index.js
shergin/react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/svg-icons/communication/present-to-all.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPresentToAll = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z"/> </SvgIcon> ); CommunicationPresentToAll = pure(CommunicationPresentToAll); CommunicationPresentToAll.displayName = 'CommunicationPresentToAll'; CommunicationPresentToAll.muiName = 'SvgIcon'; export default CommunicationPresentToAll;
src/routes/index.js
lgse/react-chat
import React from 'react'; import { IndexRedirect, Route } from 'react-router'; import App from '~/containers/App'; import Chat from '~/containers/Chat'; import Login from '~/containers/Login'; function routes(store) { function requireLogin(nextState, replace) { const { loggedIn } = store.getState().login; const nextPathname = nextState.location.pathname; let pathname = null; if (!loggedIn && nextPathname !== '/login') { pathname = '/login'; } else if (loggedIn && nextPathname === '/login') { pathname = '/chat'; } if (pathname) { replace({ pathname, state: { nextPathname }, }); } } return ( <Route path="/" component={App}> <IndexRedirect to="login" /> <Route path="chat" component={Chat} onEnter={requireLogin} /> <Route path="login" component={Login} onEnter={requireLogin} /> <Route path="*" onEnter={requireLogin} /> </Route> ); } export default routes;
app/pages/Error404/index.js
aleksandrenko/apollo-cc
import './style.less'; import React from 'react'; const Component = React.createClass({ render() { return ( <h1>404</h1> ); } }); export default Component;
lib/App.js
blittle/jspm-test
import React from 'react'; export default function App() { return ( <div>Hello</div> ) }
classic/src/scenes/wbfa/generated/FASCheckCircle.pro.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faCheckCircle } from '@fortawesome/pro-solid-svg-icons/faCheckCircle' export default class FASCheckCircle extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faCheckCircle} />) } }
src/views/components/AudioStream.js
physiii/open-automation
import React from 'react'; import PropTypes from 'prop-types'; import JSMpeg from '../../lib/jsmpeg/jsmpeg.min.js'; import {connect} from 'react-redux'; import {audioStartStream, audioStopStream, cameraStartAudioRecordingStream, cameraStopAudioRecordingStream} from '../../state/ducks/services-list/operations.js'; import './AudioStream.css'; export class AudioStream extends React.Component { constructor (props) { super(props); this.resourceStreamingStatus = {}; this.canvas = React.createRef(); } componentDidMount () { this.bootstrapPlayer(); if (this.props.autoplay) { this.start(); } } shouldComponentUpdate (nextProps) { const didRecordingChange = (nextProps.recording && nextProps.recording.id) !== (this.props.recording && this.props.recording.id), didAudioChange = nextProps.audioServiceId !== this.props.audioServiceId, didTokenChange = nextProps.streamingToken !== this.props.streamingToken; // Check to see if shouldStream changed and, if so, start or stop the stream. if (!this.props.shouldStream && nextProps.shouldStream) { this.start(); } else if (this.props.shouldStream && !nextProps.shouldStream) { this.stop(); } // Only re-render if the audio or recording changes. This prevents // unnecessary re-bootstrapping of JSMpeg. if (didRecordingChange || didAudioChange) { // Stop the stream for the current recording or audio. this.stop(); return true; } // Update if the token changes so JSMpeg can bootstrap with the new token. if (didTokenChange) { return true; } return false; } componentDidUpdate () { this.bootstrapPlayer(); } componentWillUnmount () { this.stop(); if (this.player) { this.player.destroy(); } } start () { const streamId = this.getStreamIdForCurrentResource(); // Play JSMpeg. Need to match exactly false because of JSMpeg quirks. if (this.player && this.player.isPlaying === false) { this.player.play(); } if (this.resourceStreamingStatus[streamId]) { return; } this.props.startStreaming(); this.resourceStreamingStatus[streamId] = true; } stop () { const streamId = this.getStreamIdForCurrentResource(); // Pause JSMpeg. if (this.player && this.player.isPlaying) { this.player.pause(); } if (!this.resourceStreamingStatus[streamId]) { return; } this.props.stopStreaming(); this.resourceStreamingStatus[streamId] = false; } getStreamIdForCurrentResource () { return this.props.recording ? this.props.recording.id : this.props.audioServiceId; } bootstrapPlayer () { if (this.player) { // this.player.destroy(); } this.player = new JSMpeg.Player( this.props.streamingHost + '?stream_id=' + this.getStreamIdForCurrentResource() + '&stream_token=' + this.props.streamingToken, { canvas: this.canvas.current, disableGl: true } ); if (this.props.shouldStream) { this.start(); } else { this.stop(); } } render () { return ( <canvas className={this.props.className} styleName="canvas" ref={this.canvas} /> ); } } AudioStream.propTypes = { audioServiceId: PropTypes.string.isRequired, recording: PropTypes.object, // TODO: Shape of recording object streamingToken: PropTypes.string, streamingHost: PropTypes.string, shouldStream: PropTypes.bool, // autoplay will start the stream only once when the component mounts. autoplay: PropTypes.bool, // className can be passed in to override the default CSS class. className: PropTypes.string, startStreaming: PropTypes.func.isRequired, stopStreaming: PropTypes.func.isRequired }; export const mapStateToProps = (state) => { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; return { streamingHost: protocol + '//' + window.location.hostname + ':' + state.config.stream_port + '/stream-relay' }; }, mapDispatchToProps = (dispatch, ownProps) => { return { startStreaming: () => { if (ownProps.recording) { dispatch(cameraStartAudioRecordingStream(ownProps.recording)); } else { dispatch(audioStartStream(ownProps.audioServiceId)); } }, stopStreaming: () => { if (ownProps.recording) { dispatch(cameraStopAudioRecordingStream(ownProps.recording)); } else { dispatch(audioStopStream(ownProps.audioServiceId)); } } }; }; export default connect(mapStateToProps, mapDispatchToProps)(AudioStream);
packages/core/upload/admin/src/components/EditAssetDialog/PreviewBox/CroppingActions.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { IconButton } from '@strapi/design-system/IconButton'; import { FocusTrap } from '@strapi/design-system/FocusTrap'; import { SimpleMenu, MenuItem } from '@strapi/design-system/SimpleMenu'; import Cross from '@strapi/icons/Cross'; import Check from '@strapi/icons/Check'; import { Stack } from '@strapi/design-system/Stack'; import { useIntl } from 'react-intl'; import getTrad from '../../../utils/getTrad'; import { CroppingActionRow } from './components'; export const CroppingActions = ({ onCancel, onValidate, onDuplicate }) => { const { formatMessage } = useIntl(); return ( <FocusTrap onEscape={onCancel}> <CroppingActionRow justifyContent="flex-end" paddingLeft={3} paddingRight={3}> <Stack size={1} horizontal> <IconButton label={formatMessage({ id: getTrad('control-card.stop-crop'), defaultMessage: 'Stop cropping', })} icon={<Cross />} onClick={onCancel} /> <SimpleMenu label={formatMessage({ id: getTrad('control-card.crop'), defaultMessage: 'Crop', })} as={IconButton} icon={<Check />} > <MenuItem onClick={onValidate}> {formatMessage({ id: getTrad('checkControl.crop-original'), defaultMessage: 'Crop the original asset', })} </MenuItem> {onDuplicate && ( <MenuItem onClick={onDuplicate}> {formatMessage({ id: getTrad('checkControl.crop-duplicate'), defaultMessage: 'Duplicate & crop the asset', })} </MenuItem> )} </SimpleMenu> </Stack> </CroppingActionRow> </FocusTrap> ); }; CroppingActions.defaultProps = { onDuplicate: undefined, }; CroppingActions.propTypes = { onCancel: PropTypes.func.isRequired, onDuplicate: PropTypes.func, onValidate: PropTypes.func.isRequired, };
app/javascript/mastodon/features/follow_requests/components/account_authorize.js
kagucho/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Permalink from '../../../components/permalink'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import emojify from '../../../emoji'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ authorize: { id: 'follow_request.authorize', defaultMessage: 'Authorize' }, reject: { id: 'follow_request.reject', defaultMessage: 'Reject' }, }); @injectIntl export default class AccountAuthorize extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onAuthorize: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { intl, account, onAuthorize, onReject } = this.props; const content = { __html: emojify(account.get('note')) }; return ( <div className='account-authorize__wrapper'> <div className='account-authorize'> <Permalink href={account.get('url')} to={`/accounts/${account.get('id')}`} className='detailed-status__display-name'> <div className='account-authorize__avatar'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={48} /></div> <DisplayName account={account} /> </Permalink> <div className='account__header__content' dangerouslySetInnerHTML={content} /> </div> <div className='account--panel'> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.authorize)} icon='check' onClick={onAuthorize} /></div> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.reject)} icon='times' onClick={onReject} /></div> </div> </div> ); } }
src/components/Slide.js
tgevaert/react-redux-hearts
import React from 'react'; export const Slide = ({ direction, cardinal, children }) => { let cName = 'slide'; if (direction && cardinal) { cName += '-' + direction + '-' + cardinal; } return ( <div className={cName}> {children} </div> ); };
client/scripts/components/user/projects/entity/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import {DisclosureActions} from '../../../../actions/disclosure-actions'; import { DisclosureStore } from '../../../../stores/disclosure-store'; import {EntityRelationDialog} from '../entity-relation-dialog'; import {GreyButton} from '../../../grey-button'; import {undefinedRelationExists} from '../../undefined-relation-exists'; import { getRelationshipCategoryTypeString, getRelationshipPersonTypeString } from '../../../../stores/config-store'; export class Entity extends React.Component { constructor() { super(); this.toggleDialog = this.toggleDialog.bind(this); this.getDisplayStatus = this.getDisplayStatus.bind(this); } shouldComponentUpdate() { return true; } toggleDialog() { DisclosureActions.toggleDeclaration(this.props.entity.id, 'ENTITY'); } getDisplayStatus() { if (undefinedRelationExists('PROJECT', this.props.projects, this.props.declarations)) { return 'Action Required'; } return DisclosureStore.getWorstDeclaration( this.props.declarations, this.context.configState.config.declarationTypes ); } render() { let relationshipDialog; if (this.props.open) { relationshipDialog = ( <EntityRelationDialog declarations={this.props.declarations} projects={this.props.projects} className={`${styles.override} ${this.props.open ? styles.block : styles.none}`} title={this.props.title} type={this.props.type} role={this.props.role} declarationTypes={this.props.declarationTypes} finEntityId={this.props.entity.id} id={this.props.id} entityCount={this.props.entityCount} onSave={this.toggleDialog} onNext={this.props.onNext} onPrevious={this.props.onPrevious} /> ); } const relationships = []; this.props.entity.relationships.forEach(element => { const relationshipPersonType = getRelationshipPersonTypeString( this.context.configState, element.personCd, this.context.configState.config.id ); const relationshipCategoryType = getRelationshipCategoryTypeString( this.context.configState, element.relationshipCd, this.context.configState.config.id ); relationships.push( <div key={element.id}> {relationshipPersonType} - {relationshipCategoryType} </div> ); }); let status; if (this.getDisplayStatus() === 'Action Required') { status = ( <div className={styles.attention}> - {this.getDisplayStatus()} - </div> ); } else { status = ( <div style={{marginBottom: 10}}> <div style={{fontWeight: '300'}}>Relationship Status:</div> <div style={{fontWeight: '700'}}>{this.getDisplayStatus()}</div> </div> ); } return ( <div className={`${styles.container} ${this.props.className}`}> <div className={styles.content}> <div className={styles.title}> <span className={styles.value}> {this.props.title} </span> </div> <div> <span className={styles.left}> <div className={styles.item}> <span style={{display: 'inline-block', verticalAlign: 'top'}}> Relationship: </span> <span className={styles.value}> {relationships} </span> </div> </span> <span className={styles.right}> {status} <div> <GreyButton className={`${styles.override} ${styles.button}`} onClick={this.toggleDialog}> Update </GreyButton> </div> </span> </div> </div> {relationshipDialog} </div> ); } } Entity.contextTypes = { configState: React.PropTypes.object };
src/components/Post/Author/Author.js
amoseui/blog
// @flow strict import React from 'react'; import { getContactHref } from '../../../utils'; import styles from './Author.module.scss'; import { useSiteMetadata } from '../../../hooks'; const Author = () => { const { author } = useSiteMetadata(); return ( <div className={styles['author']}> <p className={styles['author__bio']}> {author.bio} <a className={styles['author__bio-twitter']} href={getContactHref('twitter', author.contacts.twitter)} rel="noopener noreferrer" target="_blank" > <strong>{author.name}</strong> on Twitter </a> </p> </div> ); }; export default Author;
src/power-sheet/PowerSheet.js
Synchro-TEC/apollo
import React from 'react'; import ReactDOM from 'react-dom'; import Proptypes from 'prop-types'; import update from 'immutability-helper'; import ReactList from 'react-list'; import axios from 'axios'; import nanoid from 'nanoid'; import sift from 'sift'; import _get from 'lodash/get'; import _sortBy from 'lodash/sortBy'; import _find from 'lodash/find'; import _findIndex from 'lodash/findIndex'; import _has from 'lodash/has'; import _intersectionWith from 'lodash/intersectionWith'; import _xor from 'lodash/xor'; import _sumBy from 'lodash/sumBy'; import _filter from 'lodash/filter'; import _groupBy from 'lodash/groupBy'; import _map from 'lodash/map'; import GroupedTableBody from './GroupedTableBody'; import { bytesToSize } from './utils.js'; import ColumnActions from './ColumnActions'; import { conditions } from './conditions.js'; import './styles.css'; class PowerSheet extends React.Component { constructor(props) { super(props); this.originalData = []; this.groupedColumns = []; this._distinctsLimited = {}; this._distincts = {}; this.columns = this._extractColumns(props); this.columnsWidths = this._extractColumnsWidth(props); this.cachedRenderedGroup = []; this.cachedRenderedGroupHeighs = []; this._renderItem = this._renderItem.bind(this); this._renderGroupedItem = this._renderGroupedItem.bind(this); this._fixScrollBarDiff = this._fixScrollBarDiff.bind(this); this._fillDistincts = this._fillDistincts.bind(this); this._selectColumn = this._selectColumn.bind(this); this._onSort = this._onSort.bind(this); this._onApplyFilter = this._onApplyFilter.bind(this); this._onCancel = this._onCancel.bind(this); this._handlerDistinctFilters = this._handlerDistinctFilters.bind(this); this._filterDistinct = this._filterDistinct.bind(this); this._handlerConditionFilter = this._handlerConditionFilter.bind(this); this._handlerValueInConditionFilter = this._handlerValueInConditionFilter.bind(this); this._getCurrentDistinctValues = this._getCurrentDistinctValues.bind(this); this._getCurrentSelectedDistinctValues = this._getCurrentSelectedDistinctValues.bind(this); this._getFormatterOnFilter = this._getFormatterOnFilter.bind(this); this._keysThatHasFilter = this._keysThatHasFilter.bind(this); this._getItemHeight = this._getItemHeight.bind(this); this._sumRowSpan = this._sumRowSpan.bind(this); this._groupByMulti = this._groupByMulti.bind(this); this._prepareLocalData = this._prepareLocalData.bind(this); this._prepareRemoteData = this._prepareRemoteData.bind(this); this._prepareData = this._prepareData.bind(this); this._makeHeightsCache = this._makeHeightsCache.bind(this); this._clearCachedRenderedGroup = this._clearCachedRenderedGroup.bind(this); this.sortDesc = false; this.sorts = {}; this.state = { activeColumn: null, activeColumnType: 'text', activeColumnTitle: '', columnPosition: { x: '0px', y: '0px' }, collection: [], currentData: [], message: 'Iniciando o carregamento dos dados', count: 0, filters: {}, filtersByConditions: {}, isGteValueValid: true, isLteValueValid: true, selectedDistinctFilters: {}, distinctFiltersValue: {}, loading: true, sorts: {}, }; } componentDidMount() { this.props.fetch.hasOwnProperty('data') ? this._prepareLocalData() : this._prepareRemoteData(); window.addEventListener('resize', this._fixScrollBarDiff(true)); } componentDidUpdate() { this._fixScrollBarDiff(); } componentWillUnmount() { window.removeEventListener('resize', this._fixScrollBarDiff); } /** * Prepara os dados recebido pelo fetch {data} * * * @memberof PowerSheet */ _prepareLocalData() { this.originalData = this.props.fetch.data; const preparedDataState = this._prepareData(this.props.fetch.data); this.setState(preparedDataState, this._fixScrollBarDiff); } /** * Prepara os dados recebidos pelo fetch remoto {url, data, params} * * * @memberof PowerSheet */ _prepareRemoteData() { let config = { method: this.props.fetch.method, url: this.props.fetch.url, onDownloadProgress: e => { const newState = update(this.state, { message: { $set: `${bytesToSize(e.loaded)} carregados...` } }); this.setState(newState); }, }; if (this.props.fetch.params) { this.props.fetch.method === 'get' ? (config.params = this.props.fetch.params) : (config.data = this.props.fetch.params); } axios(config) .then(response => { const data = this.props.hasOwnProperty('rootProp') ? response.data[this.props.rootProp] : response.data; this.originalData = data; const preparedDataState = this._prepareData(data); this.setState(preparedDataState, this._fixScrollBarDiff); }) .catch(error => { console.error(error); const newState = update(this.state, { message: { $set: error } }); this.setState(newState); }); } /** * Prepara os dados recebidos de forma única, tanto recebidos pelo fetch local ou pelo fetch remoto * * @param {any} data * * @memberof PowerSheet */ _prepareData(data) { const distincts = this._fillDistincts(); const currentData = this.groupedColumns.length ? this._groupByMulti(data, _map(_filter(this.columns, { groupBy: true }), 'key')) : data; if (this.groupedColumns.length) { this._clearCachedRenderedGroup(); this._makeHeightsCache(currentData); } return update(this.state, { message: { $set: '' }, currentData: { $set: currentData }, distinctValues: { $set: distincts }, }); } /** * Faz o cache das alturas das linhas baseado nos rowsapn da linha agrupada * * @param {any} currentData * * @memberof PowerSheet */ _makeHeightsCache(currentData) { this.cachedRenderedGroupHeighs = []; for (let i = 0; i < currentData.length; i++) { let row = currentData[i]; this._sumRowSpan(row); this.cachedRenderedGroupHeighs.push(row.rowSpan * this.props.rowHeight); } } /** * Limpa o cache dos componentes que já foram montados * * * @memberof PowerSheet */ _clearCachedRenderedGroup() { this.cachedRenderedGroup = []; } /** * Agrupa os dados através valores groupBy recebidos * * @param {any} list * @param {any} values * @returns * * @memberof PowerSheet */ _groupByMulti(list, values) { if (!values.length) { return list; } let grouped = _groupBy(list, values[0]); let result = []; for (let prop in grouped) { result.push({ name: values[0], value: prop, nested: this._groupByMulti(grouped[prop], values.slice(1)), }); } return result; } /** * Ajusta os espaçamentos das colunas quando a barra de rolagem está visivel e deixa homogenio o comportamento * no MAC. LINUX e Windows * * @param {boolean} [shouldUpdate=false] * * @memberof PowerSheet */ _fixScrollBarDiff(shouldUpdate = false) { const container = ReactDOM.findDOMNode(this); let scrollAreaWidth = container.offsetWidth; let innerContainer = this.groupedColumns.length ? '.pw-table-grouped-tbody' : '.pw-table-tbody'; let tableContainer = container.querySelector(innerContainer); let tableRow = container.querySelector(`${innerContainer} .pw-table-tbody-row`); let tableWidth = null; if (tableRow) { tableWidth = tableRow.offsetWidth; } if (tableWidth !== null) { let headerContainer = container.querySelector('.pw-table-header'); let styles = window.getComputedStyle(tableContainer); let border = styles.borderRight.split(' ')[0]; const borderSize = parseInt(border.match(/(?:\d*\.)?\d+/g)[0], 10); headerContainer.style.paddingRight = `${scrollAreaWidth - borderSize - tableWidth}px`; } const headerContainer = container.querySelector('.pw-table-header-row'); if (headerContainer) { const fisrtMargin = 15; const lastMargin = 15; [].slice.call(headerContainer.querySelectorAll('.pw-table-header-cell')).forEach((cell, i) => { if (!this.columns[i].width) { this.columns[i].width = i === 0 ? cell.offsetWidth - fisrtMargin : cell.offsetWidth - lastMargin; } }); } if (shouldUpdate) { this.forceUpdate(); } } /** * Extrai os dados das colunas (SheetColumns) que são children do PowerTable * * @param {any} props * @returns * * @memberof PowerSheet */ _extractColumns(props) { let cols = React.Children.map(props.children, child => { if (child.props.groupBy) { this.groupedColumns.push(child.props.dataKey); } return { title: child.props.columnTitle, key: child.props.dataKey, formatter: child.props.formatter, formatterOnFilter: child.props.formatterOnFilter, searchable: child.props.searchable, groupBy: child.props.groupBy, width: child.props.width, }; }); let nonGroupedColumns = _filter(cols, { groupBy: false }); let groupedCols = _filter(cols, { groupBy: true }); return groupedCols.concat(nonGroupedColumns); } /** * Extrai os widths que são recebidos pelas colunas * * @param {any} props * @returns * * @memberof PowerSheet */ _extractColumnsWidth(props) { let widths = []; React.Children.forEach(props.children, child => widths.push(child.props.width)); return widths; } /** * Define a coluna que está selecionada * * @param {any} dataKey * @param {any} dataType * @param {any} columnTitle * @param {any} e * * @memberof PowerSheet */ _selectColumn(dataKey, dataType, columnTitle, e) { let activeColumn = dataKey === this.state.activeColumn ? null : dataKey; let activeColumnType = activeColumn ? dataType : 'text'; let selectedColumn = _find(this.columns, { key: activeColumn }); let columnIsSearchable = selectedColumn && selectedColumn.searchable; const screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; const colunmActionWidth = 250; const columnActionHeight = 451; const mouseGutter = 20; let xPosition = e.nativeEvent.x; let yPosition = e.nativeEvent.y; if (e.nativeEvent.x + colunmActionWidth >= screenWidth) { xPosition = e.nativeEvent.x - colunmActionWidth - mouseGutter; } if (e.nativeEvent.y + columnActionHeight >= screenHeight && columnIsSearchable) { yPosition = e.nativeEvent.y - columnActionHeight - mouseGutter; } const newPosition = { x: xPosition, y: yPosition }; const newState = update(this.state, { activeColumn: { $set: activeColumn }, activeColumnType: { $set: activeColumnType }, activeColumnTitle: { $set: columnTitle }, columnPosition: { $set: newPosition }, distinctValues: { $set: this._fillDistincts() }, isGteValueValid: { $set: true }, isLteValueValid: { $set: true }, }); this.setState(newState); } /** * Preenche os distincs de cada coluna * * @returns * * @memberof PowerSheet */ _fillDistincts() { for (let i = 0; i < this.columns.length; i++) { let col = this.columns[i]; if (col && col.searchable) { this._distinctsLimited[col.key] = [ ...new Set(this.originalData.slice(0, 200).map(item => _get(item, col.key))), ]; this._distincts[col.key] = [...new Set(this.originalData.map(item => _get(item, col.key)))]; } } return this._distinctsLimited; } /** * Filtra os dados que estão nos distincts, pois por motivos de desenmpenho são enviados apenas 100 valores por vez * para cada coluna. * * @param {any} filterProps * * @memberof PowerSheet */ _filterDistinct(filterProps) { const { value } = filterProps; const dataKey = this.state.activeColumn; if (value) { const contains = val => { //TODO: este if (val) se fez necessário porque um dos dados do array distincs esta vindo como undefined if (val) { return ( val .toString() .toLowerCase() .indexOf(value.toLowerCase()) > -1 ); } }; let itens = _get(this._distincts, dataKey, []).filter(contains); let distincts = itens.slice(0, 199); let oldDistinctFiltersValueState = JSON.stringify(this.state.distinctFiltersValue); let newDistinctFiltersValueState = JSON.parse(oldDistinctFiltersValueState); newDistinctFiltersValueState[dataKey] = value; let oldDistinctState = JSON.stringify(this.state.distinctValues); let newDistinctState = JSON.parse(oldDistinctState); newDistinctState[dataKey] = distincts; let oldState = JSON.stringify(this.state.selectedDistinctFilters); let newState = JSON.parse(oldState); if (newState.hasOwnProperty(dataKey)) { if (!newState[dataKey].includes(value)) { newState[dataKey].push(value); } else { let index = newState[dataKey].indexOf(value); newState[dataKey].splice(index, 1); } } else { newState[dataKey] = [value]; } this.setState( update(this.state, { distinctValues: { $set: newDistinctState }, distinctFiltersValue: { $set: newDistinctFiltersValueState }, }) ); } else { const distincts = this._fillDistincts(); const newState = update(this.state, { distinctValues: { $set: distincts }, }); this.setState(newState); } } /** * Manipula e define o comportamento dos filtros nos valores distincts * * @param {any} filterProps * * @memberof PowerSheet */ _handlerDistinctFilters(filterProps) { const { value } = filterProps; const dataKey = this.state.activeColumn; let oldState = JSON.stringify(this.state.selectedDistinctFilters); let newState = JSON.parse(oldState); if (newState.hasOwnProperty(dataKey)) { if (!newState[dataKey].includes(value)) { newState[dataKey].push(value); } else { let index = newState[dataKey].indexOf(value); newState[dataKey].splice(index, 1); } } else { newState[dataKey] = [value]; } if (!newState[dataKey].length) { delete newState[dataKey]; } this.setState(update(this.state, { selectedDistinctFilters: { $set: newState } })); } /** * Manipula e define o comportamento dos filtros por condição * * @param {any} condition * * @memberof PowerSheet */ _handlerConditionFilter(condition) { const dataKey = this.state.activeColumn; let oldState = JSON.stringify(this.state.filtersByConditions); let newState = JSON.parse(oldState); let conditionValue; if (condition) { conditionValue = condition.value; } else { conditionValue = this.state.activeColumnType === 'text' ? '$in' : '$gt'; } this._generateCondition(newState, dataKey, conditionValue); this.setState( update(this.state, { filtersByConditions: { $set: newState }, }) ); } /** * Gera as condições baseadas no tipo de dado da coluna * * @param {any} newState * @param {any} dataKey * @param {string} [condition=this.state.activeColumnType === 'text' ? '$in' : '$gt'] * * @memberof PowerSheet */ _generateCondition(newState, dataKey, condition = this.state.activeColumnType === 'text' ? '$in' : '$gt') { if (newState.hasOwnProperty(dataKey)) { newState[dataKey].condition = condition; } else { newState[dataKey] = { condition: condition, value: {} }; } } /** * Manipula e define o comportamento dos VALORES dos filtros por condição * * @param {any} name * @param {any} value * * @memberof PowerSheet */ _handlerValueInConditionFilter(name, value) { const dataKey = this.state.activeColumn; let oldState = JSON.stringify(this.state.filtersByConditions); let newState = JSON.parse(oldState); let setValue = function() { newState[dataKey].value[name] = value; }; if (newState.hasOwnProperty(dataKey)) { setValue(); } else { this._generateCondition(newState, dataKey); setValue(); } this.setState( update(this.state, { filtersByConditions: { $set: newState }, isGteValueValid: { $set: name === 'start' ? value !== '' : this.state.isGteValueValid, }, isLteValueValid: { $set: name === 'end' ? value !== '' : this.state.isLteValueValid, }, }) ); } /** * Aplica o sort das colunas * * @param {any} direction * * @memberof PowerSheet */ _onSort(direction) { this.sortDesc = direction !== 'ASC'; this.sorts = {}; this.sorts[this.state.activeColumn] = this.sortDesc; this._onApplyFilter(); } /** * Aplica todos os filtros, por valores distincts ou condição * * * @memberof PowerSheet */ _onApplyFilter() { let perValueFilter = {}; let filtersByConditions = this.state.filtersByConditions; Object.keys(this.state.selectedDistinctFilters).forEach(key => { if (key) { perValueFilter[key] = { $in: this.state.selectedDistinctFilters[key] }; } }); let itens = sift(perValueFilter, this.originalData); let perConditionsFilter = {}; let $andConditions = []; let isGteValueValid = true; let isLteValueValid = true; Object.keys(filtersByConditions).forEach(key => { let conditions = {}; let condition = filtersByConditions[key].condition; if (condition !== '$bet') { let value = filtersByConditions[key].value.only; if (value) { if (condition === '$in' || condition === '$nin') { if (condition === '$in') { value = new RegExp(`${value.toString()}`, 'gi'); } else { value = new RegExp(`[^${value.toString()}]`, 'gi'); } condition = '$regex'; } else { value = parseInt(value, 10); } conditions[condition] = value; perConditionsFilter[key] = conditions; } } else { let { start, end } = filtersByConditions[key].value; isGteValueValid = start ? true : false; isLteValueValid = end ? true : false; let startCondition = {}; let endCondition = {}; startCondition[key] = { $gte: parseInt(start, 10) }; endCondition[key] = { $lte: parseInt(end, 10) }; if (start && end) { if (start.length > 0 && end.length > 0) { $andConditions.push(startCondition, endCondition); } } perConditionsFilter = { $and: $andConditions }; } }); itens = sift(perConditionsFilter, itens); if (this.sorts) { let key = Object.keys(this.sorts)[0]; itens = _sortBy(itens, key); if (this.sorts[key]) { itens.reverse(); } } let currentData = this.groupedColumns.length ? this._groupByMulti(itens, _map(_filter(this.columns, { groupBy: true }), 'key')) : itens; const newState = update(this.state, { currentData: { $set: currentData }, activeColumn: { $set: null }, activeColumnType: { $set: 'text' }, }); if (this.groupedColumns.length) { this._clearCachedRenderedGroup(); this._makeHeightsCache(currentData); } if (isGteValueValid && isLteValueValid) { this.setState(newState, this._fixScrollBarDiff); } else { const newState = update(this.state, { isGteValueValid: { $set: isGteValueValid }, isLteValueValid: { $set: isLteValueValid }, }); this.setState(newState); } } /** * Método chamado para cancelar / fechar um box de ação * * @memberof PowerSheet */ _onCancel() { const newState = update(this.state, { activeColumn: { $set: null }, activeColumnType: { $set: 'text' }, }); this.setState(newState); } /** * Renderiza os itens quando não há nenhum agrupamento * * @param {any} index * @param {any} key * @returns * * @memberof PowerSheet */ _renderItem(index, key) { let row = this.state.currentData[index]; let cols = this.columns.map((col, i) => { let style = {}; if (this.columnsWidths[i]) { style.flex = `0 0 ${this.columnsWidths[i]}px`; } const valueToPrint = col.formatter ? col.formatter(row, col.key) : _get(row, col.key); return ( <div className="pw-table-tbody-cell" key={nanoid()} style={style}> <div>{valueToPrint}</div> </div> ); }); return ( <div className="pw-table-tbody-row" key={key}> {cols} </div> ); } /** * Calcula os rowspans das linhas agrupadas * * @param {any} row * * @memberof PowerSheet */ _sumRowSpan(row) { if (_has(row, 'nested')) { row.rowSpan = 0; for (let i = 0; i < row.nested.length; i++) { row.nested[i].parent = row; this._sumRowSpan(row.nested[i]); } row.rowSpan = _sumBy(row.nested, r => { return r.rowSpan; }); } else { row.rowSpan = 1; } } /** * Recura o altura de uma linha agrupada * * @param {int} index * @returns * * @memberof PowerSheet */ _getItemHeight(index) { return this.cachedRenderedGroupHeighs[index]; } /** * Renderiza os itens quando há coluans agrupadas * * @param {any} index * @param {any} key * @returns * * @memberof PowerSheet */ _renderGroupedItem(index, key) { let dataRow = this.state.currentData[index]; let row; if (this.cachedRenderedGroup[index]) { row = this.cachedRenderedGroup[index]; } else { row = <GroupedTableBody columns={this.columns} data={dataRow} />; this.cachedRenderedGroup.splice(index, 0, row); } return ( <div className="pw-table-tbody-row" key={key}> <table className="pw-table-grouped" style={{ tableLayout: 'fixed' }}> {row} </table> </div> ); } /** * Recupera os valores distincts da coluna ativa * * @returns * * @memberof PowerSheet */ _getCurrentDistinctValues() { const { activeColumn, distinctValues } = this.state; return activeColumn && distinctValues[activeColumn] ? distinctValues[activeColumn] : []; } /** * Recupera os valores distincts selecionados da coluna ativa * * @returns * * @memberof PowerSheet */ _getCurrentSelectedDistinctValues() { const { activeColumn, selectedDistinctFilters } = this.state; return activeColumn && selectedDistinctFilters[activeColumn] ? selectedDistinctFilters[activeColumn] : []; } /** * Recupera os valores por condição da coluna ativa * * @returns * * @memberof PowerSheet */ _getCurrentFilterByConditionValues() { const { activeColumn, filtersByConditions } = this.state; return activeColumn && filtersByConditions[activeColumn] ? filtersByConditions[activeColumn] : { condition: '', value: {} }; } _getCurrentColumnCondition() { const { activeColumn, filtersByConditions, activeColumnType } = this.state; let condition = {}; if (filtersByConditions.hasOwnProperty(activeColumn)) { let recoveredIndex = _findIndex(conditions[activeColumnType], condition => { return condition.value === filtersByConditions[activeColumn].condition; }); condition = conditions[activeColumnType][recoveredIndex]; } else { condition = conditions[activeColumnType][0]; } return condition; } /** * Verifica se um campo é "Pesquisável" ou não * * @returns * * @memberof PowerSheet */ _getSearchable() { let isSearchable = false; if (this.state.activeColumn) { isSearchable = _find(this.columns, { key: this.state.activeColumn }).searchable; } return isSearchable; } /** * Recupera os formatters da coluna ativa * * @returns * * @memberof PowerSheet */ _getFormatterOnFilter() { let formatter; if (this.state.activeColumn) { formatter = _find(this.columns, { key: this.state.activeColumn }).formatterOnFilter; } return formatter; } /** * Recupera as keys das colunas que tem filtro * * @returns * * @memberof PowerSheet */ _keysThatHasFilter() { const { selectedDistinctFilters, filtersByConditions } = this.state; return [...new Set(Object.keys(selectedDistinctFilters).concat(Object.keys(filtersByConditions)))]; } render() { let headers = []; let headerToRender = ''; let dataToRender = ''; let scrollProps = {}; headers = this.props.children.map(chield => { let newProps = { key: nanoid(), isGrouped: !!this.groupedColumns.length }; if (chield.props.dataKey) { newProps.selectedDistinctFilters = this._getCurrentSelectedDistinctValues(); newProps.filtersByConditions = this._getCurrentFilterByConditionValues(); newProps.sorts = this.sorts; newProps.onSelect = this._selectColumn; newProps.filterKeys = this._keysThatHasFilter(); } let props = { ...chield.props, ...newProps }; return React.cloneElement(chield, props); }); if (this.state.currentData.length) { scrollProps.itemRenderer = this._renderItem; scrollProps.length = this.state.currentData.length; scrollProps.type = 'uniform'; scrollProps.pageSize = this.props.pageSize; if (this.groupedColumns.length) { scrollProps.itemRenderer = this._renderGroupedItem; // scrollProps.itemSizeEstimator = this._getItemHeight; scrollProps.itemSizeGetter = this._getItemHeight; scrollProps.type = 'variable'; if (this.props.pageSize > this.groupedColumns.length) { scrollProps.pageSize = this.groupedColumns.length; } let hs = _intersectionWith(headers, this.groupedColumns, (header, key) => { return _has(header.props, 'dataKey') && key === header.props.dataKey; }); let diff = _xor(headers, hs); headers = hs.concat(diff); headerToRender = ( <table className="pw-table-grouped" style={{ tableLayout: 'fixed' }}> <thead> <tr>{headers}</tr> </thead> </table> ); } else { headerToRender = headers; } } let infoClasses = 'pw-table-info'; if (this.originalData.length === 0) { infoClasses += ' active'; } if (this.state.currentData.length > 0) { dataToRender = ( <div className={this.groupedColumns.length > 0 ? 'pw-table-grouped-tbody' : 'pw-table-tbody'} style={{ maxHeight: `${this.props.containerHeight}px` }} > <ReactList {...scrollProps} /> </div> ); } else { dataToRender = ( <div className="pw-table-row--results-not-found"> <span> Não foram encontrados resultados </span> </div> ); } return ( <div className="pw-table"> <div className={infoClasses}> {!this.originalData.length ? ( <i className="fa fa-circle-o-notch fa-spin fa-lg fa-fw" style={{ marginRight: '10px' }} /> ) : ( '' )} {this.state.message} </div> <div className="pw-table-header"> <div className="pw-table-header-row">{headerToRender}</div> </div> {dataToRender} <ColumnActions activeColumn={this.state.activeColumn} columnTitle={this.state.activeColumnTitle} condition={this._getCurrentColumnCondition()} dataType={this.state.activeColumnType} distinctValues={this._getCurrentDistinctValues()} filters={this.state.filters} filtersByConditions={this._getCurrentFilterByConditionValues()} formatterOnFilter={this._getFormatterOnFilter()} handlerConditionFilter={this._handlerConditionFilter} handlerValueInConditionFilter={this._handlerValueInConditionFilter} isGteValueValid={this.state.isGteValueValid} isLteValueValid={this.state.isLteValueValid} isVisible={this.state.activeColumn !== null} onApplyFilters={this._onApplyFilter} onCancel={this._onCancel} onFilterDistinct={this._filterDistinct} onSelect={this._selectColumn} onSelectValueOnFilter={this._handlerDistinctFilters} onSort={this._onSort} searchable={this._getSearchable()} selectedDistinctValues={this._getCurrentSelectedDistinctValues()} sorts={this.sorts} style={{ top: `${this.state.columnPosition.y + 10}px`, left: `${this.state.columnPosition.x + 10}px`, }} /> </div> ); } } PowerSheet.displayName = 'PowerSheet'; PowerSheet.propTypes = { containerHeight: Proptypes.number.isRequired, fetch: Proptypes.oneOfType([ Proptypes.shape({ url: Proptypes.string.isRequired, method: Proptypes.oneOf(['get', 'post']).isRequired, params: Proptypes.object, rootProp: Proptypes.string, }).isRequired, Proptypes.shape({ data: Proptypes.array.isRequired, }).isRequired, ]), pageSize: Proptypes.number.isRequired, rowHeight: Proptypes.number.isRequired, }; export default PowerSheet;
web/src/routes.js
xiyanxiyan10/quant
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import Dashboard from './containers/Dashboard'; import Login from './containers/Login'; import User from './containers/User'; import Exchange from './containers/Exchange'; import Algorithm from './containers/Algorithm'; import AlgorithmEdit from './containers/AlgorithmEdit'; import AlgorithmLog from './containers/AlgorithmLog'; export default ( <Route> <Route path="/" component={App}> <IndexRoute component={Dashboard} /> <Route path="/user" component={User} /> <Route path="/exchange" component={Exchange} /> <Route path="/algorithm" component={Algorithm} /> <Route path="/algorithmEdit" component={AlgorithmEdit} /> <Route path="/algorithmLog" component={AlgorithmLog} /> </Route> <Route path="/login" component={Login} /> </Route> );
app/Screens/Home/Home.js
martinvarelaaaa/tintina
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { NavigationActions } from 'react-navigation'; import Home from '../../Components/Home'; const signInNavigator = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: 'SignIn' })], }); const signUpNavigator = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: 'SignUp' })], }); class HomeScreen extends Component { componentDidMount() { // this.props.navigation.dispatch(chatNavigator); } navigateSignIn = () => { this.props.navigation.dispatch(signInNavigator); }; navigateSignUp = () => { this.props.navigation.dispatch(signUpNavigator); }; render() { return ( <Home navigateSignIn={this.navigateSignIn} navigateSignUp={this.navigateSignUp} /> ); } } HomeScreen.propTypes = { navigation: PropTypes.shape({ dispatch: PropTypes.func, }).isRequired, }; export default HomeScreen;
src/js/components/Columns.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import CSSClassnames from '../utils/CSSClassnames'; import Props from '../utils/Props'; import Responsive from '../utils/Responsive'; const CLASS_ROOT = CSSClassnames.COLUMNS; /** * @description Organize children into multiple components based on available width. * * @example * import Columns from 'grommet/components/Columns'; * * <Columns responsive={false} * masonry={true}> * <Box align='center' * pad='medium' * margin='small' * colorIndex='light-2'> * Box 1 * </Box> * <Box align='center' * pad='medium' * margin='small' * colorIndex='light-2'> * Box 2 * </Box> * </Columns> * */ export default class Columns extends Component { constructor(props, context) { super(props, context); this._onResize = this._onResize.bind(this); this._layout = this._layout.bind(this); this.state = { count: 1, maxCount: this.props.maxCount, columnBreakpoints: undefined, initMobile: false, margin: this.props.margin }; } componentDidMount () { if (this.props.masonry) { this._getColumnBreakpoints(); } window.addEventListener('resize', this._onResize); setTimeout(this._layout, 10); } componentWillReceiveProps (nextProps) { this.setState({ relayout: true }); } componentDidUpdate () { if (this.state.relayout) { this.setState({ relayout: false }); this._layout(); } } componentWillUnmount () { window.removeEventListener('resize', this._onResize); clearTimeout(this._layoutTimer); clearTimeout(this._childStylesTimer); } _onResize () { const { initMobile } = this.state; if (initMobile) { if (window.innerWidth > Responsive.smallSize()) { this._getColumnBreakpoints(); } } else { clearTimeout(this._layoutTimer); this._layoutTimer = setTimeout(this._layout, 50); } } _getChildMarginSize (childStyles) { let childMargin; if (childStyles) { let childLeftMargin = childStyles.marginLeft ? parseFloat(childStyles.marginLeft) : 0; let childRightMargin = childStyles.marginRight ? parseFloat(childStyles.marginRight) : 0; childMargin = childLeftMargin + childRightMargin; if (childMargin === 48) { return 'large'; } else if (childMargin === 24) { return 'medium'; } else if (childMargin === 12) { return 'small'; } } return undefined; } _getColumnBreakpoints () { const { initMobile, margin } = this.state; // grab CSS styles from DOM after component mounted // default to small size ($size-small = 192px) const container = findDOMNode(this.containerRef); if (container) { const column = container.childNodes[0]; const child = column.childNodes[0]; let minColumnWidth = 192; let currentMobile = (initMobile && window.innerWidth <= Responsive.smallSize()); if (child) { clearTimeout(this._childStylesTimer); this._childStylesTimer = setTimeout(() => { let childStyles = window.getComputedStyle(child); if (childStyles && childStyles.width) { let childLeftMargin = childStyles.marginLeft ? parseFloat(childStyles.marginLeft) : 0; let childRightMargin = childStyles.marginRight ? parseFloat(childStyles.marginRight) : 0; minColumnWidth = ( parseFloat(childStyles.width) + childLeftMargin + childRightMargin ); } let childMarginSize = margin || this._getChildMarginSize(childStyles); // create array of breakpoints for 1 through this.props.maxCount // number of columns of minColumnWidth width. const columnBreakpoints = Array.apply( undefined, Array(this.props.maxCount) ).map((currentMaxCount, index) => (index + 1) * minColumnWidth); this.setState({ columnBreakpoints: columnBreakpoints, margin: childMarginSize, initMobile: currentMobile }, () => { clearTimeout(this._layoutTimer); this._layoutTimer = setTimeout(this._layout, 50); }); }, 200); } } } _calculateMaxCount () { const { columnBreakpoints } = this.state; const container = findDOMNode(this.containerRef); let maxColumnWidthIndex; if (container && columnBreakpoints) { maxColumnWidthIndex = columnBreakpoints .filter((currentMin) => { return currentMin <= container.offsetWidth; }) .reduce((maxIndex, currentMin, index, columnWidths) => { return (currentMin > columnWidths[maxIndex]) ? index : maxIndex; }, 0); return maxColumnWidthIndex + 1; // return appropriate number of columns } return maxColumnWidthIndex; } _layout () { const { masonry } = this.props; const container = this.containerRef; if (container && !masonry) { // fills columns top to bottom, then left to right const children = React.Children.toArray(this.props.children); let count = 1; const child = container.childNodes[0]; if (child) { const rect = container.getBoundingClientRect(); const childRect = child.getBoundingClientRect(); const widestCount = Math.floor(rect.width / childRect.width); const childrenPerColumn = Math.ceil(children.length / widestCount); count = Math.ceil(children.length / childrenPerColumn); } if (count === 0) { count = 1; } this.setState({ count: count }); } else { // fills columns left to right, then top to bottom // by determining max number of columns (maxCount) const { maxCount } = this.state; const newMaxCount = this._calculateMaxCount(); if (newMaxCount && (maxCount !== newMaxCount)) { this.setState({ maxCount: newMaxCount }); } } } _renderColumns () { const { masonry } = this.props; const children = React.Children.toArray(this.props.children); let groups = []; if (masonry) { // fill columns horizontally for masonry option const { maxCount } = this.state; let columnGroups = {}; React.Children.map(children, (child, index) => { let currentColumn = index % maxCount; if (!columnGroups[currentColumn]) { columnGroups[currentColumn] = []; } // place children into appropriate column if (child) { columnGroups[currentColumn].push(child); } }, this); Object.keys(columnGroups).map((key, index) => { if (columnGroups[index]) { groups.push(columnGroups[index]); } }); } else { // fill columns vertically const { count } = this.state; const childrenPerColumn = Math.ceil(children.length / count); let offset = 0; while (groups.length < count) { groups.push(children.slice(offset, offset + childrenPerColumn)); offset += childrenPerColumn; } } return groups; } render () { const { className, justify, responsive, size } = this.props; const { margin } = this.state; let classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--justify-${justify}`]: justify, [`${CLASS_ROOT}--margin-${margin}`]: margin, [`${CLASS_ROOT}--responsive`]: responsive, [`${CLASS_ROOT}--${size}`]: size }, className ); const restProps = Props.omit(this.props, Object.keys(Columns.propTypes)); const groups = this._renderColumns(); const columns = groups.map((group, index) => ( <div key={index} className={`${CLASS_ROOT}__column`}> {group} </div> )); return ( <div ref={ref => this.containerRef = ref} {...restProps} className={classes}> {columns} </div> ); } } Columns.propTypes = { /** * @property {start|center|between|end} justify - How to align the contents along the main axis. */ justify: PropTypes.oneOf(['start', 'center', 'between', 'end']), margin: PropTypes.oneOf(['small', 'medium', 'large']), /** * @property {PropTypes.bool} masonry - Whether to fill the columns from left-to-right based on the component width (set with size). Defaults to false. The max number of columns can be set with maxCount. */ masonry: PropTypes.bool, /** * @property {PropTypes.number} maxCount - Number of columns to allow for masonry option, based on component width. Responds based on the width of the column children (set with size). */ maxCount: PropTypes.number, /** * @property {PropTypes.bool} responsive - Whether masonry columns should collapse into single, full-width column when the display area narrows (to achive similar behavior as responsive Tiles). Defaults to true. */ responsive: PropTypes.bool, /** * @property {small|medium|large} size - The width of each column. Defaults to medium. */ size: PropTypes.oneOf(['small', 'medium', 'large']) }; Columns.defaultProps = { maxCount: 1, justify: 'start', responsive: true };
src/svg-icons/image/brightness-1.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness1 = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="12" r="10"/> </SvgIcon> ); ImageBrightness1 = pure(ImageBrightness1); ImageBrightness1.displayName = 'ImageBrightness1'; export default ImageBrightness1;
packages/lore-hook-forms-material-ui/src/blueprints/update/Optimistic/index.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import Optimistic from './Optimistic'; export default createReactClass({ render: function() { const { modelName } = this.props; const { model, schema, fieldMap, actionMap, data, validators, fields, actions, ...other } = this.props; return ( <Optimistic modelName={modelName} model={model} schema={schema} fieldMap={fieldMap} actionMap={actionMap} data={data} validators={validators} fields={fields || [ { key: 'question', type: 'custom', props: { render: (form) => { return ( <p> No fields have been provided. </p> ); } } } ]} actions={actions || [ { type: 'raised', props: (form) => { return { label: 'Update', primary: true, disabled: form.hasError, onClick: () => { form.callbacks.onSubmit(form.data) } } } } ]} {...other} /> ); } });
fields/types/text/TextColumn.js
benkroeger/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var TextColumn = React.createClass({ displayName: 'TextColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, getValue () { // cropping text is important for textarea, which uses this column const value = this.props.data.fields[this.props.col.path]; return value ? value.substr(0, 100) : null; }, render () { const value = this.getValue(); const empty = !value && this.props.linkTo ? true : false; const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined; return ( <ItemsTableCell> <ItemsTableValue className={className} to={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}> {value} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = TextColumn;
node_modules/react-bootstrap/es/FormControl.js
nikhil-ahuja/Express-React
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import warning from 'warning'; import FormControlFeedback from './FormControlFeedback'; import FormControlStatic from './FormControlStatic'; import { bsClass, getClassSet, splitBsProps, bsSizes } from './utils/bootstrapUtils'; import { SIZE_MAP, Size } from './utils/StyleConfig'; import { prefix } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType, /** * Only relevant if `componentClass` is `'input'`. */ type: React.PropTypes.string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: React.PropTypes.string, /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <FormControl inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: React.PropTypes.func }; var defaultProps = { componentClass: 'input' }; var contextTypes = { $bs_formGroup: React.PropTypes.object }; var FormControl = function (_React$Component) { _inherits(FormControl, _React$Component); function FormControl() { _classCallCheck(this, FormControl); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormControl.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props, Component = _props.componentClass, type = _props.type, _props$id = _props.id, id = _props$id === undefined ? controlId : _props$id, inputRef = _props.inputRef, className = _props.className, bsSize = _props.bsSize, props = _objectWithoutProperties(_props, ['componentClass', 'type', 'id', 'inputRef', 'className', 'bsSize']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; process.env.NODE_ENV !== 'production' ? warning(controlId == null || id === controlId, '`controlId` is ignored on `<FormControl>` when `id` is specified.') : void 0; // input[type="file"] should not have .form-control. var classes = void 0; if (type !== 'file') { classes = getClassSet(bsProps); } // If user provides a size, make sure to append it to classes as input- // e.g. if bsSize is small, it will append input-sm if (bsSize) { var size = SIZE_MAP[bsSize] || bsSize; classes[prefix({ bsClass: 'input' }, size)] = true; } return React.createElement(Component, _extends({}, elementProps, { type: type, id: id, ref: inputRef, className: classNames(className, classes) })); }; return FormControl; }(React.Component); FormControl.propTypes = propTypes; FormControl.defaultProps = defaultProps; FormControl.contextTypes = contextTypes; FormControl.Feedback = FormControlFeedback; FormControl.Static = FormControlStatic; export default bsClass('form-control', bsSizes([Size.SMALL, Size.LARGE], FormControl));
app/packs/src/components/WellplateList.js
ComPlat/chemotion_ELN
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Table, FormControl } from 'react-bootstrap'; import SVG from 'react-inlinesvg'; export default class WellplateList extends Component { handleReadoutOfWellChange(event, well) { const value = event.target.value; const { wells, handleWellsChange } = this.props; const wellId = wells.indexOf(well); wells[wellId].readout = value; handleWellsChange(wells); } render() { const { wells } = this.props; return ( <div> <Table bordered hover condensed> <thead> <tr> <th width="3%">#</th> <th width="5%">Position</th> <th width="5%">Molecule</th> <th width="11%">Name</th> <th width="11%">External Label</th> <th width="15%">Sum-Formula</th> <th width="25%">Readout</th> <th width="25%">Imported Readout</th> </tr> </thead> <tbody> {wells.map((well, key) => { const id = key + 1; const { sample, position, readout } = well; const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); const positionY = alphabet[position.y - 1]; const positions = positionY + position.x; let svgPath = ''; let sampleName = ''; let externalLabel = ''; let sum_formular = ''; let importedReadout = ''; let svgNode = ''; const style = { resize: 'none', height: 66 }; const inputContainerStyle = { padding: 0 }; if (sample) { svgPath = `/images/molecules/${sample.molecule.molecule_svg_file}`; svgNode = <SVG className="molecule-small" src={svgPath} />; const { external_label, short_label, imported_readout } = sample; sampleName = `${short_label || ''}`; externalLabel = `${external_label || ''}`; importedReadout = imported_readout; sum_formular = sample.molecule_formula; } return ( <tr key={key}> <td>{id}</td> <td>{positions}</td> <td>{svgNode}</td> <td>{sampleName}</td> <td>{externalLabel}</td> <td>{sum_formular}</td> <td style={inputContainerStyle}> <FormControl componentClass="textarea" style={style} value={readout || ''} onChange={event => this.handleReadoutOfWellChange(event, well)} className="no-margin" /> </td> <td style={inputContainerStyle}> <FormControl componentClass="textarea" style={style} value={importedReadout || ''} disabled className="no-margin" /> </td> </tr> ); })} </tbody> </Table> </div> ); } } WellplateList.propTypes = { wells: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types handleWellsChange: PropTypes.func.isRequired };
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
Jastrzebowski/react-router
import React from 'react'; import { Link } from 'react-router'; class Sidebar extends React.Component { //static loadProps (params, cb) { //cb(null, { //assignments: COURSES[params.courseId].assignments //}); //} render () { //var { assignments } = this.props; var assignments = COURSES[this.props.params.courseId].assignments return ( <div> <h3>Sidebar Assignments</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}> <Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}> {assignment.title} </Link> </li> ))} </ul> </div> ); } } export default Sidebar;
src/routes/teacher/StudentTable/index.js
chenwydj/AFLS_edusys
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Student_Table from './StudentTable'; import fetch from '../../../core/fetch'; import Layout from '../../../components/Layout'; export default { path: '/teacher/student_table', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{studentCRUD(action: "R"){student_id,student_name,grade,class}}', }), credentials: 'include', }); const { data } = await resp.json(); console.log('data: ', data); // studentCRUD will be the name of the returned data if (!data || !data.studentCRUD) throw new Error('Failed to load the studentCRUD.'); return { title: 'React Starter Kit', component: <Layout><Student_Table studentCRUD={data.studentCRUD} /></Layout>, }; }, };
src/components/lessons/LessonBase.js
pshrmn/cryptonite
import React from 'react'; import 'scss/lesson.scss'; export default function LessonBase(props) { const { title, children } = props; return ( <div className='lesson'> <h1>{ title }</h1> { children } </div> ); }
frontend-web-v2/src/containers/NotFound.js
ClubCedille/jardiniot
import React from 'react'; import { Link } from 'react-router-dom'; export default () => ( <div id="notfound"> <div className="notfound"> <div className="notfound-404"> <h1>Oups!</h1> </div> <h2>404 - Page inexistante</h2> <p>La page que vous recherchez a peut-être été supprimée si son nom a été modifié ou est temporairement indisponible.</p> <br/> <Link to="/">Revenir à l'accueil</Link> </div> </div> );
imports/ui/components/Loader/LinearLoader.js
ShinyLeee/meteor-album-app
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withStyles } from 'material-ui/styles'; import { LinearProgress } from 'material-ui/Progress'; class LinearLoader extends Component { static propTypes = { style: PropTypes.object, classes: PropTypes.object.isRequired, } shouldComponentUpdate() { return false; } render() { const { style, classes } = this.props; return ( <LinearProgress style={style} classes={{ root: classes.root }} mode="indeterminate" /> ); } } const styles = { root: { position: 'fixed', left: 0, top: 64, width: '100%', height: 5, zIndex: 999, }, }; export default withStyles(styles)(LinearLoader);
test/test_helper.js
AmmarCloudtech/Simple-Blog
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/Footer.js
dixitc/cherry-web-portal
import React from 'react'; import {ListItem} from 'material-ui/List'; /*Need to update footer with links*/ const Footer = () => { return ( <footer className={'foot'} style={(window.innerWidth < 400) ? {display:'none'} : {opacity:'1'}} > <ListItem innerDivStyle={{height:'20px',lineHeight:'20px',paddingTop:'10px',paddingBottom:'10px'}} primaryText={<span style={{fontSize:'12px'}}>a <b>Tricon Infotech</b> product</span>} rightIcon={<span style={{width:'100px',fontSize:'12px'}}></span>}/> </footer> ) } export default Footer;
src/components/SeriesCircuit.js
hansenjl/circuit-builder-client
import React from 'react'; import Resistor from './Resistor' const Wire = <div className="Circuit Wire"></div> const SeriesCircuit = ({circuitData}) => ( <div className="SeriesCircuit"> <div className="TopRow"> <div className="Circuit Top LCorner"></div> {circuitData.loops[0].resistors.length > 1 ? <Resistor resistor={circuitData.loops[0].resistors[1]} /> : Wire} {circuitData.loops[0].resistors.length > 11 ? <Resistor resistor={circuitData.loops[0].resistors[11]} /> : Wire} <div className="Circuit Battery">{circuitData.tot_voltage} V</div> {circuitData.loops[0].resistors.length > 12 ? <Resistor resistor={circuitData.loops[0].resistors[12]} /> : Wire} {circuitData.loops[0].resistors.length > 2 ? <Resistor resistor={circuitData.loops[0].resistors[2]} /> : Wire} <div className="Circuit TopRCorner"></div> </div> <div className="MiddleRow"> {circuitData.loops[0].resistors.length > 3 ? <Resistor resistor={circuitData.loops[0].resistors[3]} /> : Wire} <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> {circuitData.loops[0].resistors.length > 4 ? <Resistor resistor={circuitData.loops[0].resistors[4]} /> : Wire} </div> <div className="MiddleRow"> {circuitData.loops[0].resistors.length > 9 ? <Resistor resistor={circuitData.loops[0].resistors[9]} /> : Wire} <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> {circuitData.loops[0].resistors.length > 10 ? <Resistor resistor={circuitData.loops[0].resistors[10]} /> : Wire} </div> <div className="MiddleRow"> {circuitData.loops[0].resistors.length > 5 ? <Resistor resistor={circuitData.loops[0].resistors[5]} /> : Wire} <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> <div className="Circuit"></div> {circuitData.loops[0].resistors.length > 6 ? <Resistor resistor={circuitData.loops[0].resistors[6]} /> : Wire} </div> <div className="BottomRow"> <div className="Circuit LCorner"></div> {circuitData.loops[0].resistors.length > 7 ? <Resistor resistor={circuitData.loops[0].resistors[7]} /> : Wire} {circuitData.loops[0].resistors.length > 13 ? <Resistor resistor={circuitData.loops[0].resistors[13]} /> : Wire} <div className="Circuit Resistor">{circuitData.loops[0].resistors[0].resistance} Ω </div> {circuitData.loops[0].resistors.length > 14 ? <Resistor resistor={circuitData.loops[0].resistors[14]} /> : Wire} {circuitData.loops[0].resistors.length > 8 ? <Resistor resistor={circuitData.loops[0].resistors[8]} /> : Wire} <div className="Circuit RCorner"></div> </div> </div> ) export default SeriesCircuit;
src/svg-icons/editor/mode-comment.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorModeComment = (props) => ( <SvgIcon {...props}> <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"/> </SvgIcon> ); EditorModeComment = pure(EditorModeComment); EditorModeComment.displayName = 'EditorModeComment'; EditorModeComment.muiName = 'SvgIcon'; export default EditorModeComment;
src/wics/node_modules/case-sensitive-paths-webpack-plugin/demo/src/AppRoot.component.js
civiclee/Hack4Cause2017
import React, { Component } from 'react'; export default class AppRoot extends Component { // we can't use `connect` in this component, so must do naiively: constructor(props) { super(props); this.state = { }; } render() { return ( <div> <h1>This is just an empty demo</h1> <p>(Run the tests.)</p> </div> ); } }
fields/components/columns/IdColumn.js
benkroeger/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var IdColumn = React.createClass({ displayName: 'IdColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, list: React.PropTypes.object, }, renderValue () { const value = this.props.data.id; if (!value) return null; return ( <ItemsTableValue padded interior title={value} to={Keystone.adminPath + '/' + this.props.list.path + '/' + value} field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = IdColumn;
src/components/ReviewList.js
reactivepod/fido-web
import React from 'react'; import ReviewItem from './ReviewItem'; const ReviewList = ({ reviews, selected }) => { const generateKey = (id, review) => `${id}-${review.date.valueOf()}`; if (reviews[selected]) { const podcast = reviews[selected].meta; return ( <div> <section className="meta"> <div> <h2 className="meta__name">{podcast.name}</h2> <p className="meta__description">{podcast.description}</p> </div> <img src={podcast.image['170']} className="meta__image" /> </section> <section className="reviews"> <ul className="reviews__list"> {reviews[selected].reviews.map((review) => <ReviewItem data={review} key={generateKey(selected, review)} />)} </ul> </section> </div> ); } else { return <div /> } } export default ReviewList;
src/pages/city.js
voidxnull/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import ApiClient from '../api/client' import { API_HOST } from '../config'; import { addCountry, addCity, setCityPosts } from '../actions'; import Header from '../components/header'; import Footer from '../components/footer'; import River from '../components/river_of_posts'; import Sidebar from '../components/sidebar' import { ActionsTrigger } from '../triggers'; import { defaultSelector } from '../selectors'; class CityPage extends Component { static displayName = 'CityPage'; static async fetchData(params, store, client) { let city = await client.city(params.city); let country = await client.country(params.country); store.dispatch(addCity(city)); store.dispatch(addCountry(country)); let cityPosts = client.cityPosts(city.id); store.dispatch(setCityPosts(city.id, await cityPosts)); } render() { const { is_logged_in, current_user, posts, geo, users } = this.props; const client = new ApiClient(API_HOST); const triggers = new ActionsTrigger(client, this.props.dispatch); let thisCityPosts = []; if(geo && geo.cityPosts && this.props.params.city in geo.cityPosts) { thisCityPosts = geo.cityPosts[this.props.params.city]; } return ( <div> <Header is_logged_in={is_logged_in} current_user={current_user} /> <div className="page__container"> <div className="page__body"> <Sidebar current_user={current_user} /> <div className="page__body_content"> <div className="tag_header"> {(geo && geo.cities && geo.countries && this.props.params.city in geo.cities && this.props.params.country in geo.countries) ? `${geo.cities[this.props.params.city].asciiname}, ${geo.countries[this.props.params.country].name}` : '' } </div> <div className="page__content page__content-spacing"> <River river={thisCityPosts} posts={posts} users={users} current_user={current_user} triggers={triggers}/> {/*<Followed/> */} {/*<Tags/>*/} </div> </div> </div> </div> <Footer/> </div> ) } } export default connect(defaultSelector)(CityPage);
src/App.js
rahulp959/airstats.web
import React from 'react' import PropTypes from 'prop-types' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import { Provider } from 'react-redux' import ReactGA from 'react-ga' import About from './Containers/About/About' import Privacy from './Containers/About/Privacy/Privacy' import FAQ from './Containers/FAQ/FAQ' import Flight from './Containers/Flight/Flight' import Footer from './Containers/Footer/Footer' import Header from './Containers/Header/Header' import Home from './Containers/Home/Home' import FlightMap from './Containers/FlightMap/FlightMap' import RouteAnalyzer from './Containers/RouteAnalyzer/RouteAnalyzer' import Search from './Containers/Search/Search' import Top10 from './Containers/Top10/Top10' import NotFound from './Containers/NotFound/NotFound' import './App.scss' ReactGA.initialize('UA-99000586-1', { debug: false }) const logPageView = () => { ReactGA.set({page: window.location.pathname + window.location.search}) ReactGA.pageview(window.location.pathname + window.location.search) return null } const App = ({store}) => ( <Provider store={store}> <Router> <div className='container'> <Route path='/' component={logPageView} /> <Header /> <Switch> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> <Route exact path='/about/privacy' component={Privacy} /> <Route exact path='/faq' component={FAQ} /> <Route exact path='/flight/map' component={FlightMap} /> <Route exact path='/statistics/top' component={Top10} /> <Route path='/flight/:flightId' component={Flight} /> <Route path='/search/:searchTerm' component={Search} /> <Route path='/analyzer/:dep?/:dest?' component={RouteAnalyzer} /> <Route component={NotFound} /> </Switch> <Footer /> </div> </Router> </Provider> ) App.propTypes = { store: PropTypes.object.isRequired } export default App
App/components/UnassignedEventList/index.js
araneforseti/caretaker-app
import React from 'react'; import { View } from 'react-native'; import EventList from '../shared/EventList'; import container from './container'; import styles from './styles'; function UnassignedEventList({events}) { return <View style={styles.container}> <EventList events={events} /> </View>; } export default container(UnassignedEventList);
src/svg-icons/hardware/desktop-windows.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDesktopWindows = (props) => ( <SvgIcon {...props}> <path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z"/> </SvgIcon> ); HardwareDesktopWindows = pure(HardwareDesktopWindows); HardwareDesktopWindows.displayName = 'HardwareDesktopWindows'; export default HardwareDesktopWindows;
src/svg-icons/image/crop-16-9.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop169 = (props) => ( <SvgIcon {...props}> <path d="M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z"/> </SvgIcon> ); ImageCrop169 = pure(ImageCrop169); ImageCrop169.displayName = 'ImageCrop169'; ImageCrop169.muiName = 'SvgIcon'; export default ImageCrop169;
src/components/decoline_list.js
lizarraldeignacio/personal-website
import React, { Component } from 'react'; import DecolineItem from './decoline_item'; import _ from 'lodash'; import { firebaseConnect } from 'react-redux-firebase'; /** DecolineList list of Decoline elements Params: elements: The elements that the list will contain path: The path of the firebase database of the list itemIconRemove: The icon of the remove action of each element auth: A flag that indicates if the user is authenticated or not **/ class DecolineList extends Component { constructor(props) { super(props); } remove(title) { const key = _.findKey(this.props.elements, (item) => {return title == item["title"]}); this.props.firebase.remove(`${this.props.path}/${key}`); } renderList() { return ( _.map(this.props.elements, element => { return ( <DecolineItem key = {element["title"]} title = {element["title"]} description = {element["description"]} itemIconRemove = {this.props.itemIconRemove} remove = {this.remove.bind(this)} auth = {this.props.auth} /> ); }) ); } render() { return ( <div className="o-grid"> {this.props.elements && this.renderList.bind(this)()} </div> ); } } export default firebaseConnect()(DecolineList);
app/components/timer/Timer.js
ArcBees/Tempora
import moment from 'moment'; import React, { Component } from 'react'; import DatePicker from 'react-datepicker'; import TimePicker from 'rc-time-picker'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import * as StorageService from '../../services/StorageService'; import * as WorklogService from '../../services/WorklogService'; import * as ProjectService from '../../services/ProjectService'; import * as IssueService from '../../services/IssueService'; import * as DateUtils from '../../utils/DateUtils'; import './Timer.scss'; const STATE = { time: '0:00', timeSeconds: '00', projectId: StorageService.getActiveProjectId(), projectName: StorageService.getActiveProjectName(), issueId: StorageService.getActiveIssueId(), issueKey: StorageService.getActiveIssueKey(), date: StorageService.getActiveDate() ? StorageService.getActiveDate() : moment(), comment: StorageService.getActiveComment() ? StorageService.getActiveComment() : '', selectedWorklogId: null, viewType: StorageService.getViewType() ? StorageService.getViewType() : 'timer' }; export default class Timer extends Component { static contextTypes = { settings: PropTypes.object, user: PropTypes.object }; constructor(props) { super(props); this.state = STATE; this.time = 0; this.showTimer(); window.eventEmitter.addListener('selectWorklog', this.setSelectedWorklog.bind(this)); window.eventEmitter.addListener('projectChange', this.fetchProject.bind(this)); window.eventEmitter.addListener('issueChange', this.fetchIssue.bind(this)); } // Timer states startTimer() { StorageService.setDateStartMoment(moment().toISOString()); StorageService.startTimer(); this.tick(); } showTimer() { window.eventEmitter.emitEvent('unselectActiveWorklog'); this.setState({ time: '0:00', timeSeconds: '00', projectName: StorageService.getActiveProjectName(), projectId: StorageService.getActiveProjectId(), issueId: StorageService.getActiveIssueId(), issueKey: StorageService.getActiveIssueKey(), comment: StorageService.getActiveComment() ? StorageService.getActiveComment() : '', date: StorageService.getActiveDate() ? StorageService.getActiveDate() : moment(), selectedWorklogId: null, viewType: 'timer' }); StorageService.setViewType('timer'); if (StorageService.isTimerStarted() === 'true') { if (StorageService.isTimerPaused() === 'false') { this.tick(); } else { const startTime = StorageService.getDateStartMoment(); const endTime = StorageService.getDatePauseMoment(); this.time = this.getDurationBetweenDates(moment(endTime), moment(startTime)); this.setState({ time: this.getTimeFromMilliseconds(), timeSeconds: this.getSecondsFromDuration() }); } } } pauseTimer() { StorageService.setDatePauseMoment(moment().toISOString()); StorageService.pauseTimer(); } unpauseTimer() { const startedAt = moment(StorageService.getDateStartMoment()); const pausedAt = moment(StorageService.getDatePauseMoment()); const timeElapsed = pausedAt.diff(startedAt); StorageService.setDateStartMoment(moment().subtract(moment.duration(timeElapsed)).toISOString()); StorageService.unpauseTimer(); this.tick(); } stopTimer() { if (!StorageService.getActiveProjectId()) { window.eventEmitter.emitEvent('requestModal', ['Oups!', 'You need to select a project.']); } else if (!StorageService.getActiveIssueKey()) { window.eventEmitter.emitEvent('requestModal', ['Oups!', 'You need to select a task.']); } else { StorageService.stopTimer(); StorageService.setTimeSpentInSeconds(Math.round(moment.duration(this.time).asSeconds())); const worklog = this.buildWorklog(); WorklogService.createWorklog(worklog) .then(() => { window.eventEmitter.emitEvent('refreshWorklogsAndTime'); this.setState({ time: '0:00', timeSeconds: '00' }); this.clearData(); }) .catch(error => window.eventEmitter.emitEvent('requestModal', ['Oups!', error])); } } // Worklogs setSelectedWorklog(worklog) { this.setState({ selectedWorklogId: worklog.id, projectId: worklog.issue.projectId, issueId: worklog.issue.id, issueKey: worklog.issue.key, viewType: 'worklog' }); StorageService.setWorklogProjectId(worklog.issue.projectId); StorageService.setViewType('worklog'); // TODO: Find a lighter way to get the project name than fetching the entire project ProjectService.getProject(worklog.issue.projectId) .then(project => { this.setState({ projectName: project.name, duration: worklog.timeSpentSeconds, time: WorklogService.getTimeSpentInHours(worklog.timeSpentSeconds), timeSeconds: '00', issue: worklog.issue.key, date: worklog.dateStarted, comment: worklog.comment }); StorageService.setWorklogProjectName(project.name); }); } saveSelectedWorklog() { const worklog = this.buildWorklogForUpdate(); WorklogService.updateWorklog(this.state.selectedWorklogId, worklog) .then(() => { window.eventEmitter.emitEvent('refreshWorklogsAndTime'); this.showTimer(); }) .catch(error => window.eventEmitter.emitEvent('requestModal', ['Oups!', error])); } deleteSelectedWorklog() { if (confirm('Are you sure you want to delete this entry?')) { WorklogService.deleteWorklog(this.state.selectedWorklogId) .then(() => { window.eventEmitter.emitEvent('refreshWorklogsAndTime'); this.showTimer(); }) .catch(error => window.eventEmitter.emitEvent('requestModal', ['Oups!', error])); } } // Functions and helpers tick() { const startTime = StorageService.getDateStartMoment(); this.time = this.getDurationBetweenDates(moment(), moment(startTime)); this.setState({ time: this.getTimeFromMilliseconds(), timeSeconds: this.getSecondsFromDuration() }); if (StorageService.isTimerStarted() === 'true' && StorageService.isTimerPaused() === 'false') { // The tick will be called multiple times per second but it will result // in a quicker response when clicking on the play/stop button setTimeout(() => this.tick(), 500); } } buildWorklog() { return { author: { name: this.context.user.name }, issue: { projectId: StorageService.getActiveProjectId(), key: StorageService.getActiveIssueKey() }, timeSpentSeconds: this.getRoundedTime(), dateStarted: StorageService.getDateStartMoment(), comment: this.state.comment }; } buildWorklogForUpdate() { return { timeSpentSeconds: this.state.duration > 0 ? this.state.duration : 60, dateStarted: moment(this.state.date).toISOString(), comment: this.state.comment, issue: { projectId: this.state.projectId, key: this.state.issueKey } }; } getTimeFromMilliseconds() { return moment.duration(this.time, 'milliseconds').format(DateUtils.DateFormat.TIME, { trim: false }); } getDurationBetweenDates(now, then) { return now.diff(then); } getSecondsFromDuration() { const seconds = moment.duration(this.time, 'milliseconds').seconds(); return seconds <= 9 ? '0' + seconds : seconds; } getRoundedTime() { const round = this.context.settings.timeRound * 60; const seconds = StorageService.getTimeSpentInSeconds(); if (round > 0) { if (seconds < round) { return round; } const rounded = (seconds % round) >= round / 2 ? parseInt(seconds / round, 10) * round + round : parseInt(seconds / round, 10) * round; StorageService.setTimeSpentInSeconds(rounded); return rounded; } return seconds; } fetchProject() { if (this.state.viewType === 'timer') { StorageService.setActiveIssueId(''); StorageService.setActiveIssueKey(''); } else { StorageService.setWorklogIssueId(''); StorageService.setWorklogIssueKey(''); } ProjectService.getProject( this.state.viewType === 'timer' ? StorageService.getActiveProjectId() : StorageService.getWorklogProjectId()) .then(project => { this.setState({ projectId: project.id, projectName: project.name, time: '0:00', timeSeconds: '00', issueId: '', issueKey: '-', date: moment(), comment: '' }); if (this.state.viewType === 'timer') { StorageService.setActiveProjectId(project.id); StorageService.setActiveProjectName(project.name); if (StorageService.isTimerStarted() === 'true' && StorageService.isTimerPaused() === 'false') { this.tick(); } } else { StorageService.setWorklogProjectId(project.id); StorageService.setWorklogProjectName(project.name); } }); } fetchIssue() { IssueService.getIssue( this.state.viewType === 'timer' ? StorageService.getActiveIssueId() : StorageService.getWorklogIssueId()) .then(issue => this.setState({ issueId: issue.id, issueKey: issue.key })); } clearData() { StorageService.clearActiveTimer(); StorageService.stopTimer(); this.setState(STATE); } clearDataConfirm() { if (confirm('Are you sure you want to delete this?')) { this.clearData(); } } // Handling components change timeChange(time) { this.setState({ duration: ((time.minutes() * 60) + (time.hours() * 3600)) }); } dateChange(date) { this.setState({ date }); if (this.state.viewType === 'timer') { StorageService.setActiveDate(moment(date).toISOString()); } } commentChange(event) { this.setState({ comment: event.target.value }); if (this.state.viewType === 'timer') { StorageService.setActiveComment(this.state.comment); } } // Template rendering renderSeconds() { if (this.state.timeSeconds) { return (<span className="timer__clock__time__seconds">.{this.state.timeSeconds}</span>); } return false; } renderTime() { if (this.state.viewType === 'timer') { return (<span className="timer__clock__time">{this.state.time}{this.renderSeconds()}</span>); } return ( <TimePicker showSecond={false} value={moment() .set({ hour: 0, minute: 0, second: 0, millisecond: 0 }) .add(this.state.duration, 'seconds')} onChange={this.timeChange.bind(this)} className="timer__clock__time" /> ); } renderButtons() { const buttons = []; if (this.state.viewType === 'timer') { if (StorageService.isTimerStarted() === 'true') { if (StorageService.isTimerPaused() === 'true') { buttons.push(<i key="btn-timer-play" className="fa fa-play-circle" aria-hidden="true" onClick={() => this.unpauseTimer()} />); } else { buttons.push(<i key="btn-timer-pause" className="fa fa-pause" aria-hidden="true" onClick={() => this.pauseTimer()} />); } buttons.push(<i key="btn-timer-stop" className="fa fa-floppy-o" aria-hidden="true" onClick={() => this.stopTimer()} />); buttons.push(<i key="btn-timer-clear" className="fa fa-trash-o" aria-hidden="true" onClick={() => this.clearDataConfirm()} />); } else { buttons.push(<i key="btn-timer-start" className="fa fa-play-circle" aria-hidden="true" onClick={() => this.startTimer()} />); } } else if (this.state.viewType === 'worklog') { buttons.push(<i key="btn-timer-save" className="fa fa-floppy-o" aria-hidden="true" onClick={() => this.saveSelectedWorklog()} />); buttons.push(<i key="btn-timer-delete" className="fa fa-trash-o" aria-hidden="true" onClick={() => this.deleteSelectedWorklog()} />); buttons.push(<i key="btn-timer-show" className="fa fa-times-circle" aria-hidden="true" onClick={() => this.showTimer()} />); } return ( <span className="timer__clock__buttons"> {buttons} </span> ); } render() { return ( <div className="timer"> <div className="timer__clock"> {this.renderTime()} {this.renderButtons()} </div> <div className="timer__datas"> <Link to="/projects" className="timer__data"> <h2 className="timer__data__title">Project</h2> <p className="timer__data__label">{this.state.projectName}</p> </Link> <Link to="/issues" className="timer__data"> <h2 className="timer__data__title">Task</h2> <p className="timer__data__label">{this.state.issueKey}</p> </Link> <div className="timer__data timer__data--no-highlight"> <h2 className="timer__data__title">Date</h2> <DatePicker className="timer__data__date" onChange={this.dateChange.bind(this)} selected={moment(this.state.date)} /> </div> <div className="timer__data timer__data--no-highlight"> <h2 className="timer__data__title">Comment</h2> <textarea className="timer__data__textarea" rows="2" cols="10" onChange={this.commentChange.bind(this)} value={this.state.comment} /> </div> </div> </div> ); } }
docs/src/pages/Introduction.js
Semantic-Org/Semantic-UI-React
import PropTypes from 'prop-types' import React from 'react' import { Link, withSiteData } from 'react-static' import { Container, Divider, Grid, Header, Icon, Label, List, Segment } from 'semantic-ui-react' import CodeSnippet from 'docs/src/components/CodeSnippet' import DocsLayout from 'docs/src/components/DocsLayout' import Logo from 'docs/src/components/Logo/Logo' import { semanticUIDocsURL, repoURL } from 'docs/src/utils' const AccordionJSX = `<Accordion panels={[ { title: 'What is a dog?', content: '...' }, { title: 'What kinds are there?', content: '...' }, ]} />` const AccordionHTML = `<div class="ui accordion"> <div class="title"> <i class="dropdown icon"></i> What is a dog? </div> <div class="content"> <p>...</p> </div> <div class="title"> <i class="dropdown icon"></i> What kinds are there? </div> <div class="content"> <p>...</p> </div> </div>` const ButtonJSX = `<Button size='small' color='green'> <Icon name='download' /> Download </Button>` const ButtonHTML = `<button class="ui small green button"> <i class="download icon"></i> Download </button>` const LabelJSX = "<Label image='veronika.jpg' />" const LabelHTML = `<div class="ui image label"> <img src="veronika.jpg"> </div>` const RatingJSX = '<Rating rating={1} maxRating={5} />' const RatingHTML = `<div class="ui rating" data-rating="1" data-max-rating="5" ></div>` const MessageIconJSX = `<Message success icon='thumbs up' header='Nice job!' content='Your profile is complete.' />` const MessageIconHTML = `<div class="ui success message"> <i class="thumbs up icon"></i> <div class="content"> <div class="header"> Nice job! </div> Your profile is complete. </div> </div>` const MessageSubcomponentsJSX = `<Message icon> <Icon name='circle notched' loading /> <Message.Content> <Message.Header> Just one second </Message.Header> We're fetching that content for you. </Message.Content> </Message>` const MessageSubcomponentsHTML = `<div class="ui icon message"> <i class="loading circle notched icon"></i> <div class="content"> <div class="header"> Just one second </div> We're fetching that content for you. </div> </div>` const HeaderAugmentationJSX = `<Header as='h3'> Learn More </Header>` const HeaderAugmentationHTML = `<h3 class="ui header"> Learn More </h3>` const MenuItemLinkAugmentationJSX = `import { Link } from 'react-router-dom' <Menu> <Menu.Item as={Link} to='/home'> Home </Menu.Item> </Menu>` const MenuItemLinkAugmentationHTML = `<div class="ui menu"> <a class="item" href="/home"> Home </a> </div>` const Comparison = ({ jsx, html }) => ( <Segment inverted style={{ backgroundColor: '#2d2d2d' }}> <Grid columns='equal' centered textAlign='left'> <Grid.Column computer='8' largeScreen='7' widescreen='7'> <Label color='grey' size='tiny' attached='top left'> JSX </Label> <CodeSnippet fitted label={false} mode='jsx' value={jsx} /> </Grid.Column> <Grid.Column largeScreen='2' only='large screen' textAlign='center'> <Divider vertical> <Icon inverted name='right arrow circle' /> </Divider> </Grid.Column> <Grid.Column computer='8' largeScreen='7' widescreen='7'> <Label color='grey' size='tiny' attached='top right'> Rendered HTML </Label> <CodeSnippet fitted label={false} mode='html' value={html} /> </Grid.Column> </Grid> </Segment> ) Comparison.propTypes = { jsx: PropTypes.string, html: PropTypes.string, } const Introduction = ({ pkg, title }) => ( <DocsLayout additionalTitle='Introduction' title={title}> <Container id='introduction-page'> <Segment basic textAlign='center'> <Logo centered size='small' /> <Header as='h1' textAlign='center'> Semantic UI React <Header.Subheader>{pkg.description}</Header.Subheader> </Header> </Segment> <Segment basic padded> <Header as='h2' dividing> Introduction </Header> <p> Semantic UI React is the official React integration for{' '} <a href={semanticUIDocsURL}>Semantic UI</a> . </p> <List> <List.Item icon='check' content='jQuery Free' /> <List.Item icon='check' content='Declarative API' /> <List.Item icon='check' content='Augmentation' /> <List.Item icon='check' content='Shorthand Props' /> <List.Item icon='check' content='Sub Components' /> <List.Item icon='check' content='Auto Controlled State' /> </List> <p> Installation instructions are provided in the <Link to='/usage'>Usage</Link> section. </p> </Segment> {/* ---------------------------------------- * jQuery Free * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> jQuery Free </Header> <p> jQuery is a DOM manipulation library. It reads from and writes to the DOM. React uses a virtual DOM (a JavaScript representation of the real DOM). React only <em>writes</em>{' '} patch updates to the DOM, but <em>never reads</em> from it. </p> <p> It is not feasible to keep real DOM manipulations in sync with React's virtual DOM. Because of this, all jQuery functionality has been re-implemented in React. </p> </Segment> {/* ---------------------------------------- * Declarative API * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> Declarative API </Header> <p>Declarative APIs provide for robust features and prop validation.</p> <Comparison jsx={RatingJSX} html={RatingHTML} /> <Comparison jsx={ButtonJSX} html={ButtonHTML} /> </Segment> {/* ---------------------------------------- * Augmentation * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> Augmentation </Header> <p> Control the rendered HTML tag, or render one component <code>as</code> another component. Extra props are passed to the component you are rendering <code>as</code>. </p> <p> Augmentation is powerful. You can compose component features and props without adding extra nested components. This is essential for working with <code>MenuLinks</code> and{' '} <code>react-router</code>. </p> <Comparison jsx={HeaderAugmentationJSX} html={HeaderAugmentationHTML} /> <Comparison jsx={MenuItemLinkAugmentationJSX} html={MenuItemLinkAugmentationHTML} /> </Segment> {/* ---------------------------------------- * Shorthand Props * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> Shorthand Props </Header> <p> Shorthand props generate markup for you, making many use cases a breeze. All object props are spread on the child components. </p> <Header as='h3'>Child Object Arrays</Header> <p> Components with repeating children accept arrays of plain objects. <a href='https://facebook.github.io/react/docs/context.html#parent-child-coupling' target='_blank' rel='noopener noreferrer' > &nbsp;Facebook is fond of this&nbsp; </a> over using context to handle parent-child coupling and so are we. </p> <Comparison jsx={AccordionJSX} html={AccordionHTML} /> <Header as='h3'>{'icon={...}'}</Header> <p> The <code>icon</code> prop is standard for many components. It can accept an Icon{' '} <code>name</code>, an Icon props object, or an <code>{'<Icon />'}</code> instance. </p> <Comparison jsx={MessageIconJSX} html={MessageIconHTML} /> <Header as='h3'>{'image={...}'}</Header> <p> The <code>image</code> prop is standard for many components. It can accept an image{' '} <code>src</code>, an Image props object, or an <code>{'<Image />'}</code> instance. </p> <Comparison jsx={LabelJSX} html={LabelHTML} /> </Segment> {/* ---------------------------------------- * Sub Components * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> Sub Components </Header> <p> Sub components give you complete access to the markup. This is essential for flexibility in customizing components. </p> <Comparison jsx={MessageSubcomponentsJSX} html={MessageSubcomponentsHTML} /> </Segment> {/* ---------------------------------------- * Auto Controlled State * -------------------------------------- */} <Segment basic padded> <Header as='h2' dividing> Auto Controlled State </Header> <p> React has the concept of <a href='https://facebook.github.io/react/docs/forms.html' target='_blank' rel='noopener noreferrer' > &nbsp;controlled and uncontrolled&nbsp; </a> components. </p> <p> Our stateful components self manage their state out of the box, without wiring. Dropdowns open on click without wiring <code>onClick</code> to the <code>open</code> prop. The value is also stored internally, without wiring <code>onChange</code> to <code>value</code>. </p> <p> If you add a <code>value</code> prop or an <code>open</code> prop, the Dropdown delegates control for that one prop to your value. The other props remain auto controlled. Mix and match any number of controlled and uncontrolled props. Add and remove control at any time by adding or removing props. Everything just works. </p> <p> Take a look at our <a href={`${repoURL}/blob/master/src/lib/ModernAutoControlledComponent.js`}> &nbsp; <code>ModernAutoControlledComponent</code> &nbsp; </a> to see how this was done. See the docs try it out live. </p> <Divider hidden section /> <Divider hidden section /> <Divider hidden section /> </Segment> </Container> </DocsLayout> ) Introduction.propTypes = { pkg: PropTypes.shape({ description: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }).isRequired, title: PropTypes.string.isRequired, } export default withSiteData(Introduction)
blueocean-material-icons/src/js/components/svg-icons/action/chrome-reader-mode.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionChromeReaderMode = (props) => ( <SvgIcon {...props}> <path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/> </SvgIcon> ); ActionChromeReaderMode.displayName = 'ActionChromeReaderMode'; ActionChromeReaderMode.muiName = 'SvgIcon'; export default ActionChromeReaderMode;
components/src/Logo/Logo.paths.js
svef/www
import React from 'react' export const Hexagon = () => ( <path className="hexagon" d="M179.900651,143.933364 C179.896894,149.457974 176.022503,156.171679 171.240383,158.932637 L103.586843,197.992427 C98.8076649,200.751686 91.0510903,200.750588 86.2669572,197.992802 L18.7059454,159.047658 C13.9196145,156.288606 10.0425734,149.570834 10.046328,144.048761 L10.0993493,66.0666357 C10.1031056,60.5420255 13.977497,53.8283212 18.7596173,51.0673628 L86.4131574,12.0075732 C91.1923351,9.24831368 98.9489097,9.24941241 103.733043,12.0071976 L171.294055,50.9523421 C176.080386,53.7113942 179.957427,60.4291661 179.953672,65.9512395 L179.900651,143.933364 Z" /> ) export const Svef = () => ( <path className="logo-graphic logo-svef" d="M142.613169,96.8376543 L160,103.463096 L160,106.648105 L142.613169,113.287498 L142.613169,109.520006 L154.647741,105.055198 L142.613169,100.605146 L142.613169,96.8376543 Z M118.004115,115.061728 L118.004115,110.246914 L120.411523,110.246914 L120.411523,100.082305 L118.004115,100.082305 L118.004115,95.2674897 L139.403292,95.2674897 L139.403292,101.687243 L133.518519,101.687243 L133.518519,100.082305 L128.703704,100.082305 L128.703704,103.024691 L132.44856,103.024691 L132.44856,107.037037 L128.703704,107.037037 L128.703704,110.246914 L131.378601,110.246914 L131.378601,115.061728 L118.004115,115.061728 Z M94.4650206,115.061728 L94.4650206,110.246914 L96.3374486,110.246914 L96.3374486,100.082305 L94.4650206,100.082305 L94.4650206,95.2674897 L115.329218,95.2674897 L115.329218,101.687243 L109.711934,101.687243 L109.711934,100.082305 L104.62963,100.082305 L104.62963,103.024691 L108.909465,103.024691 L108.909465,107.037037 L104.62963,107.037037 L104.62963,110.246914 L109.711934,110.246914 L109.711934,108.641975 L115.329218,108.641975 L115.329218,115.061728 L94.4650206,115.061728 Z M77.8993847,115.329218 L70.9360761,100.082305 L69.3209877,100.082305 L69.3209877,95.2674897 L81.090535,95.2674897 L81.090535,100.082305 L79.2008493,100.082305 L82.4468709,108.505386 L85.8502655,100.082305 L84.0329218,100.082305 L84.0329218,95.2674897 L92.8600823,95.2674897 L92.8600823,100.082305 L91.2447253,100.082305 L84.6895718,115.329218 L77.8993847,115.329218 Z M50.8643308,115.061728 L50.8643308,108.641975 L55.7453981,108.641975 C56.3278012,110.438883 57.4244511,111.304156 59.0358822,111.304156 C60.2001539,111.304156 60.7822897,110.87702 60.7822897,110.022748 C60.7822897,109.576294 60.5794242,109.206306 60.1739604,108.911979 C59.7374922,108.589212 58.8175144,108.143026 57.4140272,107.57369 C55.6467718,106.842568 54.3472564,106.211254 53.5157484,105.67948 C52.7358253,105.195732 52.0705654,104.526319 51.5197013,103.671779 C50.96857,102.826897 50.6930043,101.892133 50.6930043,100.866684 C50.6930043,99.0247935 51.3478403,97.5866965 52.6577796,96.5523935 C53.9570276,95.5175539 55.5580348,95 57.4602666,95 C59.3627656,95 60.9739295,95.4958215 62.3662551,96.4872428 L62.3662551,95.2674897 L67.18107,95.2674897 L67.18107,100.884774 L62.3568362,100.884774 C61.7642764,99.3362917 60.7144006,98.5584851 59.2072087,98.5584851 C58.1469089,98.5584851 57.6166254,98.9716697 57.6166254,99.7980389 C57.6166254,100.196735 57.7673713,100.49616 58.0685959,100.695776 C58.3596638,100.904783 59.3004894,101.365457 60.8910727,102.078067 C63.0223634,103.046904 64.4464312,103.754415 65.164078,104.200869 C65.5278461,104.419267 65.8996326,104.725399 66.2791702,105.119803 C66.6587078,105.513938 66.9730291,105.920147 67.2224013,106.338161 C67.7941132,107.268899 68.0798356,108.276104 68.0798356,109.358848 C68.0798356,111.021366 67.4041517,112.426999 66.052784,113.576403 C64.7014164,114.744857 62.9967045,115.329218 60.938114,115.329218 C59.0254583,115.329218 57.294553,114.813811 55.6790123,113.783128 L55.6790123,115.061728 L50.8643308,115.061728 Z M47.3868313,113.287498 L30,106.648105 L30,103.463096 L47.3868313,96.8376543 L47.3868313,100.605146 L35.403831,105.055198 L47.3868313,109.520006 L47.3868313,113.287498 Z" /> ) export const Awards = () => ( <path className="logo-graphic logo-awards" d="M68.4054802,149.263611 C53.1421328,145.039025 44.4060751,130.016865 48.930241,115.776659 C52.4414202,104.722665 64.8460635,98.35532 76.7023231,101.442517 C76.3240398,102.285403 75.9889164,103.153678 75.7045693,104.04734 C75.1764961,105.707724 74.8109069,107.370647 74.5900301,109.031031 C71.8379562,108.599433 69.0325672,109.020876 66.5445298,110.280128 C63.6020448,111.767872 61.4592862,114.240677 60.5046922,117.233938 C58.1410568,124.672662 62.7058436,132.522674 70.6802572,134.731441 C74.7905964,135.866291 79.2106709,135.594638 83.1153663,134.02819 C87.0886096,138.090292 92.2500176,141.225727 98.3000105,142.898805 C99.2546044,143.16538 100.219354,143.386257 101.18918,143.586823 C91.9402824,150.22836 79.8072921,152.416817 68.4054802,149.263611 M72.2720933,96.3953559 C68.2353797,96.1694015 64.2773693,96.788872 60.6392494,98.1319044 C61.3551948,97.0173652 62.3757979,96.0932371 63.6325106,95.4585337 C65.4909222,94.514095 67.6286032,94.3059123 69.6520377,94.8695289 C70.6726407,95.1487984 71.568842,95.6921045 72.2720933,96.3953559 M43.8145316,97.1620776 C47.3612542,85.9963754 59.9842354,79.6061815 71.9522028,82.9142556 C77.1288438,84.3486853 81.3305803,87.9512618 83.3260878,92.6201401 C81.647932,94.0698026 80.1551096,95.7200315 78.8983968,97.5530549 C78.7232187,97.4997398 78.5531182,97.4388083 78.3804789,97.3956485 C78.2687711,97.3601051 78.1519856,97.3372558 78.0326614,97.30679 C77.0247524,94.1789716 74.3691534,91.668085 70.9646043,90.7312627 C67.7580827,89.8401392 64.3713054,90.1752626 61.4288204,91.6630073 C58.4837966,93.1507521 56.3410379,95.6184789 55.3915216,98.6168178 C55.1401791,99.4140053 54.9624621,100.234042 54.8634484,101.054079 C50.0803236,104.214902 46.3533452,108.815232 44.5355546,114.433627 C42.2887046,108.94725 41.996741,102.879486 43.8145316,97.1620776 M80.1246438,130.489084 C77.5122046,131.293888 74.7068156,131.342125 71.9953626,130.588098 C66.4658266,129.062271 63.3024648,123.619054 64.9374608,118.457646 C65.5416984,116.568769 66.8923473,115.009937 68.74822,114.070576 C70.4695357,113.199763 72.4320386,112.966192 74.3259935,113.380019 C74.374231,116.647472 74.9886239,119.8413 76.0803137,122.870104 C75.2602769,123.144296 74.346304,123.184917 73.4678745,122.94373 L72.1502303,127.079457 C74.074651,127.610069 76.0726973,127.513594 77.8625609,126.868736 C78.5277301,128.115293 79.2842965,129.328846 80.1246438,130.489084 M127.98128,63.1165871 L125.508476,66.7648623 C142.980591,77.0572126 151.076868,97.1773105 145.191898,115.685262 C142.411897,124.446707 136.138488,131.672171 127.529372,136.033853 C118.917716,140.390457 109.003649,141.360284 99.6176547,138.760539 C84.3492297,134.538492 75.613172,119.521409 80.1398767,105.276126 C83.6840605,94.1104237 96.3095806,87.717691 108.275009,91.0308428 C112.794097,92.2824779 116.523615,95.0980222 118.770465,98.9646353 C121.014776,102.82871 121.517461,107.27925 120.176967,111.491142 C118.036747,118.229153 110.425384,122.085611 103.204998,120.090103 C97.6754623,118.559199 94.5070229,113.118521 96.1496353,107.957113 C96.7487953,106.068236 98.101983,104.509404 99.9603946,103.572582 C101.816267,102.628143 103.956487,102.419961 105.974844,102.983577 C107.477822,103.397404 108.714224,104.331687 109.463174,105.616327 C110.209585,106.900967 110.374608,108.378556 109.927777,109.779981 C109.265146,111.864347 106.909127,113.060128 104.67751,112.440658 L103.362405,116.578924 C108.038899,117.873719 112.976892,115.372988 114.363084,111.006228 C115.157733,108.49788 114.86323,105.854975 113.527814,103.559888 C112.192399,101.259723 109.976014,99.5866446 107.287411,98.8427722 C104.080889,97.9567263 100.694112,98.2867721 97.7541655,99.7745168 C94.8066029,101.267339 92.6638442,103.735066 91.7143279,106.728327 C89.3481537,114.172129 93.9154793,122.019602 101.894971,124.22837 C111.555156,126.899201 121.743415,121.737793 124.612275,112.722466 C126.303125,107.401113 125.67096,101.785257 122.837644,96.9031186 C120.956383,93.6788254 118.260163,91.0359204 115.000326,89.1571983 C113.040362,75.036317 104.52772,62.5885139 91.6559352,55 L89.1856696,58.6482752 C99.1048144,64.4951629 106.170333,73.5155677 109.183904,83.9475528 C105.675264,79.8981451 101.458295,76.3768106 96.7691058,73.6145814 L94.3039178,77.2628565 C98.3101657,79.626492 101.930514,82.609598 105.007556,86.0217635 C98.6072069,85.3210509 92.3058715,86.7859464 87.0987648,89.9036095 C84.4152388,84.5594069 79.3807714,80.4693781 73.2647694,78.7785283 C58.8544634,74.7925909 43.6520475,82.4902738 39.3792242,95.9383695 C36.6525384,104.519559 38.0082648,113.798923 43.0960473,121.397592 L43.195061,121.341738 C42.1693803,135.602254 51.7991004,149.169674 67.0929136,153.399338 C81.3178862,157.337038 96.5609231,153.88679 107.269639,144.401782 C115.005404,144.907006 122.748786,143.35833 129.735601,139.824302 C139.426252,134.916775 146.49177,126.777338 149.627205,116.90897 C156.093563,96.55784 147.189944,74.4396958 127.98128,63.1165871" /> ) export const Conf = () => ( <path className="logo-graphic logo-conf" d="M66.8761129,116.383667 C66.8761129,106.071035 76.1825271,96.4570433 81.6222536,88.4512422 C87.1762232,80.2718796 89.0260817,72.3935035 87.670544,62.4763285 C106.481101,73.0174463 117.279265,90.8283763 112.351436,112.066598 C115.163572,108.375669 118.043815,104.774816 117.925178,99.9370622 C128.723343,115.24563 120.699966,136.40476 106.404206,147.176561 C114.790085,136.138925 111.617644,123.075673 98.9784084,117.96769 C100.599781,120.8721 102.990097,127.847517 97.7744625,128.425323 C87.2838753,129.585329 98.7521193,114.661233 100.439401,112.453266 C108.651719,101.699041 107.436788,88.4007116 94.2043674,82.5062099 C99.751746,94.7038519 92.7279957,100.420398 85.5592447,109.75757 C76.8745763,121.067631 71.294243,137.246204 84.2937833,148.233309 C72.4476583,142.723279 66.8761129,128.818583 66.8761129,116.383667 M91.2318512,147.42482 C80.2381552,143.685557 78.8035262,129.400783 83.373248,120.443689 C87.8726663,111.625004 100.050535,104.207994 100.797509,93.8909687 C106.349282,104.884665 92.9938305,111.119699 89.9883596,120.098763 C86.1700056,131.503294 102.001455,138.076663 104.890486,126.977512 C113.078637,136.411351 101.819106,149.729454 91.2318512,147.42482 M120.157311,95.8199186 C116.677292,92.1970959 116.136835,86.8650215 113.695988,82.5545435 C110.165439,76.3173127 105.261776,70.6117514 99.8528071,65.9387715 C94.3911108,61.221852 88.4592604,58.1175169 82.055059,55 C83.0898373,60.6726066 84.3113591,66.3144554 83.8104473,72.1276688 C82.771275,84.1495522 72.3312183,92.6299013 66.8870979,102.852457 C58.1826567,119.200197 64.5561003,142.732067 81.4201313,151.491433 C91.9480672,156.957523 103.187825,156.258883 112.147116,147.767549 C127.187653,133.513532 132.557076,112.727889 120.157311,95.8199186" /> )
Ethereum-based-Roll4Win/node_modules/react-bootstrap/es/Card.js
brett-harvey/Smart-Contracts
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import classNames from 'classnames'; import React from 'react'; import { createBootstrapComponent } from './ThemeProvider'; import createWithBsPrefix from './utils/createWithBsPrefix'; import divWithClassName from './utils/divWithClassName'; import CardContext from './CardContext'; import CardImg from './CardImg'; var CardBody = createWithBsPrefix('card-body'); var Card = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Card, _React$Component); function Card() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.state = {}; return _this; } Card.getDerivedStateFromProps = function getDerivedStateFromProps(_ref) { var bsPrefix = _ref.bsPrefix; return { cardContext: { cardHeaderBsPrefix: bsPrefix + "-header" } }; }; var _proto = Card.prototype; _proto.render = function render() { var _this$props = this.props, bsPrefix = _this$props.bsPrefix, className = _this$props.className, Component = _this$props.as, bg = _this$props.bg, text = _this$props.text, border = _this$props.border, body = _this$props.body, children = _this$props.children, props = _objectWithoutPropertiesLoose(_this$props, ["bsPrefix", "className", "as", "bg", "text", "border", "body", "children"]); var classes = classNames(className, bsPrefix, bg && "bg-" + bg, text && "text-" + text, border && "border-" + border); return React.createElement(CardContext.Provider, { value: this.state.cardContext }, React.createElement(Component, _extends({ className: classes }, props), body ? React.createElement(CardBody, null, children) : children)); }; return Card; }(React.Component); Card.defaultProps = { as: 'div', body: false }; var DivStyledAsH5 = divWithClassName('h5'); var DivStyledAsH6 = divWithClassName('h6'); var DecoratedCard = createBootstrapComponent(Card, 'card'); DecoratedCard.Img = CardImg; DecoratedCard.Title = createWithBsPrefix('card-title', { Component: DivStyledAsH5 }); DecoratedCard.Subtitle = createWithBsPrefix('card-subtitle', { Component: DivStyledAsH6 }); DecoratedCard.Body = CardBody; DecoratedCard.Link = createWithBsPrefix('card-link', { Component: 'a' }); DecoratedCard.Text = createWithBsPrefix('card-text', { Component: 'p' }); DecoratedCard.Header = createWithBsPrefix('card-header'); DecoratedCard.Footer = createWithBsPrefix('card-footer'); DecoratedCard.ImgOverlay = createWithBsPrefix('card-img-overlay'); export default DecoratedCard;
node_modules/react-native/Libraries/Components/Keyboard/Keyboard.js
solium/swift-react-native-hybrid
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Keyboard * @flow */ 'use strict'; const invariant = require('fbjs/lib/invariant'); const NativeEventEmitter = require('NativeEventEmitter'); const KeyboardObserver = require('NativeModules').KeyboardObserver; const dismissKeyboard = require('dismissKeyboard'); const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver); type KeyboardEventName = | 'keyboardWillShow' | 'keyboardDidShow' | 'keyboardWillHide' | 'keyboardDidHide' | 'keyboardWillChangeFrame' | 'keyboardDidChangeFrame'; type KeyboardEventData = { endCoordinates: { width: number, height: number, screenX: number, screenY: number, }, }; type KeyboardEventListener = (e: KeyboardEventData) => void; // The following object exists for documentation purposes // Actual work happens in // https://github.com/facebook/react-native/blob/master/Libraries/EventEmitter/NativeEventEmitter.js /** * `Keyboard` module to control keyboard events. * * ### Usage * * The Keyboard module allows you to listen for native events and react to them, as * well as make changes to the keyboard, like dismissing it. * *``` * import React, { Component } from 'react'; * import { Keyboard, TextInput } from 'react-native'; * * class Example extends Component { * componentWillMount () { * this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); * this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); * } * * componentWillUnmount () { * this.keyboardDidShowListener.remove(); * this.keyboardDidHideListener.remove(); * } * * _keyboardDidShow () { * alert('Keyboard Shown'); * } * * _keyboardDidHide () { * alert('Keyboard Hidden'); * } * * render() { * return ( * <TextInput * onSubmitEditing={Keyboard.dismiss} * /> * ); * } * } *``` */ let Keyboard = { /** * The `addListener` function connects a JavaScript function to an identified native * keyboard notification event. * * This function then returns the reference to the listener. * * @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. This *can be any of the following: * * - `keyboardWillShow` * - `keyboardDidShow` * - `keyboardWillHide` * - `keyboardDidHide` * - `keyboardWillChangeFrame` * - `keyboardDidChangeFrame` * * Note that if you set `android:windowSoftInputMode` to `adjustResize` or `adjustNothing`, * only `keyboardDidShow` and `keyboardDidHide` events will available on Android. * * @param {function} callback function to be called when the event fires. */ addListener(eventName: KeyboardEventName, callback: KeyboardEventListener) { invariant(false, 'Dummy method used for documentation'); }, /** * Removes a specific listener. * * @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. * @param {function} callback function to be called when the event fires. */ removeListener(eventName: KeyboardEventName, callback: Function) { invariant(false, 'Dummy method used for documentation'); }, /** * Removes all listeners for a specific event type. * * @param {string} eventType The native event string listeners are watching which will be removed. */ removeAllListeners(eventName: KeyboardEventName) { invariant(false, 'Dummy method used for documentation'); }, /** * Dismisses the active keyboard and removes focus. */ dismiss() { invariant(false, 'Dummy method used for documentation'); } }; // Throw away the dummy object and reassign it to original module Keyboard = KeyboardEventEmitter; Keyboard.dismiss = dismissKeyboard; module.exports = Keyboard;
src/app/core/atoms/icon/icons/compass.js
blowsys/reservo
import React from 'react'; const Compass = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><path d="M13,13 L8,16 L11,11 L16,8 L13,13 Z M12,4 C7.582,4 4,7.582 4,12 C4,16.418 7.582,20 12,20 C16.418,20 20,16.418 20,12 C20,7.582 16.418,4 12,4 L12,4 Z"/></g></g></svg>; export default Compass;
src/svg-icons/image/filter.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter = (props) => ( <SvgIcon {...props}> <path d="M15.96 10.29l-2.75 3.54-1.96-2.36L8.5 15h11l-3.54-4.71zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/> </SvgIcon> ); ImageFilter = pure(ImageFilter); ImageFilter.displayName = 'ImageFilter'; ImageFilter.muiName = 'SvgIcon'; export default ImageFilter;
local-cli/templates/HelloWorld/index.android.js
shrutic123/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
Sources/ewsnodejs-server/node_modules/react-transition-group/esm/TransitionGroup.js
nihospr01/OpenSpeechPlatform-UCSD
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import PropTypes from 'prop-types'; import React from 'react'; import TransitionGroupContext from './TransitionGroupContext'; import { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping'; var values = Object.values || function (obj) { return Object.keys(obj).map(function (k) { return obj[k]; }); }; var defaultProps = { component: 'div', childFactory: function childFactory(child) { return child; } }; /** * The `<TransitionGroup>` component manages a set of transition components * (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition * components, `<TransitionGroup>` is a state machine for managing the mounting * and unmounting of components over time. * * Consider the example below. As items are removed or added to the TodoList the * `in` prop is toggled automatically by the `<TransitionGroup>`. * * Note that `<TransitionGroup>` does not define any animation behavior! * Exactly _how_ a list item animates is up to the individual transition * component. This means you can mix and match animations across different list * items. */ var TransitionGroup = /*#__PURE__*/function (_React$Component) { _inheritsLoose(TransitionGroup, _React$Component); function TransitionGroup(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear _this.state = { contextValue: { isMounting: true }, handleExited: handleExited, firstRender: true }; return _this; } var _proto = TransitionGroup.prototype; _proto.componentDidMount = function componentDidMount() { this.mounted = true; this.setState({ contextValue: { isMounting: false } }); }; _proto.componentWillUnmount = function componentWillUnmount() { this.mounted = false; }; TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) { var prevChildMapping = _ref.children, handleExited = _ref.handleExited, firstRender = _ref.firstRender; return { children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited), firstRender: false }; } // node is `undefined` when user provided `nodeRef` prop ; _proto.handleExited = function handleExited(child, node) { var currentChildMapping = getChildMapping(this.props.children); if (child.key in currentChildMapping) return; if (child.props.onExited) { child.props.onExited(node); } if (this.mounted) { this.setState(function (state) { var children = _extends({}, state.children); delete children[child.key]; return { children: children }; }); } }; _proto.render = function render() { var _this$props = this.props, Component = _this$props.component, childFactory = _this$props.childFactory, props = _objectWithoutPropertiesLoose(_this$props, ["component", "childFactory"]); var contextValue = this.state.contextValue; var children = values(this.state.children).map(childFactory); delete props.appear; delete props.enter; delete props.exit; if (Component === null) { return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, { value: contextValue }, children); } return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, { value: contextValue }, /*#__PURE__*/React.createElement(Component, props, children)); }; return TransitionGroup; }(React.Component); TransitionGroup.propTypes = process.env.NODE_ENV !== "production" ? { /** * `<TransitionGroup>` renders a `<div>` by default. You can change this * behavior by providing a `component` prop. * If you use React v16+ and would like to avoid a wrapping `<div>` element * you can pass in `component={null}`. This is useful if the wrapping div * borks your css styles. */ component: PropTypes.any, /** * A set of `<Transition>` components, that are toggled `in` and out as they * leave. the `<TransitionGroup>` will inject specific transition props, so * remember to spread them through if you are wrapping the `<Transition>` as * with our `<Fade>` example. * * While this component is meant for multiple `Transition` or `CSSTransition` * children, sometimes you may want to have a single transition child with * content that you want to be transitioned out and in when you change it * (e.g. routes, images etc.) In that case you can change the `key` prop of * the transition child as you change its content, this will cause * `TransitionGroup` to transition the child out and back in. */ children: PropTypes.node, /** * A convenience prop that enables or disables appear animations * for all children. Note that specifying this will override any defaults set * on individual children Transitions. */ appear: PropTypes.bool, /** * A convenience prop that enables or disables enter animations * for all children. Note that specifying this will override any defaults set * on individual children Transitions. */ enter: PropTypes.bool, /** * A convenience prop that enables or disables exit animations * for all children. Note that specifying this will override any defaults set * on individual children Transitions. */ exit: PropTypes.bool, /** * You may need to apply reactive updates to a child as it is exiting. * This is generally done by using `cloneElement` however in the case of an exiting * child the element has already been removed and not accessible to the consumer. * * If you do need to update a child as it leaves you can provide a `childFactory` * to wrap every child, even the ones that are leaving. * * @type Function(child: ReactElement) -> ReactElement */ childFactory: PropTypes.func } : {}; TransitionGroup.defaultProps = defaultProps; export default TransitionGroup;
pages/about/index.js
zendesk/copenhelp
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import s from './about.css' class AboutPage extends React.Component { componentDidMount() { document.title = 'About' } render() { return ( <Layout> <img className={s.logo} src="/logo.svg"/> <div className={s.inset}> <div class="inset"> <p> Copenhelp, a project of Bespoke and Zendesk, is intended to help homeless and low income residents of Copenhagen connect with information about critical resources. This mobile optimized website focuses on services like shelter, food, medical care, technology access, and hygiene services. </p> <p> Copenhelp is based on <a href="http://www.link-sf.org/">Link-SF</a>, a project designed and implemented by <a href="http://www.stanthonysf.org/">St. Anthony Foundation</a>, Zendesk, and user testing expert <a href="http://kimberlymccollister.com/design/">Kimberly McCollister</a>. This collaboration emerged as a result of a Community Benefits Agreement in the city of San Francisco. St. Anthony’s Tenderloin Technology Lab reached out to the tech community after observing an increase in the use of smart phones by low-income residents. Link-SF is a result of this process and is an attempt to use mobile technology to assist those most in need. </p> </div> </div> <img className={s.logo} src="/zendesk.svg"/> <div className={s.inset}> <p>Zendesk is a cloud-based customer service platform. It is designed to be easy to use, easy to customize, and easy to scale. Frustrated with the state of enterprise customer service software in 2007, three Danish entrepreneurs sought out to create beautifully simple software that could change how any company interacted with its customers. Today more than 30,000 companies use Zendesk to provide service to more than 200 million people worldwide. Zendesk has offices in eight countries, with headquarters in San Francisco. Funding from Charles River Ventures, Benchmark Capital, Goldman Sachs, GGV Capital, Index Ventures, Matrix Partners, and Redpoint Ventures. Learn more at www.zendesk.com.</p> </div> <br/> <div className={s.inset}> Link-SF is free software. Get it <a href="http://github.com/zendesk/linksf" about="_blank">here</a> </div> <br/> <p className={s.credits}> CDN hosting provided graciously by <a href="http://www.fast.ly">fast.ly</a><br/> Icons by P.J. Onori, Daniel Bruce, and Dave Gandy, courtesy of <a href="http://fontello.com">fontello.com</a> </p> </Layout> ); } } export default AboutPage;
app/components/TqnAppBar/index.js
tqn/tqn.github.io
/** * * TqnAppBar * */ import React from 'react'; import { AppBar } from 'material-ui'; import { Row, Col } from 'react-flexbox-grid'; function TqnAppBar(props) { return ( <AppBar showMenuIconButton={false} title={ <Row> <Col {...props.colProps}> Tej Qu Nair </Col> </Row> } /> ); } TqnAppBar.propTypes = { colProps: React.PropTypes.object, }; export default TqnAppBar;
src/Table.js
codyc4321/react-data-components-updated
import React, { Component } from 'react'; import PropTypes from 'prop-types'; const simpleGet = key => data => data[key]; const keyGetter = keys => data => keys.map(key => data[key]); const isEmpty = value => value == null || value === ''; const getCellValue = ({ prop, defaultContent, render }, row) => // Return `defaultContent` if the value is empty. !isEmpty(prop) && isEmpty(row[prop]) ? defaultContent : // Use the render function for the value. render ? render(row[prop], row) : // Otherwise just return the value. row[prop]; const getCellClass = ({ prop, className }, row) => !isEmpty(prop) && isEmpty(row[prop]) ? 'empty-cell' : typeof className == 'function' ? className(row[prop], row) : className; function buildSortProps(col, sortBy, onSort) { const order = sortBy && sortBy.prop === col.prop ? sortBy.order : 'none'; const nextOrder = order === 'ascending' ? 'descending' : 'ascending'; const sortEvent = onSort.bind(null, { prop: col.prop, order: nextOrder }); return { onClick: sortEvent, // Fire the sort event on enter. onKeyDown: e => { if (e.keyCode === 13) sortEvent(); }, // Prevents selection with mouse. onMouseDown: e => e.preventDefault(), tabIndex: 0, 'aria-sort': order, 'aria-label': `${col.title}: activate to sort column ${nextOrder}`, }; } export default class Table extends Component { _headers = []; static propTypes = { keys: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.string, ]).isRequired, columns: PropTypes.arrayOf( PropTypes.shape({ title: PropTypes.string.isRequired, prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), render: PropTypes.func, sortable: PropTypes.bool, defaultContent: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), className: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), }), ).isRequired, dataArray: PropTypes.arrayOf( PropTypes.oneOfType([PropTypes.array, PropTypes.object]), ).isRequired, buildRowOptions: PropTypes.func, sortBy: PropTypes.shape({ prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), order: PropTypes.oneOf(['ascending', 'descending']), }), onSort: PropTypes.func, }; componentDidMount() { // If no width was specified, then set the width that the browser applied // initially to avoid recalculating width between pages. this._headers.forEach(header => { if (!header.style.width) { header.style.width = `${header.offsetWidth}px`; } }); } render() { const { columns, keys, buildRowOptions, sortBy, onSort, dataArray, ...otherProps } = this.props; const headers = columns.map((col, idx) => { let sortProps, order; col.sortable = true; sortProps = buildSortProps(col, sortBy, onSort); order = sortProps['aria-sort']; return ( <th ref={c => (this._headers[idx] = c)} key={idx} style={{ width: col.width }} role="columnheader" scope="col" {...sortProps} > <span> {col.title} </span> {!order ? null : <span className={`sort-icon sort-${order}`} aria-hidden="true" />} </th> ); }); const getKeys = Array.isArray(keys) ? keyGetter(keys) : simpleGet(keys); const rows = dataArray.map(row => { const trProps = buildRowOptions ? buildRowOptions(row) : {}; return ( <tr key={getKeys(row)} {...trProps}> {columns.map((col, i) => <td key={i} className={getCellClass(col, row)}> {getCellValue(col, row)} </td>, )} </tr> ); }); return ( <table {...otherProps}> {!sortBy ? null : <caption className="sr-only" role="alert" aria-live="polite"> {`Sorted by ${sortBy.prop}: ${sortBy.order} order`} </caption>} <thead> <tr> {headers} </tr> </thead> <tbody> {rows.length ? rows : <tr> <td colSpan={columns.length} className="text-center"> No data </td> </tr>} </tbody> </table> ); } }
lib/client/components/MagnetSection.react.js
imsnif/wtorrent
"use strict"; import React from 'react'; import { Row } from 'react-bootstrap'; import { Col } from 'react-bootstrap'; import { Input } from 'react-bootstrap'; import { Button } from 'react-bootstrap'; import TorrentActionCreators from '../actions/TorrentActionCreators'; export default class MagnetSection extends React.Component { constructor() { super(); this.state = { magnet: "" }; this._onChange = this._onChange.bind(this); this._onClick = this._onClick.bind(this); } _onChange (event, value) { this.state.magnet = event.target.value this.setState({magnet: event.target.value}); } _onClick (event) { TorrentActionCreators.addTorrentMagnet(this.state.magnet); this.setState({magnet: ""}) } render () { return ( <Row> <Col md={9}> <Input bsSize="large" type="text" placeholder="Magnet URI" onChange={this._onChange} value={this.state.magnet} /> </Col> <Col md={3}> <Button bsStyle="success" bsSize="large" onClick={this._onClick} block>Submit Magnet </Button> </Col> </Row> ) } };
src/components/header/Header.js
BernabeFelix/generationMap
import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import NavigationMenu from 'material-ui/svg-icons/navigation/menu'; const Header = ({ height, toggleMenu }) => { return ( <MuiThemeProvider> <AppBar iconElementLeft={ <IconButton onClick={toggleMenu}> <NavigationMenu /> </IconButton> } style={{ height }} title="Generation Stores Map" /> </MuiThemeProvider> ); }; export default Header;
packages/material-ui-icons/src/Kitchen.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Kitchen = props => <SvgIcon {...props}> <path d="M18 2.01L6 2c-1.1 0-2 .89-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.11-.9-1.99-2-1.99zM18 20H6v-9.02h12V20zm0-11H6V4h12v5zM8 5h2v3H8zm0 7h2v5H8z" /> </SvgIcon>; Kitchen = pure(Kitchen); Kitchen.muiName = 'SvgIcon'; export default Kitchen;
html/dev/lib/license.js
scott-fleischman/greek-grammar
import React from 'react'; export const License = () => ( <div className="listContainer"> <p> <a rel="license" href="http://creativecommons.org/licenses/by/4.0/"> <img alt="Creative Commons License" style={{borderWidth:0}} src="https://i.creativecommons.org/l/by/4.0/88x31.png" /> </a> <br />© Scott Fleischman 2015. Except where otherwise noted, content on this site is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>. </p> <p> <a href="http://sblgnt.com/license/">SBLGNT EULA</a> </p> <p> <a href="http://morphgnt.org/">MorphGNT</a> morphological parsing and lemmatization is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA License</a>. </p> </div> );
src/server.js
labzero/lunch
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'isomorphic-fetch'; import Promise from 'bluebird'; import path from 'path'; import fs from 'fs'; import rfs from 'rotating-file-stream'; import morgan from 'morgan'; import express from 'express'; import cors from 'cors'; import { Server as HttpServer } from 'http'; import { Server as HttpsServer } from 'https'; import enforce from 'express-sslify'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import methodOverride from 'method-override'; import session from 'express-session'; import connectSessionSequelize from 'connect-session-sequelize'; import flash from 'connect-flash'; import expressJwt, { UnauthorizedError as Jwt401Error } from 'express-jwt'; import nodeFetch from 'node-fetch'; import React from 'react'; import ReactDOM from 'react-dom/server'; import expressWs from 'express-ws'; import Honeybadger from 'honeybadger'; import PrettyError from 'pretty-error'; import App from './components/App'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './components/ErrorPage/ErrorPage'; import errorPageStyle from './components/ErrorPage/ErrorPage.scss'; import generateUrl from './helpers/generateUrl'; import hasRole from './helpers/hasRole'; import teamRoutes from './routes/team'; import mainRoutes from './routes/main'; import createFetch from './createFetch'; import passport from './passport'; import routerCreator from './router'; import chunks from './chunk-manifest.json'; // eslint-disable-line import/no-unresolved import configureStore from './store/configureStore'; import config from './config'; import makeInitialState from './initialState'; import invitationMiddleware from './middlewares/invitation'; import loginMiddleware from './middlewares/login'; import passwordMiddleware from './middlewares/password'; import usersMiddleware from './middlewares/users'; import api from './api'; import { sequelize } from './models/db'; import { Team, User } from './models'; fetch.promise = Promise; process.on('unhandledRejection', (reason, p) => { console.error('Unhandled Rejection at:', p, 'reason:', reason); // send entire app down. Process manager will restart it process.exit(1); }); const logDirectory = path.join(__dirname, 'log'); // ensure log directory exists // eslint-disable-next-line no-unused-expressions fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory); // create a rotating write stream const accessLogStream = rfs('access.log', { interval: '1d', // rotate daily path: logDirectory }); const app = express(); let internalWsServer; if (process.env.USE_HTTPS === 'true') { // use self-signed cert locally const options = { key: fs.readFileSync(path.join(__dirname, '../cert/server.key')), cert: fs.readFileSync(path.join(__dirname, '../cert/server.crt')), }; internalWsServer = new HttpsServer(options, app); } else { // prod proxy will take care of https internalWsServer = new HttpServer(app); } export const wsServer = internalWsServer; // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // If you are using proxy from external machine, you can set TRUST_PROXY env // Default is to trust proxy headers only from loopback interface. // ----------------------------------------------------------------------------- app.set('trust proxy', config.trustProxy); // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(Honeybadger.requestHandler); // Use *before* all other app middleware. app.use(morgan('combined', { stream: accessLogStream })); app.get('/health', (req, res) => { res.status(200).send('welcome to the health endpoint'); }); if (process.env.NODE_ENV === 'production') { app.use(enforce.HTTPS({ trustProtoHeader: true, trustXForwardedHostHeader: true })); app.set('trust proxy', true); } app.use(compression()); app.use(express.static(path.resolve(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride((req) => { if (req.body && typeof req.body === 'object' && '_method' in req.body) { const method = req.body._method; // eslint-disable-line no-underscore-dangle delete req.body._method; // eslint-disable-line no-underscore-dangle, no-param-reassign return method; } return undefined; })); // // Redirect old labzero.com host // ----------------------------------------------------------------------------- app.use((req, res, next) => { if (req.hostname === 'lunch.labzero.com') { res.redirect(301, generateUrl(req, config.bsHost, path)); } else { next(); } }); // // Redirect www to root // ----------------------------------------------------------------------------- app.use((req, res, next) => { if (req.headers.host.slice(0, 4) === 'www.') { const newHost = req.headers.host.slice(4); res.redirect(301, `${req.protocol}://${newHost}${req.originalUrl}`); } else { next(); } }); // // Session / Flash // ----------------------------------------------------------------------------- if (__DEV__) { app.enable('trust proxy'); } const SequelizeStore = connectSessionSequelize(session.Store); app.use(session({ cookie: { domain: config.domain, secure: process.env.NODE_ENV === 'production' }, saveUninitialized: false, secret: config.auth.session.secret, store: new SequelizeStore({ db: sequelize }), resave: false, proxy: true })); app.use(flash()); // // Authentication // ----------------------------------------------------------------------------- app.use( expressJwt({ secret: config.auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, }), ); // Error handler for express-jwt app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars if (err instanceof Jwt401Error) { req.logout(); res.clearCookie('id_token', { domain: config.domain }); next(); } else { console.error('[express-jwt-error]', req.cookies.id_token); // `clearCookie`, otherwise user can't use web-app until cookie expires res.clearCookie('id_token'); next(err); } }); app.use(passport.initialize()); app.use((req, res, next) => { const subdomainMatch = req.hostname.match(`^(.*)${config.domain.replace(/\./g, '\\.')}`); if (subdomainMatch && subdomainMatch[1]) { // eslint-disable-next-line no-param-reassign req.subdomain = subdomainMatch[1]; } if (typeof req.user === 'number' || typeof req.user === 'string') { User.getSessionUser(req.user).then(user => { if (user) { // eslint-disable-next-line no-param-reassign req.user = user; } else { // eslint-disable-next-line no-param-reassign delete req.user; } next(); }).catch(err => next(err)); } else { next(); } }); app.use('/invitation', invitationMiddleware()); app.use('/login', loginMiddleware()); app.use('/password', passwordMiddleware()); app.use('/users', usersMiddleware()); app.get('/logout', (req, res) => { req.logout(); res.clearCookie('id_token', { domain: config.domain }); res.redirect('/'); }); // // Register WebSockets // ----------------------------------------------------------------------------- const wsInstance = expressWs(app, wsServer); export const wss = wsInstance.getWss(); wss.broadcast = (teamId, data) => { wss.clients.forEach(client => { if (client.teamId === teamId) { client.send(JSON.stringify(data)); } }); }; app.use((req, res, next) => { req.wss = wss; // eslint-disable-line no-param-reassign return next(); }); // // Get current team // ----------------------------------------------------------------------------- app.use(async (req, res, next) => { if (req.subdomain) { const team = await Team.findOne({ where: { slug: req.subdomain } }); if (team && hasRole(req.user, team)) { req.team = team; // eslint-disable-line no-param-reassign } } next(); }); // // Register API middleware // ----------------------------------------------------------------------------- if (__DEV__) { app.use(cors({ credentials: true, optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204 origin: true, })); } app.use('/api', api()); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- const render = async (req, res, next) => { try { const stateData = { host: config.bsHost }; if (req.user) { stateData.user = req.user; stateData.teams = await Team.findAllForUser(req.user); stateData.team = req.team; } const flashes = req.flash(); const flashKeys = Object.keys(flashes); if (flashKeys.length) { stateData.flashes = []; flashKeys.forEach(k => { flashes[k].forEach(f => { stateData.flashes.push({ message: f, type: k }); }); }); } const css = new Set(); // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader const insertCss = (...styles) => { // eslint-disable-next-line no-underscore-dangle styles.forEach(style => css.add(style._getCss())); }; // Universal HTTP client const fetch = createFetch(nodeFetch, { baseUrl: config.api.serverUrl, cookie: req.headers.cookie, }); const initialState = makeInitialState(stateData); const store = configureStore(initialState, { cookie: req.headers.cookie, fetch, // I should not use `history` on server.. but how I do redirection? follow universal-router }); // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { insertCss, fetch, // The twins below are wild, be careful! pathname: req.path, query: req.query, // You can access redux through react-redux connect store, }; let router; if (req.subdomain) { router = routerCreator(teamRoutes); } else { router = routerCreator(mainRoutes); } const route = await router.resolve({ ...context, subdomain: req.subdomain, }); if (route.redirect) { res.redirect(route.status || 302, route.redirect); return; } const pageTitle = route.title || 'Lunch'; const data = { ...route, apikey: process.env.GOOGLE_CLIENT_APIKEY || '', title: pageTitle, ogTitle: route.ogTitle || pageTitle, description: 'A simple lunch voting app for you and your team. Search nearby restaurants, add them to your list, vote for as many as you like, and decide on today’s pick!', body: '', root: generateUrl(req, req.get('host')), }; data.children = ReactDOM.renderToString( <App context={context} store={store}> {route.component} </App>, ); data.styles = [{ id: 'css', cssText: [...css].join('') }]; const scripts = new Set(); const addChunk = chunk => { if (chunks[chunk]) { chunks[chunk].forEach(asset => scripts.add(asset)); } else if (__DEV__) { throw new Error(`Chunk with name '${chunk}' cannot be found`); } }; addChunk('client'); if (route.chunk) addChunk(route.chunk); if (route.chunks) route.chunks.forEach(addChunk); data.scripts = Array.from(scripts); data.app = { apiUrl: config.api.clientUrl, state: initialState, }; const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(route.status || 200); res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }; app.post('/invitation', render); app.post('/login', render); app.post('/password', render); app.post('/users', render); app.put('/password', render); app.get('*', render); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); // eslint-disable-next-line no-unused-vars app.use((err, req, res, next) => { console.error(pe.render(err)); res.status(err.status || 500); if (req.accepts('html') === 'html') { const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html>, ); res.send(`<!doctype html>${html}`); } else { res.json({ error: true, data: { message: err.message, stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined } }); } next(err); }); app.use(Honeybadger.errorHandler); // Use *after* all other app middleware. // // Launch the server // ----------------------------------------------------------------------------- if (process.env.USE_HTTPS === 'true') { wsServer.listen(config.wsPort, () => { /* eslint-disable no-console */ console.log(`The websockets server is running at https://local.lunch.pink:${config.wsPort}/`); }); } else { wsServer.listen(config.port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://local.lunch.pink:${config.port}/`); }); } // // Hot Module Replacement // ----------------------------------------------------------------------------- if (module.hot) { app.hot = module.hot; module.hot.accept('./router'); } export default app;
example/src/Examples.js
benkeen/react-country-region-selector
import React, { Component } from 'react'; import { CountryDropdown, RegionDropdown } from 'react-country-region-selector'; class Examples extends Component { constructor (props) { super(props); this.getCountryValue = this.getCountryValue.bind(this); this.getRegionValue = this.getRegionValue.bind(this); // we really only need to stash the selected region + country in state, but I was feeling wacky this.state = { examples: [ { label: 'Simple, no-frills example.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(0)} onChange={(val) => this.selectCountry(0, val)}/> <RegionDropdown country={this.getCountryValue(0)} value={this.getRegionValue(0)} onChange={(val) => this.selectRegion(0, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n onChange={selectCountry} />\n&lt;RegionDropdown\n country={country}\n value={region}\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Region field disabled until a country is selected.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(1)} onChange={(val) => this.selectCountry(1, val)}/> <RegionDropdown disableWhenEmpty={true} country={this.getCountryValue(1)} value={this.getRegionValue(1)} onChange={(val) => this.selectRegion(1, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n onChange={selectCountry} />\n&lt;RegionDropdown\n disableWhenEmpty={true}\n country={country}\n value={region}\n onChange={selectRegion} />', country: '', region: '' }, { label: 'No country or region dropdown default option.', jsx: () => { return ( <div> <CountryDropdown showDefaultOption={false} value={this.getCountryValue(2)} onChange={(val) => this.selectCountry(2, val)}/> <RegionDropdown showDefaultOption={false} country={this.getCountryValue(2)} value={this.getRegionValue(2)} onChange={(val) => this.selectRegion(2, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n showDefaultOption={false}\n value={country}\n onChange={selectCountry} />\n&lt;RegionDropdown\n showDefaultOption={false}\n country={country}\n value={region}\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Custom default option texts for both the country and region dropdowns.', jsx: () => { return ( <div> <CountryDropdown defaultOptionLabel="Select a country, man." value={this.getCountryValue(3)} onChange={(val) => this.selectCountry(3, val)}/> <RegionDropdown blankOptionLabel="No country selected, man." defaultOptionLabel="Now select a region, pal." country={this.getCountryValue(3)} value={this.getRegionValue(3)} onChange={(val) => this.selectRegion(3, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n defaultOptionLabel="Select a country, man."\n value={country}\n onChange={selectCountry} />\n&lt;RegionDropdown\n blankOptionLabel="No country selected, man."\n defaultOptionLabel="Now select a region, pal."\n country={country}\n value={region}\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Custom name, class and ID attributes for both dropdowns.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(4)} id="my-country-field-id" name="my-country-field" classes="my-custom-class second-class" onChange={(val) => this.selectCountry(4, val)}/> <RegionDropdown country={this.getCountryValue(4)} value={this.getRegionValue(4)} name="my-region-field-name" id="my-region-field-id" classes="another-custom-class" onChange={(val) => this.selectRegion(4, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n id="my-country-field-id"\n name="my-country-field"\n classes="my-custom-class second-class"\n onChange={selectCountry} />\n&lt;RegionDropdown\n country={country}\n value={region}\n name="my-region-field-name"\n id="my-region-field-id"\n classes="another-custom-class"\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Abbreviated country and region names.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(5)} labelType="short" valueType="short" onChange={(val) => this.selectCountry(5, val)}/> <RegionDropdown country={this.getCountryValue(5)} value={this.getRegionValue(5)} countryValueType="short" labelType="short" valueType="short" onChange={(val) => this.selectRegion(5, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n labelType="short"\n valueType="short"\n onChange={selectCountry} />\n&lt;RegionDropdown\n country={country}\n value={region}\n countryValueType="short"\n labelType="short"\n valueType="short"\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Specify which countries should appear. This just shows the UK, United States and Canada. See the countryShortCode property in the source data for the country shortcodes you need to pass here.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(6)} onChange={(val) => this.selectCountry(6, val)} whitelist={['GB', 'US', 'CA']}/> <RegionDropdown country={this.getCountryValue(6)} value={this.getRegionValue(6)} onChange={(val) => this.selectRegion(6, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n labelType="short"\n valueType="short"\n onChange={selectCountry} />\n&lt;RegionDropdown\n country={country}\n value={region}\n countryValueType="short"\n labelType="short"\n valueType="short"\n onChange={selectRegion} />', country: '', region: '' }, { label: 'Specify which countries should NOT appear. This omits all countries that start with "A".', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(7)} onChange={(val) => this.selectCountry(7, val)} blacklist={['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ']}/> <RegionDropdown country={this.getCountryValue(7)} value={this.getRegionValue(7)} onChange={(val) => this.selectRegion(7, val)}/> </div> ); }, codeVisible: false, code: "&lt;CountryDropdown\n value={country}\n onChange={selectCountry}\n blacklist={['AF','AX','AL','DZ','AS','AD','AO','AI','AQ','AG']} />\n&lt;RegionDropdown\n country={country}\n value={region}\n onChange={selectRegion} />", country: '', region: '' }, { label: 'Explicitly disabling the country and region dropdowns (with defaults).', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(8)} onChange={(val) => this.selectCountry(8, val)} blacklist={['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ']} disabled={true}/> <RegionDropdown country={this.getCountryValue(8)} value={this.getRegionValue(8)} onChange={(val) => this.selectRegion(8, val)} disabled={true}/> </div> ); }, codeVisible: false, code: "&lt;CountryDropdown\n value=\"United States\"\n onChange={selectCountry}\n disabled={true} />\n&lt;RegionDropdown\n country={country}\n value=\"Washington\"\n onChange={selectRegion}\n disabled={true} />", country: 'United States', region: 'Washington' }, { label: 'Arbitrary attributes (style, tabindex) passed to Country and Region dropdown', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(9)} onChange={(val) => this.selectCountry(9, val)} style={{ backgroundColor: 'blue', color: 'white', fontSize: 20 }} tabIndex={1000}/> <RegionDropdown country={this.getCountryValue(9)} value={this.getRegionValue(9)} onChange={(val) => this.selectRegion(9, val)} style={{ backgroundColor: 'green', color: 'white' }} tabIndex={1001}/> </div> ); }, codeVisible: false, code: "&lt;CountryDropdown\n value=\"United States\"\n onChange={selectCountry}\n style={{\n backgroundColor: 'blue',\n color: 'white',\n fontSize: 20\n}}\n tabIndex={1000}\n disabled={true} />\n&lt;RegionDropdown\n country={country}\n value=\"Washington\"\n onChange={selectRegion}\n style={{\n backgroundColor: 'green',\n color: 'white']\n }}\n tabIndex={1001}\n disabled={true} />", country: '', region: '' }, { label: 'With custom options in the RegionDropdown.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(10)} onChange={(val) => this.selectCountry(10, val)}/> <RegionDropdown country={this.getCountryValue(10)} value={this.getRegionValue(10)} customOptions={['-- Custom option 1', '-- Custom option 2']} onChange={(val) => this.selectRegion(10, val)}/> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n onChange={selectCountry} />\n&lt;RegionDropdown\n country={country}\n value={region}\n onChange={selectRegion}\n customOptions={[\'-- Custom option 1\', \'-- Custom option 2\']} />', country: '', region: '' }, { label: 'Make Canada, United States and the UK appear first in the dropdown list.', jsx: () => { return ( <div> <CountryDropdown value={this.getCountryValue(11)} onChange={(val) => this.selectCountry(11, val)} priorityOptions={['CA', 'US', 'GB']} /> <RegionDropdown country={this.getCountryValue(11)} value={this.getRegionValue(11)} onChange={(val) => this.selectRegion(11, val)} /> </div> ); }, codeVisible: false, code: '&lt;CountryDropdown\n value={country}\n onChange={selectCountry}\n priorityOptions={["CA", "US", "GB"]} />\n&lt;RegionDropdown\n country={country}\n value={region}\n onChange={selectRegion} />', country: '', region: '' } ] }; } selectCountry (exampleIndex, val) { const updatedValues = this.state.examples; updatedValues[exampleIndex].country = val; this.setState({ examples: updatedValues }); } selectRegion (exampleIndex, val) { const updatedValues = this.state.examples; updatedValues[exampleIndex].region = val; this.setState({ examples: updatedValues }); } getCountryValue (index) { return this.state.examples[index].country; } getRegionValue (index) { return this.state.examples[index].region; } toggleCode (exampleIndex) { const updatedValues = this.state.examples; updatedValues[exampleIndex].codeVisible = !updatedValues[exampleIndex].codeVisible; this.setState({ examples: updatedValues }); } getExamples () { let i = 0; return this.state.examples.map((example) => { let j = i++; return ( <section key={i}> <p> <span className="counter">{i}.</span> {example.label} <span className="toggleCode" title="Toggle code" onClick={() => this.toggleCode(j)}>&lt;/&gt;</span> </p> {example.jsx()} <pre className="hljs html" style={{ display: example.codeVisible ? 'block' : 'none' }}> <code className="html" dangerouslySetInnerHTML={{ __html: example.code }}/> </pre> </section> ); }); } render () { return ( <div> {this.getExamples()} </div> ); } } export default Examples;
redux-demo/todos-with-undo/src/index.js
zhangjunhd/react-examples
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import App from './components/App' import reducer from './reducers' const store = createStore(reducer) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
examples/progressive-render/pages/index.js
nelak/next.js
import React from 'react' import NoSSR from 'react-no-ssr' import Loading from '../components/Loading' export default () => ( <main> <section> <h1> This section is server-side rendered. </h1> </section> <NoSSR onSSR={<Loading />}> <section> <h2> This section is <em>only</em> client-side rendered. </h2> </section> </NoSSR> <style jsx>{` section { align-items: center; display: flex; height: 50vh; justify-content: center; } `}</style> </main> )
src/helpers/extension.js
margox/braft-editor
/* eslint-disable no-param-reassign */ // TODO // -extended support for block-style and atomic types import React from 'react'; const extensionControls = []; const extensionDecorators = []; const propInterceptors = []; const extensionBlockRenderMaps = []; const extensionBlockRendererFns = []; const extensionInlineStyleMaps = []; const extensionInlineStyleFns = []; const extensionEntities = []; const inlineStyleImporters = []; const inlineStyleExporters = []; const blockImporters = []; const blockExporters = []; const filterByEditorId = (items, editorId) => { if (!editorId) { return items .filter((item) => !item.includeEditors) .map((item) => item.data); } return items .map((item) => { if (!item.includeEditors && !item.excludeEditors) { return item.data; } if (item.includeEditors) { return item.includeEditors.indexOf(editorId) !== -1 ? item.data : false; } if (item.excludeEditors) { return item.excludeEditors.indexOf(editorId) !== -1 ? false : item.data; } return false; }) .filter((item) => item); }; export const getPropInterceptors = (editorId) => filterByEditorId(propInterceptors, editorId); export const getExtensionControls = (editorId) => filterByEditorId(extensionControls, editorId); export const getExtensionDecorators = (editorId) => filterByEditorId(extensionDecorators, editorId, 'decorators'); export const getExtensionBlockRenderMaps = (editorId) => filterByEditorId(extensionBlockRenderMaps, editorId); export const getExtensionBlockRendererFns = (editorId) => filterByEditorId(extensionBlockRendererFns, editorId); export const getExtensionInlineStyleMap = (editorId) => { const inlineStyleMap = {}; filterByEditorId(extensionInlineStyleMaps, editorId).forEach((item) => { inlineStyleMap[item.inlineStyleName] = item.styleMap; }); return inlineStyleMap; }; export const getExtensionInlineStyleFns = (editorId) => filterByEditorId(extensionInlineStyleFns, editorId); export const compositeStyleImportFn = (styleImportFn, editorId) => ( nodeName, node, style, ) => { filterByEditorId(inlineStyleImporters, editorId).forEach((styleImporter) => { if (styleImporter.importer && styleImporter.importer(nodeName, node)) { style = style.add(styleImporter.inlineStyleName); } }); return styleImportFn ? styleImportFn(nodeName, node, style) : style; }; export const compositeStyleExportFn = (styleExportFn, editorId) => (style) => { style = style.toUpperCase(); let result = styleExportFn ? styleExportFn(style) : undefined; if (result) { return result; } filterByEditorId(inlineStyleExporters, editorId).find((item) => { if (item.inlineStyleName === style) { result = item.exporter; return true; } return false; }); return result; }; export const compositeEntityImportFn = (entityImportFn, editorId) => ( nodeName, node, createEntity, source, ) => { let result = entityImportFn ? entityImportFn(nodeName, node, createEntity, source) : null; if (result) { return result; } filterByEditorId(extensionEntities, editorId).find((entityItem) => { const matched = entityItem.importer ? entityItem.importer(nodeName, node, source) : null; if (matched) { result = createEntity( entityItem.entityType, matched.mutability || 'MUTABLE', matched.data || {}, ); } return !!matched; }); return result; }; export const compositeEntityExportFn = (entityExportFn, editorId) => ( entity, originalText, ) => { let result = entityExportFn ? entityExportFn(entity, originalText) : undefined; if (result) { return result; } const entityType = entity.type.toUpperCase(); filterByEditorId(extensionEntities, editorId).find((entityItem) => { if (entityItem.entityType === entityType) { result = entityItem.exporter ? entityItem.exporter(entity, originalText) : undefined; return true; } return false; }); return result; }; export const compositeBlockImportFn = (blockImportFn, editorId) => ( nodeName, node, source, ) => { let result = blockImportFn ? blockImportFn(nodeName, node, source) : null; if (result) { return result; } filterByEditorId(blockImporters, editorId).find((blockImporter) => { const matched = blockImporter.importer ? blockImporter.importer(nodeName, node, source) : undefined; if (matched) { result = matched; } return !!matched; }); return result; }; export const compositeBlockExportFn = (blockExportFn, editorId) => ( contentState, block, ) => { let result = blockExportFn ? blockExportFn(contentState, block) : null; if (result) { return result; } filterByEditorId(blockExporters, editorId).find((blockExporter) => { const matched = blockExporter.exporter ? blockExporter.exporter(contentState, block) : undefined; if (matched) { result = matched; } return !!matched; }); return result; }; const useExtension = (extension) => { if (extension instanceof Array) { extension.forEach(useExtension); return false; } if (!extension || !extension.type || typeof extension.type !== 'string') { return false; } const { includeEditors, excludeEditors } = extension; if (extension.type === 'control') { extensionControls.push({ includeEditors, excludeEditors, data: extension.control, }); } else if (extension.type === 'inline-style') { const inlineStyleName = extension.name.toUpperCase(); if (extension.control) { extensionControls.push({ includeEditors, excludeEditors, data: { key: inlineStyleName, type: 'inline-style', command: inlineStyleName, ...extension.control, }, }); } if (extension.style) { extensionInlineStyleMaps.push({ includeEditors, excludeEditors, data: { inlineStyleName, styleMap: extension.style, }, }); } if (extension.styleFn) { extensionInlineStyleFns.push({ includeEditors, excludeEditors, data: { inlineStyleName, styleFn: extension.styleFn, }, }); } if (extension.importer) { inlineStyleImporters.push({ includeEditors, excludeEditors, data: { inlineStyleName, importer: extension.importer, }, }); } inlineStyleExporters.push({ includeEditors, excludeEditors, data: { inlineStyleName, exporter: extension.exporter ? ( extension.exporter(extension) ) : ( <span style={extension.style} /> ), }, }); } else if (extension.type === 'block-style') { // TODO } else if (extension.type === 'entity') { const entityType = extension.name.toUpperCase(); if (extension.control) { extensionControls.push({ includeEditors, excludeEditors, data: { ...(typeof extension.control === 'function' && { key: entityType, type: 'entity', command: entityType, data: { mutability: extension.mutability || 'MUTABLE', data: extension.data || {}, }, ...extension.control, }), }, }); } extensionEntities.push({ includeEditors, excludeEditors, data: { entityType, importer: extension.importer, exporter: extension.exporter, }, }); extensionDecorators.push({ includeEditors, excludeEditors, data: { type: 'entity', decorator: { key: entityType, component: extension.component, }, }, }); } else if (extension.type === 'block') { const blockType = extension.name; if (extension.renderMap) { extensionBlockRenderMaps.push({ includeEditors, excludeEditors, data: { blockType, renderMap: extension.renderMap, }, }); } if (extension.rendererFn) { extensionBlockRendererFns.push({ includeEditors, excludeEditors, data: { blockType, rendererFn: extension.rendererFn, }, }); } if (extension.importer) { blockImporters.push({ includeEditors, excludeEditors, data: { blockType, importer: extension.importer, }, }); } if (extension.exporter) { blockExporters.push({ includeEditors, excludeEditors, data: { blockType, exporter: extension.exporter, }, }); } } else if (extension.type === 'atomic') { // TODO } else if (extension.type === 'decorator') { const { decorator } = extension; if (decorator && decorator.strategy && decorator.component) { extensionDecorators.push({ includeEditors, excludeEditors, data: { type: 'strategy', decorator, }, }); } else if (decorator && decorator.getDecorations) { extensionDecorators.push({ includeEditors, excludeEditors, data: { type: 'class', decorator, }, }); } } else if (extension.type === 'prop-interception') { propInterceptors.push({ includeEditors, excludeEditors, data: extension.interceptor, }); } return true; }; export const createExtensibleEditor = (BraftEditor) => { BraftEditor.use = useExtension; return BraftEditor; };
src/js/pages/Homepage.js
vbence86/project-bea
/* global $, ga */ import React from 'react'; import { HorizontalSplit, Navbar, NavItem, Page, Section, SignupModal } from 'neal-react'; import { ContentProvider } from '../components/ContentProvider'; import GoogleAnalytics from '../components/GoogleAnalytics'; import HeroVideo from '../components/HeroVideo'; import ProductPlan from '../components/ProductPlan'; import { CustomerFeedbacks, CustomerFeedback } from '../components/CustomerFeedback'; import { Footer } from '../components/Footer'; import PleaseWaitModal from '../components/PleaseWaitModal'; import ErrorModal from '../components/ErrorModal'; import ProductInfoModal from '../components/ProductInfoModal'; import { Team, TeamMember } from '../components/Team'; import '../components/SignupModal.Textarea'; const heroVideo = { poster: '/resources/images/first-frame-hero.jpg', source: { url: '/resources/videos/shutterstock_v17053459.m4v', type: 'video/mp4' } }; function registerGAEvents() { $('[data-target=#request-appointment-modal]').click(() => { $(document).trigger('request/open'); }); $(document).on('request/open', trackOpenRequestModal); $(document).on('request/submit', trackSubmitEvent); $(document).on('request/submit/happy-path', trackSubmitSuccess); $(document).on('request/submit/sad-path', trackSubmitFailure); $(document).on('click/product', trackProductEvent); } function trackOpenRequestModal() { ga('send', { hitType: 'event', eventCategory: 'Request an appointment', eventAction: 'click', eventLabel: 'Open' }); } function trackSubmitEvent() { ga('send', { hitType: 'event', eventCategory: 'Request an appointment', eventAction: 'click', eventLabel: 'Submit' }); } function trackSubmitSuccess() { ga('send', { hitType: 'event', eventCategory: 'Request an appointment', eventAction: 'click', eventLabel: 'Success' }); } function trackSubmitFailure() { ga('send', { hitType: 'event', eventCategory: 'Request an appointment', eventAction: 'click', eventLabel: 'Error' }); } function trackProductEvent(evt, data) { var title = data.title || 'Invalid product'; ga('send', { hitType: 'event', eventCategory: 'Product', eventAction: 'click', eventLabel: title }); } export default class Homepage extends React.Component { constructor(props) { super(props); this.state = { business: ContentProvider.get('business'), homepage: ContentProvider.get('homepage'), pleaseWaitModal: ContentProvider.get('pleaseWaitModal'), defaultErrorModal: ContentProvider.get('defaultErrorModal') }; } componentDidMount() { registerGAEvents(); } renderHeaderNavigation() { const menus = this.state.homepage.headerNavigation.map(item => { const props = { title: item.title, url: item.url }; return ( <NavItem> <a className="nav-link" href={ props.url } target="_blank">{ props.title }</a> </NavItem> ); }); return ( <Navbar brand={this.state.business.title}> { menus } </Navbar> ); } renderProductList() { const productList = this.state.homepage.productList; const numberOfFeaturesOfPremiumProduct = (products => { const premium = products[products.length - 1]; if (premium && premium.features) { return premium.features.length || 0; } else { return 0; } })(productList); const products = productList.map(item => { const pricing = { name: item.title, description: item.description, price: item.prize, buttonText: item.ctaLabel, color: item.color, bestSeller: item.bestSeller, features: (() => { if (item.features && item.features.length) { const diff = numberOfFeaturesOfPremiumProduct - item.features.length; if (item.features.length < numberOfFeaturesOfPremiumProduct) { for (let i = 0; i < diff; i += 1) { item.features.push(''); } } } return item.features; })(), onClick: evt => { evt.preventDefault(); $(document).trigger('click/product', item); } }; return ( <ProductPlan {... pricing} /> ); }); return ( <div className="row"> { products } </div> ); } renderFeedbackList() { const feedbacks = this.state.homepage.feedbacks.map(item => { const props = { text: item.text, rating: item.rating, name: item.customerName }; if (item.customerPortrait && item.customerPortrait.file) { props.imageUrl = 'http:' + item.customerPortrait.file.url; } return ( <CustomerFeedback {... props} /> ); }); return ( <CustomerFeedbacks> { feedbacks } </CustomerFeedbacks> ); } renderMemberList() { const members = this.state.homepage.memberList.map(member => { const props = { name: member.name, title: member.title, }; if (member.picture && member.picture.file) { props.imageUrl = 'http:' + member.picture.file.url; } return ( <TeamMember {... props}> { member.introduction } </TeamMember> ); }); return ( <Team> { members } </Team> ); } renderRequestModal() { const modalId = 'request-appointment-modal'; const messageServiceUrl = process.env.MESSAGE_SERVICE; const content = this.state.homepage.requestAppointmentModal; function onSendRequest() { Promise .resolve() .then(emitSubmitEvent) .then(hide.bind(null, 'request-appointment-modal')) .then(show.bind(null, 'please-wait-modal')) .then(sendFormDataToMessageService) .then(hide.bind(null, 'please-wait-modal')) .then(happyPath) .catch(sadPath); } function emitSubmitEvent() { $(document).trigger('request/submit'); } function hide(modalId) { const $modal = $(`#${modalId}`); return new Promise(resolve => { $modal.one('hidden.bs.modal', () => { resolve(); }); $modal.modal('hide'); }); } function show(modalId) { const $modal = $(`#${modalId}`); return new Promise(resolve => { $modal.one('shown.bs.modal', () => { resolve(); }); $modal.modal('show'); }); } function sendFormDataToMessageService() { const $form = $(`#${modalId} form`); const json = JSON.stringify(serializeFormData($form)); return new Promise((resolve, reject) => { $.ajax({ method: 'POST', contentType: 'application/json', dataType: 'json', data: json, url: messageServiceUrl, success: resolve, error: reject }); }); } function serializeFormData($form) { if (!$form) throw 'Invalid input!'; return $form.serializeArray().reduce((m, o) => { m[o.name] = o.value; return m; }, {}); } function happyPath() { $(document).trigger('request/submit/happy-path'); return show('request-confirmation-modal'); } function sadPath() { $(document).trigger('request/submit/sad-path'); return hide('please-wait-modal') .then(show.bind(null, 'error-modal')); } return ( <SignupModal title={content.title} buttonText={content.buttonLabel} modalId={modalId} onSubmit={onSendRequest}> <div> <p> {content.description} </p> </div> <div> <SignupModal.Input name="name" required label={content.name} placeholder={content.name} /> <SignupModal.Input name="age" required label="Age" placeholder={content.age} /> <SignupModal.Input type="email" required name="email" label={content.email} placeholder={content.email} /> <SignupModal.Textarea required name="intro" label="Introduction" placeholder={content.intro} /> <SignupModal.Textarea required name="request" rows="3" label="Request" placeholder={content.request} /> </div> </SignupModal> ); } renderRequestConfirmationModal() { const content = this.state.homepage.requestAppointmentModal.confirmationModal; const modalId = 'request-confirmation-modal'; function hideModal() { $(`#${modalId}`).modal('hide'); } return ( <SignupModal title={content.title} buttonText={ content.buttonLabel } modalId={ modalId } onSubmit={hideModal}> <div> <p>{ content.text }</p> </div> </SignupModal> ); } renderPleaseWaitModal() { const content = this.state.pleaseWaitModal; return ( <PleaseWaitModal title={content.text} modalId="please-wait-modal" /> ); } renderErrorModal() { const content = this.state.defaultErrorModal; return ( <ErrorModal title={content.title} text={content.text} buttonText={content.buttonText} modalId="error-modal" /> ); } renderProductInfoModal() { return ( <ProductInfoModal modalId="product-info-modal" /> ); } render() { return ( <Page> <GoogleAnalytics account="UA-90406705-1" /> { this.renderHeaderNavigation() } <HeroVideo {... heroVideo}> <h1 className="display-4 animated fadeInDown">{this.state.homepage.missionStatement}</h1> <p className="lead animated fadeInDown">{this.state.homepage.elevatorPitch}</p> <p> <a data-toggle="modal" data-target="#request-appointment-modal" className="btn btn-white"> {this.state.homepage.mainCta.title} </a> </p> </HeroVideo> <Section className="subhero gray"> <h3>{ this.state.homepage.subHeroTitle }</h3> </Section> <Section className="who-why-how"> <HorizontalSplit padding="md"> <div> <div className="sprite girl" title="Made by Feepik at Flaticons.com" /> <p className="lead">{ this.state.homepage.whoSection.title }</p> <p>{ this.state.homepage.whoSection.text }</p> </div> <div> <div className="sprite like" title="Made by Madebyoliver at Flaticons.com" /> <p className="lead">{ this.state.homepage.whySection.title }</p> <p>{ this.state.homepage.whySection.text }</p> </div> <div> <div className="sprite skype" title="Made by Madebyoliver at Flaticons.com" /> <p className="lead">{ this.state.homepage.howSection.title }</p> <p>{ this.state.homepage.howSection.text }</p> </div> </HorizontalSplit> </Section> <Section className="inline-cta gray"> <p> <a data-toggle="modal" data-target="#request-appointment-modal" className="btn btn-ghost btn-primary btn-lg"> {this.state.homepage.mainCta.title} </a> </p> </Section> <Section> { this.renderProductList() } </Section> <Section className="inline-cta gray"> <p> <a data-toggle="modal" data-target="#request-appointment-modal" className="btn btn-ghost btn-primary btn-lg"> {this.state.homepage.mainCta.title} </a> </p> </Section> <Section> { this.renderFeedbackList() } </Section> <Section> { this.renderMemberList() } </Section> { this.renderRequestModal() } { this.renderRequestConfirmationModal() } { this.renderPleaseWaitModal() } { this.renderErrorModal() } { this.renderProductInfoModal() } <Footer brandName={this.state.business.title} facebookUrl={this.state.business.facebookUrl} twitterUrl={this.state.business.twitterUrl} skype={this.state.business.skype} whatsup={this.state.business.whatsup} email={this.state.business.emailAddress} phone1={this.state.business.phoneNumber} phone2={this.state.business.phoneNumberOptional} address={this.state.business.address} /> </Page> ); } }
docs/src/app/components/pages/components/List/ExamplePhone.js
xmityaz/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import CommunicationCall from 'material-ui/svg-icons/communication/call'; import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble'; import {indigo500} from 'material-ui/styles/colors'; import CommunicationEmail from 'material-ui/svg-icons/communication/email'; const ListExamplePhone = () => ( <MobileTearSheet> <List> <ListItem leftIcon={<CommunicationCall color={indigo500} />} rightIcon={<CommunicationChatBubble />} primaryText="(650) 555 - 1234" secondaryText="Mobile" /> <ListItem insetChildren={true} rightIcon={<CommunicationChatBubble />} primaryText="(323) 555 - 6789" secondaryText="Work" /> </List> <Divider inset={true} /> <List> <ListItem leftIcon={<CommunicationEmail color={indigo500} />} primaryText="aliconnors@example.com" secondaryText="Personal" /> <ListItem insetChildren={true} primaryText="ali_connors@example.com" secondaryText="Work" /> </List> </MobileTearSheet> ); export default ListExamplePhone;
src/index.js
merylturner/budget-app
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import store from './store/index'; ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById('root')); registerServiceWorker();
renderer/pages/editor.js
wulkano/kap
import React from 'react'; import Head from 'next/head'; import {Provider} from 'unstated'; import {ipcRenderer as ipc} from 'electron-better-ipc'; import Editor from '../components/editor'; import Options from '../components/editor/options'; import {EditorContainer, VideoContainer} from '../containers'; const editorContainer = new EditorContainer(); const videoContainer = new VideoContainer(); videoContainer.setEditorContainer(editorContainer); editorContainer.setVideoContainer(videoContainer); export default class EditorPage extends React.Component { wasPaused = false; componentDidMount() { ipc.answerMain('file', async ({filePath, fps, originalFilePath, isNewRecording, recordingName, title}) => { await new Promise((resolve, reject) => { editorContainer.mount({filePath, fps: Number.parseInt(fps, 10), originalFilePath, isNewRecording, recordingName, title}, resolve, reject); }); return true; }); ipc.answerMain('export-options', editorContainer.setOptions); ipc.answerMain('save-original', editorContainer.saveOriginal); ipc.answerMain('blur', () => { this.wasPaused = videoContainer.state.isPaused; videoContainer.pause(); }); ipc.answerMain('focus', () => { if (!this.wasPaused) { videoContainer.play(); } }); } render() { return ( <div className="root"> <Head> <meta httpEquiv="Content-Security-Policy" content="media-src file:;"/> </Head> <div className="cover-window"> <Provider inject={[editorContainer, videoContainer]}> <div className="video-container"> <Editor/> </div> <div className="controls-container"> <Options/> </div> </Provider> </div> <style jsx global>{` html { font-size: 62.5%; } body, .cover-window { margin: 0; width: 100vw; height: 100vh; -webkit-app-region: drag; font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif; user-select: none; cursor: default; -webkit-font-smoothing: antialiased; letter-spacing: -.01rem; text-shadow: 0 1px 2px rgba(0,0,0,.1); } :root { --slider-popup-background: rgba(255, 255, 255, 0.85); --slider-background-color: #ffffff; --slider-thumb-color: #ffffff; --background-color: #222222; } .dark { --slider-popup-background: #222222; --slider-background-color: var(--input-background-color); --slider-thumb-color: var(--storm); } .cover-window { display: flex; flex-direction: column; } .video-container { flex: 1; display: flex; background: #000; } .controls-container { height: 48px; z-index: 50; display: flex; background: rgba(0, 0, 0, 0.3); } @keyframes shake-left { 10%, 90% { transform: translate3d(-1px, 0, 0); } 20%, 80% { transform: translate3d(0, 0, 0); } 30%, 50%, 70% { transform: translate3d(-4px, 0, 0); } 40%, 60% { transform: translate3d(0, 0, 0); } } @keyframes shake-right { 10%, 90% { transform: translate3d(1px, 0, 0); } 20%, 80% { transform: translate3d(0, 0, 0); } 30%, 50%, 70% { transform: translate3d(4px, 0, 0); } 40%, 60% { transform: translate3d(0, 0, 0); } } .shake-left { transform: translate3d(0, 0, 0); backface-visibility: hidden; perspective: 1000px; animation: shake-left 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; } .shake-right { transform: translate3d(0, 0, 0); backface-visibility: hidden; perspective: 1000px; animation: shake-right 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; } @keyframes shake { 10%, 90% { transform: translate3d(-1px, 0, 0); } 20%, 80% { transform: translate3d(2px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-4px, 0, 0); } 40%, 60% { transform: translate3d(4px, 0, 0); } } .shake { transform: translate3d(0, 0, 0); backface-visibility: hidden; perspective: 1000px; animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; } * { box-sizing: border-box; } `}</style> </div> ); } }
webpack/ForemanTasks/Components/TasksTable/formatters/selectionHeaderCellFormatter.js
adamruzicka/foreman-tasks
import React from 'react'; import TableSelectionHeaderCell from '../Components/TableSelectionHeaderCell'; export default (selectionController, label) => ( <TableSelectionHeaderCell label={label} checked={selectionController.allPageSelected()} disabled={!selectionController.permissions.edit} onChange={selectionController.selectPage} /> );
app/jsx/choose_mastery_path/components/path-option.js
djbender/canvas-lms
/* * Copyright (C) 2016 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import I18n from 'i18n!choose_mastery_path' import Assignment from './assignment' import SelectButton from './select-button' import assignmentShape from '../shapes/assignment-shape' const {func, number, arrayOf} = PropTypes export default class PathOption extends React.Component { static propTypes = { assignments: arrayOf(assignmentShape).isRequired, optionIndex: number.isRequired, setId: number.isRequired, selectedOption: number, selectOption: func.isRequired } selectOption = () => { this.props.selectOption(this.props.setId) } render() { const {selectedOption, setId, optionIndex} = this.props const disabled = selectedOption !== null && selectedOption !== undefined && selectedOption !== setId const selected = selectedOption === setId const optionClasses = classNames({ 'item-group-container': true, 'cmp-option': true, 'cmp-option__selected': selected, 'cmp-option__disabled': disabled }) return ( <div className={optionClasses}> <div className="item-group"> <div className="ig-header"> <span className="name">{I18n.t('Option %{index}', {index: optionIndex + 1})}</span> <SelectButton isDisabled={disabled} isSelected={selected} onSelect={this.selectOption} /> </div> <ul className="ig-list"> {this.props.assignments.map((assg, i) => ( <Assignment key={i} assignment={assg} isSelected={selected} /> ))} </ul> </div> </div> ) } }
react/src/index.js
thienan93/bms
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {createStore, applyMiddleware} from 'redux'; import {Router, hashHistory} from 'react-router'; import routes from './routes'; import rootReducers from './reducers/index-reducer'; import './components/bundle.scss'; import injectTapEventPlugin from 'react-tap-event-plugin'; import logMiddleware from './middlewares/log-middleware'; import resourceMiddleware from './middlewares/resource-middleware'; import createSagaMiddleware from 'redux-saga'; import rootSaga from './sagas/index-sagas'; import ReduxToastr from 'react-redux-toastr'; import {syncHistoryWithStore, routerMiddleware} from 'react-router-redux'; const sagaMiddleware = createSagaMiddleware(); const middlewares = [logMiddleware, resourceMiddleware, routerMiddleware(hashHistory), sagaMiddleware]; const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore); const store = createStoreWithMiddleware(rootReducers); sagaMiddleware.run(rootSaga); // Needed for onTouchTap refer http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); const history = syncHistoryWithStore(hashHistory, store); ReactDOM.render( <Provider store={store}> <div> <Router history={history} onUpdate={() => window.scrollTo(0, 0)} routes={routes} /> <ReduxToastr position="bottom-right"/> </div> </Provider>, document.getElementById('bms-root'));
src/svg-icons/device/wifi-tethering.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceWifiTethering = (props) => ( <SvgIcon {...props}> <path d="M12 11c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 2c0-3.31-2.69-6-6-6s-6 2.69-6 6c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-2.21 1.79-4 4-4s4 1.79 4 4c0 1.48-.81 2.75-2 3.45l1 1.74c1.79-1.04 3-2.97 3-5.19zM12 3C6.48 3 2 7.48 2 13c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 18.53 4 15.96 4 13c0-4.42 3.58-8 8-8s8 3.58 8 8c0 2.96-1.61 5.53-4 6.92l1 1.73c2.99-1.73 5-4.95 5-8.65 0-5.52-4.48-10-10-10z"/> </SvgIcon> ); DeviceWifiTethering = pure(DeviceWifiTethering); DeviceWifiTethering.displayName = 'DeviceWifiTethering'; DeviceWifiTethering.muiName = 'SvgIcon'; export default DeviceWifiTethering;
examples/with-koa/src/client.js
jaredpalmer/react-production-starter
import App from './App'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import React from 'react'; import { hydrate } from 'react-dom'; hydrate( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
src/svg-icons/image/switch-camera.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageSwitchCamera = (props) => ( <SvgIcon {...props}> <path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 11.5V13H9v2.5L5.5 12 9 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); ImageSwitchCamera = pure(ImageSwitchCamera); ImageSwitchCamera.displayName = 'ImageSwitchCamera'; ImageSwitchCamera.muiName = 'SvgIcon'; export default ImageSwitchCamera;
src/admin/client/modules/customers/filter/components/fields.js
cezerin/cezerin
import React from 'react'; import messages from 'lib/text'; import style from './style.css'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import Toggle from 'material-ui/Toggle'; export default ({ active, discontinued, on_sale, stock_status, setActive, setDiscontinued, setOnSale, setStock }) => { return ( <div className={style.filter}> <Toggle label={messages.products_onlyEnabled} onToggle={(e, value) => { setActive(value); }} toggled={active} className={style.toggle} /> <Toggle label={messages.products_onlyDiscontinued} onToggle={(e, value) => { setDiscontinued(value); }} toggled={discontinued} className={style.toggle} /> <Toggle label={messages.products_onlyOnSale} onToggle={(e, value) => { setOnSale(value); }} toggled={on_sale} className={style.toggle} /> <SelectField value={stock_status} onChange={(event, index, value) => { setStock(value); }} floatingLabelText={messages.products_stockStatus} fullWidth={true} > <MenuItem value={'all'} primaryText={messages.all} /> <MenuItem value={'available'} primaryText={messages.products_inStock} /> <MenuItem value={'out_of_stock'} primaryText={messages.products_outOfStock} /> <MenuItem value={'backorder'} primaryText={messages.products_backorder} /> <MenuItem value={'preorder'} primaryText={messages.products_preorder} /> <MenuItem value={'discontinued'} primaryText={messages.products_discontinued} /> </SelectField> </div> ); };
lib/components/GutterResize.js
alexcorre/git-blame
'use babel'; import { isFunction } from 'lodash'; import React from 'react'; import { compose, withHandlers } from 'recompose'; function GutterResize({children, onMouseDown}) { return ( <div className="resize-container"> {children} <div className="resize" onMouseDown={onMouseDown} role="presentation" /> </div> ); } export default compose( withHandlers({ onMouseDown({ onResizeStart }) { return function (e) { return isFunction(onResizeStart) && onResizeStart(e.nativeEvent); }; }, }) )(GutterResize);