path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
newclient/scripts/components/config/general/auto-approve-disclosure/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 ConfigActions from '../../../../actions/config-actions'; export default function AutoApproveDisclosure(props) { return ( <div className={styles.container}> <input id='autoApproveDisclosure' type="checkbox" className={styles.checkbox} checked={props.checked === undefined ? false : props.checked} onChange={ConfigActions.toggleAutoApprove} /> <label htmlFor='autoApproveDisclosure' className={styles.label} > Automatically approve annual disclosures that do not have any Financial Entities </label> </div> ); }
packages/showcase/axes/dynamic-crosshair.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import { XYPlot, XAxis, YAxis, VerticalGridLines, HorizontalGridLines, LineSeries, Crosshair } from 'react-vis'; const DATA = [ [ {x: 1, y: 10}, {x: 2, y: 7}, {x: 3, y: 15} ], [ {x: 1, y: 20}, {x: 2, y: 5}, {x: 3, y: 15} ] ]; export default class DynamicCrosshair extends React.Component { constructor(props) { super(props); this.state = { crosshairValues: [] }; } /** * Event handler for onMouseLeave. * @private */ _onMouseLeave = () => { this.setState({crosshairValues: []}); }; /** * Event handler for onNearestX. * @param {Object} value Selected value. * @param {index} index Index of the value in the data array. * @private */ _onNearestX = (value, {index}) => { this.setState({crosshairValues: DATA.map(d => d[index])}); }; render() { return ( <XYPlot onMouseLeave={this._onMouseLeave} width={300} height={300}> <VerticalGridLines /> <HorizontalGridLines /> <XAxis /> <YAxis /> <LineSeries onNearestX={this._onNearestX} data={DATA[0]} /> <LineSeries data={DATA[1]} /> <Crosshair values={this.state.crosshairValues} className={'test-class-name'} /> </XYPlot> ); } }
src/articles/2018-01-31-1st-Anniversary/TimelineItemImage.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; const TimelineItemImage = ({ source, description, wide }) => ( <figure style={wide ? { maxWidth: 800 } : undefined}> <a href={source} target="_blank" rel="noopener noreferrer"><img src={source} alt={description} /></a> <figcaption> {description} </figcaption> </figure> ); TimelineItemImage.propTypes = { source: PropTypes.string.isRequired, description: PropTypes.node.isRequired, wide: PropTypes.bool, }; export default TimelineItemImage;
src/client/react/user/stages/Registration/RegisterForm/Form2.js
bwyap/ptc-amazing-g-race
import React from 'react'; import autobind from 'core-decorators/es/autobind'; import { withApollo, gql } from 'react-apollo'; import { Button, Intent } from '@blueprintjs/core'; import FormInput from '../../../../../../../lib/react/components/forms/FormInput'; import Validator from '../../../../../../../lib/react/components/forms/validation/Validator'; import NotEmpty from '../../../../../../../lib/react/components/forms/validation/functions/NotEmpty'; import RegexCheck from '../../../../../../../lib/react/components/forms/validation/functions/RegexCheck'; import { errorProps, pendingProps, successProps } from './lib'; const QueryEmailUnique = gql`query CheckUnique($parameter:UserParameter!,$value:String!){checkUnique(parameter:$parameter,value:$value){ok}}`; @withApollo @autobind class Form2 extends React.Component { state = { email: this.props.state.email, mobileNumber: this.props.state.mobileNumber, nextDisabled: true } componentDidMount() { this._validateFormNext(); } onChange({ target }) { this.props.onChange(target.id, target.value); this.setState({ [target.id]: target.value }, () => { // Validate form for next button this._validateFormNext(); }); } async validateEmail(value) { if (NotEmpty(value)) { const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (RegexCheck(value, regex)) { // Check email with server return this.props.client.query({ query: QueryEmailUnique, variables: { parameter: 'email', value: value } }) .then((result) => { if (result.data) { if (result.data.checkUnique.ok) { return { ok: true, helperText: 'You can use this email.'}; } else { return { ok: false, helperText: 'This email is already taken.' }; } } else { return { ok: false, helperText: 'Could not verify the email with the server.' }; } }); } else { return { ok: false, helperText: 'Invalid email.'}; } } else { return { ok: false, helperText: 'Email is required.' }; } } validateMobile(value) { if (NotEmpty(value)) { const regex = /^(\+\d{1,3}[- ]?)?\d{10}$/; if (RegexCheck(value, regex)) { return { ok: true }; } else { return { ok: false, helperText: 'Invalid mobile number.' }; } } else { return { ok: false, helperText: 'Moblie number is required.' }; } } async _validateFormNext() { if (await this._validateForm()) { if (this.state.nextDisabled) this.setState({nextDisabled: false}); } else { if (!this.state.nextDisabled) this.setState({nextDisabled: true}); } } async _validateForm() { const validateEmail = await this.validateEmail(this.state.email); const validateMobile = this.validateMobile(this.state.mobileNumber); if (validateEmail.ok && validateMobile.ok) return true; else return false; } render() { return ( <div> <div className='pt-callout pt-intent-warning' style={{marginBottom: '0.3rem'}}> <h5>Step 2 of 4</h5> Your email will be used to create an account. Your mobile will be saved just in case we need to contact you, especially on the day of the event. </div> <Validator validationFunction={this.validateEmail} errorProps={errorProps()} pendingProps={pendingProps()} showPending successProps={successProps()} showSuccess> <FormInput id='email' large value={this.state.email} onChange={this.onChange} label='Email'/> </Validator> <Validator validationFunction={this.validateMobile} errorProps={errorProps()}> <FormInput id='mobileNumber' large value={this.state.mobileNumber} onChange={this.onChange} label='Mobile'/> </Validator> <Button onClick={this.props.next} className='pt-large' text='Next >' disabled={this.state.nextDisabled} intent={Intent.PRIMARY} style={{float:'right'}}/> <Button onClick={this.props.back} className='pt-large pt-minimal' text='< Back' intent={Intent.PRIMARY} style={{float:'left'}}/> </div> ); } } export default Form2;
src/svg-icons/hardware/tv.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareTv = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/> </SvgIcon> ); HardwareTv = pure(HardwareTv); HardwareTv.displayName = 'HardwareTv'; HardwareTv.muiName = 'SvgIcon'; export default HardwareTv;
src/server/router.js
wmkcc/uiams-r0
import React from 'react'; import Router from 'react-routing/lib/Router'; import HtmlContext from './HtmlContext'; // import router from 'koa-router'; import HomePage from '../layout/HomePage'; import ContactPage from '../layout/ContactPage'; import NotFoundPage from '../layout/NotFoundPage'; import ErrorPage from '../layout/ErrorPage'; function router(rules) { return function *(next, rules){ let firstPathName = this.path.split('/')[1]; if (firstPathName == '') { this._firstarg = 'index'; } else{ this._firstarg = firstPathName.toLocaleLowerCase(); } yield next; } } export default router;
app/javascript/mastodon/features/ui/components/column.js
hyuki0000/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> ); } }
ide/static/js/LayerComment.js
Cloud-CV/IDE
import React from 'react'; class LayerComment extends React.Component { constructor(props) { super(props); } render() { <div className="url-import-modal" style={{ paddingTop:'10px'}}> Comment Modal </div> } }
src/utils/childUtils.js
barakmitz/material-ui
import React from 'react'; import createFragment from 'react-addons-create-fragment'; export function createChildFragment(fragments) { const newFragments = {}; let validChildrenCount = 0; let firstKey; // Only create non-empty key fragments for (const key in fragments) { const currentChild = fragments[key]; if (currentChild) { if (validChildrenCount === 0) firstKey = key; newFragments[key] = currentChild; validChildrenCount++; } } if (validChildrenCount === 0) return undefined; if (validChildrenCount === 1) return newFragments[firstKey]; return createFragment(newFragments); } export function extendChildren(children, extendedProps, extendedChildren) { return React.isValidElement(children) ? React.Children.map(children, (child) => { const newProps = typeof (extendedProps) === 'function' ? extendedProps(child) : extendedProps; const newChildren = typeof (extendedChildren) === 'function' ? extendedChildren(child) : extendedChildren ? extendedChildren : child.props.children; return React.cloneElement(child, newProps, newChildren); }) : children; }
client/index.js
Exceltior/freecodecamp
import Rx from 'rx'; import React from 'react'; import Fetchr from 'fetchr'; import debugFactory from 'debug'; import { Router } from 'react-router'; import { history } from 'react-router/lib/BrowserHistory'; import { hydrate } from 'thundercats'; import { Render } from 'thundercats-react'; import { app$ } from '../common/app'; const debug = debugFactory('fcc:client'); const DOMContianer = document.getElementById('fcc'); const catState = window.__fcc__.data || {}; const services = new Fetchr({ xhrPath: '/services' }); Rx.longStackSupport = !!debug.enabled; // returns an observable app$(history) .flatMap( ({ AppCat }) => { const appCat = AppCat(null, services); return hydrate(appCat, catState) .map(() => appCat); }, ({ initialState }, appCat) => ({ initialState, appCat }) ) .flatMap(({ initialState, appCat }) => { return Render( appCat, React.createElement(Router, initialState), DOMContianer ); }) .subscribe( () => { debug('react rendered'); }, err => { debug('an error has occured', err.stack); }, () => { debug('react closed subscription'); } );
src/containers/ResetPasswdContainer.js
wind85/waterandboards
import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import ResetPasswd from '../components/ResetPasswd.js' import * as Actions from '../actions' const ResetPasswdContainer = ({ actions }) => { const handleReset = (e) => { // do stuff } return( <ResetPasswd hReset={handleReset} /> ) } const mapStateToProps = (state, props) => { return { feed: state.FeedRdx, } } /** * Map the actions to props. */ const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(Actions, dispatch) }) /** * Connect the component to * the Redux store. */ export default connect(mapStateToProps, mapDispatchToProps)(ResetPasswdContainer)
src/svg-icons/image/filter-center-focus.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterCenterFocus = (props) => ( <SvgIcon {...props}> <path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ImageFilterCenterFocus = pure(ImageFilterCenterFocus); ImageFilterCenterFocus.displayName = 'ImageFilterCenterFocus'; ImageFilterCenterFocus.muiName = 'SvgIcon'; export default ImageFilterCenterFocus;
components/pagination.js
volodalexey/spachat
import React from 'react' import extend_core from '../js/extend_core.js' import switcher_core from '../js/switcher_core.js' import chats_bus from '../js/chats_bus.js' import users_bus from '../js/users_bus.js' import messages from '../js/messages.js' import dom_core from '../js/dom_core.js' import Location_Wrapper from './location_wrapper' const Pagination = React.createClass({ MODE: { "PAGINATION": 'PAGINATION', "GO_TO": 'GO_TO' }, getDefaultProps() { return { mainContainer: { "element": "div", "config":{ "class": "flex ", } }, configs: [ { "element": "button", "icon": "back_arrow", "text": "", "class": "", "data": { "role": "back", "action": "switchPage", "key_disable": "disableBack" }, "name": "" }, { "element": "button", "icon": "", "text": "", "class": "", "data": { "role": "first", "action": "switchPage", "key": "firstPage", "key_disable": "disableFirst" }, "name": "" }, { "element": "button", "icon": "", "text": "...", "class": "", "data": { "throw": "true", "role": "choice", "action": "changeMode", "mode_to": "GO_TO", "toggle": true, "chat_part": "pagination", "location": "left" }, "name": "" }, { "element": "label", "icon": "", "text": "", "class": "lblStyle", "data": { "role": "current", "key": "currentPage" }, "name": "", "disable": false }, { "element": "button", "icon": "", "text": "...", "class": "", "data": { "throw": "true", "role": "choice", "action": "changeMode", "mode_to": "GO_TO", "chat_part": "pagination", "location": "right", "toggle": true }, "name": "" }, { "element": "button", "icon": "", "text": "", "class": "", "data": { "role": "last", "action": "switchPage", "key": "lastPage", "key_disable": "disableLast" }, "name": "" }, { "element": "button", "icon": "forward_arrow", "text": "", "class": "", "data": { "role": "forward", "action": "switchPage", "key_disable": "disableForward" }, "name": "" } ] } }, getInitialState() { return { currentOptions: {} } }, defineOptions(mode) { this.options = {}; switch (mode) { case 'CHATS': this.options['paginationOptions'] = this.props.data.chats_PaginationOptions; break; case 'USERS': this.options['paginationOptions'] = this.props.data.users_PaginationOptions; break; default: this.options = null; break; } }, handleClick(event) { let element = this.getDataParameter(event.currentTarget, 'action'); if (element) { switch (element.dataset.action) { case 'switchPage': this.switchPage(element); break; case 'changeMode': let mode = this.props.data.bodyMode ? this.props.data.bodyMode : this.props.data.bodyOptions.mode, currentOptions = this.optionsDefinition(this.props.data, mode); currentOptions.goToOptions.show = !currentOptions.goToOptions.show; if (currentOptions.goToOptions.show && currentOptions.goToOptions.rteChoicePage){ currentOptions.goToOptions.pageShow = currentOptions.paginationOptions.currentPage; currentOptions.goToOptions.page = currentOptions.paginationOptions.currentPage; } this.props.handleEvent.changeState({[currentOptions.goToOptions.text]: currentOptions.goToOptions}); break; } } }, countPagination(currentOptions, state, mode, options, callback) { if(!currentOptions){ currentOptions = this.optionsDefinition(state, mode); } this.countQuantityPages(currentOptions, mode, options, function(_currentOptions) { let po = _currentOptions.paginationOptions; if (po.currentPage === po.firstPage) { po.disableBack = true; po.disableFirst = true; } else { po.disableBack = false; po.disableFirst = false; } if (po.currentPage === po.lastPage) { po.disableForward = true; po.disableLast = true; } else { po.disableForward = false; po.disableLast = false; } if (callback) { callback({ [po.text]: po, [_currentOptions.listOptions.text]: _currentOptions.listOptions }); } }); }, countQuantityPages(currentOptions, mode, options, callback) { let self = this; if (currentOptions.listOptions.data_download) { messages.prototype.getAllMessages(options.chat_id, mode, function(err, messages) { self.handleCountPagination(messages, currentOptions, callback); }); } else { switch (mode) { case "CHATS": users_bus.getMyInfo(null, function(error, options, userInfo) { if (!userInfo) return; chats_bus.getChats(error, options, userInfo.chat_ids, function(error, options, chatsInfo) { if (error) { console.error(error); return; } self.handleCountPagination(chatsInfo, currentOptions, callback); }); }); break; case "USERS": users_bus.getMyInfo(null, function(error, options, userInfo) { if (!userInfo) return; users_bus.getContactsInfo(error, userInfo.user_ids, function(_error, contactsInfo) { if (_error) { console.error(_error); return; } contactsInfo = users_bus.filterUsersByTypeDisplay(contactsInfo, currentOptions.filterOptions.typeDisplayContacts); self.handleCountPagination(contactsInfo, currentOptions, callback); }); }); break; case "CONTACT_LIST": chats_bus.getChatContacts(options.chat_id, function(error, contactsInfo) { if (error) { console.error(error); return; } contactsInfo = users_bus.filterUsersByTypeDisplay(contactsInfo, currentOptions.filterOptions.typeDisplayContacts, options); self.handleCountPagination(contactsInfo, currentOptions, callback); }); break; } } }, handleCountPagination(data, currentOptions, callback) { let quantityPages, quantityData, po = currentOptions.paginationOptions, lo = currentOptions.listOptions; if (!po || !lo) return; if (data) { quantityData = data.length; } else { quantityData = 0; } if (quantityData !== 0) { quantityPages = Math.ceil(quantityData / currentOptions.paginationOptions.perPageValue); } else { quantityPages = 1; } if (po.currentPage === null) { lo.start = quantityPages * po.perPageValue - po.perPageValue; lo.final = quantityPages * po.perPageValue; po.currentPage = quantityPages; } else { lo.start = (po.currentPage - 1) * po.perPageValue; lo.final = (po.currentPage - 1) * po.perPageValue + po.perPageValue; } po.lastPage = quantityPages; if (callback) { callback(currentOptions); } }, switchPage(element) { let self = this, currentOptions = this.optionsDefinition(this.props.data, this.props.mode), po = currentOptions.paginationOptions, elementRole = element.dataset.role; if (elementRole === "first" || elementRole === "last") { po.currentPage = parseInt(element.dataset.value); } if (elementRole === "back" && po.currentPage !== po.firstPage) { po.currentPage = parseInt(po.currentPage) - 1; } if (elementRole === "forward" && po.currentPage !== po.lastPage) { po.currentPage = parseInt(po.currentPage) + 1; } this.countPagination(currentOptions, null, this.props.mode, {"chat_id": this.props.data.chat_id}, function(_newState) { self.props.handleEvent.changeState(_newState); }); }, changePage(element, currentOptions) { let value = parseInt(element.value, 10), gto = currentOptions.goToOptions, po = currentOptions.paginationOptions; gto.pageShow = element.value; if (!(value === 0 || Number.isNaN(value))) { if(value > po.lastPage){ gto.page = po.lastPage; } else { if (value < po.firstPage){ gto.page = po.firstPage; } else { gto.page = value; } } if (gto.rteChoicePage) { if(value > po.lastPage){ po.currentPage = po.lastPage; } else { if (value < po.firstPage){ po.currentPage = po.firstPage; } else { po.currentPage = value; } } } } return currentOptions; }, render() { let onEvent = { onClick: this.handleClick }, currentOptions = this.optionsDefinition(this.props.data, this.props.mode), po = currentOptions.paginationOptions; if (po && po.show) { let data = { firstPage: po.firstPage, currentPage: po.currentPage, lastPage: po.lastPage, disableBack: po.disableBack, disableFirst: po.disableFirst, disableLast: po.disableLast, disableForward: po.disableForward }; return <div> { <Location_Wrapper events={onEvent} data={data} configs={this.props.configs} mainContainer={this.props.mainContainer}/> } </div>; } else { return <div></div>; } } }); extend_core.prototype.inherit(Pagination, switcher_core); extend_core.prototype.inherit(Pagination, dom_core); export default Pagination;
lib/Card.js
danalvarez5280/Weatherly
import React from 'react'; export default function Card (props) { const propsIcon = props.icon const image = `./assets/${propsIcon}.svg` return ( <div className="card"> { props.time && <p className="card-info">{props.time}</p> } { props.day && <p className="card-info">{props.day}</p> } { props.condition && <p className="card-info">{props.condition}</p> } <p className="weather-icon card-info"><img className="small-icon" src={image}/></p> { props.temp && <p className="card-info">{props.temp} °F</p> } { props.high && <p className="card-info">{props.high} °F</p> } { props.low && <p className="card-info">{props.low} °F</p> } </div> ); }
src/svg-icons/image/gradient.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGradient = (props) => ( <SvgIcon {...props}> <path d="M11 9h2v2h-2zm-2 2h2v2H9zm4 0h2v2h-2zm2-2h2v2h-2zM7 9h2v2H7zm12-6H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z"/> </SvgIcon> ); ImageGradient = pure(ImageGradient); ImageGradient.displayName = 'ImageGradient'; ImageGradient.muiName = 'SvgIcon'; export default ImageGradient;
investninja-web-ui-admin/src/vendor/recharts/demo/component/CartesianGrid.js
InvestNinja/InvestNinja-web-ui
import React from 'react'; import { Surface, CartesianGrid } from 'recharts'; export default React.createClass({ render () { let horizontalPoints = [10, 20, 30, 100, 400]; let verticalPoints = [100, 200, 300, 400]; return ( <Surface width={500} height={500}> <CartesianGrid width={500} height={500} verticalPoints={verticalPoints} horizontalPoints={horizontalPoints} /> </Surface> ); } });
resources/src/js/components/Sidebar/components/NavListItems.js
aberon10/thermomusic.com
'use strict'; // Dependencies import React from 'react'; import { NavLink, Link } from 'react-router-dom'; function closeSidebar() { document.getElementById('nav-bar-container').classList.remove('nav-bar-visible'); } class NavListItems extends React.Component { constructor(props) { super(props); } render() { let links = this.props.links; let listItems = []; let typeLink = this.props.typeLink; links.forEach((link, index) => { let element = null; if (typeLink === '1') { element = <a href={link.url} onClick={closeSidebar}>{link.name}</a>; } else if (typeLink === '2') { element = <Link to={link.url} onClick={closeSidebar}>{link.name}</Link>; } else if (typeLink === '3') { element = <NavLink to={link.url} onClick={closeSidebar}>{link.name}</NavLink>; } listItems.push(<li className="nav-list__item" key={index}>{element}</li>); }); return ( <div> {listItems} </div> ); } } NavListItems.defaultProps = { typeLink: '1' // Tipo de enlace 1) - <a> 2) - <Link/> 3) - <NavLink/> }; export default NavListItems;
blueocean-material-icons/src/js/components/svg-icons/action/accessibility.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionAccessibility = (props) => ( <SvgIcon {...props}> <path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z"/> </SvgIcon> ); ActionAccessibility.displayName = 'ActionAccessibility'; ActionAccessibility.muiName = 'SvgIcon'; export default ActionAccessibility;
docs/app/Examples/collections/Form/Variations/FormExampleUnstackable.js
shengnian/shengnian-ui-react
import React from 'react' import { Button, Form } from 'shengnian-ui-react' const FormExampleUnstackable = () => ( <Form unstackable> <Form.Group widths={2}> <Form.Input label='First name' placeholder='First name' /> <Form.Input label='Last name' placeholder='Last name' /> </Form.Group> <Form.Checkbox label='I agree to the Terms and Conditions' /> <Button type='submit'>Submit</Button> </Form> ) export default FormExampleUnstackable
src/components/Login.js
kimochg/react-native-githubnote-app
/* * @Author: LIU CHENG * @Date: 2017-02-28 09:27:56 * @Last Modified by: LIU CHENG * @Last Modified time: 2017-02-28 19:24:21 */ import React from 'react'; import { View, Text, TextInput, TouchableHighlight, ActivityIndicator, StyleSheet } from 'react-native'; /** * Login form * props: * isLoading: Boolean spinner show or not * loginErr: String error message of login * login: func (username, password) */ class LoginForm extends React.Component { constructor(props) { super(props); this.state = { username: 'kimochg', password: 'Liucheng123', } } handleUsernameChange(username) { this.setState({ username, }) } handlePasswordChange(password) { this.setState({ password, }) } handleLogin() { const { username , password } = this.state; console.log('handleLogin', username, password); const { login } = this.props; login(username, password); } render () { return ( <View style={styles.contaienr}> <Text style={styles.title}>Github Account Login</Text> <TextInput style={styles.textInput} onChangeText={this.handleUsernameChange.bind(this)} value={this.state.username} placeholder="username" /> <TextInput style={styles.textInput} onChangeText={this.handlePasswordChange.bind(this)} value={this.state.password} placeholder="password" secureTextEntry /> <TouchableHighlight style={styles.button} onPress={this.handleLogin.bind(this)} underlayColor="white" > <Text style={styles.buttonText}>Login</Text> </TouchableHighlight> <ActivityIndicator animating={this.props.isLoading} color="#111" size="large" /> {this.props.loginErr? <Text>{this.props.loginErr}</Text> : null} </View> ) } } const styles = StyleSheet.create({ contaienr: { flex: 1, padding: 20, justifyContent: 'center', alignItems: 'center', backgroundColor: '#324050', }, title: { marginBottom: 20, fontSize: 25, textAlign: 'center', color: '#fff', }, textInput: { height: 50, padding: 5, fontSize: 23, borderWidth: 1, borderColor: 'white', borderRadius: 8, color: '#fff', marginBottom: 10, }, button: { flexDirection: 'row', height: 45, backgroundColor: 'white', borderWidth: 1, borderColor: 'white', borderRadius: 8, marginTop: 10, marginBottom: 10, alignSelf: 'stretch', justifyContent: 'center', }, buttonText: { fontSize: 18, color: '#111', alignSelf: 'center', }, }) export default LoginForm;
src/svg-icons/av/stop.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvStop = (props) => ( <SvgIcon {...props}> <path d="M6 6h12v12H6z"/> </SvgIcon> ); AvStop = pure(AvStop); AvStop.displayName = 'AvStop'; AvStop.muiName = 'SvgIcon'; export default AvStop;
examples/src/components/SelectedValuesField.js
jaakerisalu/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var SelectedValuesField = React.createClass({ displayName: 'SelectedValuesField', propTypes: { allowCreate: React.PropTypes.bool, hint: React.PropTypes.string, label: React.PropTypes.string, options: React.PropTypes.array, }, onLabelClick (data, event) { console.log(data, event); }, renderHint () { if (!this.props.hint) return null; return ( <div className="hint">{this.props.hint}</div> ); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select allowCreate={this.props.allowCreate} onOptionLabelClick={this.onLabelClick} value={this.props.options.slice(1,3)} multi={true} placeholder="Select your favourite(s)" options={this.props.options} onChange={logChange} /> {this.renderHint()} </div> ); } }); module.exports = SelectedValuesField;
app/components/SignupCard/index.js
kevinnorris/bookTrading
import React from 'react'; import ActionButton from 'components/ActionButton'; import * as val from 'utils/fieldValidation'; import TextField from 'components/TextField'; import Title from 'components/Title'; import CenterCard from 'components/CenterCard'; import ServerError from 'components/ServerError'; import { restrictedPasswords } from 'utils/constants'; const fieldValidations = [ val.ruleRunner('email', 'Email', val.required, val.mustContain('@')), val.ruleRunner('name', 'Name', val.required), val.ruleRunner('password1', 'Password', val.required, val.minLength(6), val.cantContain(restrictedPasswords, ['email', 'name'])), val.ruleRunner('password2', 'Password Confirmation', val.mustMatch('password1', 'Password')), ]; class SignupCard extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { signup: React.PropTypes.func.isRequired, error: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.bool, ]), } static defaultProps = { error: '', } state = { email: '', name: '', password1: '', password2: '', showErrors: false, validationErrors: { email: '', name: '', password1: '', password2: '', }, } errorFor(field) { if (this.state.validationErrors[field]) { return this.state.validationErrors[field]; } return ''; } handelInputChange(field) { return (e) => { const newState = { ...this.state, [field]: e.target.value, }; newState.validationErrors = val.run(newState, fieldValidations); this.setState(newState); }; } handelSubmit = (e) => { e.preventDefault(); this.setState({ ...this.state, showErrors: true, }); // Check if validationErrors is empty if (Object.getOwnPropertyNames(this.state.validationErrors).length === 0) { // send to server this.props.signup({ email: this.state.email, name: this.state.name, password: this.state.password1 }); } } render() { return ( <CenterCard zLevel={1}> <Title className="SignupCard-title">Signup</Title> <form className={'text-left'} onSubmit={this.handelSubmit}> <TextField name="email" label="Email Address" placeHolder="Email address" showError={this.state.showErrors} text={this.state.email} isPassword={false} onFieldChange={this.handelInputChange('email')} errorText={this.errorFor('email')} /> <TextField name="name" label="Name" placeHolder="Name" showError={this.state.showErrors} text={this.state.name} isPassword={false} onFieldChange={this.handelInputChange('name')} errorText={this.errorFor('name')} /> <TextField name="password1" label="Password *" placeHolder="Password" showError={this.state.showErrors} text={this.state.password1} isPassword onFieldChange={this.handelInputChange('password1')} errorText={this.errorFor('password1')} /> <TextField name="password2" placeHolder="Confirm password" showError={this.state.showErrors} text={this.state.password2} isPassword onFieldChange={this.handelInputChange('password2')} errorText={this.errorFor('password2')} /> <p>* required fields</p> <div className="text-center"> {this.props.error ? <ServerError>{this.props.error}</ServerError> : ''} <ActionButton type="submit">Submit</ActionButton> </div> </form> </CenterCard> ); } } export default SignupCard;
packages/mineral-ui-icons/src/IconSentimentNeutral.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconSentimentNeutral(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M9 14h6v1.5H9z"/><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </g> </Icon> ); } IconSentimentNeutral.displayName = 'IconSentimentNeutral'; IconSentimentNeutral.category = 'social';
src/components/google_map.js
benjaminboruff/CityWeather
import React, { Component } from 'react'; class GoogleMap extends Component { componentDidMount() { new google.maps.Map(this.refs.map, { zoom: 12, center: { lat: this.props.lat, lng: this.props.lon } }); } render() { return <div ref="map"></div>; } } export default GoogleMap;
src/SwitchNext.js
Edorka/steam2graph
import React, { Component } from 'react'; import './SwitchNext.css'; // Include its styles in you build process as well class SwitchNext extends Component { constructor(props){ super(props); this.choices = []; this.state = { choice: {'label':''}, position: null }; } componentDidMount() { this.choices = this.props.choices; this.setState({ position: 0, choice: this.choices[0] }); } next(e){ var newPosition = this.state.position + 1; newPosition = newPosition < this.choices.length ? newPosition: 0; this.setState({ position: newPosition, choice: this.choices[newPosition] }); this.props.onSelection(this.state.choice); } render() { return( <button onClick={(e) => this.next(e)}> {this.state.choice.label} </button> ); } } export default SwitchNext
src/components/search_bar.js
AihaitiAbudureheman/learn-react
import React, { Component } from 'react'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: ''}; } render (){ return ( <div> <input onChange={ event => this.setState({ term: event.target.value})} /> </div> ) } } export default SearchBar;
src/parser/priest/holy/modules/talents/90/Halo.js
sMteX/WoWAnalyzer
import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox'; import React from 'react'; import ItemHealingDone from 'interface/others/ItemHealingDone'; import ItemDamageDone from 'interface/others/ItemDamageDone'; // Example Log: /report/hRd3mpK1yTQ2tDJM/1-Mythic+MOTHER+-+Kill+(2:24)/14-丶寶寶小喵 class Halo extends Analyzer { haloDamage = 0; haloHealing = 0; haloOverhealing = 0; haloCasts = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.HALO_TALENT.id); } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_DAMAGE.id) { this.haloDamage += event.amount || 0; } } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_HEAL.id) { this.haloHealing += event.amount || 0; this.haloOverhealing += event.overhealing || 0; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_TALENT.id) { this.haloCasts += 1; } } statistic() { return ( <TalentStatisticBox talent={SPELLS.HALO_TALENT.id} value={( <> <ItemHealingDone amount={this.haloHealing} /><br /> <ItemDamageDone amount={this.haloDamage} /> </> )} tooltip={`Halos Cast: ${this.haloCasts}`} position={STATISTIC_ORDER.CORE(6)} /> ); } } export default Halo;
ui/src/components/DeviceProfileForm.js
jcampanell-cablelabs/lora-app-server
import React, { Component } from 'react'; import Select from "react-select"; import NetworkServerStore from "../stores/NetworkServerStore"; import SessionStore from "../stores/SessionStore"; class DeviceProfileForm extends Component { static contextTypes = { router: React.PropTypes.object.isRequired }; constructor() { super(); this.state = { deviceProfile: { deviceProfile: {}, }, networkServers: [], update: false, activeTab: "general", isAdmin: false, }; this.handleSubmit = this.handleSubmit.bind(this); this.changeTab = this.changeTab.bind(this); } componentDidMount() { NetworkServerStore.getAllForOrganizationID(this.props.organizationID, 9999, 0, (totalCount, networkServers) => { this.setState({ deviceProfile: this.props.deviceProfile, networkServers: networkServers, isAdmin: SessionStore.isAdmin(), }); }); } componentWillReceiveProps(nextProps) { this.setState({ deviceProfile: nextProps.deviceProfile, update: nextProps.deviceProfile.deviceProfile.deviceProfileID !== undefined, }); } handleSubmit(e) { e.preventDefault(); this.props.onSubmit(this.state.deviceProfile); } onChange(fieldLookup, e) { let lookup = fieldLookup.split("."); const fieldName = lookup[lookup.length-1]; lookup.pop(); // remove last item let deviceProfile = this.state.deviceProfile; let obj = deviceProfile; for (const f of lookup) { obj = obj[f]; } if (fieldName === "factoryPresetFreqsStr") { let freqsStr = e.target.value.split(","); obj[fieldName] = e.target.value; obj["factoryPresetFreqs"] = freqsStr.map((c, i) => parseInt(c, 10)); } else if (e.target.type === "number") { obj[fieldName] = parseInt(e.target.value, 10); } else if (e.target.type === "checkbox") { obj[fieldName] = e.target.checked; } else { obj[fieldName] = e.target.value; } this.setState({ deviceProfile: deviceProfile, }); } onSelectChange(fieldLookup, val) { let lookup = fieldLookup.split("."); const fieldName = lookup[lookup.length-1]; lookup.pop(); // remove last item let deviceProfile = this.state.deviceProfile; let obj = deviceProfile; for (const f of lookup) { obj = obj[f]; } obj[fieldName] = val.value; this.setState({ deviceProfile: deviceProfile, }); } changeTab(e) { e.preventDefault(); this.setState({ activeTab: e.target.getAttribute("aria-controls"), }); } render() { const networkServerOptions = this.state.networkServers.map((networkServer, i) => { return { value: networkServer.id, label: networkServer.name, }; }); const macVersionOptions = [ {value: "1.0.0", label: "1.0.0"}, {value: "1.0.1", label: "1.0.1"}, {value: "1.0.2", label: "1.0.2"}, {value: "1.1.0", label: "1.1.0"}, ]; const regParamsOptions = [ {value: "A", label: "A"}, {value: "B", label: "B"}, ]; return( <div> <ul className="nav nav-tabs"> <li role="presentation" className={(this.state.activeTab === "general" ? "active" : "")}><a onClick={this.changeTab} href="#general" aria-controls="general">General</a></li> <li role="presentation" className={(this.state.activeTab === "join" ? "active" : "")}><a onClick={this.changeTab} href="#join" aria-controls="join">Join (OTAA / ABP)</a></li> <li role="presentation" className={(this.state.activeTab === "classC" ? "active" : "")}><a onClick={this.changeTab} href="#classC" aria-controls="classC">Class-C</a></li> </ul> <hr /> <form onSubmit={this.handleSubmit}> <fieldset disabled={!this.state.isAdmin}> <div className={(this.state.activeTab === "general" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="name">Device-profile name</label> <input className="form-control" id="name" type="text" placeholder="e.g. my device-profile" required value={this.state.deviceProfile.name || ''} onChange={this.onChange.bind(this, 'name')} /> <p className="help-block"> A memorable name for the device-profile. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="networkServerID">Network-server</label> <Select name="networkServerID" options={networkServerOptions} value={this.state.deviceProfile.networkServerID} onChange={this.onSelectChange.bind(this, 'networkServerID')} disabled={this.state.update} /> <p className="help-block"> The network-server on which this device-profile will be provisioned. After creating the device-profile, this value can't be changed. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="macVersion">LoRaWAN MAC version</label> <Select name="macVersion" options={macVersionOptions} value={this.state.deviceProfile.deviceProfile.macVersion} onChange={this.onSelectChange.bind(this, 'deviceProfile.macVersion')} /> <p className="help-block"> Version of the LoRaWAN supported by the End-Device. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="macVersion">LoRaWAN Regional Parameters revision</label> <Select name="regParamsRevision" options={regParamsOptions} value={this.state.deviceProfile.deviceProfile.regParamsRevision} onChange={this.onSelectChange.bind(this, 'deviceProfile.regParamsRevision')} /> <p className="help-block"> Revision of the Regional Parameters document supported by the End-Device. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="maxEIRP">Max EIRP</label> <input className="form-control" name="maxEIRP" id="maxEIRP" type="number" value={this.state.deviceProfile.deviceProfile.maxEIRP || 0} onChange={this.onChange.bind(this, 'deviceProfile.maxEIRP')} /> <p className="help-block"> Maximum EIRP supported by the End-Device. </p> </div> </div> <div className={(this.state.activeTab === "join" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="supportsJoin">Supports join (OTAA)</label> <div className="checkbox"> <label> <input type="checkbox" name="supportsJoin" id="supportsJoin" checked={this.state.deviceProfile.deviceProfile.supportsJoin} onChange={this.onChange.bind(this, 'deviceProfile.supportsJoin')} /> Supports join </label> </div> <p className="help-block"> End-Device supports Join (OTAA) or not (ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDelay1">RX1 delay</label> <input className="form-control" name="rxDelay1" id="rxDelay1" type="number" value={this.state.deviceProfile.deviceProfile.rxDelay1 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDelay1')} /> <p className="help-block"> Class A RX1 delay (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDROffset1">RX1 data-rate offset</label> <input className="form-control" name="rxDROffset1" id="rxDROffset1" type="number" value={this.state.deviceProfile.deviceProfile.rxDROffset1 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDROffset1')} /> <p className="help-block"> RX1 data rate offset (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDataRate2">RX2 data-rate</label> <input className="form-control" name="rxDataRate2" id="rxDataRate2" type="number" value={this.state.deviceProfile.deviceProfile.rxDataRate2 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDataRate2')} /> <p className="help-block"> RX2 data rate (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxFreq2">RX2 channel frequency</label> <input className="form-control" name="rxFreq2" id="rxFreq2" type="number" value={this.state.deviceProfile.deviceProfile.rxFreq2 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxFreq2')} /> <p className="help-block"> RX2 channel frequency (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="factoryPresetFreqsStr">Factory-present frequencies</label> <input className="form-control" id="factoryPresetFreqsStr" type="text" placeholder="e.g. 860100000, 868300000, 868500000" value={this.state.deviceProfile.deviceProfile.factoryPresetFreqsStr || ''} onChange={this.onChange.bind(this, 'deviceProfile.factoryPresetFreqsStr')} /> <p className="help-block"> List of factory-preset frequencies (mandatory for ABP). </p> </div> </div> <div className={(this.state.activeTab === "classC" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="supportsClassC">Supports Class-C</label> <div className="checkbox"> <label> <input type="checkbox" name="supportsClassC" id="supportsClassC" checked={this.state.deviceProfile.deviceProfile.supportsClassC} onChange={this.onChange.bind(this, 'deviceProfile.supportsClassC')} /> Supports Class-C </label> </div> <p className="help-block"> End-Device supports Class C. </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsClassC === true ? "" : "hidden")}> <label className="control-label" htmlFor="classCTimeout">Class-C confirmed downlink timeout</label> <input className="form-control" name="classCTimeout" id="classCTimeout" type="number" value={this.state.deviceProfile.deviceProfile.classCTimeout || 0} onChange={this.onChange.bind(this, 'deviceProfile.classCTimeout')} /> <p className="help-block"> Class-C timeout (in seconds) for confirmed downlink transmissions. </p> </div> </div> </fieldset> <hr /> <div className={"btn-toolbar pull-right " + (this.state.isAdmin ? "" : "hidden")}> <a className="btn btn-default" onClick={this.context.router.goBack}>Go back</a> <button type="submit" className="btn btn-primary">Submit</button> </div> </form> </div> ); } } export default DeviceProfileForm;
app/components/common/Modal.js
mswiszcz/pagebuilder
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Modal.css'; export default class Modal extends Component { render() { return ( <div className={styles.overlay} onClick={this.props.onClose}> <div className={styles.content} onClick={(e) => { e.stopPropagation() }}> { this.props.children } </div> </div> ); } }
src/hoister.js
ulisesbocchio/react-redux-boilerout
import React from 'react'; export function hoistClassBehavior(clazz, behaviour) { const instanceKeys = Reflect.ownKeys(behaviour); for (let property of instanceKeys) { const hoistedDescriptor = Reflect.getOwnPropertyDescriptor(behaviour, property); const originalDescriptor = Reflect.getOwnPropertyDescriptor(clazz.prototype, property); const mergedDescriptor = Object.assign({}, originalDescriptor, hoistedDescriptor, { value: function(...args) { const hoistedRet = hoistedDescriptor.value.bind(this)(...args); const originalRet = originalDescriptor && originalDescriptor.value.bind(this)(...args); return typeof originalRet !== 'undefined' ? originalRet : hoistedRet; } }); Object.defineProperty(clazz.prototype, property, mergedDescriptor); } return clazz; } export function hoistComponentBehavior(component, behaviour) { class HoistedComponent extends React.Component { render() { return React.createElement(component, this.props); } } hoistClassBehavior(HoistedComponent, behaviour); HoistedComponent.propTypes = component.propTypes; HoistedComponent.defaultProps = component.defaultProps; HoistedComponent.displayName = `HoistedComponent(${component.displayName || component.name || 'Component'})`; return HoistedComponent; }
src/svg-icons/content/archive.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentArchive = (props) => ( <SvgIcon {...props}> <path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zM12 17.5L6.5 12H10v-2h4v2h3.5L12 17.5zM5.12 5l.81-1h12l.94 1H5.12z"/> </SvgIcon> ); ContentArchive = pure(ContentArchive); ContentArchive.displayName = 'ContentArchive'; ContentArchive.muiName = 'SvgIcon'; export default ContentArchive;
src/components/rb-icon.js
Pier1/rocketbelt
import PropTypes from 'prop-types'; import React from 'react'; const RbIcon = ({ icon, className }) => { return ( <svg className={`icon ${className}`} dangerouslySetInnerHTML={{ __html: `<use xlink:href="/icons/rocketbelt.icons.svg#rb-icon-${icon}"></use>`, }} /> ); }; RbIcon.propTypes = { icon: PropTypes.string.isRequired, }; export default RbIcon;
reactviews/src/ChartDoghnut.js
yvesago/dioc
import React from 'react'; import {Doughnut, Chart} from 'react-chartjs-2'; // some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/ var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw; Chart.helpers.extend(Chart.controllers.doughnut.prototype, { draw: function() { originalDoughnutDraw.apply(this, arguments); var chart = this.chart; var width = chart.chart.width, height = chart.chart.height, ctx = chart.chart.ctx; var fontSize = (height / 114).toFixed(2); ctx.font = fontSize + 'em sans-serif'; ctx.textBaseline = 'middle'; var sum = 0; for (var i = 0; i < chart.config.data.datasets[0].data.length; i++) { sum += chart.config.data.datasets[0].data[i]; } var text = sum, textX = Math.round((width - ctx.measureText(text).width) / 2), textY = height / 2; ctx.fillText(text, textX, textY); } }); const options={ legend: { display: false, }, }; class DonutWithText extends React.Component { constructor(props) { super(props); this.state = { data: {labels:[],datasets:[]} }; } static fixData (alertes) { var ndata = {labels:[],datasets:[]}; var o = {data:[]}; for (var i in alertes){ var ni = alertes[i]; for (var k in ni){ if (ni.hasOwnProperty(k)) { ndata.labels.push(k); o.data.push(ni[k]); } } } o.backgroundColor = [ '#ff7f0e', '#1f77b4', '#aec7e8', '#ffca28', '#d4e157','#4caf50','#26a69a','#00e5ff', '#00b0ff', '#ff1744' ]; o.hoverBackgroundColor = [ '#ff9f2e', '#3f97d4', '#bed7f8', '#ffca28', '#d4e157','#4caf50','#26a69a','#00e5ff', '#00b0ff', '#ff1744']; ndata.datasets.push(o); return ndata; } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.data !== null && nextProps.data.length !== 0 ) { return { data: DonutWithText.fixData(nextProps.data) }; } return null; } render() { var a = this.props.data; if (a === null || a.length === 0) { return ( <div>...</div> ); } return ( <div> {this.props.title} : <Doughnut data={this.state.data} options={options} height={150} width={180} /> </div> ); } } export default DonutWithText;
client/routes/Items/index.js
patzj/ims
import React from 'react'; import ItemsPanel from './components/ItemsPanel'; export const Items = () => { return <ItemsPanel /> }; export default Items;
pages/api/dialog-actions.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './dialog-actions.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
components/Welcome.ios.js
xfredlix/snacktime
'use strict'; import React, { Component } from 'react'; import { Alert, Animated, Dimensions, Easing, Image, LayoutAnimation, Navigator, Platform, ScrollView, StyleSheet, Switch, Text, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback, View, UIManager, } from 'react-native'; import App from './App.ios.js'; import { NavigatorIOS } from 'react-native'; import Video from 'react-native-video'; import BaseApp from './baseApp.ios.js'; import Button from 'react-native-flat-button' import * as Animatable from 'react-native-animatable'; import styles from '../styles.ios.js'; // const Storage = require('google-cloud/node_modules/@google-cloud/storage'); // const Vision = require('google-cloud/node_modules/@google-cloud/vision'); // const gcloud = require('google-cloud'); // const fs = require('fs'); // const google = require('googleapis'); // // Instantiates clients // const storage = Storage(); // const vision = Vision(); export default class Welcome extends Component { constructor(props) { super(props); } toRoute() { this.props.navigator.push({ component: BaseApp }) } render() { return ( <TouchableWithoutFeedback onPress={this.toRoute.bind(this)} > <View> <Video repeat resizeMode='cover' source={require('../public/food.mp4')} style={styles.backgroundVideo} /> <Animatable.Text style={styles.header} animation="fadeInDown" duration={4000} direction="alternate" > <Text>Snacktime</Text> </Animatable.Text> <Animatable.Text style={styles.comingInWord} animation="fadeInUp" color="#841584" delay={2000} duration={4000} > <Text>Touch Anywhere to begin</Text> </Animatable.Text> </View> </TouchableWithoutFeedback> ); } } // testing // <TouchableWithoutFeedback // onPress={this.toRoute} // > // <Image // source={require('../backgroundimage/funny.jpg')} // style={styles.backgroundimage}> // // </View> // </Image> // </TouchableWithoutFeedback> // <View> // <video autoplay loop id="video-background" muted> // <source src="https://player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761" type="video/mp4"> // </video> // </View> ///////////////////////////////// ONE STYLE /////////////////// // import Button from 'apsl-react-native-button' // <Animatable.View // animation="fadeInUp" // color="#841584" // delay={3000} // duration={10000} // > // <Button // style={{backgroundColor: 'blue', width: 200}} // onPress={this.toRoute} // > // <View style={styles.nestedViewStyle}> // <Text style={styles.nestedTextStyle}>Nested views!</Text> // </View> // </Button> // </Animatable.View> ///////////////////////////////// ONE STYLE /////////////////// ///////////////////////////////// BUTTON STYLE //////////////////////// // <Animatable.View // ref="view" // animation="fadeInUp" // color="#841584" // delay={2000} // duration={7000} // > // <Button // type="warn" // onPress={this.toAnotherRoute} // title={'Learn More!'} // containerStyle={styles.buttonContainer} // > // Learn More! // </Button> // </Animatable.View> // // <Animatable.View // animation="fadeInUp" // color="#841584" // delay={2000} // duration={7000} // > // <Button // type="info" // onPress={this.toRoute} // containerStyle={styles.buttonContainer} // > // Lets Go! // </Button> // </Animatable.View> ///////////////////////////////// BUTTON STYLE ////////////////////////
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js
Technaesthetic/ua-tools
import _transformLib from 'transform-lib'; const _components = { Foo: { displayName: 'Foo' } }; const _transformLib2 = _transformLib({ filename: '%FIXTURE_PATH%', components: _components, locals: [], imports: [] }); function _wrapComponent(id) { return function (Component) { return _transformLib2(Component, id); }; } import React, { Component } from 'react'; const Foo = _wrapComponent('Foo')(class Foo extends Component { render() {} });
src/components/TextInputCSSModules/TextInputCSSModules.js
ebirito/ps-react-ebirito
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; import styles from './textInput.css'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { return ( <div className={styles.fieldset}> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} className={error && styles.inputError} {...props}/> {children} {error && <div className={styles.error}>{error}</div>} </div> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
app/client/src/scenes/LoggedOutHome/LoggedOutHome.js
uprisecampaigns/uprise-app
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import Link from 'components/Link'; import s from 'styles/Page.scss'; function LoggedOutHome(props) { return ( <div className={s.root}> <div className={s.homeContentSection1}> <div className={s.fullContainer}> <div className={s.contentTitle}>Take Action</div> <div className={s.contentText}> UpRise is reforming our political campaign process by putting you back in the drivers&apos; seat. Sign up now to find volunteering opportunities or create a page so volunteers can find you. </div> <div className={s.homeButtonContainer}> <Link useAhref={false} to="/signup"> <FlatButton className={s.homeButton} label="Sign up now" /> </Link> </div> </div> </div> <div className={s.homeContentSection2}> <div className={s.fullContainer}> <div className={s.contentTitle}>Volunteers</div> <div className={s.contentText}> UpRise is a social network platform you can use to organize your political life: to find, sign up for and create real-world actions. </div> <div className={s.linkContainer}> <Link useAhref to="uprisecampaigns.org/home/volunteers" external sameTab> Learn More </Link> </div> </div> </div> <div className={s.homeContentSection3}> <div className={s.fullContainer}> <div className={s.contentTitle}>Campaigns</div> <div className={s.contentText}> UpRise will connect you with new volunteers and provide the tools you need to create effective volunteer-powered campaigns. </div> <div className={s.linkContainer}> <Link useAhref to="uprisecampaigns.org/home/campaigns" external sameTab> Learn More </Link> </div> </div> </div> <div className={s.homeContentSection4}> <div className={s.fullContainer}> <div className={s.halfContainer}> <div className={s.contentTitle}>Subscribe</div> <div className={s.contentText}>Subscribe today and join the UpRise community.</div> <div className={s.homeButtonContainer}> <Link useAhref={false} to="https://act.myngp.com/Forms/-8815703986835813888" external sameTab> <FlatButton className={s.homeButton} label="Get the Newsletter" /> </Link> </div> </div> <div className={s.halfContainer}> <div className={s.contentTitle}>Support</div> <div className={s.contentText}>Become a supporting member of UpRise.</div> <div className={s.homeButtonContainer}> <Link useAhref={false} to="https://act.myngp.com/Forms/-8527473610684102144" external sameTab> <FlatButton className={s.homeButton} label="Contribute Today" /> </Link> </div> </div> </div> </div> <div className={s.homeContentSection5}> <div className={s.fullContainer}> <div className={s.contentTitle}>Contact Us</div> <div className={s.contentText}>Email: staff@uprise.org</div> <div className={s.contentText}>21001 N Tatum Blvd STE 1630 #618 | Phoenix | AZ | 85050-4242</div> </div> </div> </div> ); } export default LoggedOutHome;
frontend/src/AddMovie/ImportMovie/Import/ImportMovie.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; import translate from 'Utilities/String/translate'; import getSelectedIds from 'Utilities/Table/getSelectedIds'; import selectAll from 'Utilities/Table/selectAll'; import toggleSelected from 'Utilities/Table/toggleSelected'; import ImportMovieFooterConnector from './ImportMovieFooterConnector'; import ImportMovieTableConnector from './ImportMovieTableConnector'; class ImportMovie extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { allSelected: false, allUnselected: false, lastToggled: null, selectedState: {}, contentBody: null }; } // // Control setScrollerRef = (ref) => { this.setState({ scroller: ref }); } // // Listeners getSelectedIds = () => { return getSelectedIds(this.state.selectedState, { parseIds: false }); } onSelectAllChange = ({ value }) => { // Only select non-dupes this.setState(selectAll(this.state.selectedState, value)); } onSelectedChange = ({ id, value, shiftKey = false }) => { this.setState((state) => { return toggleSelected(state, this.props.items, id, value, shiftKey); }); } onRemoveSelectedStateItem = (id) => { this.setState((state) => { const selectedState = Object.assign({}, state.selectedState); delete selectedState[id]; return { ...state, selectedState }; }); } onInputChange = ({ name, value }) => { this.props.onInputChange(this.getSelectedIds(), name, value); } onImportPress = () => { this.props.onImportPress(this.getSelectedIds()); } // // Render render() { const { rootFolderId, path, rootFoldersFetching, rootFoldersError, rootFoldersPopulated, unmappedFolders } = this.props; const { allSelected, allUnselected, selectedState, scroller } = this.state; return ( <PageContent title={translate('ImportMovies')}> <PageContentBody registerScroller={this.setScrollerRef} onScroll={this.onScroll} > { rootFoldersFetching ? <LoadingIndicator /> : null } { !rootFoldersFetching && !!rootFoldersError ? <div> {translate('UnableToLoadRootFolders')} </div> : null } { !rootFoldersError && !rootFoldersFetching && rootFoldersPopulated && !unmappedFolders.length ? <div> {translate('AllMoviesInPathHaveBeenImported', [path])} </div> : null } { !rootFoldersError && !rootFoldersFetching && rootFoldersPopulated && !!unmappedFolders.length && scroller ? <ImportMovieTableConnector rootFolderId={rootFolderId} unmappedFolders={unmappedFolders} allSelected={allSelected} allUnselected={allUnselected} selectedState={selectedState} scroller={scroller} onSelectAllChange={this.onSelectAllChange} onSelectedChange={this.onSelectedChange} onRemoveSelectedStateItem={this.onRemoveSelectedStateItem} /> : null } </PageContentBody> { !rootFoldersError && !rootFoldersFetching && !!unmappedFolders.length ? <ImportMovieFooterConnector selectedIds={this.getSelectedIds()} onInputChange={this.onInputChange} onImportPress={this.onImportPress} /> : null } </PageContent> ); } } ImportMovie.propTypes = { rootFolderId: PropTypes.number.isRequired, path: PropTypes.string, rootFoldersFetching: PropTypes.bool.isRequired, rootFoldersPopulated: PropTypes.bool.isRequired, rootFoldersError: PropTypes.object, unmappedFolders: PropTypes.arrayOf(PropTypes.object), items: PropTypes.arrayOf(PropTypes.object), onInputChange: PropTypes.func.isRequired, onImportPress: PropTypes.func.isRequired }; ImportMovie.defaultProps = { unmappedFolders: [] }; export default ImportMovie;
client/app/components/ContentEditor/customPlugins/latex-plugin/components/InsertTeXButton.js
bryanph/Geist
import React from 'react'; import {insertTeXBlock} from '../modifiers/insertTeXBlock'; export class InsertTeXButton extends React.Component { constructor(props) { super(props) this.insertTeX = this.insertTeX.bind(this) } insertTeX() { this.props.setEditorState(insertTeXBlock(this.props.editorState)) } render() { const className = this.props.theme.button; return ( <button className={className} onMouseDown={this.insertTeX}> { this.props.label || "TeX" } </button> ) } } InsertTeXButton.defaultProps = { theme: { button: 'add-media-button' } } export class InsertInlineTeXButton extends React.Component { constructor(props) { super(props) this.insertTeX = this.insertTeX.bind(this) } insertTeX() { this.props.setEditorState(insertTeXBlock(this.props.editorState, true)) } render() { const className = this.props.theme.button; return ( <button className={className} onMouseDown={this.insertTeX}> { this.props.label || "TeX" } </button> ) } } InsertInlineTeXButton.defaultProps = { theme: { button: 'add-media-button' } }
app/containers/CardView.js
wenwuwu/redux-restful-example
import React from 'react' import { connect } from 'react-redux' import Card from '../components/Card' import BackToCardList from '../components/BackToCardList' import _ from 'underscore' import { bindActionCreators } from 'redux' import * as ActionCreators from '../actions' import { Link, withRouter } from 'react-router' const CardView = ({id, name, deleteCard, router}) => ( <div id="view-card-wrapper"> <BackToCardList /> <div className="section"> <Card id={id} name={name} /> <div className="row btns"> <Link className="btn" to={`/cards/${id}/edit`}> Edit </Link> <button className="btn" onClick={e => { deleteCard(id) router.push("/cards") }}> Delete </button> </div> </div> </div> ) function mapStateToProps (state, ownProps) { const {cards} = state const idx = _.findIndex(cards, {id: ownProps.params.cardId}) return cards[idx] } export default connect( mapStateToProps, dispatch => bindActionCreators(ActionCreators, dispatch) )(withRouter(CardView))
src/svg-icons/social/sentiment-dissatisfied.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentDissatisfied = (props) => ( <SvgIcon {...props}> <circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/> </SvgIcon> ); SocialSentimentDissatisfied = pure(SocialSentimentDissatisfied); SocialSentimentDissatisfied.displayName = 'SocialSentimentDissatisfied'; SocialSentimentDissatisfied.muiName = 'SvgIcon'; export default SocialSentimentDissatisfied;
src/components/ListPage.js
GatesmanAgency/GraphQL-Relay-Modern-QuickStart
import React from 'react' import Post from './Post' import WeatherWidget from './WeatherWidget' import { Link } from 'react-router-dom' import { createFragmentContainer, graphql } from 'react-relay' class ListPage extends React.Component { render () { console.log('ListPage - render - environment', this.props.relay.environment) return ( <div className='w-100 flex justify-center'> <Link to='/create' className='fixed bg-white top-0 right-0 pa4 ttu dim black no-underline'> + New Post </Link> <div className="cf ph2-ns"> <div className='fl w-100 w-50-ns pa2'> <WeatherWidget /> </div> <div className='fl w-100 w-50-ns pa2' style={{ maxWidth: 400 }}> {this.props.viewer.allPosts.edges.map(({node}) => <Post key={node.id} post={node} viewer={this.props.viewer} /> )} </div> </div> </div> ) } } export default createFragmentContainer(ListPage, graphql` fragment ListPage_viewer on Viewer { ...Post_viewer allPosts(last: 100, orderBy: updatedAt_DESC) @connection(key: "ListPage_allPosts", filters: []) { edges { node { id description imageUrl location ...Post_post } } } } `)
app/components/template/Loading.js
jendela/jendela
import React from 'react' class Loading extends React.Component { render() { const style = { display: "block", marginTop: "2em", marginBottom: "2em", marginLeft: "auto", marginRight: "auto", textAlign: "center" } return <img src="img/loading.gif" style={style} /> } } export default Loading
src/bootstrap/AdminPanelWrapper.js
EehMauro/dyscalculia-web
import React from 'react'; import { push } from 'react-router-redux'; import { connect } from 'react-redux'; import { withStyles } from 'material-ui/styles'; import { CircularProgress } from 'material-ui/Progress'; import { fetchSession, doLogout } from '../actions'; import { colors } from '../conventions'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Drawer from 'material-ui/Drawer'; import Divider from 'material-ui/Divider'; import List, { ListItem, ListItemIcon, ListItemText } from 'material-ui/List'; import Icon from 'material-ui/Icon'; const styles = theme => ({ root: { position: 'relative', width: '100%', height: '100%' }, appBar: { padding: '19px 24px 21px', background: colors.primary[500], color: '#FFF', position: 'relative' }, appBarDecoration: { position: 'absolute', left: 0, top: 0, width: 8, height: '100%', backgroundColor: colors.secondary['A200'] }, appTitle: { fontWeight: 400, margin: 0, padding: 0 }, sectionBar: { width: 'calc(100% - 300px)', marginLeft: 300 }, sectionTitle: { fontWeight: 300 }, drawerPaper: { width: 300, border: 'none', boxShadow: '0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)' }, menuList: { flex: 0 }, content: { position: 'relative', padding: 24, paddingTop: 86, marginLeft: 300 } }); const mapStateToProps = state => ({ session: state.session, navigation: state.navigation }); class AdminPanelWrapper extends React.Component { componentDidMount () { this.props.dispatch(fetchSession()); } renderLoading () { return ( <div style={{ position: 'fixed', height: '100vh', width: '100vw', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <CircularProgress size={ 120 } /> </div> ); } render () { let { classes, session } = this.props; if (session.sessionIsFetching) { return this.renderLoading(); } if (!session.profile) return null; return ( <div className={ classes.root }> <AppBar className={ classes.sectionBar }> <Toolbar> <Typography type="title" color="inherit" className={ classes.sectionTitle }> { this.props.navigation.title } </Typography> </Toolbar> </AppBar> <Drawer type="permanent" classes={{ paper: classes.drawerPaper }} > <div className={ classes.appBar }> <div className={ classes.appBarDecoration } /> <Typography type="title" color="inherit" className={ classes.appTitle }> Admin panel </Typography> </div> <List className={ classes.menuList }> <ListItem button onClick={ () => this.props.dispatch(push('/admin')) }> <ListItemIcon> <Icon>dashboard</Icon> </ListItemIcon> <ListItemText primary="Dashboard" /> </ListItem> </List> <Divider /> <List className={ classes.menuList }> <ListItem button onClick={ () => this.props.dispatch(doLogout()) }> <ListItemIcon> <Icon>arrow_back</Icon> </ListItemIcon> <ListItemText primary="Log out" /> </ListItem> </List> </Drawer> <div className={ classes.content }> { this.props.children } </div> </div> ); } } export default connect(mapStateToProps)(withStyles(styles)(AdminPanelWrapper))
examples/shared/wrapInTestContext.js
jowcy/react-dnd
import React, { Component } from 'react'; import TestBackend from 'react-dnd/modules/backends/Test'; import { DragDropContext } from 'react-dnd'; export default function wrapInTestContext(DecoratedComponent) { @DragDropContext(TestBackend) class TestStub extends Component { render() { return <DecoratedComponent {...this.props} />; } } return TestStub; }
packages/react-scripts/template/src/index.js
lolaent/create-react-app
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
jqwidgets/jqwidgets-react/react_jqxtagcloud.js
UCF/IKM-APIM
/* jQWidgets v5.6.0 (2018-Feb) Copyright (c) 2011-2017 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxTagCloud extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['alterTextCase','disabled','displayLimit','displayMember','displayValue','fontSizeUnit','height','maxColor','maxFontSize','maxValueToDisplay','minColor','minFontSize','minValueToDisplay','rtl','sortBy','sortOrder','source','tagRenderer','takeTopWeightedItems','textColor','urlBase','urlMember','valueMember','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).jqxTagCloud(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxTagCloud('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).jqxTagCloud(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; alterTextCase(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('alterTextCase', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('alterTextCase'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('disabled', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('disabled'); } }; displayLimit(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('displayLimit', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('displayLimit'); } }; displayMember(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('displayMember', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('displayMember'); } }; displayValue(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('displayValue', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('displayValue'); } }; fontSizeUnit(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('fontSizeUnit', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('fontSizeUnit'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('height', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('height'); } }; maxColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('maxColor', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('maxColor'); } }; maxFontSize(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('maxFontSize', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('maxFontSize'); } }; maxValueToDisplay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('maxValueToDisplay', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('maxValueToDisplay'); } }; minColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('minColor', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('minColor'); } }; minFontSize(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('minFontSize', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('minFontSize'); } }; minValueToDisplay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('minValueToDisplay', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('minValueToDisplay'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('rtl', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('rtl'); } }; sortBy(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('sortBy', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('sortBy'); } }; sortOrder(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('sortOrder', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('sortOrder'); } }; source(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('source', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('source'); } }; tagRenderer(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('tagRenderer', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('tagRenderer'); } }; takeTopWeightedItems(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('takeTopWeightedItems', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('takeTopWeightedItems'); } }; textColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('textColor', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('textColor'); } }; urlBase(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('urlBase', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('urlBase'); } }; urlMember(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('urlMember', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('urlMember'); } }; valueMember(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('valueMember', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('valueMember'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTagCloud('width', arg) } else { return JQXLite(this.componentSelector).jqxTagCloud('width'); } }; destroy() { JQXLite(this.componentSelector).jqxTagCloud('destroy'); }; findTagIndex(tag) { return JQXLite(this.componentSelector).jqxTagCloud('findTagIndex', tag); }; getHiddenTagsList() { return JQXLite(this.componentSelector).jqxTagCloud('getHiddenTagsList'); }; getRenderedTags() { return JQXLite(this.componentSelector).jqxTagCloud('getRenderedTags'); }; getTagsList() { return JQXLite(this.componentSelector).jqxTagCloud('getTagsList'); }; hideItem(index) { JQXLite(this.componentSelector).jqxTagCloud('hideItem', index); }; insertAt(index, item) { JQXLite(this.componentSelector).jqxTagCloud('insertAt', index, item); }; removeAt(index) { JQXLite(this.componentSelector).jqxTagCloud('removeAt', index); }; updateAt(index, item) { JQXLite(this.componentSelector).jqxTagCloud('updateAt', index, item); }; showItem(index) { JQXLite(this.componentSelector).jqxTagCloud('showItem', index); }; render() { let id = 'jqxTagCloud' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
jenkins-design-language/src/js/components/material-ui/svg-icons/image/lens.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageLens = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/> </SvgIcon> ); ImageLens.displayName = 'ImageLens'; ImageLens.muiName = 'SvgIcon'; export default ImageLens;
packages/generator-emakinacee-react/generators/app/templates/static/src/containers/App/App.js
emakina-cee-oss/react-cli
import React from 'react'; import Home from '../Home/Home'; import logo from './logo.svg'; import styles from './App.module.scss'; const App = () => { return ( <div className={styles.app}> <div className={styles.header}> <img src={logo} className={styles.logo} alt="logo" /> <h2>Welcome to React</h2> </div> <Home /> </div> ); }; export default App;
src/components/StatementHeader/StatementHeader.js
nambawan/g-old
/* eslint-disable */ import React from 'react'; import Proptypes from 'prop-types'; const renderLikeButton = (likeFn, liked) => ( <button onClick={likeFn} className={cn(s.like, liked ? 'fa fa-thumbs-up' : 'fa fa-thumbs-o-up')} /> ); const renderFollowButton = (ownStatement, isFollowee, followFn) => (ownStatement || isFollowee ? null : <button onClick={followFn}> +follow </button>); const StatementHeader = props => { const { id, text, author, flag, user, likes, canLike, ownLike, ownStatement, isFollowee, handleLikeClick, updateUser, } = props; throw Error('NOT FINISHED'); return ( <div className={s.header}> <div> <span className={s.author}> {author.name} {author.surname} </span> <span> {likes ? ` (+${likes})` : ''} {canLike && renderLikeButton(ownLike, () => { handleLikeClick(e, ownLike); })} </span> </div> {renderFollowButton( ownStatement, isFollowee, updateUser({ id: user.id, followee: author.id }), )} {!ownStatement && <button onClick={() => flag({ statementId: id, content: text, })} > !Flag! </button>} <span className={s.menu}> {(this.props.asInput || ownStatement || ['admin', 'mod'].includes(user.role.type)) && <span style={{ marginRight: '0.5em' }}> {this.state.edit ? <span> <button onClick={this.onTextSubmit} disabled={!hasMinimumInput}> <i className="fa fa-check" /> </button> <button onClick={this.onEndEditing} disabled={this.props.asInput && !hasMinimumInput} > <i className="fa fa-times" /> </button> </span> : <button onClick={this.onEditStatement}> <i className="fa fa-pencil" /> </button>} {!this.props.asInput && <button onClick={this.onDeleteStatement}> <i className="fa fa-trash" /> </button>} </span>} </span> </div> ); }; /* eslint-enable */
src/collections/Form/FormDropdown.js
Semantic-Org/Semantic-UI-React
import PropTypes from 'prop-types' import React from 'react' import { getElementType, getUnhandledProps } from '../../lib' import Dropdown from '../../modules/Dropdown' import FormField from './FormField' /** * Sugar for <Form.Field control={Dropdown} />. * @see Dropdown * @see Form */ function FormDropdown(props) { const { control } = props const rest = getUnhandledProps(FormDropdown, props) const ElementType = getElementType(FormDropdown, props) return <ElementType {...rest} control={control} /> } FormDropdown.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** A FormField control prop. */ control: FormField.propTypes.control, } FormDropdown.defaultProps = { as: FormField, control: Dropdown, } export default FormDropdown
src/components/tos.js
colinmegill/polis-admin-console
/* * Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file * in the same directory. */ import React from 'react'; import Radium from 'radium'; import _ from 'lodash'; import { doSignout } from '../actions'; import StaticContentContainer from "./framework/static-content-container"; const styles = { card: { position: "relative", zIndex: 10, backgroundColor: "rgba(0,0,0,.3)", padding: "50px", borderRadius: 3, color: "white", maxWidth: 700, margin: 50 }, } @Radium class TOS extends React.Component { render() { return ( <StaticContentContainer> <div style={styles.card}> <p>"Last Updated: 6/26/2014"</p> <p>"Po.lis Terms of Use"</p> <p>"Welcome, and thank you for your interest in Polis Technology Inc ('Pol.is', 'we,' or 'us') and our Web site at <a href='http://pol.is/'>http://pol.is/</a> (the 'Site'), as well as all related web sites, networks, embeddable widgets, downloadable software, mobile applications (including tablet applications), and other services provided by us and on which a link to these Terms of Use is displayed (collectively, together with the Site, our 'Service'). These Terms of Use are a legally binding contract between you and Pol.is regarding your use of the Service."</p> <p>"PLEASE READ THE FOLLOWING TERMS OF USE CAREFULLY. BY CLICKING 'I ACCEPT,' YOU ACKNOWLEDGE THAT YOU HAVE READ, UNDERSTOOD, AND AGREE TO BE BOUND BY THE FOLLOWING TERMS AND CONDITIONS, INCLUDING THE POL.IS PRIVACY POLICY <a href= 'https://pol.is/privacy'>https://pol.is/privacy</a> (COLLECTIVELY, THESE 'TERMS'). If you are not eligible, or do not agree to these Terms, then please do not use the Service."</p> <p>"These Terms of Use provide that all disputes between you and Pol.is will be resolved by BINDING ARBITRATION. YOU AGREE TO GIVE UP YOUR RIGHT TO GO TO COURT to assert or defend your rights under this contract (except for matters that may be taken to small claims court). Your rights will be determined by a NEUTRAL ARBITRATOR and NOT a judge or jury and your claims cannot be brought as a class action. Please review the Arbitration Agreement below for the details regarding your agreement to arbitrate any disputes with Pol.is."</p> <ol> <li>"Eligibility. You must be at least thirteen (13) years of age to use the Service. By agreeing to these Terms, you represent and warrant to us: (i) that you are at least thirteen (13) years of age; (ii) that you have not previously been suspended or removed from the Service; and (iii) that your registration and your use of the Service is in compliance with any and all applicable laws and regulations. If you are using the Service on behalf of an entity, organization, or company, you represent and warrant that you have the authority to bind such organization to these Terms and you agree to be bound by these Terms on behalf of such organization."</li> <li>"Accounts and Registration. To access most features of the Service, you must register for an account. When you register for an account, you may be required to provide us with some information about yourself (such as your e-mail address or other contact information). You agree that the information you provide to us is accurate and that you will keep it accurate and up-to-date at all times. When you register, you will be asked to provide a password. You are solely responsible for maintaining the confidentiality of your account and password. You agree to accept responsibility for all activities that occur under your account. If you have reason to believe that your account is no longer secure, then you must immediately notify us at info@pol.is."</li> <li>"Payment. Access to the Service, or to certain features of the Service, may require you to pay fees. Before you are required to pay any fees, you will have an opportunity to review and accept the applicable fees that you will be charged. All fees are in U.S. Dollars and are non-refundable. Pol.is may change the fees for the Service or any feature of the Service, including by adding additional fees or charges, on a going-forward basis at any time. Pol.is will charge the payment method you specify at the time of purchase. You authorize Pol.is to charge all sums described herein to such payment method. If you pay any applicable fees with a credit card, Pol.is may seek pre-authorization of your credit card account prior to your purchase to verify that the credit card is valid and has the necessary funds or credit available to cover your purchase."</li> <li>User Content <ol> <li>"User Content Generally. Certain features of the Service may permit users to post content, including messages, questions, responses, data, text, and other types of works (collectively, 'User Content') and to publish User Content on the Service. You retain copyright and any other proprietary rights that you may hold in the User Content that you post to the Service."</li> <li>"Limited License Grant to Pol.is. By posting or publishing User Content, you grant Pol.is a worldwide, non-exclusive, royalty-free right and license (with the right to sublicense) to host, store, transfer, display, perform, reproduce, modify, and distribute your User Content, in whole or in part, in any media formats and through any media channels (now known or hereafter developed). Any such use of your User Content by Pol.is may be without any compensation paid to you."</li> <li>"Limited License Grant to Other Users. By posting User Content or sharing User Content with another user of the Service, you hereby grant to other users of the Service a non-exclusive license to access and use such User Content as permitted by these Terms and the functionality of the Service."</li> <li>"User Content Representations and Warranties. You are solely responsible for your User Content and the consequences of posting or publishing User Content. By posting and publishing User Content, you affirm, represent, and warrant that:"</li> </ol> </li> <li>"you are the creator and owner of, or have the necessary licenses, rights, consents, and permissions to use and to authorize Pol.is and users of the Service to use and distribute your User Content as necessary to exercise the licenses granted by you in this Section 4 and in the manner contemplated by Pol.is and these Terms; and "</li> <li>"your User Content, and the use thereof as contemplated herein, does not and will not: (i) infringe, violate, or misappropriate any third-party right, including any copyright, trademark, patent, trade secret, moral right, privacy right, right of publicity, or any other intellectual property or proprietary right; or (ii) slander, defame, libel, or invade the right of privacy, publicity or other property rights of any other person." <ol> <li>"User Content Disclaimer. We are under no obligation to edit or control User Content that you or other users post or publish, and will not be in any way responsible or liable for User Content. Pol.is may, however, at any time and without prior notice, screen, remove, edit, or block any User Content that in our sole judgment violates these Terms or is otherwise objectionable. You understand that when using the Service you will be exposed to User Content from a variety of sources and acknowledge that User Content may be inaccurate, offensive, indecent or objectionable. You agree to waive, and hereby do waive, any legal or equitable rights or remedies you have or may have against Pol.is with respect to User Content. We expressly disclaim any and all liability in connection with User Content. If notified by a user or content owner that User Content allegedly does not conform to these Terms, we may investigate the allegation and determine in our sole discretion whether to remove the User Content, which we reserve the right to do at any time and without notice. For clarity, Pol.is does not permit copyright-infringing activities on the Service."</li> </ol> </li> <li>"Prohibited Conduct. BY USING THE SERVICE YOU AGREE NOT TO:" <ol> <li>"use the Service for any illegal purpose, or in violation of any local, state, national, or international law;"</li> <li>"violate, or encourage others to violate, the rights of third parties, including by infringing or misappropriating third party intellectual property rights;"</li> <li>"post, upload, or distribute any User Content or other content that is unlawful, defamatory, libelous, inaccurate, or that a reasonable person could deem to be objectionable, profane, indecent, pornographic, harassing, threatening, embarrassing, hateful, or otherwise inappropriate;"</li> <li>"interfere with security-related features of the Service, including without limitation by (i) disabling or circumventing features that prevent or limit use or copying of any content, or (ii) reverse engineering or otherwise attempting to discover the source code of the Service or any part thereof except to the extent that such activity is expressly permitted by applicable law; "</li> <li>"interfere with the operation of the Service or any user's enjoyment of the Service, including without limitation by (i) uploading or otherwise disseminating viruses, adware, spyware, worms, or other malicious code, (ii) making unsolicited offers or advertisements to other users of the Service, (iii) attempting to collect, personal information about users or third parties without their consent; or (iv) interfering with or disrupting any networks, equipment, or servers connected to or used to provide the Service, or violating the regulations, policies, or procedures of such networks, equipment, or servers;"</li> <li>"perform any fraudulent activity including impersonating any person or entity, claiming false affiliations, accessing the Service accounts of others without permission, or falsifying your age or date of birth; "</li> <li>"sell or otherwise transfer the access granted herein or any Materials (as defined in Section 10 below) or any right or ability to view, access, or use any Materials; or"</li> <li>"attempt to do any of the foregoing in this Section 5, or assist or permit any persons in engaging in any of the activities described in this Section 5."</li> </ol> </li> <li>"Third-Party Services and Linked Websites. Pol.is may provide tools through the Service that enable you to export information, including User Content, to third party services such as Twitter or Facebook or to web sites. By using these tools, you agree that we may transfer such information to the applicable third-party service or web site. Such third party services and web sites are not under our control, and we are not responsible for their use of your exported information. The Service may also contain links to third-party websites. Such linked websites are not under our control, and we are not responsible for their content."</li> <li>"Termination of Use; Discontinuation and Modification of the Service. If you violate any provision of these Terms, your permission to use the Service will terminate automatically. Additionally, Pol.is, in its sole discretion may terminate your user account on the Service or suspend or terminate your access to the Service at any time, with or without notice. We also reserve the right to modify or discontinue the Service at any time (including, without limitation, by limiting or discontinuing certain features of the Service) without notice to you. We will have no liability whatsoever on account of any change to the Service or any suspension or termination of your access to or use of the Service. You may terminate your account at any time by contacting customer service at info@pol.is. If you terminate your account, you will remain obligated to pay all outstanding fees, if any, relating to your use of the Service incurred prior to termination. To the extent permitted by applicable laws and regulations, no unused portions of pre-paid fees will be refunded following termination."</li> <li>"Privacy Policy; Additional Terms" <ol> <li>"Privacy Policy. Please read the Pol.is Privacy Policy [<a href= 'https://pol.is/privacy'>https://pol.is/privacy</a>] carefully for information relating to our collection, use, storage and disclosure of your personal information. The Pol.is Privacy Policy is hereby incorporated by reference into, and made a part of, these Terms."</li> <li>"Additional Terms. Your use of the Service is subject to any and all additional terms, policies, rules, or guidelines applicable to the Service or certain features of the Service that we may post on or link to on the Service (the 'Additional Terms'), such as end-user license agreements for any downloadable applications that we may offer, or rules applicable to particular features or content on the Service, subject to Section 9 below. All such Additional Terms are hereby incorporated by reference into, and made a part of, these Terms."</li> </ol> </li> <li>"Modification of these Terms. We reserve the right, at our discretion, to change these Terms on a going-forward basis at any time. Please check these Terms periodically for changes. In the event that a change to these Terms materially modifies your rights or obligations, you will be required to accept such modified terms in order to continue to use the Service. Material modifications are effective upon your acceptance of such the modified Terms. Immaterial modifications are effective upon publication. For the avoidance of doubt, disputes arising under these Terms will be resolved in accordance with these Terms in effect that the time the dispute arose."</li> <li>"Ownership; Proprietary Rights. The Service is owned and operated by Pol.is. The visual interfaces, application programming interfaces, graphics, design, compilation, information, data, computer code (including source code or object code), products, software, services, and all other elements of the Service (the 'Materials') provided by Pol.is are protected by all relevant intellectual property and proprietary rights and applicable laws. All Materials contained in the Service are the property of Pol.is or our third-party licensors. Except as expressly authorized by Pol.is, you may not make use of the Materials. Pol.is reserves all rights to the Materials not granted expressly in these Terms."</li> <li>"Indemnity. You agree that you will be responsible for your use of the Service, and you agree to defend, indemnify, and hold harmless Pol.is and its officers, directors, employees, consultants, affiliates, subsidiaries and agents (collectively, the Pol.is Entities') from and against any and all claims, liabilities, damages, losses, and expenses, including reasonable attorneys' fees and costs, arising out of or in any way connected with (i) your access to, use of, or alleged use of the Service; (ii) your violation of these Terms or any representation, warranty, or agreements referenced herein, or any applicable law or regulation; (iii) your violation of any third-party right, including without limitation any intellectual property right, publicity, confidentiality, property or privacy right; or (iv) any disputes or issues between you and any third party. We reserve the right, at our own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you (and without limiting your indemnification obligations with respect to such matter), and in such case, you agree to cooperate with our defense of such claim."</li> <li>"Disclaimers; No Warranties THE SERVICE AND ALL MATERIALS AND CONTENT AVAILABLE THROUGH THE SERVICE ARE PROVIDED 'AS IS' AND ON AN 'AS AVAILABLE' BASIS, WITHOUT WARRANTY OR CONDITION OF ANY KIND, EITHER EXPRESS OR IMPLIED. THE POL.IS ENTITIES SPECIFICALLY (BUT WITHOUT LIMITATION) DISCLAIM ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, RELATING TO THE SERVICE AND ALL MATERIALS AND CONTENT AVAILABLE THROUGH THE SERVICE, INCLUDING BUT NOT LIMITED TO (i) ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, QUIET ENJOYMENT, OR NON-INFRINGEMENT; AND (ii) ANY WARRANTIES ARISING OUT OF COURSE OF DEALING, USAGE, OR TRADE. THE POL.IS ENTITIES DO NOT WARRANT THAT THE SERVICE OR ANY PART THEREOF, OR ANY MATERIALS OR CONTENT OFFERED THROUGH THE SERVICE, WILL BE UNINTERRUPTED, SECURE, OR FREE OF ERRORS, VIRUSES, OR OTHER HARMFUL COMPONENTS, AND DO NOT WARRANT THAT ANY OF THE FOREGOING WILL BE CORRECTED."</li> </ol> <p>"NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM THE SERVICE OR ANY MATERIALS OR CONTENT AVAILABLE ON OR THROUGH THE SERVICE WILL CREATE ANY WARRANTY REGARDING ANY OF THE POL.IS ENTITIES OR THE SERVICE THAT IS NOT EXPRESSLY STATED IN THESE TERMS. YOU ASSUME ALL RISK FOR ALL DAMAGES THAT MAY RESULT FROM YOUR USE OF OR ACCESS TO THE SERVICE, YOUR DEALINGS WITH OTHER SERVICE USERS, AND ANY MATERIALS OR CONTENT AVAILABLE THROUGH THE SERVICE. YOU UNDERSTAND AND AGREE THAT YOU USE THE SERVICE AND USE, ACCESS, DOWNLOAD, OR OTHERWISE OBTAIN MATERIALS OR CONTENT THROUGH THE SERVICE AND ANY ASSOCIATED SITES OR SERVICES AT YOUR OWN DISCRETION AND RISK, AND YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR PROPERTY (INCLUDING YOUR COMPUTER SYSTEM USED IN CONNECTION WITH THE SERVICE) OR LOSS OF DATA THAT RESULTS FROM THE USE OF THE SERVICE OR THE DOWNLOAD OR USE OF SUCH MATERIALS OR CONTENT.<br /> SOME JURISDICTIONS MAY PROHIBIT A DISCLAIMER OF WARRANTIES AND YOU MAY HAVE OTHER RIGHTS THAT VARY FROM JURISDICTION TO JURISDICTION."</p> <ol> <li>"Limitation of Liability: IN NO EVENT WILL THE POL.IS ENTITIES BE LIABLE TO YOU FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA, OR OTHER INTANGIBLE LOSSES) ARISING OUT OF OR RELATING TO YOUR ACCESS TO OR USE OF, OR YOUR INABILITY TO ACCESS OR USE, THE SERVICE OR ANY MATERIALS OR CONTENT ON THE SERVICE, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), STATUTE OR ANY OTHER LEGAL THEORY, WHETHER OR NOT THE POL.IS ENTITIES HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGE. YOU AGREE THAT THE AGGREGATE LIABILITY OF THE POL.IS ENTITIES TO YOU FOR ANY AND ALL CLAIMS ARISING OUT OF RELATING TO THE USE OF OR ANY INABILITY TO USE THE SERVICE (INCLUDING ANY MATERIALS OR CONTENT AVAILABLE THROUGH THE SERVICE) OR OTHERWISE UNDER THESE TERMS, WHETHER IN CONTRACT, TORT, OR OTHERWISE, IS LIMITED TO THE GREATER OF (i) THE AMOUNTS YOU HAVE PAID TO POL.IS FOR ACCESS TO AND USE OF THE SERVICE IN THE 12 MONTHS PRIOR TO THE CLAIM OR (ii) $100. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES. ACCORDINGLY, THE ABOVE LIMITATION MAY NOT APPLY TO YOU. EACH PROVISION OF THESE TERMS THAT PROVIDES FOR A LIMITATION OF LIABILITY, DISCLAIMER OF WARRANTIES, OR EXCLUSION OF DAMAGES IS TO ALLOCATE THE RISKS UNDER THESE TERMS BETWEEN THE PARTIES. THIS ALLOCATION IS AN ESSENTIAL ELEMENT OF THE BASIS OF THE BARGAIN BETWEEN THE PARTIES. EACH OF THESE PROVISIONS IS SEVERABLE AND INDEPENDENT OF ALL OTHER PROVISIONS OF THESE TERMS. THE LIMITATIONS IN THIS SECTION 13 WILL APPLY EVEN IF ANY LIMITED REMEDY FAILS OF ITS ESSENTIAL PURPOSE."</li> <li>"Governing Law. These Terms shall be governed by the laws of the State of Washington without regard to conflict of law principles. To the extent that any lawsuit or court proceeding is permitted hereunder, you and Pol.is agree to submit to the personal and exclusive jurisdiction of the state courts and federal courts located within King County, Washington for the purpose of litigating all such disputes. We operate the Service from our offices in Washington, and we make no representation that Materials included in the Service are appropriate or available for use in other locations."</li> <li>"General. These Terms, together with the Privacy Policy and any other agreements expressly incorporated by reference herein, constitute the entire and exclusive understanding and agreement between you and Pol.is regarding your use of and access to the Service, and except as expressly permitted above may be amended only by a written agreement signed by authorized representatives of all parties to these Terms. You may not assign or transfer these Terms or your rights hereunder, in whole or in part, by operation of law or otherwise, without our prior written consent. We may assign these Terms at any time without notice. The failure to require performance of any provision will not affect our right to require performance at any time thereafter, nor shall a waiver of any breach or default of these Terms or any provision of these Terms constitute a waiver of any subsequent breach or default or a waiver of the provision itself. Use of section headers in these Terms is for convenience only and shall not have any impact on the interpretation of particular provisions. In the event that any part of these Terms is held to be invalid or unenforceable, the unenforceable part shall be given effect to the greatest extent possible and the remaining parts will remain in full force and effect. Upon termination of these Terms, any provision that by its nature or express terms should survive will survive such termination or expiration, including, but not limited to, Sections 1, 3, and Error! Reference source not found. through 17."</li> <li>"Dispute Resolution and Arbitration" <ol> <li>"Generally. In the interest of resolving disputes between you and Pol.is in the most expedient and cost effective manner, you and Pol.is agree that any and all disputes arising in connection with these Terms shall be resolved by binding arbitration. Arbitration is more informal than a lawsuit in court. Arbitration uses a neutral arbitrator instead of a judge or jury, may allow for more limited discovery than in court, and can be subject to very limited review by courts. Arbitrators can award the same damages and relief that a court can award. Our agreement to arbitrate disputes includes, but is not limited to all claims arising out of or relating to any aspect of these Terms, whether based in contract, tort, statute, fraud, misrepresentation or any other legal theory, and regardless of whether the claims arise during or after the termination of these Terms. YOU UNDERSTAND AND AGREE THAT, BY ENTERING INTO THESE TERMS, YOU AND POL.IS ARE EACH WAIVING THE RIGHT TO A TRIAL BY JURY OR TO PARTICIPATE IN A CLASS ACTION."</li> <li>"Exceptions. Notwithstanding subsection 16.1, we both agree that nothing herein will be deemed to waive, preclude, or otherwise limit either of our right to (i) bring an individual action in small claims court, (ii) pursue enforcement actions through applicable federal, state, or local agencies where such actions are available, (iii) seek injunctive relief in a court of law, or (iv) to file suit in a court of law to address intellectual property infringement claims."</li> <li>"Arbitrator. Any arbitration between you and Pol.is will be governed by the Commercial Dispute Resolution Procedures and the Supplementary Procedures for Consumer Related Disputes (collectively, 'AAA Rules') of the American Arbitration Association ('AAA'), as modified by these Terms, and will be administered by the AAA. The AAA Rules and filing forms are available online at www.adr.org, by calling the AAA at 1-800-778-7879, or by contacting Pol.is."</li> <li>"Notice; Process. A party who intends to seek arbitration must first send a written notice of the dispute to the other, by certified mail or Federal Express (signature required), or in the event that we do not have a physical address on file for you, by electronic mail ('Notice'). The address of Pol.is for Notice is: Polis Technology Inc 3601 Fremont Ave. N, Suite 300 Seattle, WA 98103. The Notice must (i) describe the nature and basis of the claim or dispute; and (ii) set forth the specific relief sought ('Demand'). We agree to use good faith efforts to resolve the claim directly, but if we do not reach an agreement to do so within 30 days after the Notice is received, you or Pol.is may commence an arbitration proceeding. During the arbitration, the amount of any settlement offer made by you or Pol.is shall not be disclosed to the arbitrator until after the arbitrator makes a final decision and award, if any. In the event our dispute is finally resolved through arbitration in your favor, Pol.is shall pay you (i) the amount awarded by the arbitrator, if any, (ii) the last written settlement amount offered by Pol.is in settlement of the dispute prior to the arbitrator's award; or (iii) $1,000.00, whichever is greater."</li> <li>"Fees. In the event that you commence arbitration in accordance with these Terms, Pol.is will reimburse you for your payment of the filing fee, unless your claim is for greater than $10,000, in which case the payment of any fees shall be decided by the AAA Rules. Any arbitration hearings will take place at a location to be agreed upon in King County, Washington, provided that if the claim is for $10,000 or less, you may choose whether the arbitration will be conducted (i) solely on the basis of documents submitted to the arbitrator; (ii) through a non-appearance based telephonic hearing; or (iii) by an in-person hearing as established by the AAA Rules in the county (or parish) of your billing address. If the arbitrator finds that either the substance of your claim or the relief sought in the Demand is frivolous or brought for an improper purpose (as measured by the standards set forth in Federal Rule of Civil Procedure 11(b)), then the payment of all fees will be governed by the AAA Rules. In such case, you agree to reimburse Pol.is for all monies previously disbursed by it that are otherwise your obligation to pay under the AAA Rules. Regardless of the manner in which the arbitration is conducted, the arbitrator shall issue a reasoned written decision sufficient to explain the essential findings and conclusions on which the decision and award, if any, are based. The arbitrator may make rulings and resolve disputes as to the payment and reimbursement of fees or expenses at any time during the proceeding and upon request from either party made within 14 days of the arbitrator's ruling on the merits."</li> <li>"No Class Actions. YOU AND POL.IS AGREE THAT EACH MAY BRING CLAIMS AGAINST THE OTHER ONLY IN YOUR OR ITS INDIVIDUAL CAPACITY AND NOT AS A PLAINTIFF OR CLASS MEMBER IN ANY PURPORTED CLASS OR REPRESENTATIVE PROCEEDING. Further, unless both you and Pol.is agree otherwise, the arbitrator may not consolidate more than one person's claims, and may not otherwise preside over any form of a representative or class proceeding."</li> <li>"Modifications. In the event that Pol.is makes any future change to this arbitration provision (other than a change to the address of Pol.is for Notice), you may reject any such change by sending us written notice within 30 days of the change to the address of Pol.is for Notice, in which case your account with Pol.is shall be immediately terminated and this arbitration provision, as in effect immediately prior to the amendments you reject shall survive."</li> <li>"Enforceability. If Subsection 16.6 is found to be unenforceable or if the entirety of this Section 16 is found to be unenforceable, then the entirety of this Section 16 shall be null and void and, in such case, the parties agree that the exclusive jurisdiction and venue described in Section 14 shall govern any action arising out of or related to these Terms."</li> </ol> </li> <li>"Consent to Electronic Communications. By using the Service, you consent to receiving certain electronic communications from us as further described in our Privacy Policy. Please read our Privacy Policy to learn more about your choices regarding our electronic communications practices. You agree that any notices, agreements, disclosures, or other communications that we send to you electronically will satisfy any legal communication requirements, including that such communications be in writing. "</li> <li>"Contact Information. The services hereunder are offered by Polis Technology Inc located at 3601 Fremont Ave. N, Suite 300 Seattle, WA 98103. You may contact us by sending correspondence to the foregoing address or by emailing us at info@pol.is. If you are a California resident, you may have these Terms mailed to you electronically by sending a letter to the foregoing address with your electronic mail address and a request for these Terms."</li> </ol> </div> </StaticContentContainer> ); } } export default TOS;
website-prototyping-tools/RelayPlayground.js
lucasterra/relay
import './RelayPlayground.css'; import 'codemirror/mode/javascript/javascript'; import Codemirror from 'react-codemirror'; import React from 'react'; import ReactDOM from 'react/lib/ReactDOM'; import Relay from 'react-relay'; window.Relay = Relay; import babel from 'babel-core/browser'; import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin'; import debounce from 'lodash.debounce'; import defer from 'lodash.defer'; import delay from 'lodash.delay'; import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher'; import errorCatcherPlugin from 'babel-plugin-react-error-catcher'; import evalSchema from './evalSchema'; import getBabelRelayPlugin from 'babel-relay-plugin'; import {introspectionQuery} from 'graphql/utilities'; import {graphql} from 'graphql'; var {PropTypes} = React; const CODE_EDITOR_OPTIONS = { extraKeys: { Tab(cm) { // Insert spaces when the tab key is pressed var spaces = Array(cm.getOption('indentUnit') + 1).join(' '); cm.replaceSelection(spaces); }, }, indentWithTabs: false, lineNumbers: true, mode: 'javascript', tabSize: 2, theme: 'solarized light', }; const ERROR_TYPES = { graphql: 'GraphQL Validation', query: 'Query', runtime: 'Runtime', schema: 'Schema', syntax: 'Syntax', }; const RENDER_STEP_EXAMPLE_CODE = `ReactDOM.render( <Relay.RootContainer Component={MyRelayContainer} route={new MyHomeRoute()} />, mountNode );`; class PlaygroundRenderer extends React.Component { componentDidMount() { this._container = document.createElement('div'); this.refs.mountPoint.appendChild(this._container); this._updateTimeoutId = defer(this._update); } componentDidUpdate(prevProps) { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } this._updateTimeoutId = defer(this._update); } componentWillUnmount() { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } try { ReactDOM.unmountComponentAtNode(this._container); } catch(e) {} } _update = () => { ReactDOM.render(React.Children.only(this.props.children), this._container); } render() { return <div ref="mountPoint" />; } } export default class RelayPlayground extends React.Component { static propTypes = { initialAppSource: PropTypes.string, initialSchemaSource: PropTypes.string, onAppSourceChange: PropTypes.func, onSchemaSourceChange: PropTypes.func, }; state = { appElement: null, appSource: this.props.initialAppSource, busy: false, editTarget: 'app', error: null, schemaSource: this.props.initialSchemaSource, }; componentDidMount() { // Hijack console.warn to collect GraphQL validation warnings (we hope) this._originalConsoleWarn = console.warn; var collectedWarnings = []; console.warn = (...args) => { collectedWarnings.push([Date.now(), args]); this._originalConsoleWarn.apply(console, args); } // Hijack window.onerror to catch any stray fatals this._originalWindowOnerror = window.onerror; window.onerror = (message, url, lineNumber, something, error) => { // GraphQL validation warnings are followed closely by a thrown exception. // Console warnings that appear too far before this exception are probably // not related to GraphQL. Throw those out. if (/GraphQL validation error/.test(message)) { var recentWarnings = collectedWarnings .filter(([createdAt, args]) => Date.now() - createdAt <= 500) .reduce((memo, [createdAt, args]) => memo.concat(args), []); this.setState({ error: {stack: recentWarnings.join('\n')}, errorType: ERROR_TYPES.graphql, }); } else { this.setState({error, errorType: ERROR_TYPES.runtime}); } collectedWarnings = []; return false; }; this._updateSchema(this.state.schemaSource, this.state.appSource); } componentDidUpdate(prevProps, prevState) { var appChanged = this.state.appSource !== prevState.appSource; var schemaChanged = this.state.schemaSource !== prevState.schemaSource; if (appChanged || schemaChanged) { this.setState({busy: true}); this._handleSourceCodeChange( this.state.appSource, schemaChanged ? this.state.schemaSource : null, ); } } componentWillUnmount() { clearTimeout(this._errorReporterTimeout); clearTimeout(this._warningScrubberTimeout); this._handleSourceCodeChange.cancel(); console.warn = this._originalConsoleWarn; window.onerror = this._originalWindowOnerror; } _handleSourceCodeChange = debounce((appSource, schemaSource) => { if (schemaSource != null) { this._updateSchema(schemaSource, appSource); } else { this._updateApp(appSource); } }, 300, {trailing: true}) _updateApp = (appSource) => { clearTimeout(this._errorReporterTimeout); // We're running in a browser. Create a require() shim to catch any imports. var require = (path) => { switch (path) { // The errorCatcherPlugin injects a series of import statements into the // program body. Return locally bound variables in these three cases: case '//error-catcher.js': return (React, filename, displayName, reporter) => { // When it fatals, render an empty <span /> in place of the app. return errorCatcher(React, filename, <span />, reporter); }; case 'react': return React; case 'reporterProxy': return (error, instance, filename, displayName) => { this._errorReporterTimeout = defer( this.setState.bind(this), {error, errorType: ERROR_TYPES.runtime} ); }; default: throw new Error(`Cannot find module "${path}"`); } }; try { var {code} = babel.transform(appSource, { filename: 'RelayPlayground', plugins : [ babelRelayPlaygroundPlugin, this._babelRelayPlugin, errorCatcherPlugin('reporterProxy'), ], retainLines: true, sourceMaps: 'inline', stage: 0, }); var result = eval(code); if ( React.isValidElement(result) && result.type.name === 'RelayRootContainer' ) { this.setState({ appElement: React.cloneElement(result, {forceFetch: true}), }); } else { this.setState({ appElement: ( <div> <h2> Render a Relay.RootContainer into <code>mountNode</code> to get started. </h2> <p> Example: </p> <pre>{RENDER_STEP_EXAMPLE_CODE}</pre> </div> ), }); } this.setState({error: null}); } catch(error) { this.setState({error, errorType: ERROR_TYPES.syntax}); } this.setState({busy: false}); } _updateCode = (newSource) => { var sourceStorageKey = `${this.state.editTarget}Source`; this.setState({[sourceStorageKey]: newSource}); if (this.state.editTarget === 'app' && this.props.onAppSourceChange) { this.props.onAppSourceChange(newSource); } if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) { this.props.onSchemaSourceChange(newSource); } } _updateEditTarget = (editTarget) => { this.setState({editTarget}); } _updateSchema = (schemaSource, appSource) => { try { var Schema = evalSchema(schemaSource); } catch(error) { this.setState({error, errorType: ERROR_TYPES.schema}); return; } graphql(Schema, introspectionQuery).then((result) => { if ( this.state.schemaSource !== schemaSource || this.state.appSource !== appSource ) { // This version of the code is stale. Bail out. return; } this._babelRelayPlugin = getBabelRelayPlugin(result.data); Relay.injectNetworkLayer({ sendMutation: (mutationRequest) => { var graphQLQuery = mutationRequest.getQueryString(); var variables = mutationRequest.getVariables(); graphql(Schema, graphQLQuery, null, variables).then(result => { if (result.errors) { mutationRequest.reject(new Error(result.errors)); this.setState({ error: {stack: result.errors.map(e => e.message).join('\n')}, errorType: ERROR_TYPES.query, }); } else { mutationRequest.resolve({response: result.data}); } }); }, sendQueries: (queryRequests) => { return Promise.all(queryRequests.map(queryRequest => { var graphQLQuery = queryRequest.getQueryString(); graphql(Schema, graphQLQuery).then(result => { if (result.errors) { queryRequest.reject(new Error(result.errors)); this.setState({ error: {stack: result.errors.map(e => e.message).join('\n')}, errorType: ERROR_TYPES.query, }); } else { queryRequest.resolve({response: result.data}); } }); })); }, supports: () => false, }); this._updateApp(appSource); }); } render() { var sourceCode = this.state.editTarget === 'schema' ? this.state.schemaSource : this.state.appSource; return ( <div className="rpShell"> <section className="rpCodeEditor"> <nav className="rpCodeEditorNav"> <button className={this.state.editTarget === 'app' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'app')}> Code </button> <button className={this.state.editTarget === 'schema' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'schema')}> Schema </button> </nav> <Codemirror onChange={this._updateCode} options={CODE_EDITOR_OPTIONS} value={sourceCode} /> </section> <section className="rpResult"> <h1 className="rpResultHeader"> Relay Playground <span className={ 'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '') } /> </h1> <div className="rpResultOutput"> {this.state.error ? <div className="rpError"> <h1>{this.state.errorType} Error</h1> <pre className="rpErrorStack">{this.state.error.stack}</pre> </div> : <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer> } </div> </section> </div> ); } }
packages/showcase/misc/animation-example.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import ShowcaseButton from '../showcase-components/showcase-button'; import { XYPlot, XAxis, YAxis, VerticalGridLines, HorizontalGridLines, MarkSeries } from 'react-vis'; function generateData() { return [...new Array(10)].map(() => ({ x: Math.random() * 5, y: Math.random() * 10 })); } const MODE = ['noWobble', 'gentle', 'wobbly', 'stiff']; export default class Example extends React.Component { state = { data: generateData(), modeIndex: 0 }; updateModeIndex = increment => () => { const newIndex = this.state.modeIndex + (increment ? 1 : -1); const modeIndex = newIndex < 0 ? MODE.length - 1 : newIndex >= MODE.length ? 0 : newIndex; this.setState({ modeIndex }); }; render() { const {modeIndex, data} = this.state; return ( <div className="centered-and-flexed"> <div className="centered-and-flexed-controls"> <ShowcaseButton onClick={this.updateModeIndex(false)} buttonContent={'PREV'} /> <div> {`ANIMATION TECHNIQUE: ${MODE[modeIndex]}`} </div> <ShowcaseButton onClick={this.updateModeIndex(true)} buttonContent={'NEXT'} /> </div> <XYPlot width={300} height={300}> <VerticalGridLines /> <HorizontalGridLines /> <XAxis /> <YAxis /> <MarkSeries animation={MODE[modeIndex]} data={data} /> </XYPlot> <ShowcaseButton onClick={() => this.setState({data: generateData()})} buttonContent={'UPDATE DATA'} /> </div> ); } }
src/containers/NewCampaign/Amount/BuyItem.js
kingpowerclick/kpc-web-backend
import React, { Component } from 'react'; import classNames from 'classnames'; import { Breadcrumb, NewCampaginMenu } from 'components'; import { SplitButton, MenuItem } from 'react-bootstrap'; export default class ByItem extends Component { render() { const styles = require('./newCampaign.scss'); return ( <div className="container-fluid"> <div className="row"> <div className={ classNames(styles['marketing-add-new-gwp-view']) }> <header className={ styles['page-header']}> <div className={ styles['page-title']}> <h1 className={ styles.header }><strong>Add New Campaign</strong></h1> <Breadcrumb breadcrumb={ "Marketing > Add New Campaign" }/> </div> <div className={ styles['sub-menu']}> <ul> <li><a href="#"><i className="fa fa-chevron-left"></i> Back </a></li> <li><a href="#"><i className="fa fa-eye"></i> Preview </a></li> <li><a href="#"><i className="fa fa-floppy-o"></i> Save and Exit </a></li> </ul> </div> </header> <div className={styles['panel-left']}> <NewCampaginMenu subMenu= { `Amountc` } mainMenu={ `Amount` }/> </div> <div className={styles['panel-right']}> <div className={styles['panel-content']}> <p className={styles['list-menu']}>Buy items X Get Discount Amount off</p> <div className={ classNames(styles['control-group'], 'row') }> <label className={styles['control-label']}>Turn On/Off</label> <div className={styles['control-on-off']}> <label className="radio-inline"><input type="radio">Off</input></label> <label className="radio-inline"><input type="radio">On</input></label> </div> <hr></hr> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}>Set Condition</label> </div> <div className={ classNames(styles['control-optional'], styles['top-border'])}> <div className={styles['content-option']}> <span>If you buy <strong>Item X</strong></span> <span>Get Discount </span> <label><input type="text" className="form-control"/></label> <span>THB</span> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}></label> </div> <div className={styles['control-optional']}> <div className={styles['content-option']}> <span>But not Exceed</span> <label><input type="text" className="form-control"/></label> <strong>THB</strong> <div className={styles['border-bottom-blue']}></div> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}>Select products to include</label> </div> <div className={styles['control-optional']}> <div className={styles['content-option']}> <label>Product is</label> <label> <SplitButton title="none" pullRight id="split-button-pull-right"> <MenuItem eventKey="1">Action</MenuItem> <MenuItem eventKey="2">Another action</MenuItem> <MenuItem eventKey="3">Something else here</MenuItem> <MenuItem eventKey="4">Separated link</MenuItem> </SplitButton> </label> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}>Result of included </label> </div> <div className={styles['control-optional']}> <div className={styles['content-option']}> <ul> <li>by Category : --</li> <li>by Brand : --</li> <li>by SKU : --</li> <li>by Specific Group : --</li> <li>by Mass Upload : --</li> </ul> <div className={styles['border-bottom-blue']}></div> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}>Select products to exclude</label> </div> <div className={styles['control-optional']}> <div className={styles['content-option']}> <label>Product is</label> <label> <SplitButton title="none" pullRight id="split-button-pull-right"> <MenuItem eventKey="1">Action</MenuItem> <MenuItem eventKey="2">Another action</MenuItem> <MenuItem eventKey="3">Something else here</MenuItem> <MenuItem eventKey="4">Separated link</MenuItem> </SplitButton> </label> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}>Select products to exclude</label> </div> <div className={styles['control-optional']}> <div className={styles['content-option']}> <ul> <li>by Category : --</li> <li>by Brand : --</li> <li>by SKU : --</li> <li>by Specific Group : --</li> <li>by Mass Upload : --</li> </ul> </div> </div> </div> <div className={ classNames(styles['control-group'], 'row') }> <div className={styles['control-label']}> <label className={styles['control-label']}></label> </div> <div className={styles['control-optional']}> <div className={styles['border-bottom']}></div> </div> </div> <div className={styles['divied-blue']}></div> <div className={styles['add-new-box']}> <a href="#"><i className="fa fa-plus-circle"></i>Add New another Condition</a> </div> </div> </div> <button className={ classNames(styles['btn-blue'], 'btn', 'btn-default') }> Save</button> </div> </div> </div> ); } }
src/svg-icons/communication/portable-wifi-off.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPortableWifiOff = (props) => ( <SvgIcon {...props}> <path d="M17.56 14.24c.28-.69.44-1.45.44-2.24 0-3.31-2.69-6-6-6-.79 0-1.55.16-2.24.44l1.62 1.62c.2-.03.41-.06.62-.06 2.21 0 4 1.79 4 4 0 .21-.02.42-.05.63l1.61 1.61zM12 4c4.42 0 8 3.58 8 8 0 1.35-.35 2.62-.95 3.74l1.47 1.47C21.46 15.69 22 13.91 22 12c0-5.52-4.48-10-10-10-1.91 0-3.69.55-5.21 1.47l1.46 1.46C9.37 4.34 10.65 4 12 4zM3.27 2.5L2 3.77l2.1 2.1C2.79 7.57 2 9.69 2 12c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 17.53 4 14.96 4 12c0-1.76.57-3.38 1.53-4.69l1.43 1.44C6.36 9.68 6 10.8 6 12c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-.65.17-1.25.44-1.79l1.58 1.58L10 12c0 1.1.9 2 2 2l.21-.02.01.01 7.51 7.51L21 20.23 4.27 3.5l-1-1z"/> </SvgIcon> ); CommunicationPortableWifiOff = pure(CommunicationPortableWifiOff); CommunicationPortableWifiOff.displayName = 'CommunicationPortableWifiOff'; CommunicationPortableWifiOff.muiName = 'SvgIcon'; export default CommunicationPortableWifiOff;
app/views/Player/LifeBar.js
thomasboyt/bipp
import React from 'react'; import RenderedCanvas from '../lib/RenderedCanvas'; const LifeBar = React.createClass({ propTypes: { width: React.PropTypes.number.isRequired, height: React.PropTypes.number.isRequired, hp: React.PropTypes.number.isRequired, }, renderCanvas(ctx) { const percentFilled = this.props.hp / 100; const borderWidth = 3; ctx.fillStyle = 'red'; ctx.fillRect(borderWidth, borderWidth, this.props.width - borderWidth * 2, this.props.height - borderWidth * 2); ctx.fillStyle = 'yellow'; ctx.fillRect(borderWidth, borderWidth, (this.props.width - borderWidth * 2) * percentFilled, this.props.height - borderWidth * 2); }, render() { return ( <RenderedCanvas render={this.renderCanvas} width={this.props.width} height={this.props.height} className="life-bar" /> ); } }); export default LifeBar;
src/svg-icons/communication/import-export.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationImportExport = (props) => ( <SvgIcon {...props}> <path d="M9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3z"/> </SvgIcon> ); CommunicationImportExport = pure(CommunicationImportExport); CommunicationImportExport.displayName = 'CommunicationImportExport'; CommunicationImportExport.muiName = 'SvgIcon'; export default CommunicationImportExport;
src/components/mysql/plain-wordmark/MysqlPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './MysqlPlainWordmark.svg' /** MysqlPlainWordmark */ function MysqlPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'MysqlPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } MysqlPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default MysqlPlainWordmark
actor-apps/app-web/src/app/components/DialogSection.react.js
Rogerlin2013/actor-platform
import _ from 'lodash'; import React from 'react'; import { PeerTypes } from 'constants/ActorAppConstants'; import MessagesSection from 'components/dialog/MessagesSection.react'; import TypingSection from 'components/dialog/TypingSection.react'; import ComposeSection from 'components/dialog/ComposeSection.react'; import DialogStore from 'stores/DialogStore'; import MessageStore from 'stores/MessageStore'; import GroupStore from 'stores/GroupStore'; import DialogActionCreators from 'actions/DialogActionCreators'; // On which scrollTop value start loading older messages const LoadMessagesScrollTop = 100; const initialRenderMessagesCount = 20; const renderMessagesStep = 20; let renderMessagesCount = initialRenderMessagesCount; let lastPeer = null; let lastScrolledFromBottom = 0; const getStateFromStores = () => { const messages = MessageStore.getAll(); let messagesToRender; if (messages.length > renderMessagesCount) { messagesToRender = messages.slice(messages.length - renderMessagesCount); } else { messagesToRender = messages; } return { peer: DialogStore.getSelectedDialogPeer(), messages: messages, messagesToRender: messagesToRender }; }; class DialogSection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); DialogStore.addSelectListener(this.onSelectedDialogChange); MessageStore.addChangeListener(this.onMessagesChange); } componentWillUnmount() { DialogStore.removeSelectListener(this.onSelectedDialogChange); MessageStore.removeChangeListener(this.onMessagesChange); } componentDidUpdate() { this.fixScroll(); this.loadMessagesByScroll(); } render() { const peer = this.state.peer; if (peer) { let isMember = true, memberArea; if (peer.type === PeerTypes.GROUP) { const group = GroupStore.getGroup(peer.id); isMember = DialogStore.isGroupMember(group); } if (isMember) { memberArea = ( <div> <TypingSection/> <ComposeSection peer={this.state.peer}/> </div> ); } else { memberArea = ( <section className="compose compose--disabled row center-xs middle-xs"> <h3>You are not a member</h3> </section> ); } return ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <div className="messages"> <MessagesSection messages={this.state.messagesToRender} peer={this.state.peer} ref="MessagesSection"/> </div> {memberArea} </section> ); } else { return ( <section className="dialog dialog--empty row center-xs middle-xs"> <h2>Select dialog or start a new one.</h2> </section> ); } } fixScroll = () => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); node.scrollTop = node.scrollHeight - lastScrolledFromBottom; } }; onSelectedDialogChange = () => { renderMessagesCount = initialRenderMessagesCount; if (lastPeer != null) { DialogActionCreators.onConversationClosed(lastPeer); } lastPeer = DialogStore.getSelectedDialogPeer(); DialogActionCreators.onConversationOpen(lastPeer); }; onMessagesChange = _.debounce(() => { this.setState(getStateFromStores()); }, 10, {maxWait: 50, leading: true}); loadMessagesByScroll = _.debounce(() => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); let scrollTop = node.scrollTop; lastScrolledFromBottom = node.scrollHeight - scrollTop; if (node.scrollTop < LoadMessagesScrollTop) { DialogActionCreators.onChatEnd(this.state.peer); if (this.state.messages.length > this.state.messagesToRender.length) { renderMessagesCount += renderMessagesStep; if (renderMessagesCount > this.state.messages.length) { renderMessagesCount = this.state.messages.length; } this.setState(getStateFromStores()); } } } }, 5, {maxWait: 30}); } export default DialogSection;
src/main.js
nitrog7/nl-fluid
import React from 'react'; import ReactDOM from 'react-dom'; import AppView from 'views/AppView'; const target = document.getElementById('main'); // Render initial ReactJS code ReactDOM.render(<AppView />, target);
src/svg-icons/action/accessible.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccessible = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1c-2.28.46-4 2.48-4 4.9 0 2.76 2.24 5 5 5 2.42 0 4.44-1.72 4.9-4h-2.07z"/> </SvgIcon> ); ActionAccessible = pure(ActionAccessible); ActionAccessible.displayName = 'ActionAccessible'; ActionAccessible.muiName = 'SvgIcon'; export default ActionAccessible;
dynamic/swagger-to-api-doc.js
JeremyCraigMartinez/developer-dot
import path from 'path'; import React from 'react'; import {createStore} from 'redux'; import {Provider} from 'react-redux'; import reducer from './react/api-app/reducers/reducer'; import SwaggerParser from 'swagger-parser'; import App from './react/api-app/app'; import {renderToString} from 'react-dom/server'; import parseSwaggerUi from './parseSwaggerUI'; import mkdirp from 'mkdirp'; import fs from 'fs'; const saveStaticPage = (tagName, apiPath, buildHtmlFunc, state) => { const store = createStore(reducer, state); const staticHtml = renderToString( <Provider store={store}> <App /> </Provider> ); const html = buildHtmlFunc(tagName, staticHtml, state); const savePath = path.join(__dirname, '..', apiPath); mkdirp(savePath, (err) => { if (err) { throw err; } fs.writeFile(`${savePath}/index.html`, html, (writeErr) => { if (writeErr) { throw writeErr; } /* eslint-disable no-console */ console.log(`/${apiPath}/index.html saved successfully!`); /* eslint-enable no-console */ }); }); }; export default (fileName, apiName, apiPath, product) => { if (!fileName || !apiName || !apiPath) { throw new Error('`filepath`, `apiName` and `apiPath` required!'); } const swaggerPath = path.join(__dirname, 'swagger', fileName); fs.access(swaggerPath, (swaggerPathErr) => { if (swaggerPathErr) { /* eslint-disable no-console */ console.log('\x1b[31m', swaggerPathErr, '\x1b[0m'); /* eslint-enable no-console */ } else { new SwaggerParser().dereference(swaggerPath).then((swaggerDoc) => { let staticState; try { staticState = parseSwaggerUi(swaggerDoc, swaggerPath); } catch (e) { /* eslint-disable no-console */ console.log('Error parsing swaggerDoc', e); /* eslint-enable no-console */ throw new Error('Error parsing swaggerDoc'); } const buildHtml = (tagName, reactHtml, initialState) => { const endpointLinks = initialState.apiEndpoints.reduce((accum, endpt) => `${accum}["#${endpt.operationId.replace(/\s/g, '')}", "${endpt.name}"],\n`, ''); return ( `--- layout: default title: "API Console" api_console: 1 api_name: ${apiName} ${tagName ? `tag_name: ${tagName}` : ''} nav: apis product: ${product} doctype: api_references endpoint_links: [ ${endpointLinks} ] --- <div id="api-console">${reactHtml}</div> <script>window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};</script> <script src="/public/js/api-bundle.js"></script>` ); }; const tagMap = {...staticState.tagMap}; if (tagMap && Object.keys(tagMap).length > 0) { // Save off a configuration file detaling tag link name and its endpoints mkdirp(path.join(__dirname, '..', '_data', 'api_tag_pages'), (err) => { if (err) { throw err; } let tagPageConfig = `api_name: ${apiName}\napi_tags:\n`; Object.keys(tagMap).forEach((tag) => { tagPageConfig += ` - name: '${tag}'\n`; }); fs.writeFile(`${path.join(__dirname, '..', '_data', 'api_tag_pages')}/${apiName}.yml`, tagPageConfig, (writeErr) => { if (writeErr) { throw writeErr; } /* eslint-disable no-console */ console.log(`/${apiPath}/index.html saved successfully!`); /* eslint-enable no-console */ }); }); // Save off a simplified version of the App for our set of tags' 'root page' saveStaticPage(null, apiPath, buildHtml, {...staticState, apiEndpoints: []}); // Want to save off pages for each tagin the API's endpoints Object.keys(tagMap).forEach((tag) => { const operationIdsForTag = tagMap[tag]; const newApiPath = path.join(path.join(apiPath, tag)); saveStaticPage(tag, newApiPath, buildHtml, {...staticState, apiEndpoints: staticState.apiEndpoints.filter((ep) => operationIdsForTag.indexOf(ep.operationId) !== -1)}); }); } else { // Normal case, just save a single API pages saveStaticPage(null, apiPath, buildHtml, staticState); } }).catch((err) => { /* eslint-disable no-console */ console.log('Error thrown in SwaggerParser', err); /* eslint-enable no-console */ throw new Error(err); }); } }); };
src/components/round/takeRound.js
jollopre/beverage_planning
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { RoundShape } from '../../shapes/roundShape'; class TakeRound extends Component { constructor() { super(); this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); const { history, round } = this.props; history.push(`/bars/${round.bar_id}`); } anyOrderedBeverages() { const { round, orderedBeverages } = this.props; return Object.keys(orderedBeverages) .find(id => orderedBeverages[id].round_id === round.id) !== undefined; } render() { return (this.anyOrderedBeverages() ? (<form onSubmit={this.onSubmit}> <button className="btn btn-default" type="submit">Take Round</button> </form>) : null ); } } const mapStateToProps = (state, ownProps) => { const { rounds, orderedBeverages } = state; const { match } = ownProps; const round = rounds.byId[match.params.roundId]; // TODO check roundId exist return { round, orderedBeverages: orderedBeverages.byId }; } TakeRound.propTypes = { round: RoundShape, orderedBeverages: PropTypes.object.isRequired, } export default withRouter(connect(mapStateToProps)(TakeRound));
app/scripts/components/Routes.react.js
darbio/auth0-roles-permissions-dashboard-sample
import React from 'react'; import Router from 'react-router'; import Config from '../core/Config'; import RouterService from '../core/RouterService'; // Initialize logger. import { LogFactory } from '../core/Logger'; let logger = LogFactory('router'); // Root handler. var Shell = React.createClass({ render: function() { return (<Router.RouteHandler {...this.props} />); } }); // Load views. import Login from '../views/Login.react'; import Authenticated from './Authenticated.react'; import Dashboard from './Dashboard.react'; import Roles from '../views/Roles.react'; import Users from '../views/Users.react'; import Permissions from '../views/Permissions.react'; // Define the routes. var routes = ( <Router.Route name="app" path="/" handler={Shell}> <Router.Route name="login" path="/login" handler={Login} /> <Router.Route handler={Authenticated}> <Router.Route handler={Dashboard}> <Router.Route name="permissions" path="/permissions" handler={Permissions} /> <Router.Route name="roles" path="/roles" handler={Roles} /> <Router.Route name="users" path="/users" handler={Users} /> <Router.Redirect from="" to="roles" /> </Router.Route> </Router.Route> </Router.Route> ); // Create the router. var router = Router.create({ routes }); RouterService.set(router); // Start the router. export function init(config) { router.run(function (Handler, state) { // Log every router event. logger.info('Navigating to *' + state.path + '*'); // Render the current route. React.render(<Handler {...state} />, document.body); }); }
src/svg-icons/image/assistant-photo.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAssistantPhoto = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ImageAssistantPhoto = pure(ImageAssistantPhoto); ImageAssistantPhoto.displayName = 'ImageAssistantPhoto'; ImageAssistantPhoto.muiName = 'SvgIcon'; export default ImageAssistantPhoto;
src/icons/RoomServiceIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class RoomServiceIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M4 34h40v4H4zm23.67-18.42c.21-.48.33-1.02.33-1.58 0-2.21-1.79-4-4-4s-4 1.79-4 4c0 .56.12 1.1.33 1.58C12.5 17.2 6.54 23.86 6 32h36c-.54-8.14-6.5-14.8-14.33-16.42z"/></svg>;} };
client/routes.js
vaibhavmule/lead_crud
import React from 'react' import { Route, IndexRoute } from 'react-router' import App from './components/App' import LeadsIndex from './pages/LeadsIndex' import LeadDetail from './pages/LeadDetail' import CreateLead from './pages/CreateLead' export default ( <Route path="/" component={App}> <IndexRoute component={LeadsIndex} /> <Route path="leads/:id" component={LeadDetail} /> <Route path="/createLead" component={CreateLead} /> </Route> )
apps/marketplace/index.js
AusDTO/dto-digitalmarketplace-frontend
/* eslint-disable*/ import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from 'react-router-dom' import { Provider } from 'react-redux' import Header from './components/Header/Header' import AUFooter from './components/Footer/AUFooter' import SkipToLinks from './components/SkipToLinks/SkipToLinks' import configureStore from './store' import RootContainer from './routes' import { fetchAuth } from './actions/appActions' import styles from './main.scss' const store = configureStore() store.dispatch(fetchAuth()) const App = () => ( <Provider store={store}> <BrowserRouter> <div id="Application"> <SkipToLinks /> <header role="banner" className={styles.noPrint}> <Header /> </header> <main id="content" role="region" aria-live="polite"> <div className={`container ${styles.noPrintContainer}`}> <div className="row"> <div className="col-xs-12"> <RootContainer /> </div> </div> </div> </main> <AUFooter /> </div> </BrowserRouter> </Provider> ) ReactDOM.render(<App />, document.getElementById('root'))
ui/src/components/Modal/ConfirmDeleteModal.js
LearningLocker/learninglocker
import React from 'react'; import PropTypes from 'prop-types'; import { compose, withProps, setPropTypes } from 'recompose'; import ConfirmModal from 'ui/components/Modal/ConfirmModal'; const enhanceConfirmModal = compose( setPropTypes({ target: PropTypes.string.isRequired, }), withProps(({ target }) => ({ title: 'Confirm delete', message: ( <span> This will delete the {target} <b>permanently</b>. Are you sure? </span> ) })), ); /** * @param {boolean} _.isOpen * @param {string} _.target * @param {() => void} _.onConfirm * @param {() => void} _.onCancel */ export default enhanceConfirmModal(ConfirmModal);
examples/focus/app.js
mdamien/react-tabs
import React from 'react'; import { Tab, Tabs, TabList, TabPanel } from '../../lib/main'; const App = React.createClass({ handleInputChange() { this.forceUpdate(); }, render() { return ( <div style={{padding: 50}}> <Tabs> <TabList> <Tab>First</Tab> <Tab>Second</Tab> </TabList> <TabPanel> <p>Tab to focus `First`, then arrow to select `Second`.</p> </TabPanel> <TabPanel> <p>Tab to focus input, then begin typing. Focus should stay.</p> <input type="text" onChange={this.handleInputChange} /> </TabPanel> </Tabs> </div> ); } }); React.render(<App/>, document.getElementById('example'));
src/routes/Devices/components/nodes/Region.js
KozlovDmitriy/Pos.Hierarchy.Net
import React from 'react' import PropTypes from 'prop-types' import { Group } from '@vx/group' import Plus from './Plus' import NodeLabel from './NodeLabel' import CollapsedNode from './CollapsedNode' class Region extends CollapsedNode { static propTypes = { node: PropTypes.object.isRequired, errors: PropTypes.array.isRequired, warnings: PropTypes.array.isRequired, setPopoverIsOpen: PropTypes.func.isRequired, collapseNodeAndRewriteTree: PropTypes.func.isRequired } render () { const { node } = this.props const loading = this.getLoading(22, 12) const plus = node.collapsed ? ( this.state.loading ? loading : ( <Plus color={this.statusColor || '#00d6b2'} onDoubleClick={this.handleDoubleClick} /> ) ) : void 0 const label = ( <NodeLabel x={0} y={-19} fontSize={15} color={this.statusColor || '#00afa3'} text={node.name} onClick={this.onClick} /> ) return ( <Group y={node.y} x={node.x} style={{ cursor: 'pointer' }}> <polygon ref={this.refCallback} points={'-1, -10, -8, 11, 9, -2, -11, -2, 6, 11'} fill={this.statusColor || '#00d6b2'} stroke={this.statusColor || '#00d6b2'} strokeWidth={2.5} strokeOpacity={0.8} /> {plus} {label} {this.badge} </Group> ) } } export default Region
components/Welcome.js
RomainInnocent/tpdevops
/** * Created by Adrien on 30/06/2017. */ import React from 'react'; const style = { textAlign: 'center' } const Welcome = (props) => ( <div style={style}> <h1>{props.title}</h1> <p>{props.msg}</p> </div> ); export default Welcome;
src/components/BookList.js
pixel-glyph/better-reads
import React from 'react'; import PropTypes from 'prop-types'; import Remove from './svg/Remove'; class BookList extends React.Component { switchListSelect = (list) => { if(this.props.onMobile) { this.props.toggleSideList(); } this.props.switchList(list); }; removeList = (e) => { e.stopPropagation(); let parentElem = e.target.parentNode; while(!parentElem.classList.contains("list-picker-remove-icon")) { parentElem = parentElem.parentNode; } const listToRemove = parentElem.previousSibling.firstChild.textContent; this.props.removeListHandler(listToRemove); }; render() { const { listDisplayName, listName, lists, onMobile } = this.props; const selectedClass = !onMobile && lists[listName] && lists[listName].selected ? " selected" : ""; return ( <li className={`list-name${selectedClass}`} onClick={() => this.switchListSelect(listName)}> <div className="list-name-text"> <span>{listDisplayName}</span> <span> ({this.props.numBooks})</span> </div> {!onMobile && listDisplayName !== "Want to Read" && listDisplayName !== "Read" ? <div className="list-picker-remove-icon" onClick={(e) => this.removeList(e)}> <Remove/> </div> : null } </li> ) } } BookList.propTypes = { listName: PropTypes.string.isRequired, listDisplayName: PropTypes.string.isRequired, numBooks: PropTypes.number.isRequired, toggleSideList: PropTypes.func.isRequired, switchList: PropTypes.func.isRequired, removeListHandler: PropTypes.func, onMobile: PropTypes.bool, lists: PropTypes.object }; export default BookList;
examples/with-algolia-react-instantsearch/components/app.js
BlancheXu/test
import React from 'react' import PropTypes from 'prop-types' import { RefinementList, SearchBox, Hits, Configure, Highlight, Pagination } from 'react-instantsearch/dom' import { InstantSearch } from './instantsearch' const HitComponent = ({ hit }) => ( <div className='hit'> <div> <div className='hit-picture'> <img src={`${hit.image}`} /> </div> </div> <div className='hit-content'> <div> <Highlight attributeName='name' hit={hit} /> <span> - ${hit.price}</span> <span> - {hit.rating} stars</span> </div> <div className='hit-type'> <Highlight attributeName='type' hit={hit} /> </div> <div className='hit-description'> <Highlight attributeName='description' hit={hit} /> </div> </div> </div> ) HitComponent.propTypes = { hit: PropTypes.object } export default class extends React.Component { static propTypes = { searchState: PropTypes.object, resultsState: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), onSearchStateChange: PropTypes.func } render () { return ( <InstantSearch appId='appId' // change this apiKey='apiKey' // change this indexName='indexName' // change this resultsState={this.props.resultsState} onSearchStateChange={this.props.onSearchStateChange} searchState={this.props.searchState} > <Configure hitsPerPage={10} /> <header> <h1>React InstantSearch + Next.Js</h1> <SearchBox /> </header> <content> <menu> <RefinementList attributeName='category' /> </menu> <results> <Hits hitComponent={HitComponent} /> </results> </content> <footer> <Pagination /> <div> See{' '} <a href='https://github.com/algolia/react-instantsearch/tree/master/packages/react-instantsearch/examples/next-app'> source code </a>{' '} on github </div> </footer> </InstantSearch> ) } }
examples/simple/index.js
macropodhq/react-custom-scrollbars
import React from 'react'; import { render } from 'react-dom'; import App from './components/App'; render(<App />, document.getElementById('root'));
components/Animation.js
sturquier/hyne
import React, { Component } from 'react'; import { Animated } from 'react-native'; class Animation extends Component { constructor(props) { super(props); this.state = { animation: new Animated.ValueXY({x: 200, y:0}) } } componentDidMount() { Animated.timing( this.state.animation, { /* delay defined on Row Component */ delay: this.props.delay, duration: 300, toValue: {x: 0, y:0} } ).start() } render() { return ( /* We pass the style which is injected by the properties to the Animation, and we transform it Then, we pass children to the Animation */ <Animated.View style={{ ...this.props.style, transform: this.state.animation.getTranslateTransform() }}> {this.props.children} </Animated.View> ) } } export default Animation;
src/svg-icons/notification/airline-seat-flat-angled.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatFlatAngled = (props) => ( <SvgIcon {...props}> <path d="M22.25 14.29l-.69 1.89L9.2 11.71l2.08-5.66 8.56 3.09c2.1.76 3.18 3.06 2.41 5.15zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94c1.49-.72 2.12-2.51 1.41-4C7.99 4.71 6.2 4.08 4.7 4.8c-1.49.71-2.12 2.5-1.4 4 .71 1.49 2.5 2.12 4 1.4z"/> </SvgIcon> ); NotificationAirlineSeatFlatAngled = pure(NotificationAirlineSeatFlatAngled); NotificationAirlineSeatFlatAngled.displayName = 'NotificationAirlineSeatFlatAngled'; NotificationAirlineSeatFlatAngled.muiName = 'SvgIcon'; export default NotificationAirlineSeatFlatAngled;
docs/app/Examples/elements/Label/Groups/index.js
shengnian/shengnian-ui-react
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const LabelGroups = () => ( <ExampleSection title='Groups'> <ComponentExample title='Group Size' description='Labels can share sizes together' examplePath='elements/Label/Groups/LabelExampleGroupSize' /> <ComponentExample title='Colored Group' description='Labels can share colors together' examplePath='elements/Label/Groups/LabelExampleGroupColored' /> <ComponentExample title='Tag Group' description='Labels can share tag formatting' examplePath='elements/Label/Groups/LabelExampleGroupTag' /> <ComponentExample title='Circular Group' description='Labels can share shapes' examplePath='elements/Label/Groups/LabelExampleGroupCircular' /> </ExampleSection> ) export default LabelGroups
src/settings/PatronGroupsSettings.js
folio-org/ui-users
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage, injectIntl, } from 'react-intl'; import { ControlledVocab } from '@folio/stripes/smart-components'; import { withStripes } from '@folio/stripes/core'; class PatronGroupsSettings extends React.Component { static propTypes = { stripes: PropTypes.shape({ connect: PropTypes.func.isRequired, }).isRequired, intl: PropTypes.object.isRequired, }; constructor(props) { super(props); this.connectedControlledVocab = props.stripes.connect(ControlledVocab); } isPositiveInteger = (n) => { // match integer by regular expression as backend does not accept input like '5.0' const isInteger = val => /^\d+$/.test(val); const isGreaterEqualOne = val => Number.parseInt(val, 10) >= 1; return isInteger(n) && isGreaterEqualOne(n); }; isValidExpirationOffset = (n) => { if (n) { return this.isPositiveInteger(n); } return true; } validateFields = (item, _index, _items) => ({ expirationOffsetInDays: this.isValidExpirationOffset(item.expirationOffsetInDays) ? undefined : this.props.intl.formatMessage({ id: 'ui-users.information.patronGroup.expirationOffset.error' }), }); render() { const { intl } = this.props; return ( <this.connectedControlledVocab {...this.props} // We have to unset the dataKey to prevent the props.resources in // <ControlledVocab> from being overwritten by the props.resources here. dataKey={undefined} baseUrl="groups" records="usergroups" label={intl.formatMessage({ id: 'ui-users.information.patronGroups' })} labelSingular={intl.formatMessage({ id: 'ui-users.information.patronGroup' })} objectLabel={<FormattedMessage id="ui-users.information.patronGroup.users" />} visibleFields={['group', 'desc', 'expirationOffsetInDays']} hiddenFields={['numberOfObjects']} columnMapping={{ group: intl.formatMessage({ id: 'ui-users.information.patronGroup' }), desc: intl.formatMessage({ id: 'ui-users.description' }), expirationOffsetInDays: intl.formatMessage({ id: 'ui-users.information.patronGroup.expirationOffset' }), }} validate={this.validateFields} nameKey="group" id="patrongroups" sortby="group" /> ); } } export default injectIntl(withStripes(PatronGroupsSettings));
src/React/Widgets/LayoutsWidget/TwoBottom.js
Kitware/paraviewweb
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/LayoutsWidget.mcss'; export default function render(props) { return ( <table className={props.active === '3xB' ? style.activeTable : style.table} name="3xB" onClick={props.onClick} > <tbody> <tr> <td className={props.activeRegion === 0 ? style.activeTd : style.td} /> <td className={props.activeRegion === 1 ? style.activeTd : style.td} /> </tr> <tr> <td colSpan="2" className={props.activeRegion === 2 ? style.activeTd : style.td} /> </tr> </tbody> </table> ); } render.propTypes = { onClick: PropTypes.func, active: PropTypes.string, activeRegion: PropTypes.number, }; render.defaultProps = { onClick: () => {}, activeRegion: -1, active: undefined, };
packages/@unimodules/react-native-adapter/build/NativeViewManagerAdapter.native.js
exponent/exponent
import omit from 'lodash/omit'; import pick from 'lodash/pick'; import React from 'react'; import { NativeModules, UIManager, ViewPropTypes, requireNativeComponent } from 'react-native'; // To make the transition from React Native's `requireNativeComponent` to Expo's // `requireNativeViewManager` as easy as possible, `requireNativeViewManager` is a drop-in // replacement for `requireNativeComponent`. // // For each view manager, we create a wrapper component that accepts all of the props available to // the author of the universal module. This wrapper component splits the props into two sets: props // passed to React Native's View (ex: style, testID) and custom view props, which are passed to the // adapter view component in a prop called `proxiedProperties`. // NOTE: React Native is moving away from runtime PropTypes and may remove ViewPropTypes, in which // case we will need another way to separate standard React Native view props from other props, // which we proxy through the adapter const ViewPropTypesKeys = Object.keys(ViewPropTypes); /** * A drop-in replacement for `requireNativeComponent`. */ export function requireNativeViewManager(viewName) { if (__DEV__) { const { NativeUnimoduleProxy } = NativeModules; if (!NativeUnimoduleProxy.viewManagersNames.includes(viewName)) { const exportedViewManagerNames = NativeUnimoduleProxy.viewManagersNames.join(', '); console.warn(`The native view manager required by name (${viewName}) from NativeViewManagerAdapter isn't exported by @unimodules/react-native-adapter. Views of this type may not render correctly. Exported view managers: [${exportedViewManagerNames}].`); } } // Set up the React Native native component, which is an adapter to the universal module's view // manager const reactNativeViewName = `ViewManagerAdapter_${viewName}`; const ReactNativeComponent = requireNativeComponent(reactNativeViewName); const reactNativeUIConfiguration = (UIManager.getViewManagerConfig ? UIManager.getViewManagerConfig(reactNativeViewName) : UIManager[reactNativeViewName]) || { NativeProps: {}, directEventTypes: {}, }; const reactNativeComponentPropNames = [ 'children', ...ViewPropTypesKeys, ...Object.keys(reactNativeUIConfiguration.NativeProps), ...Object.keys(reactNativeUIConfiguration.directEventTypes), ]; // Define a component for universal-module authors to access their native view manager function NativeComponentAdapter(props, ref) { // TODO: `omit` may incur a meaningful performance cost across many native components rendered // in the same update. Profile this and write out a partition function if this is a bottleneck. const nativeProps = pick(props, reactNativeComponentPropNames); const proxiedProps = omit(props, reactNativeComponentPropNames); return React.createElement(ReactNativeComponent, Object.assign({}, nativeProps, { proxiedProperties: proxiedProps, ref: ref })); } NativeComponentAdapter.displayName = `Adapter<${viewName}>`; return React.forwardRef(NativeComponentAdapter); } //# sourceMappingURL=NativeViewManagerAdapter.native.js.map
src/react/JSONTree/JSONArrayNode.js
threepointone/redux-devtools
import React from 'react'; import reactMixin from 'react-mixin'; import { ExpandedStateHandlerMixin } from './mixins'; import JSONArrow from './JSONArrow'; import grabNode from './grab-node'; const styles = { base: { position: 'relative', paddingTop: 3, paddingBottom: 3, paddingRight: 0, marginLeft: 14 }, label: { margin: 0, padding: 0, display: 'inline-block' }, span: { cursor: 'default' }, spanType: { marginLeft: 5, marginRight: 5 } }; @reactMixin.decorate(ExpandedStateHandlerMixin) export default class JSONArrayNode extends React.Component { defaultProps = { data: [], initialExpanded: false }; // flag to see if we still need to render our child nodes needsChildNodes = true; // cache store for our child nodes renderedChildren = []; // cache store for the number of items string we display itemString = false; constructor(props) { super(props); this.state = { expanded: this.props.initialExpanded, createdChildNodes: false }; } // Returns the child nodes for each element in the array. If we have // generated them previously, we return from cache, otherwise we create // them. getChildNodes() { if (this.state.expanded && this.needsChildNodes) { let childNodes = []; this.props.data.forEach((element, idx) => { let prevData; if (typeof this.props.previousData !== 'undefined') { prevData = this.props.previousData[idx]; } const node = grabNode(idx, element, prevData, this.props.theme); if (node !== false) { childNodes.push(node); } }); this.needsChildNodes = false; this.renderedChildren = childNodes; } return this.renderedChildren; } // Returns the "n Items" string for this node, generating and // caching it if it hasn't been created yet. getItemString() { if (!this.itemString) { this.itemString = this.props.data.length + ' item' + (this.props.data.length !== 1 ? 's' : ''); } return this.itemString; } render() { const childNodes = this.getChildNodes(); const childListStyle = { padding: 0, margin: 0, listStyle: 'none', display: (this.state.expanded) ? 'block' : 'none' }; let containerStyle; let spanStyle = { ...styles.span, color: this.props.theme.base0E }; containerStyle = { ...styles.base }; if (this.state.expanded) { spanStyle = { ...spanStyle, color: this.props.theme.base03 }; } return ( <li style={containerStyle}> <JSONArrow theme={this.props.theme} open={this.state.expanded} onClick={::this.handleClick}/> <label style={{ ...styles.label, color: this.props.theme.base0D }} onClick={::this.handleClick}> {this.props.keyName}: </label> <span style={spanStyle} onClick={::this.handleClick}> <span style={styles.spanType}>[]</span> {this.getItemString()} </span> <ol style={childListStyle}> {childNodes} </ol> </li> ); } }
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js
WitchesTown/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { refreshHashtagTimeline, expandHashtagTimeline, } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { connectHashtagStream } from '../../../actions/streaming'; @connect() export default class HashtagTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, hashtag: PropTypes.string.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch, hashtag } = this.props; dispatch(refreshHashtagTimeline(hashtag)); this.disconnect = dispatch(connectHashtagStream(hashtag)); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = () => { this.props.dispatch(expandHashtagTimeline(this.props.hashtag)); } render () { const { hashtag } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='hashtag' title={hashtag} onClick={this.handleHeaderClick} /> <StatusListContainer trackScroll={false} scrollKey='standalone_hashtag_timeline' timelineId={`hashtag:${hashtag}`} loadMore={this.handleLoadMore} /> </Column> ); } }
src/server.js
RomanovRoman/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import React from 'react'; import ReactDOM from 'react-dom/server'; import UniversalRouter from 'universal-router'; import PrettyError from 'pretty-error'; import App from './components/App'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import assets from './assets'; // eslint-disable-line import/no-unresolved import { port, auth } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, })); app.use(passport.initialize()); if (process.env.NODE_ENV !== 'production') { app.enable('trust proxy'); } app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }), ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); }, ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: process.env.NODE_ENV !== 'production', rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { const css = new Set(); // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle styles.forEach(style => css.add(style._getCss())); }, }; const route = await UniversalRouter.resolve(routes, { path: req.path, query: req.query, }); if (route.redirect) { res.redirect(route.status || 302, route.redirect); return; } const data = { ...route }; data.children = ReactDOM.renderToString(<App context={context}>{route.component}</App>); data.style = [...css].join(''); data.scripts = [ assets.vendor.js, assets.client.js, ]; if (assets[route.chunk]) { data.scripts.push(assets[route.chunk].js); } const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(route.status || 200); res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html>, ); res.status(err.status || 500); res.send(`<!doctype html>${html}`); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ models.sync().catch(err => console.error(err.stack)).then(() => { app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */
fields/types/boolean/BooleanField.js
creynders/keystone
import React from 'react'; import Field from '../Field'; import Checkbox from '../../components/Checkbox'; import { FormField } from 'elemental'; const NOOP = () => {}; module.exports = Field.create({ displayName: 'BooleanField', statics: { type: 'Boolean', }, propTypes: { indent: React.PropTypes.bool, label: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, path: React.PropTypes.string.isRequired, value: React.PropTypes.bool, }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, renderFormInput () { if (!this.shouldRenderField()) return; return ( <input name={this.getInputName(this.props.path)} type="hidden" value={!!this.props.value} /> ); }, renderUI () { const { indent, value, label, path } = this.props; return ( <div data-field-name={path} data-field-type="boolean"> <FormField offsetAbsentLabel={indent}> <label style={{ height: '2.3em' }}> {this.renderFormInput()} <Checkbox checked={value} onChange={(this.shouldRenderField() && this.valueChanged) || NOOP} readonly={!this.shouldRenderField()} /> <span style={{ marginLeft: '.75em' }}> {label} </span> </label> {this.renderNote()} </FormField> </div> ); }, });
temp.js
SerenityTn/knowledge_map
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { constructor(){ super(); this.state = { user: {firstName: "Serenity", lastName: "Amamou"} } } hello(user){ return "Good morning " + user.firstName + " " + user.lastName; } 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"> {this.hello(this.state.user)} </p> </div> ); } } export default App;
node_modules/case-sensitive-paths-webpack-plugin/demo/src/AppRoot.component.js
myapos/ClientManagerSpringBoot
import React, { Component } from 'react'; export default class AppRoot extends Component { // we can't use `connect` in this component, so must do naiively: constructor(props) { super(props); this.state = { }; } render() { return ( <div> <h1>This is just an empty demo</h1> <p>(Run the tests.)</p> </div> ); } }
subjects/HigherOrderComponents/exercise.js
integral-llc/react-interview
//////////////////////////////////////////////////////////////////////////////// // Exercise: // // Make `withMousePosition`a a "higher-order component" that sends the mouse // position to the component as props. // // hint: use `event.clientX` and `event.clientY` import React from 'react' import { render } from 'react-dom' const withMousePosition = (Component) => { return Component }; class App extends React.Component { static propTypes = { mouse: React.PropTypes.shape({ x: React.PropTypes.number.isRequired, y: React.PropTypes.number.isRequired }).isRequired }; render() { return ( <div> <h1>With the mouse!</h1> <pre>{JSON.stringify(this.props.mouse, null, 2)}</pre> </div> ) } } const AppWithMouse = withMousePosition(App); render(<AppWithMouse/>, document.getElementById('app'));
app/javascript/mastodon/components/timeline_hint.js
danhunsaker/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; const TimelineHint = ({ resource, url }) => ( <div className='timeline-hint'> <strong><FormattedMessage id='timeline_hint.remote_resource_not_displayed' defaultMessage='{resource} from other servers are not displayed.' values={{ resource }} /></strong> <br /> <a href={url} target='_blank'><FormattedMessage id='account.browse_more_on_origin_server' defaultMessage='Browse more on the original profile' /></a> </div> ); TimelineHint.propTypes = { resource: PropTypes.node.isRequired, url: PropTypes.string.isRequired, }; export default TimelineHint;
src/common/components/static/TOC.js
ThinkingInReact/ThinkingInReact.xyz
import React, { Component } from 'react'; import TOCMD from 'content//TOC.md'; class TOC extends Component { render() { return ( <section className="TOC"> <h1 className="TOC__Title"> Table of Contents </h1> <TOCMD /> </section> ); } } export default TOC;
js/KindAnalysisPanel.react.js
Sable/McLab-Web
import AT from './constants/AT'; import classnames from 'classnames'; import Dispatcher from './Dispatcher'; import DropdownSelect from './DropdownSelect.react'; import FortranCompileActions from './actions/FortranCompileActions'; import FortranCompileArgumentSelector from './FortranCompileArgumentSelector.react'; import KindAnalysisActions from './actions/KindAnalysisActions'; import MatlabArgTypes from './constants/MatlabArgTypes'; import React from 'react'; import SidePanelBase from './SidePanelBase.react'; const { PropTypes, Component } = React; class KindAnalysisPanel extends Component { _collect(collection) { const map = new Map(); for (let sym of collection) { if (!map.has(sym.name)) { map.set(sym.name, []); } map.get(sym.name).push(sym.position); } return map; } _renderSymbol(symName, positionList) { if (positionList.length === 0) { return null; } const renderedPositions = []; let count = 0; for (let pos of positionList) { const lineno = pos.startRow + 1; const startColumn = pos.startColumn + 1; const endColumn = pos.endColumn + 1; renderedPositions.push( <div key={`${symName}-${count}`} className="kind-analysis-panel-sym-position"> {`Line ${lineno}, Column ${startColumn}-${endColumn}`} </div> ); count += 1; } return ( <div> <div className="kind-analysis-panel-sym-name"> {symName} </div> <div className="kind-analysis-panel-sym-position-container"> {renderedPositions} </div> </div> ); } _renderSymbolList(kind, symPositions) { const renderedList = []; const symMap = this._collect(symPositions); for (let p of symMap) { const symName = p[0]; const positionList = p[1]; renderedList.push( <div className="kind-analysis-panel-sym-container" key={"sym-" + symName}> {this._renderSymbol(symName, positionList)} </div> ); } if (renderedList.length === 0) { return null; } return ( <div> <div className="kind-analysis-panel-kind-name"> {kind} </div> <div className="kind-analaysis-panel-sym-list-container"> {renderedList} </div> </div> ); } render() { if(!this.props.variables && !this.props.functions) { return ( <SidePanelBase title="Kind Analysis Results"> <div className="side-panel-card"> No results to show here. <a className="cursor-pointer" onClick={KindAnalysisActions.runKindAnalysis}> {' '}Run kind analysis on this file. </a> </div> </SidePanelBase> ); } const varSection = this.props.variables ? this._renderSymbolList("Variables", this.props.variables) : []; const funSection = this.props.functions ? this._renderSymbolList("Functions", this.props.functions) : []; return ( <SidePanelBase title="Kind Analysis Results"> <div className="side-panel-card"> {varSection} {funSection} </div> </SidePanelBase> ); } } KindAnalysisPanel.propTypes = { variables: PropTypes.arrayOf(PropTypes.object), functions: PropTypes.arrayOf(PropTypes.object), } export default KindAnalysisPanel;
ui/src/components/StockChart.js
Ion-Petcu/StockTrainer
import React from 'react' import {Line} from 'react-chartjs-2' export class StockChart extends React.Component { render() { let chartData = { labels: [], datasets: [ { fill: true, cubicInterpolationMode: 'monotone', // lineTension: 0.1, backgroundColor: 'rgba(0,150,136,0.4)', borderColor: 'rgba(0,150,136,1)', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'rgba(0,150,136,1)', pointBackgroundColor: '#fff', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'rgba(75,192,192,1)', pointHoverBorderColor: 'rgba(220,220,220,1)', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [] } ] }; let chartOptions = { legend: { display: false }, title: { display: true, text: 'Stock' }, tooltips: { displayColors: false, callbacks: { //title: (t) => null, label: (t) => t.yLabel } }, scales: { xAxes: [{ ticks: { autoSkip: true, maxTicksLimit: 12 } }] }, animation: { duration: 10, easing: 'linear' } }; chartData.labels = this.props.data.map((e) => e[0]); chartData.datasets[0].data = this.props.data.map((e) => e[1]); chartOptions.title.text = this.props.stock + ' ' + parseFloat(this.props.price).toFixed(2); return ( <div className="w3-container" style={{margin: '50px 0px 100px 0px'}}> <Line data={chartData} options={chartOptions} /> </div> ) } } export default StockChart;
src/components/icons/CollapseIcon.js
austinknight/ui-components
import React from 'react'; const CollapseIcon = props => ( <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" fill="white" width="18px" height="18px" x="0px" y="0px" viewBox="0 0 18 18"> {props.title && <title>{props.title}</title>} <g id="collapse" transform="translate(-872.000000, -57.000000)"> <g id="Email-Client" transform="translate(100.000000, 44.000000)"> <g id="Collapse-Icon" transform="translate(769.000000, 10.000000)"> <polygon id="Shape" fill="none" points="0,0 24,0 24,24 0,24 "/> <path id="Combined-Shape" fillOpacity="0.8" d="M6,12h6v6l-2.3-2.3l-4.9,4.9l-1.4-1.4l4.9-4.9L6,12z M18,12h-6V6l2.3,2.3l4.9-4.9 l1.4,1.4l-4.9,4.9L18,12z"/> </g> </g> </g> </svg> ); export default CollapseIcon;
src/withStyles.js
kriasoft/isomorphic-style-loader
/** * Isomorphic CSS style loader for Webpack * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react' import PropTypes from 'prop-types' import hoistStatics from 'hoist-non-react-statics' import StyleContext from './StyleContext' function withStyles(...styles) { return function wrapWithStyles(ComposedComponent) { class WithStyles extends React.PureComponent { constructor(props, context) { super(props, context) this.removeCss = context.insertCss(...styles) } componentWillUnmount() { if (typeof this.removeCss === 'function') { setTimeout(this.removeCss, 0) } } render() { const { __$$withStylesRef, ...props } = this.props return <ComposedComponent ref={__$$withStylesRef} {...props} /> } } const displayName = ComposedComponent.displayName || ComposedComponent.name || 'Component' WithStyles.propTypes = { __$$withStylesRef: PropTypes.oneOfType([ PropTypes.func, PropTypes.shape({ current: PropTypes.instanceOf(typeof Element === 'undefined' ? Function : Element), }), ]), } WithStyles.defaultProps = { __$$withStylesRef: undefined, } WithStyles.contextType = StyleContext const ForwardedWithStyles = React.forwardRef((props, ref) => ( <WithStyles {...props} __$$withStylesRef={ref} /> )) ForwardedWithStyles.ComposedComponent = ComposedComponent ForwardedWithStyles.displayName = `WithStyles(${displayName})` return hoistStatics(ForwardedWithStyles, ComposedComponent) } } export default withStyles
examples/progressive-render/components/Loading.js
sedubois/next.js
import React from 'react' export default () => ( <div> <h3>Loading...</h3> <style jsx>{` div { align-items: center; display: flex; height: 50vh; justify-content: center; } `}</style> </div> )
src/client/pages/tocheck.react.js
sljuka/bucka-portfolio
import Component from '../components/component.react'; import React from 'react'; import {Link} from 'react-router'; import ToCheckItem from './tocheckitem.react'; import {msg, msgs} from '../intl/store'; class ToCheck extends Component { render() { return ( <div className="tocheck"> <h3> {msg('toCheck.header')} </h3> <ul> {msgs('toCheck.itemListHtml').map((item) => <ToCheckItem item={item} key={item.get('key')} /> )} <li> {msg('toCheck.isomorphicPage')}{' '} <Link to="/this-is-not-the-web-page-you-are-looking-for">404</Link>. </li> <li> {msg('toCheck.andMuchMore')} </li> </ul> </div> ); } } export default ToCheck;