path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/RichTextAreaComposite/RichTextAreaComposite.js
nirhart/wix-style-react
import React from 'react'; import {children, optional, once} from '../Composite'; import RichTextArea from '../RichTextArea'; import Label from '../Label'; import InputAreaWithLabelComposite from '../Composite/InputAreaWithLabelComposite/InputAreaWithLabelComposite'; const RichTextAreaComposite = ({...props, children}) => ( <InputAreaWithLabelComposite {...props}> {children} </InputAreaWithLabelComposite> ); RichTextAreaComposite.propTypes = { children: children(optional(Label), once(RichTextArea)) }; RichTextAreaComposite.displayName = 'RichTextAreaComposite'; export default RichTextAreaComposite;
src/Components/CompilerButton.js
MaxGraey/Assembleash
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import DropdownButton from 'react-bootstrap/lib/DropdownButton'; import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger'; import MenuItem from 'react-bootstrap/lib/MenuItem'; import tooltip from './Tooltip'; import { CompilerList } from '../Common/Common'; export default class CompilerButton extends Component { static defaultProps = { compiler: CompilerList[0], onSelect: () => {}, } static propTypes = { compiler: PropTypes.string, onSelect: PropTypes.func, } static styles = { button: { minWidth: '238px', }, menuItem: { minWidth: '238px', textAlign: 'center', } } constructor(props) { super(props); this.state = { compiler: props.compiler, }; } onSelect = eventKey => { const compiler = CompilerList[eventKey]; this.setState({ compiler }, () => { this.props.onSelect(compiler); }); } render() { const { styles } = this.constructor; return ( <OverlayTrigger rootClose placement='bottom' trigger={[ 'hover' ]} overlay={ tooltip('Choose Compiler') } > <DropdownButton id='compilers' bsStyle='info' bsSize='large' title={ this.state.compiler } style={ styles.button } onSelect={ this.onSelect } > { CompilerList.map((value, index) => ( <MenuItem key={ value } eventKey={ index } href={ `#${ value }` } bsStyle='info' style={ styles.menuItem }> <h4>{ value }</h4> </MenuItem> )) } </DropdownButton> </OverlayTrigger> ); } }
src/lib/items/defaultItemRenderer.js
namespace-ee/react-calendar-timeline
import React from 'react' import PropTypes from 'prop-types' export const defaultItemRenderer = ({ item, itemContext, getItemProps, getResizeProps }) => { const { left: leftResizeProps, right: rightResizeProps } = getResizeProps() return ( <div {...getItemProps(item.itemProps)}> {itemContext.useResizeHandle ? <div {...leftResizeProps} /> : ''} <div className="rct-item-content" style={{ maxHeight: `${itemContext.dimensions.height}` }} > {itemContext.title} </div> {itemContext.useResizeHandle ? <div {...rightResizeProps} /> : ''} </div> ) } // TODO: update this to actual prop types. Too much to change before release // future me, forgive me. defaultItemRenderer.propTypes = { item: PropTypes.any, itemContext: PropTypes.any, getItemProps: PropTypes.any, getResizeProps: PropTypes.any }
newclient/scripts/components/user/nav-sidebar/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import ProgressIndicator from '../progress-indicator'; import {DisclosureActions} from '../../../actions/disclosure-actions'; import NextLink from '../next-link'; import SubmitLink from '../submit-link'; import PreviousLink from '../previous-link'; export class NavSidebar extends React.Component { constructor() { super(); this.nextClicked = this.nextClicked.bind(this); this.submitDisclosure = this.submitDisclosure.bind(this); } nextClicked() { if (!this.props.nextDisabled) { DisclosureActions.nextStep(); } } submitDisclosure() { if (!this.props.submitDisabled) { DisclosureActions.submitDisclosure(); } } render() { let nextLink; if (this.props.showNextLink) { nextLink = ( <NextLink onClick={this.nextClicked} disabled={this.props.nextDisabled} className={`${styles.override} ${styles.link}`} /> ); } let submitLink; if (this.props.showSubmitLink) { submitLink = ( <SubmitLink onClick={this.submitDisclosure} disabled={this.props.submitDisabled} className={`${styles.override} ${styles.link}`} /> ); } let previousLink; if (this.props.showPreviousLink) { previousLink = ( <PreviousLink onClick={DisclosureActions.previousQuestion} className={`${styles.override} ${styles.link}`} label={this.props.previousLabel} /> ); } return ( <span className={styles.navigation}> <div onClick={this.advance}> <ProgressIndicator percent={this.props.percentComplete} useColor={!window.colorBlindModeOn} /> </div> <div className={styles.stepButtons}> {previousLink} {submitLink} {nextLink} </div> </span> ); } }
6.webpack/src/index.js
zhufengnodejs/201615node
import React from 'react'; import ReactDOM from 'react-dom'; require('bootstrap/dist/css/bootstrap.css'); import MessageBox from './containers/MessageBox'; let store = require('./api'); ReactDOM.render(<MessageBox store={store}/>,document.querySelector('#app'));
src/components/common/svg-icons/image/filter-3.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter3 = (props) => ( <SvgIcon {...props}> <path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z"/> </SvgIcon> ); ImageFilter3 = pure(ImageFilter3); ImageFilter3.displayName = 'ImageFilter3'; ImageFilter3.muiName = 'SvgIcon'; export default ImageFilter3;
mod12/src/App.js
mauricedb/mwd-2017-02-20
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import DisplayValue from './DisplayValue'; import UpdateValue from './UpdateValue' class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> <UpdateValue /> <DisplayValue /> </div> ); } } export default App;
CompositeUi/src/views/component/HelpText.js
kreta-io/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/components/_help-text.scss'; import React from 'react'; const HelpText = props => <p className={`help-text${props.center ? ' help-text--center' : ''}`}> {props.children} </p>; export default HelpText;
src/views/HeaderTitle.js
half-shell/react-navigation
/* @flow */ import React from 'react'; import { Platform, StyleSheet, Text, } from 'react-native'; import type { Style, } from '../TypeDefinition'; type Props = { tintColor?: ?string; style?: Style, }; const HeaderTitle = ({ style, ...rest }: Props) => ( <Text numberOfLines={1} {...rest} style={[styles.title, style]} /> ); const styles = StyleSheet.create({ title: { fontSize: Platform.OS === 'ios' ? 17 : 18, fontWeight: Platform.OS === 'ios' ? '600' : '500', color: 'rgba(0, 0, 0, .9)', textAlign: Platform.OS === 'ios' ? 'center' : 'left', marginHorizontal: 16, }, }); HeaderTitle.propTypes = { style: Text.propTypes.style, }; export default HeaderTitle;
src/client.js
wchargin/wchargin.github.io
/* * Client-side entry point. Rehydrates a server-side rendered page. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; export default function initializeClient() { const container = document.getElementById("container"); ReactDOM.hydrate(<App />, container); }
docs/src/app/components/pages/components/TimePicker/ExampleSimple.js
nathanmarks/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/layouts/layout-5-4.js
nazaninreihani/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} {components[1]} </div> <div className="vertical"> {components[2]} {components[3]} {components[4]} </div> </div> );
examples/src/components/CustomComponents.js
range-me/react-select
import React from 'react'; import Select from 'react-select'; import Gravatar from 'react-gravatar'; const USERS = require('../data/users'); const GRAVATAR_SIZE = 15; const GravatarOption = React.createClass({ propTypes: { children: React.PropTypes.node, className: React.PropTypes.string, isDisabled: React.PropTypes.bool, isFocused: React.PropTypes.bool, isSelected: React.PropTypes.bool, onFocus: React.PropTypes.func, onSelect: React.PropTypes.func, onUnfocus: React.PropTypes.func, option: React.PropTypes.object.isRequired, }, handleMouseDown (event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter (event) { this.props.onFocus(this.props.option, event); }, handleMouseMove (event) { if (this.props.isFocused) return; this.props.onFocus(this.props.option, event); }, handleMouseLeave (event) { this.props.onUnfocus(this.props.option, event); }, render () { let gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseMove={this.handleMouseMove} onMouseLeave={this.handleMouseLeave} title={this.props.option.title}> <Gravatar email={this.props.option.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </div> ); } }); const GravatarValue = React.createClass({ propTypes: { children: React.PropTypes.node, placeholder: React.PropTypes.string, value: React.PropTypes.object }, render () { var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className="Select-value" title={this.props.value.title}> <span className="Select-value-label"> <Gravatar email={this.props.value.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </span> </div> ); } }); const UsersField = React.createClass({ propTypes: { hint: React.PropTypes.string, label: React.PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); }, render () { var placeholder = <span>&#9786; Select User</span>; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select onChange={this.setValue} optionComponent={GravatarOption} options={USERS} placeholder={placeholder} value={this.state.value} valueComponent={GravatarValue} /> <div className="hint"> This example implements custom Option and Value components to render a Gravatar image for each user based on their email. It also demonstrates rendering HTML elements as the placeholder. </div> </div> ); } }); module.exports = UsersField;
app/components/Setting.js
ayqy/ready-to-work
import React, { Component } from 'react'; import { Form, Icon, Input, Button, Checkbox, Row, Col, Select } from 'antd'; const Option = Select.Option; const FormItem = Form.Item; import HeaderBar from '../containers/common/HeaderBar'; const defaultSetting = { duration: '25', duration_options: new Array(12).fill(0).map((v, i) => (i + 1) * 5 + ''), short_break: '5', short_break_options: new Array(15).fill(0).map((v, i) => i + 1 + ''), long_break: '5', long_break_options: new Array(6).fill(0).map((v, i) => (i + 1) * 5 + ''), long_break_after: '4', long_break_after_options: new Array(9).fill(0).map((v, i) => i + 2 + ''), target: '10', target_options: new Array(15).fill(0).map((v, i) => i + 4 + ''), auto_launch: true, notifiy_desktop: true, notifiy_sound: false, tray_timer: true }; const formItemLayout = { labelCol: { span: 8, offset: 4 }, wrapperCol: { span: 10, offset: 2 }, }; class SettingForm extends Component { static defaultProps = {...defaultSetting}; render() { const { getFieldDecorator } = this.props.form; const padding = '6px'; const selectWidth = '100px'; const DURATION_UNIT = '分钟'; return ( <div className="setting"> <HeaderBar/> <Form onSubmit={this.handleSubmit.bind(this)} className="setting-form" ref="form"> <FormItem {...formItemLayout} label="一个番茄钟" style={{marginBottom: 0}}> {getFieldDecorator('duration', { rules: [{ required: false, message: 'Please select a pomodoro duration!' }], initialValue: this.props.duration })( <Select style={{width: selectWidth, display: 'inline-block'}} size="small"> { this.props.duration_options.map(d => <Option key={d} value={d}>{d + DURATION_UNIT}</Option>) } </Select> )} </FormItem> <FormItem {...formItemLayout} label="小休息" style={{marginBottom: 0}}> {getFieldDecorator('short_break', { rules: [{ required: false, message: 'Please select a short break!' }], initialValue: this.props.short_break })( <Select style={{width: selectWidth, display: 'inline-block'}} size="small"> { this.props.short_break_options.map(d => <Option key={d} value={d}>{d + DURATION_UNIT}</Option>) } </Select> )} </FormItem> <FormItem {...formItemLayout} label="大休息" style={{marginBottom: 0}}> {getFieldDecorator('long_break', { rules: [{ required: false, message: 'Please select a long break!' }], initialValue: this.props.long_break })( <Select style={{width: selectWidth, display: 'inline-block'}} size="small"> { this.props.long_break_options.map(d => <Option key={d} value={d}>{d + DURATION_UNIT}</Option>) } </Select> )} </FormItem> <FormItem {...formItemLayout} label="每几个番茄后大休息" style={{marginBottom: 0}}> {getFieldDecorator('long_break_after', { rules: [{ required: false, message: 'Please select a long break after!' }], initialValue: this.props.long_break_after })( <Select style={{width: selectWidth, display: 'inline-block'}} size="small"> { this.props.long_break_after_options.map(d => <Option key={d} value={d}>{d + '个番茄'}</Option>) } </Select> )} </FormItem> <FormItem {...formItemLayout} label="每日目标" style={{marginBottom: 0}}> {getFieldDecorator('target', { rules: [{ required: false, message: 'Please select a target!' }], initialValue: this.props.target })( <Select style={{width: selectWidth, display: 'inline-block'}} size="small"> { this.props.target_options.map(d => <Option key={d} value={d}>{d + '个番茄'}</Option>) } </Select> )} </FormItem> <FormItem {...formItemLayout} label="开机启动" style={{marginBottom: 0}}> {getFieldDecorator('auto_launch', { valuePropName: 'checked', initialValue: this.props.auto_launch })( <Checkbox></Checkbox> )} </FormItem> <FormItem {...formItemLayout} label="桌面通知" style={{marginBottom: 0}}> {getFieldDecorator('notifiy_desktop', { valuePropName: 'checked', initialValue: this.props.notifiy_desktop })( <Checkbox></Checkbox> )} </FormItem> <FormItem {...formItemLayout} label="声音通知" style={{marginBottom: 0}}> {getFieldDecorator('notifiy_sound', { valuePropName: 'checked', initialValue: this.props.notifiy_sound })( <Checkbox></Checkbox> )} </FormItem> <FormItem {...formItemLayout} label="系统栏显示倒计时" style={{marginBottom: 0}}> {getFieldDecorator('tray_timer', { valuePropName: 'checked', initialValue: this.props.tray_timer })( <Checkbox></Checkbox> )} </FormItem> <FormItem style={{marginBottom: 0, textAlign: 'center'}}> <Button style={{marginRight: '10px'}} size="small" onClick={this.resetToDefault.bind(this)}> 推荐设置 </Button> <Button size="small" htmlType="submit" className="setting-form-button"> 保存 </Button> </FormItem> </Form> </div> ); } handleSubmit(e) { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { // console.log('Received values of form: ', values); this.props.saveSetting(values); } else { console.error(err); } }); } resetToDefault() { const newFields = {}; Object.keys(defaultSetting).filter( key => key.indexOf('_options') === -1 ).forEach(key => (newFields[key] = {value: defaultSetting[key]})) this.props.form.setFields(newFields); } } const WrappedSettingForm = Form.create()(SettingForm); export default WrappedSettingForm;
examples/pinterest/app.js
Dodelkin/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, IndexRoute, Link } from 'react-router' const history = useBasename(createHistory)({ basename: '/pinterest' }) const PICTURES = [ { id: 0, src: 'http://placekitten.com/601/601' }, { id: 1, src: 'http://placekitten.com/610/610' }, { id: 2, src: 'http://placekitten.com/620/620' } ] const Modal = React.createClass({ styles: { position: 'fixed', top: '20%', right: '20%', bottom: '20%', left: '20%', padding: 20, boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)', overflow: 'auto', background: '#fff' }, render() { return ( <div style={this.styles}> <p><Link to={this.props.returnTo}>Back</Link></p> {this.props.children} </div> ) } }) const App = React.createClass({ componentWillReceiveProps(nextProps) { // if we changed routes... if (( nextProps.location.key !== this.props.location.key && nextProps.location.state && nextProps.location.state.modal )) { // save the old children (just like animation) this.previousChildren = this.props.children } }, render() { let { location } = this.props let isModal = ( location.state && location.state.modal && this.previousChildren ) return ( <div> <h1>Pinterest Style Routes</h1> <div> {isModal ? this.previousChildren : this.props.children } {isModal && ( <Modal isOpen={true} returnTo={location.state.returnTo}> {this.props.children} </Modal> )} </div> </div> ) } }) const Index = React.createClass({ render() { return ( <div> <p> The url `/pictures/:id` can be rendered anywhere in the app as a modal. Simply put `modal: true` in the `state` prop of links. </p> <p> Click on an item and see its rendered as a modal, then copy/paste the url into a different browser window (with a different session, like Chrome -> Firefox), and see that the image does not render inside the overlay. One URL, two session dependent screens :D </p> <div> {PICTURES.map(picture => ( <Link key={picture.id} to={`/pictures/${picture.id}`} state={{ modal: true, returnTo: this.props.location.pathname }}> <img style={{ margin: 10 }} src={picture.src} height="100" /> </Link> ))} </div> <p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p> </div> ) } }) const Deep = React.createClass({ render() { return ( <div> <p>You can link from anywhere really deep too</p> <p>Params stick around: {this.props.params.one} {this.props.params.two}</p> <p> <Link to={`/pictures/0`} state={{ modal: true, returnTo: this.props.location.pathname }}> Link to picture with Modal </Link><br/> <Link to={`/pictures/0`}> Without modal </Link> </p> </div> ) } }) const Picture = React.createClass({ render() { return ( <div> <img src={PICTURES[this.props.params.id].src} style={{ height: '80%' }} /> </div> ) } }) React.render(( <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="/pictures/:id" component={Picture}/> <Route path="/some/:one/deep/:two/route" component={Deep}/> </Route> </Router> ), document.getElementById('example'))
src/app/routes/App/App.js
michalniemiec288/clocker
import React from 'react' import Header from '../../components/Header' const App = ({children}) => <div className="app"> <section className="page"> <Header /> <div className="content"> {children} </div> </section> </div> export default App
node_modules/react-router/es6/RoutingContext.js
captify-iolenchenko/leaderboard
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
app/containers/AppContainer.js
youtogod/webpack-sample-project
import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import { Provider } from 'react-redux'; import AppRoutes from './AppRoutes'; import store from 'store'; class AppContainer extends Component { render() { return ( <Provider store ={store} > <BrowserRouter> <Route path='/' component={AppRoutes} /> </BrowserRouter> </Provider> ); } } export default AppContainer
src/Parser/MistweaverMonk/Modules/Spells/SoothingMist.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Module from 'Parser/Core/Module'; const debug = false; class SoothingMist extends Module { soomTicks = 0; on_byPlayer_heal(event) { const spellId = event.ability.guid; if(spellId === SPELLS.SOOTHING_MIST.id) { this.soomTicks++; } } on_finished() { if(debug) { console.log('SooM Ticks: ' + this.soomTicks); console.log('SooM Perc Uptime: ', (this.soomTicks * 2 / this.owner.fightDuration * 1000)); console.log('SooM Buff Update: ', this.owner.selectedCombatant.getBuffUptime(SPELLS.SOOTHING_MIST.id), ' Percent: ', this.owner.selectedCombatant.getBuffUptime(SPELLS.SOOTHING_MIST.id) / this.owner.fightDuration); } } suggestions(when) { const soomTicksPerDuration = (this.soomTicks * 2 / this.owner.fightDuration * 1000) || 0; when(soomTicksPerDuration).isGreaterThan(.75) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You are allowing <SpellLink id={SPELLS.SOOTHING_MIST.id} /> to channel for an extended period of time. <SpellLink id={SPELLS.SOOTHING_MIST.id} /> does little healing, so your time is better spent DPS'ing throug the use of <SpellLink id={SPELLS.TIGER_PALM.id} /> and <SpellLink id={SPELLS.BLACKOUT_KICK.id} />.</span>) .icon(SPELLS.SOOTHING_MIST.icon) .actual(`${soomTicksPerDuration.toFixed(2)} ticks per second`) .recommended(`<${recommended} ticks per second is recommended`) .regular(recommended + .25).major(recommended + .75); }); } } export default SoothingMist;
j2c/button.js
konce/css-in-js
import React from 'react'; import j2c from 'j2c'; let styles = j2c.scoped({ container: { 'text-align': 'center' }, button: { 'background-color': '#ff0000', width: '320px', padding: '20px', 'border-radius': '5px', border: 'none', outline: 'none', ':hover': { color: '#fff', }, ':active': { position: 'relative', top: '2px' }, '@media (max-width: 480px)': { width: '160px' } } }); let Button = React.createClass({ render() { return ( <div> <style>{styles.valueOf()}</style> <div className={styles.container}> <button className={styles.button}>Click me!</button> </div> </div> ); } }); React.render(<Button />, document.getElementById('content'));
src/components/EventVolunteerRow.js
codefordenver/encorelink
import PropTypes from 'prop-types'; import React from 'react'; import { Link } from 'react-router'; import AddToCalendar from 'react-add-to-calendar'; import { getFormattedDayAndTime } from '../utils/dateFormatting'; const EventVolunteerRow = ({ eventVolunteer, isCurrentlyPending, approveEventMusician, rejectEventMusician }) => { const { day, time } = getFormattedDayAndTime( eventVolunteer.event.date, eventVolunteer.event.endDate ); const { event } = eventVolunteer; return ( <tr> <td> <a href={`mailto:${eventVolunteer.volunteer.email}`}> {eventVolunteer.volunteer.email} </a> <br /> <Link to={`/musician/${eventVolunteer.volunteer.id}`}>View Profile</Link> </td> <td>{day} {time}</td> <td> <AddToCalendar event={{ title: event.name, description: event.notes, location: event.location, startTime: event.date, endTime: event.endDate }} buttonLabel="add to calendar" /> </td> {isCurrentlyPending && <td> <div className="button-group"> <a className="button secondary" href={`mailto:${eventVolunteer.volunteer.email}`} >Contact </a> <button className="button success" onClick={() => approveEventMusician(eventVolunteer)} >Approve </button> <button className="button alert" onClick={() => rejectEventMusician(eventVolunteer)} >Pass </button> </div> </td>} </tr> ); }; EventVolunteerRow.propTypes = { eventVolunteer: PropTypes.shape({ event: PropTypes.shape({ date: PropTypes.string.isRequired, endDate: PropTypes.string.isRequired, }), volunteer: PropTypes.shape({ email: PropTypes.string.isRequired, id: PropTypes.number.isRequired }) }), approveEventMusician: PropTypes.func.isRequired, rejectEventMusician: PropTypes.func.isRequired, isCurrentlyPending: PropTypes.bool.isRequired }; export default EventVolunteerRow;
app/javascript/mastodon/features/notifications/components/column_settings.js
pixiv/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ClearColumnButton from './clear_column_button'; import SettingToggle from './setting_toggle'; export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, pushSettings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; onPushChange = (path, checked) => { this.props.onChange(['push', ...path], checked); } render () { const { settings, pushSettings, onChange, onClear } = this.props; const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />; const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />; const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />; const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed'); const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />; const pushMeta = showPushSettings && <FormattedMessage id='notifications.column_settings.push_meta' defaultMessage='This device' />; return ( <div> <div className='column-settings__row'> <ClearColumnButton onClick={onClear} /> </div> <div role='group' aria-labelledby='notifications-follow'> <span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-favourite'> <span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-mention'> <span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-reblog'> <span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} /> </div> </div> </div> ); } }
modules/dreamview/frontend/src/components/RouteEditingBar/index.js
xiaoxq/apollo
import React from 'react'; import { inject, observer } from 'mobx-react'; import EditingTip from 'components/RouteEditingBar/EditingTip'; import removeAllIcon from 'assets/images/routing/remove_all.png'; import removeLastIcon from 'assets/images/routing/remove_last.png'; import sendRouteIcon from 'assets/images/routing/send_request.png'; import addPoiIcon from 'assets/images/routing/add_poi.png'; class RouteEditingButton extends React.Component { render() { const { label, icon, onClick } = this.props; return ( <button onClick={onClick} className="button"> <img src={icon} /> <span>{label}</span> </button> ); } } @inject('store') @observer export default class RouteEditingMenu extends React.Component { render() { const { routeEditingManager, options } = this.props.store; return ( <div className="route-editing-bar"> <div className="editing-panel"> <RouteEditingButton label="Add Point of Interest" icon={addPoiIcon} onClick={() => { this.props.store.handleOptionToggle('showPOI'); }} /> <RouteEditingButton label="Remove Last Point" icon={removeLastIcon} onClick={() => { routeEditingManager.removeLastRoutingPoint(); }} /> <RouteEditingButton label="Remove All Points" icon={removeAllIcon} onClick={() => { routeEditingManager.removeAllRoutingPoints(); }} /> <RouteEditingButton label="Send Routing Request" icon={sendRouteIcon} onClick={() => { if (routeEditingManager.sendRoutingRequest(false)) { options.showRouteEditingBar = false; } }} /> <EditingTip /> </div> </div> ); } }
src/addons/Select/Select.js
aabustamante/Semantic-UI-React
import React from 'react' import { META } from '../../lib' import Dropdown from '../../modules/Dropdown' /** * A Select is sugar for <Dropdown selection />. * @see Dropdown * @see Form */ function Select(props) { return <Dropdown {...props} selection /> } Select._meta = { name: 'Select', type: META.TYPES.ADDON, } Select.Divider = Dropdown.Divider Select.Header = Dropdown.Header Select.Item = Dropdown.Item Select.Menu = Dropdown.Menu export default Select
src/modules/pages/routes/index.js
cltk/cltk_frontend
import React from 'react'; import { Route } from 'react-router'; // components import AboutPage from '../components/AboutPage'; import NotFoundPage from '../components/NotFoundPage'; import MainLayout from '../../../layouts/MainLayout'; export default ( <div> <Route path="about" component={() => ( <MainLayout> <AboutPage /> </MainLayout> )} /> <Route path=":slug" component={() => ( <MainLayout> <NotFoundPage /> </MainLayout> )} /> </div> );
fields/components/NestedFormField.js
linhanyang/keystone
import React from 'react'; import { StyleSheet } from 'aphrodite/no-important'; import { FormField, FormLabel } from '../../admin/client/App/elemental'; import theme from '../../admin/client/theme'; function NestedFormField ({ children, className, label, ...props }) { return ( <FormField {...props}> <FormLabel aphroditeStyles={classes.label}> {label} </FormLabel> {children} </FormField> ); }; const classes = StyleSheet.create({ label: { color: theme.color.gray40, fontSize: theme.font.size.small, [`@media (min-width: ${theme.breakpoint.tabletLandscapeMin})`]: { paddingLeft: '1em', }, }, }); module.exports = NestedFormField;
src/App.js
ltoddy/ltoddy.github.io
import React from 'react' import Header from './header/Header' import Content from './content/Content' import Footer from './Footer' import Corner from './components/Corner' import css from './App.css' import { username, essays, header, perPageCount } from './config' class Application extends React.Component { constructor(props) { super(props) this.state = { repos: [] } } componentDidMount() { fetch(`https://api.github.com/users/${username}/repos`) .then(response => response.json()) .then(repos => this.setState(() => ({ repos: repos.sort((a, b) => b.stargazers_count - a.stargazers_count), })) ) } componentWillUnmount() { delete this.state.repos } render() { return ( <div className={css.container}> <Header navigation={header.navigation} banner={header.banner} /> <Content essays={essays} repos={this.state.repos} perPageCount={perPageCount} /> <Footer /> <Corner /> </div> ) } } export default Application
node_modules/react-ga/dist/esm/components/OutboundLink.js
jerednel/jerednel.github.io
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; import warn from '../utils/console/warn'; var NEWTAB = '_blank'; var MIDDLECLICK = 1; var OutboundLink = /*#__PURE__*/ function (_Component) { _inherits(OutboundLink, _Component); function OutboundLink() { var _getPrototypeOf2; var _this; _classCallCheck(this, OutboundLink); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(OutboundLink)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "handleClick", function (event) { var _this$props = _this.props, target = _this$props.target, eventLabel = _this$props.eventLabel, to = _this$props.to, onClick = _this$props.onClick, trackerNames = _this$props.trackerNames; var eventMeta = { label: eventLabel }; var sameTarget = target !== NEWTAB; var normalClick = !(event.ctrlKey || event.shiftKey || event.metaKey || event.button === MIDDLECLICK); if (sameTarget && normalClick) { event.preventDefault(); OutboundLink.trackLink(eventMeta, function () { window.location.href = to; }, trackerNames); } else { OutboundLink.trackLink(eventMeta, function () {}, trackerNames); } if (onClick) { onClick(event); } }); return _this; } _createClass(OutboundLink, [{ key: "render", value: function render() { var _this$props2 = this.props, href = _this$props2.to, oldProps = _objectWithoutProperties(_this$props2, ["to"]); var props = _objectSpread({}, oldProps, { href: href, onClick: this.handleClick }); if (this.props.target === NEWTAB) { props.rel = 'noopener noreferrer'; } delete props.eventLabel; delete props.trackerNames; return React.createElement('a', props); } }]); return OutboundLink; }(Component); _defineProperty(OutboundLink, "trackLink", function () { warn('ga tracking not enabled'); }); _defineProperty(OutboundLink, "propTypes", { eventLabel: PropTypes.string.isRequired, target: PropTypes.string, to: PropTypes.string, onClick: PropTypes.func, trackerNames: PropTypes.arrayOf(PropTypes.string) }); _defineProperty(OutboundLink, "defaultProps", { target: null, to: null, onClick: null, trackerNames: null }); export { OutboundLink as default };
src/components/common/Button.js
xmano/filterlistview
import React from 'react'; import { Text, View, TouchableOpacity } from 'react-native'; const Button = (props) => { const { viewStyle, textStyle } = stylesVal; return ( <TouchableOpacity style={viewStyle} onPress={props.onPress}> <Text style={textStyle}> {props.children} </Text> </TouchableOpacity> ); }; const stylesVal = { viewStyle: { flex: 1, alignSelf: 'stretch', backgroundColor: '#fff', borderWidth: 1, borderRadius: 5, borderColor: '#007aff', marginLeft: 5, marginRight: 5 }, textStyle: { alignSelf: 'center', fontSize: 18, fontWeight: '600', paddingTop: 10, paddingBottom: 10, color: '#007aff' } }; export { Button } ;
webpack/move_to_pf/TooltipButton/TooltipButton.js
adamruzicka/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Tooltip, OverlayTrigger } from 'patternfly-react'; import './TooltipButton.scss'; const TooltipButton = ({ disabled, title, tooltipText, tooltipId, tooltipPlacement, renderedButton, ...props }) => { if (!disabled) return renderedButton || (<Button {...props}>{title}</Button>); return ( <OverlayTrigger placement={tooltipPlacement} delayHide={150} overlay={<Tooltip id={tooltipId}>{tooltipText}</Tooltip>} > <div className="tooltip-button-helper"> {renderedButton || (<Button {...props} disabled>{title}</Button>)} </div> </OverlayTrigger> ); }; TooltipButton.propTypes = { disabled: PropTypes.bool, title: PropTypes.string, tooltipText: PropTypes.string, tooltipId: PropTypes.string.isRequired, tooltipPlacement: PropTypes.string, renderedButton: PropTypes.node, }; TooltipButton.defaultProps = { disabled: false, title: '', tooltipPlacement: 'bottom', tooltipText: '', renderedButton: null, }; export default TooltipButton;
client/modules/panel/routes.js
open-dash/open-dash
import React from 'react'; import { mount } from 'react-mounter'; import PanelLayout from '/client/modules/core/containers/panel_layout'; import Panel from './containers/panel'; export default function (injectDeps, { FlowRouter }) { const PanelLayoutCtx = injectDeps(PanelLayout); FlowRouter.route('/panel', { name: 'panel', action() { mount(PanelLayoutCtx, { content: () => (<Panel />) }); } }); }
src/components/BlogLink.js
jcmnunes/josenunesxyz
import React from 'react'; import { Link } from 'gatsby'; import styled from 'styled-components'; import PrimaryButton from '../styles/PrimaryButton'; import { Location } from '@reach/router'; const StyledBlogLink = styled(Link)` @media (max-width: ${props => props.theme.bp_small}) { position: absolute; top: 32px; right: 32px; } `; const BlogLink = () => { const getButtonText = location => { if (location.pathname.includes('/blog')) { return 'home'; } return 'blog'; }; const getToUrl = location => { if (location.pathname.includes('/blog')) { return '/'; } return '/blog'; }; return ( <Location> {({ location }) => ( <StyledBlogLink to={getToUrl(location)}> <PrimaryButton>{getButtonText(location)}</PrimaryButton> </StyledBlogLink> )} </Location> ); }; export default BlogLink;
client/helpers/scope.js
waterkhair/template
// Modules import DefaultLayout from '../react/layouts/default'; import HomePage from '../react/pages/auth/home/home'; import LoginPage from '../react/pages/public/login/login'; import React from 'react'; /** * Creates a admin scope validator * @param {object} store - Redux store * @param {ReactComponent} Component - React component * @return {ReactComponent} - Returns ReactComponent */ export const adminScopeValidator = (store, Component) => (mapProps) => { const sessionState = store.getState().session; if (sessionState.credentials.scope === 'admin') { return <DefaultLayout {...mapProps} children={<Component {...mapProps} />} />; } return userScopeValidator(store, HomePage); }; /** * Creates a user scope validator * @param {object} store - Redux store * @param {ReactComponent} Component - React component * @return {ReactComponent} - Returns ReactComponent */ export const userScopeValidator = (store, Component) => (mapProps) => { const sessionState = store.getState().session; if (sessionState.isAuthenticated) { return <DefaultLayout {...mapProps} children={<Component {...mapProps} />} />; } return <LoginPage {...mapProps} />; };
src/media/js/site/components/subnav.js
ziir/marketplace-content-tools
import classnames from 'classnames'; import {connect} from 'react-redux'; import React from 'react'; import {reverse, ReverseLink} from 'react-router-reverse'; export class Subnav extends React.Component { render() { return ( <nav className="page--subnav"> <ul> {this.props.children.map(item => <li>{item}</li>)} </ul> </nav> ); } }
src/panels/JobMonitor/LogFold.js
Kitware/HPCCloud
import React from 'react'; import PropTypes from 'prop-types'; import style from 'HPCCloudStyle/JobMonitor.mcss'; import state from 'HPCCloudStyle/States.mcss'; export default class LogFold extends React.Component { constructor(props) { super(props); this.state = { open: false, }; this.toggleOpen = this.toggleOpen.bind(this); } toggleOpen() { this.setState({ open: !this.state.open }); } render() { return ( <div className={`${style.logEntry} ${this.props.color}`}> {this.state.open ? ( <i className={style.foldOpen} onClick={this.toggleOpen} /> ) : ( <i className={style.foldClosed} onClick={this.toggleOpen} /> )} {this.props.header} <div className={this.state.open ? '' : state.isHidden}> {this.props.content} </div> </div> ); } } LogFold.propTypes = { header: PropTypes.string.isRequired, content: PropTypes.string.isRequired, color: PropTypes.string, }; LogFold.defaultProps = { color: '', };
webpack/containers/Application/index.js
daviddavis/katello
import React from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import Routes from './Routes'; export default () => ( <Router> <Routes /> </Router> );
src/js/components/config/config.js
sepro/React-Pomodoro
import React from 'react'; import Modal from 'boron/FadeModal'; import TextButton, {FixedButton} from '../styled-components/text-button'; import ConfigButton from './config-button'; import ConfigInput from './config-input'; import ConfigBody from './config-body'; import FaCog from 'react-icons/fa/cog'; const boronStyle = { width: '300px' }; class Config extends React.Component { constructor(props) { super(props); this.state = { pomodoro: this.props.config.pomodoro, short: this.props.config.short, long: this.props.config.long }; } showModal = () => { this.refs.modal.show(); } handlePomodoroChange = (event) => { var value = parseInt(event.target.value); if (isNaN(value)) { this.setState({pomodoro: 0}); event.target.select(); } else { this.setState({pomodoro: value * 60000}); } } handleShortChange = (event) => { var value = parseInt(event.target.value); if (isNaN(value)) { this.setState({pomodoro: 0}); event.target.select(); } else { this.setState({short: value * 60000}); } } handleLongChange = (event) => { var value = parseInt(event.target.value); if (isNaN(value)) { this.setState({pomodoro: 0}); event.target.select(); } else { this.setState({long: value * 60000}); } } acceptSettings = () => { this.props.set_pomodoro(this.state.pomodoro); this.props.set_short_break(this.state.short); this.props.set_long_break(this.state.long); this.refs.modal.hide(); } hideModal = () => { this.setState({ pomodoro: this.props.config.pomodoro, short: this.props.config.short, long: this.props.config.long }); this.refs.modal.hide(); } render() { return ( <div> <ConfigButton onClick={this.showModal}><FaCog size={46} /></ConfigButton> <Modal ref="modal" closeOnClick={ false } modalStyle={ boronStyle }> <ConfigBody> <h2>Set time</h2> <label for="set_pomodoro">Pomodoro</label> <ConfigInput type="text" id="set_pomodoro" name="pomodoro" ref="pomodoro" onChange={ this.handlePomodoroChange } value={ (this.state.pomodoro/60000) }/> <label for="set_short_break">Short break</label> <ConfigInput type="text" id="set_short_break" name="short_break" onChange={ this.handleShortChange } value={ (this.state.short/60000) }/> <label for="set_long_break">Long break</label> <ConfigInput type="text" id="set_long_break" name="long_break" onChange={ this.handleLongChange } value={ (this.state.long/60000) }/> <hr /> <FixedButton onClick={this.acceptSettings} primary small>Accept</FixedButton><FixedButton onClick={this.hideModal} small>Cancel</FixedButton> </ConfigBody> </Modal> </div> ); } } export default Config
src/LeaderboardHeader5/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Typography from '../Typography'; import classNames from 'classnames'; import styles from './styles.css'; function LeaderboardHeader5(props) { const caption = props.household ? 'Husholdning' : 'Deltager'; return ( <div className={classNames(styles.wrapper, { [props.className]: props.className })} > <Typography className={styles.caption} type={'caption2Normal'} > {caption} </Typography> </div> ); } LeaderboardHeader5.propTypes = { className: PropTypes.string, household: PropTypes.bool }; export default LeaderboardHeader5;
Realization/frontend/czechidm-core/src/components/basic/LabelWrapper/LabelWrapper.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Joi from 'joi'; // import AbstractFormComponent from '../AbstractFormComponent/AbstractFormComponent'; import Tooltip from '../Tooltip/Tooltip'; /** * Form label decorator. * * @author Vít Švanda * @author Radek Tomiška */ class LabelWrapper extends AbstractFormComponent { getRequiredValidationSchema() { return Joi.string().required(); } /** * Focus input field */ focus() { // this.refs.input.focus(); } onChange() { // super.onChange(event); } getBody(feedback) { const { labelSpan, label, componentSpan, required, rendered } = this.props; // if (!rendered) { return null; } // const labelClassName = classNames(labelSpan); let showAsterix = false; if (required && !this.state.value) { showAsterix = true; } const title = this.getValidationResult() != null ? this.getValidationResult().message : null; const _label = []; if (label) { _label.push(label); } if (_label.length > 0 && required) { _label.push(' *'); } // return ( <div className={ classNames( { 'has-feedback': feedback } ) }> { _label.length === 0 || <label className={ labelClassName }> { _label } { this.renderHelpIcon() } </label> } <div className={componentSpan}> <Tooltip ref="popover" placement="right" value={ title }> <span> { this.props.children } { feedback || showAsterix ? <span className="form-control-feedback" style={{color: 'red', zIndex: 0}}>*</span> : '' } </span> </Tooltip> { _label.length === 0 ? this.renderHelpIcon() : null } { this.renderHelpBlock() } </div> </div> ); } } LabelWrapper.propTypes = { ...AbstractFormComponent.propTypes, type: PropTypes.string, placeholder: PropTypes.string, help: PropTypes.string }; LabelWrapper.defaultProps = { ...AbstractFormComponent.defaultProps, type: 'text' }; export default LabelWrapper;
src/elements/Rail/Rail.js
aabustamante/Semantic-UI-React
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useKeyOrValueAndKey, } from '../../lib' /** * A rail is used to show accompanying content outside the boundaries of the main view of a site. */ function Rail(props) { const { attached, children, className, close, dividing, internal, position, size, } = props const classes = cx( 'ui', position, size, useKeyOnly(attached, 'attached'), useKeyOnly(dividing, 'dividing'), useKeyOnly(internal, 'internal'), useKeyOrValueAndKey(close, 'close'), 'rail', className, ) const rest = getUnhandledProps(Rail, props) const ElementType = getElementType(Rail, props) return <ElementType {...rest} className={classes}>{children}</ElementType> } Rail._meta = { name: 'Rail', type: META.TYPES.ELEMENT, } Rail.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** A rail can appear attached to the main viewport. */ attached: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** A rail can appear closer to the main viewport. */ close: PropTypes.oneOfType([ PropTypes.bool, PropTypes.oneOf(['very']), ]), /** A rail can create a division between itself and a container. */ dividing: PropTypes.bool, /** A rail can attach itself to the inside of a container. */ internal: PropTypes.bool, /** A rail can be presented on the left or right side of a container. */ position: PropTypes.oneOf(SUI.FLOATS).isRequired, /** A rail can have different sizes. */ size: PropTypes.oneOf(_.without(SUI.SIZES, 'medium')), } export default Rail
src/svg-icons/device/screen-rotation.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenRotation = (props) => ( <SvgIcon {...props}> <path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/> </SvgIcon> ); DeviceScreenRotation = pure(DeviceScreenRotation); DeviceScreenRotation.displayName = 'DeviceScreenRotation'; DeviceScreenRotation.muiName = 'SvgIcon'; export default DeviceScreenRotation;
client/src/views/ErrorModal.js
MissUchiha/CANX
import React from 'react' import Modal from 'react-modal' import {modalStyle} from '../style/modalStyle' function ErrorModal(props) { return ( <Modal isOpen={props.args.isOpen} onRequestClose={props.args.closeModal} contentLabel="Error" shouldCloseOnOverlayClick={true} style={modalStyle}> <h2> {props.args.title} </h2> <button className='modal-ok modal-close' value='Close' onClick={props.args.closeModal}></button> </Modal> ) } export default ErrorModal
src/pages/containers/LoginContainer.js
martinkogut/react-native-android-starter
import React, { Component } from 'react'; import * as COLOR from '../../constants/colors'; import { AppRegistry, StyleSheet, Navigator, View, Text, Button, TouchableHighlight } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; export default class LoginContainer extends Component { constructor(props) { super(props); } render() { let provider = [{ name: 'facebook', text: 'Sign In with Facebook' },{ name: 'twitter', text: 'Sign In with Twitter' }]; let connectProvider = (authProvider) => { // TODO: Implement authentication provider alert(`connect ${authProvider}`); }; return ( <View style={styles.container}> { provider.map((key, val) => { return ( <TouchableHighlight key={val} onPress={ () => connectProvider(key.name) } style={styles.btnLayout}> <View style={styles.btnContainer}> <Icon name={key.name} size={25} color={'#fff'} /> <Text style={styles.btnText}>{key.text}</Text> </View> </TouchableHighlight> ) }) } </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, btnLayout: { flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-start', alignSelf: 'flex-start', backgroundColor: COLOR.md_blue_grey_500, padding: 5, marginTop: 5, marginBottom: 5, marginLeft: 10, marginRight: 10 }, btnContainer: { flex: 1, flexDirection: 'row', justifyContent: 'center', borderRadius: 10, }, btnText: { fontSize: 18, color: '#FAFAFA', marginLeft: 10, marginTop: 2, minWidth: 200 } }); AppRegistry.registerComponent('starter', () => LoginContainer);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js
sThig/jabbascrypt
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(users) { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, ...users, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load([{ id: 42, name: '42' }]); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-spread"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
web/src/client/components/not-found.js
mrsharpoblunto/it-gets-the-hose-again
/* * @format */ import React from 'react'; export default function NotFound() { return ( <div> <h2>You have requested a page that doesn&apos;t exist</h2> </div> ); }
pootle/static/js/auth/components/AuthWindow.js
r-o-b-b-i-e/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import Modal from 'components/Modal'; const AuthWindow = React.createClass({ propTypes: { canContact: React.PropTypes.bool.isRequired, }, renderFooter() { if (!this.props.canContact) { return null; } return ( <a href="#" className="js-contact"> {gettext('Contact Us')} </a> ); }, render() { return ( <Modal className="auth-window" footer={this.renderFooter} {...this.props} /> ); }, }); export default AuthWindow;
blueocean-material-icons/src/js/components/svg-icons/editor/format-clear.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const EditorFormatClear = (props) => ( <SvgIcon {...props}> <path d="M3.27 5L2 6.27l6.97 6.97L6.5 19h3l1.57-3.66L16.73 21 18 19.73 3.55 5.27 3.27 5zM6 5v.18L8.82 8h2.4l-.72 1.68 2.1 2.1L14.21 8H20V5H6z"/> </SvgIcon> ); EditorFormatClear.displayName = 'EditorFormatClear'; EditorFormatClear.muiName = 'SvgIcon'; export default EditorFormatClear;
node_modules/react-router/es6/Router.js
orionwei/mygit
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import createHashHistory from 'history/lib/createHashHistory'; import useQueries from 'history/lib/useQueries'; import invariant from 'invariant'; import React from 'react'; import createTransitionManager from './createTransitionManager'; import { routes } from './InternalPropTypes'; import RouterContext from './RouterContext'; import { createRoutes } from './RouteUtils'; import { createRouterObject, createRoutingHistory } from './RouterUtils'; import warning from './routerWarning'; function isDeprecatedHistory(history) { return !history || !history.__v2_compatible__; } /* istanbul ignore next: sanity check */ function isUnsupportedHistory(history) { // v3 histories expose getCurrentLocation, but aren't currently supported. return history && history.getCurrentLocation; } var _React$PropTypes = React.PropTypes; var func = _React$PropTypes.func; var object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = React.createClass({ displayName: 'Router', propTypes: { history: object, children: routes, routes: routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // Deprecated: parseQueryString: func, stringifyQuery: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return React.createElement(RouterContext, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount: function componentWillMount() { var _this = this; var _props = this.props; var parseQueryString = _props.parseQueryString; var stringifyQuery = _props.stringifyQuery; process.env.NODE_ENV !== 'production' ? warning(!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : void 0; var _createRouterObjects = this.createRouterObjects(); var history = _createRouterObjects.history; var transitionManager = _createRouterObjects.transitionManager; var router = _createRouterObjects.router; this._unlisten = transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { _this.setState(state, _this.props.onUpdate); } }); this.history = history; this.router = router; }, createRouterObjects: function createRouterObjects() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext; } var history = this.props.history; var _props2 = this.props; var routes = _props2.routes; var children = _props2.children; !!isUnsupportedHistory(history) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v3.x. ' + 'This version of React Router is not compatible with v3 history ' + 'objects. Please use history v2.x instead.') : invariant(false) : void 0; if (isDeprecatedHistory(history)) { history = this.wrapDeprecatedHistory(history); } var transitionManager = createTransitionManager(history, createRoutes(routes || children)); var router = createRouterObject(history, transitionManager); var routingHistory = createRoutingHistory(history, transitionManager); return { history: routingHistory, transitionManager: transitionManager, router: router }; }, wrapDeprecatedHistory: function wrapDeprecatedHistory(history) { var _props3 = this.props; var parseQueryString = _props3.parseQueryString; var stringifyQuery = _props3.stringifyQuery; var createHistory = void 0; if (history) { process.env.NODE_ENV !== 'production' ? warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : void 0; createHistory = function createHistory() { return history; }; } else { process.env.NODE_ENV !== 'production' ? warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : void 0; createHistory = createHashHistory; } return useQueries(createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state; var location = _state.location; var routes = _state.routes; var params = _state.params; var components = _state.components; var _props4 = this.props; var createElement = _props4.createElement; var render = _props4.render; var props = _objectWithoutProperties(_props4, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { history: this.history, router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); export default Router;
server/sonar-web/src/main/js/apps/settings/components/Definition.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // @flow import React from 'react'; import { connect } from 'react-redux'; import shallowCompare from 'react-addons-shallow-compare'; import classNames from 'classnames'; import Input from './inputs/Input'; import DefinitionDefaults from './DefinitionDefaults'; import DefinitionChanges from './DefinitionChanges'; import { getPropertyName, getPropertyDescription, getSettingValue, isDefaultOrInherited } from '../utils'; import { translateWithParameters, translate } from '../../../helpers/l10n'; import { resetValue, saveValue } from '../store/actions'; import { passValidation } from '../store/settingsPage/validationMessages/actions'; import { cancelChange, changeValue } from '../store/settingsPage/changedValues/actions'; import { TYPE_PASSWORD } from '../constants'; import { getSettingsAppChangedValue, isSettingsAppLoading, getSettingsAppValidationMessage } from '../../../store/rootReducer'; class Definition extends React.Component { mounted: boolean; timeout: number; static propTypes = { component: React.PropTypes.object, setting: React.PropTypes.object.isRequired, changedValue: React.PropTypes.any, loading: React.PropTypes.bool.isRequired, validationMessage: React.PropTypes.string, changeValue: React.PropTypes.func.isRequired, cancelChange: React.PropTypes.func.isRequired, saveValue: React.PropTypes.func.isRequired, resetValue: React.PropTypes.func.isRequired, passValidation: React.PropTypes.func.isRequired }; state = { success: false }; componentDidMount() { this.mounted = true; } shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } componentWillUnmount() { this.mounted = false; } safeSetState(changes) { if (this.mounted) { this.setState(changes); } } handleChange(value) { clearTimeout(this.timeout); this.props.changeValue(this.props.setting.definition.key, value); if (this.props.setting.definition.type === TYPE_PASSWORD) { this.handleSave(); } } handleReset() { const componentKey = this.props.component ? this.props.component.key : null; const { definition } = this.props.setting; return this.props .resetValue(definition.key, componentKey) .then(() => { this.safeSetState({ success: true }); this.timeout = setTimeout(() => this.safeSetState({ success: false }), 3000); }) .catch(() => { /* do nothing */ }); } handleCancel() { this.props.cancelChange(this.props.setting.definition.key); this.props.passValidation(this.props.setting.definition.key); } handleSave() { this.safeSetState({ success: false }); const componentKey = this.props.component ? this.props.component.key : null; this.props .saveValue(this.props.setting.definition.key, componentKey) .then(() => { this.safeSetState({ success: true }); this.timeout = setTimeout(() => this.safeSetState({ success: false }), 3000); }) .catch(() => { /* do nothing */ }); } render() { const { setting, changedValue, loading } = this.props; const { definition } = setting; const propertyName = getPropertyName(definition); const hasValueChanged = changedValue != null; const className = classNames('settings-definition', { 'settings-definition-changed': hasValueChanged }); const effectiveValue = hasValueChanged ? changedValue : getSettingValue(setting); const isDefault = isDefaultOrInherited(setting) && !hasValueChanged; return ( <div className={className} data-key={definition.key}> <div className="settings-definition-left"> <h3 className="settings-definition-name" title={propertyName}> {propertyName} </h3> <div className="settings-definition-description markdown small spacer-top" dangerouslySetInnerHTML={{ __html: getPropertyDescription(definition) }} /> <div className="settings-definition-key note little-spacer-top"> {translateWithParameters('settings.key_x', definition.key)} </div> </div> <div className="settings-definition-right"> <Input setting={setting} value={effectiveValue} onChange={this.handleChange.bind(this)} /> {!hasValueChanged && <DefinitionDefaults setting={setting} isDefault={isDefault} onReset={() => this.handleReset()} />} {hasValueChanged && <DefinitionChanges onSave={this.handleSave.bind(this)} onCancel={this.handleCancel.bind(this)} />} <div className="settings-definition-state"> {loading && <span className="text-info"> <span className="settings-definition-state-icon"> <i className="spinner" /> </span> {translate('settings.state.saving')} </span>} {!loading && this.props.validationMessage != null && <span className="text-danger"> <span className="settings-definition-state-icon"> <i className="icon-alert-error" /> </span> {translateWithParameters( 'settings.state.validation_failed', this.props.validationMessage )} </span>} {!loading && this.state.success && <span className="text-success"> <span className="settings-definition-state-icon"> <i className="icon-check" /> </span> {translate('settings.state.saved')} </span>} </div> </div> </div> ); } } const mapStateToProps = (state, ownProps) => ({ changedValue: getSettingsAppChangedValue(state, ownProps.setting.definition.key), loading: isSettingsAppLoading(state, ownProps.setting.definition.key), validationMessage: getSettingsAppValidationMessage(state, ownProps.setting.definition.key) }); export default connect(mapStateToProps, { changeValue, saveValue, resetValue, passValidation, cancelChange })(Definition);
js/components/tab/configTab.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Button, Icon, Tabs, Tab, Text, Right, Left, Body, TabHeading } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import myTheme from '../../themes/base-theme'; import TabOne from './tabOne'; import TabTwo from './tabTwo'; import TabThree from './tabThree'; const { popRoute, } = actions; class ConfigTab extends Component { // eslint-disable-line static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container> <Header hasTabs> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title> Advanced Tabs</Title> </Body> <Right /> </Header> <Tabs style={{ elevation: 3 }}> <Tab heading={<TabHeading><Icon name="camera" /><Text>Camera</Text></TabHeading>}> <TabOne /> </Tab> <Tab heading={<TabHeading><Text>No Icon</Text></TabHeading>}> <TabTwo /> </Tab> <Tab heading={<TabHeading><Icon name="apps" /></TabHeading>}> <TabThree /> </Tab> </Tabs> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(ConfigTab);
components/app/common/ContactUs/ContactUsForm.js
resource-watch/resource-watch
import React from 'react'; // Services import { toastr } from 'react-redux-toastr'; import { contactUs } from 'services/contact-us'; // Components import Spinner from 'components/ui/Spinner'; import Field from 'components/form/Field'; import Input from 'components/form/Input'; import TextArea from 'components/form/TextArea'; import Select from 'components/form/SelectInput'; import Modal from 'components/modal/modal-component'; import SubmitModalComponent from 'components/modal/submit-modal'; // Constants import { FORM_ELEMENTS, STATE_DEFAULT, FORM_TOPICS } from './constants'; class ContactUsForm extends React.Component { state = { ...STATE_DEFAULT, form: STATE_DEFAULT.form, showSubmitModal: false, }; /** * UI EVENTS * - onSubmit * - onChange * - handleToggleModal */ onSubmit = (event) => { const { form } = this.state; event.preventDefault(); // Validate the form FORM_ELEMENTS.validate(form); // Set a timeout due to the setState function of react setTimeout(() => { const valid = FORM_ELEMENTS.isValid(form); if (valid) { this.setState({ submitting: true }); // Save data contactUs(form) .then(() => { this.setState({ submitting: false }); this.handleToggleModal(true); }) .catch(() => { this.setState({ submitting: false }); toastr.error('Error', 'Oops!! There was an error. Try again'); }); } else { toastr.error('Error', 'Fill all the required fields or correct the invalid values'); } }, 0); }; onChange(obj) { const form = { ...this.state.form, ...obj }; this.setState({ form }); } handleToggleModal = (bool) => { this.setState({ showSubmitModal: bool }); }; render() { const { submitting } = this.state; return ( <div className="c-contact-us"> <form className="c-form" onSubmit={this.onSubmit} noValidate> <Field ref={(c) => { if (c) FORM_ELEMENTS.elements.topic = c; }} onChange={(value) => this.onChange({ topic: value })} validations={['required']} className="-fluid" options={FORM_TOPICS.options} properties={{ name: 'topic', label: 'Topic', type: 'text', required: true, default: this.state.form.topic, }} > {Select} </Field> <Field ref={(c) => { if (c) FORM_ELEMENTS.elements.email = c; }} onChange={(value) => this.onChange({ email: value })} validations={['required', 'email']} className="-fluid" properties={{ name: 'email', label: 'Email', type: 'email', required: true, placeholder: 'Your Email', default: this.state.form.email, }} > {Input} </Field> <Field ref={(c) => { if (c) FORM_ELEMENTS.elements.text = c; }} onChange={(value) => this.onChange({ text: value })} validations={['required']} className="-fluid" properties={{ name: 'text', label: 'Message', required: true, placeholder: 'Tell us how we can help.', default: this.state.form.text, }} > {TextArea} </Field> <div className="flex justify-end"> <button type="submit" className={`c-btn -primary ${submitting ? '-disabled' : null}`} disabled={submitting} > {submitting && ( <Spinner className="-small -transparent -white-icon" isLoading={submitting} /> )} Submit </button> </div> </form> <Modal isOpen={this.state.showSubmitModal} className="-medium" onRequestClose={() => this.handleToggleModal(false)} > <SubmitModalComponent header="Thanks for your message." text="Someone from our team will be in touch shortly." /> </Modal> </div> ); } } export default ContactUsForm;
packages/lightning-core/common/CurrencyInput.js
DaReaper/lightning-app
import React from 'react' import reactCSS from 'reactcss' import Input from './Input' import { enforceNumbers } from '../helpers/currencies' export const CurrencyInput = (props) => { const styles = reactCSS({ 'default': { changer: { marginTop: 10, marginBottom: 10, borderLeft: '1px solid #ddd', paddingLeft: 15, paddingRight: 15, display: 'flex', alignItems: 'center', color: '#999', }, }, }) const changer = ( <div style={ styles.changer }>SAT</div> ) return ( <Input { ...props } right={ changer } sanitizeReturn={ enforceNumbers } /> ) } export default CurrencyInput
App/Platform/StatusBar.android.js
taskrabbit/ReactNativeSampleApp
import React from 'react'; var StatusBar = { setNetworkActive(active) { }, setHidden(hidden) { }, setStyle(style) { }, }; export default StatusBar;
client/js/components/About.js
bmacheski/tech-connect
'use strict'; import React from 'react'; class About extends React.Component { render() { return ( <div className="ui container holder"> <h2>What is Tech Connect?</h2> <p className="about p">Tech Connect was built to address the dissatisfaction with existing tools to connect IT professionals with home users in need of technical assistance. Tech Connect aims to solve this problem. </p> <h2>How does this work?</h2> <p className="about p">Users would like to register as technicians will need to click the "become a technician" tab in the navigation. They will then be able to view job postings that users submit and will then be able to initiate communication with clients for jobs that they would like to take on. </p> </div> ) } } export default About;
client/src/components/sales/rotator-nav.js
iNeedCode/mern-starter
import React, { Component } from 'react'; class RotatorNav extends Component { renderNav() { const toMap = []; for (let i = 0; i < this.props.length; i++) { toMap.push( <li key={`${i}nav`} value={i} className={i == this.props.active ? 'slider-nav-bullet active' : 'slider-nav-bullet'} onClick={this.props.setPage} />, ); } return toMap; } render() { return ( <ul> {this.renderNav()} </ul> ); } } export default RotatorNav;
src/svg-icons/notification/tap-and-play.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationTapAndPlay = (props) => ( <SvgIcon {...props}> <path d="M2 16v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0 4v3h3c0-1.66-1.34-3-3-3zm0-8v2c4.97 0 9 4.03 9 9h2c0-6.08-4.92-11-11-11zM17 1.01L7 1c-1.1 0-2 .9-2 2v7.37c.69.16 1.36.37 2 .64V5h10v13h-3.03c.52 1.25.84 2.59.95 4H17c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99z"/> </SvgIcon> ); NotificationTapAndPlay = pure(NotificationTapAndPlay); NotificationTapAndPlay.displayName = 'NotificationTapAndPlay'; NotificationTapAndPlay.muiName = 'SvgIcon'; export default NotificationTapAndPlay;
app/components/TableRow/index.js
X0nic/cloud-cost
import React from 'react'; import { fromJS } from 'immutable'; import styles from './styles.css'; function TableRow(props) { let content; if (props.items) { content = props.items.map((item, index) => ( <td key={`item-${index}`}>{item}</td> )); } else { content = (<td>Nothing to render</td>); } return (<tr>{content}</tr>); } TableRow.propTypes = { // component: React.PropTypes.func.isRequired, items: React.PropTypes.array, headers: React.PropTypes.array, }; export default TableRow;
client/modules/Post/components/PostListItem/PostListItem.js
mraq1234/mod11
import React from 'react'; import propTypes from 'prop-types'; import { Link } from 'react-router'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './PostListItem.css'; function PostListItem(props) { return ( <div className={styles['single-post']}> <h3 className={styles['post-title']}> <Link to={`/posts/${props.post.slug}-${props.post.cuid}`} > {props.post.title} </Link> </h3> <p className={styles['author-name']}><FormattedMessage id="by" /> {props.post.name}</p> <p className={styles['post-desc']}>{props.post.content}</p> <p className={styles['post-action']}><a href="#" onClick={props.onDelete}><FormattedMessage id="deletePost" /></a></p> <hr className={styles.divider} /> </div> ); } PostListItem.propTypes = { post: propTypes.shape({ name: propTypes.string.isRequired, title: propTypes.string.isRequired, content: propTypes.string.isRequired, slug: propTypes.string.isRequired, cuid: propTypes.string.isRequired, }).isRequired, onDelete: propTypes.func.isRequired, }; export default PostListItem;
imports/startup/client/app.js
ShinyLeee/meteor-album-app
import { Meteor } from 'meteor/meteor'; import { platform } from '/imports/utils'; import React from 'react'; import { render } from 'react-dom'; // import App_Mobile from '/imports/ui/App'; // import App_PC from '/imports/ui/App_PC'; // const App = platform().mobile ? App_Mobile : App_PC; async function renderAsync() { const [ // React, // { render }, { default: App }, ] = await Promise.all([ // import('react'), // import('react-dom'), platform().mobile ? import('/imports/ui/App') : import('/imports/ui/App_PC'), ]); render(<App />, document.getElementById('app')); } // This is Use of Disabling User zooming the Page in IOS10 const noScalable = () => { document.documentElement.addEventListener('touchstart', (evt) => { if (evt.touches.length > 1) { evt.preventDefault(); } }, false); let lastTouchEnd = 0; document.documentElement.addEventListener('touchend', (evt) => { const now = (new Date()).getTime(); if (now - lastTouchEnd <= 300) { evt.preventDefault(); } lastTouchEnd = now; }, false); }; Meteor.startup(() => { noScalable(); const renderStart = Date.now(); const startupTime = renderStart - window.performance.timing.responseStart; console.log(`Meteor.startup took: ${startupTime}ms`); renderAsync().then(() => { const renderTime = Date.now() - renderStart; console.log(`renderAsync took: ${renderTime}ms`); console.log(`Total time: ${startupTime + renderTime}ms`); }); });
client/src/components/Modal/ConfirmDeletionModal.js
Wiredcraft/jekyllpro-cms
import React from 'react'; import Modal from 'react-modal'; import ModalCustomStyle from '../Modal'; import ModalCloseIcon from '../svg/ModalCloseIcon'; const confirmDeleteionModal = props => { return ( <Modal contentLabel="Confirm removal" className="confirm-deletion" style={ModalCustomStyle} isOpen={props.isOpen} onRequestClose={props.onclose} > <header className="header"> <a className="close" id="close-modal" onClick={props.onclose}> <ModalCloseIcon /> </a> <h2>Are you sure to delete this file?</h2> </header> <section className="body"> <p> <button className="button primary" onClick={props.onsubmit}> Yes </button> <button className="button" onClick={props.oncancel}> Cancel </button> </p> </section> </Modal> ); }; export default confirmDeleteionModal;
common/components/ide/Terminal.js
ebertmi/webbox
import React from 'react'; import { Terminal as Term } from 'xterm'; import * as fit from 'xterm/lib/addons/fit/fit'; import capitalize from 'lodash/capitalize'; import debounce from 'lodash/debounce'; import isFunction from 'lodash/isFunction'; import Debug from 'debug'; import TerminalManager from '../../models/terminalManager'; const debug = Debug('webbox:Terminal'); const events = [ 'data', 'end', 'finish', 'title', 'bell', 'destroy' ]; // Load fit addon Term.applyAddon(fit); export function once(type, listener) { var fired = false; if (!isFunction(listener)) { throw TypeError('listener must be a function'); } function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; } export function pipeXterm(src, dest) { let ondata; let onerror; let onend; function unbind() { src.removeListener('data', ondata); src.removeListener('error', onerror); src.removeListener('end', onend); dest.removeListener('error', onerror); dest.removeListener('close', unbind); } src.on('data', ondata = function ondata(data) { dest.write(data); }); src.on('error', onerror = function onerror( err) { unbind(); if (!this.listeners('error').length) { throw err; } }); src.on('end', onend = function onend() { dest.end(); unbind(); }); dest.on('error', onerror); dest.on('close', unbind); dest.emit('pipe', src); return dest; } export default class Terminal extends React.Component { constructor(props) { super(props); this.onStreamChange = this.onStreamChange.bind(this); this.onResize = debounce(this.onResize.bind(this), 100, true); } componentDidMount() { if (this.props.process) { this.props.process.on('streamsChanged', this.onStreamChange); } let reuse = false; if (this.props.process && TerminalManager.has(this.props.process.id)) { this.terminal = TerminalManager.get(this.props.process.id); reuse = true; } else { this.terminal = new Term({ screenKeys: true, cursorBlink: true }); // add once method as in xterm.js 3.x is was optimized away -.- this.terminal.once = once.bind(this.terminal); // add standard EventEmitter.removeListener this.terminal.removeListener = this.terminal.off; TerminalManager.set(this.props.process.id, this.terminal); } this.terminal.open(this.container); this.terminal.focus(); this.terminal.setOption('fontFamily', this.props.fontFamily); this.terminal.setOption('fontSize', this.props.fontSize); window.addEventListener('resize', this.onResize); events.forEach(event => { this.terminal.on(event, (...args) => { const handler = this.props['on' + capitalize(event)]; if (handler) { handler(...args); } }); }); this.onResize(); this.terminal.refresh(0, this.terminal.rows - 1); this.terminal.focus(); // Do not attach the streams again, after mounting again if (reuse === true) { return; } this.onStreamChange(reuse); } componentDidUpdate(prevProps) { if (!this.props.hidden) { this.onResize(); //this.terminal.refresh(0, this.terminal.rows - 1); if (prevProps.hidden) { this.terminal.element.focus(); this.terminal.focus(); } } // apply changed props this.terminal.setOption('fontFamily', this.props.fontFamily); this.terminal.setOption('fontSize', this.props.fontSize); } componentWillUnmount() { if (this.props.process) { this.props.process.removeListener('streamsChanged', this.onStreamChange); } window.removeEventListener('resize', this.onResize); } onStreamChange(reuse) { const process = this.props.process; // Reset the terminal and delete old lines! if (reuse === false) { this.terminal.clear(); } if (process.stdin) { pipeXterm(this.terminal, process.stdin); } if (process.stdout) { process.stdout.setEncoding('utf8'); process.stdout.pipe(this.terminal, { end: false }); } if (process.stderr && process.stderr !== process.stdout) { process.stderr.setEncoding('utf8'); process.stderr.pipe(this.terminal, { end: false }); } this.terminal.refresh(); this.terminal.focus(); } onResize() { if (this.props.hidden) { return; } this.terminal.fit(); } render() { const style = { fontFamily: this.props.fontFamily, fontSize: this.props.fontSize }; return ( <div className="terminal-wrapper" hidden={this.props.hidden}> <div style={style} className="terminal-container" hidden={this.props.hidden} ref={div => this.container = div}/> </div>); } }
node_modules/react-router/es6/Lifecycle.js
ajkhatibi/wheevy
import warning from './routerWarning'; import React from 'react'; import invariant from 'invariant'; var object = React.PropTypes.object; /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ var Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount: function componentDidMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : void 0; !this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : void 0; var route = this.props.route || this.context.route; !route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : void 0; this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave); }, componentWillUnmount: function componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute(); } }; export default Lifecycle;
src/svg-icons/device/battery-charging-full.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryChargingFull = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/> </SvgIcon> ); DeviceBatteryChargingFull = pure(DeviceBatteryChargingFull); DeviceBatteryChargingFull.displayName = 'DeviceBatteryChargingFull'; DeviceBatteryChargingFull.muiName = 'SvgIcon'; export default DeviceBatteryChargingFull;
node_modules/react-router/es6/Link.js
tacrow/tacrow
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]), query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; !this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(location); }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (to == null) { return React.createElement('a', props); } var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(location); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(location, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
src/svg-icons/action/card-membership.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCardMembership = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V4h16v6z"/> </SvgIcon> ); ActionCardMembership = pure(ActionCardMembership); ActionCardMembership.displayName = 'ActionCardMembership'; ActionCardMembership.muiName = 'SvgIcon'; export default ActionCardMembership;
frontend/jqwidgets/jqwidgets-react/react_jqxcheckbox.js
liamray/nexl-js
/* jQWidgets v5.7.2 (2018-Apr) Copyright (c) 2011-2018 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxCheckBox extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['animationShowDelay','animationHideDelay','boxSize','checked','disabled','enableContainerClick','groupName','height','hasThreeStates','locked','rtl','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxCheckBox(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxCheckBox('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxCheckBox(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; animationShowDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('animationShowDelay', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('animationShowDelay'); } }; animationHideDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('animationHideDelay', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('animationHideDelay'); } }; boxSize(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('boxSize', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('boxSize'); } }; checked(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('checked', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('checked'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('disabled', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('disabled'); } }; enableContainerClick(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('enableContainerClick', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('enableContainerClick'); } }; groupName(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('groupName', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('groupName'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('height', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('height'); } }; hasThreeStates(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('hasThreeStates', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('hasThreeStates'); } }; locked(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('locked', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('locked'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('rtl', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('rtl'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('theme', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('width', arg) } else { return JQXLite(this.componentSelector).jqxCheckBox('width'); } }; check() { JQXLite(this.componentSelector).jqxCheckBox('check'); }; disable() { JQXLite(this.componentSelector).jqxCheckBox('disable'); }; destroy() { JQXLite(this.componentSelector).jqxCheckBox('destroy'); }; enable() { JQXLite(this.componentSelector).jqxCheckBox('enable'); }; focus() { JQXLite(this.componentSelector).jqxCheckBox('focus'); }; indeterminate() { JQXLite(this.componentSelector).jqxCheckBox('indeterminate'); }; performRender() { JQXLite(this.componentSelector).jqxCheckBox('render'); }; toggle() { JQXLite(this.componentSelector).jqxCheckBox('toggle'); }; uncheck() { JQXLite(this.componentSelector).jqxCheckBox('uncheck'); }; val(value) { if (value !== undefined) { JQXLite(this.componentSelector).jqxCheckBox('val', value) } else { return JQXLite(this.componentSelector).jqxCheckBox('val'); } }; render() { let id = 'jqxCheckBox' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}><span>{this.props.value}</span></div> ) }; };
src/components/Disciplina/Notas/index.js
RodolfoSilva/DeVryCalc
import React from 'react' import { View } from 'react-native' import Nota from '../Nota' import PropTypes from 'prop-types' import { styleByNota } from './styles' const Notas = ({ ap1 = null, ap2 = null, ap3 = null, style }) => ( <View style={style}> <Nota value={ap1} valueStyle={styleByNota(ap1)} title="AP1" /> <Nota value={ap2} valueStyle={styleByNota(ap2)} title="AP2" /> <Nota value={ap3} valueStyle={styleByNota(ap3)} title="AP3" /> </View> ) Notas.propTypes = { ap1: PropTypes.number, ap2: PropTypes.number, ap3: PropTypes.number, style: View.propTypes.style } export default Notas
src/test-component/draft/draft-settings-map/BlockRenderMap.js
GoreStarry/Stories_Kingdom
import React from 'react'; import Immutable from 'immutable'; import BlockWapperTest from '../components/BlockWapperTest.jsx'; import CommentBlock from '../components/CommentBlock.jsx'; export const BlockRenderMap = Immutable.Map({ 'superTitleBlock': { element: 'h1', wrapper: <BlockWapperTest/> }, 'commendBlock': { element: 'div', wrapper: <CommentBlock/> } }) export function myBlockStyleFn(contentBlock) { const type = contentBlock.getType(); switch (type) { case 'superTitleBlock': return 'super__title' case 'commendBlock': return 'block__comment' } }
app/screens/Settings.js
celikmus/MathWise
import React from 'react'; import { Text, StatusBar } from 'react-native'; import { Container } from '../components/Container'; import styles from './styles'; const Settings = () => <Container> <StatusBar translucent={false} barStyle="default" /> <Text>Settings page lala...</Text> </Container>; Settings.navigationOptions = { headerTitle: 'Settings' }; export default Settings;
src/js/components/icons/base/Sidebar.js
linde12/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}-sidebar`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'sidebar'); 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="M1,22 L23,22 L23,2 L1,2 L1,22 Z M16,2 L16,22 L16,2 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Sidebar'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/javascript/mastodon/features/ui/index.js
koba-lab/mastodon
import classNames from 'classnames'; import React from 'react'; import { HotKeys } from 'react-hotkeys'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import NotificationsContainer from './containers/notifications_container'; import LoadingBarContainer from './containers/loading_bar_container'; import ModalContainer from './containers/modal_container'; import { layoutFromWindow } from 'mastodon/is_mobile'; import { debounce } from 'lodash'; import { uploadCompose, resetCompose, changeComposeSpoilerness } from '../../actions/compose'; import { expandHomeTimeline } from '../../actions/timelines'; import { expandNotifications } from '../../actions/notifications'; import { fetchFilters } from '../../actions/filters'; import { clearHeight } from '../../actions/height_cache'; import { focusApp, unfocusApp, changeLayout } from 'mastodon/actions/app'; import { synchronouslySubmitMarkers, submitMarkers, fetchMarkers } from 'mastodon/actions/markers'; import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers'; import UploadArea from './components/upload_area'; import ColumnsAreaContainer from './containers/columns_area_container'; import DocumentTitle from './components/document_title'; import PictureInPicture from 'mastodon/features/picture_in_picture'; import { Compose, Status, GettingStarted, KeyboardShortcuts, PublicTimeline, CommunityTimeline, AccountTimeline, AccountGallery, HomeTimeline, Followers, Following, Reblogs, Favourites, DirectTimeline, HashtagTimeline, Notifications, FollowRequests, GenericNotFound, FavouritedStatuses, BookmarkedStatuses, ListTimeline, Blocks, DomainBlocks, Mutes, PinnedStatuses, Lists, Directory, Explore, FollowRecommendations, } from './util/async-components'; import { me } from '../../initial_state'; import { closeOnboarding, INTRODUCTION_VERSION } from 'mastodon/actions/onboarding'; // Dummy import, to make sure that <Status /> ends up in the application bundle. // Without this it ends up in ~8 very commonly used bundles. import '../../components/status'; const messages = defineMessages({ beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' }, }); const mapStateToProps = state => ({ layout: state.getIn(['meta', 'layout']), isComposing: state.getIn(['compose', 'is_composing']), hasComposingText: state.getIn(['compose', 'text']).trim().length !== 0, hasMediaAttachments: state.getIn(['compose', 'media_attachments']).size > 0, canUploadMore: !state.getIn(['compose', 'media_attachments']).some(x => ['audio', 'video'].includes(x.get('type'))) && state.getIn(['compose', 'media_attachments']).size < 4, dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null, firstLaunch: state.getIn(['settings', 'introductionVersion'], 0) < INTRODUCTION_VERSION, username: state.getIn(['accounts', me, 'username']), }); const keyMap = { help: '?', new: 'n', search: 's', forceNew: 'option+n', toggleComposeSpoilers: 'option+x', focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'], reply: 'r', favourite: 'f', boost: 'b', mention: 'm', open: ['enter', 'o'], openProfile: 'p', moveDown: ['down', 'j'], moveUp: ['up', 'k'], back: 'backspace', goToHome: 'g h', goToNotifications: 'g n', goToLocal: 'g l', goToFederated: 'g t', goToDirect: 'g d', goToStart: 'g s', goToFavourites: 'g f', goToPinned: 'g p', goToProfile: 'g u', goToBlocked: 'g b', goToMuted: 'g m', goToRequests: 'g r', toggleHidden: 'x', toggleSensitive: 'h', openMedia: 'e', }; class SwitchingColumnsArea extends React.PureComponent { static propTypes = { children: PropTypes.node, location: PropTypes.object, mobile: PropTypes.bool, }; componentWillMount () { if (this.props.mobile) { document.body.classList.toggle('layout-single-column', true); document.body.classList.toggle('layout-multiple-columns', false); } else { document.body.classList.toggle('layout-single-column', false); document.body.classList.toggle('layout-multiple-columns', true); } } componentDidUpdate (prevProps) { if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) { this.node.handleChildrenContentChange(); } if (prevProps.mobile !== this.props.mobile) { document.body.classList.toggle('layout-single-column', this.props.mobile); document.body.classList.toggle('layout-multiple-columns', !this.props.mobile); } } setRef = c => { if (c) { this.node = c.getWrappedInstance(); } } render () { const { children, mobile } = this.props; const redirect = mobile ? <Redirect from='/' to='/home' exact /> : <Redirect from='/' to='/getting-started' exact />; return ( <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}> <WrappedSwitch> {redirect} <WrappedRoute path='/getting-started' component={GettingStarted} content={children} /> <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} /> <WrappedRoute path={['/home', '/timelines/home']} component={HomeTimeline} content={children} /> <WrappedRoute path={['/public', '/timelines/public']} exact component={PublicTimeline} content={children} /> <WrappedRoute path={['/public/local', '/timelines/public/local']} exact component={CommunityTimeline} content={children} /> <WrappedRoute path={['/conversations', '/timelines/direct']} component={DirectTimeline} content={children} /> <WrappedRoute path='/tags/:id' component={HashtagTimeline} content={children} /> <WrappedRoute path='/lists/:id' component={ListTimeline} content={children} /> <WrappedRoute path='/notifications' component={Notifications} content={children} /> <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} /> <WrappedRoute path='/bookmarks' component={BookmarkedStatuses} content={children} /> <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} /> <WrappedRoute path='/start' component={FollowRecommendations} content={children} /> <WrappedRoute path='/directory' component={Directory} content={children} /> <WrappedRoute path={['/explore', '/search']} component={Explore} content={children} /> <WrappedRoute path={['/publish', '/statuses/new']} component={Compose} content={children} /> <WrappedRoute path={['/@:acct', '/accounts/:id']} exact component={AccountTimeline} content={children} /> <WrappedRoute path={['/@:acct/with_replies', '/accounts/:id/with_replies']} component={AccountTimeline} content={children} componentParams={{ withReplies: true }} /> <WrappedRoute path={['/@:acct/followers', '/accounts/:id/followers']} component={Followers} content={children} /> <WrappedRoute path={['/@:acct/following', '/accounts/:id/following']} component={Following} content={children} /> <WrappedRoute path={['/@:acct/media', '/accounts/:id/media']} component={AccountGallery} content={children} /> <WrappedRoute path='/@:acct/:statusId' exact component={Status} content={children} /> <WrappedRoute path='/@:acct/:statusId/reblogs' component={Reblogs} content={children} /> <WrappedRoute path='/@:acct/:statusId/favourites' component={Favourites} content={children} /> {/* Legacy routes, cannot be easily factored with other routes because they share a param name */} <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} /> <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} /> <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} /> <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} /> <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} /> <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} /> <WrappedRoute path='/blocks' component={Blocks} content={children} /> <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} /> <WrappedRoute path='/mutes' component={Mutes} content={children} /> <WrappedRoute path='/lists' component={Lists} content={children} /> <WrappedRoute component={GenericNotFound} content={children} /> </WrappedSwitch> </ColumnsAreaContainer> ); } } export default @connect(mapStateToProps) @injectIntl @withRouter class UI extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { dispatch: PropTypes.func.isRequired, children: PropTypes.node, isComposing: PropTypes.bool, hasComposingText: PropTypes.bool, hasMediaAttachments: PropTypes.bool, canUploadMore: PropTypes.bool, location: PropTypes.object, intl: PropTypes.object.isRequired, dropdownMenuIsOpen: PropTypes.bool, layout: PropTypes.string.isRequired, firstLaunch: PropTypes.bool, username: PropTypes.string, }; state = { draggingOver: false, }; handleBeforeUnload = e => { const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props; dispatch(synchronouslySubmitMarkers()); if (isComposing && (hasComposingText || hasMediaAttachments)) { e.preventDefault(); // Setting returnValue to any string causes confirmation dialog. // Many browsers no longer display this text to users, // but we set user-friendly message for other browsers, e.g. Edge. e.returnValue = intl.formatMessage(messages.beforeUnload); } } handleWindowFocus = () => { this.props.dispatch(focusApp()); this.props.dispatch(submitMarkers({ immediate: true })); } handleWindowBlur = () => { this.props.dispatch(unfocusApp()); } handleDragEnter = (e) => { e.preventDefault(); if (!this.dragTargets) { this.dragTargets = []; } if (this.dragTargets.indexOf(e.target) === -1) { this.dragTargets.push(e.target); } if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files') && this.props.canUploadMore) { this.setState({ draggingOver: true }); } } handleDragOver = (e) => { if (this.dataTransferIsText(e.dataTransfer)) return false; e.preventDefault(); e.stopPropagation(); try { e.dataTransfer.dropEffect = 'copy'; } catch (err) { } return false; } handleDrop = (e) => { if (this.dataTransferIsText(e.dataTransfer)) return; e.preventDefault(); this.setState({ draggingOver: false }); this.dragTargets = []; if (e.dataTransfer && e.dataTransfer.files.length >= 1 && this.props.canUploadMore) { this.props.dispatch(uploadCompose(e.dataTransfer.files)); } } handleDragLeave = (e) => { e.preventDefault(); e.stopPropagation(); this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el)); if (this.dragTargets.length > 0) { return; } this.setState({ draggingOver: false }); } dataTransferIsText = (dataTransfer) => { return (dataTransfer && Array.from(dataTransfer.types).filter((type) => type === 'text/plain').length === 1); } closeUploadModal = () => { this.setState({ draggingOver: false }); } handleServiceWorkerPostMessage = ({ data }) => { if (data.type === 'navigate') { this.context.router.history.push(data.path); } else { console.warn('Unknown message type:', data.type); } } handleLayoutChange = debounce(() => { this.props.dispatch(clearHeight()); // The cached heights are no longer accurate, invalidate }, 500, { trailing: true, }); handleResize = () => { const layout = layoutFromWindow(); if (layout !== this.props.layout) { this.handleLayoutChange.cancel(); this.props.dispatch(changeLayout(layout)); } else { this.handleLayoutChange(); } } componentDidMount () { window.addEventListener('focus', this.handleWindowFocus, false); window.addEventListener('blur', this.handleWindowBlur, false); window.addEventListener('beforeunload', this.handleBeforeUnload, false); window.addEventListener('resize', this.handleResize, { passive: true }); document.addEventListener('dragenter', this.handleDragEnter, false); document.addEventListener('dragover', this.handleDragOver, false); document.addEventListener('drop', this.handleDrop, false); document.addEventListener('dragleave', this.handleDragLeave, false); document.addEventListener('dragend', this.handleDragEnd, false); if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage); } // On first launch, redirect to the follow recommendations page if (this.props.firstLaunch) { this.context.router.history.replace('/start'); this.props.dispatch(closeOnboarding()); } this.props.dispatch(fetchMarkers()); this.props.dispatch(expandHomeTimeline()); this.props.dispatch(expandNotifications()); setTimeout(() => this.props.dispatch(fetchFilters()), 500); this.hotkeys.__mousetrap__.stopCallback = (e, element) => { return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName); }; } componentWillUnmount () { window.removeEventListener('focus', this.handleWindowFocus); window.removeEventListener('blur', this.handleWindowBlur); window.removeEventListener('beforeunload', this.handleBeforeUnload); window.removeEventListener('resize', this.handleResize); document.removeEventListener('dragenter', this.handleDragEnter); document.removeEventListener('dragover', this.handleDragOver); document.removeEventListener('drop', this.handleDrop); document.removeEventListener('dragleave', this.handleDragLeave); document.removeEventListener('dragend', this.handleDragEnd); } setRef = c => { this.node = c; } handleHotkeyNew = e => { e.preventDefault(); const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea'); if (element) { element.focus(); } } handleHotkeySearch = e => { e.preventDefault(); const element = this.node.querySelector('.search__input'); if (element) { element.focus(); } } handleHotkeyForceNew = e => { this.handleHotkeyNew(e); this.props.dispatch(resetCompose()); } handleHotkeyToggleComposeSpoilers = e => { e.preventDefault(); this.props.dispatch(changeComposeSpoilerness()); } handleHotkeyFocusColumn = e => { const index = (e.key * 1) + 1; // First child is drawer, skip that const column = this.node.querySelector(`.column:nth-child(${index})`); if (!column) return; const container = column.querySelector('.scrollable'); if (container) { const status = container.querySelector('.focusable'); if (status) { if (container.scrollTop > status.offsetTop) { status.scrollIntoView(true); } status.focus(); } } } handleHotkeyBack = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } setHotkeysRef = c => { this.hotkeys = c; } handleHotkeyToggleHelp = () => { if (this.props.location.pathname === '/keyboard-shortcuts') { this.context.router.history.goBack(); } else { this.context.router.history.push('/keyboard-shortcuts'); } } handleHotkeyGoToHome = () => { this.context.router.history.push('/home'); } handleHotkeyGoToNotifications = () => { this.context.router.history.push('/notifications'); } handleHotkeyGoToLocal = () => { this.context.router.history.push('/public/local'); } handleHotkeyGoToFederated = () => { this.context.router.history.push('/public'); } handleHotkeyGoToDirect = () => { this.context.router.history.push('/conversations'); } handleHotkeyGoToStart = () => { this.context.router.history.push('/getting-started'); } handleHotkeyGoToFavourites = () => { this.context.router.history.push('/favourites'); } handleHotkeyGoToPinned = () => { this.context.router.history.push('/pinned'); } handleHotkeyGoToProfile = () => { this.context.router.history.push(`/@${this.props.username}`); } handleHotkeyGoToBlocked = () => { this.context.router.history.push('/blocks'); } handleHotkeyGoToMuted = () => { this.context.router.history.push('/mutes'); } handleHotkeyGoToRequests = () => { this.context.router.history.push('/follow_requests'); } render () { const { draggingOver } = this.state; const { children, isComposing, location, dropdownMenuIsOpen, layout } = this.props; const handlers = { help: this.handleHotkeyToggleHelp, new: this.handleHotkeyNew, search: this.handleHotkeySearch, forceNew: this.handleHotkeyForceNew, toggleComposeSpoilers: this.handleHotkeyToggleComposeSpoilers, focusColumn: this.handleHotkeyFocusColumn, back: this.handleHotkeyBack, goToHome: this.handleHotkeyGoToHome, goToNotifications: this.handleHotkeyGoToNotifications, goToLocal: this.handleHotkeyGoToLocal, goToFederated: this.handleHotkeyGoToFederated, goToDirect: this.handleHotkeyGoToDirect, goToStart: this.handleHotkeyGoToStart, goToFavourites: this.handleHotkeyGoToFavourites, goToPinned: this.handleHotkeyGoToPinned, goToProfile: this.handleHotkeyGoToProfile, goToBlocked: this.handleHotkeyGoToBlocked, goToMuted: this.handleHotkeyGoToMuted, goToRequests: this.handleHotkeyGoToRequests, }; return ( <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef} attach={window} focused> <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}> <SwitchingColumnsArea location={location} mobile={layout === 'mobile' || layout === 'single-column'}> {children} </SwitchingColumnsArea> {layout !== 'mobile' && <PictureInPicture />} <NotificationsContainer /> <LoadingBarContainer className='loading-bar' /> <ModalContainer /> <UploadArea active={draggingOver} onClose={this.closeUploadModal} /> <DocumentTitle /> </div> </HotKeys> ); } }
examples/real-world/src/containers/Root.dev.js
lifeiscontent/redux
import React from 'react' import PropTypes from 'prop-types' import { Provider } from 'react-redux' import routes from '../routes' import DevTools from './DevTools' import { Router } from 'react-router' const Root = ({ store, history }) => ( <Provider store={store}> <div> <Router history={history} routes={routes} /> <DevTools /> </div> </Provider> ) Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired } export default Root
lavalab/html/node_modules/react-bootstrap/es/Badge.js
LavaLabUSC/usclavalab.org
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; // TODO: `pullRight` doesn't belong here. There's no special handling here. var propTypes = { pullRight: PropTypes.bool }; var defaultProps = { pullRight: false }; var Badge = function (_React$Component) { _inherits(Badge, _React$Component); function Badge() { _classCallCheck(this, Badge); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Badge.prototype.hasContent = function hasContent(children) { var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Badge.prototype.render = function render() { var _props = this.props, pullRight = _props.pullRight, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['pullRight', 'className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), { 'pull-right': pullRight, // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return React.createElement( 'span', _extends({}, elementProps, { className: classNames(className, classes) }), children ); }; return Badge; }(React.Component); Badge.propTypes = propTypes; Badge.defaultProps = defaultProps; export default bsClass('badge', Badge);
node_modules/react-taco-table/site/src/components/ExampleSummarizer.js
together-web-pj/together-web-pj
import React from 'react'; import { TacoTable, DataType, Formatters, Summarizers, TdClassNames } from 'react-taco-table'; import cellLinesData from '../data/cell_lines.json'; /** * An example demonstrating how to use column summarizers. */ const columns = [ { id: 'name', value: rowData => rowData.cellLine.label, header: 'Cell Line', type: DataType.String, }, { id: 'receptorStatus', header: 'Receptor Status', value: rowData => rowData.receptorStatus.label, type: DataType.String, }, { id: 'MLL3', type: DataType.String, // find the most frequently occurring value summarize: (column, tableData, columns) => { let mostFrequent; tableData.reduce((counts, rowData) => { const cellData = rowData.MLL3; if (!counts[cellData]) { counts[cellData] = 1; } else { counts[cellData] += 1; } if (mostFrequent == null || (counts[cellData] > counts[mostFrequent])) { mostFrequent = cellData; } return counts; }, {}); return { mostFrequent }; }, // color the most frequently occuring value tdStyle: (cellData, summary, column, rowData) => { if (cellData === summary.mostFrequent) { return { color: '#34c', fontWeight: 'bold' }; } return undefined; }, }, { id: 'value', type: DataType.Number, renderer: Formatters.plusMinusFormat(1), // use the built-in summarizer to find minimum and maximum values summarize: Summarizers.minMaxSummarizer, // add highlight-max to max value and highlight-min to the min-value tdClassName: TdClassNames.minMaxClassName, }, { id: 'value-max-only', value: rowData => rowData.value, type: DataType.Number, renderer: Formatters.plusMinusFormat(1), // use the built-in summarizer to find minimum and maximum values summarize: Summarizers.minMaxSummarizer, // add highlight-max to max value tdClassName: TdClassNames.maxClassName, }, { id: 'rating', type: DataType.Number, renderer: Formatters.plusMinusFormat(2), summarize: Summarizers.minMaxSummarizer, // manually style the min and max values tdStyle: (cellData, summary, column, rowData) => { if (cellData === summary.min) { return { color: '#c00', fontWeight: 'bold' }; } else if (cellData === summary.max) { return { color: '#0a0', fontWeight: 'bold' }; } return undefined; }, }, { id: 'level', type: DataType.NumberOrdinal, summarize: Summarizers.frequencySummarizer, // color the most frequently occuring value tdStyle: (cellData, summary, column, rowData) => { if (cellData === summary.mostFrequent) { return { color: '#34c', fontWeight: 'bold' }; } return undefined; }, }, ]; class ExampleStyle extends React.Component { render() { return ( <TacoTable columns={columns} data={cellLinesData} sortable /> ); } } export default ExampleStyle;
src/library/Card/CardStatus.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import IconDangerSimple from '../Icon/IconDangerSimple'; import IconSuccessSimple from '../Icon/IconSuccessSimple'; import IconWarningSimple from '../Icon/IconWarningSimple'; import { CardStatusRoot as Root } from './styled'; import { cardStatusPropTypes } from './propTypes'; import type { CardStatusProps } from './types'; const statusIcons = { danger: <IconDangerSimple />, success: <IconSuccessSimple />, warning: <IconWarningSimple /> }; export default function CardStatus(props: CardStatusProps) { const { children, variant, ...restProps } = props; const rootProps = { variant, ...restProps }; const icon = statusIcons[variant]; return ( <Root {...rootProps}> {icon} {children} </Root> ); } CardStatus.displayName = 'CardStatus'; CardStatus.propTypes = cardStatusPropTypes;
src/Parser/Rogue/Subtlety/Modules/Talents/DarkShadow/DarkShadowSpecterOfBetrayal.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import ItemLink from 'common/ItemLink'; import ITEMS from 'common/ITEMS'; import { formatPercentage } from 'common/format'; import DarkShadow from './DarkShadow'; class DarkShadowSpecterOfBetrayal extends DarkShadow { suggestions(when) { const totalSpecterCastsInShadowDance = this.danceDamageTracker.getAbility(SPELLS.SUMMON_DREAD_REFLECTION.id).casts; const totalSpecterCast = this.damageTracker.getAbility(SPELLS.SUMMON_DREAD_REFLECTION.id).casts; const castsInDanceShare = totalSpecterCastsInShadowDance / totalSpecterCast; when(castsInDanceShare).isLessThan(0.90) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Use <ItemLink id={ITEMS.SPECTER_OF_BETRAYAL.id} /> during <SpellLink id={SPELLS.SHADOW_DANCE.id} /> when you are using <SpellLink id={SPELLS.DARK_SHADOW_TALENT.id} />. </Wrapper>) .icon(ITEMS.SPECTER_OF_BETRAYAL.icon) .actual(`You used Specter of Betrayal in Shadow Dance ${formatPercentage(actual)}% of the time`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(0.80); //Its around 1% dps loss when pressing it on cooldown, so never Major. }); } } export default DarkShadowSpecterOfBetrayal;
examples/src/components/Creatable.js
serkanozer/react-select
import React from 'react'; import createClass from 'create-react-class'; import PropTypes from 'prop-types'; import Select from 'react-select'; var CreatableDemo = createClass({ displayName: 'CreatableDemo', propTypes: { hint: PropTypes.string, label: PropTypes.string }, getInitialState () { return { multi: true, multiValue: [], options: [ { value: 'R', label: 'Red' }, { value: 'G', label: 'Green' }, { value: 'B', label: 'Blue' } ], value: undefined }; }, handleOnChange (value) { const { multi } = this.state; if (multi) { this.setState({ multiValue: value }); } else { this.setState({ value }); } }, render () { const { multi, multiValue, options, value } = this.state; return ( <div className="section"> <h3 className="section-heading">{this.props.label} <a href="https://github.com/JedWatson/react-select/tree/master/examples/src/components/Creatable.js">(Source)</a></h3> <Select.Creatable multi={multi} options={options} onChange={this.handleOnChange} value={multi ? multiValue : value} /> <div className="hint">{this.props.hint}</div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={multi} onChange={() => this.setState({ multi: true })} /> <span className="checkbox-label">Multiselect</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={!multi} onChange={() => this.setState({ multi: false })} /> <span className="checkbox-label">Single Value</span> </label> </div> </div> ); } }); module.exports = CreatableDemo;
src/components/theme/Heading1Ext/Heading1Ext.js
mutualmobile/Brazos
import React, { Component } from 'react'; export default platformCode = { render: function() { return ( <h1>Web Page View</h1> ); } }
src/App.js
OutcomeLife/layout
import React, { Component } from 'react'; import { Header, Body, Sidebar, Content, ButtonThick } from 'genny-components'; import { VerticleLayout} from './components'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as BaseEntity from "./actions/baseEntityActions"; import * as VertxActions from "./actions/vertxAction"; import * as SetupActions from './actions/setupActions'; import * as AuthActions from './actions/authActions'; import * as eventType from './utils/eventType'; import './style.css'; class App extends Component { constructor() { super(); this._account = this._account.bind(this); this._logout = this._logout.bind(this); } _account() { this.props.AuthActions.account(); } _logout() { this.props.AuthActions.logout(); } componentWillMount() { //console.log("started connection"); //this.props.VertxActions.receiveMessage(); } componentWillReceiveProps(props) { if ( props.setup.keycloak ) { props.VertxActions.receiveMessage( props.setup.keycloak ); } // props.VertxActions.sendInitialEvent("token"); } componentDidMount() { this.props.SetupActions.config(); this.props.SetupActions.init(this.props.setup.config); // this.props.VertxActions.sendInitialEvent("token"); } send_event(e,id, code, evtType) { this.props.VertxActions.sendEvent(id, code, evtType); } //this returns a data required for the layout receive_data_message() { const asks = Object.keys(this.props.vertx.data).length !== 0 ? this.props.vertx.data.items : []; return (<div> <VerticleLayout asks={asks} onChange={this.props.VertxActions.sendAnswer} /> </div>); } //this is for getting event from the server evt_message() { } //this returns a layout name receive_cmd_message() { let { cmd } = this.props.vertx; if(cmd !== null ) { if (cmd.cmd_type === 'CMD_LAYOUT') { return cmd.code; } else if (cmd.cmd_type === 'CMD_REDIRECT') { const redirectUrl = cmd.redirect_url; this.props.AuthActions.redirectUrl(redirectUrl); } else if (cmd.cmd_type === 'CMD_LOGOUT'){ this.props.AuthActions.logout(); } else { //erro handling display error react compon } } } // This will combine data and layout to render in the browser layout() { const { user, logo } = this.props.setup; const { baseEntities } = this.props.baseEntity; const dropdownListItem = [ { name: "account", onClick: this._account, icon: "settings" }, { name: "logout", onClick: this._logout, icon: "exit_to_app" } ]; const baseEntity = baseEntities.map((baseEntity) => { const { id, code } = baseEntity; return ( <a key={id} style={{ cursor: "pointer" }} onClick={() => this.props.VertxActions.sendEvent(id, code)} > <i className="material-icons arrow" key={id}>keyboard_arrow_right</i> {baseEntity.name} </a> ); }); const layout = this.receive_cmd_message(); let theme = "default"; let themeName = null; switch(layout) { case "Layout1": theme = "default"; themeName = "Layout 1" break; case "Layout2": theme = "cyan"; themeName = "Layout 2" break; case "Layout3": theme = "blue"; themeName = "Layout 3" break; default: theme = "cyan"; themeName = "Layout 2" break; } let contentStyle = { backgroundColor: "white", } return ( <div className={theme}> <Header logo={logo} user={user} dropdownListItem={dropdownListItem} /> <Body > <Sidebar> {themeName} {baseEntity} </Sidebar> <Content style={contentStyle}> <ButtonThick label="Layout 1" code="Layout1" icon="android" onClick={(e) => this.send_event(e, 1, "Layout1", eventType.BUTTON_CLICK)} /> <ButtonThick label="Layout 2" code="Layout2" icon="android" onClick={(e) => this.send_event(e, 2, "Layout2", eventType.BUTTON_CLICK)} /> <ButtonThick label="Layout 3" code="Layout3" icon="android" onClick={(e) => this.send_event(e, 3, "Layout3", eventType.BUTTON_CLICK)} /> <ButtonThick label="Random Button" code="Random" icon="android" onClick={(e) => this.send_event(e, 4, "Random ", eventType.BUTTON_CLICK)} /> <ButtonThick label="Redirect Button" code="Redirect" icon="android" onClick={(e) => this.send_event(e, 5 , "Redirect ", eventType.BUTTON_CLICK)} /> {this.receive_cmd_message()} {this.receive_data_message()} </Content> </Body> </div>); } render() { return ( <div> {this.layout()} </div> ); } } const mapStateToProps = (store, props) => { return { baseEntity: store.baseEntity, vertx: store.vertx, setup: store.setup, auth: store.auth }; } const mapDispatchToProps = (dispatch) => { return { BaseEntity: bindActionCreators(BaseEntity, dispatch), VertxActions: bindActionCreators(VertxActions, dispatch), SetupActions: bindActionCreators(SetupActions, dispatch), AuthActions: bindActionCreators(AuthActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(App);
src/components/TeamPage/index.js
KidsFirstProject/KidsFirstProject.github.io
import React from 'react'; import { Container, Col, Row, Image, CardColumns, Card } from 'react-bootstrap'; import MemberCard from './MemberCard'; import styles from './TeamPage.module.css'; import teamImage from '../../assets/images/chapters/portland-or/hfh06.jpg'; import directors from '../../data/team/directors'; import volunteerLeaders from '../../data/team/volunteer-leaders'; import advisors from '../../data/team/advisors'; import sponsors from '../../data/team/sponsors'; import partners from '../../data/team/partners'; const TeamPage = () => ( <Container className="page-container"> <h1>Our Team</h1> <hr /> <Row> <Col lg> <Image fluid src={teamImage} rounded /> </Col> <Col className="d-flex flex-column justify-content-center"> <h2>Who we are</h2> <p> We’re a group of individuals passionate about social justice and youth empowerment who have come together to bridge the gap between a child experiencing homelessness and the resources needed to help them reach their full potential. </p> </Col> </Row> <Row className={styles.teamSection}> <Col> <h2>Board of Directors</h2> </Col> </Row> <hr /> <Row> {directors.map(director => ( <MemberCard member={director} key={`member-card-${director.name}`} /> ))} </Row> <Row className={styles.teamSection}> <Col> <h2>Volunteer Leaders</h2> </Col> </Row> <hr /> <Row> {volunteerLeaders.map(leader => ( <MemberCard member={leader} key={`member-card-${leader.name}`} /> ))} </Row> <Row className={styles.teamSection}> <Col> <h2>Advisory Board</h2> </Col> </Row> <hr /> <Row> {advisors.map(advisor => ( <MemberCard member={advisor} key={`member-card-${advisor.name}`} /> ))} </Row> <Row className={styles.teamSection}> <Col> <h2>Our Sponsors</h2> </Col> </Row> <hr /> <Row> <CardColumns> {sponsors.map((imageUrl, index) => ( <Card border="secondary" key={`sponsor-card-${index}`}> <Card.Img className="p-3" src={imageUrl} /> </Card> ))} </CardColumns> </Row> <Row className={styles.teamSection}> <Col> <h2>Our Partners</h2> </Col> </Row> <hr /> <Row> <CardColumns> {partners.map(({ imageUrl, ctaUrl }, index) => ( <Card border="secondary" key={`partner-card-${index}`}> <a href={ctaUrl}> <Card.Img className="p-3" src={imageUrl} /> </a> </Card> ))} </CardColumns> </Row> </Container> ); export default TeamPage;
app/javascript/mastodon/features/mutes/index.js
pointlessone/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchMutes, expandMutes } from '../../actions/mutes'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.mutes', defaultMessage: 'Muted users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'mutes', 'items']), }); export default @connect(mapStateToProps) @injectIntl class Mutes extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchMutes()); } handleLoadMore = debounce(() => { this.props.dispatch(expandMutes()); }, 300, { leading: true }); render () { const { intl, shouldUpdateScroll, accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />; return ( <Column icon='volume-off' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='mutes' onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} > {accountIds.map(id => <AccountContainer key={id} id={id} /> )} </ScrollableList> </Column> ); } }
src/scenes/connector-03.js
jdpigeon/neurodoro
import React, { Component } from 'react'; import { StyleSheet, Text, View, } from 'react-native'; import{ Actions, }from 'react-native-router-flux'; import { connect } from 'react-redux'; import { MediaQueryStyleSheet } from 'react-native-responsive'; import * as colors from '../styles/colors'; // Components. For JS UI elements import Button from '../components/Button'; export default class ConnectorThree extends Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <View style={styles.titleContainer}> <Text style={styles.title}>Step 3</Text> <Text style={styles.body}>Make sure the Muse is properly fit to your head</Text> </View> <View style={styles.spacerContainer}/> <View style={styles.buttonContainer}> <Button onPress={Actions.Timer}>Okay</Button> </View> </View> ); } } const styles = MediaQueryStyleSheet.create( { // Base styles body: { fontFamily: 'OpenSans-Regular', fontSize: 25, margin: 20, color: colors.grey, textAlign: 'center' }, title: { textAlign: 'center', margin: 15, lineHeight: 50, color: colors.tomato, fontFamily: 'YanoneKaffeesatz-Regular', fontSize: 50, }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', margin: 50, }, titleContainer: { flex: 2, justifyContent: 'center', }, spacerContainer: { justifyContent: 'center', flex: 1, }, buttonContainer: { justifyContent: 'center', flex: 1, }, logo: { width: 200, height: 200, }, }, // Responsive styles { "@media (min-device-height: 700)": { body: { fontSize: 30, marginLeft: 50, marginRight: 50 } } });
react-native/AwesomeProject/components/StyledText.js
glandre/prototypes
import React from 'react'; import { Text } from 'react-native'; export class MonoText extends React.Component { render() { return <Text {...this.props} style={[this.props.style, { fontFamily: 'space-mono' }]} />; } }
app/containers/LocaleToggle/index.js
akash6190/apollo-starter
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { makeSelectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
src/components/question/Question.js
Oblium/react-math
import React from 'react'; import './question.scss'; class Question extends React.Component { render() { return !this.props.gameEnded ? ( <div className="questionContainer"> {this.props.question} </div> ) : ( <div className="timer">Time is up!</div> ); } } export default Question;
project-templates/reactfiber/externals/react-fiber/fixtures/dom/src/components/fixtures/input-change-events/InputPlaceholderFixture.js
itsa-server/itsa-cli
import React from 'react'; import Fixture from '../../Fixture'; class InputPlaceholderFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { placeholder: 'A placeholder', changeCount: 0, }; } handleChange = () => { this.setState(({ changeCount }) => { return { changeCount: changeCount + 1 } }) } handleGeneratePlaceholder = () => { this.setState({ placeholder: `A placeholder: ${Math.random() * 100}` }) } handleReset = () => { this.setState({ changeCount: 0, }) } render() { const { placeholder, changeCount } = this.state; const color = changeCount === 0 ? 'green' : 'red'; return ( <Fixture> <input type='text' placeholder={placeholder} onChange={this.handleChange} /> {' '} <button onClick={this.handleGeneratePlaceholder}> Change placeholder </button> <p style={{ color }}> <code>onChange</code>{' calls: '}<strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset count</button> </Fixture> ) } } export default InputPlaceholderFixture;
jenkins-design-language/src/js/components/material-ui/svg-icons/image/photo-size-select-large.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImagePhotoSizeSelectLarge = (props) => ( <SvgIcon {...props}> <path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1zm2 8l2.5-3.21 1.79 2.15 2.5-3.22L13 19H3z"/> </SvgIcon> ); ImagePhotoSizeSelectLarge.displayName = 'ImagePhotoSizeSelectLarge'; ImagePhotoSizeSelectLarge.muiName = 'SvgIcon'; export default ImagePhotoSizeSelectLarge;
src/svg-icons/navigation/chevron-left.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationChevronLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); NavigationChevronLeft = pure(NavigationChevronLeft); NavigationChevronLeft.displayName = 'NavigationChevronLeft'; NavigationChevronLeft.muiName = 'SvgIcon'; export default NavigationChevronLeft;
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbMassiveSizeExample.js
jcarbo/stardust
import React from 'react' import { Breadcrumb } from 'stardust' const BreadcrumbMassiveSizeExample = () => ( <Breadcrumb size='massive'> <Breadcrumb.Section link>Home</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section link>Registration</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section active>Personal Information</Breadcrumb.Section> </Breadcrumb> ) export default BreadcrumbMassiveSizeExample
src/main/viz/CoverageTrack.js
snaheth/pileup.js
/** * Coverage visualization of Alignment sources. * @flow */ 'use strict'; import type Interval from '../Interval'; import type {TwoBitSource} from '../sources/TwoBitDataSource'; import type {DataCanvasRenderingContext2D} from 'data-canvas'; import type {Scale} from './d3utils'; import type {CoverageDataSource} from '../sources/CoverageDataSource'; import type {VizProps} from '../VisualizationWrapper'; import RemoteRequest from '../RemoteRequest'; import type {PositionCount} from '../sources/CoverageDataSource'; import React from 'react'; import scale from '../scale'; import shallowEquals from 'shallow-equals'; import d3utils from './d3utils'; import _ from 'underscore'; import dataCanvas from 'data-canvas'; import canvasUtils from './canvas-utils'; import style from '../style'; import ContigInterval from '../ContigInterval'; import TiledCanvas from './TiledCanvas'; import type {State, NetworkStatus} from './pileuputils'; class CoverageTiledCanvas extends TiledCanvas { height: number; options: Object; source: CoverageDataSource; constructor(source: CoverageDataSource, height: number, options: Object) { super(); this.source = source; this.height = Math.max(1, height); this.options = options; } heightForRef(ref: string): number { return this.height; } update(height: number, options: Object) { // workaround for an issue in PhantomJS where height always comes out to zero. this.height = Math.max(1, height); this.options = options; } yScaleForRef(range: ContigInterval<string>, resolution: ?number): (y: number) => number { var maxCoverage = this.source.maxCoverage(range, resolution); return scale.linear() .domain([maxCoverage, 0]) .range([style.COVERAGE_PADDING, this.height - style.COVERAGE_PADDING]) .nice(); } // This is called by TiledCanvas over all tiles in a range render(ctx: DataCanvasRenderingContext2D, xScale: (x: number)=>number, range: ContigInterval<string>, originalRange: ?ContigInterval<string>, resolution: ?number) { var relaxedRange = new ContigInterval( range.contig, Math.max(1, range.start() - 1), range.stop() + 1); var bins = this.source.getCoverageInRange(relaxedRange, resolution); // if original range is not set, use tiled range which is a subset of originalRange if (!originalRange) { originalRange = range; } var yScale = this.yScaleForRef(originalRange, resolution); renderBars(ctx, xScale, yScale, relaxedRange, bins, resolution, this.options); } } // Draw coverage bins function renderBars(ctx: DataCanvasRenderingContext2D, xScale: (num: number) => number, yScale: (num: number) => number, range: ContigInterval<string>, bins: PositionCount[], resolution: ?number, options: Object) { if (_.isEmpty(bins)) return; // make sure bins are sorted by position bins = _.sortBy(bins, x => x.start); var barWidth = xScale(1) - xScale(0); var showPadding = (barWidth > style.COVERAGE_MIN_BAR_WIDTH_FOR_GAP); var padding = showPadding ? 1 : 0; var binPos = function(ps: PositionCount) { // Round to integer coordinates for crisp lines, without aliasing. var barX1 = Math.round(xScale(ps.start)), barX2 = Math.max(barX1 + 2, Math.round(xScale(ps.end)) - padding), // make sure bar is >= 1px barY = Math.round(yScale(ps.count)); return {barX1, barX2, barY}; }; var vBasePosY = yScale(0); // the very bottom of the canvas // go to the first bin in dataset (specified by the smallest start position) ctx.fillStyle = style.COVERAGE_BIN_COLOR; ctx.beginPath(); bins.forEach(bin => { ctx.pushObject(bin); let {barX1, barX2, barY} = binPos(bin); ctx.moveTo(barX1, vBasePosY); // start at bottom left of bar ctx.lineTo(barX1, barY); // left edge of bar ctx.lineTo(barX2, barY); // top of bar ctx.lineTo(barX2, vBasePosY); // right edge of the right bar. ctx.popObject(); }); ctx.closePath(); ctx.fill(); } class CoverageTrack extends React.Component { props: VizProps & { source: CoverageDataSource }; state: State; static defaultOptions: Object; tiles: CoverageTiledCanvas; constructor(props: VizProps) { super(props); this.state = { networkStatus: null }; } render(): any { // These styles allow vertical scrolling to see the full pileup. // Adding a vertical scrollbar shrinks the visible area, but we have to act // as though it doesn't, since adjusting the scale would put it out of sync // with other tracks. var containerStyles = { 'height': '100%' }; var statusEl = null, networkStatus = this.state.networkStatus; if (networkStatus) { statusEl = ( <div ref='status' className='network-status'> <div className='network-status-message'> Loading coverage… </div> </div> ); } var rangeLength = this.props.range.stop - this.props.range.start; // If range is too large, do not render 'canvas' if (rangeLength > RemoteRequest.MONSTER_REQUEST) { return ( <div> <div className='center'> Zoom in to see coverage </div> <canvas onClick={this.handleClick.bind(this)} /> </div> ); } else { return ( <div> {statusEl} <div ref='container' style={containerStyles}> <canvas ref='canvas' onClick={this.handleClick.bind(this)} /> </div> </div> ); } } getScale(): Scale { return d3utils.getTrackScale(this.props.range, this.props.width); } componentDidMount() { this.tiles = new CoverageTiledCanvas(this.props.source, this.props.height, this.props.options); this.props.source.on('newdata', range => { var oldMax = this.props.source.maxCoverage(range); this.props.source.getCoverageInRange(range); var newMax = this.props.source.maxCoverage(range); if (oldMax != newMax) { this.tiles.invalidateAll(); } else { this.tiles.invalidateRange(range); } this.visualizeCoverage(); }); this.props.source.on('newdata', range => { this.tiles.invalidateRange(range); this.visualizeCoverage(); }); this.props.source.on('networkprogress', e => { this.setState({networkStatus: e}); }); this.props.source.on('networkdone', e => { this.setState({networkStatus: null}); }); } componentDidUpdate(prevProps: any, prevState: any) { if (!shallowEquals(this.props, prevProps) || !shallowEquals(this.state, prevState)) { if (this.props.height != prevProps.height || this.props.options != prevProps.options) { this.tiles.update(this.props.height, this.props.options); this.tiles.invalidateAll(); } this.visualizeCoverage(); } } getContext(): CanvasRenderingContext2D { var canvas = (this.refs.canvas : HTMLCanvasElement); // The typecast through `any` is because getContext could return a WebGL context. var ctx = ((canvas.getContext('2d') : any) : CanvasRenderingContext2D); return ctx; } // Draw three ticks on the left to set the scale for the user renderTicks(ctx: DataCanvasRenderingContext2D, yScale: (num: number)=>number) { var axisMax = yScale.domain()[0]; [0, Math.round(axisMax / 2), axisMax].forEach(tick => { // Draw a line indicating the tick ctx.pushObject({value: tick, type: 'tick'}); var tickPosY = Math.round(yScale(tick)); ctx.strokeStyle = style.COVERAGE_FONT_COLOR; canvasUtils.drawLine(ctx, 0, tickPosY, style.COVERAGE_TICK_LENGTH, tickPosY); ctx.popObject(); if (tick > 0) { var tickLabel = tick + 'X'; ctx.pushObject({value: tick, label: tickLabel, type: 'label'}); // Now print the coverage information ctx.font = style.COVERAGE_FONT_STYLE; var textPosX = style.COVERAGE_TICK_LENGTH + style.COVERAGE_TEXT_PADDING, textPosY = tickPosY + style.COVERAGE_TEXT_Y_OFFSET; // The stroke creates a border around the text to make it legible over the bars. ctx.strokeStyle = 'white'; ctx.lineWidth = 2; ctx.strokeText(tickLabel, textPosX, textPosY); ctx.lineWidth = 1; ctx.fillStyle = style.COVERAGE_FONT_COLOR; ctx.fillText(tickLabel, textPosX, textPosY); ctx.popObject(); } }); } visualizeCoverage() { var canvas = (this.refs.canvas : HTMLCanvasElement), width = this.props.width, height = this.props.height, range = ContigInterval.fromGenomeRange(this.props.range); // Hold off until height & width are known. if (width === 0 || typeof canvas == 'undefined') return; d3utils.sizeCanvas(canvas, width, height); var ctx = dataCanvas.getDataContext(this.getContext()); ctx.save(); ctx.reset(); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); var yScale = this.tiles.yScaleForRef(range); this.tiles.renderToScreen(ctx, range, this.getScale()); this.renderTicks(ctx, yScale); ctx.restore(); } handleClick(reactEvent: any) { var ev = reactEvent.nativeEvent, x = ev.offsetX; // It's simple to figure out which position was clicked using the x-scale. // No need to render the scene to determine what was clicked. var range = ContigInterval.fromGenomeRange(this.props.range), xScale = this.getScale(), bins = this.props.source.getCoverageInRange(range), pos = Math.floor(xScale.invert(x)) - 1, bin = bins[pos]; var alert = window.alert || console.log; if (bin) { // Construct a JSON object to show the user. var messageObject = _.extend( { 'position': range.contig + ':' + (1 + pos), 'read depth': bin.count }); alert(JSON.stringify(messageObject, null, ' ')); } } } CoverageTrack.displayName = 'coverage'; module.exports = CoverageTrack;
app/javascript/mastodon/components/missing_indicator.js
sylph-sin-tyaku/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import illustration from 'mastodon/../images/elephant_ui_disappointed.svg'; import classNames from 'classnames'; const MissingIndicator = ({ fullPage }) => ( <div className={classNames('regeneration-indicator', { 'regeneration-indicator--without-header': fullPage })}> <div className='regeneration-indicator__figure'> <img src={illustration} alt='' /> </div> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> ); MissingIndicator.propTypes = { fullPage: PropTypes.bool, }; export default MissingIndicator;
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/es/ModalHeader.js
GoogleCloudPlatform/prometheus-engine
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; var _excluded = ["className", "cssModule", "children", "toggle", "tag", "wrapTag", "closeAriaLabel", "charCode", "close"]; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; var propTypes = { tag: tagPropType, wrapTag: tagPropType, toggle: PropTypes.func, className: PropTypes.string, cssModule: PropTypes.object, children: PropTypes.node, closeAriaLabel: PropTypes.string, charCode: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), close: PropTypes.object }; var defaultProps = { tag: 'h5', wrapTag: 'div', closeAriaLabel: 'Close', charCode: 215 }; var ModalHeader = function ModalHeader(props) { var closeButton; var className = props.className, cssModule = props.cssModule, children = props.children, toggle = props.toggle, Tag = props.tag, WrapTag = props.wrapTag, closeAriaLabel = props.closeAriaLabel, charCode = props.charCode, close = props.close, attributes = _objectWithoutPropertiesLoose(props, _excluded); var classes = mapToCssModules(classNames(className, 'modal-header'), cssModule); if (!close && toggle) { var closeIcon = typeof charCode === 'number' ? String.fromCharCode(charCode) : charCode; closeButton = /*#__PURE__*/React.createElement("button", { type: "button", onClick: toggle, className: mapToCssModules('close', cssModule), "aria-label": closeAriaLabel }, /*#__PURE__*/React.createElement("span", { "aria-hidden": "true" }, closeIcon)); } return /*#__PURE__*/React.createElement(WrapTag, _extends({}, attributes, { className: classes }), /*#__PURE__*/React.createElement(Tag, { className: mapToCssModules('modal-title', cssModule) }, children), close || closeButton); }; ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; export default ModalHeader;
docs/lib/Components/index.js
video-react/video-react
import React from 'react'; import { Link } from 'react-router'; import { Container, Row, Col, Nav, NavItem, NavLink } from 'reactstrap'; const ComponentLink = props => ( <NavItem> <NavLink tag={Link} to={props.item.to} activeClassName="active"> {props.item.name} </NavLink> </NavItem> ); class Components extends React.Component { constructor(props) { super(props); this.state = { navItems: [ { name: 'Player', to: '/components/player/' }, { name: 'Shortcut', to: '/components/shortcut/' }, { name: 'BigPlayButton', to: '/components/big-play-button/' }, { name: 'PosterImage', to: '/components/poster-image/' }, { name: 'LoadingSpinner', to: '/components/loading-spinner/' }, { name: 'ControlBar', to: '/components/control-bar/' }, { name: 'PlayToggle', to: '/components/play-toggle/' }, { name: 'ReplayControl', to: '/components/replay-control/' }, { name: 'ForwardControl', to: '/components/forward-control/' }, { name: 'VolumeMenuButton', to: '/components/volume-menu-button/' }, { name: 'PlaybackRateMenuButton', to: '/components/playback-rate-menu-button/' }, { name: 'ClosedCaptionButton', to: '/components/captioned-video' } ] }; } render() { return ( <Container className="content"> <Row> <Col md={{ size: 3 }}> <div className="docs-sidebar mb-3"> <h5>Components</h5> <Nav className="flex-column"> {this.state.navItems.map(item => ( <ComponentLink key={item.name} item={item} /> ))} </Nav> </div> </Col> <Col md={{ size: 9 }}>{this.props.children}</Col> </Row> </Container> ); } } export default Components;
src/svg-icons/alert/warning.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertWarning = (props) => ( <SvgIcon {...props}> <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/> </SvgIcon> ); AlertWarning = pure(AlertWarning); AlertWarning.displayName = 'AlertWarning'; AlertWarning.muiName = 'SvgIcon'; export default AlertWarning;
app/containers/CatKitDemo/SlabView.js
mhoffman/CatAppBrowser
import React from 'react'; import PropTypes from 'prop-types'; import Grid from 'material-ui/Grid'; import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions'; export class SlabView extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> { this.props.bulkCif === '' ? null : <div> <Grid container direction="row" justify="center"> <Grid item> <Grid container justify="flex-start" direction="column"> {this.props.images.map((image, i) => ( <Grid item key={`item_${i}`}> <GeometryCanvasWithOptions cifdata={image} uniqueId={`slab_preview_${i}`} key={`slab_preview_${i}`} id={`slab_preview_${i}`} x={2} y={2} z={1} /> </Grid> ))} </Grid> </Grid> </Grid> </div> } </div> ); } } SlabView.propTypes = { bulkCif: PropTypes.string.isRequired, images: PropTypes.array, };
src/svg-icons/editor/format-strikethrough.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatStrikethrough = (props) => ( <SvgIcon {...props}> <path d="M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z"/> </SvgIcon> ); EditorFormatStrikethrough = pure(EditorFormatStrikethrough); EditorFormatStrikethrough.displayName = 'EditorFormatStrikethrough'; export default EditorFormatStrikethrough;
node_modules/react-bootstrap/es/Breadcrumb.js
ProjectSunday/rooibus
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import BreadcrumbItem from './BreadcrumbItem'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var Breadcrumb = function (_React$Component) { _inherits(Breadcrumb, _React$Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Breadcrumb.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('ol', _extends({}, elementProps, { role: 'navigation', 'aria-label': 'breadcrumbs', className: classNames(className, classes) })); }; return Breadcrumb; }(React.Component); Breadcrumb.Item = BreadcrumbItem; export default bsClass('breadcrumb', Breadcrumb);
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
Jeremy-Meng/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactsSectionItem extends React.Component { static propTypes = { contact: React.PropTypes.object }; constructor(props) { super(props); } openNewPrivateCoversation = () => { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); } render() { const contact = this.props.contact; return ( <li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> </li> ); } } export default ContactsSectionItem;
src/app/app.js
nazar/soapee-ui
/*global FB*/ //load CSS assets first require( '../assets/main.css' ); import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import Router from 'react-router'; import ga from 'react-ga'; import config from 'config'; import routes from './routes'; /////////////////// /// INITIALISE let analytics = _.get( config, 'analytics.google' ); if ( analytics ) { ga.initialize( analytics ); } FB.init( { appId: config.auth.facebookClientId, cookie: true, version: 'v2.10', xfbml: true } ); Reflux.setPromiseFactory( require( 'when' ).promise ); Router.run( routes, Router.HistoryLocation, function ( Handler, state ) { if ( analytics ) { ga.pageview( state.pathname ); } React.render( <Handler/>, document.getElementById( 'application' ) ); } );
app/javascript/mastodon/features/ui/components/column.js
vahnj/mastodon
import React from 'react'; import ColumnHeader from './column_header'; import PropTypes from 'prop-types'; import { debounce } from 'lodash'; import { scrollTop } from '../../../scroll'; import { isMobile } from '../../../is_mobile'; export default class Column extends React.PureComponent { static propTypes = { heading: PropTypes.string, icon: PropTypes.string, children: PropTypes.node, active: PropTypes.bool, hideHeadingOnMobile: PropTypes.bool, }; handleHeaderClick = () => { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } scrollTop () { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleScroll = debounce(() => { if (typeof this._interruptScrollAnimation !== 'undefined') { this._interruptScrollAnimation(); } }, 200) setRef = (c) => { this.node = c; } render () { const { heading, icon, children, active, hideHeadingOnMobile } = this.props; const showHeading = heading && (!hideHeadingOnMobile || (hideHeadingOnMobile && !isMobile(window.innerWidth))); const columnHeaderId = showHeading && heading.replace(/ /g, '-'); const header = showHeading && ( <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} columnHeaderId={columnHeaderId} /> ); return ( <div ref={this.setRef} role='region' aria-labelledby={columnHeaderId} className='column' onScroll={this.handleScroll} > {header} {children} </div> ); } }