path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/handbook/scouting_values.js
khayyamj/thunderbirds_troop51
import React from 'react'; export default function () { return ( <div> <p className="p1"><span className="s1"><strong>Scouting Values</strong></span></p> <p className="p2">&nbsp;</p> <p className="p3"><span className="s1">All scouts and leaders agree to abide by the Scout Oath, the Scout Law and the Outdoor Code.<span className="Apple-converted-space">&nbsp; </span>Moral, social and religious values are important parts of the scouting program, even though we do not promote a specific faith.</span></p> <p className="p4">&nbsp;</p> <p className="p3"><span className="s1">One of the purposes of Scouting is to transfer its moral values in your own life. As a result the Scout Oath, Law, Motto, and Slogan should not only be memorized but regularly pondered. Make it a goal to practice one of the principles from them each day.</span></p> <p className="p4">&nbsp;</p> <p className="p3"><span className="s1">Being a Scout also means that you keep the <strong>highest standards of personal conduct</strong>, both as to <em>personal morality </em>and in your <em>interactions with others</em>. You should discipline yourself so that others have no need to. You should be enthusiastic and helpful when it is time to&nbsp;</span><span className="s1">participate in games as well as when it is time to clean up. If you do these things you have true Scout Spirit.&nbsp;</span></p> </div> ) }
docs/src/app/components/pages/components/TimePicker/ExampleSimple.js
xmityaz/material-ui
import React from 'react'; import TimePicker from 'material-ui/TimePicker'; const TimePickerExampleSimple = () => ( <div> <TimePicker hintText="12hr Format" /> <TimePicker format="24hr" hintText="24hr Format" /> <TimePicker disabled={true} format="24hr" hintText="Disabled TimePicker" /> </div> ); export default TimePickerExampleSimple;
src/routes/login/index.js
miaoji/guojibackend
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Button, Row, Form, Input } from 'antd' import { config } from '../../utils' import styles from './index.less' const FormItem = Form.Item const Login = ({ login, dispatch, form: { getFieldDecorator, validateFieldsAndScroll, }, }) => { const { loginLoading } = login function handleOk () { validateFieldsAndScroll((errors, values) => { if (errors) { return } dispatch({ type: 'login/login', payload: values }) }) } return ( <div> <canvas id='background'></canvas> <div className={styles.form}> <div className={styles.logo}> <img alt={'logo'} src={config.logo} /> <span>{config.name}</span> </div> <form> <FormItem hasFeedback> {getFieldDecorator('username', { rules: [ { required: true, message: '请输入用户名', }, ], })(<Input size="large" onPressEnter={handleOk} placeholder="用户名" />)} </FormItem> <FormItem hasFeedback> {getFieldDecorator('password', { rules: [ { required: true, message: '请输入密码', }, ], })(<Input size="large" type="password" onPressEnter={handleOk} placeholder="密码" />)} </FormItem> <Row> <Button type="primary" size="large" onClick={handleOk} loading={loginLoading}> 登录 </Button> </Row> </form> </div> </div> ) } Login.propTypes = { form: PropTypes.object, login: PropTypes.object, dispatch: PropTypes.func, } export default connect(({ login }) => ({ login }))(Form.create()(Login))
src/components/sidebar/DepartmentButton.react.js
EaglesoftZJ/iGem_Web
/* * Copyright (C) 2015-2016 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import classNames from 'classnames'; import { Container } from 'flux/utils'; import { FormattedMessage } from 'react-intl'; import Tooltip from 'rc-tooltip'; import EventListener from 'fbjs/lib/EventListener'; import { KeyCodes } from '../../constants/ActorAppConstants'; import DepartmentActionCreators from '../../actions/DepartmentActionCreators'; import DepartmentStore from '../../stores/DepartmentStore'; import history from '../../utils/history'; class QuickSearchButton extends Component { static getStores() { return [DepartmentStore]; } static calculateState() { return { show: DepartmentStore.getState().department_show } } constructor(props) { super(props); this.openQuickSearch = this.openQuickSearch.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); } componentDidMount() { this.setListeners(); } componentWillUnmount() { this.cleanListeners(); } setListeners() { this.cleanListeners(); this.listeners = [ EventListener.listen(document, 'keydown', this.handleKeyDown) ]; } cleanListeners() { if (this.listeners) { this.listeners.forEach((listener) => listener.remove()); this.listeners = null; } } handleKeyDown(event) { if (event.keyCode === KeyCodes.K && event.metaKey) { event.stopPropagation(); event.preventDefault(); this.openQuickSearch() } } openQuickSearch() { // DepartmentActionCreators.show(); history.push('/im/department'); } render() { const { show } = this.state; console.log('show', show); var className = classNames({selected: show}); return ( <footer className="sidebar__department"> <Tooltip placement="top" mouseEnterDelay={0.15} mouseLeaveDelay={0} overlay={<FormattedMessage id="tooltip.department"/>}> <a onClick={this.openQuickSearch} className={className}> <div className="icon-holder"><i className="material-icons">search</i></div> <FormattedMessage id="button.department"/> </a> </Tooltip> </footer> ) } } export default Container.create(QuickSearchButton);
src/svg-icons/action/done.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDone = (props) => ( <SvgIcon {...props}> <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/> </SvgIcon> ); ActionDone = pure(ActionDone); ActionDone.displayName = 'ActionDone'; ActionDone.muiName = 'SvgIcon'; export default ActionDone;
app/components/App.js
mAustinKos/Random-Quote-Generator
import React from 'react'; import QuoteDiv from './QuoteDiv.js'; export default class App extends React.Component { render() { return ( <div className='body'> <div className='Title'> <h1><a href="https://www.whitehouse.gov/">President Donald Trump</a> Quote Generator </h1> </div> <QuoteDiv /> </div> ); } }
components/latest-sermon.js
hillcitymnag/www.hillcitymnag.church
import React from 'react' import css, {merge} from 'next/css' import {color, mediaQuery, pseudo} from '../shared/constants' import {btn, link} from '../shared/styles' export default props => { const {latestSermon} = props const {src} = latestSermon.enclosure const latestSermonHref = src.slice(0, src.length - 4) return ( <div className="col-md-6" {...main}> <h2 {...header}>Latest Sermon</h2> <img alt="Small Town Preacher" src="static/img/light-logo.svg" {...artwork} /> <h4 {...date}>{latestSermon.date}</h4> <a href={latestSermonHref} {...titleLink}> <h3 {...title}>{latestSermon.title}</h3> </a> <p {...description}>{latestSermon.description.replace(/<\/?p>/g, '')}</p> <a className="btn btn-default btn-lg" href={latestSermonHref} {...btn}> <i className="fa fa-play-circle-o fa-lg" aria-hidden="true" {...icon} /> Listen </a> <a href="https://www.buzzsprout.com/140598" {...merge(link, allSermons)}> All sermons › </a> </div> ) } const main = css({ margin: '0 auto', maxWidth: 450, [mediaQuery.md]: { paddingRight: 50, borderRight: '1px solid #eee', maxWidth: 'none' } }) const header = css({ margin: 0, fontFamily: 'proxima-nova-condensed, sans-serif', fontSize: 55, fontWeight: 900, lineHeight: 1, textAlign: 'center', textTransform: 'uppercase', [mediaQuery.md]: { padding: '0 15%', fontSize: 66 } }) const artwork = css({ margin: '30px auto', marginBottom: 40, maxWidth: '100%', maxHeight: 225, [mediaQuery.md]: {maxHeight: 300} }) const date = css({ margin: 0, color: color.lightGreen, fontFamily: 'proxima-nova-condensed, sans-serif', fontSize: 22, fontWeight: '900', textTransform: 'uppercase' }) const titleHover = css({ color: color.darkGray, textDecoration: 'none' }) const titleLink = css({ color: color.darkGray, [pseudo.focus]: titleHover, [pseudo.hover]: titleHover }) const title = css({ marginTop: 0, fontFamily: 'reklame-script, sans-serif', fontSize: 44, fontWeight: 500 }) const description = css({ marginBottom: 20, fontSize: 18, fontWeight: 300, lineHeight: 1.25 }) const icon = css({ marginRight: 7 }) const allSermons = css({ position: 'relative', display: 'inline-block', margin: '0 16px', fontSize: 16, top: 3 })
pages/work/air.js
k97/node-slasher-app
import React from 'react'; import axios from 'axios'; import ReactMarkdown from 'react-markdown'; import mediumZoom from 'medium-zoom'; import Layout from '../../components/Layout/index'; import ProjectTitle from '../../components/Work/ProjectTitle'; import EditProject from '../../components/Work/EditProject'; import UILoader from '../../components/Home/UILoader'; class ProjectAir extends React.Component { constructor(props) { super(props); this.state = { project: {}, loading: true }; this.fetchProjectDetail = this.fetchProjectDetail.bind(this); } componentDidMount() { this.fetchProjectDetail(); } fetchProjectDetail() { axios.get('/api/project/air').then(response => { this.setState({ project: response.data, loading: false }); mediumZoom('.work-detail-wrapper img',{ margin: 70 }) }).catch(error => { this.setState({ loading: false }); }); } render() { const content = this.state.project.content; return ( <Layout title={`Airport Info Repo - Karthik`}> <div className='body-content'> <ProjectTitle heading="Airport Info Repo" date="September, 2016" bgColor="bg-air" /> <section className='w-100 ph2 ph3-m ph4-l'> <div className='cf pa2'> <section className="work-detail-wrapper fw4 measure-wide db center f4 lh-copy black-60 ft-serif"> <UILoader loading={this.state.loading} /> {content ? <ReactMarkdown source={content} /> : ''} </section> </div> </section> <EditProject project={this.state.project} /> </div> </Layout> ); } } export default ProjectAir
examples/universal/server/server.js
bjfletcher/redux
/* eslint-disable no-console, no-use-before-define */ import path from 'path'; import Express from 'express'; import qs from 'qs'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; import { fetchCounter } from '../common/api/counter'; const app = new Express(); const port = 3000; // Use this middleware to server up static files built into dist app.use(require('serve-static')(path.join(__dirname, '../dist'))); // This is fired every time the server side receives a request app.use(handleRender); function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query); const counter = parseInt(params.counter, 10) || apiResult || 0; // Compile an initial state const initialState = { counter }; // Create a new Redux store instance const store = configureStore(initialState); // Render the component to a string const html = React.renderToString( <Provider store={store}> { () => <App/> } </Provider>); // Grab the initial state from our Redux store const finalState = store.getState(); // Send the rendered page back to the client res.send(renderFullPage(html, finalState)); }); } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; </script> <script src="/bundle.js"></script> </body> </html> `; } app.listen(port, (error) => { if (error) { console.error(error); } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`); } });
Console/app/node_modules/rc-calendar/es/calendar/OkButton.js
RisenEsports/RisenEsports.github.io
import React from 'react'; export default function OkButton(_ref) { var prefixCls = _ref.prefixCls, locale = _ref.locale, okDisabled = _ref.okDisabled, onOk = _ref.onOk; var className = prefixCls + "-ok-btn"; if (okDisabled) { className += " " + prefixCls + "-ok-btn-disabled"; } return React.createElement( "a", { className: className, role: "button", onClick: okDisabled ? null : onOk }, locale.ok ); }
local/share/nvim/templates/=template=react-class-component.js
leonfeng/dotfiles
import React, { Component } from 'react'; class %CLASS% extends Component { render() { %HERE% } } export default %CLASS%;
src/svg-icons/av/play-arrow.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPlayArrow = (props) => ( <SvgIcon {...props}> <path d="M8 5v14l11-7z"/> </SvgIcon> ); AvPlayArrow = pure(AvPlayArrow); AvPlayArrow.displayName = 'AvPlayArrow'; AvPlayArrow.muiName = 'SvgIcon'; export default AvPlayArrow;
src/components/EmailInput/messages.js
transitlinks/web-app
import React from 'react'; import { defineMessages } from 'react-intl'; export default defineMessages({ 'email': { id: 'email.emailLabel', defaultMessage: 'E-mail', description: 'E-mail' }, 'missing-at': { id: 'email.missingAt', defaultMessage: '@ symbol is missing', description: '@ symbol is missing' }, 'missing-prefix': { id: 'email.missingPrefix', defaultMessage: 'E-mail prefix is missing', description: 'E-mail prefix is missing' }, 'too-many-ats': { id: 'email.tooManyAts', defaultMessage: 'Too many @ symbols', description: 'Too many @ symbols' }, 'missing-domain': { id: 'email.missingDomain', defaultMessage: 'Domain name is missing', description: 'Domain name is missing' }, 'missing-postfix': { id: 'email.missingPostfix', defaultMessage: 'Domain postfix is missing', description: 'Domain postfix is missing' }, 'postfix-too-short': { id: 'email.postfixTooShort', defaultMessage: 'Domain postfix too short', description: 'Domain postfix too short' } });
projects/model-threating-tool/src/components/Content.js
hodovanyuk/hodovanyuk.github.io
import React, { Component } from 'react'; import {Button} from 'react-bootstrap'; class Content extends Component { render() { return ( <div className="offices-body-wrapper"> <h1 className="offices-header"> OFFICES | COMPANY INFO </h1> <div className="offices-body-description"> Updating your location and contact information helps you appeal to regional investors and service providers. </div> <div> <div className="split-line"></div> <Button>Add New Office</Button> <p className="offices-counter">3 Offices</p> <div className="split-line"></div> <Button>Back</Button> <Button className="btn-add-comment">Provide additional comments</Button> <div className="offices-flow-control-list"> <Button>Skip this step</Button> <Button bsStyle="primary">Continue</Button> </div> </div> </div> ); } } export default Content;
examples/huge-apps/routes/Course/components/Course.js
batmanimal/react-router
import React from 'react'; import Dashboard from './Dashboard'; import Nav from './Nav'; var styles = {}; styles.sidebar = { float: 'left', width: 200, padding: 20, borderRight: '1px solid #aaa', marginRight: 20 }; class Course extends React.Component { render () { let { children, params } = this.props; let course = COURSES[params.courseId]; return ( <div> <h2>{course.name}</h2> <Nav course={course} /> {children && children.sidebar && children.main ? ( <div> <div className="Sidebar" style={styles.sidebar}> {children.sidebar} </div> <div className="Main" style={{padding: 20}}> {children.main} </div> </div> ) : ( <Dashboard /> )} </div> ); } } export default Course;
src/views/BootCard/BootCard.js
shengnian/shengnian-ui-react
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import { mapToCssModules } from '../../lib/' const propTypes = { tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), inverse: PropTypes.bool, color: PropTypes.string, block: PropTypes.bool, outline: PropTypes.bool, className: PropTypes.string, cssModule: PropTypes.object, } const defaultProps = { tag: 'div', } const Card = (props) => { const { className, cssModule, color, block, inverse, outline, tag: Tag, ...attributes } = props const classes = mapToCssModules(cx( className, 'card', inverse ? 'card-inverse' : false, block ? 'card-block' : false, color ? `card${outline ? '-outline' : ''}-${color}` : false, ), cssModule) return ( <Tag {...attributes} className={classes} /> ) } Card.propTypes = propTypes Card.defaultProps = defaultProps export default Card
client/modules/polls/VoteForm/VotePage.js
ncrmro/ango
import React from 'react' import Page from 'components/Page/Page' import withRelayContainer from 'utils/relay' import { VoteFormFragmentContainer } from './VoteForm' const VotePage = (props) => <Page heading="Question" > <VoteFormFragmentContainer {...props} question={props.viewer.question} /> </Page> const query = graphql` query VotePageQuery($id: ID!) { viewer{ question(id: $id) { ...VoteForm_question } } } ` export default withRelayContainer(VotePage, query)
src/css/style.js
RoyalSix/Eagle-Connect
import React, { Component } from 'react'; import { StyleSheet, Dimensions } from 'react-native'; var { height, width } = Dimensions.get('window'); var css = { container: { flex: 1, backgroundColor: "#FF5E5E", justifyContent: 'flex-start', }, loginHeading: { fontSize: 30, textAlign: 'center', margin: 10, color: 'white', fontFamily: 'Arial Rounded MT Bold', textShadowOffset: { width: 0, height: 3 }, textShadowRadius: 2, textShadowColor: 'black', }, biolaLogo: { alignSelf: 'center', height: height / 3.5, width: width / 2, marginTop: height / 6, shadowOpacity: .8, shadowOffset: { width: 0, height: 3 }, }, loginSubHeading: { fontSize: 20, margin: 10, color: 'white', fontFamily: 'Arial Rounded MT Bold', alignSelf: 'flex-start', marginLeft: width / 12, textShadowOffset: { width: 0, height: 3 }, textShadowRadius: 2, textShadowColor: 'black' }, loginSubHeadingContainer: { flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', marginVertical: 10 }, loginTextField: { flexDirection: 'column', backgroundColor: 'white', height: 40, width: width / 1.2, borderRadius: 5, shadowOpacity: .8, shadowOffset: { width: 0, height: 3 }, marginLeft: width / 12, fontSize: 30, paddingLeft: 10 }, chapelContainer: { flex: 1, }, chapelSeparator: { flex: 1, height: 1, backgroundColor: '#8E8E8E', }, chapelHeading: { fontSize: 30, backgroundColor: 'black', color: 'white', textAlign: 'center' } } var localStyles = StyleSheet.create(css); export default localStyles;
src/components/Selection.js
kevinbarabash/react-text-editor
import React, { Component } from 'react'; class Selection extends Component { render() { let { charWidth, charHeight } = this.props; let gutterWidth = 45; let { node } = this.props; let style = { position: 'absolute', height: charHeight, background: 'rgb(181, 213, 255)' }; if (node.type === "BinaryExpression") { let line = node.left.loc.end.line; let column = node.left.loc.end.column + 1; Object.assign(style, { left: column * charWidth + gutterWidth, top: (line - 1) * charHeight, width: charWidth * node.operator.length }); } else if (node.type === "ReturnStatement") { let line = node.loc.start.line; let column = node.loc.start.column; Object.assign(style, { left: column * charWidth + gutterWidth, top: (line - 1) * charHeight, width: charWidth * 6 }); } else { let loc = node.loc; Object.assign(style, { left: loc.start.column * charWidth + gutterWidth, top: (loc.start.line - 1) * charHeight, width: charWidth * (loc.end.column - loc.start.column) }); } return <div style={style}></div>; } } export default Selection;
app/javascript/mastodon/features/getting_started/components/announcements.js
kirakiratter/mastodon
import React from 'react'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import Icon from 'mastodon/components/icon'; import { defineMessages, injectIntl, FormattedMessage, FormattedDate } from 'react-intl'; import { autoPlayGif, reduceMotion } from 'mastodon/initial_state'; import elephantUIPlane from 'mastodon/../images/elephant_ui_plane.svg'; import { mascot } from 'mastodon/initial_state'; import unicodeMapping from 'mastodon/features/emoji/emoji_unicode_mapping_light'; import classNames from 'classnames'; import EmojiPickerDropdown from 'mastodon/features/compose/containers/emoji_picker_dropdown_container'; import AnimatedNumber from 'mastodon/components/animated_number'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, next: { id: 'lightbox.next', defaultMessage: 'Next' }, }); class Content extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { announcement: ImmutablePropTypes.map.isRequired, }; setRef = c => { this.node = c; } componentDidMount () { this._updateLinks(); this._updateEmojis(); } componentDidUpdate () { this._updateLinks(); this._updateEmojis(); } _updateEmojis () { const node = this.node; if (!node || autoPlayGif) { return; } const emojis = node.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; if (emoji.classList.contains('status-emoji')) { continue; } emoji.classList.add('status-emoji'); emoji.addEventListener('mouseenter', this.handleEmojiMouseEnter, false); emoji.addEventListener('mouseleave', this.handleEmojiMouseLeave, false); } } _updateLinks () { 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.announcement.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 { let status = this.props.announcement.get('statuses').find(item => link.href === item.get('url')); if (status) { link.addEventListener('click', this.onStatusClick.bind(this, status), false); } link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } } 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}`); } } onStatusClick = (status, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/statuses/${status.get('id')}`); } } handleEmojiMouseEnter = ({ target }) => { target.src = target.getAttribute('data-original'); } handleEmojiMouseLeave = ({ target }) => { target.src = target.getAttribute('data-static'); } render () { const { announcement } = this.props; return ( <div className='announcements__item__content' ref={this.setRef} dangerouslySetInnerHTML={{ __html: announcement.get('contentHtml') }} /> ); } } const assetHost = process.env.CDN_HOST || ''; class Emoji extends React.PureComponent { static propTypes = { emoji: PropTypes.string.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, hovered: PropTypes.bool.isRequired, }; render () { const { emoji, emojiMap, hovered } = this.props; if (unicodeMapping[emoji]) { const { filename, shortCode } = unicodeMapping[this.props.emoji]; const title = shortCode ? `:${shortCode}:` : ''; return ( <img draggable='false' className='emojione' alt={emoji} title={title} src={`${assetHost}/emoji/${filename}.svg`} /> ); } else if (emojiMap.get(emoji)) { const filename = (autoPlayGif || hovered) ? emojiMap.getIn([emoji, 'url']) : emojiMap.getIn([emoji, 'static_url']); const shortCode = `:${emoji}:`; return ( <img draggable='false' className='emojione custom-emoji' alt={shortCode} title={shortCode} src={filename} /> ); } else { return null; } } } class Reaction extends ImmutablePureComponent { static propTypes = { announcementId: PropTypes.string.isRequired, reaction: ImmutablePropTypes.map.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, style: PropTypes.object, }; state = { hovered: false, }; handleClick = () => { const { reaction, announcementId, addReaction, removeReaction } = this.props; if (reaction.get('me')) { removeReaction(announcementId, reaction.get('name')); } else { addReaction(announcementId, reaction.get('name')); } } handleMouseEnter = () => this.setState({ hovered: true }) handleMouseLeave = () => this.setState({ hovered: false }) render () { const { reaction } = this.props; let shortCode = reaction.get('name'); if (unicodeMapping[shortCode]) { shortCode = unicodeMapping[shortCode].shortCode; } return ( <button className={classNames('reactions-bar__item', { active: reaction.get('me') })} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} title={`:${shortCode}:`} style={this.props.style}> <span className='reactions-bar__item__emoji'><Emoji hovered={this.state.hovered} emoji={reaction.get('name')} emojiMap={this.props.emojiMap} /></span> <span className='reactions-bar__item__count'><AnimatedNumber value={reaction.get('count')} /></span> </button> ); } } class ReactionsBar extends ImmutablePureComponent { static propTypes = { announcementId: PropTypes.string.isRequired, reactions: ImmutablePropTypes.list.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, }; handleEmojiPick = data => { const { addReaction, announcementId } = this.props; addReaction(announcementId, data.native.replace(/:/g, '')); } willEnter () { return { scale: reduceMotion ? 1 : 0 }; } willLeave () { return { scale: reduceMotion ? 0 : spring(0, { stiffness: 170, damping: 26 }) }; } render () { const { reactions } = this.props; const visibleReactions = reactions.filter(x => x.get('count') > 0); const styles = visibleReactions.map(reaction => ({ key: reaction.get('name'), data: reaction, style: { scale: reduceMotion ? 1 : spring(1, { stiffness: 150, damping: 13 }) }, })).toArray(); return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <div className={classNames('reactions-bar', { 'reactions-bar--empty': visibleReactions.isEmpty() })}> {items.map(({ key, data, style }) => ( <Reaction key={key} reaction={data} style={{ transform: `scale(${style.scale})`, position: style.scale < 0.5 ? 'absolute' : 'static' }} announcementId={this.props.announcementId} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} emojiMap={this.props.emojiMap} /> ))} {visibleReactions.size < 8 && <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} button={<Icon id='plus' />} />} </div> )} </TransitionMotion> ); } } class Announcement extends ImmutablePureComponent { static propTypes = { announcement: ImmutablePropTypes.map.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, selected: PropTypes.bool, }; state = { unread: !this.props.announcement.get('read'), }; componentDidUpdate () { const { selected, announcement } = this.props; if (!selected && this.state.unread !== !announcement.get('read')) { this.setState({ unread: !announcement.get('read') }); } } render () { const { announcement } = this.props; const { unread } = this.state; const startsAt = announcement.get('starts_at') && new Date(announcement.get('starts_at')); const endsAt = announcement.get('ends_at') && new Date(announcement.get('ends_at')); const now = new Date(); const hasTimeRange = startsAt && endsAt; const skipYear = hasTimeRange && startsAt.getFullYear() === endsAt.getFullYear() && endsAt.getFullYear() === now.getFullYear(); const skipEndDate = hasTimeRange && startsAt.getDate() === endsAt.getDate() && startsAt.getMonth() === endsAt.getMonth() && startsAt.getFullYear() === endsAt.getFullYear(); const skipTime = announcement.get('all_day'); return ( <div className='announcements__item'> <strong className='announcements__item__range'> <FormattedMessage id='announcement.announcement' defaultMessage='Announcement' /> {hasTimeRange && <span> · <FormattedDate value={startsAt} hour12={false} year={(skipYear || startsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month='short' day='2-digit' hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /> - <FormattedDate value={endsAt} hour12={false} year={(skipYear || endsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month={skipEndDate ? undefined : 'short'} day={skipEndDate ? undefined : '2-digit'} hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /></span>} </strong> <Content announcement={announcement} /> <ReactionsBar reactions={announcement.get('reactions')} announcementId={announcement.get('id')} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} emojiMap={this.props.emojiMap} /> {unread && <span className='announcements__item__unread' />} </div> ); } } export default @injectIntl class Announcements extends ImmutablePureComponent { static propTypes = { announcements: ImmutablePropTypes.list, emojiMap: ImmutablePropTypes.map.isRequired, dismissAnnouncement: PropTypes.func.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { index: 0, }; static getDerivedStateFromProps(props, state) { if (props.announcements.size > 0 && state.index >= props.announcements.size) { return { index: props.announcements.size - 1 }; } else { return null; } } componentDidMount () { this._markAnnouncementAsRead(); } componentDidUpdate () { this._markAnnouncementAsRead(); } _markAnnouncementAsRead () { const { dismissAnnouncement, announcements } = this.props; const { index } = this.state; const announcement = announcements.get(index); if (!announcement.get('read')) dismissAnnouncement(announcement.get('id')); } handleChangeIndex = index => { this.setState({ index: index % this.props.announcements.size }); } handleNextClick = () => { this.setState({ index: (this.state.index + 1) % this.props.announcements.size }); } handlePrevClick = () => { this.setState({ index: (this.props.announcements.size + this.state.index - 1) % this.props.announcements.size }); } render () { const { announcements, intl } = this.props; const { index } = this.state; if (announcements.isEmpty()) { return null; } return ( <div className='announcements'> <img className='announcements__mastodon' alt='' draggable='false' src={mascot || elephantUIPlane} /> <div className='announcements__container'> <ReactSwipeableViews animateHeight={!reduceMotion} adjustHeight={reduceMotion} index={index} onChangeIndex={this.handleChangeIndex}> {announcements.map((announcement, idx) => ( <Announcement key={announcement.get('id')} announcement={announcement} emojiMap={this.props.emojiMap} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} intl={intl} selected={index === idx} /> ))} </ReactSwipeableViews> {announcements.size > 1 && ( <div className='announcements__pagination'> <IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.previous)} icon='chevron-left' onClick={this.handlePrevClick} size={13} /> <span>{index + 1} / {announcements.size}</span> <IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.next)} icon='chevron-right' onClick={this.handleNextClick} size={13} /> </div> )} </div> </div> ); } }
examples/src/components/CustomOption.js
snowkeeper/react-select
import React from 'react'; import Gravatar from 'react-gravatar'; var Option = React.createClass({ propTypes: { addLabelText: React.PropTypes.string, className: React.PropTypes.string, mouseDown: React.PropTypes.func, mouseEnter: React.PropTypes.func, mouseLeave: React.PropTypes.func, option: React.PropTypes.object.isRequired, renderFunc: React.PropTypes.func }, render () { var obj = this.props.option; var size = 15; var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown}> <Gravatar email={obj.email} size={size} style={gravatarStyle} /> {obj.value} </div> ); } }); module.exports = Option;
src/svg-icons/places/smoking-rooms.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesSmokingRooms = (props) => ( <SvgIcon {...props}> <path d="M2 16h15v3H2zm18.5 0H22v3h-1.5zM18 16h1.5v3H18zm.85-8.27c.62-.61 1-1.45 1-2.38C19.85 3.5 18.35 2 16.5 2v1.5c1.02 0 1.85.83 1.85 1.85S17.52 7.2 16.5 7.2v1.5c2.24 0 4 1.83 4 4.07V15H22v-2.24c0-2.22-1.28-4.14-3.15-5.03zm-2.82 2.47H14.5c-1.02 0-1.85-.98-1.85-2s.83-1.75 1.85-1.75v-1.5c-1.85 0-3.35 1.5-3.35 3.35s1.5 3.35 3.35 3.35h1.53c1.05 0 1.97.74 1.97 2.05V15h1.5v-1.64c0-1.81-1.6-3.16-3.47-3.16z"/> </SvgIcon> ); PlacesSmokingRooms = pure(PlacesSmokingRooms); PlacesSmokingRooms.displayName = 'PlacesSmokingRooms'; PlacesSmokingRooms.muiName = 'SvgIcon'; export default PlacesSmokingRooms;
src/index.js
Zyber17/hey-so-um
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('wrapper')) registerServiceWorker()
packages/es-components/src/components/controls/buttons/Button.js
TWExchangeSolutions/es-components
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import tinycolor from 'tinycolor2'; import { useTheme } from '../../util/useTheme'; import { darken, getTextColor } from '../../util/colors'; import ButtonBase from './ButtonBase'; const StyledButton = styled(ButtonBase)` background-color: ${props => props.colors.bgColor}; border: 2px solid transparent; border-color: ${props => props.colors.bgColor}; border-bottom-left-radius: ${props => props.borderRadii.bottomLeft}; border-bottom-right-radius: ${props => props.borderRadii.bottomRight}; border-top-left-radius: ${props => props.borderRadii.topLeft}; border-top-right-radius: ${props => props.borderRadii.topRight}; box-sizing: border-box; color: ${props => props.colors.textColor}; cursor: pointer; display: ${props => (props.mobileBlock ? 'block' : 'inline-block')}; font-family: inherit; font-size: ${props => props.buttonSize.fontSize}; font-weight: ${props => props.buttonSize.fontWeight || 'normal'}; line-height: ${props => props.buttonSize.lineHeight ? props.buttonSize.lineHeight : props.theme.font.baseLineHeight}; min-width: 100px; padding-bottom: ${props => props.buttonSize.paddingBottom}; padding-left: ${props => props.buttonSize.paddingSides}; padding-right: ${props => props.buttonSize.paddingSides}; padding-top: ${props => props.buttonSize.paddingTop}; position: relative; text-align: center; text-decoration: none; text-transform: ${props => props.buttonSize.textTransform ? props.buttonSize.textTransform : 'none'}; transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; user-select: none; vertical-align: middle; white-space: nowrap; width: ${props => (props.mobileBlock ? '100%' : 'auto')}; @media (min-width: ${props => props.theme.screenSize.tablet}) { display: ${props => (props.block ? 'block' : 'inline-block')}; width: ${props => (props.block ? '100%' : 'auto')}; } @media (hover: hover), (-ms-high-contrast: none) { &:hover { color: ${props => props.colors.hoverTextColor}; background-color: ${props => props.colors.hoverBgColor}; border-color: ${props => props.colors.hoverBorderColor}; text-decoration: none; } } &:focus { color: ${props => props.colors.hoverTextColor}; background-color: ${props => props.colors.hoverBgColor}; border: 1px solid; border-color: ${props => props.colors.hoverBorderColor}; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 0.2rem ${props => props.colors.focusBoxShadowColor}; outline: 0; } &:active, &.pressed { color: ${props => props.colors.activeTextColor}; background-color: ${props => props.colors.activeBgColor}; border-color: ${props => props.colors.activeBorderColor}; box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.25); } &:active:focus, &.pressed:focus { box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.25), 0 0 0 0.2rem ${props => props.colors.focusBoxShadowColor}; } &[disabled], &[data-waiting] { color: #777; cursor: not-allowed; background-color: #e6e6e6; border-color: #e6e6e6; &:hover, &:active &.pressed, background-color: #e6e6e6; border-color: #e6e6e6; color: #777; &:focus { box-shadow: 0 0 0 0.2rem ${props => props.colors.focusBoxShadowColor}; } } > * { pointer-events: none; } } `; const Button = React.forwardRef(function Button( { children, styleType, size, block, mobileBlock, flatLeftEdge, flatRightEdge, ...other }, ref ) { const theme = useTheme(); const buttonSize = theme.buttonStyles.button.size[size]; const variant = theme.buttonStyles.button.variant[styleType]; const isInheritedStyle = styleType === 'inherited'; const mobileBlockSetting = flatLeftEdge || flatRightEdge ? false : mobileBlock; const defaultRadius = buttonSize.borderRadius; const borderRadii = { topLeft: flatLeftEdge ? 0 : defaultRadius, topRight: flatRightEdge ? 0 : defaultRadius, bottomRight: flatRightEdge ? 0 : defaultRadius, bottomLeft: flatLeftEdge ? 0 : defaultRadius }; function getButtonColors() { if (isInheritedStyle) { return { bgColor: 'inherited', textColor: 'inherited', borderColor: 'inherited', hoverBgColor: 'inherited', focusBoxShadowColor: theme.colors.gray4, activeBgColor: 'inherited', activeTextColor: 'inherited', activeBorderColor: 'inherited', hoverTextColor: 'inherited' }; } const focusBoxShadowColor = tinycolor.mix( variant.bgColor, theme.colors.black, 14 ); focusBoxShadowColor.setAlpha(0.5); const calculatedButtonColors = { bgColor: variant.bgColor, textColor: getTextColor(variant.bgColor), borderColor: variant.bgColor, hoverBgColor: darken(variant.bgColor, 7.5), hoverBorderColor: darken(variant.bgColor, 9.9), focusBoxShadowColor: focusBoxShadowColor.toRgbString() }; calculatedButtonColors.activeBgColor = darken( calculatedButtonColors.hoverBgColor, 2.5 ); calculatedButtonColors.activeTextColor = getTextColor( calculatedButtonColors.activeBgColor ); calculatedButtonColors.activeBorderColor = darken( calculatedButtonColors.hoverBgColor, 5 ); calculatedButtonColors.hoverTextColor = getTextColor( calculatedButtonColors.hoverBgColor ); return calculatedButtonColors; } const buttonColors = getButtonColors(); return ( <StyledButton type="button" block={block} mobileBlock={mobileBlockSetting} buttonSize={buttonSize} colors={buttonColors} ref={ref} borderRadii={borderRadii} {...other} > {children} </StyledButton> ); }); Button.propTypes = { ...(ButtonBase.propTypes || {}), waiting: PropTypes.bool, children: PropTypes.node.isRequired, /** Select the color style of the button, types come from theme buttonStyles.button */ styleType: PropTypes.string, size: PropTypes.oneOf(['lg', 'default', 'sm', 'xs']), /** Make the button's width the size of it's parent container */ block: PropTypes.bool, /** Override the default block mobile style */ mobileBlock: PropTypes.bool, /** Styles the Button with a flat left edge */ flatLeftEdge: PropTypes.bool, /** Styles the Button with a flat right edge */ flatRightEdge: PropTypes.bool }; Button.defaultProps = { ...(ButtonBase.defaultProps || {}), waiting: false, styleType: 'default', block: false, mobileBlock: true, size: 'default', flatLeftEdge: false, flatRightEdge: false }; export default Button;
actor-apps/app-web/src/app/components/Login.react.js
treejames/actor-platform
import _ from 'lodash'; import React from 'react'; import classNames from 'classnames'; import { Styles, RaisedButton, TextField } from 'material-ui'; import { AuthSteps } from 'constants/ActorAppConstants'; import LoginActionCreators from 'actions/LoginActionCreators'; import LoginStore from 'stores/LoginStore'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = function () { return ({ step: LoginStore.getStep(), errors: LoginStore.getErrors(), smsRequested: LoginStore.isSmsRequested(), signupStarted: LoginStore.isSignupStarted(), codeSent: false }); }; class Login extends React.Component { static contextTypes = { router: React.PropTypes.func }; static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { LoginStore.removeChangeListener(this.onChange); } componentDidMount() { this.handleFocus(); } componentDidUpdate() { this.handleFocus(); } constructor(props) { super(props); this.state = _.assign({ phone: '', name: '', code: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); if (LoginStore.isLoggedIn()) { window.setTimeout(() => this.context.router.replaceWith('/'), 0); } else { LoginStore.addChangeListener(this.onChange); } } onChange = () => { this.setState(getStateFromStores()); } onPhoneChange = event => { this.setState({phone: event.target.value}); } onCodeChange = event => { this.setState({code: event.target.value}); } onNameChange = event => { this.setState({name: event.target.value}); } onRequestSms = event => { event.preventDefault(); LoginActionCreators.requestSms(this.state.phone); } onSendCode = event => { event.preventDefault(); LoginActionCreators.sendCode(this.context.router, this.state.code); } onSignupRequested = event => { event.preventDefault(); LoginActionCreators.sendSignup(this.context.router, this.state.name); } onWrongNumberClick = event => { event.preventDefault(); LoginActionCreators.wrongNumberClick(); } handleFocus = () => { switch (this.state.step) { case AuthSteps.PHONE_WAIT: this.refs.phone.focus(); break; case AuthSteps.CODE_WAIT: this.refs.code.focus(); break; case AuthSteps.SIGNUP_NAME_WAIT: this.refs.name.focus(); break; default: return; } } render() { let requestFormClassName = classNames('login__form', 'login__form--request', { 'login__form--done': this.state.step > AuthSteps.PHONE_WAIT, 'login__form--active': this.state.step === AuthSteps.PHONE_WAIT }); let checkFormClassName = classNames('login__form', 'login__form--check', { 'login__form--done': this.state.step > AuthSteps.CODE_WAIT, 'login__form--active': this.state.step === AuthSteps.CODE_WAIT }); let signupFormClassName = classNames('login__form', 'login__form--signup', { 'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT }); return ( <section className="login-new row center-xs middle-xs"> <div className="login-new__welcome col-xs row center-xs middle-xs"> <img alt="Actor messenger" className="logo" src="assets/img/logo.png" srcSet="assets/img/[email protected] 2x"/> <article> <h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1> <p> Actor Messenger brings all your business network connections into one place, makes it easily accessible wherever you go. </p> <p> Our aim is to make your work easier, reduce your email amount, make the business world closer by reducing time to find right contacts. </p> </article> <footer> <div className="pull-left"> Actor Messenger © 2015 </div> <div className="pull-right"> <a href="//actor.im/ios">iPhone</a> <a href="//actor.im/android">Android</a> </div> </footer> </div> <div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs"> <div> <h1 className="login-new__heading">Sign in</h1> <form className={requestFormClassName} onSubmit={this.onRequestSms}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.PHONE_WAIT} errorText={this.state.errors.phone} floatingLabelText="Phone number" onChange={this.onPhoneChange} ref="phone" type="tel" value={this.state.phone}/> <footer className="text-center"> <RaisedButton label="Request code" type="submit"/> </footer> </form> <form className={checkFormClassName} onSubmit={this.onSendCode}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.CODE_WAIT} errorText={this.state.errors.code} floatingLabelText="Auth code" onChange={this.onCodeChange} ref="code" type="text" value={this.state.code}/> <footer className="text-center"> <RaisedButton label="Check code" type="submit"/> </footer> </form> <form className={signupFormClassName} onSubmit={this.onSignupRequested}> <TextField className="login__form__input" errorText={this.state.errors.signup} floatingLabelText="Your name" onChange={this.onNameChange} ref="name" type="text" value={this.state.name}/> <footer className="text-center"> <RaisedButton label="Sign up" type="submit"/> </footer> </form> </div> </div> </section> ); } } export default Login;
src/app/Router-min.js
kolabdigital/notification_demo
import React from 'react'; import Home from './modules/home/components/Home'; import Birthdays from './modules/birthdays/components/Birthdays'; import { ConnectedRouter } from 'react-router-redux'; import { Route } from 'react-router'; export default class Router extends React.Component { render () { return ( <ConnectedRouter history={this.props.history}> <div> <Route exact path="/" component={Home}/> <Route exact path="/birthdays" component={Birthdays}/> </div> </ConnectedRouter> ); } }
maodou/wechat/client/components/sign-in-button.js
ShannChiang/meteor-react-redux-base
import React from 'react'; export const UIState = { IDLE: 'idle', LOGGING_IN: 'loggingIn', LOGGED_IN: 'loggedIn', ERROR: 'error' }; export default (props) => { switch (props.uiState) { case UIState.IDLE: return <a href={props.authUrl}>微信一键登录</a>; case UIState.LOGGED_IN: return <span>已登录</span>; case UIState.LOGGING_IN: return <span>正在登录...</span>; default: return <div>登录失败 <a href={props.authUrl}>重试登录</a></div>; } }
components/Layout/Header.js
gusdewa/MultiStores
import React from 'react'; import Navigation from './Navigation'; import Link from '../Link'; import s from './Header.css'; class Header extends React.Component { componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { return ( <header className={`mdl-layout__header ${s.header}`} ref={node => (this.root = node)}> <div className={`mdl-layout__header-row ${s.row}`}> <Link className={`mdl-layout-title ${s.title}`} to="/"> MultiStores </Link> <div className="mdl-layout-spacer"></div> <Navigation /> </div> </header> ); } } export default Header;
Magistrate/client/components/permissions/singlePermissionView.js
Pondidum/Magistrate
import React from 'react' import InlineEditor from '../InlineEditor' var SinglePermissionView = React.createClass({ onNameChanged(newName) { var json = JSON.stringify({ name: newName }); $.ajax({ url: this.props.url + "/name", cache: false, method: "PUT", data: json, success: function() { this.props.permission.name = newName; }.bind(this) }); }, onDescriptionChanged(newDescription) { var json = JSON.stringify({ description: newDescription }); $.ajax({ url: this.props.url + "/description", cache: false, method: "PUT", data: json, success: function() { this.props.permission.description = newDescription; }.bind(this) }); }, render() { var permission = this.props.permission; var self = this; if (permission == null) return (<h1>Unknown permission {this.props.permissionKey}</h1>); return ( <div className="well"> <h1><InlineEditor initialValue={permission.name} onChange={this.onNameChanged} /></h1> <div><InlineEditor initialValue={permission.description} onChange={this.onDescriptionChanged} /></div> </div> ) } }); export default SinglePermissionView
eventkit_cloud/ui/static/ui/app/components/Notification/NotificationMenu.js
venicegeo/eventkit-cloud
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { withTheme } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import OpenInNewIcon from '@material-ui/icons/OpenInNew'; import FlagIcon from '@material-ui/icons/Flag'; import CloseIcon from '@material-ui/icons/Close'; import IconMenu from '../common/IconMenu'; import { getNotificationViewPath } from '../../utils/notificationUtils'; import { markNotificationsAsRead, markNotificationsAsUnread, removeNotifications, } from '../../actions/notificationsActions'; export class NotificationMenu extends React.Component { constructor(props) { super(props); this.handleMarkAsRead = this.handleMarkAsRead.bind(this); this.handleMarkAsUnread = this.handleMarkAsUnread.bind(this); this.handleRemove = this.handleRemove.bind(this); this.handleView = this.handleView.bind(this); } handleMarkAsRead() { if (this.props.onMarkAsRead(this.props.notification)) { this.props.markNotificationsAsRead([this.props.notification]); } } handleMarkAsUnread() { if (this.props.onMarkAsUnread(this.props.notification)) { this.props.markNotificationsAsUnread([this.props.notification]); } } handleRemove() { if (this.props.onRemove(this.props.notification)) { this.props.removeNotifications([this.props.notification]); } } handleView() { const path = getNotificationViewPath(this.props.notification); if (this.props.onView(this.props.notification, path)) { this.props.history.push(path); this.props.markNotificationsAsRead([this.props.notification]); } } render() { const { colors } = this.props.theme.eventkit; const styles = { menuItem: { fontSize: '12px', lineHeight: '24px', }, icon: { color: colors.text_primary, marginRight: '5px', }, }; const viewPath = getNotificationViewPath(this.props.notification); return ( <IconMenu className="qa-NotificationMenu-IconMenu" menuStyle={{ zIndex: 1400 }} style={{ width: '26px', height: '26px' }} > {viewPath ? ( <MenuItem key="view" className="qa-NotificationMenu-MenuItem-View" style={styles.menuItem} onClick={this.handleView} > <OpenInNewIcon style={styles.icon} /> {' '} View </MenuItem> ) : null} {this.props.notification.unread ? ( <MenuItem key="markRead" className="qa-NotificationMenu-MenuItem-MarkAsRead" style={styles.menuItem} onClick={this.handleMarkAsRead} > <FlagIcon style={styles.icon} /> {' '} Mark As Read </MenuItem> ) : ( <MenuItem key="markUnread" className="qa-NotificationMenu-MenuItem-MarkAsUnread" style={styles.menuItem} onClick={this.handleMarkAsUnread} > <FlagIcon style={styles.icon} /> {' '} Mark As Unread </MenuItem> )} <MenuItem key="remove" className="qa-NotificationMenu-MenuItem-Remove" style={styles.menuItem} onClick={this.handleRemove} > <CloseIcon style={styles.icon} /> {' '} Remove </MenuItem> </IconMenu> ); } } NotificationMenu.propTypes = { notification: PropTypes.object.isRequired, history: PropTypes.object.isRequired, onMarkAsRead: PropTypes.func, onMarkAsUnread: PropTypes.func, onRemove: PropTypes.func, onView: PropTypes.func, markNotificationsAsRead: PropTypes.func.isRequired, markNotificationsAsUnread: PropTypes.func.isRequired, removeNotifications: PropTypes.func.isRequired, theme: PropTypes.object.isRequired, }; NotificationMenu.defaultProps = { onMarkAsRead: () => true, onMarkAsUnread: () => true, onRemove: () => true, onView: () => true, }; function mapDispatchToProps(dispatch) { return { markNotificationsAsRead: (notifications) => dispatch(markNotificationsAsRead(notifications)), markNotificationsAsUnread: (notifications) => dispatch(markNotificationsAsUnread(notifications)), removeNotifications: (notifications) => dispatch(removeNotifications(notifications)), }; } export default withTheme(connect(null, mapDispatchToProps)(NotificationMenu));
app/components/Th/index.js
clairealmozinos/marvel-univers
// // Component <th></th> // import React from 'react'; import './styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class Th extends React.Component { render() { return ( <th>{this.props.value}</th> ); } } Th.propTypes = { value: React.PropTypes.string.isRequired, };
examples/huge-apps/routes/Messages/components/Messages.js
SpainTrain/react-router
import React from 'react'; class Messages extends React.Component { render () { return ( <div> <h2>Messages</h2> </div> ); } } export default Messages;
examples/with-loading/pages/index.js
BlancheXu/test
import React from 'react' const IndexPage = () => <p>Hello Next.js!</p> export default IndexPage
src/svg-icons/image/filter-drama.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterDrama = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.61 5.64 5.36 8.04 2.35 8.36 0 10.9 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4h2c0-2.76-1.86-5.08-4.4-5.78C8.61 6.88 10.2 6 12 6c3.03 0 5.5 2.47 5.5 5.5v.5H19c1.65 0 3 1.35 3 3s-1.35 3-3 3z"/> </SvgIcon> ); ImageFilterDrama = pure(ImageFilterDrama); ImageFilterDrama.displayName = 'ImageFilterDrama'; ImageFilterDrama.muiName = 'SvgIcon'; export default ImageFilterDrama;
src/components/head.js
basvandriel/WWW
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import favicon from '@images/favicons/favicon.ico'; import appleIcon57x57 from '@images/favicons/apple-icon-57x57.png'; import appleIcon72x72 from '@images/favicons/apple-icon-72x72.png'; import appleIcon76x76 from '@images/favicons/apple-icon-76x76.png'; import appleIcon114x114 from '@images/favicons/apple-icon-114x114.png'; import appleIcon120x120 from '@images/favicons/apple-icon-120x120.png'; import appleIcon144x144 from '@images/favicons/apple-icon-144x144.png'; import appleIcon152x152 from '@images/favicons/apple-icon-152x152.png'; import appleIcon180x180 from '@images/favicons/apple-icon-180x180.png'; const Head = ({ metadata }) => ( <Helmet> <html lang="nl" prefix="og: http://ogp.mee/ns#" /> <title itemProp="name" lang="en">{metadata.title}</title> <link rel="shortcut icon" href={favicon} /> <link rel="canonical" href="https://basvandriel.nl" /> <meta name="description" content={metadata.description} /> <meta name="keywords" content={metadata.siteKeywords} /> <meta property="og:title" content={metadata.title} /> <meta property="og:description" content={metadata.description} /> <meta property="og:type" content="website" /> <meta property="og:url" content={metadata.siteUrl} /> <meta property="og:site_name" content={metadata.title} /> <meta property="og:image:width" content="1200" /> <meta property="og:image:height" content="630" /> <meta property="og:image:type" content="image/png" /> <meta property="og:locale" content={metadata.locale} /> <meta itemProp="name" content={metadata.title} /> <meta itemProp="description" content={metadata.description} /> <link rel="apple-touch-icon" sizes="57x57" href={appleIcon57x57} /> <link rel="apple-touch-icon" sizes="72x72" href={appleIcon72x72} /> <link rel="apple-touch-icon" sizes="76x76" href={appleIcon76x76} /> <link rel="apple-touch-icon" sizes="114x114" href={appleIcon114x114} /> <link rel="apple-touch-icon" sizes="120x120" href={appleIcon120x120} /> <link rel="apple-touch-icon" sizes="144x144" href={appleIcon144x144} /> <link rel="apple-touch-icon" sizes="152x152" href={appleIcon152x152} /> <link rel="apple-touch-icon" sizes="180x180" href={appleIcon180x180} /> </Helmet> ); export default Head; Head.propTypes = { metadata: PropTypes.object.isRequired, };
src/containers/root.js
martinkwan/HNGRY
/** |========================================================================================== | This is a container that wraps App with redux |------------------------------------------------------------------------------------------ */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import App from '../components/app'; export default class Root extends Component { render() { const { store } = this.props; return ( <Provider store={store} > <App /> </Provider> ); } } Root.propTypes = { store: PropTypes.object, };
src/index.js
mavivian/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/pages/Commons/ErrorBoundary.js
hyy1115/react-redux-webpack2
import React from 'react' //捕捉子组件的错误 //例如 /* * <ErrorBoundary> * <Header * bgColor={bgClass} * imgUrl={search} * linkTo="search" * title="react-redux架构" * /> * </ErrorBoundary> * * */ class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { error: null, errorInfo: null } } componentDidCatch(error, errorInfo) { this.setState(() => ({ error: error, errorInfo: errorInfo })) } render() { const { errorInfo } = this.state if (errorInfo) { return <h3 style={{ color: 'red', background: '#eab3b3' }}>error</h3> } else { return this.props.children } } } export default ErrorBoundary
front/cryptofx/src/App.js
Alex-Werner/CryptoFX
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
fields/components/Checkbox.js
alobodig/keystone
import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; import { darken, fade } from '../../admin/client/utils/color'; import E from '../../admin/client/constants'; var Checkbox = React.createClass({ displayName: 'Checkbox', propTypes: { checked: React.PropTypes.bool, component: React.PropTypes.node, onChange: React.PropTypes.func, readonly: React.PropTypes.bool, }, getDefaultProps () { return { component: 'button', }; }, getInitialState () { return { active: null, focus: null, hover: null, }; }, componentDidMount () { window.addEventListener('mouseup', this.handleMouseUp, false); }, componentWillUnmount () { window.removeEventListener('mouseup', this.handleMouseUp, false); }, getStyles () { const { checked, readonly } = this.props; const { active, focus, hover } = this.state; const checkedColor = '#3999fc'; let background = (checked && !readonly) ? checkedColor : 'white'; let borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.15) rgba(0,0,0,0.1) rgba(0,0,0,0.05)' : 'rgba(0,0,0,0.3) rgba(0,0,0,0.2) rgba(0,0,0,0.15)'; let boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 0 rgba(0,0,0,0.06)'; let color = (checked && !readonly) ? 'white' : '#bbb'; const textShadow = (checked && !readonly) ? '0 1px 0 rgba(0,0,0,0.2)' : null; // pseudo state if (hover && !focus && !readonly) { borderColor = (checked) ? 'rgba(0,0,0,0.1) rgba(0,0,0,0.15) rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.35) rgba(0,0,0,0.3) rgba(0,0,0,0.25)'; } if (active) { background = (checked && !readonly) ? darken(checkedColor, 20) : '#eee'; borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.4) rgba(0,0,0,0.35) rgba(0,0,0,0.3)'; boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 3px rgba(0,0,0,0.2)'; } if (focus && !active) { borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : checkedColor; boxShadow = (checked && !readonly) ? `0 0 0 3px ${fade(checkedColor, 15)}` : `inset 0 1px 2px rgba(0,0,0,0.15), 0 0 0 3px ${fade(checkedColor, 15)}`; } // noedit if (readonly) { background = 'rgba(255,255,255,0.5)'; borderColor = 'rgba(0,0,0,0.1)'; boxShadow = 'none'; color = checked ? checkedColor : '#bbb'; } return { alignItems: 'center', background: background, border: '1px solid', borderColor: borderColor, borderRadius: E.borderRadius.sm, boxShadow: boxShadow, color: color, display: 'inline-block', fontSize: 14, height: 16, lineHeight: '15px', outline: 'none', padding: 0, textAlign: 'center', textShadow: textShadow, verticalAlign: 'middle', width: 16, msTransition: 'all 120ms ease-out', MozTransition: 'all 120ms ease-out', WebkitTransition: 'all 120ms ease-out', transition: 'all 120ms ease-out', }; }, handleKeyDown (e) { if (e.keyCode !== 32) return; this.toggleActive(true); }, handleKeyUp () { this.toggleActive(false); }, handleMouseOver () { this.toggleHover(true); }, handleMouseDown () { this.toggleActive(true); this.toggleFocus(true); }, handleMouseUp () { this.toggleActive(false); }, handleMouseOut () { this.toggleHover(false); }, toggleActive (pseudo) { this.setState({ active: pseudo }); }, toggleHover (pseudo) { this.setState({ hover: pseudo }); }, toggleFocus (pseudo) { this.setState({ focus: pseudo }); }, handleChange () { this.props.onChange(!this.props.checked); }, render () { const { checked, readonly } = this.props; const props = blacklist(this.props, 'checked', 'component', 'onChange', 'readonly'); props.style = this.getStyles(); props.ref = 'checkbox'; props.className = classnames('octicon', { 'octicon-check': checked, 'octicon-x': (typeof checked === 'boolean') && !checked && readonly, }); props.type = readonly ? null : 'button'; props.onKeyDown = this.handleKeyDown; props.onKeyUp = this.handleKeyUp; props.onMouseDown = this.handleMouseDown; props.onMouseUp = this.handleMouseUp; props.onMouseOver = this.handleMouseOver; props.onMouseOut = this.handleMouseOut; props.onClick = readonly ? null : this.handleChange; props.onFocus = readonly ? null : () => this.toggleFocus(true); props.onBlur = readonly ? null : () => this.toggleFocus(false); const node = readonly ? 'span' : this.props.component; return React.createElement(node, props); }, }); module.exports = Checkbox;
src/components/IntroParagraph/index.js
iris-dni/iris-frontend
import React from 'react'; import styles from './intro-paragraph.scss'; const IntroParagraph = ({ children, text }) => ( <p className={styles.root}> {children || text} </p> ); export default IntroParagraph;
src/index.js
Lordmzn/personal-website
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
docs/src/app/components/pages/components/List/ExampleMessages.js
pancho111203/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors'; import IconButton from 'material-ui/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={grey400} /> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Reply</MenuItem> <MenuItem>Forward</MenuItem> <MenuItem>Delete</MenuItem> </IconMenu> ); const ListExampleMessages = () => ( <div> <MobileTearSheet> <List> <Subheader>Today</Subheader> <ListItem leftAvatar={<Avatar src="images/ok-128.jpg" />} primaryText="Brunch this weekend?" secondaryText={ <p> <span style={{color: darkBlack}}>Brendan Lim</span> -- I&apos;ll be in your neighborhood doing errands this weekend. Do you want to grab brunch? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kolage-128.jpg" />} primaryText={ <p>Summer BBQ&nbsp;&nbsp;<span style={{color: lightBlack}}>4</span></p> } secondaryText={ <p> <span style={{color: darkBlack}}>to me, Scott, Jennifer</span> -- Wish I could come, but I&apos;m out of town this weekend. </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/uxceo-128.jpg" />} primaryText="Oui oui" secondaryText={ <p> <span style={{color: darkBlack}}>Grace Ng</span> -- Do you have Paris recommendations? Have you ever been? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kerem-128.jpg" />} primaryText="Birdthday gift" secondaryText={ <p> <span style={{color: darkBlack}}>Kerem Suer</span> -- Do you have any ideas what we can get Heidi for her birthday? How about a pony? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />} primaryText="Recipe to try" secondaryText={ <p> <span style={{color: darkBlack}}>Raquel Parrado</span> -- We should eat this: grated squash. Corn and tomatillo tacos. </p> } secondaryTextLines={2} /> </List> </MobileTearSheet> <MobileTearSheet> <List> <Subheader>Today</Subheader> <ListItem leftAvatar={<Avatar src="images/ok-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Brendan Lim" secondaryText={ <p> <span style={{color: darkBlack}}>Brunch this weekend?</span><br /> I&apos;ll be in your neighborhood doing errands this weekend. Do you want to grab brunch? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kolage-128.jpg" />} rightIconButton={rightIconMenu} primaryText="me, Scott, Jennifer" secondaryText={ <p> <span style={{color: darkBlack}}>Summer BBQ</span><br /> Wish I could come, but I&apos;m out of town this weekend. </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/uxceo-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Grace Ng" secondaryText={ <p> <span style={{color: darkBlack}}>Oui oui</span><br /> Do you have any Paris recs? Have you ever been? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kerem-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Kerem Suer" secondaryText={ <p> <span style={{color: darkBlack}}>Birthday gift</span><br /> Do you have any ideas what we can get Heidi for her birthday? How about a pony? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Raquel Parrado" secondaryText={ <p> <span style={{color: darkBlack}}>Recipe to try</span><br /> We should eat this: grated squash. Corn and tomatillo tacos. </p> } secondaryTextLines={2} /> </List> </MobileTearSheet> </div> ); export default ListExampleMessages;
ui/src/components/denali/Menu/Menu.js
yahoo/athenz
/* * Copyright 2020 Verizon Media * * 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 { cx } from '@emotion/css'; import { cssArrow, makeCssPopperBox } from './styles'; import TooltipTrigger from 'react-popper-tooltip'; // Default offset when 'placement' ends with '-start' or '-end' const DEFAULT_ARROW_OFFSET = 10; const ARROW_SIZE = 16; // Modifier to position the arrow depending on placement (start|end) export const arrowMod = (data, options) => { if (data.placement.match(/(bottom|top)/)) { const popperWidth = data.offsets.popper.width; if (data.placement.match(/start/)) { data.arrowStyles.left = DEFAULT_ARROW_OFFSET + options.arrowOffset; } else if (data.placement.match(/end/)) { data.arrowStyles.left = popperWidth - ARROW_SIZE - DEFAULT_ARROW_OFFSET + options.arrowOffset; } else { data.arrowStyles.left += options.arrowOffset; } } else { const popperHeight = data.offsets.popper.height; if (data.placement.match(/start/)) { data.arrowStyles.top = DEFAULT_ARROW_OFFSET + options.arrowOffset; } else if (data.placement.match(/end/)) { data.arrowStyles.top = popperHeight - ARROW_SIZE - DEFAULT_ARROW_OFFSET + options.arrowOffset; } else { data.arrowStyles.top += options.arrowOffset; } } return data; }; // Modifier to adjust the position export const popperMod = (data, options) => { if (data.placement.match(/(bottom|top)/)) { data.styles.left += options.menuOffset; } else { data.styles.top += options.menuOffset; } return data; }; /** * Menu component that activates on hovering over a trigger. This menu is based * on [PopperJS](https://popper.js.org/), a library to manage popups. The Menu * supports configurable positioning and method of activation (click or hover). * Menus are defined by the trigger (the element you interact with to open the * menu), and the menu content. Contrary to the name, the content does not have * to actually be a list of clickable items. Anything can go inside the popup. * Only the outer border box is styled by `<Menu>`; within the popup, you can * style it as you see it. * * Basic usage: * * ```bash * render() { * const trigger = <span>Hover over me</span>; * return ( * <Menu placement="bottom-start" trigger={trigger}> * <ul> * <a href="#">Section A</a> * <a href="#">Section B</a> * </ul> * </Menu> * ); * } * ``` * * If the content of the menu is a simple string (eg. `<Menu>some text</Menu>`), * then it will be wrapped in a `<span>` with `padding: 10px 20px`. Otherwise, * if you pass in a React node/element/component, no styling will be applied. * * NOTE: There is an issue where if the trigger is in a scrollable div, and the * menu is open, you cannot scroll if the cursor is over the menu. This is an * issue with the underlying `react-popper-tooltip` library, and it may be fixed * soon. * */ class Menu extends React.Component { renderTrigger = ({ getTriggerProps, triggerRef }) => { if (typeof this.props.trigger === 'function') { const renderedTrigger = this.props.trigger({ getTriggerProps, triggerRef, }); return renderedTrigger && React.Children.only(renderedTrigger); } let trigger; if (typeof this.props.trigger === 'string') { trigger = <span>{this.props.trigger}</span>; } else { trigger = this.props.trigger; } return React.cloneElement(trigger, { ...getTriggerProps({ ref: triggerRef, }), }); }; renderTooltip = ({ getTooltipProps, getArrowProps, tooltipRef, arrowRef, placement, }) => ( <div {...getTooltipProps({ className: cx( makeCssPopperBox({ basic: typeof this.props.children === 'string', noanim: this.props.noanim, }), this.props.className ), ref: tooltipRef, 'data-placement': placement, })} > {this.props.children} {!this.props.noArrow && ( <div {...getArrowProps({ className: cssArrow, ref: arrowRef, 'data-placement': placement, })} /> )} </div> ); render() { // DEPRECATED: align will be deprecated, but support for now. let placement; if (this.props.align) { placement = `bottom-${this.props.align}`; } else { placement = this.props.placement; } return ( <TooltipTrigger modifiers={{ arrowMod: { arrowOffset: this.props.arrowOffset, enabled: true, order: 890, fn: arrowMod, }, popperMod: { menuOffset: this.props.menuOffset, enabled: true, order: 880, fn: popperMod, }, preventOverflow: { boundariesElement: this.props.boundary, padding: 0, }, }} onVisibilityChange={this.props.onVisibilityChange} placement={placement} tooltip={this.renderTooltip} tooltipShown={this.props.showMenu} trigger={this.props.triggerOn} usePortal={this.props.usePortal} > {this.renderTrigger} </TooltipTrigger> ); } } Menu.propTypes = { /** * @deprecated * * Justify menu to the left or right side of the trigger */ align: PropTypes.oneOf(['center', 'left', 'right']), /** * Change the offset position of the arrow. Positive values moves the arrow N * pixels to the right/down (depending on intiial top/bottom, left/right * placement), negative values to the left/up. If `align` is 'left' or * 'right', the arrow already has an offset of 10 pixels from the edge, so * `arrowOffset` is added on top of this internal offset. */ arrowOffset: PropTypes.number, /** * Boundary of the tooltip that it must be contained within. This can be * either 'scrollParent', 'window', or 'viewport'. See: * https://popper.js.org/popper-documentation.html#modifiers..preventOverflow.boundariesElement */ boundary: PropTypes.oneOf(['scrollParent', 'viewport', 'window']), /** * Content to render within the menu. This can be anything from a simple * string to a complex HTML markup to another React component. * * NOTE: If this is a simple string, it will be wrapped in a `<div>` with * some padding. If you want full control, pass in a pre-styled element. */ children: PropTypes.node, /** Additonal class to apply to the popup div */ className: PropTypes.string, /** * Change the offset position of the menu. Positive values moves the menu N * pixels to the right/down (depending on intiial top/bottom, left/right * placement), negative values to the left/up. */ menuOffset: PropTypes.number, /** Disable animations / transitions */ noanim: PropTypes.bool, /** Hide the arrow */ noArrow: PropTypes.bool, /** * Called when visibility changes. Needed if 'showMenu' is used. */ onVisibilityChange: PropTypes.func, /** * Placement of the menu. Note: if there is not enough space in the viewport * for the specified position, it will be placed on the opposite side * (eg. specified 'top', show on 'bottom') */ placement: PropTypes.oneOf([ 'top', 'top-start', 'top-end', 'bottom', 'bottom-start', 'bottom-end', 'left', 'left-start', 'left-end', 'right', 'right-start', 'right-end', ]), /** * Control prop. * * Use this prop if you want to control the visibility state of the menu. */ showMenu: PropTypes.bool, /** * A React element representing the trigger (element to hover over). This can * be a simple string to another React component / element. * * NOTE: If this is a string, it will be wrapped in a `<span>` element. */ trigger: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired, /** Activate the menu on hover (default) or click */ triggerOn: PropTypes.oneOf(['click', 'hover']), /** * Advanced - Use React Portal to render the menu. * * See: https://www.npmjs.com/package/react-popper-tooltip#useportal * And: https://github.com/FezVrasta/react-popper#usage-with-reactdomcreateportal */ usePortal: PropTypes.bool, }; Menu.defaultProps = { arrowOffset: 0, boundary: 'scrollParent', menuOffset: 0, noanim: false, noArrow: true, placement: 'bottom', triggerOn: 'hover', usePortal: false, }; export default Menu;
packages/core/src/icons/components/CheckboxHalf.js
iCHEF/gypcrete
import React from 'react'; export default function SvgCheckboxHalf(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="-1980 -5057 32 32" width="1em" height="1em" {...props} > <path data-name="\u9577\u65B9\u5F62 7901" fill="transparent" d="M-1980-5057h32v32h-32z" /> <path data-name="\u524D\u9762\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u578B\u629C\u304D 8" d="M-1958-5031h-12a4.005 4.005 0 01-4-4v-12a4 4 0 014-4h12a4 4 0 014 4v12a4 4 0 01-4 4zm-12-11.5v3h12v-3z" /> </svg> ); }
frontend/Components/Dashboard/ForumBox/index.js
shoumma/ReForum
import React, { Component } from 'react'; import classnames from 'classnames'; import styles from './styles'; import Button from 'Components/Button'; class ForumBox extends Component { constructor(props) { super(props); this.state = { newForumTitle: '', newForumSlug: '', errorMsg: null, }; this.handleCreateForum = this.handleCreateForum.bind(this); } handleCreateForum() { // remove any error messages this.setState({ errorMsg: null }); const { newForumTitle, newForumSlug, } = this.state; let convertedTitle = null; let convertedSlug = null; // check and convert forum title if (newForumTitle !== '') { // trim any leading or ending white spaces convertedTitle = newForumTitle.trim(); // check the length, 4 is hardcoded here if (convertedTitle.length < 4) { return this.setState({ errorMsg: 'Forum title should have at least 4 charecters.' }); } } else { return this.setState({ errorMsg: 'Forum title is empty. Please provide a valid Forum Title.' }); } // check and confirm forum slug if (convertedSlug !== '') { const slugRegex = /^[a-z\_]+$/; convertedSlug = newForumSlug.match(slugRegex) ? newForumSlug : null; // length check if (convertedSlug && convertedSlug.length < 4) { return this.setState({ errorMsg: 'Forum slug should have at least 4 charecters.' }); } } else { return this.setState({ errorMsg: 'Forum slug is empty. Please provide a valid Forum Slug.' }); } if (!convertedTitle) { return this.setState({ errorMsg: 'Please provide a valid Forum Title.' }); } if (!convertedSlug) { return this.setState({ errorMsg: 'Please provide a valid Forum Slug. Slug can only contain small case alphabets and underscore.' }); } if (convertedTitle && convertedSlug) { this.props.createAction({ title: convertedTitle, slug: convertedSlug }); } } render() { const { forums, creatingForum, deleteAction, deletingForum, } = this.props; const { newForumTitle, newForumSlug, errorMsg, } = this.state; return ( <div className={styles.container}> <div className={styles.title}>Current Forums</div> <div className={styles.forumsContainer}> { deletingForum && <div className={styles.loadingMsg}>Removing forum, please wait...</div> } { forums.map((forum) => <div key={forum.id} className={styles.forum}> <div className={styles.forumTitle}>{ forum.name }</div> <div className={styles.forumSlug}>({ forum.slug })</div> <div className={styles.removeButton}> <Button onClick={() => { deleteAction(forum.id); }}>Remove</Button> </div> </div>) } </div> <div className={styles.createForumContainer}> { creatingForum && <div className={styles.loadingMsg}>Creating forum, please wait...</div> } <div className={styles.createTitle}>Create New Forum</div> <div className={styles.createForum}> <div className={styles.createInputContainer}> <div className={styles.inputLabel}>Title: </div> <input type={'text'} className={styles.createInput} placeholder={'Forum Title'} onChange={(e) => { this.setState({ newForumTitle: e.target.value }); }} /> </div> <div className={styles.createInputContainer}> <div className={styles.inputLabel}>Slug: </div> <input type={'text'} className={styles.createInput} placeholder={'forum_slug'} onChange={(e) => { this.setState({ newForumSlug: e.target.value }); }} /> </div> <Button onClick={this.handleCreateForum}>Create</Button> </div> { errorMsg && <div className={styles.errorMsg}>{errorMsg}</div> } </div> </div> ); } } ForumBox.defaultProps = { }; ForumBox.propTypes = { forums: React.PropTypes.array, deletingForum: React.PropTypes.bool, deleteAction: React.PropTypes.func, creatingForum: React.PropTypes.bool, createAction: React.PropTypes.func, }; export default ForumBox;
integration/umd-react/src/index.js
Webfreshener/JSD
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
client/src/AzureLogin.js
clembou/github-requests
import React from 'react'; import { Grid, Row, Col } from 'react-bootstrap'; import azureClient from './shared/azureClient'; import { LoadingWithMessage } from './shared/Loading'; import SignInButton from './SignInButton'; const AUTO_LOGIN = process.env.NODE_ENV === 'production'; //const AUTO_LOGIN = true class AzureAuthorisation extends React.Component { state = { message: '' }; componentDidMount() { if (this.props.location.hash) { azureClient.getToken(this.props.location.hash, (isAuthenticated, isAdmin, state) => this.props.onAuth(isAuthenticated, isAdmin, state)); } if (!this.props.location.hash && AUTO_LOGIN) { // Automatically initiate authentication in production azureClient.authenticate(this.getFromState()); } } getFromState() { //eslint-disable-next-line return this.props.location.state && this.props.location.state.from || { pathname: '/' }; } render() { const from = this.getFromState(); const content = AUTO_LOGIN || this.props.location.hash ? <Col md={6}> <LoadingWithMessage message="Authentication in progress..." /> </Col> : <Col md={6}> <p> You must log in to view the page at <code>{from.pathname}</code> </p> <SignInButton from={from} /> </Col>; return ( <Grid> <Row> {content} </Row> </Grid> ); } } export default AzureAuthorisation;
admin/client/components/Lightbox.js
tony2cssc/keystone
import React from 'react'; import blacklist from 'blacklist'; import Portal from './Portal'; import Transition from 'react-addons-css-transition-group'; const BODY = document.getElementsByTagName('body')[0]; var Lightbox = React.createClass({ displayName: 'Lightbox', propTypes: { backdropClosesModal: React.PropTypes.bool, className: React.PropTypes.string, enableKeyboardInput: React.PropTypes.bool, height: React.PropTypes.number, images: React.PropTypes.array, initialImage: React.PropTypes.number, isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, showCloseButton: React.PropTypes.bool, width: React.PropTypes.number, }, getDefaultProps () { return { backdropClosesModal: true, enableKeyboardInput: true, initialImage: 0, height: 600, width: 900, }; }, getInitialState () { return { currentImage: this.props.initialImage, }; }, componentWillReceiveProps (nextProps) { this.setState({ currentImage: nextProps.initialImage, }); if (nextProps.isOpen && nextProps.enableKeyboardInput) { window.addEventListener('keydown', this.handleKeyboardInput); } else { window.removeEventListener('keydown', this.handleKeyboardInput); } if (nextProps.isOpen) { BODY.style.overflow = 'hidden'; } else { BODY.style.overflow = null; } }, handleKeyboardInput (event) { if (event.keyCode === 37) { this.gotoPrevious(); } else if (event.keyCode === 39) { this.gotoNext(); } else if (event.keyCode === 27) { this.props.onCancel(); } else { return false; } }, gotoPrevious () { if (this.state.currentImage === 0) return; this.setState({ currentImage: this.state.currentImage - 1, }); }, gotoNext () { if (this.state.currentImage === (this.props.images.length - 1)) return; this.setState({ currentImage: this.state.currentImage + 1, }); }, renderArrowPrev () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage > 0) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowPrev)} onClick={this.gotoPrevious} className="octicon octicon-chevron-left" />} </Transition> ); }, renderArrowNext () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage < (this.props.images.length - 1)) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowNext)} onClick={this.gotoNext} className="octicon octicon-chevron-right" />} </Transition> ); }, renderBackdrop () { if (!this.props.isOpen) return; return <div key="backdrop" style={styles.backdrop} onClick={this.props.backdropClosesModal ? this.props.onCancel : null} />; }, renderCloseButton () { if (!this.props.showCloseButton) return; return <button key="close" style={styles.close} onClick={this.props.onCancel}>Close</button>; }, renderDialog () { if (!this.props.isOpen) return; return ( <div key="dialog" style={Object.assign({}, styles.dialog, { height: this.props.height, width: this.props.width })}> {this.renderImages()} {this.renderArrowPrev()} {this.renderArrowNext()} {this.renderCloseButton()} </div> ); }, renderImages () { const { images } = this.props; const { currentImage } = this.state; if (!images || !images.length) return; return ( <Transition transitionName="react-transitiongroup-fade" style={styles.imageContainer} component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> <img key={'image' + currentImage} src={images[currentImage]} style={styles.image} /> </Transition> ); }, render () { const props = blacklist(this.props, 'backdropClosesModal', 'initialImage', 'height', 'images', 'isOpen', 'onCancel', 'showCloseButton', 'width'); return ( <Portal {...props}> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderDialog()} </Transition> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderBackdrop()} </Transition> </Portal> ); }, }); const styles = { arrow: { background: 'none', border: 'none', bottom: 0, color: 'white', fontSize: 48, right: 0, outline: 'none', padding: 0, position: 'absolute', top: 0, width: '10%', zIndex: 1002, // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, arrowNext: { right: 0, }, arrowPrev: { left: 0, }, backdrop: { backgroundColor: 'rgba(0,0,0,0.66)', bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1000, }, close: { background: 'none', border: 'none', bottom: -32, color: 'white', fontSize: 16, height: 32, left: 0, marginLeft: 'auto', marginRight: 'auto', outline: 'none', padding: 0, position: 'absolute', right: 0, textAlign: 'center', textTransform: 'uppercase', width: 100, }, dialog: { // backgroundColor: 'rgba(255,255,255,0.26)', left: 0, lineHeight: 1, marginLeft: 'auto', marginRight: 'auto', maxHeight: '100%', maxWidth: '100%', position: 'fixed', right: 0, top: '50%', zIndex: 1001, WebkitTransform: 'translateY(-50%)', MozTransform: 'translateY(-50%)', msTransform: 'translateY(-50%)', transform: 'translateY(-50%)', }, image: { boxShadow: '0 1px 4px rgba(0,0,0,0.25)', maxHeight: '100%', maxWidth: '80%', position: 'absolute', // center the image within the dialog left: '50%', top: '50%', WebkitTransform: 'translate(-50%, -50%)', MozTransform: 'translate(-50%, -50%)', msTransform: 'translate(-50%, -50%)', transform: 'translate(-50%, -50%)', // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, }; module.exports = Lightbox;
ide/static/js/field.js
Cloud-CV/IDE
import React from 'react'; class Field extends React.Component { constructor(props) { super(props); this.change = this.change.bind(this); } change(e) { if (this.props.data.type === 'checkbox') { this.props.changeField(this.props.id, e.target.checked); } else if(this.props.data.type === 'number') { this.props.changeField(this.props.id, Number(e.target.value)); } else { this.props.changeField(this.props.id, e.target.value); } } render() { const type = this.props.data.type; let inputElement; if (type === 'text') { inputElement = ( <input type="text" disabled={this.props.disabled} value={this.props.value} className="form-control" id={this.props.id} onChange={this.change} /> ); } else if (type === 'number') { inputElement = ( <input type="number" value={this.props.value} disabled={this.props.disabled} className="form-control" id={this.props.id} onChange={this.change} /> ); } else if (type === 'float') { inputElement = ( <input type="number" step="0.01" disabled={this.props.disabled} value={this.props.value} className="form-control" id={this.props.id} onChange={this.change} /> ); } else if (type === 'select') { const options = []; this.props.data.options.forEach(i => { options.push(<option key={i} value={i}>{i}</option>); }); inputElement = ( <select value={this.props.value} id={this.props.id} disabled={this.props.disabled} className="form-control" onChange={this.change} > {options} </select> ); } else if (type === 'checkbox') { inputElement = ( <div className="paramsCheckbox"> <input type="checkbox" disabled={this.props.disabled} checked={this.props.value} id={this.props.id} onChange={this.change} /> <label htmlFor={this.props.id}></label> </div> ); } let displayStyle = "inherit"; if (inputElement.props.className == 'paramsCheckbox'){ displayStyle = "flex"; } return ( <div style={{display: displayStyle}}> <label htmlFor={this.props.id} className="sidebar-heading" style={{fontSize:"0.85em"}}> {this.props.data.name.toUpperCase()} </label> {inputElement} <br/> </div> ); } } Field.propTypes = { id: React.PropTypes.string.isRequired, data: React.PropTypes.object, changeField: React.PropTypes.func, value: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.bool ]), disabled: React.PropTypes.bool }; export default Field;
src/routes/resume-purty/index.js
oct16/Blog-FE
import React from 'react' import Layout from 'components/Layout' import Resume from 'components/Docment/Resume' export default { path: '/resume/purty', async action() { const data = await require.ensure([], require => require('../resume/resume.md'), 'resume'); return { title: 'Resume-Purty', chunk: 'Resume-Purty', component: <Resume {...data} /> } }, }
packages/mineral-ui-icons/src/IconTexture.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 IconTexture(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M19.51 3.08L3.08 19.51c.09.34.27.65.51.9.25.24.56.42.9.51L20.93 4.49c-.19-.69-.73-1.23-1.42-1.41zM11.88 3L3 11.88v2.83L14.71 3h-2.83zM5 3c-1.1 0-2 .9-2 2v2l4-4H5zm14 18c.55 0 1.05-.22 1.41-.59.37-.36.59-.86.59-1.41v-2l-4 4h2zm-9.71 0h2.83L21 12.12V9.29L9.29 21z"/> </g> </Icon> ); } IconTexture.displayName = 'IconTexture'; IconTexture.category = 'image';
public/js/cat_source/es6/components/analyze/JobAnalyze.js
Ostico/MateCat
import React from 'react' import JobAnalyzeHeader from './JobAnalyzeHeader' import JobTableHeader from './JobTableHeader' import ChunkAnalyze from './ChunkAnalyze' import AnalyzeConstants from '../../constants/AnalyzeConstants' import AnalyzeStore from '../../stores/AnalyzeStore' class JobAnalyze extends React.Component { constructor(props) { super(props) this.showDetails = this.showDetails.bind(this) } getChunks() { let self = this if (this.props.chunks) { return _.map(this.props.jobInfo.chunks, function (item, index) { let files = self.props.chunks.get(item.jpassword) index++ let job = self.props.project.get('jobs').find(function (jobElem) { return jobElem.get('password') === item.jpassword }) return ( <ChunkAnalyze key={item.jpassword} files={files} job={job} project={self.props.project} total={self.props.total.get(item.jpassword)} index={index} chunkInfo={item} chunksSize={_.size(self.props.jobInfo.chunks)} /> ) }) } return '' } showDetails(idJob) { if (idJob == this.props.idJob) { this.scrollElement() } } scrollElement() { let itemComponent = this.container let self = this if (itemComponent) { this.container.classList.add('show-details') $('html, body').animate( { scrollTop: $(itemComponent).offset().top, }, 500, ) // ReactDOM.findDOMNode(itemComponent).scrollIntoView({block: 'end'}); setTimeout(function () { self.container.classList.remove('show-details') }, 1000) } else { setTimeout(function () { self.scrollElement() }, 500) } } componentDidMount() { AnalyzeStore.addListener(AnalyzeConstants.SHOW_DETAILS, this.showDetails) } componentWillUnmount() { AnalyzeStore.removeListener(AnalyzeConstants.SHOW_DETAILS, this.showDetails) } shouldComponentUpdate() { return true } render() { return ( <div className="job ui grid"> <div className="job-body sixteen wide column"> <div className="ui grid chunks"> <div className="chunk-container sixteen wide column"> <div className="ui grid analysis" ref={(container) => (this.container = container)} > <JobAnalyzeHeader totals={this.props.total} project={this.props.project} jobInfo={this.props.jobInfo} status={this.props.status} /> <JobTableHeader rates={this.props.jobInfo.rates} /> {this.getChunks()} </div> </div> </div> </div> </div> ) } } export default JobAnalyze
src/react.js
ngbrown/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
frontend/src/Calendar/Day/CalendarDayConnector.js
Radarr/Radarr
import _ from 'lodash'; import moment from 'moment'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import CalendarDay from './CalendarDay'; function sort(items) { return _.sortBy(items, (item) => { if (item.isGroup) { return moment(item.events[0].inCinemas).unix(); } return moment(item.inCinemas).unix(); }); } function createCalendarEventsConnector() { return createSelector( (state, { date }) => date, (state) => state.calendar.items, (date, items) => { const filtered = _.filter(items, (item) => { return (item.inCinemas && moment(date).isSame(moment(item.inCinemas), 'day')) || (item.physicalRelease && moment(date).isSame(moment(item.physicalRelease), 'day')) || (item.digitalRelease && moment(date).isSame(moment(item.digitalRelease), 'day')); }); return sort(filtered); } ); } function createMapStateToProps() { return createSelector( (state) => state.calendar, createCalendarEventsConnector(), (calendar, events) => { return { time: calendar.time, view: calendar.view, events }; } ); } class CalendarDayConnector extends Component { // // Render render() { return ( <CalendarDay {...this.props} /> ); } } CalendarDayConnector.propTypes = { date: PropTypes.string.isRequired }; export default connect(createMapStateToProps)(CalendarDayConnector);
src/components/common/svg-icons/hardware/keyboard-capslock.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardCapslock = (props) => ( <SvgIcon {...props}> <path d="M12 8.41L16.59 13 18 11.59l-6-6-6 6L7.41 13 12 8.41zM6 18h12v-2H6v2z"/> </SvgIcon> ); HardwareKeyboardCapslock = pure(HardwareKeyboardCapslock); HardwareKeyboardCapslock.displayName = 'HardwareKeyboardCapslock'; HardwareKeyboardCapslock.muiName = 'SvgIcon'; export default HardwareKeyboardCapslock;
packages/wix-style-react/src/ColorInput/ColorInput.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Input from '../Input'; import { Hash } from './components/Hash'; import { ColorViewer } from './components/ColorViewer'; import { validateHex, normalizeHexInput } from './hex-helpers'; import Box from '../Box'; class ColorInput extends React.Component { static displayName = 'ColorInput'; static propTypes = { /** placeholder to display */ placeholder: PropTypes.string, /** when set to true this component is disabled */ disabled: PropTypes.bool, /** Sets UI to indicate a status */ status: PropTypes.oneOf(['error', 'warning', 'loading']), /** The status message to display when hovering the status icon, if not given or empty there will be no tooltip */ statusMessage: PropTypes.node, /** input size */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** colorpicker popover placement */ popoverPlacement: PropTypes.oneOf([ 'auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start', ]), /** colorpicker popover calculation to a dom element */ popoverAppendTo: PropTypes.oneOf([ 'window', 'scrollParent', 'viewport', 'parent', ]), /** input value */ value: PropTypes.string.isRequired, /** returns confirmed value */ onConfirm: PropTypes.func, /** returns last confirmed value which is from user prop - value */ onCancel: PropTypes.func, /** returns either input's or colorpicker's changed value */ onChange: PropTypes.func, /** Children to render in <ColorPicker /> component */ colorPickerChildren: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), /** Callback called with color `hex` string when add color button pressed */ onAddColor: PropTypes.func, /** Content to show in color picker add button tooltip */ addTooltipContent: PropTypes.node, /** Popover props */ popoverProps: PropTypes.object, }; static defaultProps = { placeholder: '', size: 'medium', popoverPlacement: 'bottom', popoverAppendTo: 'parent', onChange: () => {}, onConfirm: () => {}, onCancel: () => {}, popoverProps: {}, }; constructor(props) { super(props); this.state = { active: false, previous: props.value, value: '', }; } static getDerivedStateFromProps(props, state) { if (!state.active && props.value !== state.value) { return { value: normalizeHexInput(props.value), }; } return {}; } _renderPrefix = () => { const { disabled, size } = this.props; const { active, value } = this.state; const hash = ( <Input.Affix> <Hash disabled={disabled} size={size} /> </Input.Affix> ); return active || value ? hash : undefined; }; _renderSuffix = () => { const { value, active } = this.state; const { size, popoverPlacement, popoverAppendTo, disabled, colorPickerChildren, onAddColor, addTooltipContent, placeholder, popoverProps, } = this.props; return ( <Box verticalAlign="middle"> <ColorViewer value={value} active={active} disabled={disabled} size={size} placement={popoverPlacement} appendTo={popoverAppendTo} onClick={this.click} onChange={this._onPickerChange} onCancel={this.cancel} onConfirm={this.confirm} onClickOutside={this.confirm} children={colorPickerChildren} onAddColor={onAddColor} addTooltipContent={addTooltipContent} placeholder={placeholder} popoverProps={popoverProps} /> </Box> ); }; _onChange = evt => { const { onChange } = this.props; const value = normalizeHexInput(evt.target.value); this.setState({ value }, () => onChange(value)); }; _onPickerChange = value => { const { onChange } = this.props; this.setState({ active: true, value }, () => onChange(value)); }; _onFocus = () => this.setState({ active: true }); _keyDown = e => { e.stopPropagation(); e.key === 'Enter' && this.confirm(); e.key === 'Escape' && this.cancel(); }; /** * clicks the input element * @returns {Void} */ click = () => { this.input.focus(); this.setState({ active: true }); }; /** * sets the picked color * @returns {Void} */ confirm = () => { const { onConfirm, onChange } = this.props; const value = validateHex(this.state.value); this.setState({ active: false, value, previous: value }, () => { onConfirm(value); onChange(value); }); }; /** * sets the previous color * @returns {Void} */ cancel = () => { const { onCancel, onChange } = this.props; const { previous } = this.state; this.setState({ active: false, value: previous }, () => { onCancel(previous); onChange(previous); }); }; render() { const { placeholder, size, ...rest } = this.props; const { active, value } = this.state; return ( <Input {...rest} ref={input => (this.input = input)} placeholder={active ? '' : placeholder} size={size} onKeyDown={this._keyDown} onChange={this._onChange} onFocus={this._onFocus} onInputClicked={this.click} value={value.replace('#', '')} prefix={this._renderPrefix()} suffix={this._renderSuffix()} /> ); } } export default ColorInput;
client/pages/examples/threejs/tensors/elements/basics-ortho.js
fdesjardins/webgl
import React from 'react' import PT from 'prop-types' import * as THREE from 'three' import threeOrbitControls from 'three-orbit-controls' import { createAxes, createLineGraph, create3dGraph } from '../utils' const init = ({ state }) => { const canvas = document.getElementById('ex1') let scene = new THREE.Scene() // const camera = new THREE.PerspectiveCamera(75, canvas.clientWidth / canvas.clientWidth, 0.1, 1000) const camera = new THREE.OrthographicCamera( canvas.clientWidth / -2, canvas.clientWidth / 2, canvas.clientWidth / 2, canvas.clientWidth / -2, 0.1, 1000 ) camera.zoom = 4 camera.updateProjectionMatrix() camera.position.z = 65 camera.position.x = 27 camera.position.y = 7 let renderer = new THREE.WebGLRenderer({ canvas, antialias: true }) // renderer.shadowMap.enabled = true // renderer.shadowMap.type = THREE.PCFSoftShadowMap renderer.setSize(canvas.clientWidth, canvas.clientWidth) // scene.background = new THREE.Color(0xffffff) scene.background = new THREE.Color(0x000000) const OrbitControls = threeOrbitControls(THREE) const controls = new OrbitControls(camera, renderer.domElement) controls.enableDamping = true controls.update() const light = new THREE.PointLight(0xffffff, 2, 100) light.position.set(0, 0, 20) scene.add(light) const geometry = new THREE.IcosahedronGeometry(1) const material = new THREE.MeshPhongMaterial({ color: 0xffffff }) const object = new THREE.Mesh(geometry, material) const faceNormals = new THREE.FaceNormalsHelper(object, 2, 0x00ff00, 1) object.add(faceNormals) object.add(createAxes({ size: 12, fontSize: 2 })) scene.add(object) const xyGrid = new THREE.GridHelper(100, 20, 0x444444, 0x444444) scene.add(xyGrid) const xzGrid = new THREE.GridHelper(100, 20, 0x444444, 0x444444) xzGrid.rotation.x = Math.PI / 2 scene.add(xzGrid) const zyGrid = new THREE.GridHelper(100, 20, 0x444444, 0x444444) zyGrid.rotation.z = Math.PI / 2 scene.add(zyGrid) const { object: lineGraph, animate: animateLineGraph } = createLineGraph( (t) => (x) => 5 * Math.sin(x + t / 200), 'f(x) = 5 * sin(x)', 0x00ff00, 'dashed' ) const { object: lineGraph2, animate: animateLineGraph2 } = createLineGraph( (t) => (x) => 20 + 5 * Math.sin(x + t / 200), 'f(x) = 20 + 5 * sin(x)', 0xff0000 ) lineGraph2.rotation.y = Math.PI / 2 scene.add(lineGraph) scene.add(lineGraph2) const { object: graph3d, animate: animate3dGraph } = create3dGraph() scene.add(graph3d) const axes = createAxes({ size: 50 }) scene.add(axes) const resizeRendererToDisplaySize = (renderer) => { const canvas = renderer.domElement const width = canvas.clientWidth const height = canvas.clientHeight const needResize = canvas.width !== width || canvas.height !== height if (needResize) { renderer.setSize(width, height, false) } return needResize } const objectState = state.select('object') let thenSecs = 0 const animate = (now) => { if (!renderer) { return } if (resizeRendererToDisplaySize(renderer)) { const c = renderer.domElement camera.aspect = c.clientWidth / c.clientHeight camera.left = c.clientWidth / -2 camera.right = c.clientWidth / 2 camera.top = c.clientHeight / 2 camera.bottom = c.clientHeight / -2 camera.updateProjectionMatrix() } requestAnimationFrame(animate) const nowSecs = now * 0.001 const deltaSecs = nowSecs - thenSecs thenSecs = nowSecs // animateGraph1(now) // animateGraph2(now) animateLineGraph(now) animateLineGraph2(now) animate3dGraph(now) if (deltaSecs) { const rotationSpeed = objectState.get('rotationSpeed') object.rotation.x += rotationSpeed.x * deltaSecs object.rotation.y += rotationSpeed.y * deltaSecs object.rotation.z += rotationSpeed.z * deltaSecs object.position.x = Math.cos(nowSecs) * 50 object.position.y = Math.sin(nowSecs) * 50 objectState.set('position', object.position) objectState.set('rotation', { x: object.rotation.x, y: object.rotation.y, z: object.rotation.z, }) // axes.children.map(child => child.lookAt(camera.position)) } renderer.render(scene, camera) } animate() return () => { renderer.dispose() scene = null renderer = null } } const BasicsOrtho = ({ state, labels }) => { React.useEffect(() => { if (document.getElementById('ex1')) { return init({ state }) } }) return <canvas id="ex1" /> } BasicsOrtho.propTypes = { state: PT.object, labels: PT.array, } export { init } export default BasicsOrtho
src/js/components/icons/base/Revert.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-revert`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'revert'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M8,3 L3,8 L8,13 M12,20 L15,20 C18.3137085,20 21,17.3137085 21,14 C21,10.6862915 18.3137085,8 15,8 L4,8"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Revert'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
docs/app/components/editor/index.js
react-toolbox/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import CodeMirror from 'codemirror'; import style from './style.css'; import 'codemirror/lib/codemirror.css'; import 'codemirror/mode/javascript/javascript.js'; import './one-dark.css'; class Editor extends React.Component { static propTypes = { className: PropTypes.string, codeText: PropTypes.string, lineNumbers: PropTypes.bool, onChange: PropTypes.func, readOnly: PropTypes.bool, tabSize: PropTypes.number, theme: PropTypes.string }; static defaultProps = { className: '', lineNumbers: false, readOnly: false, tabSize: 2, theme: 'one-dark' }; componentDidMount () { this.editor = CodeMirror.fromTextArea(this.refs.editor, { mode: 'javascript', lineNumbers: this.props.lineNumbers, smartIndent: false, tabSize: this.props.tabSize, matchBrackets: true, theme: this.props.theme, readOnly: this.props.readOnly }); this.editor.on('change', this.handleChange); } componentDidUpdate () { if (this.props.readOnly) { this.editor.setValue(this.props.codeText); } } handleChange = () => { if (!this.props.readOnly && this.props.onChange) { this.props.onChange(this.editor.getValue()); } }; setCode (code) { this.editor.getDoc().setValue(code); this.handleChange(); } render () { let className = style.editor; if (this.props.className) className += ` ${this.props.className}`; return ( <div className={className}> <textarea ref="editor" defaultValue={this.props.codeText} /> </div> ); } } export default Editor;
src/example/Example.js
nkbt/dashboard
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; const appRoot = document.createElement('div'); appRoot.id = 'app'; document.body.appendChild(appRoot); ReactDOM.render(<App />, appRoot);
frontend/src/app/containers/SharePage.js
6a68/testpilot
import React from 'react'; import View from '../components/View'; export default class SharePage extends React.Component { render() { return ( <View spaceBetween={true} showNewsletterFooter={false} {...this.props}> <div className="centered-banner"> <div id="share" className="modal delayed-fade-in"> <div className="modal-content"> <p data-l10n-id="sharePrimary">Love Test Pilot? Help us find some new recruits.</p> <ul className="share-list"> <li className="share-facebook"><a href={'https://www.facebook.com/sharer/sharer.php?u=' + this.shareUrl('facebook', true)} onClick={this.handleClick('facebook')} target="_blank">Facebook</a></li> <li className="share-twitter"><a href={'https://twitter.com/home?status=' + this.shareUrl('twitter', true)} onClick={this.handleClick('twitter')} target="_blank">Twitter</a></li> <li className="share-email"><a href={'mailto:?body=' + this.shareUrl('email', true)} data-l10n-id="shareEmail" onClick={this.handleClick('email')}>E-mail</a></li> </ul> <p data-l10n-id="shareSecondary">or just copy and paste this link...</p> <fieldset className="share-url-wrapper"> <div className="share-url"> <input type="text" readOnly value={this.shareUrl('copy', false)} /> <button data-l10n-id="shareCopy" onClick={this.handleClick('copy')} data-clipboard-target=".share-url input">Copy</button> </div> </fieldset> </div> </div> <div className="copter-wrapper"> <div className="copter fade-in-fly-up"></div> </div> </div> </View> ); } shareUrl(medium, urlencode) { const url = `https://testpilot.firefox.com/?utm_source=${medium}&utm_medium=social&utm_campaign=share-page`; return urlencode ? encodeURIComponent(url) : url; } handleClick(label) { return () => this.props.sendToGA('event', { eventCategory: 'ShareView Interactions', eventAction: 'button click', eventLabel: label }); } } SharePage.propTypes = { hasAddon: React.PropTypes.bool, uninstallAddon: React.PropTypes.func, sendToGA: React.PropTypes.func, openWindow: React.PropTypes.func };
examples/huge-apps/routes/Grades/components/Grades.js
CivBase/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
lib/components/Button.js
StephanieEA/firebae
import React from 'react'; const Button = ({ text, onClick, className }) => <button className={className} aria-label={text} onClick={onClick}>{text}</button> export default Button;
docs/src/IntroductionPage.js
snadn/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
src/components/mail/composeMail.js
EncontrAR/backoffice
import React, { Component } from 'react'; import Async from '../../helpers/asyncComponent'; import Button from '../uielements/button'; import Input from '../uielements/input'; import ComposeAutoComplete from './composeAutoComplete'; import notification from '../notification'; import IntlMessages from '../utility/intlMessages'; // import '../../style/mailbox/draft-editor.css'; const Editor = props => <Async load={import(/* webpackChunkName: "compose-mAIL--editor" */ '../uielements/editor')} componentProps={props} />; function uploadCallback(file) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.imgur.com/3/image'); xhr.setRequestHeader('Authorization', 'Client-ID 8d26ccd12712fca'); const data = new FormData(); data.append('image', file); xhr.send(data); xhr.addEventListener('load', () => { const response = JSON.parse(xhr.responseText); resolve(response); }); xhr.addEventListener('error', () => { const error = JSON.parse(xhr.responseText); reject(error); }); }); } export default class ComposeMail extends Component { constructor(props) { super(props); this.state = { editorState: null, loading: false, iconLoading: false }; } render() { const onEditorStateChange = editorState => { this.setState({ editorState }); }; const ComposeAutoCompleteTO = { allMails: this.props.allMails, updateData: () => {}, placeholder: 'To' }; const ComposeAutoCompleteCC = { allMails: this.props.allMails, updateData: () => {}, placeholder: 'CC' }; const editorOption = { style: { width: '90%', height: '70%' }, editorState: this.state.editorState, toolbarClassName: 'home-toolbar', wrapperClassName: 'home-wrapper', editorClassName: 'home-editor', onEditorStateChange: onEditorStateChange, uploadCallback: uploadCallback, toolbar: { image: { uploadCallback: uploadCallback } } }; return ( <div className="isoComposeMailWrapper"> <ComposeAutoComplete {...ComposeAutoCompleteTO} /> <ComposeAutoComplete {...ComposeAutoCompleteCC} /> <Input placeholder="Subject" className="isoInputBox" /> <Editor {...editorOption} /> <div className="isoComposeMailBtnWrapper"> {this.props.mobileView ? <Button type="primary" onClick={() => { this.props.changeComposeMail(false); }} className="isoCancelMailBtn" > <IntlMessages id="email.cancel" /> </Button> : ''} <Button type="primary" onClick={e => notification('success', `Mail has been sent`, '')} className="isoSendMailBtn" > <IntlMessages id="email.send" /> </Button> </div> </div> ); } }
frontend/src/components/ExpenseEmptyState.js
OpenCollective/opencollective-website
import React from 'react'; export default ({i18n}) => { return ( <div className='center'> <div className='flex items-center justify-center'> <img width='111' height='151' src='/public/images/collectives/expenses-empty-state-image.jpg' srcSet='/public/images/collectives/[email protected] 2x'/> </div> <p className='h3 -fw-bold'>{i18n.getString('expensesPlaceholderTitle')}</p> <p className='h5 muted mb3'>{i18n.getString('expensesPlaceholderText')}</p> </div> ); }
Demo/src/components/ListItem.js
bspaulding/presentation-react-router-4-universal-links
import React from 'react'; import { StyleSheet, View } from 'react-native'; import Text from './Text'; import Link from './Link'; const styles = StyleSheet.create({ text: { flex: 1, fontSize: 21, paddingVertical: 12, textAlign: 'center' } }); const ListItem = ({ children, to }) => ( <Link to={to}> <View> <Text style={styles.text}>{children}</Text> </View> </Link> ); export default ListItem;
imports/startup/client/index.js
kishigo/react.drought
/** * The MIT License (MIT) * * Copyright (c) 2016 kishigo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import React from 'react'; import { ReactDOM, render } from 'react-dom'; import './routes.jsx'; import { createStore } from 'redux'; import { combineReducers } from 'redux'; import { Provider, connect } from 'react-redux'; import Sample from '../../ui/components/index.jsx'; //render( // <Provider store={store}> // <Sample /> // </Provider>, // document.getElementById('react-root') //); //var child1 = React.createElement('li', null, 'First Text Content'); //var root = React.createElement('ul', { className: 'my-list' }, child1); //ReactDOM.render(root, document.getElementById('react-root'));
js/components/comments/index.js
chris50bn/Between
'use strict'; import React, { Component } from 'react'; import { Image, View, TouchableOpacity, Platform } from 'react-native'; import { connect } from 'react-redux'; import { popRoute } from '../../actions/route'; import { Container, Header, Content, Text, Input, Button, Icon, Card, CardItem, Thumbnail } from 'native-base'; import { Grid, Col, Row } from 'react-native-easy-grid'; import theme from '../../themes/base-theme'; import styles from './style'; var primary = require('../../themes/variable').brandPrimary; class Comments extends Component { constructor(props) { super(props); this.state = { offset: { x:0, y:0 } }; this.constructor.childContextTypes = { theme: React.PropTypes.object, } } popRoute() { this.props.popRoute(); } render() { return ( <Container theme={theme}> <Image source={require('../../../images/glow2.png')} style={styles.container} > <Header> <Grid style={styles.headerContainer}> <Col style={styles.headerBtns}> <Button transparent onPress={() => this.popRoute()}> <Icon name='ios-arrow-back' style={styles.headerIcons} /> </Button> </Col> <Col style={styles.headerBtns}> <Button transparent> <Icon name='ios-chatboxes-outline' style={styles.headerIcons} /> </Button> </Col> <Col style={styles.headerBtns}> <Button transparent> <Text style={styles.headerTextIcon}>Aa</Text> </Button> </Col> <Col style={styles.headerBtns} > <Button transparent> <Icon name='ios-bookmarks-outline' style={styles.headerIcons} /> </Button> </Col> <Col style={styles.headerBtns}> <Button transparent> <Icon name='ios-download-outline' style={styles.headerIcons} /> </Button> </Col> </Grid> </Header> <View style={styles.commentHeadbg}> <Text style={styles.commentHeader}>23 COMMENTS</Text> <Grid> <Col> <Button rounded primary block style={styles.channelBtn1} textStyle={Platform.OS === 'android' ? {fontSize: 12, lineHeight:15, fontWeight: '900',textAlign: 'center'} : {fontSize: 12, lineHeight:15, fontWeight: '900'}} > Best </Button> </Col> <Col> <Button transparent block textStyle={{fontSize: 12,fontWeight: '900',textAlign: 'center', lineHeight:15}}> Newest </Button> </Col> <Col> <Button transparent block textStyle={{fontSize: 12,fontWeight: '900',textAlign: 'center', lineHeight:15}}> Oldest </Button> </Col> </Grid> </View> <Content> <Card foregroundColor='#222' style={styles.card}> <CardItem style={styles.cardHeader} header> <Thumbnail source={require('../../../images/contacts/sanket.png')} style={Platform.OS === 'android' ? {borderRadius: 40} : {}} /> <Text>Kumar Sanket</Text> <Icon name='ios-time-outline' style={styles.timeIcon} /> <Text style={styles.date}>May 24, 11:00 AM</Text> <Icon name='ios-heart-outline' style={styles.likeIcon} /> <Text style={styles.date}>12</Text> </CardItem> <CardItem style={styles.cardItem} > <Text> Contrary to popular belief, Lorem Ipsum is not simply random text. </Text> </CardItem> </Card> <Card foregroundColor='#222' style={styles.card}> <CardItem style={styles.cardHeader} header> <Thumbnail source={require('../../../images/contacts/pratik.png')} style={Platform.OS === 'android' ? {borderRadius: 40} : {}}/> <Text>Kumar Pratik</Text> <Icon name='ios-time-outline' style={styles.timeIcon} /> <Text style={styles.date}>May 24, 11:00 AM</Text> <Icon name='ios-heart-outline' style={styles.likeIcon} /> <Text style={styles.date}>12</Text> </CardItem> <CardItem style={styles.cardItem} > <Text> It is a long established fact that a reader will be distracted by the readable content. </Text> </CardItem> </Card> <Card foregroundColor='#222' style={styles.card}> <CardItem style={styles.cardHeader} header> <Thumbnail source={require('../../../images/contacts/saurav.png')} style={Platform.OS === 'android' ? {borderRadius: 40} : {}}/> <Text>Saurav Sahu</Text> <Icon name='ios-time-outline' style={styles.timeIcon} /> <Text style={styles.date}>Feb 17, 04:30 PM</Text> <Icon name='ios-heart-outline' style={styles.likeIcon} /> <Text style={styles.date}>5</Text> </CardItem> <CardItem style={styles.cardItem} > <Text> There are many variations of passages of Lorem Ipsum available. </Text> </CardItem> </Card> <Card foregroundColor='#222' style={styles.card}> <CardItem style={styles.cardHeader} header> <Thumbnail source={require('../../../images/contacts/atul.png')} style={Platform.OS === 'android' ? {borderRadius: 40} : {}}/> <Text>Atul Ranjan</Text> <Icon name='ios-time-outline' style={styles.timeIcon} /> <Text style={styles.date}>Feb 03, 01:00 PM</Text> <Icon name='ios-heart-outline' style={styles.likeIcon} /> <Text style={styles.date}>5</Text> </CardItem> <CardItem style={styles.cardItem} > <Text> The generated Lorem Ipsum is therefore always free from repetition </Text> </CardItem> </Card> <Card foregroundColor='#222' style={styles.card}> <CardItem style={styles.cardHeader} header> <Thumbnail source={require('../../../images/contacts/varun.png')} style={Platform.OS === 'android' ? {borderRadius: 40} : {}}/> <Text>Varun Sahu</Text> <Icon name='ios-time-outline' style={styles.timeIcon} /> <Text style={styles.date}>Jan 12, 09:30 PM</Text> <Icon name='ios-heart-outline' style={styles.likeIcon} /> <Text style={styles.date}>4</Text> </CardItem> <CardItem style={styles.cardItem} > <Text> Various versions have evolved over the years, sometimes by accident </Text> </CardItem> </Card> </Content> <View style={styles.commentBox}> <View style={styles.attachIconContainer}> <Icon name='ios-attach' style={styles.attachIcon} /> </View> <Input placeholder='Write something...' placeholderTextColor='#797979' style={styles.input}/> <TouchableOpacity style={styles.arrowForwardIconContainer}> <Icon name='ios-arrow-forward' style={styles.arrowForwardIcon} /> </TouchableOpacity> </View> </Image> </Container> ) } } function bindAction(dispatch) { return { popRoute: () => dispatch(popRoute()) } } export default connect(null, bindAction)(Comments);
src/main.js
patrickfatrick/wonderland
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import App from './App'; import './styles/base.css'; // `path` prop would probably be passed in from the server or URL render( <Provider store={store}> <App bookId="26tniea82c" /> </Provider>, document.getElementById('app'), );
src/index.js
Iconscout/logodrop
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import { visitor } from './ga' import sketchLogosApp from './reducers' import App from './components/App' import './stylesheets/main.css' import { checkPluginUpdate, fetchLogos } from './actions' //import '../node_modules/bootstrap/dist/css/bootstrap.css' let store = createStore( sketchLogosApp, applyMiddleware(thunk) ) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); store.dispatch(checkPluginUpdate()) store.dispatch(fetchLogos("logo")) window.ga = visitor visitor.pageview('/', 'com.iconscout.sketch.logodrop').event('app', 'sketch').send()
chapter-11/chunked_with_redux/src/pages/NotFound.js
mocheng/react-and-redux
import React from 'react'; const NotFound = () => { return ( <div>404: Not Found</div> ); }; export default NotFound;
react_preset/index.js
pavbox/webpack-configs-collection
import React from 'react' import ReactDOM from 'react-dom' import Button from './components/Button' import Table from './components/Table' ReactDOM.render( <div> <h1>bobby</h1> <Table name="pbx row" /> <Button /> </div> , document.getElementById("root") ) /* Application design main page - schedule board - week switcher - some widgets */
examples/src/app.js
markdalgleish/react-autosuggest
require('./app.less'); import React, { Component } from 'react'; import Badges from './Badges/Badges'; import Examples from './Examples'; import Footer from './Footer/Footer'; import ForkMeOnGitHub from './ForkMeOnGitHub/ForkMeOnGitHub'; class App extends Component { // eslint-disable-line no-shadow render() { return ( <div> <h1>react-autosuggest</h1> <Badges /> <Examples /> <Footer /> <ForkMeOnGitHub user="moroshko" repo="react-autosuggest" /> </div> ); } } React.render(<App />, document.getElementById('app'));
src/icons/AndroidCheckboxBlank.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidCheckboxBlank extends React.Component { render() { if(this.props.bare) { return <g> <g id="Icon_23_"> <g> <path d="M405.333,64H106.667C83.198,64,64,83.198,64,106.667v298.666C64,428.802,83.198,448,106.667,448h298.666 C428.802,448,448,428.802,448,405.333V106.667C448,83.198,428.802,64,405.333,64z"></path> </g> </g> </g>; } return <IconBase> <g id="Icon_23_"> <g> <path d="M405.333,64H106.667C83.198,64,64,83.198,64,106.667v298.666C64,428.802,83.198,448,106.667,448h298.666 C428.802,448,448,428.802,448,405.333V106.667C448,83.198,428.802,64,405.333,64z"></path> </g> </g> </IconBase>; } };AndroidCheckboxBlank.defaultProps = {bare: false}
app/index.js
manti-by/Archimed
import './node_modules/react-mdl/extra/material.min.css'; import './node_modules/react-mdl/extra/material.min.js'; import React from 'react'; import { render } from 'react-dom'; import configureStore from './store/configure'; import App from './containers/App'; const store = configureStore(); render( <App store={store} />, document.getElementById('root') );
server/client/routes.js
stevenlundy/agnition
import React from 'react'; import { Route } from 'react-router'; import App from './screens/App'; import Dashboard from './screens/Dashboard'; import NewExperiment from './screens/NewExperiment'; import About from './components/About'; export default ( <div> <Route path="/" component={App}> <Route path="/dashboard" component={Dashboard} /> <Route path="/new-experiment" component={NewExperiment} /> </Route> <Route path="/about" component={About} /> </div> );
src/svg-icons/action/help-outline.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHelpOutline = (props) => ( <SvgIcon {...props}> <path d="M11 18h2v-2h-2v2zm1-16C6.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 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"/> </SvgIcon> ); ActionHelpOutline = pure(ActionHelpOutline); ActionHelpOutline.displayName = 'ActionHelpOutline'; ActionHelpOutline.muiName = 'SvgIcon'; export default ActionHelpOutline;
local-cli/templates/HelloWorld/index.ios.js
gilesvangruisen/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
index.ios.js
shuiszhang/fanfou
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './app/app'; AppRegistry.registerComponent('fanfou', () => App);
src/browser/components/Title.js
sikhote/davidsinclair
// @flow import Helmet from 'react-helmet'; import React from 'react'; import { injectIntl } from 'react-intl'; type TitleProps = {| intl: $IntlShape, message: string | Object, values?: Object, |}; const Title = ({ intl, message, values }: TitleProps) => ( typeof message === 'string' ? <Helmet title={message} /> : <Helmet title={intl.formatMessage(message, values)} /> ); export default injectIntl(Title);
app/javascript/mastodon/features/ui/util/react_router_helpers.js
verniy6462/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Switch from 'react-router-dom/Switch'; import Route from 'react-router-dom/Route'; import ColumnLoading from '../components/column_loading'; import BundleColumnError from '../components/bundle_column_error'; import BundleContainer from '../containers/bundle_container'; // Small wrapper to pass multiColumn to the route components export const WrappedSwitch = ({ multiColumn, children }) => ( <Switch> {React.Children.map(children, child => React.cloneElement(child, { multiColumn }))} </Switch> ); WrappedSwitch.propTypes = { multiColumn: PropTypes.bool, children: PropTypes.node, }; // Small Wraper to extract the params from the route and pass // them to the rendered component, together with the content to // be rendered inside (the children) export class WrappedRoute extends React.Component { static propTypes = { component: PropTypes.func.isRequired, content: PropTypes.node, multiColumn: PropTypes.bool, } renderComponent = ({ match }) => { const { component, content, multiColumn } = this.props; return ( <BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}> {Component => <Component params={match.params} multiColumn={multiColumn}>{content}</Component>} </BundleContainer> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { component: Component, content, ...rest } = this.props; return <Route {...rest} render={this.renderComponent} />; } }
variations/fix-state-way/src/components/Button.js
xaviervia/tessellation
import React from 'react' export default function Button ({children, title, ...props}) { return <button className='b--none bg-navy' {...props}> {children} <span className='below'>{title}</span> </button> }
lib/FocusLink/stories/FocusLink.stories.js
folio-org/stripes-components
import React from 'react'; import { storiesOf } from '@storybook/react'; import withReadme from 'storybook-readme/with-readme'; import readme from '../readme.md'; import BasicUsage from './BasicUsage'; storiesOf('FocusLink', module) .addDecorator(withReadme(readme)) .add('Basic Usage', () => <BasicUsage />);
src/components/ImgFigure.js
jiang-12196/gallery-by-react
/** * Created by jianghan on 2016/12/12. */ import React from 'react'; require('styles/ImgFigure.css'); require('normalize.css/normalize.css'); class ImgFigure extends React.Component { render () { console.log(this.props.inverse); let styleObj = {}; if (this.props.arrange.pos) { styleObj = this.props.arrange.pos } if(this.props.arrange.rotate) { (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach( function (value) { styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this) ); } let imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? '-is-inverse':''; return( <figure className={ imgFigureClassName } style={ styleObj } > <img src={this.props.data.imgURL} alt={this.props.data.title} /> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" > <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ) } } export { ImgFigure };
node_modules/redux-devtools-log-monitor/src/LogMonitorButtonBar.js
jotamaggi/react-calendar-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import shouldPureComponentUpdate from 'react-pure-render/function'; import { ActionCreators } from 'redux-devtools'; import LogMonitorButton from './LogMonitorButton'; const { reset, rollback, commit, sweep } = ActionCreators; const style = { textAlign: 'center', borderBottomWidth: 1, borderBottomStyle: 'solid', borderColor: 'transparent', zIndex: 1, display: 'flex', flexDirection: 'row' }; export default class LogMonitorButtonBar extends Component { static propTypes = { dispatch: PropTypes.func, theme: PropTypes.object }; shouldComponentUpdate = shouldPureComponentUpdate; constructor(props) { super(props); this.handleReset = this.handleReset.bind(this); this.handleRollback = this.handleRollback.bind(this); this.handleSweep = this.handleSweep.bind(this); this.handleCommit = this.handleCommit.bind(this); } handleRollback() { this.props.dispatch(rollback()); } handleSweep() { this.props.dispatch(sweep()); } handleCommit() { this.props.dispatch(commit()); } handleReset() { this.props.dispatch(reset()); } render() { const { theme, hasStates, hasSkippedActions } = this.props; return ( <div style={{...style, borderColor: theme.base02}}> <LogMonitorButton theme={theme} onClick={this.handleReset} enabled> Reset </LogMonitorButton> <LogMonitorButton theme={theme} onClick={this.handleRollback} enabled={hasStates}> Revert </LogMonitorButton> <LogMonitorButton theme={theme} onClick={this.handleSweep} enabled={hasSkippedActions}> Sweep </LogMonitorButton> <LogMonitorButton theme={theme} onClick={this.handleCommit} enabled={hasStates}> Commit </LogMonitorButton> </div> ); } }
src/components/Main.js
neoyoun/gallery-with-react
require('normalize.css/normalize.css'); require('styles/reset.css'); require('styles/App.scss'); import React from 'react'; //引用图片资源 let imageDatas = require('../data/imageDatas.json'); //利用自执行函数 ,根据图片名添加图片路径属性 imageDatas = (function getImageURL (imageDataArr) { for (let i = 0 ; i < imageDataArr.length; i++) { let singleImagaData = imageDataArr[i]; singleImagaData.imageURL = require('images/' + singleImagaData.fileName); imageDataArr[i] = singleImagaData; } return imageDataArr; })(imageDatas); //封装的获取范围的函数 let getRangeRandom = (low , high) => low + Math.round( Math.random() * (high - low)); //单个图片的组件,图片交互在这里实现 class ImgFigure extends React.Component{ constructor(props) { super(props); this.tick = this.tick.bind(this); } tick(e) { /* *翻转事件,props中的 inverseClick 属性; *选中居中事件,props中的 inCenterClick 属性; */ if(this.props.arrange.isCenter){ this.props.inverseClick(); }else{ this.props.inCenterClick(); } e.stopPropagation(); e.preventDefault(); } render(){ let styleObj={}; if(this.props.arrange.pos){ styleObj = this.props.arrange.pos; } if(this.props.arrange.rotate){ ['MozT','MsT','WebkitT','t'].forEach( value => { styleObj[value + 'ransform' ]= 'rotate('+this.props.arrange.rotate+'deg)'; }) } let isInverse = this.props.arrange.isInverse; let isCenter = this.props.arrange.isCenter; let imgFigureClsName = 'img-figure'; imgFigureClsName +=isCenter?' in-center':''; imgFigureClsName +=isInverse?' inverse':''; return ( <figure key={this.props.data.fileName} ref='imgbox' style={styleObj} className={imgFigureClsName} onClick={this.tick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> </figcaption> <div className="img-back" onClick={this.handleClick}> {this.props.data.description} </div> </figure> ) } } //下方控制组件 class ControllerUnits extends React.Component{ constructor(props) { super(props); this.tick = this.tick.bind(this); } //事件的命名不重要,在 constructor 中做了重新引用 tick(e) { /* *翻转事件,props中的 inverseClick 属性; *选中事件,props中的 selectClick 属性; */ if(this.props.status.isSelect){ this.props.inverseClick(); }else{ this.props.selectClick(); } e.stopPropagation(); e.preventDefault(); } render() { let isSelect = this.props.status.isSelect; let isInverse = this.props.status.isInverse; let controllerUnitClassName = 'controller-unit'; controllerUnitClassName += isSelect?' is-select':''; controllerUnitClassName += isInverse?' inverse':''; return (<span className={controllerUnitClassName} onClick={this.tick} ></span>); } } //主组件,设置了单个图片的加载方式 class GalleryByReactApp extends React.Component { constructor(props){ super(props) this.Constant = { centerPos : { left : 0, top : 0 }, hPosRange : { //水平方向取值范围 leftSecX : [0 , 0], rightSecX : [0 , 0], y : [0 , 0] }, vPosRange : { //垂直方向取值范围 x : [0 , 0], topY : [0 ,0] } } this.state = { imgsArrangeArr:[ /*{ pos: { left : 0, top : 0 }, rotate:0, isInverse:false, isCenter:false }*/ ], controllerUnitsArr :[ /* //控制按钮的状态有 3 种,未选中,选中,选中并翻转 { isSelect : false, isInverse : false }*/ ] } /* *定义图片翻转方法,返回一个函数供子组件调用 *@param idx 需要被翻转的图片和控制按钮的索引值 *@return {Function} */ this.inverse = idx =>{ return ()=> { let imgsArrangeArr = this.state.imgsArrangeArr; let controllerUnitsArr = this.state.controllerUnitsArr; imgsArrangeArr[idx].isInverse = !imgsArrangeArr[idx].isInverse; controllerUnitsArr[idx].isInverse = !controllerUnitsArr[idx].isInverse; // this.rearrange(idx); this.setState({ imgsArrangeArr : imgsArrangeArr, controllerUnitsArr : controllerUnitsArr }) } } /* *利用reararrange排列图片和选择当前按钮 ,和翻转一样返回一个闭包函数 *@param idx 需要被居中的图片和控制按钮的索引值 *@return {Funtction} */ this.center = idx =>{ return ()=>{ this.rearrange(idx) } } } /* *重新布局所有图片 *@param centerIndex 指定居中哪张图片 */ rearrange(centerIndex) { let imgsArrangeArr = this.state.imgsArrangeArr; let controllerUnitsArr = this.state.controllerUnitsArr; let Constant = this.Constant; let centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeX = vPosRange.x, vPosRangeTopY = vPosRange.topY; //将所有控制器的选中状态取消并改变当前按钮的属性 controllerUnitsArr.forEach(val =>{ val.isSelect = false }) controllerUnitsArr[centerIndex].isSelect = true; //每个区间分布图片设计为数组 //将目标图片设置为居中图片 let imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex , 1); imgsArrangeCenterArr[0] = { pos:centerPos, rotate:0, isCenter:true } imgsArrangeCenterArr[0].pos['zIndex'] = 100; //上区间 1 ~ 2 张图片 let imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), topImgSpliceIndex = 0; //选择上区间图片开始取值的index值,为了防止取值在数组末尾导致无值可取,需要在剩下的数组中把图片数量预留出来; topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)) imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex , topImgNum) //布局上侧的图片并设置图片状态,由于这里的索引值并不是和控制按钮索引值一一对应,所以不能在这里设置按钮状态 imgsArrangeTopArr.forEach((value,idx) => { imgsArrangeTopArr[idx].pos = { top : getRangeRandom(vPosRangeTopY[0] , vPosRangeTopY[1]), left : getRangeRandom(vPosRangeX[0] , vPosRangeX[1]) } imgsArrangeTopArr[idx].rotate = getRangeRandom(-20 , 20); imgsArrangeTopArr[idx].isCenter = false; imgsArrangeTopArr[idx].isInverse = false; }) //布局左右两侧的图片 for(let i = 0,l = imgsArrangeArr.length,k=l/2; i<l ; i++){ let hPosRangeLorRX = null; if(i < k){ hPosRangeLorRX = hPosRangeLeftSecX; }else { hPosRangeLorRX = hPosRangeRightSecX; } imgsArrangeArr[i].pos = { top : getRangeRandom(hPosRangeY[0] , hPosRangeY[1]), left : getRangeRandom(hPosRangeLorRX[0] , hPosRangeLorRX[1]) } imgsArrangeArr[i].rotate = getRangeRandom(-30 , 30); imgsArrangeArr[i].isCenter = false; imgsArrangeArr[i].isInverse = false; } //把顶部和中心取出的元素放回大数组中 if(imgsArrangeTopArr && imgsArrangeTopArr[0]){ imgsArrangeArr.splice(topImgSpliceIndex , 0 , ...imgsArrangeTopArr); } imgsArrangeArr.splice(centerIndex , 0 , ...imgsArrangeCenterArr); // console.log('rearrange done...'); this.setState({imgsArrangeArr:imgsArrangeArr , controllerUnitsArr:controllerUnitsArr}); //this.state.imgsArrangeArr = imgsArrangeArr; } //组件加载后,为每张图片设置位置 componentDidMount() { //获取舞台大小 let stageDOM = this.refs.stage; let stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //拿到一个 imgFigure 的大小 let imgFigureDOM = this.refs.imgFigure0.refs.imgbox; let imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH /2); //计算中心点的位置 this.Constant.centerPos = { left : halfStageW - halfImgW, top : halfStageH - halfImgH } //计算水平方向图片位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; //计算上侧区域图片位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH*3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); } render() { let controllerUnits = []; let imgfigures = []; imageDatas.forEach((value,idx) =>{ if(!this.state.imgsArrangeArr[idx]){ this.state.imgsArrangeArr[idx] = { pos: { left : 0, top : 0 }, rotate:0, isInverse:false, isCenter:false } this.state.controllerUnitsArr[idx] = { isSelect : false, isInverse : false } } imgfigures.push(<ImgFigure data={value} ref={'imgFigure' + idx} arrange={this.state.imgsArrangeArr[idx]} inverseClick={this.inverse(idx)} inCenterClick={this.center(idx)} key={idx}/>); controllerUnits.push(<ControllerUnits key={'ctrl'+idx} status={this.state.controllerUnitsArr[idx]} selectClick={this.center(idx)} inverseClick={this.inverse(idx)} /> ) }) return ( <section className='stage' ref="stage"> <section className="img-sec"> {imgfigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } GalleryByReactApp.defaultProps = { }; export default GalleryByReactApp;
iris-frontend/src/index.js
echoneet/iris
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import 'semantic-ui-css/semantic.min.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/svg-icons/image/exposure-neg-1.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageExposureNeg1 = (props) => ( <SvgIcon {...props}> <path d="M4 11v2h8v-2H4zm15 7h-2V7.38L14 8.4V6.7L18.7 5h.3v13z"/> </SvgIcon> ); ImageExposureNeg1 = pure(ImageExposureNeg1); ImageExposureNeg1.displayName = 'ImageExposureNeg1'; ImageExposureNeg1.muiName = 'SvgIcon'; export default ImageExposureNeg1;
docs/app/Examples/elements/Segment/Groups/SegmentExampleNestedSegments.js
shengnian/shengnian-ui-react
import React from 'react' import { Segment } from 'shengnian-ui-react' const SegmentExampleNestedSegments = () => ( <Segment.Group> <Segment>Top</Segment> <Segment.Group> <Segment>Nested Top</Segment> <Segment>Nested Middle</Segment> <Segment>Nested Bottom</Segment> </Segment.Group> <Segment.Group horizontal> <Segment>Top</Segment> <Segment>Middle</Segment> <Segment>Bottom</Segment> </Segment.Group> <Segment>Bottom</Segment> </Segment.Group> ) export default SegmentExampleNestedSegments
client/src/AboutButton.js
roxroy/codeploy
import React, { Component } from 'react'; class AboutButton extends Component { render() { return ( <div> <button className="modal-button" onClick={this.props.viewAbout}>About</button> </div> ) } } module.exports = AboutButton;
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
bs1180/react-router
import React from 'react' class Assignments extends React.Component { render() { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ) } } export default Assignments
src/manager/UI/Toolbar.js
react-theming/react-theming
import React from 'react'; import * as styled from './Toolbar.styled'; const Toolbar = ({ children, footer }) => ( <styled.Container footer={footer}>{children}</styled.Container> ); export default Toolbar;
src/components/LeadForm/LeadForm.js
eliaslopezgt/ps-react-eli
import React from 'react'; import PropTypes from 'prop-types'; import FullNameInput from 'ps-react/FullNameInput'; import EmailInput from 'ps-react/EmailInput'; import PhoneInput from 'ps-react/PhoneInput'; import SubmitButton from 'ps-react/SubmitButton'; import HiddenInput from 'ps-react/HiddenInput'; /** LeadForm */ function LeadForm({action, className, htmlId, method, name, fullNameOnChange, emailOnChange, phoneOnChange}) { return ( <form action={action} className={className} id={htmlId} method={method} name={name}> <FullNameInput htmlId="leadFormFullname" onChange={fullNameOnChange}/> <EmailInput htmlId="leadFormEmail" onChange={emailOnChange}/> <PhoneInput htmlId="leadFormPhone" onChange={phoneOnChange}/> <HiddenInput name="creative_id"/> <HiddenInput name="campaignid"/> <HiddenInput name="utm_source"/> <HiddenInput name="SessionId"/> <HiddenInput name="DesiredState"/> <HiddenInput name="DesiredCity"/> <HiddenInput name="DesiredZip"/> <HiddenInput name="DesiredCountry"/> <HiddenInput name="SourceId"/> <HiddenInput name="SubsourceId"/> <HiddenInput name="Form_url"/> <HiddenInput name="Referrer_url"/> <HiddenInput name="Form_id"/> <HiddenInput name="inputLocation"/> <HiddenInput name="inputMileRadius"/> <HiddenInput name="inputRoomType"/> <HiddenInput name="inputBudget"/> <HiddenInput name="authenticity_token"/> <HiddenInput name="DesiredCareType"/> <SubmitButton className="submit-btn" label="Request info" iconClassName="fa icon-chevron-right"/> </form> ); } LeadForm.propTypes = { /** Action for the form */ action: PropTypes.string.isRequired, /** Form ClassName */ className: PropTypes.string, /** Form htmlId */ htmlId: PropTypes.string, /** Form Method */ method: PropTypes.oneOf(['post', 'get']), /** Form Name */ name: PropTypes.string, /** Function called when fullName input value changes */ fullNameOnChange: PropTypes.func, /** Function called when Email input value changes */ emailOnChange: PropTypes.func, /** Function called when Phone input value changes */ phoneOnChange: PropTypes.func, }; export default LeadForm;
app/containers/NotFoundPage/index.js
emise/hoosit
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; export default function NotFound() { return ( <article> <H1> <FormattedMessage {...messages.header} /> </H1> </article> ); }
src/front/app/features/main/navigation/NavigationItem.js
travel-and-help/start-kit
import React from 'react'; import { Link } from 'react-router'; const NavigationItem = ({ link, iconClass }) => ( <Link className={`navigation-item navigation-item_${iconClass}`} activeClassName="navigation-item_active" to={link} /> ); NavigationItem.propTypes = { link: React.PropTypes.string, iconClass: React.PropTypes.string }; export default NavigationItem;
src/components/Homepage/components/ProfessionalSection.js
Dynatos/personal-website
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Skills from "./Skills"; class ProfessionalSection extends Component { aboutMe() { const { data } = this.props; return( <div className="resume-about-me-parent"> <h4 className="resume-title-bar resume-about-me-title-box"> About </h4> <div className="resume-about-me"> {data.dataBox.aboutMe} </div> </div> ); } // This is the only part of this component that isn't really self explanatory. This function allows the page to // render all of the objects in our data file dynamically, so if a job is added or removed the page will reflect // this change automatically. renderJobs() { const { data } = this.props; const jobs = data.dataBox.experience; return jobs.map(function renderJobsCallback(e, jobNumber) { return ( <div key={"jobExperience" + jobNumber}> <div className={"resume-job-experience job-number-" + jobNumber}> <div className={"resume-job-company-name company--" + jobs[jobNumber].company}> {jobs[jobNumber].company} </div> <div className="resume-job-position"> {jobs[jobNumber].position} </div> <div className="resume-job-dates-parent"> <div className="resume-job-start-date resume-job-date"> {jobs[jobNumber].startDate} </div> <div> &mdash; </div> <div className="resume-job-end-date resume-job-date"> {jobs[jobNumber].endDate} </div> </div> </div> </div> ); }); } render() { return ( <div className="resume-professional-child"> {this.aboutMe()} <h4 className="resume-title-bar resume-job-experience-title-box"> Professional History </h4> <div className="resume-jobs-parent"> {this.renderJobs()} </div> <div className="resume-skills-highest-parent"> <h4 className="resume-title-bar resume-skills-title-box"> Skills </h4> <Skills {...this.props} /> </div> </div> ); } } export default ProfessionalSection; ProfessionalSection.propTypes = { data: PropTypes.object.isRequired };
src/client/routes.js
YingQQQ/React-Blog
import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import App from './containers/App'; import Home from './containers/Home'; import About from './containers/About'; import Blog from './containers/Blog'; import Login from './containers/Login'; import Write from './containers/Write'; import Single from './containers/Single'; let routes = ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/blog" component={Blog} /> <Route path="/blog/:id" component={Single} /> <Route path="/about" component={About} /> <Route path="/login" component={Login} /> <Route path="/write" component={Write} /> </Route> </Router> ); // <IndexRoute component={Home} /> // <Route path="/blog" component={Blog} /> // RHL3 if (module.hot) { const oldRoutes = module.hot.data && module.hot.data.routes; if (oldRoutes) { routes = oldRoutes; } module.hot.dispose((data) => { data.routes = routes; }); } export default routes;
app/javascript/mastodon/features/list_timeline/index.js
ikuradon/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnBackButton from '../../components/column_back_button'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'; import { connectListStream } from '../../actions/streaming'; import { expandListTimeline } from '../../actions/timelines'; import { fetchList, deleteList, updateList } from '../../actions/lists'; import { openModal } from '../../actions/modal'; import MissingIndicator from '../../components/missing_indicator'; import LoadingIndicator from '../../components/loading_indicator'; import Icon from 'mastodon/components/icon'; import RadioButton from 'mastodon/components/radio_button'; const messages = defineMessages({ deleteMessage: { id: 'confirmations.delete_list.message', defaultMessage: 'Are you sure you want to permanently delete this list?' }, deleteConfirm: { id: 'confirmations.delete_list.confirm', defaultMessage: 'Delete' }, followed: { id: 'lists.replies_policy.followed', defaultMessage: 'Any followed user' }, none: { id: 'lists.replies_policy.none', defaultMessage: 'No one' }, list: { id: 'lists.replies_policy.list', defaultMessage: 'Members of the list' }, }); const mapStateToProps = (state, props) => ({ list: state.getIn(['lists', props.params.id]), hasUnread: state.getIn(['timelines', `list:${props.params.id}`, 'unread']) > 0, }); export default @connect(mapStateToProps) @injectIntl class ListTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, columnId: PropTypes.string, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, list: PropTypes.oneOfType([ImmutablePropTypes.map, PropTypes.bool]), intl: PropTypes.object.isRequired, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('LIST', { id: this.props.params.id })); this.context.router.history.push('/'); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch } = this.props; const { id } = this.props.params; dispatch(fetchList(id)); dispatch(expandListTimeline(id)); this.disconnect = dispatch(connectListStream(id)); } componentWillReceiveProps (nextProps) { const { dispatch } = this.props; const { id } = nextProps.params; if (id !== this.props.params.id) { if (this.disconnect) { this.disconnect(); this.disconnect = null; } dispatch(fetchList(id)); dispatch(expandListTimeline(id)); this.disconnect = dispatch(connectListStream(id)); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { id } = this.props.params; this.props.dispatch(expandListTimeline(id, { maxId })); } handleEditClick = () => { this.props.dispatch(openModal('LIST_EDITOR', { listId: this.props.params.id })); } handleDeleteClick = () => { const { dispatch, columnId, intl } = this.props; const { id } = this.props.params; dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.deleteMessage), confirm: intl.formatMessage(messages.deleteConfirm), onConfirm: () => { dispatch(deleteList(id)); if (!!columnId) { dispatch(removeColumn(columnId)); } else { this.context.router.history.push('/lists'); } }, })); } handleRepliesPolicyChange = ({ target }) => { const { dispatch } = this.props; const { id } = this.props.params; dispatch(updateList(id, undefined, false, target.value)); } render () { const { hasUnread, columnId, multiColumn, list, intl } = this.props; const { id } = this.props.params; const pinned = !!columnId; const title = list ? list.get('title') : id; const replies_policy = list ? list.get('replies_policy') : undefined; if (typeof list === 'undefined') { return ( <Column> <div className='scrollable'> <LoadingIndicator /> </div> </Column> ); } else if (list === false) { return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <MissingIndicator /> </Column> ); } return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={title}> <ColumnHeader icon='list-ul' active={hasUnread} title={title} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <div className='column-settings__row column-header__links'> <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleEditClick}> <Icon id='pencil' /> <FormattedMessage id='lists.edit' defaultMessage='Edit list' /> </button> <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleDeleteClick}> <Icon id='trash' /> <FormattedMessage id='lists.delete' defaultMessage='Delete list' /> </button> </div> { replies_policy !== undefined && ( <div role='group' aria-labelledby={`list-${id}-replies-policy`}> <span id={`list-${id}-replies-policy`} className='column-settings__section'> <FormattedMessage id='lists.replies_policy.title' defaultMessage='Show replies to:' /> </span> <div className='column-settings__row'> { ['none', 'list', 'followed'].map(policy => ( <RadioButton name='order' key={policy} value={policy} label={intl.formatMessage(messages[policy])} checked={replies_policy === policy} onChange={this.handleRepliesPolicyChange} /> ))} </div> </div> )} </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`list_timeline-${columnId}`} timelineId={`list:${id}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.list' defaultMessage='There is nothing in this list yet. When members of this list post new statuses, they will appear here.' />} bindToDocument={!multiColumn} /> </Column> ); } }