path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
docs/app/Examples/views/Card/Content/CardExampleHeaderCard.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Card } from 'semantic-ui-react' const CardExampleHeaderCard = () => ( <Card.Group> <Card> <Card.Content> <Card.Header>Matthew Harris</Card.Header> <Card.Meta>Co-Worker</Card.Meta> <Card.Description>Matthew is a pianist living in Nashville.</Card.Description> </Card.Content> </Card> <Card> <Card.Content> <Card.Header content='Jake Smith' /> <Card.Meta content='Musicians' /> <Card.Description content='Jake is a drummer living in New York.' /> </Card.Content> </Card> <Card> <Card.Content header='Elliot Baker' meta='Friend' description='Elliot is a music producer living in Chicago.' /> </Card> <Card header='Jenny Hess' meta='Friend' description='Jenny is a student studying Media Management at the New School' /> </Card.Group> ) export default CardExampleHeaderCard
Console/app/node_modules/antd/es/input-number/index.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import classNames from 'classnames'; import RcInputNumber from 'rc-input-number'; var InputNumber = function (_React$Component) { _inherits(InputNumber, _React$Component); function InputNumber() { _classCallCheck(this, InputNumber); return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments)); } _createClass(InputNumber, [{ key: 'render', value: function render() { var _classNames; var _a = this.props, className = _a.className, size = _a.size, others = __rest(_a, ["className", "size"]); var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className); return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others)); } }]); return InputNumber; }(React.Component); export default InputNumber; InputNumber.defaultProps = { prefixCls: 'ant-input-number', step: 1 };
src/components/Navbar/Navbar.js
uiruson/chorongi
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; import React from 'react'; var Navbar = React.createClass({ render() { return ( /* jshint ignore:start */ <div className="navbar-top" role="navigation"> <div className="container"> <a className="navbar-brand row" href="/"> <img src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span>React.js Starter Kit</span> </a> </div> </div> /* jshint ignore:end */ ); } }); module.exports = Navbar;
src/Input.js
buildo/rc-datepicker
import React from 'react'; import cx from 'classnames'; import { props } from 'tcomb-react'; import t from 'tcomb'; import View from 'react-flexview'; import skinnable from './utils/skinnable'; import pure from './utils/pure'; @pure @skinnable() @props({ value: t.maybe(t.String), onInputChange: t.Function, iconClearClassName: t.String, iconClassName: t.String, hasValue: t.Boolean, active: t.Boolean, small: t.Boolean, onButtonClick: t.maybe(t.Function), onInputClick: t.maybe(t.Function), onInputClear: t.maybe(t.Function), onInputKeyUp: t.Function }, { strict: false }) export default class Input extends React.Component { getLocals(props) { const { value, iconClearClassName, iconClassName, hasValue, active, small, onButtonClick, onInputClick, onInputChange, onInputClear, onInputKeyUp, ...inputProps } = props; return { className: cx('react-datepicker-input', { 'is-open': active, 'has-value': hasValue, 'is-small': small }), inputButtonProps: onButtonClick && { onButtonClick, iconClassName, className: cx('input-button', { active }) }, clearButtonProps: onInputClear && hasValue && { onInputClear, iconClearClassName }, inputProps: { value, onChange: onInputChange, onClick: onInputClick, onKeyUp: onInputKeyUp, ...inputProps } }; } templateInputButton({ className, onButtonClick, iconClassName }) { return ( <View shrink={false} className={className} onClick={onButtonClick}> <i className={iconClassName} /> </View> ); } templateClearButton({ onInputClear, iconClearClassName }) { return ( <View shrink={false} className='clear-button' onClick={onInputClear}> <i className={iconClearClassName} /> </View> ); } template({ className, inputButtonProps, clearButtonProps, inputProps }) { return ( <div className={className}> <input {...inputProps} /> <View className='button-wrapper' vAlignContent='center'> {clearButtonProps && this.templateClearButton(clearButtonProps)} {inputButtonProps && this.templateInputButton(inputButtonProps)} </View> </div> ); } }
docs/src/Routes.js
SSLcom/Bootsharp
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import ComponentsPage from './ComponentsPage'; import NotFoundPage from './NotFoundPage'; import Root from './Root'; export default ( <Route path="/" component={Root}> <IndexRoute component={ComponentsPage} /> <Route path="components.html" component={ComponentsPage} /> <Route path="*" component={NotFoundPage} /> </Route> );
src/logo.js
coma/spotify
import React from 'react'; import style from './logo.css'; class Logo extends React.Component { render () { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 45 40" className={ style.main }> <path className={ style.a } d="M45,25c0,9.32 -10.074,15 -22.5,15c-12.426,0 -22.5,-5.68 -22.5,-15c0,-9.32 10.074,-18.75 22.5,-18.75c12.426,0 22.5,9.43 22.5,18.75"/> <path className={ style.b } d="M39.694,13.345c1.71,-1.375 2.806,-3.482 2.806,-5.845c0,-4.142 -3.358,-7.5 -7.5,-7.5c-3.576,0 -6.563,2.506 -7.313,5.856c-1.611,-0.604 -3.355,-0.948 -5.187,-0.948c-1.831,0 -3.576,0.344 -5.186,0.948c-0.752,-3.35 -3.738,-5.856 -7.314,-5.856c-4.141,0 -7.5,3.358 -7.5,7.5c0,2.363 1.097,4.47 2.806,5.845c-3.306,3.35 -5.306,7.511 -5.306,11.655c0,9.32 10.074,1.25 22.5,1.25c12.427,0 22.5,8.07 22.5,-1.25c0,-4.144 -1.999,-8.305 -5.306,-11.655"/> <path className={ style.c } d="M13.75,6.875c0,2.416 -1.959,4.375 -4.375,4.375c-2.416,0 -4.375,-1.959 -4.375,-4.375c0,-2.416 1.959,-4.375 4.375,-4.375c2.416,0 4.375,1.959 4.375,4.375"/> <path className={ style.d } d="M11.25,6.875c0,1.036 -0.839,1.875 -1.875,1.875c-1.036,0 -1.875,-0.839 -1.875,-1.875c0,-1.036 0.839,-1.875 1.875,-1.875c1.036,0 1.875,0.839 1.875,1.875"/> <path className={ style.c } d="M40,6.875c0,2.416 -1.958,4.375 -4.375,4.375c-2.418,0 -4.375,-1.959 -4.375,-4.375c0,-2.416 1.957,-4.375 4.375,-4.375c2.417,0 4.375,1.959 4.375,4.375"/> <path className={ style.d } d="M37.5,6.875c0,1.036 -0.84,1.875 -1.875,1.875c-1.035,0 -1.875,-0.839 -1.875,-1.875c0,-1.036 0.84,-1.875 1.875,-1.875c1.035,0 1.875,0.839 1.875,1.875"/> <path className={ style.e } d="M18.75,22.5c0,0.691 -0.56,1.25 -1.25,1.25c-0.69,0 -1.25,-0.559 -1.25,-1.25c0,-0.691 0.56,-1.25 1.25,-1.25c0.69,0 1.25,0.559 1.25,1.25"/> <path className={ style.e } d="M28.75,22.5c0,0.691 -0.559,1.25 -1.25,1.25c-0.691,0 -1.25,-0.559 -1.25,-1.25c0,-0.691 0.559,-1.25 1.25,-1.25c0.691,0 1.25,0.559 1.25,1.25"/> </svg> ); } } export default Logo;
app/javascript/mastodon/features/compose/containers/warning_container.js
WitchesTown/mastodon
import React from 'react'; import { connect } from 'react-redux'; import Warning from '../components/warning'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { me } from '../../../initial_state'; const APPROX_HASHTAG_RE = /(?:^|[^\/\)\w])#(\w*[a-zA-Z·]\w*)/i; const mapStateToProps = state => ({ needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']), hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])), }); const WarningWrapper = ({ needsLockWarning, hashtagWarning }) => { if (needsLockWarning) { return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />; } if (hashtagWarning) { return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />; } return null; }; WarningWrapper.propTypes = { needsLockWarning: PropTypes.bool, hashtagWarning: PropTypes.bool, }; export default connect(mapStateToProps)(WarningWrapper);
src/containers/SearchFormContainer.js
blwoosky/DigCSS-Theme-v4-Redesign
import React, { Component } from 'react'; import SearchForm from "./../components/SearchForm"; import { Link,browserHistory } from 'react-router'; import { connect } from "react-redux"; import { search } from "./../actions"; export default class SearchFormContainer extends Component { constructor(props) { super(props); this.onInputChange = this.onInputChange.bind(this); this.onSearch = this.onSearch.bind(this); this.state = { keyword: "" } } onInputChange(e) { this.setState({ keyword: e.target.value }); //console.log(this.state.keyword); } onSearch(e) { e.preventDefault(); this.props.setOpened(false); this.setState({ keyword: "" }); browserHistory.push(`/search/${this.state.keyword}`); } render() { return ( <SearchForm keyword={this.state.keyword} {...this.props} {...this}/> ) } } //function mapStateToProps(store) { // return { // list: store.search.list, // pageNum: store.search.pageNum, // totalPages: store.search.totalPages // }; //} export default connect(null, {search})(SearchFormContainer);
src/Fade.js
mengmenglv/react-bootstrap
import React from 'react'; import Transition from 'react-overlays/lib/Transition'; import CustomPropTypes from './utils/CustomPropTypes'; import deprecationWarning from './utils/deprecationWarning'; class Fade extends React.Component { render() { let timeout = this.props.timeout || this.props.duration; return ( <Transition {...this.props} timeout={timeout} className="fade" enteredClassName="in" enteringClassName="in" > {this.props.children} </Transition> ); } } // Explicitly copied from Transition for doc generation. // TODO: Remove duplication once #977 is resolved. Fade.propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: React.PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: React.PropTypes.number, /** * duration * @private */ duration: CustomPropTypes.all([ React.PropTypes.number, (props)=> { if (props.duration != null) { deprecationWarning('Fade `duration`', 'the `timeout` prop'); } return null; } ]), /** * Callback fired before the component fades in */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: React.PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: React.PropTypes.func, /** * Callback fired before the component fades out */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: React.PropTypes.func, /** * Callback fired after the component has faded out */ onExited: React.PropTypes.func }; Fade.defaultProps = { in: false, timeout: 300, unmountOnExit: false, transitionAppear: false }; export default Fade;
src/routes.js
ProjectSunday/rooibus
import React from 'react' import { Route, IndexRoute } from 'react-router' import About from './components/about' import Root from './components/root' import FriendMap from './components/friend-map' import Session from './components/session' export default ( <Route path="/" component={Root}> <IndexRoute component={FriendMap} /> <Route path="/about" component={About} /> <Route path="/:mapId" component={Session} /> </Route> )
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Listing/MoreMenu.js
Minoli/carbon-apimgt
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Button from 'material-ui/Button'; import Grow from 'material-ui/transitions/Grow'; import Paper from 'material-ui/Paper'; import { withStyles } from 'material-ui/styles'; import { Manager, Target, Popper } from 'react-popper'; import ClickAwayListener from 'material-ui/utils/ClickAwayListener'; import MoreHoriz from '@material-ui/icons/MoreHoriz'; import List, {ListItem, ListItemText} from 'material-ui/List'; import {Link} from 'react-router-dom' const styles = { root: { display: 'flex', zIndex: 1202, position: 'absolute', marginTop: -20, left: 190, }, popperClose: { pointerEvents: 'none', }, moreButton: { backgroundColor: '#4c4c4c', minWidth: 55, minHeight: 20, color: '#fff', padding: 0, } }; class MoreMenu extends React.Component { state = { open: false, }; handleClick = () => { this.setState({ open: true }); }; handleClose = () => { this.setState({ open: false }); }; render() { const { classes } = this.props; const { open } = this.state; const tabs = [ "overview", "lifecycle", "endpoints", "resources", "scopes", "documents", "permission", "mediation", "scripting", "subscriptions", "security" ]; return ( <div className={classes.root}> <Manager> <Target> <Button aria-owns={open ? 'menu-list' : null} aria-haspopup="true" onClick={this.handleClick} className={classes.moreButton} variant="raised" > <MoreHoriz /> </Button> </Target> <Popper placement="bottom-start" eventsEnabled={open} className={classNames({ [classes.popperClose]: !open })} > <ClickAwayListener onClickAway={this.handleClose}> <Grow in={open} id="menu-list" style={{ transformOrigin: '0 0 0' }}> <Paper> <List> {tabs.map(tab => (<ListItem key={tab}> <Link name={tab} to={"/apis/" + this.props.api_uuid + "/" + tab}> <ListItemText primary={tab}/></Link> </ListItem>) )} </List> </Paper> </Grow> </ClickAwayListener> </Popper> </Manager> </div> ); } } MoreMenu.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(MoreMenu);
app/javascript/mastodon/components/status_content.js
tootcafe/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; import PollContainer from 'mastodon/containers/poll_container'; import Icon from 'mastodon/components/icon'; import { autoPlayGif } from 'mastodon/initial_state'; const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top) export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, showThread: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, collapsable: PropTypes.bool, onCollapsedToggle: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; if (!node) { return; } const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } if (this.props.status.get('collapsed', null) === null) { let collapsed = this.props.collapsable && this.props.onClick && node.clientHeight > MAX_HEIGHT && this.props.status.get('spoiler_text').length === 0; if(this.props.onCollapsedToggle) this.props.onCollapsedToggle(collapsed); this.props.status.set('collapsed', collapsed); } } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, ''); if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; let element = e.target; while (element) { if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') { return; } element = element.parentNode; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const renderReadMore = this.props.onClick && status.get('collapsed'); const renderViewThread = this.props.showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']); const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, 'status__content--with-spoiler': status.get('spoiler_text').length > 0, 'status__content--collapsed': renderReadMore, }); const showThreadButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick}> <FormattedMessage id='status.show_thread' defaultMessage='Show thread' /> </button> ); const readMoreButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'> <FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' fixedWidth /> </button> ); if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} className='translate' /> {' '} <button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} dangerouslySetInnerHTML={content} /> {!hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } else if (this.props.onClick) { const output = [ <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div>, ]; if (renderReadMore) { output.push(readMoreButton); } return output; } else { return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } } }
src/components/pages/PatientsSummary/patients-summary.config.js
PulseTile/PulseTile-React
import React from 'react'; import { get } from 'lodash'; import { themePatientSummaryConfig } from '../../theme/config/plugins'; import { allergiesPrevImage, problemsPrevImage, contactsPrevImage, medicationsPrevImage, } from './ImageSources'; import { themeConfigs } from '../../../themes.config'; import { isPluginVisible, rangePlugins } from '../../../utils/themeSettings-helper'; const problemsTitle = get(themeConfigs.patientsSummaryTitles, 'diagnoses', 'Problems / Diagnosis'); const contactsTitle = get(themeConfigs.patientsSummaryTitles, 'contacts', 'Contacts'); const allergiesTitle = get(themeConfigs.patientsSummaryTitles, 'allergies', 'Allergies'); const medicationsTitle = get(themeConfigs.patientsSummaryTitles, 'medications', 'Medications'); const corePatientsSummaryConfig = [ { key: 'problems', panelId: 'summary-panel-problems', title: problemsTitle, emptyMessage: 'No information available', state: 'diagnoses', titleCheckboxes: problemsTitle, nameCheckboxes: 'problems', imgPreview: problemsPrevImage, isDefaultSelected: true, }, { key: 'contacts', panelId: 'summary-panel-contacts', title: contactsTitle, emptyMessage: 'No information available', titleCheckboxes: contactsTitle, state: 'contacts', nameCheckboxes: 'contacts', imgPreview: contactsPrevImage, isDefaultSelected: true, }, { key: 'allergies', panelId: 'summary-panel-allergies', title: allergiesTitle, emptyMessage: 'No information available', titleCheckboxes: allergiesTitle, state: 'allergies', nameCheckboxes: 'allergies', imgPreview: allergiesPrevImage, isDefaultSelected: true, }, { key: 'medications', panelId: 'summary-panel-medications', title: medicationsTitle, emptyMessage: 'No information available', titleCheckboxes: medicationsTitle, state: 'medications', nameCheckboxes: 'medications', imgPreview: medicationsPrevImage, isDefaultSelected: true, }, ]; /** * This constant returns list of pattient summary plugins, excluded corePluginsToHide (themes settings) * * @return {array} */ const filterPatientsSummaryConfig = corePatientsSummaryConfig.filter(item => { const hiddenCorePlugins = get(themeConfigs, 'corePluginsToHide', []); return isPluginVisible(hiddenCorePlugins, item.state); }); const totalSummaryConfig = filterPatientsSummaryConfig.concat(themePatientSummaryConfig); export const patientsSummaryConfig = rangePlugins(totalSummaryConfig); export const defaultViewOfBoardsSelected = { full: true, preview: false, list: false, };
node_modules/react-bootstrap/es/Table.js
xuan6/admin_dashboard_local_dev
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 { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { striped: PropTypes.bool, bordered: PropTypes.bool, condensed: PropTypes.bool, hover: PropTypes.bool, responsive: PropTypes.bool }; var defaultProps = { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; var Table = function (_React$Component) { _inherits(Table, _React$Component); function Table() { _classCallCheck(this, Table); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Table.prototype.render = function render() { var _extends2; var _props = this.props, striped = _props.striped, bordered = _props.bordered, condensed = _props.condensed, hover = _props.hover, responsive = _props.responsive, className = _props.className, props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'striped')] = striped, _extends2[prefix(bsProps, 'bordered')] = bordered, _extends2[prefix(bsProps, 'condensed')] = condensed, _extends2[prefix(bsProps, 'hover')] = hover, _extends2)); var table = React.createElement('table', _extends({}, elementProps, { className: classNames(className, classes) })); if (responsive) { return React.createElement( 'div', { className: prefix(bsProps, 'responsive') }, table ); } return table; }; return Table; }(React.Component); Table.propTypes = propTypes; Table.defaultProps = defaultProps; export default bsClass('table', Table);
developers.diem.com/src/pages/index.js
libra/libra
import React from 'react'; import {Redirect} from '@docusaurus/router'; import useBaseUrl from '@docusaurus/useBaseUrl'; function Home() { return <Redirect to={useBaseUrl('/docs/welcome-to-diem/')} />; } export default Home;
lib/Card.js
robbiegreiner/weathrly
import React from 'react'; const Card = ({ time, condition, img, temp, }) => { return ( <div className='card'> <p className='time'>{time}</p> <div className='card-condition'> <p>{condition}</p> </div> <div className='img-background'> <img src={img} alt={condition}/> </div> <p className='temp'>{temp}</p> </div> ); }; export default Card;
src/containers/layout/List/List.js
max-gram/react-saga-universal
import React from 'react' import PropTypes from 'prop-types' import { Grid, Row } from 'react-flexbox-grid' import css from './List.css' const List = ({children, className}) => { return ( <section className={className ? className : css.section}> <Grid fluid> <Row middle="xs" className={css.row}> {children} </Row> </Grid> </section> ) } List.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, } export default List
docs/Documentation/DatePickerPage.js
reactivers/react-mcw
/** * Created by muratguney on 29/03/2017. */ import React from 'react'; import {Card, IconButton,CardHeader,DatePicker,Table, TableRow, TableHeaderColumn, TableHeader, TableRowColumn, TableBody} from '../../lib'; import Highlight from 'react-highlight.js' export default class ChipPage extends React.Component { state = {dialog: false, open: false}; render() { let document = ` <div> <DatePicker/> <DatePicker value="Fri Apr 30 2027 23:47:26 GMT+0300 (+03)"/> <DatePicker value="Fri Apr 30 2017 23:47:26 GMT+0300 (+03)" open={this.state.open} onClose={this.closeDatepicker} /> <IconButton onClick={this.openDatePicker} iconName={"date_range"}/> </div> `; return ( <Card style={{padding: 8}}> <CardHeader title="DatePicker"/> <div style={{margin: "0 auto"}}> <DatePicker/> <div style={{padding: 16}}></div> <DatePicker value="Fri Apr 30 2027 23:47:26 GMT+0300 (+03)"/> <div style={{padding: 16}}></div> <DatePicker value="Fri Apr 30 2017 23:47:26 GMT+0300 (+03)" open={this.state.open} onClose={() => this.setState({open: false})}/> <IconButton onClick={() => this.setState({open: true})} iconName={"date_range"}/> </div> <Highlight language="javascript">{document}</Highlight> <CardHeader title="Datepicker properties"/> <Table> <TableHeader> <TableRow> <TableHeaderColumn>Props</TableHeaderColumn> <TableHeaderColumn>Type</TableHeaderColumn> <TableHeaderColumn>Description</TableHeaderColumn> </TableRow> </TableHeader> <TableBody> <TableRow> <TableRowColumn>open</TableRowColumn> <TableRowColumn>Boolean</TableRowColumn> <TableRowColumn>If true, dialog opens as dialog and shows cancel and ok buttons.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>value</TableRowColumn> <TableRowColumn>Date</TableRowColumn> <TableRowColumn>You can send a date as string.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>onClose</TableRowColumn> <TableRowColumn>Function</TableRowColumn> <TableRowColumn>Fire when dialog close.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>onChange</TableRowColumn> <TableRowColumn>Function</TableRowColumn> <TableRowColumn>Gets value of date.</TableRowColumn> </TableRow> </TableBody> </Table> </Card> ) } }
blueocean-material-icons/src/js/components/svg-icons/image/wb-sunny.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageWbSunny = (props) => ( <SvgIcon {...props}> <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> </SvgIcon> ); ImageWbSunny.displayName = 'ImageWbSunny'; ImageWbSunny.muiName = 'SvgIcon'; export default ImageWbSunny;
tp-3/juan-pablo-gonzalez/src/components/Root.js
solp/sovos-reactivo-2017
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import App from './App'; import { BrowserRouter as Router } from 'react-router-dom'; export default class Root extends Component { render() { return ( <Router> <App /> </Router> ); } } Root.propTypes = { history: PropTypes.object };
src/containers/LandingPage/AboutPidc/index.js
westoncolemanl/tabbr-web
import React from 'react' import Body from './Body' export default () => { window.scrollTo(0, 0) return ( <div> <Body /> </div> ) }
app/components/EarningsTableFooter/index.js
projectcashmere/web-server
/** * * EarningsTableFooter * */ import React from 'react'; import styled from 'styled-components'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; const Table = styled.table` background-color: grey; color: white; height: 40px; margin: 5px; margin-bottom: 20px; width: 100%; `; function EarningsTableFooter(props) { return ( <div> <Table> <tbody> <tr className='row'> <td className='col-sm-6'>TOTAL</td> <td className='col-sm-2'>{props.roomIncomeTotal}</td> <td className='col-sm-2'>{props.addIncomeTotal}</td> <td className='col-sm-2'>{props.roomIncomeTotal + props.addIncomeTotal}</td> </tr> </tbody> </Table> </div> ); } EarningsTableFooter.propTypes = { }; export default EarningsTableFooter;
packages/react/src/components/ErrorBoundary/ErrorBoundary.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import { ErrorBoundaryContext } from './ErrorBoundaryContext'; /** * React introduced additional lifecycle methods in v16 for capturing errors * that occur in a specific sub-tree of components. This component helps to * consolidate some of the duplication that occurs when using these lifecycle * methods across a codebase. In addition, it allows you to specify the fallback * UI to display when an error occurs in the sub-tree through the `fallback` * prop. * * This component roughly follows the React.js docs example code for these * methods. In addition, it takes advantage of an `ErrorBoundaryContext` so that * consumers can specify their own logic for logging errors. For example, * reporting an error in the UI to an external service for every `ErrorBoundary` * used. * * Reference: * https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries */ export default class ErrorBoundary extends React.Component { static propTypes = { children: PropTypes.node, fallback: PropTypes.node, }; static contextType = ErrorBoundaryContext; static getDerivedStateFromError() { return { hasError: true, }; } state = { hasError: false, }; componentDidCatch(error, info) { this.context.log(error, info); } componentDidUpdate(prevProps) { if (prevProps.children !== this.props.children) { this.setState({ hasError: false }); } } render() { if (this.state.hasError) { return this.props.fallback; } return this.props.children; } }
app/jsx/external_apps/components/AppDetails.js
djbender/canvas-lms
/* * Copyright (C) 2014 - 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 I18n from 'i18n!external_tools' import React from 'react' import PropTypes from 'prop-types' import page from 'page' import Header from './Header' import AddApp from './AddApp' import 'compiled/jquery.rails_flash_notifications' export default class AppDetails extends React.Component { static propTypes = { store: PropTypes.object.isRequired, baseUrl: PropTypes.string.isRequired, shortName: PropTypes.string.isRequired } state = { app: null } componentDidMount() { const app = this.props.store.findAppByShortName(this.props.shortName) if (app) { this.setState({app}) } else { page('/') } } handleToolInstalled = () => { const app = this.state.app app.is_installed = true this.setState({app}) this.props.store.flagAppAsInstalled(app.short_name) this.props.store.setState({filter: 'installed', filterText: ''}) $.flashMessage(I18n.t('The app was added successfully')) page('/') } alreadyInstalled = () => { if (this.state.app.is_installed) { return <div className="gray-box-centered">{I18n.t('Installed')}</div> } } render() { if (!this.state.app) { return <img src="/images/ajax-loader-linear.gif" /> } return ( <div className="AppDetails"> <Header> <a href={`${this.props.baseUrl}/configurations`} className="btn view_tools_link lm pull-right" > {I18n.t('View App Configurations')} </a> <a href={this.props.baseUrl} className="btn view_tools_link lm pull-right"> {I18n.t('View App Center')} </a> </Header> <div className="app_full"> <table className="individual-app"> <tbody> <tr> <td className="individual-app-left" valign="top"> <div className="app"> <img className="img-polaroid" src={this.state.app.banner_image_url} /> {this.alreadyInstalled()} </div> <AddApp ref="addAppButton" app={this.state.app} handleToolInstalled={this.handleToolInstalled} /> <a href={this.props.baseUrl} className="app_cancel"> &laquo; {I18n.t('Back to App Center')} </a> </td> <td className="individual-app-right" valign="top"> <h2 ref="appName">{this.state.app.name}</h2> <p ref="appDescription" dangerouslySetInnerHTML={{__html: this.state.app.description}} /> </td> </tr> </tbody> </table> </div> </div> ) } }
src/icons/index.stories.js
resmio/mantecao
import React from 'react' import { storiesOf } from '@storybook/react' import AddIcon from './AddIcon' import ArrivedIcon from './ArrivedIcon' import ArrowIcon from './ArrowIcon' import BlankIcon from './BlankIcon' import BookIcon from './BookIcon' import BookingIcon from './BookingIcon' import CalendarIcon from './CalendarIcon' import CheckIcon from './CheckIcon' import CloseIcon from './CloseIcon' import CreditIcon from './CreditIcon' import DotDotDotIcon from './DotDotDotIcon' import EditIcon from './EditIcon' import EmailIcon from './EmailIcon' import ErrorIcon from './ErrorIcon' import EyeClosedIcon from './EyeClosedIcon' import FinishedIcon from './FinishedIcon' import GuestIcon from './GuestIcon' import GuestsIcon from './GuestsIcon' import InfoIcon from './InfoIcon' import LockedIcon from './LockedIcon' import NoteIcon from './NoteIcon' import PhoneIcon from './PhoneIcon' import ScheduledIcon from './ScheduledIcon' import SeatedIcon from './SeatedIcon' import SettingsIcon from './SettingsIcon' import SuccessIcon from './SuccessIcon' import ThumbIcon from './ThumbIcon' import TicketIcon from './TicketIcon' import TrashIcon from './TrashIcon' import UpgradeIcon from './UpgradeIcon' import WalkInIcon from './WalkInIcon' import WarningIcon from './WarningIcon' storiesOf('32 Icons', module).add('all icons', () => <div style={{ display: 'flex', flexWrap: 'wrap' }}> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>AddIcon</p> <AddIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>ArrivedIcon</p> <ArrivedIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>ArrowIcon</p> <ArrowIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>BlankIcon</p> <BlankIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>BookIcon</p> <BookIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>BookingIcon</p> <BookingIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>CalendarIcon</p> <CalendarIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>CheckIcon</p> <CheckIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>CloseIcon</p> <CloseIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>CreditIcon</p> <CreditIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>DotDotDotIcon</p> <DotDotDotIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>EditIcon</p> <EditIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>EmailIcon</p> <EmailIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>ErrorIcon</p> <ErrorIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>EyeClosedIcon</p> <EyeClosedIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>FinishedIcon</p> <FinishedIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>GuestIcon</p> <GuestIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>GuestsIcon</p> <GuestsIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>InfoIcon</p> <InfoIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>LockedIcon</p> <LockedIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>NoteIcon</p> <NoteIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>PhoneIcon</p> <PhoneIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>ScheduledIcon</p> <ScheduledIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>SeatedIcon</p> <SeatedIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>SettingsIcon</p> <SettingsIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>SuccessIcon</p> <SuccessIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>ThumbIcon</p> <ThumbIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>TicketIcon</p> <TicketIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>TrashIcon</p> <TrashIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>UpgradeIcon</p> <UpgradeIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>WalkInIcon</p> <WalkInIcon large /> </div> <div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}> <p>WarningIcon</p> <WarningIcon large /> </div> </div> )
src/components/shell/Shell.js
ipfs/webui
import React from 'react' import classNames from 'classnames' const Shell = ({ title = 'Shell', children, className }) => { return ( <div className={classNames('br1 overflow-hidden', className)}> <div className='f7 mb0 sans-serif ttu tracked charcoal pv1 pl2 bg-black-20'>{ title }</div> <div className='bg-black-70 snow pa2 f7 lh-copy monospace nowrap overflow-x-auto'> {children} </div> </div> ) } export default Shell
examples/with-clerk/pages/index.js
zeit/next.js
import React from 'react' import Head from 'next/head' import Link from 'next/link' import styles from '../styles/Home.module.css' import { SignedIn, SignedOut } from '@clerk/nextjs' const ClerkFeatures = () => ( <Link href="/user"> <a className={styles.cardContent}> <img src="/icons/layout.svg" /> <div> <h3>Explore features provided by Clerk</h3> <p> Interact with the user button, user profile, and more to preview what your users will see </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const SignupLink = () => ( <Link href="/sign-up"> <a className={styles.cardContent}> <img src="/icons/user-plus.svg" /> <div> <h3>Sign up for an account</h3> <p> Sign up and sign in to explore all the features provided by Clerk out-of-the-box </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const apiSample = `import { withSession } from '@clerk/nextjs/api' export default withSession((req, res) => { res.statusCode = 200 if (req.session) { res.json({ id: req.session.userId }) } else { res.json({ id: null }) } })` // Main component using <SignedIn> & <SignedOut>. // // The SignedIn and SignedOut components are used to control rendering depending // on whether or not a visitor is signed in. // // https://docs.clerk.dev/frontend/react/signedin-and-signedout const Main = () => ( <main className={styles.main}> <h1 className={styles.title}>Welcome to your new app</h1> <p className={styles.description}>Sign up for an account to get started</p> <div className={styles.cards}> <div className={styles.card}> <SignedIn> <ClerkFeatures /> </SignedIn> <SignedOut> <SignupLink /> </SignedOut> </div> <div className={styles.card}> <Link href="https://dashboard.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.cardContent}> <img src="/icons/settings.svg" /> <div> <h3>Configure settings for your app</h3> <p> Visit Clerk to manage instances and configure settings for user management, theme, and more </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> </div> </div> <APIRequest /> <div className={styles.links}> <Link href="https://docs.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read Clerk documentation</span> </a> </Link> <Link href="https://nextjs.org/docs"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read NextJS documentation</span> </a> </Link> </div> </main> ) const APIRequest = () => { React.useEffect(() => { if (window.Prism) { window.Prism.highlightAll() } }) const [response, setResponse] = React.useState( '// Click above to run the request' ) const makeRequest = async () => { setResponse('// Loading...') try { const res = await fetch('/api/getAuthenticatedUserId') const body = await res.json() setResponse(JSON.stringify(body, null, ' ')) } catch (e) { setResponse( '// There was an error with the request. Please contact [email protected]' ) } } return ( <div className={styles.backend}> <h2>API request example</h2> <div className={styles.card}> <button target="_blank" rel="noreferrer" className={styles.cardContent} onClick={() => makeRequest()} > <img src="/icons/server.svg" /> <div> <h3>fetch('/api/getAuthenticatedUserId')</h3> <p> Retrieve the user ID of the signed in user, or null if there is no user </p> </div> <div className={styles.arrow}> <img src="/icons/download.svg" /> </div> </button> </div> <h4> Response <em> <SignedIn> You are signed in, so the request will return your user ID </SignedIn> <SignedOut> You are signed out, so the request will return null </SignedOut> </em> </h4> <pre> <code className="language-js">{response}</code> </pre> <h4>pages/api/getAuthenticatedUserId.js</h4> <pre> <code className="language-js">{apiSample}</code> </pre> </div> ) } // Footer component const Footer = () => ( <footer className={styles.footer}> Powered by{' '} <a href="https://clerk.dev" target="_blank" rel="noopener noreferrer"> <img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} /> </a> + <a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer"> <img src="/nextjs.svg" alt="Next.js" className={styles.logo} /> </a> </footer> ) const Home = () => ( <div className={styles.container}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" ></meta> </Head> <Main /> <Footer /> </div> ) export default Home
src/components/GlobalNavigation/NavBar/BackButton.android.js
aaron-edwards/Spirit-Guide
import React from 'react'; import { I18nManager, Image, StyleSheet, TouchableNativeFeedback, View } from 'react-native' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; export default NavigationHeaderBackButton = (props: Props) => { return ( <TouchableNativeFeedback style={[styles.buttonContainer, props.style]} useForeground={true} background={TouchableNativeFeedback.Ripple('#FFFFFF', true)} onPress={props.onPress}> <View style={styles.buttonContainer}> <Icon style={styles.button} name="arrow-left" size={24} color="white" /> </View> </TouchableNativeFeedback> ); }; NavigationHeaderBackButton.propTypes = { onPress: React.PropTypes.func.isRequired }; const styles = StyleSheet.create({ buttonContainer: { borderRadius: 12, }, button: { borderRadius: 12, margin: 16, } });
modules/RouteUtils.js
calebmichaelsanchez/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
src/js/OrderSentPage.js
merlox/dapp-transactions
import React from 'react' import Header from './Header' import {Link} from 'react-router-dom' import './../stylus/index.styl' import './../stylus/ordersentpage.styl' import LINKS from './utils.js' class OrderSentPage extends React.Component { constructor(props) { super(props) } render(){ return ( <div style={{height: '100%'}}> <div className="order-sent-container"> <img src={LINKS.baseUrl + "img/order-sent/check-last.png"} /> <h1>Purchase Order Sent</h1> <div className="order-sent-buttons-container"> <Link to={LINKS.home} className="order-sent-back">Back to Login</Link> <Link to={LINKS.retailer} onClick={() => {this.props.hideRetailers()}} className="order-sent-login">Login as Wholesaler</Link> </div> </div> </div> ) } } export default OrderSentPage
src/routes/Home/components/TopicListing/TopicListing.js
spbsamuel/digg-clone
import React from 'react' import classes from './TopicListing.scss' import TopicCard from '../TopicCard' import Shuffle from 'react-shuffle' export const TopicListing = ({topics, visibleTopics, upVoteTopic, downVoteTopic}) => { return ( <div> <Shuffle> {visibleTopics.map(id => <div key={id}> <TopicCard key={id} {...topics[id]} voteUp={upVoteTopic(id)} voteDown={downVoteTopic(id)} /> </div> )} </Shuffle> </div> ) }; export default TopicListing
docs/src/examples/elements/Rail/Types/RailExampleDividing.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Grid, Image, Rail, Segment } from 'semantic-ui-react' const RailExampleDividing = () => ( <Grid centered columns={3}> <Grid.Column> <Segment> <Image src='/images/wireframe/paragraph.png' /> <Rail dividing position='left'> <Segment>Left Rail Content</Segment> </Rail> <Rail dividing position='right'> <Segment>Right Rail Content</Segment> </Rail> </Segment> </Grid.Column> </Grid> ) export default RailExampleDividing
examples/src/components/States.js
pedroseac/react-select
import React from 'react'; import Select from 'react-select'; const STATES = require('../data/states'); var StatesField = React.createClass({ displayName: 'StatesField', propTypes: { label: React.PropTypes.string, searchable: React.PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, selectValue: 'new-south-wales', clearable: true, }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { console.log('State changed to ' + newValue); this.setState({ selectValue: newValue }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var options = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Clearable</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } }); module.exports = StatesField;
examples/windows/components/navPane.js
gabrielbull/react-desktop
import React, { Component } from 'react'; import { NavPane, NavPaneItem, Text } from 'react-desktop/windows'; export default class extends Component { static defaultProps = { color: '#cc7f29', theme: 'light' }; constructor() { super(); this.state = { selected: 'Item 1' } } render() { return ( <NavPane openLength={200} push color={this.props.color} theme={this.props.theme}> {this.renderItem('Item 1', 'Content 1')} {this.renderItem('Item 2', 'Content 2')} {this.renderItem('Item 3', 'Content 3')} </NavPane> ); } renderItem(title, content) { return ( <NavPaneItem title={title} icon={this.renderIcon(title)} theme="light" background="#ffffff" selected={this.state.selected === title} onSelect={() => this.setState({ selected: title })} padding="10px 20px" push > <Text>{content}</Text> </NavPaneItem> ); } renderIcon(name) { const fill = this.props.theme === 'dark' ? '#ffffff' : '#000000'; switch(name) { case 'Item 1': return ( <svg x="0px" y="0px" width="16px" height="14.9px" viewBox="0 0 16 14.9"> <polygon fill={fill} points="16,5.6 10.6,4.7 8,0 5.4,4.7 0,5.7 3.8,9.6 3.1,14.9 8,12.6 13,14.8 12.3,9.5 "/> </svg> ); case 'Item 2': return ( <svg x="0px" y="0px" width="16px" height="13.5px" viewBox="0 0 16 13.5"> <path fill={fill} d="M16,4.2C16,1.9,14.1,0,11.7,0c-1.4,0-2.6,0.6-3.4,1.6c0,0,0,0,0,0C8.3,1.7,8.1,1.8,8,1.8 c-0.2,0-0.3-0.1-0.4-0.2c0,0,0,0,0,0C6.8,0.6,5.6,0,4.3,0C1.9,0,0,1.9,0,4.2c0,0,0,0.1,0,0.1l0,0c0,0,0,0.1,0,0.3 C0,4.8,0.1,5,0.1,5.2c0.3,1.4,1.4,4.1,5.1,6.5c2.1,1.4,2.6,1.8,2.8,1.8c0,0,0,0,0,0c0,0,0,0,0,0c0.1,0,0.7-0.4,2.8-1.8 c3.5-2.3,4.6-4.8,5-6.3C15.9,5.1,16,4.8,16,4.5C16,4.3,16,4.2,16,4.2L16,4.2C16,4.2,16,4.2,16,4.2z" /> </svg> ); case 'Item 3': return ( <svg x="0px" y="0px" width="16px" height="15.6px" viewBox="0 0 16 15.6"> <path fill={fill} d="M14.9,3.2c0.7-0.9,1-1.7,1.1-2.4c0-0.2,0-0.4-0.1-0.5c0,0,0-0.1-0.1-0.1c0,0-0.1-0.1-0.1-0.1 C15.6,0,15.4,0,15.2,0c-0.7,0-1.6,0.4-2.4,1c-0.7,0.5-1.4,1.2-2.4,2.3C10.2,3.5,10,3.6,9.8,3.8L8.3,3.4L7.9,3.3C8,3.2,8.1,3.1,8.1,3 c0-0.1,0-0.2-0.1-0.3L7.6,2.3C7.5,2.3,7.4,2.2,7.3,2.2c-0.1,0-0.2,0-0.3,0.1L6.5,2.8L6.2,2.8c0.1-0.1,0.1-0.2,0.1-0.3 c0-0.1,0-0.2-0.1-0.3L5.8,1.9C5.7,1.8,5.6,1.8,5.5,1.8c-0.1,0-0.2,0-0.3,0.1L4.7,2.3L2.8,1.8c0,0-0.1,0-0.1,0 c-0.1,0-0.3,0.1-0.4,0.1L1.6,2.6C1.5,2.6,1.5,2.7,1.5,2.8c0,0.1,0.1,0.3,0.2,0.3l4.1,2.2c0,0,0.1,0.1,0.1,0.1L7,6.6 C6,7.7,5,8.8,4.2,9.7C4.2,9.8,4.1,9.9,4,10L0.9,9.7c0,0,0,0-0.1,0c-0.1,0-0.3,0.1-0.4,0.2l-0.3,0.3C0,10.3,0,10.4,0,10.5 c0,0.1,0.1,0.3,0.2,0.3l2.2,1c0,0,0.1,0,0.1,0.1l0.2,0.2c-0.1,0.2-0.1,0.3-0.1,0.4c0,0.2,0.1,0.3,0.2,0.4C2.9,13,3,13.1,3.2,13.1 c0.1,0,0.3,0,0.4-0.1l0.2,0.2c0,0,0,0.1,0.1,0.1l1.1,2.2c0.1,0.1,0.2,0.2,0.4,0.2c0.1,0,0.2,0,0.3-0.1l0.3-0.3C6,15.1,6,14.9,6,14.8 c0,0-0.3-3.1-0.3-3.1c0.1-0.1,0.2-0.1,0.3-0.2c1-0.7,2.1-1.7,3.2-2.7l1.2,1.1c0,0,0.1,0.1,0.1,0.1l2.3,4c0.1,0.1,0.2,0.2,0.3,0.2 c0.1,0,0.2,0,0.3-0.1l0.7-0.7c0.1-0.1,0.1-0.2,0.1-0.3c0,0,0-0.1,0-0.1l-0.5-1.8L13.6,11l0.5-0.4c0.1-0.1,0.1-0.2,0.1-0.3 c0-0.1,0-0.2-0.1-0.3l-0.3-0.3c-0.1-0.1-0.2-0.1-0.3-0.1c-0.1,0-0.2,0-0.3,0.1l-0.1-0.3l0.5-0.5c0.1-0.1,0.1-0.2,0.1-0.3 c0-0.1,0-0.2-0.1-0.3l-0.3-0.3c-0.1-0.1-0.2-0.1-0.3-0.1c-0.1,0-0.2,0-0.3,0.1L12.1,6c0.2-0.2,0.4-0.4,0.6-0.5 C13.7,4.5,14.4,3.8,14.9,3.2z" /> </svg> ); } } }
spec/javascripts/jsx/grading/AssignmentPostingPolicyTray/AssignmentPostingPolicyTraySpec.js
djbender/canvas-lms
/* * Copyright (C) 2019 - 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 ReactDOM from 'react-dom' import {waitForElement, wait} from '@testing-library/react' import AssignmentPostingPolicyTray from 'jsx/grading/AssignmentPostingPolicyTray' import * as Api from 'jsx/grading/AssignmentPostingPolicyTray/Api' import * as FlashAlert from 'jsx/shared/FlashAlert' QUnit.module('AssignmentPostingPolicyTray', suiteHooks => { let $container let context let tray suiteHooks.beforeEach(() => { $container = document.body.appendChild(document.createElement('div')) context = { assignment: { id: '2301', name: 'Math 1.1', postManually: false }, onAssignmentPostPolicyUpdated: sinon.spy(), onExited: sinon.spy() } const bindRef = ref => { tray = ref } ReactDOM.render(<AssignmentPostingPolicyTray ref={bindRef} />, $container) }) suiteHooks.afterEach(async () => { if (getTrayElement()) { getCloseButton().click() await waitForTrayClosed() } ReactDOM.unmountComponentAtNode($container) $container.remove() }) function getTrayElement() { return document.querySelector('[role="dialog"][aria-label="Grade posting policy tray"]') } function getCancelButton() { const $tray = getTrayElement() return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Cancel') } function getCloseButton() { const $tray = getTrayElement() return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Close') } function getSaveButton() { const $tray = getTrayElement() return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Save') } function getLabel(text) { const $tray = getTrayElement() return [...$tray.querySelectorAll('label')].find($label => $label.textContent.includes(text)) } function getInputByLabel(label) { const $label = getLabel(label) if ($label === undefined) return undefined return document.getElementById($label.htmlFor) } function show() { tray.show(context) return waitForElement(getTrayElement) } function waitForTrayClosed() { return wait(() => { if (context.onExited.callCount > 0) { return } throw new Error('Tray is still open') }) } QUnit.module('#show()', () => { test('opens the tray', async () => { await show() ok(getTrayElement()) }) test('includes the name of the assignment', async () => { await show() const heading = getTrayElement().querySelector('h2') equal(heading.textContent, 'Grade Posting Policy: Math 1.1') }) test('disables the "Automatically" input for an anonymous assignment', async () => { context.assignment.anonymousGrading = true await show() strictEqual(getInputByLabel('Automatically').disabled, true) }) QUnit.module('when the assignment is moderated', hooks => { hooks.beforeEach(() => { context.assignment.moderatedGrading = true }) test('disables the "Automatically" input when grades are not published', async () => { context.assignment.gradesPublished = false await show() strictEqual(getInputByLabel('Automatically').disabled, true) }) test('enables the "Automatically" input when grades are published', async () => { context.assignment.gradesPublished = true await show() strictEqual(getInputByLabel('Automatically').disabled, false) }) test('always disables the "Automatically" input when the assignment is anonymous', async () => { context.assignment.anonymousGrading = true context.assignment.gradesPublished = true await show() strictEqual(getInputByLabel('Automatically').disabled, true) }) }) test('enables the "Automatically" input if the assignment is not anonymous or moderated', async () => { await show() strictEqual(getInputByLabel('Automatically').disabled, false) }) test('the "Automatically" input is initally selected if an auto-posted assignment is passed', async () => { await show() strictEqual(getInputByLabel('Automatically').checked, true) }) test('the "Manually" input is initially selected if a manual-posted assignment is passed', async () => { context.assignment.postManually = true await show() strictEqual(getInputByLabel('Manually').checked, true) }) test('enables the "Save" button if the postManually value has changed and no request is in progress', async () => { await show() getInputByLabel('Manually').click() strictEqual(getSaveButton().disabled, false) }) test('disables the "Save" button if the postManually value has not changed', async () => { await show() getInputByLabel('Manually').click() getInputByLabel('Automatically').click() strictEqual(getSaveButton().disabled, true) }) test('disables the "Save" button if a request is already in progress', async () => { let resolveRequest const setAssignmentPostPolicyStub = sinon.stub(Api, 'setAssignmentPostPolicy').returns( new Promise(resolve => { resolveRequest = () => { resolve({assignmnentId: '2301', postManually: true}) } }) ) await show() getInputByLabel('Manually').click() getSaveButton().click() strictEqual(getSaveButton().disabled, true) resolveRequest() setAssignmentPostPolicyStub.restore() }) }) QUnit.module('"Close" Button', hooks => { hooks.beforeEach(show) test('closes the tray', async () => { getCloseButton().click() await waitForTrayClosed() notOk(getTrayElement()) }) }) QUnit.module('"Cancel" button', hooks => { hooks.beforeEach(show) test('closes the tray', async () => { getCancelButton().click() await waitForTrayClosed() notOk(getTrayElement()) }) test('is enabled when no request is in progress', () => { strictEqual(getCancelButton().disabled, false) }) test('is disabled when a request is in progress', () => { let resolveRequest const setAssignmentPostPolicyStub = sinon.stub(Api, 'setAssignmentPostPolicy').returns( new Promise(resolve => { resolveRequest = () => { resolve({assignmnentId: '2301', postManually: true}) } }) ) getInputByLabel('Manually').click() getSaveButton().click() strictEqual(getCancelButton().disabled, true) resolveRequest() setAssignmentPostPolicyStub.restore() }) }) QUnit.module('"Save" button', hooks => { let setAssignmentPostPolicyStub let showFlashAlertStub hooks.beforeEach(() => { return show().then(() => { getInputByLabel('Manually').click() showFlashAlertStub = sinon.stub(FlashAlert, 'showFlashAlert') setAssignmentPostPolicyStub = sinon .stub(Api, 'setAssignmentPostPolicy') .resolves({assignmentId: '2301', postManually: true}) }) }) hooks.afterEach(() => { FlashAlert.destroyContainer() setAssignmentPostPolicyStub.restore() showFlashAlertStub.restore() }) test('calls setAssignmentPostPolicy', () => { getSaveButton().click() strictEqual(setAssignmentPostPolicyStub.callCount, 1) }) test('passes the assignment ID to setAssignmentPostPolicy', () => { getSaveButton().click() strictEqual(setAssignmentPostPolicyStub.firstCall.args[0].assignmentId, '2301') }) test('passes the selected postManually value to setAssignmentPostPolicy', () => { getSaveButton().click() strictEqual(setAssignmentPostPolicyStub.firstCall.args[0].postManually, true) }) QUnit.module('on success', () => { const waitForSuccess = async () => { await wait(() => getTrayElement() == null) } test('renders a success alert', async () => { getSaveButton().click() await waitForSuccess() strictEqual(showFlashAlertStub.callCount, 1) }) test('the rendered alert includes a message referencing the assignment', async () => { getSaveButton().click() await waitForSuccess() const message = 'Success! The post policy for Math 1.1 has been updated.' strictEqual(showFlashAlertStub.firstCall.args[0].message, message) }) test('calls the provided onAssignmentPostPolicyUpdated function', async () => { getSaveButton().click() await waitForSuccess() strictEqual(context.onAssignmentPostPolicyUpdated.callCount, 1) }) test('passes the assignmentId to onAssignmentPostPolicyUpdated', async () => { getSaveButton().click() await waitForSuccess() strictEqual(context.onAssignmentPostPolicyUpdated.firstCall.args[0].assignmentId, '2301') }) test('passes the postManually value to onAssignmentPostPolicyUpdated', async () => { getSaveButton().click() await waitForSuccess() strictEqual(context.onAssignmentPostPolicyUpdated.firstCall.args[0].postManually, true) }) }) QUnit.module('on failure', failureHooks => { const waitForFailure = async () => { await wait(() => FlashAlert.showFlashAlert.callCount > 0) } failureHooks.beforeEach(() => { setAssignmentPostPolicyStub.rejects({error: 'oh no'}) }) test('renders an error alert', async () => { getSaveButton().click() await waitForFailure() strictEqual(showFlashAlertStub.callCount, 1) }) test('the rendered error alert contains a message', async () => { getSaveButton().click() await waitForFailure() const message = 'An error occurred while saving the assignment post policy' strictEqual(showFlashAlertStub.firstCall.args[0].message, message) }) test('the tray remains open', async () => { getSaveButton().click() await waitForFailure() ok(getTrayElement()) }) }) }) })
src/index.js
zumbara/zumbara-web
// @flow import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import createHistory from 'history/createBrowserHistory'; import { injectGlobal } from 'styled-components'; import 'normalize.css/normalize.css'; import configureStore from './redux/configureStore'; import registerServiceWorker from './registerServiceWorker'; import App from './App'; const history = createHistory(); const store = configureStore(undefined, history); // eslint-disable-next-line injectGlobal` body { margin: 0; padding: 0; background: #efefef; font-family: 'Source Sans Pro', sans-serif; color: #555; font-size: 16px; line-height: 1.5; } `; const render = Component => { ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <Component /> </ConnectedRouter> </Provider>, document.getElementById('root'), ); }; /* istanbul ignore if */ if (process.env.NODE_ENV === 'development' && module.hot) { module.hot.accept('./App', () => { // eslint-disable-next-line const NextApp = require('./App').default; render(NextApp); }); } render(App); registerServiceWorker();
src/Button.story.js
prometheusresearch/react-ui
/** * @flow */ import React from 'react'; import {storiesOf} from '@kadira/storybook'; import Button from './Button'; import I18N from './I18N'; export function createButtonStories(Button: any) { storiesOf(`<${Button.displayName || Button.name} />`, module) .add('Default state', () => <Button>Click me</Button>) .add('Size: x-small', () => <Button size="x-small">Click me</Button>) .add('Size: small', () => <Button size="small">Click me</Button>) .add('Size: normal', () => <Button size="normal">Click me</Button>) .add('Size: large', () => <Button size="large">Click me</Button>) .add('With icon', () => <Button icon="+">Add</Button>) .add('With icon (rtl)', () => ( <I18N dir="rtl"> <Button icon="+">Add</Button> </I18N> )) .add('With icon only', () => <Button icon="+" />) .add('With icon (alternative)', () => <Button iconAlt="+">Add</Button>) .add('With icon (alternative, rtl)', () => ( <I18N dir="rtl"> <Button iconAlt="+">Add</Button> </I18N> )) .add('Grouped horizontally', () => ( <div> <Button groupHorizontally>Add</Button> <Button groupHorizontally>No op</Button> <Button groupHorizontally>Remove</Button> </div> )) .add('Grouped horizontally (rtl)', () => ( <I18N dir="rtl"> <div> <Button groupHorizontally>Add</Button> <Button groupHorizontally>No op</Button> <Button groupHorizontally>Remove</Button> </div> </I18N> )) .add('Grouped vertically', () => ( <div style={{display: 'flex', flexDirection: 'column'}}> <Button groupVertically>Add</Button> <Button groupVertically>No op</Button> <Button groupVertically>Remove</Button> </div> )); } createButtonStories(Button);
src/svg-icons/navigation/arrow-downward.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDownward = (props) => ( <SvgIcon {...props}> <path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/> </SvgIcon> ); NavigationArrowDownward = pure(NavigationArrowDownward); NavigationArrowDownward.displayName = 'NavigationArrowDownward'; NavigationArrowDownward.muiName = 'SvgIcon'; export default NavigationArrowDownward;
src/page/TimePickerPage.js
jerryshew/react-uikits
import React, { Component } from 'react'; import {CN, TitleBlock} from '../util/tools'; import {TimePicker} from '../component'; import CodeView from './CodeView'; export class TimePickerPage extends Component { constructor(props) { super(props); this.state = { value: 4981 } } handleTimeChange(value){ this.setState({ value }); } render() { return ( <section> {TitleBlock('时间选择')} <h4>默认时间选择</h4> <CodeView component={<TimePicker onChange={value => {}} />}> {`<TimePicker onChange={onChangeFunction} />`} </CodeView> <br/> <h4>带默认值的时间选择</h4> <CodeView component={<TimePicker value={12217} onChange={value => {}} />}> {`<TimePicker value={12217} onChange={onChangeFunction} />`} </CodeView> <br/> <h4>onChange 事件</h4> <CodeView component={ <div> <p>选择的时间秒数为 {this.state.value}</p> <TimePicker value={this.state.value} onChange={this.handleTimeChange.bind(this)} /> </div> }> {`<TimePicker value={4981} onChange={onChangeFunction} />`} </CodeView> <br/> <h4>简单的时间选择</h4> <CodeView component={<TimePicker simple={true} onChange={value => {}} />}> {`<TimePicker simple={true} onChange={onChangeFunction} />`} </CodeView> <br/> <h4>时间选择位置</h4> <CodeView component={<div> <TimePicker position="top" onChange={value => {}}/> </div>}> {`<TimePicker position="top" onChange={onChangeFunction}/>`} </CodeView> <br/> <h4>属性</h4> <table className="dot table"> <thead> <tr> <th>名称</th> <th>描述</th> <th>类型</th> <th>默认值</th> <th>required</th> </tr> </thead> <tbody> <tr> <td>value</td> <td>值(秒数 0 ~ 86399)</td> <td>整形(例如:4981 代表 '03:23:37')</td> <td>0</td> <td>否</td> </tr> <tr> <td>simple</td> <td>简洁版</td> <td>Boolean</td> <td>false</td> <td>否</td> </tr> <tr> <td>position</td> <td>展开位置</td> <td>'top', 'bottom' 中的一个</td> <td>bottom</td> <td>否</td> </tr> <tr> <td>onChange</td> <td>时间变化触发事件</td> <td>函数(时间字符串)</td> <td> {`onChange(time){ }`} </td> <td>是</td> </tr> </tbody> </table> </section> ); } }
examples/custom-grid/src/index.js
Hellenic/react-hexgrid
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/addons/documents/mango/components/ExecutionStats.js
popojargo/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import PropTypes from 'prop-types'; import { Popover, OverlayTrigger } from 'react-bootstrap'; const TOO_MANY_DOCS_SCANNED_WARNING = "The number of documents examined is high in proportion to the number of results returned. Consider adding an index to improve this."; export default class ExecutionStats extends React.Component { constructor (props) { super(props); } humanizeDuration(milliseconds) { if (milliseconds < 1000) { return Math.round(milliseconds) + ' ms'; } let seconds = milliseconds / 1000; if (seconds < 60) { return Math.floor(seconds) + ' seconds'; } const minutes = Math.floor(seconds / 60); seconds = seconds - (minutes * 60); return minutes + 'minute, ' + seconds + 'seconds'; } getWarning(executionStats, warning) { if (!executionStats) { return warning; } // warn if many documents scanned in relation to results returned if (!warning && executionStats.results_returned) { const docsExamined = executionStats.total_docs_examined || executionStats.total_quorum_docs_examined; if (docsExamined / executionStats.results_returned > 10) { return TOO_MANY_DOCS_SCANNED_WARNING; } } return warning; } warningPopupComponent(warningText) { if (!!warningText) { return (<div className="warning"> <i className="fonticon-attention-circled"></i> {warningText} </div>); } } executionStatsLine(title, value, alwaysShow = false, units = "") { const hasValue = value === 0 && !alwaysShow ? "false" : "true"; return <div data-status={hasValue}>{title + ": "}<span className="value">{value.toLocaleString()} {units}</span></div>; } executionStatsPopupComponent(executionStats) { if (!executionStats) return null; return ( <div className="execution-stats-popup-component"> {/* keys examined always 0 so hide it for now */} {/* {this.executionStatsLine("keys examined", executionStats.total_keys_examined)} */} {this.executionStatsLine("documents examined", executionStats.total_docs_examined)} {this.executionStatsLine("documents examined (quorum)", executionStats.total_quorum_docs_examined)} {this.executionStatsLine("results returned", executionStats.results_returned, true)} {this.executionStatsLine("execution time", executionStats.execution_time_ms, false, "ms")} </div> ); } popup(executionStats, warningText) { return ( <Popover id="popover-execution-stats" title="Execution Statistics"> <div className="execution-stats-popup"> {this.executionStatsPopupComponent(executionStats)} {this.warningPopupComponent(warningText)} </div> </Popover> ); } render() { const { executionStats, warning } = this.props; const warningText = this.getWarning(executionStats, warning); let warningComponent = null; if (!!warningText) { warningComponent = <i className="fonticon-attention-circled"></i>; } let executionStatsComponent = null; if (executionStats) { executionStatsComponent = ( <span className="execution-stats-component">Executed in {this.humanizeDuration(executionStats.execution_time_ms)}</span> ); } else if (!!warningText) { executionStatsComponent = ( <span className="execution-stats-component">Warning</span> ); } const popup = this.popup(executionStats, warningText); return ( <OverlayTrigger trigger={['hover', 'focus', 'click']} placement="right" overlay={popup}> <span className="execution-stats"> {warningComponent} {executionStatsComponent} </span> </OverlayTrigger> ); } }; ExecutionStats.propTypes = { executionStats: PropTypes.object, warning: PropTypes.string };
web/assets/js/detailpage-need-to-integrate/CarDetail.js
xuqiantong/NY_Auto
/** * Created by jeanliu on 4/14/17. */ import React, { Component } from 'react'; import './CarDetail2.css'; var Row = require('react-bootstrap/lib/Row'); var Col = require('react-bootstrap/lib/Col'); var Button = require('react-bootstrap/lib/Button'); // const PHOTOS = [ // {id: 0, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-01.jpeg'}, // {id: 1, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-02.jpeg'}, // {id: 2, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-03.jpeg'}, // {id: 3, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-04.jpeg'}, // {id: 4, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-05.jpeg'}, // {id: 6, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-06.jpeg'}, // {id: 7, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-07.jpeg'}, // {id: 8, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-08.jpeg'}, // {id: 9, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-09.jpeg'} // ]; function BannerDivider(props) { return ( <Row > <Col md={10} mdPush={1} className="banner-divider"></Col> </Row> ); } class CarPhotoBanner extends Component { constructor(props) { super(props); this.state = {photoIndex: 0}; this.getPrevPhoto = this.getPrevPhoto.bind(this); this.getNextPhoto = this.getNextPhoto.bind(this); } getPrevPhoto(e) { console.log("get prev photo"); if (this.state.photoIndex != 0) { this.setState({ photoIndex: (this.state.photoIndex - 1) }); } } getNextPhoto(e) { console.log("get next photo"); if (this.state.photoIndex != PHOTOS.length-1) { this.setState({ photoIndex: (this.state.photoIndex + 1) }); } } render() { const photos = this.props.photos; var Background = photos[this.state.photoIndex]; var sectionStyle = { backgroundImage: "url(" + Background + ")", backgroundSize: "cover", backgroundPositionY: "50%" }; return ( <Row id="car-photo-banner"> <Col md={12} id="car-photo" className="car-photo-item" style={sectionStyle}> <Row className="btn-wrapper"> <Col md={1} className="car-img-btn img-prev" onClick={this.getPrevPhoto}> <span className="arrow left leftarrow"></span> </Col> <Col md={1} className="car-img-btn img-next" onClick={this.getNextPhoto}> <span className="arrow right rightarrow"></span> </Col> </Row> </Col> </Row> ); } } function PriceBanner(props) { //const car = props.car; const title = props.title; const price = props.price; const mileage = props.mileage; return ( <Row className="price-banner-wrapper"> <Col md={12} className="price-banner"> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} className="banner-title"> {title} </Col> </Row> <Row> <Col md={3} mdPush={1} sm={3} smPush={1} xs={4} id="car-price" className="price-banner-text"> <span className="item-title">Price</span> <span className="item-content">$ {price}</span> </Col> <Col md={4} mdPush={1} sm={4} smPush={1} xs={4} id="car-mileage" className="price-banner-text"> <span className="item-title">Mileage</span> <span className="item-content">{mileage} mi</span> </Col> <Col md={5} sm={5} xs={12} id="car-mileage" className="price-banner-text btn-area"> <Col md={6} sm={6} xs={6}> <Button bsStyle="primary" className="submit-btn" >View CARFAX</Button> </Col> <Col md={6} sm={6} xs={6}> <Button bsStyle="primary" className="submit-btn" >Make An Offer</Button> </Col> </Col> </Row> </Col> </Row> ); } function ProfileBanner(props) { const doors = props.doors; const drive = props.drive; return ( <Row className="profile-banner-wrapper"> <Row> <Col md={9} mdPush={1} className="profile-banner"> <Col md={2} sm={2} xs={3} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/door.png" className="profile-icon"/> <div className="profile-text">{doors} Doors</div> </Col> <Col md={2} sm={2} xs={3} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/passengers.png" className="profile-icon"/> <div className="profile-text">5 Passengers</div> </Col> <Col md={2} sm={2} xs={3} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/gearbox.png" className="profile-icon"/> <div className="profile-text">Automatic</div> </Col> <Col md={2} sm={2} xs={3} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/cogwheel-outline.png" className="profile-icon"/> <div className="profile-text">{drive}</div> </Col> </Col> <Col md={2} smHidden xsHidden className="share-btn disappear-in-md"> <Button bsStyle="primary" className="submit-btn" >Share</Button> </Col> </Row> <Row className="sm-screen-btn-row"> <Col sm={2} smPush={5} xs={4} xsPush={4}> <Button bsStyle="primary" className="submit-btn">Share</Button> </Col> </Row> </Row> ); } function ColorBanner(props) { const color_ext = props.color_ext; const color_int = props.color_int; var ExtBg = "#ffffff"; var IntBg = "#ddd9c5"; var extStyle = { backgroundColor: color_ext, }; var intStyle = { backgroundColor: color_int, }; return( <Row className="color-banner-wrapper"> <Col md={12}> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Color</Col> </Row> <Row> <Col md={10} mdPush={1} sm={10} smPush={1} xs={12} className="color-banner"> <Row className="color-items-wrapper"> <Col md={6} sm={6} xs={6}> <div className="color-circle" style={extStyle}></div> <div className="color-text-wrapper"> <div className="color-title">Exterior:</div> <div className="color-content">{color_ext}</div> </div> </Col> <Col md={6} sm={6} xs={6}> <div className="color-circle" style={intStyle}></div> <div className="color-text-wrapper"> <div className="color-title">Interior:</div> <div className="color-content">{color_int}</div> </div> </Col> </Row> </Col> </Row> </Col> </Row> ); } function PkgBanner(props) { return ( <Row className="pkg-banner-wrapper"> <Col md={12}> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Featured Packages</Col> </Row> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} className="pkg-items-wrapper"> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/bluetooth.png" className="pkg-icon"/> <div className="profile-text">Bluetooth</div> </Col> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/keyless.png" className="pkg-icon"/> <div className="profile-text">Keyless Entry</div> </Col> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/start.png" className="pkg-icon"/> <div className="profile-text">Keyless Start</div> </Col> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/aux.png" className="pkg-icon"/> <div className="profile-text">Aux</div> </Col> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/leather_seats.png" className="pkg-icon"/> <div className="profile-text">Leather Seats</div> </Col> <Col md={1} sm={1} xs={2} className="profile-item"> <img src="./static/bundles/images/detailpage/icons/heated_seats.png" className="pkg-icon"/> <div className="profile-text">Heated Seats</div> </Col> </Col> </Row> </Col> </Row> ); } function PerfBanner(props) { return ( <Row className="perf-banner-wrapper"> <Col md={12}> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Performance</Col> </Row> <Row> <Col md={11} mdPush={1} sm={11} smPush={1} xs={12}> <Col md={6} sm={6} xs={6} className="perf-left-col"> <Row className="perf-row"> <Col md={5} className="perf-info-key">Horsepower: </Col> <Col md={7} className="perf-info-value">320 hp</Col> </Row> <Row className="perf-row"> <Col md={5} className="perf-info-key">Displacement: </Col> <Col md={7} className="perf-info-value">2.0 L</Col> </Row> <Row className="perf-row"> <Col md={5} className="perf-info-key">Fuel-type: </Col> <Col md={7} className="perf-info-value">Gasoline</Col> </Row> </Col> <Col md={6} sm={6} xs={6} className="perf-right-col"> <Row className="perf-row"> <Col md={5} className="perf-info-key">Torque: </Col> <Col md={7} className="perf-info-value">200 lb-ft</Col> </Row> <Row className="perf-row"> <Col md={5} className="perf-info-key">Cylinder: </Col> <Col md={7} className="perf-info-value">4</Col> </Row> <Row className="perf-row"> <Col md={5} className="perf-info-key">Compressor Type: </Col> <Col md={7} className="perf-info-value">Turbo-charged</Col> </Row> </Col> </Col> </Row> </Col> </Row> ); } export default class CarDetail extends Component { // static propTypes = { // pages: PropTypes.array, // active_page_slug: PropTypes.string, // } // static contextTypes = { // router: PropTypes.object.isRequired, // store: PropTypes.object.isRequired // }; // activateAndLoadPage = (e) => { // e.preventDefault(); // let slug = e.target.dataset.slug; // this.context.router.transitionTo('/page/' + slug); // } constructor(props) { super(props); this.state = { vehicle: null, images: [], title: null, price: 0, mileage: 0, drive: null, color_ext: null, color_int: null, featured_packages: [], in_stock_time: null, location: null, handler: null, carfaxPath: null, interior_type: null, top_type: null, body_type: null, fuel: null, transmission: null, engine: null, owner_num: null, condition: null, min_price: null, trim: null, status: null, vin: null }; } componentWillMount() { var vehicle_id = window.location.href.split("/").pop().substring(6); var vehicle_url = "/api/vehicle/" + vehicle_id; var image_url = "/api/has_image/"; $.ajax({ url: vehicle_url, datatype: 'json', cache: false, success: function(vehicle) { const title = vehicle.year + " " + vehicle.make + " " + vehicle.model; const price = vehicle.list_price; const mileage = vehicle.mileage; const doors = vehicle.door; const drive = vehicle.drive; const color_ext = vehicle.color_ext; const color_int = vehicle.color_int; const in_stock_time = vehicle.in_stock_time; const location = vehicle.location; const handler = vehicle.handler; const carfaxPath = vehicle.carfaxPath; const interior_type = vehicle.interior_type; const top_type = vehicle.top_type; const body_type = vehicle.body_type; const fuel = vehicle.fuel; const transmission = vehicle.transmission; const engine = vehicle.engine; const owner_num = vehicle.owner_num; const condition = vehicle.condition; const min_price = vehicle.min_price; const trim = vehicle.trim; const status = vehicle.status; const vin = vehicle.vin; var featuredPackages = []; for(var attribute in vehicle) { if(attribute.substring(0,3) == "es_" || attribute.substring(0,3) == "ep_" || attribute.substring(0,3) == "eb_") { if(vehicle[attribute] == true) { featuredPackages.push(attribute); } } } this.setState({ vehicle: vehicle, title: title, price: price, mileage: mileage, doors: doors, drive: drive, color_ext: color_ext, color_int: color_int, featured_packages: featuredPackages, in_stock_time: in_stock_time, location: location, handler: handler, carfaxPath: carfaxPath, interior_type: interior_type, top_type: top_type, body_type: body_type, fuel: fuel, transmission: transmission, engine: engine, owner_num: owner_num, condition: condition, min_price: min_price, trim: trim, status: status, vin: vin }); }.bind(this) }) $.ajax({ url: image_url, datatype: 'json', cache: false, success: function(image_list) { for(var image in image_list) { if(image_list[image].vehicle == vehicle_id) { var images = this.state.images; images.push(image_list[image].image); this.setState({images: images}) } } }.bind(this) }) } render() { console.log(this.state); return ( <div id="car-detail"> <CarPhotoBanner photos={this.state.images} /> <PriceBanner title={this.state.title} price={this.state.price} mileage={this.state.mileage} /> <ProfileBanner doors={this.state.doors} drive={this.state.drive} /> <BannerDivider /> <ColorBanner color_ext={this.state.color_ext} color_int={this.state.color_int} /> <BannerDivider /> <PkgBanner /> <BannerDivider /> <PerfBanner /> </div> ); } }
app/components/Icon.js
nmorel/magic-counter
import React from 'react'; import {StyleSheet, Text} from 'react-native'; export const icons = { new: convertFontCode('e05e'), addPlayer: convertFontCode('e7f0'), reset: convertFontCode('e042'), menu: convertFontCode('e3c7'), add: convertFontCode('e147'), remove: convertFontCode('e15c'), }; function convertFontCode(code) { return String.fromCharCode(parseInt(code, 16)); } export function Icon({icon, style}) { return <Text style={[styles.icon, style]}>{icon}</Text>; } const styles = StyleSheet.create({ icon: { fontFamily: 'icomoon', }, });
src/examples/react/src/editors/InputPet.js
nikospara/egkyron
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Pet from 'model/Pet'; import Vaccination from 'model/Vaccination'; import InputText from 'controls/InputText'; import InputGender from './InputGender'; import InputArray from './InputArray'; import InputVaccination from './InputVaccination'; import { attachInput, simpleShouldComponentUpdate } from 'controls/utils'; import Form from 'react-bootstrap/Form'; import Col from 'react-bootstrap/Col'; import uuid from 'uuid'; const GENDER_OPTIONS = [ { id: 'M', label: 'Male' }, { id: 'F', label: 'Female' } ]; export default class InputPet extends Component { _handlers = { addVaccination: null }; constructor(props) { super(props); this.state = { value: props.value || new Pet() }; this._handlers.addVaccination = this.addVaccination.bind(this); } handleChange(field, value) { var newValue = new Pet(this.state.value); newValue[field] = value; this.setState({ value: newValue }); this.props.onChange && this.props.onChange(newValue); } addVaccination() { return new Vaccination({id: uuid.v4()}); } shouldComponentUpdate(nextProps, nextState) { return simpleShouldComponentUpdate.call(this, nextProps, nextState); } render() { return ( <Form.Row> {this.props.label ? <legend>{this.props.label}</legend> : null} <Col sm={5}> <InputText label="Name" {...attachInput(this, 'name')} /> </Col> <Col sm={5}> <InputText label="Type" {...attachInput(this, 'type')} /> </Col> <Col sm={2}> <InputGender label="Gender" {...attachInput(this, 'gender')} options={GENDER_OPTIONS} /> </Col> <Col sm={12}> <InputArray label="Vaccinations" {...attachInput(this, 'vaccinations')} innerComponent={InputVaccination} add={this._handlers.addVaccination} addLabel="Add vaccination" removeLabel="Remove vaccination" /> </Col> </Form.Row> ); } } InputPet.propTypes = { value: PropTypes.instanceOf(Pet), onChange: PropTypes.func, label: PropTypes.string, validity: PropTypes.object };
src/components/google_map.js
CaseyKelly/react-redux-weather-charts
import React, { Component } from 'react'; class GoogleMap extends Component { componentDidMount() { new google.maps.Map(this.refs.map, { zoom: 12, center: { lat: this.props.lat, lng: this.props.lon } }); } render() { return <div ref="map" />; } } export default GoogleMap;
example/src/client.js
tizmagik/react-head
import React from 'react'; import { hydrate } from 'react-dom'; import { HeadProvider } from 'react-head'; import App from '../App'; hydrate( <HeadProvider> <App /> </HeadProvider>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
packages/react-devtools-shared/src/devtools/views/ReactLogo.js
mjackson/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 styles from './ReactLogo.css'; type Props = {| className?: string, |}; export default function ReactLogo({className}: Props) { return ( <svg xmlns="http://www.w3.org/2000/svg" className={`${styles.ReactLogo} ${className || ''}`} viewBox="-11.5 -10.23174 23 20.46348"> <circle cx="0" cy="0" r="2.05" fill="currentColor" /> <g stroke="currentColor" strokeWidth="1" fill="none"> <ellipse rx="11" ry="4.2" /> <ellipse rx="11" ry="4.2" transform="rotate(60)" /> <ellipse rx="11" ry="4.2" transform="rotate(120)" /> </g> </svg> ); }
src/components/Datepicker/index.js
wiki1024/sam-bs
import React from 'react' import moment from 'moment' import _ from 'lodash' import Calendar from './Calendar' import { Collapse } from 'react-bootstrap' import { updateMonth, selectDate, toggleOpen } from '../../actions/datePickerAction' import { debounce } from '../../util' import Header from './header' import Month from './month' import classnames from 'classnames' const DatePicker = (props) =>{ let {id, date, month, year, isOpen} = props let dates = generateDates(month,year) let controlClass = classnames({ 'control-group':true, 'focused':isOpen }) return ( <div className='datePicker' onClick={ (e)=>{ e.stopPropagation() } }> <span className={ controlClass } onClick = { (e) => { toggleOpen({id:id, isOpen:!isOpen});e.stopPropagation() } }> <input className='form-control' type='text' value={ date.format('MM/DD/YYYY') } /> <div className='input-group-addon'><i className='fa fa-calendar' aria-hidden='true'></i></div> </span> <Collapse in= { isOpen }> <div className='calendar' > <Header month={month} id={id} year={year} updateMonth={debounce(updateMonth,100)}/> <Month month={month} id={id} year={year} dates={dates} selected= {date} selectDate={selectDate} key={month}/> </div> </Collapse> </div> ) } function generateDates(month,year) { let firstDate = moment([year, month]).weekday(0) let dates = _.range(42).map((val, index) => { return firstDate.clone().add(index, 'd') }) return dates } // export default DatePicker
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
cojennin/react-router
import React from 'react'; import { Link } from 'react-router'; class Sidebar extends React.Component { render () { 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;
frontend/component/TopicDetail.js
wangmuming/node-forum
import React from 'react'; import 'highlight.js/styles/github-gist.css'; import {getTopicDetail, addComment, deleteComment, deleteTopic} from '../lib/client'; import {renderMarkdown} from '../lib/utils'; import { Router, Route, Link, browserHistory } from 'react-router'; import CommentEditor from './CommentEditor'; import {redirectURL} from '../lib/utils'; export default class TopicDetail extends React.Component{ constructor(pros){ super(pros); this.state = {}; } componentDidMount(){ this.refresh(); } // 调取话题接口 refresh(){ getTopicDetail(this.props.params.id) .then(topic => { topic.html = renderMarkdown(topic.content); if(topic.comments){ for(const item of topic.comments){ item.html = renderMarkdown(item.content); } } this.setState({topic}); }) .catch(err => console.error(err)); } // 点击删除评论按钮 handleDeleteComment(cid){ if(!confirm('是否删除评论?')) return; deleteComment(this.state.topic._id, cid) .then(comment => { this.refresh(); }) .catch(err => { alert(err); }); } handleDeleteTopic(){ if(!confirm('是否删除主题?')) return; deleteTopic(this.state.topic._id) .then(() => { redirectURL('/'); }) .catch(err => { alert(err); }); } render(){ const topic = this.state.topic; if(!topic){ return( <div>正在加载...</div> ); } return( <div> <h2>{topic.title}</h2> <p>{topic.author.nickname || '佚名'} 发表于 {topic.createdAt}</p> <p> {!topic.permission.edit ? null : <Link to={`/topic/${topic._id}/edit`} className="btn btn-xs btn-primary"> <i className="glyphicon glyphicon-edit"></i> 编辑 </Link> } &nbsp;&nbsp; {!topic.permission.delete ? null : <button className="btn btn-xs btn-danger" onClick={this.handleDeleteTopic.bind(this)}> <i className="glyphicon glyphicon-trash"></i> 删除 </button> } </p> <hr /> <p>标签: {topic.tags.map((tag, i) => { return( <span className="label label-primary" style={{marginRight: 10}} key={i}>{tag}</span> ); })} </p> <section dangerouslySetInnerHTML={{__html: topic.html}}></section> <CommentEditor title="发表评论" onSave={(comment, done) => { addComment(this.state.topic._id, comment.content) .then(comment => { done(); this.refresh(); }) .catch(err => { done(); alert(err); }); }} /> <ul className="list-group"> {topic.comments.map((item, i) => { return( <li className="list-group-item" key={i}> <span className="pull-right"> {!item.permission.delete ? null : <button className="btn btn-xs btn-danger" onClick={this.handleDeleteComment.bind(this, item._id)}> <i className="glyphicon glyphicon-trash"></i> </button> } </span> {item.author.nickname || '佚名'}于{item.createdAt}说: <p dangerouslySetInnerHTML={{__html: item.html}}></p> </li> ); })} </ul> </div> ); } }
web/client/configdev/src/config/ScreensaverMenu.js
project-owner/Peppy
/* Copyright 2019 Peppy Player [email protected] This file is part of Peppy Player. Peppy Player is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Peppy Player is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Peppy Player. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import {FormControl} from '@material-ui/core'; import Factory from "../Factory"; export default class ScreensaverMenu extends React.Component { render() { const { params, updateState, labels } = this.props; const items = ["clock", "logo", "slideshow", "peppymeter", "peppyweather", "spectrum", "lyrics", "random"]; return ( <FormControl> {items.map((v) => {return Factory.createCheckbox(v, params, updateState, labels)})} </FormControl> ); } }
src/views/Components/Buttons/Buttons.js
corbinpage/react-play
import React, { Component } from 'react'; class Buttons extends Component { render() { return ( <div className="animated fadeIn"> <div className="row"> <div className="col-md-6"> <div className="card"> <div className="card-header"> <strong>Options</strong> </div> <div className="card-block"> <button type="button" className="btn btn-primary">Primary</button> <button type="button" className="btn btn-secondary">Secondary</button> <button type="button" className="btn btn-success">Success</button> <button type="button" className="btn btn-warning">Warning</button> <button type="button" className="btn btn-danger">Danger</button> <button type="button" className="btn btn-link">Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>With Icons</strong> </div> <div className="card-block"> <button type="button" className="btn btn-primary"><i className="fa fa-star"></i>&nbsp; Primary</button> <button type="button" className="btn btn-secondary"><i className="fa fa-lightbulb-o"></i>&nbsp; Secondary</button> <button type="button" className="btn btn-success"><i className="fa fa-magic"></i>&nbsp; Success</button> <button type="button" className="btn btn-warning"><i className="fa fa-map-marker"></i>&nbsp; Warning</button> <button type="button" className="btn btn-danger"><i className="fa fa-rss"></i>&nbsp; Danger</button> <button type="button" className="btn btn-link"><i className="fa fa-link"></i>&nbsp; Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Size Large</strong> <small>Add this class <code>.btn-lg</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-primary btn-lg">Primary</button> <button type="button" className="btn btn-secondary btn-lg">Secondary</button> <button type="button" className="btn btn-success btn-lg">Success</button> <button type="button" className="btn btn-info btn-lg">Info</button> <button type="button" className="btn btn-warning btn-lg">Warning</button> <button type="button" className="btn btn-danger btn-lg">Danger</button> <button type="button" className="btn btn-link btn-lg">Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Size Small</strong> <small>Add this class <code>.btn-sm</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-primary btn-sm">Primary</button> <button type="button" className="btn btn-secondary btn-sm">Secondary</button> <button type="button" className="btn btn-success btn-sm">Success</button> <button type="button" className="btn btn-info btn-sm">Info</button> <button type="button" className="btn btn-warning btn-sm">Warning</button> <button type="button" className="btn btn-danger btn-sm">Danger</button> <button type="button" className="btn btn-link btn-sm">Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Disabled state</strong> <small>Add this <code>disabled="disabled"</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-primary" disabled="disabled">Primary</button> <button type="button" className="btn btn-secondary" disabled="disabled">Secondary</button> <button type="button" className="btn btn-success" disabled="disabled">Success</button> <button type="button" className="btn btn-info" disabled="disabled">Info</button> <button type="button" className="btn btn-warning" disabled="disabled">Warning</button> <button type="button" className="btn btn-danger" disabled="disabled">Danger</button> <button type="button" className="btn btn-link" disabled="disabled">Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Active state</strong> <small>Add this class <code>.active</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-primary active">Primary</button> <button type="button" className="btn btn-secondary active">Secondary</button> <button type="button" className="btn btn-success active">Success</button> <button type="button" className="btn btn-info active">Info</button> <button type="button" className="btn btn-warning active">Warning</button> <button type="button" className="btn btn-danger active">Danger</button> <button type="button" className="btn btn-link active">Link</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Block Level Buttons</strong> <small>Add this class <code>.btn-block</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-secondary btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-primary btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-success btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-info btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-warning btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-danger btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-link btn-lg btn-block">Block level button</button> </div> </div> </div> <div className="col-md-6"> <div className="card"> <div className="card-header"> <strong>Options</strong> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary">Primary</button> <button type="button" className="btn btn-outline-secondary">Secondary</button> <button type="button" className="btn btn-outline-success">Success</button> <button type="button" className="btn btn-outline-warning">Warning</button> <button type="button" className="btn btn-outline-danger">Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>With Icons</strong> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary"><i className="fa fa-star"></i>&nbsp; Primary</button> <button type="button" className="btn btn-outline-secondary"><i className="fa fa-lightbulb-o"></i>&nbsp; Secondary</button> <button type="button" className="btn btn-outline-success"><i className="fa fa-magic"></i>&nbsp; Success</button> <button type="button" className="btn btn-outline-warning"><i className="fa fa-map-marker"></i>&nbsp; Warning</button> <button type="button" className="btn btn-outline-danger"><i className="fa fa-rss"></i>&nbsp; Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Size Large</strong> <small>Add this class <code>.btn-lg</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary btn-lg">Primary</button> <button type="button" className="btn btn-outline-secondary btn-lg">Secondary</button> <button type="button" className="btn btn-outline-success btn-lg">Success</button> <button type="button" className="btn btn-outline-info btn-lg">Info</button> <button type="button" className="btn btn-outline-warning btn-lg">Warning</button> <button type="button" className="btn btn-outline-danger btn-lg">Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Size Small</strong> <small>Add this class <code>.btn-sm</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary btn-sm">Primary</button> <button type="button" className="btn btn-outline-secondary btn-sm">Secondary</button> <button type="button" className="btn btn-outline-success btn-sm">Success</button> <button type="button" className="btn btn-outline-info btn-sm">Info</button> <button type="button" className="btn btn-outline-warning btn-sm">Warning</button> <button type="button" className="btn btn-outline-danger btn-sm">Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Disabled state</strong> <small>Add this <code>disabled="disabled"</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary" disabled="disabled">Primary</button> <button type="button" className="btn btn-outline-secondary" disabled="disabled">Secondary</button> <button type="button" className="btn btn-success" disabled="disabled">Success</button> <button type="button" className="btn btn-outline-info" disabled="disabled">Info</button> <button type="button" className="btn btn-outline-warning" disabled="disabled">Warning</button> <button type="button" className="btn btn-outline-danger" disabled="disabled">Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Active state</strong> <small>Add this class <code>.active</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-outline-primary active">Primary</button> <button type="button" className="btn btn-outline-secondary active">Secondary</button> <button type="button" className="btn btn-outline-success active">Success</button> <button type="button" className="btn btn-outline-info active">Info</button> <button type="button" className="btn btn-outline-warning active">Warning</button> <button type="button" className="btn btn-outline-danger active">Danger</button> </div> </div> <div className="card"> <div className="card-header"> <strong>Block Level Buttons</strong> <small>Add this class <code>.btn-block</code></small> </div> <div className="card-block"> <button type="button" className="btn btn-outline-secondary btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-outline-primary btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-outline-success btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-outline-info btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-outline-warning btn-lg btn-block">Block level button</button> <button type="button" className="btn btn-outline-danger btn-lg btn-block">Block level button</button> </div> </div> </div> </div> </div> ) } } export default Buttons;
js/source/Customizer.js
peano-ito/giuseppe
/*********************************************************************/ /* Customizer */ /* (c) 2017 Peano System Inc. */ /*********************************************************************/ 'use strict'; import React from 'react'; import { store } from './Reducer.js'; import Utility from './Utility.js'; /*********************************************************************/ /* Constants */ /*********************************************************************/ const THEME_COLOR = { A: { '--text-color': '#000000', '--background-color': '#FFFFFF', '--main-color': '#008000', '--main-assoc-color': '#FFFFFF', '--sub-color': '#00EE00', '--sub-assoc-color': '#FFFFFF', '--accent-color': '#3333FF', '--accent-assoc-color': '#FFFFFF', '--highlighted-color': '#FF33FF', '--highlighted-assoc-color': '#FFFFFF', '--ok-color': '#0000FF', '--ng-color': '#FF0000', }, B: { '--text-color': '#000000', '--background-color': '#FFFFFF', '--main-color': '#FF0000', '--main-assoc-color': '#FFFFFF', '--sub-color': '#000000', '--sub-assoc-color': '#FFFFFF', '--accent-color': '#008000', '--accent-assoc-color': '#FFFFFF', '--highlighted-color': '#0000FF', '--highlighted-assoc-color': '#FFFFFF', '--ok-color': '#0000FF', '--ng-color': '#FF0000', }, C: { '--text-color': '#333333', '--background-color': '#FAF1F2', '--main-color': '#7A3849', '--main-assoc-color': '#EEEEEE', '--sub-color': '#666666', '--sub-assoc-color': '#EEEEEE', '--accent-color': '#305C37', '--accent-assoc-color': '#EEEEEE', '--highlighted-color': '#B66BB6', '--highlighted-assoc-color': '#EEEEEE', '--ok-color': '#244077', '--ng-color': '#875548', }, D: { '--text-color': '#333333', '--background-color': '#FCFCF6', '--main-color': '#4B4238', '--main-assoc-color': '#FFFFFF', '--sub-color': '#BAB7A3', '--sub-assoc-color': '#FFFFFF', '--accent-color': '#DB7093', '--accent-assoc-color': '#FFFFFF', '--highlighted-color': '#82B340', '--highlighted-assoc-color': '#FFFFFF', '--ok-color': '#0000FF', '--ng-color': '#FF0000', }, }; /*********************************************************************/ /* Switch Theme Color */ /*********************************************************************/ function switchThemeColor(key) { let color = THEME_COLOR[key]; for (var variable in color) { document.documentElement.style.setProperty(variable, color[variable]); } return; } // Initialize switchThemeColor('A'); /*********************************************************************/ /* Dispatch */ /*********************************************************************/ const dispatch = { selectThemeColor: (e) => { e.stopPropagation(); store.dispatch(Utility.createAction('CUSTOMIZER', 'COLOR', { color: e.target.value })); return; }, selectNaviDesign: (e) => { e.stopPropagation(); store.dispatch(Utility.createAction('CUSTOMIZER', 'NAV_DESIGN', { design: e.target.value })); return; }, selectNaviStyle: (e) => { e.stopPropagation(); store.dispatch(Utility.createAction('CUSTOMIZER', 'NAV_STYLE', { style: e.target.value })); return; }, }; /*********************************************************************/ /* Reducer */ /*********************************************************************/ export function reducer(state, action) { var ret = state; if (action.action == 'COLOR') { ret = Utility.clone(state); ret.customizer.color = action.data.color; switchThemeColor(action.data.color); } else if (action.action == 'NAV_DESIGN') { ret = Utility.clone(state); ret.customizer.navi.design = action.data.design; ret.customizer.navi.style = state.customizer.navi.old[action.data.design]; } else if (action.action == 'NAV_STYLE') { ret = Utility.clone(state); ret.customizer.navi.style = action.data.style; ret.customizer.navi.old[state.customizer.navi.design] = action.data.style; } return ret; } /*********************************************************************/ /* [Customizer] Customizer */ /*********************************************************************/ class Customizer extends React.Component { constructor(props) { super(props); } render() { return( <section className="band Customizer"> <div> <span> <span>テーマカラー:</span> <select value={this.props.state.customizer.color} onChange={dispatch.selectThemeColor.bind(this)}> <option value="A">A案: 新緑</option> <option value="B">B案: 情熱</option> <option value="C">C案: あずき</option> <option value="D">D案: ノスタルジー</option> </select> </span> <span> <span>ナビ設計:</span> <select value={this.props.state.customizer.navi.design} onChange={dispatch.selectNaviDesign.bind(this)}> <option value="a">(a)案: シングルナビゲーション</option> <option value="b">(b)案: ドロップダウン</option> </select> </span> <span> <span>ナビスタイル:</span> {(() => { if (this.props.state.customizer.navi.design == 'a') { return( <select value={this.props.state.customizer.navi.style} onChange={dispatch.selectNaviStyle.bind(this)}> <option value="D1">(a)-①案:</option> <option value="D2">(a)-②案:</option> </select> ); } else { return( <select value={this.props.state.customizer.navi.style} onChange={dispatch.selectNaviStyle.bind(this)}> <option value="D1">(b)-①案:</option> <option value="D2">(b)-②案:</option> <option value="D3">(b)-③案:</option> </select> ); } })()} </span> </div> </section> ); } } /*********************************************************************/ /* Export */ /*********************************************************************/ export default Customizer;
client/node_modules/uu5g03/doc/main/client/src/components/component-loader.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import UU5 from 'uu5'; import './component-loader.css'; export default React.createClass({ //@@viewOn:mixins mixins: [ UU5.Common.BaseMixin, UU5.Common.LoadMixin, UU5.Layout.ContainerMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Doc.Components.ComponentLoader', classNames: { main: 'uu5-doc-components-component-loader' }, defaults: {}, limits: {}, calls: { onLoad: 'loadComponentData' }, warnings: {}, errors: {}, lsi: {}, opt: {} }, //@@viewOff:statics //@@viewOn:propTypes //@@viewOff:propTypes //@@viewOn:getDefaultProps //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle componentWillReceiveProps(nextProps) { let dtoIn = this._getReloadDtoIn(); dtoIn.data = { name: nextProps.name }; this.reload('onLoad', dtoIn); }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods getOnLoadData_() { return { name: this.getName() }; }, //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers //@@viewOff:componentSpecificHelpers //@@viewOn:render render() { return ( <UU5.Layout.Container {...this.getMainPropsToPass()}> {this.getLoadFeedbackChildren(dtoOut => { let result = null; if (this.getName().match(/Mixin$/)) { result = <UU5.DocKit.Mixin mixinData={dtoOut.data} />; } else { result = <UU5.DocKit.Component componentData={dtoOut.data} />; } return result; })} </UU5.Layout.Container> ); } //@@viewOn:render });
packages/mineral-ui-icons/src/IconPlayCircleOutline.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconPlayCircleOutline(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </g> </Icon> ); } IconPlayCircleOutline.displayName = 'IconPlayCircleOutline'; IconPlayCircleOutline.category = 'av';
from-zero-to-vertical/src/components/atoms/PApp/PApp2.js
Muzietto/react-playground
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; // cfr. https://codeburst.io/my-journey-to-make-styling-with-material-ui-right-6a44f7c68113 const useStyles = makeStyles(() => ({ outlinedRoot: { // if the style the root, the fieldset inside will mess up things '&:hover': { border: '1px solid red', }, }, })); function PApp2() { const classes = useStyles(); const InputProps = { classes: { root: classes.outlinedRoot, }, }; return ( <TextField id='outlined-name' label='Name' className={classes.textField} margin='normal' variant='outlined' InputProps={InputProps} /> ); } export default PApp2;
src/components/Switch/index.js
HenriBeck/materialize-react
// @flow strict-local import React from 'react'; import PropTypes from 'prop-types'; import getNotDeclaredProps from 'react-get-not-declared-props'; import Ripple from '../Ripple'; import { ENTER, SPACE_BAR, } from '../../utils/constants'; import Sheet, { type Data } from './Sheet'; type Props = { toggled: boolean, onChange: () => void, className: string, disabled: boolean, noink: boolean, color: 'primary' | 'accent', }; type State = { isFocused: boolean }; export default class Switch extends React.PureComponent<Props, State> { static propTypes = { toggled: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired, className: PropTypes.string, disabled: PropTypes.bool, noink: PropTypes.bool, color: PropTypes.oneOf([ 'primary', 'accent', ]), }; static defaultProps = { className: '', disabled: false, noink: false, color: 'primary', }; state = { isFocused: false }; handleFocus = () => { this.setState({ isFocused: true }); }; handleBlur = () => { this.setState({ isFocused: false }); }; handleKeyUp = (ev: SyntheticKeyboardEvent<HTMLSpanElement>) => { if (ev.keyCode === ENTER || ev.keyCode === SPACE_BAR) { this.props.onChange(); } }; handleClick = (ev: SyntheticMouseEvent<HTMLSpanElement>) => { if (ev.target === ev.currentTarget) { this.props.onChange(); } }; render() { const data: Data = { toggled: this.props.toggled, disabled: this.props.disabled, color: this.props.color, }; return ( <Sheet data={data}> {({ classes }) => ( <span {...getNotDeclaredProps(this.props, Switch)} role="switch" className={`${classes.switch} ${this.props.className}`} aria-checked={this.props.toggled} aria-disabled={this.props.disabled} tabIndex={this.props.disabled ? -1 : 0} onKeyUp={this.handleKeyUp} onFocus={this.handleFocus} onBlur={this.handleBlur} onClick={this.handleClick} > <span className={classes.track} /> <span className={classes.thumb}> <Ripple round center nowaves={this.props.noink} isFocused={this.state.isFocused} className={classes.ripple} onPress={this.props.onChange} /> </span> </span> )} </Sheet> ); } }
app/jsx/shared/components/CreateOrUpdateUserModal.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {bool, func, shape, string, element, oneOf} from 'prop-types' import {Avatar} from '@instructure/ui-elements' import {Button} from '@instructure/ui-buttons' import {Checkbox, TextInput} from '@instructure/ui-forms' import {FormFieldGroup} from '@instructure/ui-form-field' import update from 'immutability-helper' import {get, isEmpty} from 'lodash' import axios from 'axios' import I18n from 'i18n!account_course_user_search' import {firstNameFirst, lastNameFirst, nameParts} from 'user_utils' import preventDefault from 'compiled/fn/preventDefault' import unflatten from 'compiled/object/unflatten' import registrationErrors from 'compiled/registration/registrationErrors' import Modal from './InstuiModal' import TimeZoneSelect from './TimeZoneSelect' const trim = (str = '') => str.trim() const initialState = { open: false, data: { user: {}, pseudonym: { send_confirmation: true } }, errors: {} } export default class CreateOrUpdateUserModal extends React.Component { static propTypes = { // whatever you pass as the child, when clicked, will open the dialog children: element.isRequired, createOrUpdate: oneOf(['create', 'update']).isRequired, url: string.isRequired, user: shape({ name: string.isRequired, sortable_name: string, short_name: string, email: string, time_zone: string }), customized_login_handle_name: string, delegated_authentication: bool.isRequired, showSIS: bool.isRequired, afterSave: func.isRequired } static defaultProps = { customized_login_handle_name: window.ENV.customized_login_handle_name, delegated_authentication: window.ENV.delegated_authentication, showSIS: window.ENV.SHOW_SIS_ID_IN_NEW_USER_FORM } state = {...initialState} componentWillMount() { if (this.props.createOrUpdate === 'update') { // only get the attributes from the user that we are actually going to show in the <input>s // and send to the server. Because if we send the server extraneous attributes like user[id] // it throws 401 errors const userDataFromProps = this.getInputFields().reduce((memo, {name}) => { const key = name.match(/user\[(.*)\]/)[1] // extracts 'short_name' from 'user[short_name]' return {...memo, [key]: this.props.user[key]} }, {}) this.setState(update(this.state, {data: {user: {$set: userDataFromProps}}})) } } onChange = (field, value) => { this.setState(prevState => { let newState = update(prevState, { data: unflatten({[field]: {$set: value}}), errors: {$set: {}} }) // set sensible defaults for sortable_name and short_name if (field === 'user[name]') { const u = prevState.data.user // shamelessly copypasted from user_sortable_name.js const sortableNameParts = nameParts(trim(u.sortable_name)) if (!trim(u.sortable_name) || trim(firstNameFirst(sortableNameParts)) === trim(u.name)) { const newSortableName = lastNameFirst(nameParts(value, sortableNameParts[1])) newState = update(newState, {data: {user: {sortable_name: {$set: newSortableName}}}}) } if (!trim(u.short_name) || trim(u.short_name) === trim(u.name)) { newState = update(newState, {data: {user: {short_name: {$set: value}}}}) } } return newState }) } close = () => this.setState({open: false}) onSubmit = () => { if (!isEmpty(this.state.errors)) return const method = {create: 'POST', update: 'PUT'}[this.props.createOrUpdate] axios({url: this.props.url, method, data: this.state.data}).then( response => { const getUserObj = o => (o.user ? getUserObj(o.user) : o) const user = getUserObj(response.data) const userName = user.name const wrapper = `<a href='/users/${user.id}'>$1</a>` $.flashMessage( response.data.message_sent ? I18n.t( '*%{userName}* saved successfully! They should receive an email confirmation shortly.', {userName, wrapper} ) : I18n.t('*%{userName}* saved successfully!', {userName, wrapper}) ) this.setState({...initialState}) if (this.props.afterSave) this.props.afterSave(response) }, ({response}) => { const errors = registrationErrors(response.data.errors) $.flashError('Something went wrong saving user details.') this.setState({errors}) } ) } getInputFields = () => { const showCustomizedLoginId = this.props.customized_login_handle_name || this.props.delegated_authentication return [ { name: 'user[name]', label: I18n.t('Full Name'), hint: I18n.t('This name will be used by teachers for grading.'), required: I18n.t('Full name is required') }, { name: 'user[short_name]', label: I18n.t('Display Name'), hint: I18n.t('People will see this name in discussions, messages and comments.') }, { name: 'user[sortable_name]', label: I18n.t('Sortable Name'), hint: I18n.t('This name appears in sorted lists.') } ] .concat( this.props.createOrUpdate === 'create' ? [ { name: 'pseudonym[unique_id]', label: this.props.customized_login_handle_name || I18n.t('Email'), required: this.props.customized_login_handle_name ? I18n.t('%{login_handle} is required', { login_handle: this.props.customized_login_handle_name }) : I18n.t('Email is required') }, showCustomizedLoginId && { name: 'pseudonym[path]', label: I18n.t('Email'), required: I18n.t('Email is required') }, this.props.showSIS && { name: 'pseudonym[sis_user_id]', label: I18n.t('SIS ID') }, { name: 'pseudonym[send_confirmation]', label: I18n.t('Email the user about this account creation'), Component: Checkbox } ] : [ { name: 'user[email]', label: I18n.t('Default Email') }, { name: 'user[time_zone]', label: I18n.t('Time Zone'), Component: TimeZoneSelect } ] ) .filter(Boolean) } render = () => ( <span> <Modal as="form" onSubmit={preventDefault(this.onSubmit)} open={this.state.open} onDismiss={this.close} size="medium" label={ this.props.createOrUpdate === 'create' ? ( I18n.t('Add a New User') ) : ( <span> <Avatar size="small" name={this.state.data.user.name} src={this.props.user.avatar_url} data-fs-exclude />{' '} {I18n.t('Edit User Details')} </span> ) } > <Modal.Body> <FormFieldGroup layout="stacked" rowSpacing="small" description=""> {this.getInputFields().map(({name, label, hint, required, Component = TextInput}) => ( <Component key={name} label={label} value={get(this.state.data, name)} checked={get(this.state.data, name)} onChange={e => this.onChange( name, e.target.type === 'checkbox' ? e.target.checked : e.target.value ) } required={!!required} layout="inline" messages={(this.state.errors[name] || []) .map(errMsg => ({type: 'error', text: errMsg})) .concat(hint && {type: 'hint', text: hint}) .filter(Boolean)} /> ))} </FormFieldGroup> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>{I18n.t('Cancel')}</Button> &nbsp; <Button type="submit" variant="primary"> {this.props.createOrUpdate === 'create' ? I18n.t('Add User') : I18n.t('Save')} </Button> </Modal.Footer> </Modal> {React.Children.map(this.props.children, child => // when you click whatever is the child element to this, open the modal React.cloneElement(child, { onClick: (...args) => { if (child.props.onClick) child.props.onClick(...args) this.setState({open: true}) } }) )} </span> ) }
src/components/vidoe_detail.js
dulik06/ReduxStarter
import React from 'react'; const VideoDetail = (props) => { const video = props.video; if(!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return( <div className='video-detail col-md-8'> <div className='embed-responsive embed-responsive-16by9'> <iframe className='embed-responsive-item' src={ url }></iframe> </div> <div className='details'> <div>{ video.snippet.title }</div> <div>{ video.snippet.description }</div> </div> </div> ); } export default VideoDetail;
src/PlayerView.js
hannes-hochreiner/more-podcasts
import React, { Component } from 'react'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import PlayerPresenter from './PlayerPresenter'; import Toolbar from '@material-ui/core/Toolbar'; import AppBar from '@material-ui/core/AppBar'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import SpeedHighIcon from '@material-ui/icons/FastForward'; import SpeedLowIcon from '@material-ui/icons/PlayArrow'; import VolumeHighIcon from '@material-ui/icons/VolumeUp'; import VolumeLowIcon from '@material-ui/icons/VolumeDown'; import PlayIcon from '@material-ui/icons/PlayCircleFilled'; import PauseIcon from '@material-ui/icons/PauseCircleFilled'; import Slider from '@material-ui/core/Slider'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import './PlayerView.css'; export default class PlayerView extends Component { state = { items: [], selectedItem: null, playing: false, volume: 0.5, speed: 1.0, currentTime: 0, duration: 0 }; componentDidMount() { this._pres = new PlayerPresenter(this); } componentWillUnmount() { this._pres.finalize(); } set items(value) { this.setState({ items: value }); } set selectedItem(value) { this.setState({ selectedItem: value }); } set playing(value) { this.setState({ playing: value }); } set volume(value) { this.setState({ volume: value }); } set speed(value) { this.setState({ speed: value }); } get currentTime() { return this.state.currentTime; } set currentTime(value) { this.setState({ currentTime: value }); } set duration(value) { this.setState({ duration: value }); } _handleListItemClick(item) { this._pres.selectedItemChanged(item); } _handleVolumeChange(event, value) { this.setState({ volume: value }); this._pres.volumeChanged(value); } _handleSpeedChange(event, value) { this.setState({ speed: value }); this._pres.speedChanged(value); } _handleCurrentTimeChange(event, value) { this.setState({ currentTime: value }); this._pres.currentTimeChanged(value); } _handleEnclosureRefresh(item, event) { this._pres.refreshEnclosure(item); } _handleEnclosureDelete(item, event) { this._pres.deleteEnclosure(item); } _formatTime(value) { let sec = `${Math.round(value % 60)}`; let min = `${Math.floor(value / 60)}`; if (sec.length === 1) { sec = '0' + sec; } if (min.length === 1) { min = '0' + min; } return `${min}:${sec}`; } render() { const menu = <div> <IconButton><MenuIcon color={'#FFF'}/></IconButton> <Menu anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} > <MenuItem primaryText="channels" onClick={() => {this._pres.goToChannelListPage();}}/> <MenuItem primaryText="info" onClick={() => {this._pres.goToInfoPage();}}/> </Menu> </div>; let itemMenu = (item) => { return (<div> <IconButton><MoreVertIcon /></IconButton> <Menu anchorOrigin={{horizontal: 'right', vertical: 'top'}} targetOrigin={{horizontal: 'right', vertical: 'top'}} > <MenuItem primaryText="refresh" onClick={this._handleEnclosureRefresh.bind(this, item)}/> <MenuItem primaryText="delete" onClick={this._handleEnclosureDelete.bind(this, item)} /> </Menu> </div>); } const playButton = ( <IconButton disabled={!this.state.selectedItem || this.state.playing} onClick={() => {this._pres.start()}} > <PlayIcon/> </IconButton> ); const pauseButton = ( <IconButton disabled={!this.state.selectedItem || !this.state.playing} onClick={() => {this._pres.stop()}} > <PauseIcon/> </IconButton> ); let pausePlayButton = this.state.playing ? pauseButton : playButton; return ( <div> <AppBar title="player" iconElementLeft={menu}/> <Toolbar> {pausePlayButton} {this.state.selectedItem ? this.state.selectedItem.title : ''} </Toolbar> <div className="sliderGroup"> <table> <tbody> <tr> <td>{this._formatTime(this.state.currentTime)}</td> <td className="sliderColumn"><Slider min={0} max={this.state.duration} step={1} value={this.state.currentTime} onChange={this._handleCurrentTimeChange.bind(this)}/></td> <td>{this._formatTime(this.state.duration)}</td> </tr> <tr> <td><VolumeLowIcon/></td> <td className="sliderColumn"><Slider min={0} max={1} step={0.01} value={this.state.volume} onChange={this._handleVolumeChange.bind(this)}/></td> <td><VolumeHighIcon/></td> </tr> <tr> <td><SpeedLowIcon/></td> <td className="sliderColumn"><Slider min={0.5} max={2} step={0.05} value={this.state.speed} onChange={this._handleSpeedChange.bind(this)}/></td> <td><SpeedHighIcon/></td> </tr> </tbody> </table> </div> <List> {this.state.items.map(item => { return <ListItem key={item.id} primaryText={item.title} onClick={this._handleListItemClick.bind(this, item)} rightIconButton={itemMenu(item)} />; })} </List> </div> ); } }
packages/ringcentral-widgets/components/CircleButton/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import styles from './styles.scss'; /** * Circle Button with SVG */ function CircleButton(props) { let icon; if (props.icon) { const Icon = props.icon; icon = ( <Icon className={classnames(styles.icon, props.iconClassName)} width={props.iconWidth} height={props.iconHeight} x={props.iconX} y={props.iconY} /> ); } const circleClass = classnames( styles.circle, props.showBorder ? null : styles.noBorder ); const onClick = props.disabled ? null : props.onClick; return ( <svg xmlns="http://www.w3.org/2000/svg" className={classnames(styles.btnSvg, props.className)} viewBox="0 0 500 500" onClick={onClick} width={props.width} height={props.height} x={props.x} y={props.y} > {props.title ? <title>{props.title}</title> : null} <g className={styles.btnSvgGroup} > <circle className={circleClass} cx="250" cy="250" r="245" /> {icon} </g> </svg> ); } CircleButton.propTypes = { icon: PropTypes.func, className: PropTypes.string, showBorder: PropTypes.bool, iconClassName: PropTypes.string, onClick: PropTypes.func, width: PropTypes.string, height: PropTypes.string, x: PropTypes.number, y: PropTypes.number, disabled: PropTypes.bool, iconWidth: PropTypes.number, iconHeight: PropTypes.number, iconX: PropTypes.number, iconY: PropTypes.number, title: PropTypes.string, }; CircleButton.defaultProps = { icon: undefined, className: undefined, showBorder: true, iconClassName: undefined, disabled: false, onClick: null, width: '100%', height: '100%', x: 0, y: 0, iconWidth: 200, iconHeight: 200, iconX: 150, iconY: 150, title: null, }; export default CircleButton;
src/svg-icons/image/add-a-photo.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAddAPhoto = (props) => ( <SvgIcon {...props}> <path d="M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z"/> </SvgIcon> ); ImageAddAPhoto = pure(ImageAddAPhoto); ImageAddAPhoto.displayName = 'ImageAddAPhoto'; ImageAddAPhoto.muiName = 'SvgIcon'; export default ImageAddAPhoto;
test/helpers/shallowRenderHelper.js
Solshal/solshal-chrome-extension
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
es/Switch/Switch.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // weak import React from 'react'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import SwitchBase from '../internal/SwitchBase'; export const styles = theme => ({ root: { display: 'inline-flex', width: 62, position: 'relative', flexShrink: 0 }, bar: { borderRadius: 7, display: 'block', position: 'absolute', width: 34, height: 14, top: '50%', marginTop: -7, left: '50%', marginLeft: -17, transition: theme.transitions.create(['opacity', 'background-color'], { duration: theme.transitions.duration.shortest }), backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff', opacity: theme.palette.type === 'light' ? 0.38 : 0.3 }, icon: { boxShadow: theme.shadows[1], backgroundColor: 'currentColor', width: 20, height: 20, borderRadius: '50%' }, // For SwitchBase default: { zIndex: 1, color: theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[400], transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest }) }, checked: { color: theme.palette.primary[500], transform: 'translateX(14px)', '& + $bar': { backgroundColor: theme.palette.primary[500], opacity: 0.5 } }, disabled: { color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800], '& + $bar': { backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff', opacity: theme.palette.type === 'light' ? 0.12 : 0.1 } } }); function Switch(props) { const { classes, className } = props, other = _objectWithoutProperties(props, ['classes', 'className']); const icon = React.createElement('span', { className: classes.icon }); return React.createElement( 'span', { className: classNames(classes.root, className) }, React.createElement(SwitchBase, _extends({ icon: icon, classes: { default: classes.default, checked: classes.checked, disabled: classes.disabled }, checkedIcon: icon }, other)), React.createElement('span', { className: classes.bar }) ); } export default withStyles(styles, { name: 'MuiSwitch' })(Switch);
app/javascript/mastodon/features/list_editor/components/account.js
MitarashiDango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import { removeFromListEditor, addToListEditor } from '../../../actions/lists'; const messages = defineMessages({ remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId, added }) => ({ account: getAccount(state, accountId), added: typeof added === 'undefined' ? state.getIn(['listEditor', 'accounts', 'items']).includes(accountId) : added, }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { accountId }) => ({ onRemove: () => dispatch(removeFromListEditor(accountId)), onAdd: () => dispatch(addToListEditor(accountId)), }); export default @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl class Account extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onRemove: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, added: PropTypes.bool, }; static defaultProps = { added: false, }; render () { const { account, intl, onRemove, onAdd, added } = this.props; let button; if (added) { button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />; } else { button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />; } return ( <div className='account'> <div className='account__wrapper'> <div className='account__display-name'> <div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div> <DisplayName account={account} /> </div> <div className='account__relationship'> {button} </div> </div> </div> ); } }
actor-sdk/sdk-web/src/components/sidebar/HeaderSection.react.js
y0ke/actor-platform
/* * Copyright (C) 2015-2016 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import { Container } from 'flux/utils'; import classnames from 'classnames'; import ActorClient from '../../utils/ActorClient'; import { escapeWithEmoji } from '../../utils/EmojiUtils' import confirm from '../../utils/confirm' import SharedContainer from '../../utils/SharedContainer'; import { FormattedMessage } from 'react-intl'; import ProfileActionCreators from '../../actions/ProfileActionCreators'; import CreateGroupActionCreators from '../../actions/CreateGroupActionCreators'; import LoginActionCreators from '../../actions/LoginActionCreators'; import HelpActionCreators from '../../actions/HelpActionCreators'; import AddContactActionCreators from '../../actions/AddContactActionCreators'; import PreferencesActionCreators from '../../actions/PreferencesActionCreators'; import ProfileStore from '../../stores/ProfileStore'; import SvgIcon from '../common/SvgIcon.react'; import AvatarItem from '../common/AvatarItem.react'; class HeaderSection extends Component { constructor(props) { super(props); this.state = { isOpened: false } this.openHelp = this.openHelp.bind(this); this.openTwitter = this.openTwitter.bind(this); this.openFacebook = this.openFacebook.bind(this); this.openHomePage = this.openHomePage.bind(this); this.setLogout = this.setLogout.bind(this); this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this); this.closeHeaderMenu = this.closeHeaderMenu.bind(this); this.openMyProfile = this.openMyProfile.bind(this); this.openCreateGroup = this.openCreateGroup.bind(this); this.openAddContactModal = this.openAddContactModal.bind(this); this.onSettingsOpen = this.onSettingsOpen.bind(this); } static getStores() { return [ProfileStore]; } static calculateState() { return { profile: ProfileStore.getProfile() } } toggleHeaderMenu() { const { isOpened } = this.state; if (!isOpened) { this.setState({ isOpened: true }); document.addEventListener('click', this.closeHeaderMenu, false); } else { this.closeHeaderMenu(); } } closeHeaderMenu() { this.setState({ isOpened: false }); document.removeEventListener('click', this.closeHeaderMenu, false); } openMyProfile() { ProfileActionCreators.show(); } openCreateGroup() { CreateGroupActionCreators.open(); } openAddContactModal() { AddContactActionCreators.open(); } onSettingsOpen() { PreferencesActionCreators.show(); } openHelp() { HelpActionCreators.open() } openTwitter(event) { const { twitter } = SharedContainer.get(); event.preventDefault(); if (ActorClient.isElectron()) { ActorClient.handleLinkClick(event); } else { window.open(`https://twitter.com/${twitter}`, '_blank'); } } openFacebook(event) { const { facebook } = SharedContainer.get(); event.preventDefault(); if (ActorClient.isElectron()) { ActorClient.handleLinkClick(event); } else { window.open(`https://facebook.com/${facebook}`, '_blank'); } } openHomePage(event) { const { homePage } = SharedContainer.get(); event.preventDefault(); if (ActorClient.isElectron()) { ActorClient.handleLinkClick(event); } else { window.open(homePage, '_blank'); } } setLogout() { confirm(<FormattedMessage id="modal.confirm.logout"/>).then( () => LoginActionCreators.setLoggedOut(), () => {} ); } renderTwitterLink() { const { twitter } = SharedContainer.get(); if (!twitter) return null; return ( <li className="dropdown__menu__item"> <a href={`https://twitter.com/${twitter}`} onClick={this.openTwitter}> <SvgIcon className="icon icon--dropdown sidebar__header__twitter" glyph="twitter" /> <FormattedMessage id="menu.twitter"/> </a> </li> ); } renderFacebookLink() { const { facebook } = SharedContainer.get(); if (!facebook) return null; return ( <li className="dropdown__menu__item"> <a href={`https://facebook.com/${facebook}`} onClick={this.openFacebook}> <SvgIcon className="icon icon--dropdown sidebar__header__facebook" glyph="facebook" /> <FormattedMessage id="menu.facebook"/> </a> </li> ); } renderHomeLink() { const { homePage } = SharedContainer.get(); if (!homePage) return null; return ( <li className="dropdown__menu__item"> <a href={homePage} onClick={this.openHomePage}> <i className="material-icons">public</i> <FormattedMessage id="menu.homePage"/> </a> </li> ); } renderHelpLink() { const { helpPhone } = SharedContainer.get(); if (!helpPhone) return null; if (/@/.test(helpPhone)) { return ( <li className="dropdown__menu__item"> <a href={`mailto:${helpPhone}`}> <i className="material-icons">help</i> <FormattedMessage id="menu.helpAndFeedback"/> </a> </li> ); } else { return ( <li className="dropdown__menu__item" onClick={this.openHelp}> <i className="material-icons">help</i> <FormattedMessage id="menu.helpAndFeedback"/> </li> ); } } render() { const { profile, isOpened } = this.state; if (!profile) return null; const headerClass = classnames('sidebar__header', 'sidebar__header--clickable', { 'sidebar__header--opened': isOpened }); const menuClass = classnames('dropdown', { 'dropdown--opened': isOpened }); return ( <header className={headerClass}> <div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}> <AvatarItem className="sidebar__avatar" image={profile.avatar} placeholder={profile.placeholder} size="tiny" title={profile.name} /> <span className="sidebar__header__user__name col-xs" dangerouslySetInnerHTML={{ __html: escapeWithEmoji(profile.name) }}/> <div className={menuClass}> <span className="dropdown__button"> <i className="material-icons">arrow_drop_down</i> </span> <ul className="dropdown__menu dropdown__menu--right"> <li className="dropdown__menu__item" onClick={this.openMyProfile}> <i className="material-icons">edit</i> <FormattedMessage id="menu.editProfile"/> </li> <li className="dropdown__menu__item" onClick={this.openAddContactModal}> <i className="material-icons">person_add</i> <FormattedMessage id="menu.addToContacts"/> </li> <li className="dropdown__menu__item" onClick={this.openCreateGroup}> <i className="material-icons">group_add</i> <FormattedMessage id="menu.createGroup"/> </li> <li className="dropdown__menu__separator"/> <li className="dropdown__menu__item" onClick={this.onSettingsOpen}> <i className="material-icons">settings</i> <FormattedMessage id="menu.preferences"/> </li> {this.renderHelpLink()} {this.renderTwitterLink()} {this.renderFacebookLink()} {this.renderHomeLink()} <li className="dropdown__menu__separator"/> <li className="dropdown__menu__item" onClick={this.setLogout}> <FormattedMessage id="menu.signOut"/> </li> </ul> </div> </div> </header> ); } } export default Container.create(HeaderSection);
app/components/Toggle/index.js
gihrig/react-boilerplate
/** * * LocaleToggle * */ import React from 'react'; import Select from './Select'; import ToggleOption from '../ToggleOption'; function Toggle(props) { let content = (<option>--</option>); // If we have items, render them if (props.values) { content = props.values.map((value) => ( <ToggleOption key={value} value={value} message={props.messages[value]} /> )); } return ( <Select value={props.value} onChange={props.onToggle}> {content} </Select> ); } Toggle.propTypes = { onToggle: React.PropTypes.func, values: React.PropTypes.array, value: React.PropTypes.string, messages: React.PropTypes.object, }; export default Toggle;
src/js/Codedojo/Not.js
pankiv/news
/** * Created by Vasul on 03.10.2017. */ import React from 'react'; const Not = () => { return ( <h1>Not fount</h1> ) }; export default Not;
src/esm/components/graphics/icons/ellipsis-icon/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "title"]; import React from 'react'; import PropTypes from 'prop-types'; export var EllipsisIcon = function EllipsisIcon(_ref) { var color = _ref.color, title = _ref.title, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("svg", _extends({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 16 4", width: "16", height: "4", fill: "none" }, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("circle", { cx: "2", cy: "2", r: "2", fill: color }), /*#__PURE__*/React.createElement("circle", { cx: "8", cy: "2", r: "2", fill: color }), /*#__PURE__*/React.createElement("circle", { cx: "14", cy: "2", r: "2", fill: color })); }; EllipsisIcon.propTypes = { color: PropTypes.string, title: PropTypes.string }; EllipsisIcon.defaultProps = { color: '#222', title: '' };
pkg/interface/chat/src/js/components/lib/backlog-element.js
ngzax/urbit
import React, { Component } from 'react'; import classnames from 'classnames'; export class BacklogElement extends Component { render() { let props = this.props; return ( <div className="center mw6"> <div className="db pa3 ma3 ba b--gray4 bg-gray5 b--gray2-d bg-gray1-d white-d flex items-center"> <img className="invert-d spin-active v-mid" src="/~chat/img/Spinner.png" width={16} height={16} /> <p className="lh-copy db ml3"> Past messages are being restored </p> </div> </div> ); } }
src/pages/vida-bela.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Vida Bela' /> )
src/components/TextInputBEM/TextInputBEM.js
coryhouse/ps-react
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 TextInput({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> ); }; TextInput.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 TextInput;
client/vehicle-finder-spa/src/containers/user-management/single-user.js
Del7a/vehicle-finder
import React, { Component } from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {setCurrentUser, formChanged} from '../../actions/user'; import {updateSingleUser} from '../../actions/user-management'; import Form from '../../components/profile/info'; class SingleUser extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.formInputChanged = this.formInputChanged.bind(this); } componentDidMount() { if(this.props.match.params.userId) { const userId = this.props.match.params.userId const user = this.getCurretnUseFromManagementState(this.props.userManagement.allUsers, userId); if(user.length > 0) { this.props.setCurrentUser(user[0]); } } } handleSubmit(ev) { ev.preventDefault(); const userId = this.props.match.params.userId const user = this.getCurretnUseFromManagementState(this.props.userManagement.allUsers, userId) const userForSubmit = {...user[0], username: this.props.user.username, email: this.props.user.username, firstName: this.props.user.firstName, lastName: this.props.user.lastName } this.props.updateSingleUser(userForSubmit) } formInputChanged(newFormState) { this.props.formChanged(newFormState); } getCurretnUseFromManagementState(allUsers, targetUserId) { return allUsers.filter(function(usr) { return usr._id === targetUserId }) } render(){ const infoMessage = this.props.userManagement.currentInfoMessage !== '' ? <div className="alert alert-success"> <strong>Success!</strong> {this.props.userManagement.currentInfoMessage} </div> : '' const errorMessage = this.props.userManagement.currentErrorMessage !== '' ? <div className="alert alert-danger"> {this.props.userManagement.currentErrorMessage} </div> : '' return( <div> {infoMessage} {errorMessage} {<Form username={this.props.user.username} email={this.props.user.email} firstName={this.props.user.firstName} lastName={this.props.user.lastName} handleSubmit={this.handleSubmit} formInputChanged={this.formInputChanged} />} </div> ) } } function mapStateToProps({user, userManagement}) { return {user, userManagement}; } function mapDispatchToProps(dispatch) { return bindActionCreators({formChanged,updateSingleUser, setCurrentUser}, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(SingleUser);
app/routes/method/CreateRoute.js
ryrudnev/dss-wm
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as Method } from '../../entities/Method'; import { Collection as MethodTypes } from '../../entities/MethodType'; import { PageHeader, Row, Col, Panel } from 'react-bootstrap'; import MethodForm from '../../components/MethodForm'; import Progress from 'react-progress-2'; import radio from 'backbone.radio'; const router = radio.channel('router'); export default class MethodCreateRoute extends Route { breadcrumb = 'Создать способ управления отходами' onCancel() { router.request('navigate', `companies/${this.companyFid}`); } fetch({ params }) { this.companyFid = params.fid; this.methodTypes = new MethodTypes; return this.methodTypes.fetch(); } onSubmit(values) { Progress.show(); const method = new Method(values); method.forSubjectParam(this.companyFid); method.save({}, { success: model => { Progress.hide(); router.request('navigate', `companies/${this.companyFid}/methods/${model.id}`); }, }); } render() { return ( <div> <Helmet title="Создание способа управления отходами" /> <PageHeader>Создание способа управления отходами</PageHeader> <Row> <Col md={8}> <Panel> <MethodForm create onSubmit={(values) => this.onSubmit(values)} onCancel={() => this.onCancel()} methodTypes={this.methodTypes.toJSON()} /> </Panel> </Col> </Row> </div> ); } }
docs/src/NotFoundPage.js
egauci/react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const NotFoundPage = React.createClass({ render() { return ( <div> <NavMain activePage="" /> <PageHeader title="404" subTitle="Hmmm this is awkward." /> <PageFooter /> </div> ); } }); export default NotFoundPage;
app/containers/LoginPage/index.js
gitlab-classroom/classroom-web
/* * * LoginPage * */ import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import styled from 'styled-components'; import selectLoginPage from './selectors'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import Paper from 'material-ui/Paper'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import { setAppbar } from '../Header/actions'; import { actions as sessionActions } from '../../apis/session'; import { actions as loginPageActions } from './actions'; import Img from '../../components/Img'; import AvatarImg from '../../avatar.jpg'; const PageContainer = styled.div` display: flex; flex-direction: column; `; const HeaderMessage = styled.h1` align-self: center; font-size: 38px; color: #555; font-weight: 300; letter-spacing: 1px; `; const LoginContainer = styled(Paper)` width: 354px; padding: 40px; margin-bottom: 80px; background-color: #f7f7f7; text-align: center; align-self: center; display: flex; flex-direction: column; `; const StyledAvatar = styled(Img)` width: 96px; height: 96px; align-self: center; border-radius: 48px; `; export class LoginPage extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { setAppbar: React.PropTypes.func, login: React.PropTypes.func, testLogin: React.PropTypes.func, } state = { username: '', password: '', } componentDidMount() { this.props.setAppbar({ hide: true, }); this.props.testLogin(); } handleUsernameChanged = (event) => { this.setState({ username: event.target.value, }); } handlePasswordChanged = (event) => { this.setState({ password: event.target.value, }); } handleLogin = () => { const { username, password } = this.state; this.props.login({ username, password, }); } render() { return ( <PageContainer> <HeaderMessage> <FormattedMessage {...messages.header} /> </HeaderMessage> <LoginContainer zDepth={1} style={{ backgroundColor: '#f7f7f7' }}> <StyledAvatar src={AvatarImg} alt="Avatar" /> <TextField floatingLabelText={<FormattedMessage {...messages.username} />} style={{ width: '100%' }} onChange={this.handleUsernameChanged} /> <TextField floatingLabelText={<FormattedMessage {...messages.password} />} type="password" style={{ width: '100%', marginTop: -16, marginBottom: 16 }} onChange={this.handlePasswordChanged} /> <RaisedButton primary label={<FormattedMessage {...messages.login} />} onTouchTap={this.handleLogin} /> </LoginContainer> </PageContainer> ); } } const mapStateToProps = selectLoginPage(); function mapDispatchToProps(dispatch) { return bindActionCreators({ setAppbar, login: sessionActions.login, testLogin: loginPageActions.testLogin, }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);
docs/src/app/components/pages/components/Card/ExampleControlled.js
ArcanisCz/material-ui
import React from 'react'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; import Toggle from 'material-ui/Toggle'; export default class CardExampleControlled extends React.Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpandChange = (expanded) => { this.setState({expanded: expanded}); }; handleToggle = (event, toggle) => { this.setState({expanded: toggle}); }; handleExpand = () => { this.setState({expanded: true}); }; handleReduce = () => { this.setState({expanded: false}); }; render() { return ( <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}> <CardHeader title="URL Avatar" subtitle="Subtitle" avatar="images/ok-128.jpg" actAsExpander={true} showExpandableButton={true} /> <CardText> <Toggle toggled={this.state.expanded} onToggle={this.handleToggle} labelPosition="right" label="This toggle controls the expanded state of the component." /> </CardText> <CardMedia expandable={true} overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />} > <img src="images/nature-600-337.jpg" /> </CardMedia> <CardTitle title="Card title" subtitle="Card subtitle" expandable={true} /> <CardText expandable={true}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> <CardActions> <FlatButton label="Expand" onTouchTap={this.handleExpand} /> <FlatButton label="Reduce" onTouchTap={this.handleReduce} /> </CardActions> </Card> ); } }
fields/types/titleposition/TitlePositionField.js
nickhsine/keystone
import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import { FormInput } from 'elemental'; import cx from 'classnames'; /** * TODO: * - Custom path support */ const CENTER = 'center'; const BOTTOM = 'bottom'; const BOTTOMLEFT = 'bottom-left'; const imageSrc = { [CENTER]:'title-center', [BOTTOM]:'title-bottom', [BOTTOMLEFT]:'title-bottonLeft', 'title-upon-left': 'title-upon-left', 'title-above': 'title-above', 'header-upon': 'header-upon', 'header-above': 'header-above' }; module.exports = Field.create({ displayName: 'TitlePositionField', generateRadioGroup (nameValue, ops, value) { return ops.map((obj, i) => { const imgStyle = cx({ 'image-content': true, 'current': obj.value === value }) return ( <label key={i} className="col-4 image-container"> <input type="radio" name={nameValue} value={obj.value} /> <img className={imgStyle} src={`https://storage.googleapis.com/twreporter-multimedia/images/${imageSrc[obj.value]}.png`} onClick={() => { this.valueChanged(obj.value); }} style={{ objectFit: 'cover', width: '100%', height: '100%' }} /> </label> ); }); }, valueChanged (newValue) { // TODO: This should be natively handled by the Select component if (this.props.numeric && typeof newValue === 'string') { newValue = newValue ? Number(newValue) : undefined; } this.props.onChange({ path: this.props.path, value: newValue, }); this.setState({ active: newValue }); }, renderValue () { var selected = this.props.ops.find(option => option.value === this.props.value); return <FormInput noedit>{selected ? selected.label : null}</FormInput>; }, renderField () { // TODO: This should be natively handled by the Select component var ops = (this.props.numeric) ? this.props.ops.map(function (i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops; var value = (typeof this.props.value === 'number') ? String(this.props.value) : this.props.value; return <div className="row">{this.generateRadioGroup(this.props.path, ops, value)}</div>; }, });
V2-Node/esquenta.v2/UI/src/views/Base/Collapses/Collapses.js
leandrocristovao/esquenta
import React, { Component } from 'react'; import { Badge, Button, Card, CardBody, CardFooter, CardHeader, Col, Collapse, Fade, Row } from 'reactstrap'; class Collapses extends Component { constructor(props) { super(props); this.onEntering = this.onEntering.bind(this); this.onEntered = this.onEntered.bind(this); this.onExiting = this.onExiting.bind(this); this.onExited = this.onExited.bind(this); this.toggle = this.toggle.bind(this); this.toggleAccordion = this.toggleAccordion.bind(this); this.toggleCustom = this.toggleCustom.bind(this); this.toggleFade = this.toggleFade.bind(this); this.state = { collapse: false, accordion: [true, false, false], custom: [true, false], status: 'Closed', fadeIn: true, timeout: 300, }; } onEntering() { this.setState({ status: 'Opening...' }); } onEntered() { this.setState({ status: 'Opened' }); } onExiting() { this.setState({ status: 'Closing...' }); } onExited() { this.setState({ status: 'Closed' }); } toggle() { this.setState({ collapse: !this.state.collapse }); } toggleAccordion(tab) { const prevState = this.state.accordion; const state = prevState.map((x, index) => tab === index ? !x : false); this.setState({ accordion: state, }); } toggleCustom(tab) { const prevState = this.state.custom; const state = prevState.map((x, index) => tab === index ? !x : false); this.setState({ custom: state, }); } toggleFade() { this.setState({ fadeIn: !this.state.fadeIn }); } render() { return ( <div className="animated fadeIn"> <Row> <Col xl="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i><strong>Collapse</strong> <div className="card-header-actions"> <a href="https://reactstrap.github.io/components/collapse/" rel="noreferrer noopener" target="_blank" className="card-header-action"> <small className="text-muted">docs</small> </a> </div> </CardHeader> <Collapse isOpen={this.state.collapse} onEntering={this.onEntering} onEntered={this.onEntered} onExiting={this.onExiting} onExited={this.onExited}> <CardBody> <p> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. </p> <p> Donec molestie odio id nisi malesuada, mattis tincidunt velit egestas. Sed non pulvinar risus. Aenean elementum eleifend nunc, pellentesque dapibus arcu hendrerit fringilla. Aliquam in nibh massa. Cras ultricies lorem non enim volutpat, a eleifend urna placerat. Fusce id luctus urna. In sed leo tellus. Mauris tristique leo a nisl feugiat, eget vehicula leo venenatis. Quisque magna metus, luctus quis sollicitudin vel, vehicula nec ipsum. Donec rutrum commodo lacus ut condimentum. Integer vel turpis purus. Etiam vehicula, nulla non fringilla blandit, massa purus faucibus tellus, a luctus enim orci non augue. Aenean ullamcorper nisl urna, non feugiat tortor volutpat in. Vivamus lobortis massa dolor, eget faucibus ipsum varius eget. Pellentesque imperdiet, turpis sed sagittis lobortis, leo elit laoreet arcu, vehicula sagittis elit leo id nisi. </p> </CardBody> </Collapse> <CardFooter> <Button color="primary" onClick={this.toggle} style={{ marginBottom: '1rem' }}>Toggle</Button> <h5>Current state: {this.state.status}</h5> </CardFooter> </Card> <Card> <CardHeader> <i className="fa fa-align-justify"></i><strong>Fade</strong> <div className="card-header-actions"> <a href="https://reactstrap.github.io/components/fade/" rel="noreferrer noopener" target="_blank" className="card-header-action"> <small className="text-muted">docs</small> </a> </div> </CardHeader> <CardBody> <Fade timeout={this.state.timeout} in={this.state.fadeIn} tag="h5" className="mt-3"> This content will fade in and out as the button is pressed... </Fade> </CardBody> <CardFooter> <Button color="primary" onClick={this.toggleFade}>Toggle Fade</Button> </CardFooter> </Card> </Col> <Col xl="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Collapse <small>accordion</small> <div className="card-header-actions"> <Badge>NEW</Badge> </div> </CardHeader> <CardBody> <div id="accordion"> <Card> <CardHeader id="headingOne"> <Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(0)} aria-expanded={this.state.accordion[0]} aria-controls="collapseOne"> <h5 className="m-0 p-0">Collapsible Group Item #1</h5> </Button> </CardHeader> <Collapse isOpen={this.state.accordion[0]} data-parent="#accordion" id="collapseOne" aria-labelledby="headingOne"> <CardBody> 1. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </CardBody> </Collapse> </Card> <Card> <CardHeader id="headingTwo"> <Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(1)} aria-expanded={this.state.accordion[1]} aria-controls="collapseTwo"> <h5 className="m-0 p-0">Collapsible Group Item #2</h5> </Button> </CardHeader> <Collapse isOpen={this.state.accordion[1]} data-parent="#accordion" id="collapseTwo"> <CardBody> 2. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </CardBody> </Collapse> </Card> <Card> <CardHeader id="headingThree"> <Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(2)} aria-expanded={this.state.accordion[2]} aria-controls="collapseThree"> <h5 className="m-0 p-0">Collapsible Group Item #3</h5> </Button> </CardHeader> <Collapse isOpen={this.state.accordion[2]} data-parent="#accordion" id="collapseThree"> <CardBody> 3. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </CardBody> </Collapse> </Card> </div> </CardBody> </Card> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Collapse <small>custom accordion</small> <div className="card-header-actions"> <Badge>NEW</Badge> </div> </CardHeader> <CardBody> <div id="exampleAccordion" data-children=".item"> <div className="item"> <Button className="m-0 p-0" color="link" onClick={() => this.toggleCustom(0)} aria-expanded={this.state.custom[0]} aria-controls="exampleAccordion1"> Toggle item </Button> <Collapse isOpen={this.state.custom[0]} data-parent="#exampleAccordion" id="exampleAccordion1"> <p className="mb-3"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium lorem non vestibulum scelerisque. Proin a vestibulum sem, eget tristique massa. Aliquam lacinia rhoncus nibh quis ornare. </p> </Collapse> </div> <div className="item"> <Button className="m-0 p-0" color="link" onClick={() => this.toggleCustom(1)} aria-expanded={this.state.custom[1]} aria-controls="exampleAccordion2"> Toggle item 2 </Button> <Collapse isOpen={this.state.custom[1]} data-parent="#exampleAccordion" id="exampleAccordion2"> <p className="mb-3"> Donec at ipsum dignissim, rutrum turpis scelerisque, tristique lectus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus nec dui turpis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p> </Collapse> </div> </div> </CardBody> </Card> </Col> </Row> </div> ); } } export default Collapses;
fixtures/nesting/src/modern/App.js
cpojer/react
import React from 'react'; import {useState, Suspense} from 'react'; import {BrowserRouter, Switch, Route} from 'react-router-dom'; import HomePage from './HomePage'; import AboutPage from './AboutPage'; import ThemeContext from './shared/ThemeContext'; export default function App() { const [theme, setTheme] = useState('slategrey'); function handleToggleClick() { if (theme === 'slategrey') { setTheme('hotpink'); } else { setTheme('slategrey'); } } return ( <BrowserRouter> <ThemeContext.Provider value={theme}> <div style={{fontFamily: 'sans-serif'}}> <div style={{ margin: 20, padding: 20, border: '1px solid black', minHeight: 300, }}> <button onClick={handleToggleClick}>Toggle Theme Context</button> <br /> <Suspense fallback={<Spinner />}> <Switch> <Route path="/about"> <AboutPage /> </Route> <Route path="/"> <HomePage /> </Route> </Switch> </Suspense> </div> </div> </ThemeContext.Provider> </BrowserRouter> ); } function Spinner() { return null; }
app/timer/timer.page.js
kosich/pomodoro-pi
// @flow import React, { Component } from 'react'; import Timer from './timer.component.js'; export default class TimerPage extends Component { render() { return ( <Timer /> ); } }
src/svg-icons/av/video-label.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLabel = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 13H3V5h18v11z"/> </SvgIcon> ); AvVideoLabel = pure(AvVideoLabel); AvVideoLabel.displayName = 'AvVideoLabel'; AvVideoLabel.muiName = 'SvgIcon'; export default AvVideoLabel;
stories/components/label/index.js
NestorSegura/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import Label from 'shared/components/label/label'; storiesOf('shared/components/label', module) .add('Default', () => ( <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'row', justifyContent: 'center', }} > <input type="checkbox" id="check" /> <Label htmlFor="check" style={{ marginLeft: '16px' }} > clickable </Label> </div> ));
www/js/components/Sidebar.js
grant/CSE-The-Game
import React, { Component } from 'react'; const sidebarItems = [ { id: 'item1', name: 'Item 1', subitems: [{ id: 'subitem1', name: 'Subitem 1', }, { id: 'subitem2', name: 'Sub 2', subitems: [{ id: 'subsubitem1', name: 'sub sub item 1', }], }], }, { id: 'item2', name: 'Item 2', }, ]; /** * A list of buttons on the left side of the screen. */ class Sidebar extends Component { static propTypes = {}; constructor() { super(); this.state = { // value at index _n_ is the selection (index of item selected in that column) at column _n_ // so [2, 0] would mean column[0][2] and column[1][0] are selected. selection: [], }; } onItemClick(id:string, columnIndex:number, rowIndex:number) { // Update the selection to reflect the click let selection = this.state.selection; let selectionDepth = selection.length; if (columnIndex === selectionDepth) { // If clicked on columnIndex at selectionDepth, expand deeper selection selection.push(rowIndex); } else if (columnIndex < selectionDepth) { if (selection.length - 1 === columnIndex && selection[columnIndex] === rowIndex) { // Deselect deepest selection selection.pop(); } else { // Unselect all up until column index selection.length = columnIndex; // Push new shallow selection selection.push(rowIndex); } } // If clicked on selection, disable the selection // Update the selection this.setState({ selection: selection, }); } render() { let state = this.state; // Subcomponents let createSidebarItem = (sidebarItem:Object, columnIndex:number, rowIndex:number) => { let id = sidebarItem.id; let selected = (columnIndex < state.selection.length && state.selection[columnIndex] === rowIndex) ? 'selected' : ''; return ( <li className={`${id} sidebarItem ${selected}`} onClick={this.onItemClick.bind(this, id, columnIndex, rowIndex)} > <img className='icon' src={`img/sidebar/${id}.png`}/> <span className='title'> {sidebarItem.name} </span> </li> ); }; // Populate column data (note the <=) let sidebarColumnData = []; let currentColumn = sidebarItems; for (let columnIndex = 0; columnIndex <= state.selection.length; ++columnIndex) { // Push current column if exists if (currentColumn) { sidebarColumnData.push(currentColumn); } // Look at next selection column if (columnIndex != state.selection.length) { currentColumn = currentColumn[state.selection[columnIndex]].subitems; } } return ( <ul className="Sidebar" > {sidebarColumnData.map((columnData, columnIndex) => { return ( <div className={`column ${columnIndex}`}> {columnData.map(function (columnDatum, rowIndex) { return createSidebarItem(columnDatum, columnIndex, rowIndex); })} </div> ); })} </ul> ); } } export default Sidebar;
App/Client/Component/person.js
qianyuchang/React-Chat
import React from 'react' import { mockData } from './mockData' const ArrowIcon=React.createClass({ render:function(){ return( <i className="arrow fa fa-angle-right"></i> ); } }); const QrcodeIcon=React.createClass({ render:function(){ return( <i className="qrcode fa fa-qrcode"></i> ); } }); const SettingItem=React.createClass({ render:function () { return( <li className="settingItem"> <span className="icon"><i className={this.props.icon}></i></span> <span className="settingName">{this.props.children}</span> <ArrowIcon/> </li>) } }); const SocialGroup=React.createClass({ render:function () { return( <ul className="socialGroup tabGroup"> <SettingItem icon="fa fa-picture-o">相册</SettingItem> </ul> ) } }); const SettingGroup=React.createClass({ render:function () { return( <div className="settingGroup tabGroup"> <SettingItem icon="fa fa-cog">设置</SettingItem> </div> ); } }); const Account=React.createClass({ getInitialState:function(){ return{ data:{} } }, componentDidMount:function(){ this.setState({ data:mockData.AccountInfo }); }, render:function(){ var that=this; return( <div className="account"> <div className="headImage"><img src={that.state.data.headImage} width="60"/></div> <div className="accountInfo"> <div className="nickName">{that.state.data.nickName}</div> <div className="accountNumber">{that.state.data.token}</div> </div> <QrcodeIcon/> <ArrowIcon/> </div> ); } }); const Person=React.createClass({ render:function(){ return( <div className="person"> <Account/> <SocialGroup/> <SettingGroup/> </div> ); } }); export default Person;
src/collections/Form/FormSelect.js
aabustamante/Semantic-UI-React
import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' import Select from '../../addons/Select' import FormField from './FormField' /** * Sugar for <Form.Field control={Select} />. * @see Form * @see Select */ function FormSelect(props) { const { control } = props const rest = getUnhandledProps(FormSelect, props) const ElementType = getElementType(FormSelect, props) return <ElementType {...rest} control={control} /> } FormSelect._meta = { name: 'FormSelect', parent: 'Form', type: META.TYPES.COLLECTION, } FormSelect.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** A FormField control prop. */ control: FormField.propTypes.control, } FormSelect.defaultProps = { as: FormField, control: Select, } export default FormSelect
video-player/src/components/SearchBar.js
HeroSizy/Modern-react-with-redux
import React from 'react' import { Component } from 'react' class SearchBar extends Component { constructor(props){ super(props); //only can manipulate state using '=' //in constructor this.state = { term: '' }; //to not lose context, use bind this.onInputChange = this.onInputChange.bind(this); } onInputChange(event) { const term = event.target.value; //event.target.value => ge t the value //on the element who triggers the event // console.log(event.target.value); this.setState({term}); this.props.onSearchTermChange(term); } render() { return( <div className="search-bar"> <input value = {this.state.term} onChange={this.onInputChange} /> <br /> input: {this.state.term} </div> ); } } export default SearchBar
packages/material-ui-icons/src/InsertLink.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z" /></g> , 'InsertLink');
sample-app/EmployeeDirectory/index.ios.js
TGPSKI/cavy
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import { Provider } from 'react-redux'; import { reduxForm } from 'redux-form'; import { Tester, TestHookStore } from 'cavy'; import EmployeeDirectoryApp from 'App/EmployeeDirectoryApp'; import GLOBAL from 'Helpers/globals.js'; if (GLOBAL.TEST_ENABLED) { var testHookStore = new TestHookStore(); var testSuites = require('Specs/itSuites.js'); var testSuitesArray = [testSuites.filterEmployeeList, testSuites.tapAndEmail]; } const { store } = () => { return { form: reduxForm() }; }; class AppWrapper extends Component { render() { if (GLOBAL.TEST_ENABLED) { return ( <Provider store={store}> <Tester suites={testSuitesArray} store={testHookStore} waitTime={1000} testStartDelay={1000} consoleLog={true} reporter={true} reRender={true} reduxStore={store} > <EmployeeDirectoryApp /> </Tester> </Provider> ); } else { return ( <Provider store={store}> <EmployeeDirectoryApp /> </Provider> ); } } } AppRegistry.registerComponent('EmployeeDirectory', () => AppWrapper);
fields/types/azurefile/AzureFileColumn.js
asifiqbal84/keystone
import React from 'react'; var AzureFileColumn = React.createClass({ renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; return <a href={value.url} target='_blank'>{value.url}</a>; }, render () { return ( <td className="ItemList__col"> <div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div> </td> ); } }); module.exports = AzureFileColumn;
src/js/ui/components/welcome/signUpForm.js
heartnotes/heartnotes
import $ from 'jquery'; import _ from 'lodash'; import React from 'react'; import Button from '../button'; import ExternalLink from '../externalLink'; import ProgressButton from '../progressButton'; import EmailInput from '../emailInput'; import NewPasswordInput from '../newPasswordInput'; import UserShouldRememberPasswordDialog from '../userShouldRememberPasswordDialog'; import { connectRedux, routing } from '../../helpers/decorators'; import * as Detect from '../../../utils/detect'; const TERMS_URL = Detect.serverHost() + '/terms-and-conditions'; var Component = React.createClass({ propTypes: { onCreate: React.PropTypes.func.isRequired, progressCheckVar: React.PropTypes.object.isRequired, createButtonText: React.PropTypes.string, }, getDefaultProps: function() { return { createButtonText: 'Sign up', }; }, getInitialState: function() { return { id: null, password: null, } }, render: function() { let { creating } = this.props.data.diary; var buttonAttrs = { defaultProgressMsg: 'Signing up...', checkVar: this.props.progressCheckVar, onClick: this._createNew, }; if ( !this.state.terms || !_.get(this.state.password, 'length') || !_.get(this.state.id, 'length') ) { buttonAttrs.disabled = true; } return ( <div className="sign-up-form"> <form onSubmit={this._createNew}> <div className="input-fields row"> <EmailInput onChange={this._setId} disabled={this.props.progressCheckVar.inProgress} tabIndex={1} /> </div> <div className="input-fields row"> <NewPasswordInput onChange={this._setPassword} requiredStrength={0} centeredStrengthMeter={true} disabled={this.props.progressCheckVar.inProgress} tabIndex={2} /> </div> <div className="row terms"> <input type="checkbox" onChange={this._toggleTerms} /> <span> I agree to the <ExternalLink href={TERMS_URL}>terms and conditions</ExternalLink>. </span> </div> <div className="action row"> <ProgressButton {...buttonAttrs}>{this.props.createButtonText}</ProgressButton> </div> </form> <UserShouldRememberPasswordDialog password={this.state.password} ref="rememberDialog" /> </div> ); }, _setPassword: function(password) { this.setState({ password: password }); }, _setId: function(id) { this.setState({ id: id, }); }, _toggleTerms: function(e) { let checked = $(e.currentTarget).is(':checked'); this.setState({ terms: !!checked, }); }, _createNew: function(e) { e.preventDefault(); this.refs.rememberDialog.ask((shouldProceed) => { if (shouldProceed) { this.props.onCreate( this.state.id, this.state.password ) .then(() => { this.setState(this.getInitialState()); }); } }); }, }); module.exports = connectRedux([ 'createDiary' ])(Component);
src/index.js
shibe97/react-awesome-modal
import React, { Component } from 'react'; import style from './style.js'; export default class Modal extends Component { constructor(props) { super(props); let effect = props.effect || 'fadeInDown'; this.setSize(effect); this.state = { visible : props.visible, style : style[effect] } } componentWillReceiveProps({visible, effect = 'fadeInDown'}) { this.setState({ visible : visible }); this.setSize(effect); this.setStyles(effect); } setStyles(effect){ if (this.props && this.props.styles) { style[effect].panel = { ...style[effect].panel, ...this.props.styles }; } } setSize(effect) { if (this.props && this.props.width) { if (this.props.width.charAt(this.props.width.length-1) === '%') { // Use Percentage const width = this.props.width.slice(0, -1); style[effect].panel.width = width + '%'; } else if (this.props.width.charAt(this.props.width.length-1) === 'x') { // Use Pixels const width = this.props.width.slice(0, -2); style[effect].panel.width = width + 'px'; } else { // Defaults style[effect].panel.width = this.props.width + 'px'; } } if (this.props && this.props.height) { if (this.props.height.charAt(this.props.height.length-1) === '%') { // Use Percentage const height = this.props.height.slice(0, -1); style[effect].panel.height = height + 'vh'; } else if (this.props.height.charAt(this.props.height.length-1) === 'x') { // Use Pixels const height = this.props.height.slice(0, -2); style[effect].panel.height = height + 'px'; } else { // Defaults style[effect].panel.height = this.props.height + 'px'; } } } render() { return ( <div> <div style={this.state.visible ? this.state.style.container : this.state.style.containerHidden}> <div style={this.state.visible ? {...this.state.style.panel} : this.state.style.panelHidden}> {this.props.children} </div> <div style={this.state.visible ? this.state.style.mask : this.state.style.maskHidden} onClick={this.props.onClickAway ? this.props.onClickAway : null} /> </div> </div> ); } }
chrome/extension/inject.js
CKPalk/PA-POC-Video-Contoller
import React from 'react' import ReactDOM from 'react-dom' import VideoRoot from '../../app/containers/VideoRoot' import { getUid } from '../../app/utils/helpers' import { getState, onStateChange } from '../../app/utils/localStorage' /** * Whether this youtube video is currently an advertisement. * @param {Object} video A HTML5 video element * @return {Boolean} Whether the user is watching an ad */ async function videoIsAd(video) { return !!video } function findBestContainer(video) { const isGoodContainer = ({ offsetWidth, offsetHeight }) => ( offsetWidth === video.offsetWidth && offsetHeight === video.offsetHeight ) let bestContainer = video.parentElement let container = video.parentElement while (container) { if (isGoodContainer(container)) { bestContainer = container } container = container.parentElement } return bestContainer } function renderOverlayForVideo(video) { const mount = document.createElement('div') mount.style.position = 'absolute' mount.style.top = 0 mount.style.pointerEvents = 'none' findBestContainer(video).appendChild(mount) const adID = getUid() const renderOverlayWithCurrentState = () => { getState() .then(state => { ReactDOM.render( <VideoRoot appState={state} video={video} adID={adID} />, mount ) }) } renderOverlayWithCurrentState() // When the state changes, we render our overlay with the updated state onStateChange(renderOverlayWithCurrentState) } function handleVideo(video) { video.onloadstart = () => { handleVideo(video) } if (videoIsAd(video)) { renderOverlayForVideo(video) } } function locateAndHandleVideos() { const allVideos = Array(...document.getElementsByTagName('video')) if (allVideos.length === 0) { setTimeout(locateAndHandleVideos, 500) return } allVideos.forEach(video => { video.crossOrigin = 'anonymous' if (video.readyState === 4) { handleVideo(video) } else { video.onloadeddata = () => { video.onloadeddata = () => {} handleVideo(video) } } }) } window.addEventListener('load', locateAndHandleVideos)
web/app/containers/RepoListItem/index.js
agapic/TwitchChatStreaming
/** * RepoListItem * * Lists the name and the issue count of a repository */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { FormattedNumber } from 'react-intl'; import IssueIcon from './IssueIcon'; import IssueLink from './IssueLink'; import ListItem from 'components/ListItem'; import RepoLink from './RepoLink'; import Wrapper from './Wrapper'; import { selectCurrentUser } from 'containers/App/selectors'; export class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; let nameprefix = ''; // If the repository is owned by a different person than we got the data for // it's a fork and we should show the name of the owner if (item.owner.login !== this.props.currentUser) { nameprefix = `${item.owner.login}/`; } // Put together the content of the repository const content = ( <Wrapper> <RepoLink href={item.html_url} target="_blank"> {nameprefix + item.name} </RepoLink> <IssueLink href={`${item.html_url}/issues`} target="_blank"> <IssueIcon /> <FormattedNumber value={item.open_issues_count} /> </IssueLink> </Wrapper> ); // Render the content into a list item return ( <ListItem key={`repo-list-item-${item.full_name}`} item={content} /> ); } } RepoListItem.propTypes = { item: React.PropTypes.object, currentUser: React.PropTypes.string, }; export default connect(createSelector( selectCurrentUser(), (currentUser) => ({ currentUser }) ))(RepoListItem);
tp-4/euge/src/pages/posts/Listado.js
jpgonzalezquinteros/sovos-reactivo-2017
import React from 'react'; import PropTypes from 'prop-types'; import { Layout, Table, Button } from 'antd'; const { Content } = Layout; const columns = [{ title: 'title', dataIndex: 'title', width: '30%', }, { title: 'body', dataIndex: 'body', width: '20%', }]; class Listado extends React.Component { state = { showPostForm: false, postSeleccionado: {} } componentWillMount(){ this.props.actions.fetchPosts(); } handlePlusClick = () => { this.setState({ postSeleccionado: null }); this.setState({ showPostForm: true }); } handleCloseParametrosForm= () => { this.setState({ showPostForm: false }); } render() { return ( <div className="content-inner"> <Layout > <Content> <Button className="editable-add-btn" onClick={this.handlePlusClick}>Nuevo Post</Button> <Table columns={columns} rowKey={record => record.id} dataSource={this.props.posts} loading={this.props.trabajando} /> </Content> </Layout> </div> ); } } Listado.propTypes = { trabajando: PropTypes.bool.isRequired, posts:PropTypes.array.isRequired, actions: PropTypes.shape({ fetchPosts: PropTypes.func, guardarPost: PropTypes.func, eliminarPost: PropTypes.func, }).isRequired, }; Listado.defaultProps = { trabajando: false, posts:[] }; export default Listado;
src/js/components/gallery/ImportAlbumPopup.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { FACEBOOK_PHOTOS_SCOPE, GOOGLE_PHOTOS_SCOPE } from '../../constants/Constants'; import translate from '../../i18n/Translate'; @translate('ImportAlbumPopup') export default class ImportAlbumPopup extends Component { static propTypes = { onAlbumClickHandler : PropTypes.func, onFileUploadClickHandler: PropTypes.func, contentRef: PropTypes.func, // Injected by @translate: strings : PropTypes.object }; onResourceClick(resource, scope) { this.props.onAlbumClickHandler(resource, scope); } render() { const {contentRef, strings} = this.props; return ( <div className="popup popup-import-album tablet-fullscreen"> <div ref={contentRef} className="content-block"> <div className="title">{strings.importAlbum}</div> <br /> <div className="social-icons-row-wrapper social-box"> <div className="icon-wrapper text-facebook" onClick={this.onResourceClick.bind(this, 'facebook', FACEBOOK_PHOTOS_SCOPE)}> <span className="icon icon-facebook"></span> </div> <div className="icon-wrapper text-google" onClick={this.onResourceClick.bind(this, 'google', GOOGLE_PHOTOS_SCOPE)}> <span className="icon icon-google"></span> </div> </div> <div className="upload-wrapper" onClick={this.props.onFileUploadClickHandler}> <div className="button button-fill button-round"> <span className="icon icon-uploadthin"></span> <span className="">{strings.uploadFromDevice}</span> </div> </div> </div> </div> ); } } ImportAlbumPopup.defaultProps = { strings: { close : 'Close', importAlbum : 'Import an album', uploadFromDevice: 'Upload from device' } };
12_ReactJS Fundamentals/01_contacter/src/index.js
akkirilov/SoftUniProject
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
app/javascript/mastodon/features/ui/components/media_modal.js
imas/mastodon
import React from 'react'; import ReactSwipeableViews from 'react-swipeable-views'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Video from 'mastodon/features/video'; import classNames from 'classnames'; import { defineMessages, injectIntl } from 'react-intl'; import IconButton from 'mastodon/components/icon_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImageLoader from './image_loader'; import Icon from 'mastodon/components/icon'; import GIFV from 'mastodon/components/gifv'; import { disableSwiping } from 'mastodon/initial_state'; import Footer from 'mastodon/features/picture_in_picture/components/footer'; import { getAverageFromBlurhash } from 'mastodon/blurhash'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, next: { id: 'lightbox.next', defaultMessage: 'Next' }, }); export const previewState = 'previewMediaModal'; export default @injectIntl class MediaModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, statusId: PropTypes.string, index: PropTypes.number.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onChangeBackgroundColor: PropTypes.func.isRequired, currentTime: PropTypes.number, autoPlay: PropTypes.bool, volume: PropTypes.number, }; static contextTypes = { router: PropTypes.object, }; state = { index: null, navigationHidden: false, zoomButtonHidden: false, }; handleSwipe = (index) => { this.setState({ index: index % this.props.media.size }); } handleTransitionEnd = () => { this.setState({ zoomButtonHidden: false, }); } handleNextClick = () => { this.setState({ index: (this.getIndex() + 1) % this.props.media.size, zoomButtonHidden: true, }); } handlePrevClick = () => { this.setState({ index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size, zoomButtonHidden: true, }); } handleChangeIndex = (e) => { const index = Number(e.currentTarget.getAttribute('data-index')); this.setState({ index: index % this.props.media.size, zoomButtonHidden: true, }); } handleKeyDown = (e) => { switch(e.key) { case 'ArrowLeft': this.handlePrevClick(); e.preventDefault(); e.stopPropagation(); break; case 'ArrowRight': this.handleNextClick(); e.preventDefault(); e.stopPropagation(); break; } } componentDidMount () { window.addEventListener('keydown', this.handleKeyDown, false); if (this.context.router) { const history = this.context.router.history; history.push(history.location.pathname, previewState); this.unlistenHistory = history.listen(() => { this.props.onClose(); }); } this._sendBackgroundColor(); } componentDidUpdate (prevProps, prevState) { if (prevState.index !== this.state.index) { this._sendBackgroundColor(); } } _sendBackgroundColor () { const { media, onChangeBackgroundColor } = this.props; const index = this.getIndex(); const blurhash = media.getIn([index, 'blurhash']); if (blurhash) { const backgroundColor = getAverageFromBlurhash(blurhash); onChangeBackgroundColor(backgroundColor); } } componentWillUnmount () { window.removeEventListener('keydown', this.handleKeyDown); if (this.context.router) { this.unlistenHistory(); if (this.context.router.history.location.state === previewState) { this.context.router.history.goBack(); } } this.props.onChangeBackgroundColor(null); } getIndex () { return this.state.index !== null ? this.state.index : this.props.index; } toggleNavigation = () => { this.setState(prevState => ({ navigationHidden: !prevState.navigationHidden, })); }; handleStatusClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/statuses/${this.props.statusId}`); } } render () { const { media, statusId, intl, onClose } = this.props; const { navigationHidden } = this.state; const index = this.getIndex(); const leftNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}><Icon id='chevron-left' fixedWidth /></button>; const rightNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}><Icon id='chevron-right' fixedWidth /></button>; const content = media.map((image) => { const width = image.getIn(['meta', 'original', 'width']) || null; const height = image.getIn(['meta', 'original', 'height']) || null; if (image.get('type') === 'image') { return ( <ImageLoader previewSrc={image.get('preview_url')} src={image.get('url')} width={width} height={height} alt={image.get('description')} key={image.get('url')} onClick={this.toggleNavigation} zoomButtonHidden={this.state.zoomButtonHidden} /> ); } else if (image.get('type') === 'video') { const { currentTime, autoPlay, volume } = this.props; return ( <Video preview={image.get('preview_url')} blurhash={image.get('blurhash')} src={image.get('url')} width={image.get('width')} height={image.get('height')} frameRate={image.getIn(['meta', 'original', 'frame_rate'])} currentTime={currentTime || 0} autoPlay={autoPlay || false} volume={volume || 1} onCloseVideo={onClose} detailed alt={image.get('description')} key={image.get('url')} /> ); } else if (image.get('type') === 'gifv') { return ( <GIFV src={image.get('url')} width={width} height={height} key={image.get('preview_url')} alt={image.get('description')} onClick={this.toggleNavigation} /> ); } return null; }).toArray(); // you can't use 100vh, because the viewport height is taller // than the visible part of the document in some mobile // browsers when it's address bar is visible. // https://developers.google.com/web/updates/2016/12/url-bar-resizing const swipeableViewsStyle = { width: '100%', height: '100%', }; const containerStyle = { alignItems: 'center', // center vertically }; const navigationClassName = classNames('media-modal__navigation', { 'media-modal__navigation--hidden': navigationHidden, }); let pagination; if (media.size > 1) { pagination = media.map((item, i) => ( <button key={i} className={classNames('media-modal__page-dot', { active: i === index })} data-index={i} onClick={this.handleChangeIndex}> {i + 1} </button> )); } return ( <div className='modal-root__modal media-modal'> <div className='media-modal__closer' role='presentation' onClick={onClose} > <ReactSwipeableViews style={swipeableViewsStyle} containerStyle={containerStyle} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleTransitionEnd} index={index} disabled={disableSwiping} > {content} </ReactSwipeableViews> </div> <div className={navigationClassName}> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={40} /> {leftNav} {rightNav} <div className='media-modal__overlay'> {pagination && <ul className='media-modal__pagination'>{pagination}</ul>} {statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />} </div> </div> </div> ); } }
modules/gob-web/modules/course-table/year.js
hawkrives/gobbldygook
// @flow import React from 'react' import {connect} from 'react-redux' import {FlatButton} from '../../components/button' import Semester from './semester' import {findFirstAvailableSemester} from '../../helpers/find-first-available-semester' import {expandYear, semesterName} from '@gob/school-st-olaf-college' import {Student, Schedule} from '@gob/object-student' import * as theme from '../../theme' import { changeStudent, type ChangeStudentFunc, } from '../../redux/students/actions/change' import styled from 'styled-components' const Container = styled.div` margin-bottom: var(--page-edge-padding); ` const Header = styled.header` ${theme.noSelect}; margin: 0; display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; font-variant-numeric: tabular-nums; line-height: 1em; font-weight: 500; font-size: 0.9em; ` const TitleText = styled.h1` ${theme.headingNeutral}; white-space: nowrap; flex: 1; margin-left: calc(var(--semester-spacing) + var(--semester-side-padding)); ` const TitleButton = styled(FlatButton)` transition: 0.15s; min-height: 0; padding: 0 0.5em; text-transform: none; font-weight: 400; color: var(--gray-500); & + & { margin-left: 0.1em; } ` const RemoveYearButton = styled(TitleButton)` &:hover { color: var(--red-500); background-color: var(--red-50); border: solid 1px var(--red-500); } ` const SemesterList = styled.div` flex: 1; display: flex; flex-flow: row wrap; ` const canAddSemester = (nextAvailableSemester?: number) => { return nextAvailableSemester != null && nextAvailableSemester <= 5 } type Props = { student: Student, year: number, changeStudent: ChangeStudentFunc, } class Year extends React.Component<Props> { addSemester = () => { let nextAvailableSemester = findFirstAvailableSemester( [...this.props.student.schedules.values()], this.props.year, ) let s = this.props.student.addSchedule( new Schedule({ year: this.props.year, semester: nextAvailableSemester, index: 1, active: true, }), ) this.props.changeStudent(s) } removeYear = () => { let s = this.props.student.destroySchedulesForYear(this.props.year) this.props.changeStudent(s) } render() { let {student, year} = this.props let schedules = student.schedules .filter(s => s.active === true && s.year === year) .sortBy(s => s.getTerm()) .toList() let niceYear = expandYear(year) let nextSemester = findFirstAvailableSemester( [...schedules.values()], year, ) let isAddSemesterDisabled = !canAddSemester(nextSemester) return ( <Container> <Header> <TitleText>{niceYear}</TitleText> <> {!isAddSemesterDisabled && nextSemester != null && ( <TitleButton type="flat" title="Add Semester" onClick={this.addSemester} > Add ‘{semesterName(nextSemester)}’ </TitleButton> )} <RemoveYearButton type="flat" title={`Remove the year ${niceYear}`} onClick={this.removeYear} > Remove Year </RemoveYearButton> </> </Header> <SemesterList> {schedules.map(schedule => ( <Semester key={schedule.semester} schedule={schedule} semester={schedule.semester} student={student} year={year} /> ))} </SemesterList> </Container> ) } } const connected = connect( undefined, {changeStudent}, )(Year) export {connected as Year}
blueocean-material-icons/src/js/components/svg-icons/content/create.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentCreate = (props) => ( <SvgIcon {...props}> <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/> </SvgIcon> ); ContentCreate.displayName = 'ContentCreate'; ContentCreate.muiName = 'SvgIcon'; export default ContentCreate;