path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
test/fixtures/unnamed-function-hoc/actual.js
layershifter/babel-plugin-transform-react-handled-props
import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; export default function() { return function(Component) { class Wrapper extends React.Component { render() { return <Component {...this.props} />; } } return hoistStatics(Wrapper, Component); } }
src/containers/SaleProducts/ProductSummary/ProductSummary.js
GoogleChromeLabs/react-shrine
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import IconButton from '@material-ui/core/IconButton'; import ErrorOutline from '@material-ui/icons/ErrorOutline'; import AddCart from '../../../components/AddCart/AddCart'; import AbrilText from '../../../components/AbrilText/AbrilText'; import './product-summary.css'; const ProductSummary = ({ openDetailViewer, product }) => ( <div className='product-summary'> <div onClick={openDetailViewer} className='image-container'> <img src={product.imageUrl} alt={product.title} /> <IconButton className='info-outline' color='inherit' aria-label='Menu'> <ErrorOutline /> </IconButton> </div> <div className='product-details-wrapper'> <AbrilText text={product.title} className='heading' /> <div className='description'>{product.description}</div> <AddCart /> <div className='store-description'> <div className='store-heading'>{product.storeName}</div> <div className='description'>{product.storeDescription}</div> </div> </div> </div> ); export default ProductSummary;
renderer/components/TabContainer.js
markmarcelo/reactide
import React from 'react'; import Tab from './Tab'; import PropTypes from 'prop-types'; const TabContainer = ({ appState, setActiveTab, closeTab }) => { const tabs = []; for (var i = 0; i < appState.openTabs.length; i++) { tabs.push( <Tab key={i} name={appState.openTabs[i].name} setActiveTab={setActiveTab} id={appState.openTabs[i].id} closeTab={closeTab} />); } return ( <ul className="list-inline tab-bar inset-panel tab-container"> {tabs} </ul> ) } TabContainer.propTypes = { appState: PropTypes.object.isRequired, setActiveTab: PropTypes.func.isRequired, closeTab: PropTypes.func.isRequired } export default TabContainer;
src/SplitButton.js
mengmenglv/react-bootstrap
import React from 'react'; import BootstrapMixin from './BootstrapMixin'; import Button from './Button'; import Dropdown from './Dropdown'; import SplitToggle from './SplitToggle'; class SplitButton extends React.Component { render() { let { children, title, onClick, target, href, // bsStyle is validated by 'Button' component bsStyle, // eslint-disable-line ...props } = this.props; let { disabled } = props; let button = ( <Button onClick={onClick} bsStyle={bsStyle} disabled={disabled} target={target} href={href} > {title} </Button> ); return ( <Dropdown {...props}> {button} <SplitToggle aria-label={title} bsStyle={bsStyle} disabled={disabled} /> <Dropdown.Menu> {children} </Dropdown.Menu> </Dropdown> ); } } SplitButton.propTypes = { ...Dropdown.propTypes, ...BootstrapMixin.propTypes, /** * @private */ onClick() {}, target: React.PropTypes.string, href: React.PropTypes.string, /** * The content of the split button. */ title: React.PropTypes.node.isRequired }; SplitButton.defaultProps = { disabled: false, dropup: false, pullRight: false }; SplitButton.Toggle = SplitToggle; export default SplitButton;
packages/material-ui-icons/src/Filter1.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 10h2V5h-4v2h2v8zm7-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z" /></g> , 'Filter1');
src/main/webapp/resources/js/components/antd/antd-demo.js
peterchenhdu/infosys
import React from 'react' import { Calendar } from 'antd'; import { Switch } from 'antd'; import { Rate } from 'antd'; import { Progress } from 'antd'; export default class AntdDemo extends React.Component{ constructor(props){ super(props); this.state = {} } render() { return ( <div> <div className="antd-calendar"> <Calendar /> </div> <div className="antd-ib"> <Switch defaultChecked={true} /> </div> <div className="antd-ib"> <Rate allowHalf defaultValue={2.5} /> </div> <div className="antd-ib"> <Progress type="circle" percent={30} width={80} /> <Progress type="circle" percent={70} width={80} status="exception" /> <Progress type="circle" percent={100} width={80} /> </div> </div> ); } }
app/component/Tag.js
vankai/hitokoto-pwa
import React from 'react' import style from './Tag.css' export default function Tag(props) { return ( <div className={style.tag}> <div> <p>一言</p> </div> </div> ) }
app/src/js/components/Home.js
seiyavw/electron-template
import React, { Component } from 'react'; import { Link } from 'react-router'; export default class Home extends Component { render() { return ( <div> <div className="home"> <h2>Home</h2> <Link to="/counter">to Counter</Link> </div> </div> ); } }
pages/contact.js
EvanSimpson/evansimpson.github.io
import React, { Component } from 'react'; import styles from '../css/contact.module.css'; class About extends Component { render() { return ( <div> <div className={ styles.container }> <p>Say hello at</p> <p>me @ this domain</p> </div> </div> ); } } export default About;
node_modules/@material-ui/core/esm/internal/svg-icons/RadioButtonChecked.js
pcclarke/civ-techs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M8.465 8.465C9.37 7.56 10.62 7 12 7C14.76 7 17 9.24 17 12C17 13.38 16.44 14.63 15.535 15.535C14.63 16.44 13.38 17 12 17C9.24 17 7 14.76 7 12C7 10.62 7.56 9.37 8.465 8.465Z" }), 'RadioButtonChecked');
src/containers/Contact/ThankYouSection.js
d-amit/in-di-go
import React from 'react'; import { Section } from '../../components'; const ThankYouSection = ({ id, className }) => { let sectionClass = `thankyou ${className}`; let aos = { type : "fade-up", duration: 1500 }; return ( <Section id={id} aos={aos} className={sectionClass}> <h2 className="centered" data-aos="zoom-in">Thank You!</h2> <p className="centered" data-aos="fade-in"> Your message has been sent and ICG will get back to you as soon as possible. </p> </Section> ); } export default ThankYouSection;
src/components/ChangePassword.js
JMIsham/AboutgccFront
/** * Created by Isham on 5/15/2017. */ import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import FlatButton from 'material-ui/RaisedButton'; import { TextField } from 'redux-form-material-ui'; const required = value => value == null ? 'Required' : undefined; class ChangePassword extends Component{ handlePassword(value){ if(this.refs.password.value==undefined) return "Please Enter a Password First"; return value.toString() == this.refs.password.value.toString() ? undefined : "Password Mismatch" } render(){ const { handleSubmit, pristine, reset, submitting } = this.props; return( <div> <form onSubmit={handleSubmit}> <div> <Field name="password" id = "oldPassword" type = "password" component={TextField} hintText="Current Password" floatingLabelText="Current Password" errorText = {this.props.passwordError} validate={required} /> </div> <div> <Field name="newPassword1" id = "password" type = "password" component={TextField} hintText="New Password" floatingLabelText="New Password" validate={required} ref = "password" /> </div> <div> <Field name="newPassword2" id = "rePassword" type = "password" component={TextField} hintText="Conform Password" floatingLabelText="Conform Password" validate={[required,this.handlePassword.bind(this)]} /> </div> {this.props.succeeded} <div > <FlatButton type="submit" labelStyle = {{color :"#2196f3",}} style={{ marginRight:'10px',marginLeft:"20px",}} disabled={submitting} label="Change Password" className="button-submit" /> <FlatButton disabled={pristine || submitting} onClick={reset} label="Clear All" secondary={true} /> </div> </form> </div> ); } } ChangePassword = reduxForm({form: 'change password'})(ChangePassword); export default ChangePassword;
local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js
shrutic/react-native
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, Image, ListView, Platform, StyleSheet, View, } from 'react-native'; import ListItem from '../../components/ListItem'; import Backend from '../../lib/Backend'; export default class ChatListScreen extends Component { static navigationOptions = { title: 'Chats', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./chat-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { isLoading: true, dataSource: ds, }; } async componentDidMount() { const chatList = await Backend.fetchChatList(); this.setState((prevState) => ({ dataSource: prevState.dataSource.cloneWithRows(chatList), isLoading: false, })); } // Binding the function so it can be passed to ListView below // and 'this' works properly inside renderRow renderRow = (name) => { return ( <ListItem label={name} onPress={() => { // Start fetching in parallel with animating this.props.navigation.navigate('Chat', { name: name, }); }} /> ); } render() { if (this.state.isLoading) { return ( <View style={styles.loadingScreen}> <ActivityIndicator /> </View> ); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} style={styles.listView} /> ); } } const styles = StyleSheet.create({ loadingScreen: { backgroundColor: 'white', paddingTop: 8, flex: 1, }, listView: { backgroundColor: 'white', }, icon: { width: 30, height: 26, }, });
fields/types/name/NameField.js
pswoodworth/keystone
import Field from '../Field'; import React from 'react'; import { FormField, FormInput, FormRow } from 'elemental'; module.exports = Field.create({ displayName: 'NameField', focusTargetRef: 'first', valueChanged: function (which, event) { this.props.value[which] = event.target.value; this.props.onChange({ path: this.props.path, value: this.props.value, }); }, renderValue () { return ( <FormRow> <FormField width="one-half"> <FormInput noedit style={{ width: '100%' }}>{this.props.value.first}</FormInput> </FormField> <FormField width="one-half"> <FormInput noedit style={{ width: '100%' }}>{this.props.value.last}</FormInput> </FormField> </FormRow> ); }, renderField () { return ( <FormRow> <FormField width="one-half"> <FormInput name={this.props.paths.first} placeholder="First name" ref="first" value={this.props.value.first} onChange={this.valueChanged.bind(this, 'first')} autoComplete="off" /> </FormField> <FormField width="one-half"> <FormInput name={this.props.paths.last} placeholder="Last name" ref="last" value={this.props.value.last} onChange={this.valueChanged.bind(this, 'last')} autoComplete="off" /> </FormField> </FormRow> ); }, });
src/svg-icons/device/gps-off.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceGpsOff = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/> </SvgIcon> ); DeviceGpsOff = pure(DeviceGpsOff); DeviceGpsOff.displayName = 'DeviceGpsOff'; export default DeviceGpsOff;
docs/src/components/Docs/index.js
michalko/draft-wyswig
import React, { Component } from 'react'; import Installation from './Installation'; import Usage from './Usage'; import Props from './Props'; import ARIASupport from './ARIASupport'; import DataConversion from './DataConversion'; import './styles.css'; export default () => <div className="docs-root"> <Installation /> <Usage /> <Props /> <ARIASupport /> <DataConversion /> </div>;
src/components/App.js
react-puzzle-games/15-puzzle
import React, { Component } from 'react'; import levelFactory from './../lib/levels-factory'; import Game from './Game'; import Footer from './Footer'; import PropTypes from 'prop-types'; import styled from 'styled-components'; class App extends Component { constructor(props) { super(props); const level = props.level ? props.level : levelFactory(4 ** 2); const originalLevel = Object.assign({}, level); this.state = { original: originalLevel, level, }; } onResetClick = () => { this.setState({ level: { tileSet: this.state.original.tileSet, }, }); }; onNewClick = () => { const newLevel = levelFactory(4 ** 2); const newOriginalLevel = Object.assign({}, newLevel); this.setState({ level: newLevel, original: newOriginalLevel, }); }; render() { const { className } = this.props; return ( <div className={className}> <Game gridSize={4} tileSize={90} numbers={this.state.level.tileSet} onResetClick={this.onResetClick} onNewClick={this.onNewClick} original={this.state.original.tileSet} /> <Footer /> </div> ); } } App.propTypes = { level: PropTypes.shape({ tileSet: PropTypes.arrayOf(PropTypes.number).isRequired, }), }; export default styled(App)` display: flex; flex-direction: column; min-height: 100vh; `;
react-youtube-adaptive-loading/src/containers/SideBar/Subscriptions/Subscriptions.js
GoogleChromeLabs/adaptive-loading
import React from 'react'; import {Subscription} from "./Subscription/Subscription"; import {Divider} from "semantic-ui-react"; import {SideBarHeader} from '../SideBarHeader/SideBarHeader'; export class Subscriptions extends React.Component { render() { return ( <React.Fragment> <SideBarHeader title='Subscriptions'/> <Subscription label='PewDiePie' broadcasting/> <Subscription label='Joe Robinet' amountNewVideos={10}/> <Subscription label='Venture 4wd' amountNewVideos={23}/> <Subscription label='Man City' amountNewVideos={4}/> <Subscription label='MarleyThirteen' amountNewVideos={114}/> <Divider/> </React.Fragment> ); } }
envkey-react/src/components/billing/billing_columns.js
envkey/envkey-app
import React from 'react' import h from "lib/ui/hyperscript_with_helpers" export default function({columns}){ const renderBillingList = (header, items)=> h.div(".billing-list", [ (header ? h.h4(header) : null), h.div(".items", items.map((i)=> h.p([i]))) ]) return h.div(".billing-columns", columns.map(lists => h.div(".column", lists.map(([header, items])=> renderBillingList(header, items))) ) ) }
modules/experimental/AsyncProps.js
kenwheeler/react-router
import React from 'react'; import invariant from 'invariant'; var { func, array, shape, object } = React.PropTypes; var contextTypes = { asyncProps: shape({ reloadComponent: func, propsArray: array, componentsArray: array }) }; var _serverPropsArray = null; function setServerPropsArray(array) { invariant(!_serverPropsArray, 'You cannot call AsyncProps.hydrate more than once'); _serverPropsArray = array; } export function _clearCacheForTesting() { _serverPropsArray = null; } function hydrate(routerState, cb) { var { components, params } = routerState; var flatComponents = filterAndFlattenComponents(components); loadAsyncProps(flatComponents, params, cb); } function eachComponents(components, iterator) { for (var i = 0, l = components.length; i < l; i++) { if (typeof components[i] === 'object') { for (var key in components[i]) { iterator(components[i][key], i, key); } } else { iterator(components[i], i); } } } function filterAndFlattenComponents(components) { var flattened = []; eachComponents(components, function(Component) { if (Component.loadProps) flattened.push(Component); }); return flattened; } function loadAsyncProps(components, params, cb) { var propsArray = []; var componentsArray = []; var canceled = false; var needToLoadCounter = components.length; components.forEach(function(Component, index) { Component.loadProps(params, function(error, props) { needToLoadCounter--; propsArray[index] = props; componentsArray[index] = Component; maybeFinish(); }); }); function maybeFinish() { if (canceled === false && needToLoadCounter === 0) cb(null, {propsArray, componentsArray}); } return { cancel () { canceled = true; } }; } function getPropsForComponent(Component, componentsArray, propsArray) { var index = componentsArray.indexOf(Component); return propsArray[index]; } function mergeAsyncProps(current, changes) { for (var i = 0, l = changes.propsArray.length; i < l; i++) { let Component = changes.componentsArray[i]; let position = current.componentsArray.indexOf(Component); let isNew = position === -1; if (isNew) { current.propsArray.push(changes.propsArray[i]); current.componentsArray.push(changes.componentsArray[i]); } else { current.propsArray[position] = changes.propsArray[i]; } } } function arrayDiff(previous, next) { var diff = []; for (var i = 0, l = next.length; i < l; i++) if (previous.indexOf(next[i]) === -1) diff.push(next[i]); return diff; } function shallowEqual(a, b) { var key; var ka = 0; var kb = 0; for (key in a) { if (a.hasOwnProperty(key) && a[key] !== b[key]) return false; ka++; } for (key in b) if (b.hasOwnProperty(key)) kb++; return ka === kb; } var RouteComponentWrapper = React.createClass({ contextTypes: contextTypes, // this is here to meet the case of reloading the props when a component's params change, // the place we know that is here, but the problem is we get occasional waterfall loads // when clicking links quickly at the same route, AsyncProps doesn't know to load the next // props until the previous finishes rendering. // // if we could tell that a component needs its props reloaded in AsyncProps instead of here // (by the arrayDiff stuff in componentWillReceiveProps) then we wouldn't need this code at // all, and we coudl get rid of the terrible forceUpdate hack as well. I'm just not sure // right now if we can know to reload a pivot transition. componentWillReceiveProps(nextProps, context) { var paramsChanged = !shallowEqual( this.props.routerState.routeParams, nextProps.routerState.routeParams ); if (paramsChanged) { this.reloadProps(nextProps.routerState.routeParams); } }, reloadProps(params) { this.context.asyncProps.reloadComponent( this.props.Component, params || this.props.routerState.routeParams, this ); }, render() { var { Component, routerState } = this.props; var { componentsArray, propsArray, loading } = this.context.asyncProps; var asyncProps = getPropsForComponent(Component, componentsArray, propsArray); return <Component {...routerState} {...asyncProps} loading={loading} reloadAsyncProps={this.reloadProps} />; } }); var AsyncProps = React.createClass({ statics: { hydrate: hydrate, rehydrate: setServerPropsArray, createElement(Component, state) { return typeof Component.loadProps === 'function' ? <RouteComponentWrapper Component={Component} routerState={state}/> : <Component {...state}/>; } }, childContextTypes: contextTypes, getChildContext() { return { asyncProps: Object.assign({ reloadComponent: this.reloadComponent, loading: this.state.previousProps !== null }, this.state.asyncProps), }; }, getInitialState() { return { asyncProps: { propsArray: _serverPropsArray, componentsArray: _serverPropsArray ? filterAndFlattenComponents(this.props.components) : null, }, previousProps: null }; }, componentDidMount() { var initialLoad = this.state.asyncProps.propsArray === null; if (initialLoad) { hydrate(this.props, (err, asyncProps) => { this.setState({ asyncProps }); }); } }, componentWillReceiveProps(nextProps) { var routerTransitioned = nextProps.location !== this.props.location; if (!routerTransitioned) return; var oldComponents = this.props.components; var newComponents = nextProps.components; var components = arrayDiff( filterAndFlattenComponents(oldComponents), filterAndFlattenComponents(newComponents) ); if (components.length === 0) return; this.loadAsyncProps(components, nextProps.params); }, beforeLoad(cb) { this.setState({ previousProps: this.props }, cb); }, afterLoad(err, asyncProps, cb) { this.inflightLoader = null; mergeAsyncProps(this.state.asyncProps, asyncProps); this.setState({ previousProps: null, asyncProps: this.state.asyncProps }, cb); }, loadAsyncProps(components, params, cb) { if (this.inflightLoader) { this.inflightLoader.cancel(); } this.beforeLoad(() => { this.inflightLoader = loadAsyncProps(components, params, (err, asyncProps) => { this.afterLoad(err, asyncProps, cb); }); }); }, reloadComponent(Component, params, instance) { this.loadAsyncProps([Component], params, () => { // gotta fix this hack ... change in context doesn't cause the // RouteComponentWrappers to rerender (first one will because // of cloneElement) if (instance.isMounted()) instance.forceUpdate(); }); }, render() { var { route } = this.props; var { asyncProps, previousProps } = this.state; var initialLoad = asyncProps.propsArray === null; if (initialLoad) return route.renderInitialLoad ? route.renderInitialLoad() : null; else if (previousProps) return React.cloneElement(previousProps.children, { loading: true }); else return this.props.children; } }); export default AsyncProps;
src/components/smart_scroll/index.js
VictorQD/react-pdf-viewer
import React, { Component } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; import { range, cloneDeep } from 'lodash'; // isEqual const offsetBottom = node => node.offsetTop + node.clientHeight; const offsetTop = node => node.offsetTop; // itemClassName // getScroll // setCurrentItem class SmartScroll extends Component { constructor(props) { super(props); this.scroll = null; this.containerNode = null; this.items = []; this.topIndex = 0; this.bottomIndex = 0; this.topRendered = 0; this.bottomRendered = 0; this.renderedTail = 2; this.lastScrollTop = 0; this.scrollResponse = 50; this.itemClassName = `.${props.itemClassName}`; } componentDidMount() { // console.log('%c SmartScroll ==========> componentDidMount', 'color: red;'); this.setInitState(); } componentDidUpdate() { // console.log('%c SmartScroll ==========> componentDidUpdate', 'color: red;'); this.setInitState(); } setInitState() { console.log('%c SmartScroll === === ===> setInitState', 'color: green; font-weight: bold'); range(this.items.length).forEach(this.hideItem); this.updateItems(); } isVisible(itemIndex) { const item = this.items[itemIndex] || this.items[0]; const { scrollTop, clientHeight } = this.scroll.getValues(); const scrollBottom = scrollTop + clientHeight; const pageTop = offsetTop(item); const pageBottom = offsetBottom(item); return !(pageTop > scrollBottom || pageBottom < scrollTop); } topPageLeave() { if (!this.isVisible(this.topIndex)) { // console.log('%c \ntopPageLeave', 'color: red;'); this.topIndex += 1; return true; } return false; } topPageIn() { const item = this.items[this.topIndex - 1]; if (!!item && this.isVisible(this.topIndex - 1)) { // console.log('%c \ntopPageIn', 'color: green;'); this.topIndex -= 1; return true; } return false; } handleVisibility = ({ scrollTop }) => { if (Math.abs(this.lastScrollTop - scrollTop) < this.scrollResponse) return; this.lastScrollTop = scrollTop; if (this.topPageLeave(scrollTop) || this.topPageIn(scrollTop)) { this.updateItems(); if (typeof this.props.setCurrentItem === 'function') { this.setCurrentItem(); } } } updateItems() { const nowVisible = this.getVisibleIndexes(); const newVisible = this.findIndexes(); this.setIndexes(newVisible); // console.log('nowVisible: ', nowVisible); // console.log('newVisible: ', newVisible); // console.log('topRenderedNow: %o, bottomRenderedNow: %o', topRendered, bottomRendered); if (nowVisible === null) { console.log('%c updateItems ===> No visible', 'color: red;'); range(newVisible.topRendered, newVisible.bottomRendered + 1) .forEach(this.showItem); return; } console.log('%c updateItems ===> Update visible', 'color: green;'); const minTop = Math.min(nowVisible.topRendered, newVisible.topRendered); const maxTop = Math.max(nowVisible.topRendered, newVisible.topRendered); const minBottom = Math.min(nowVisible.bottomRendered, newVisible.bottomRendered); const maxBottom = Math.max(nowVisible.bottomRendered, newVisible.bottomRendered); range(minTop, maxBottom + 1).forEach((itemIndex) => { if (itemIndex >= maxTop && itemIndex <= minBottom) return; // for overlaping indexes if (itemIndex < newVisible.topRendered || itemIndex > newVisible.bottomRendered) { // item out of new indexes this.hideItem(itemIndex); return; } this.showItem(itemIndex); }); } getVisibleIndexes() { const nowVisible = [...this.containerNode.querySelectorAll('[data-index]')]; if (nowVisible.length) { const topRendered = parseInt(nowVisible[0].dataset.index); const bottomRendered = parseInt(nowVisible[nowVisible.length - 1].dataset.index); return { topRendered, bottomRendered }; } return null; } showItem = (itemIndex) => { this.items[itemIndex].setAttribute('data-index', itemIndex); this.items[itemIndex].classList.remove('hidden'); } hideItem = (itemIndex) => { this.items[itemIndex].removeAttribute('data-index'); this.items[itemIndex].classList.add('hidden'); } setIndexes(indexes) { // console.log('setIndexes === === === ===> indexes'); const { topIndex, bottomIndex, topRendered, bottomRendered } = indexes; this.topRendered = topRendered; this.bottomRendered = bottomRendered; this.topIndex = topIndex; this.bottomIndex = bottomIndex; // this.logIndexes(); } findIndexes = () => { console.log('\nSmartScroll === ===> findIndexes'); const { renderedTail, items } = this; // items const startIndex = this.topIndex || 0; // console.log('findIndexes === ===> startIndex: ', topIndex); let newTopIndex = null; let newBottomIndex = null; let topIndex = null; let bottomIndex = null; let topRendered = null; let bottomRendered = null; const newIndexes = () => { topIndex = newTopIndex; bottomIndex = newBottomIndex || newTopIndex; topRendered = (newTopIndex - renderedTail) >= 0 ? (newTopIndex - renderedTail) : 0; bottomRendered = (bottomIndex + renderedTail) < items.length ? (bottomIndex + renderedTail) : items.length - 1; // console.log('now return new indexes'); // console.log({ topIndex, bottomIndex, topRendered, bottomRendered }); return { topIndex, bottomIndex, topRendered, bottomRendered }; }; const findVisible = (itemIndex) => { // console.log('=== === ===> try index: ', itemIndex); if (this.isVisible(itemIndex)) { // console.log('visible'); if (newTopIndex === null) { // console.log('newTopIndex: ', itemIndex); newTopIndex = itemIndex; } else { // console.log('newBottomIndex: ', itemIndex); newBottomIndex = itemIndex; } } else if (newTopIndex !== null) { return newIndexes(); } if (itemIndex + 1 < items.length && topRendered === null) { // console.log('will test next index'); findVisible(itemIndex + 1); } return newIndexes(); }; return findVisible(startIndex); } logIndexes() { const { topIndex, bottomIndex, topRendered, bottomRendered } = this; console.log('%c\nIndexes now', 'color: green; font-weight: bold'); console.log('%c topIndex: %o, bottomIndex: %o', 'color: green;', topIndex, bottomIndex); console.log('%c topRendered: %o, bottomRendered: %o', 'color: red;', topRendered, bottomRendered); } // ================================================================= findCurrentItem() { // return Math.round((this.topIndex + this.bottomIndex) / 2); return Math.floor((this.topIndex + this.bottomIndex) / 2); } setCurrentItem() { const { setCurrentItem } = this.props; const newCurrentIndex = this.findCurrentItem(); if (this.currentIndex !== newCurrentIndex) { this.currentIndex = newCurrentIndex; setCurrentItem(this.currentIndex); } } scrollToItem = (itemIndex) => { console.log('SmartScroll === ===> scrollToItem itemIndex: ', itemIndex); if (itemIndex >= 0 && itemIndex < this.items.length) { const { offsetTop } = this.items[itemIndex]; this.scroll.scrollTop(offsetTop); } } // ================================================================= getScroll = (scrollRef) => { if (!scrollRef) return; // console.log('SmartScroll ===> getScroll'); this.scroll = scrollRef; this.containerNode = scrollRef.refs.container; this.items = [...this.containerNode.querySelectorAll(this.itemClassName)]; this.lastIndex = this.items.lendth - 1; const scrollToItem = this.scrollToItem; const smartScroll = { ...scrollRef, scrollToItem }; this.props.getScroll && this.props.getScroll(smartScroll); } clearProps() { const scrollProps = cloneDeep(this.props); delete scrollProps.getScroll; delete scrollProps.itemClassName; delete scrollProps.setCurrentItem; return scrollProps; } render() { const scrollProps = this.clearProps(); return ( <Scrollbars ref={this.getScroll} onScrollFrame={this.handleVisibility} {...scrollProps} > {this.props.children} </Scrollbars> ); } } export default SmartScroll;
src/js/components/icons/base/Clipboard.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-clipboard`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'clipboard'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M16,3 L21,3 L21,23 L3,23 L3,3 L3,3 L8,3 M8,1 L16,1 L16,6 L8,6 L8,1 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Clipboard'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/svg-icons/places/casino.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesCasino = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.5 18c-.83 0-1.5-.67-1.5-1.5S6.67 15 7.5 15s1.5.67 1.5 1.5S8.33 18 7.5 18zm0-9C6.67 9 6 8.33 6 7.5S6.67 6 7.5 6 9 6.67 9 7.5 8.33 9 7.5 9zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm0-9c-.83 0-1.5-.67-1.5-1.5S15.67 6 16.5 6s1.5.67 1.5 1.5S17.33 9 16.5 9z"/> </SvgIcon> ); PlacesCasino = pure(PlacesCasino); PlacesCasino.displayName = 'PlacesCasino'; PlacesCasino.muiName = 'SvgIcon'; export default PlacesCasino;
src/components/player-details.js
orouvinen/dnf-ranks-frontend
import React, { Component } from 'react'; import MatchRow from './match-row'; import PlayerBadge from './player-badge'; class PlayerDetails extends Component { render() { const player = this.props.player; const matches = this.props.matches; return ( <div className="row"> <div className="col-lg-6 col-md-6 col-sm-12"> <PlayerBadge player={player} matches={matches} /> </div> <div className="col-lg-6 col-md-6 col-sm-12"> <table className="player-matches"> <caption style={{ textAlign: "left" }}>Match history</caption> <thead> <tr> <td>Player 1</td> <td>Player 2</td> <td>Result</td> </tr> </thead> <tbody> {matches.map((match, i) => <MatchRow key={i} player={player} match={match} />) } </tbody> </table> </div> </div> ); } } export default PlayerDetails;
src/js/tooltip/index.js
HBM/md-components
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' /** * Tooltip */ export default class Tooltip extends React.Component { /** * Property types */ static propTypes = { content: PropTypes.string, visible: PropTypes.bool } /** * Default properties */ static defaultProps = { content: 'tooltip content', visible: false } /** * Initial state */ state = { left: 'auto', visible: this.props.visible } show = () => { this.setState({ visible: true }) } hide = () => { this.setState({ visible: false }) } /** * Get width of tooltip */ componentDidMount () { // to get the right width we have to make sure // that the tooltip is scaled properly // invisible tooltips are scaled down to 0 // and there we aren't able to get the right width // when initially hidden we do not have any refs if (!this.tooltipRef) { return } var tooltipRect = this.tooltipRef.getBoundingClientRect() var contentRect = this.refs.content.getBoundingClientRect() var left = (contentRect.width / 2) + contentRect.left - (tooltipRect.width / 2) this.setState({left}) } /** * Placeholder for tooltip ref * first-class references * https://github.com/reactjs/react-future/blob/master/01%20-%20Core/06%20-%20Refs.js * https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute */ tooltipRef = null /** * Render component */ render () { const {left} = this.state return ( <div onMouseOver={this.show} onMouseOut={this.hide}> {React.Children.map(this.props.children, child => React.cloneElement(child, { ref: 'content' }) )} <div className={classnames('Tooltip', { 'is-active': this.state.visible })} ref={(component) => { this.tooltipRef = component }} style={{left}} > {this.props.content} </div> </div> ) } }
src/components/Head.js
shiyangzhaoa/redux-cnode
import React from 'react' import { connect } from 'react-redux' import * as Actions from '../actions' import { Link } from 'react-router' import { Icon, Form, Input, Button, Popover, BackTop, Spin, message } from 'antd' const FormItem = Form.Item const react_img = require('../public/redux.png') const style = { body: { backgroundColor: '#fff', paddingBottom: '20px', width: '90%', borderRadius: '8px', margin: '20px auto 20px' }, header: { fontSize: '14px', width: '100%', borderRadius: '8px 8px 0 0', backgroundColor: '#f6f6f6', padding: '10px' }, nav: { color: '#80bd01', padding: '3px 4px', margin: '0 10px', transition: 'all 0.5s' }, message: { color: '#888', padding: '3px 4px', margin: '0 15px' }, create_topic: { color: '#fff', padding: '3px 4px', margin: '0 15px', backgroundColor: '#57c5f7', borderRadius: '3px' }, select: { backgroundColor: '#80bd01', color: '#fff', borderRadius: '3px' }, login: { position: 'fixed', right: '10px', zIndex: '99' }, signIn: { position: 'fixed', right: '0', top: '80px', zIndex: '99' }, collectionList: { padding: '5px 0', textAlign: 'center', backgroundColor: '#f2f2f2', marginTop: '10px', borderRadius: '8px' }, react: { width: '147px', height: '30px', marginBottom: '-10px' }, message_numb: { padding: '1px 7px', color: '#fff', backgroundColor: '#80bd01', borderRadius: '100%' } } export class Head extends React.Component { static propTypes = { name: React.PropTypes.string, } state = { selected: 'all', loginname: '', visible: false, form: false } componentWillMount = () => { const slugParam = this.getSlug() const username = localStorage.getItem("username") || '' const accesstoken = localStorage.getItem("loginname") || '' if (username) { this.props.getMessageNum(accesstoken) } this.setState({ selected: slugParam, loginname: username }) } componentWillReceiveProps = (nextProps) => { const slug = nextProps.params.categorySlug const nextSlug = slug ? slug : 'all' const cnodeNow = this.props.state.cnode const cnodeNext = nextProps.state.cnode if (this.getSlug() !== nextSlug) { this.setState({ selected: nextSlug }) } if (cnodeNow.login !== cnodeNext.login && cnodeNext.login === 'success') { message.success('登陆成功') const username = localStorage.getItem("username") || '' this.setState({ form: false, loginname: username }) } if (cnodeNow.login !== cnodeNext.login && cnodeNext.login === 'fail') { message.error('登陆失败') } if (cnodeNow.login !== cnodeNext.login && cnodeNext.login === 'leave') { message.success('成功退出') this.setState({ loginname: '' }) } } signOut = () => { this.setState({ visible: false }) this.props.signOut() localStorage.clear("loginname", "username") } getSlug = () => { let slugParam = this.props.params.categorySlug slugParam = slugParam ? slugParam : 'all' return slugParam } signIn = () => { this.setState({ form: true, visible: false }) } login = (data) => { const { userLogin } = this.props userLogin(data) this.setState({ modal1Visible: false }) } handleVisibleChange = (visible) => { this.setState({ visible }) } render() { const username = this.state.loginname let that = this const tabList = ['all', 'good', 'share', 'ask', 'job'] const HorizontalLoginForm = Form.create()(React.createClass({ handleSubmit(e) { e.preventDefault() this.props.form.validateFields((err, values) => { if (!err) { that.login(values) } }); }, render() { const { getFieldDecorator } = this.props.form return ( <Form inline onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('accesstoken', { rules: [{ required: true, message: 'Please input your username!' }], })( <Input addonBefore={<Icon type="user" />} placeholder="请输入你的accesstoken" /> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit">登陆</Button> </FormItem> </Form> ); }, })) return ( <div style={style.body}> <div style={style.login}> <Spin tip="Loading..." spinning={this.props.state.cnode.login==='request'}> <BackTop visibilityHeight='100'/> <Popover content={<a onClick={username ? this.signOut : this.signIn}>{username ? '退出' : '登陆'}</a>} title="登陆/退出" trigger="click" visible={this.state.visible} onVisibleChange={this.handleVisibleChange} > <Button type="primary">{username || '未登录'}</Button> </Popover> { !username || <Link to={`/collect/${username}`}><div style={style.collectionList}>收藏列表</div></Link> } { !username || <Link to={`/user/${username}`}><div style={style.collectionList}>个人信息</div></Link> } </Spin> </div> <div style={style.signIn} > {this.state.form ? <HorizontalLoginForm /> : ''} </div> <div style={style.header}> <Link to='/'><img style={style.react} src={react_img} alt="react" /></Link> {tabList.map((value, index) => { let selected = (this.state.selected === value) ? {...style.nav, ...style.select} : style.nav const end = value.replace('ask', '问答').replace('job', '招聘').replace('share', '分享').replace('good', '精华').replace('all', '全部') return <Link style={selected} to={`/category/${value}`} key={index}>{end}</Link> } )} { !username || <Link to='/message' style={style.message} >未读信息{this.props.state.message.messageNum ? <span style={style.message_numb}>{this.props.state.message.messageNum}</span> : ''}</Link>} { !username || <Link to='/createtopic' style={style.create_topic} >发布主题</Link>} </div> {this.props.children} </div> ) } } const mapStateToProps = state => ({ state: state }) export default connect( mapStateToProps, Actions )(Head)
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
wisc/spectacle-caching
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
src/routes/chart/Container.js
zhangjingge/sse-antd-admin
import React from 'react' import PropTypes from 'prop-types' import styles from './Container.less' import { ResponsiveContainer } from 'recharts' const Container = ({ children, ratio = 5 / 2, minHeight = 250, maxHeight = 350 }) => <div className={styles.container} style={{ minHeight, maxHeight }}> <div style={{ marginTop: `${100 / ratio}%` || '100%' }}></div> <div className={styles.content} style={{ minHeight, maxHeight }}> <ResponsiveContainer> {children} </ResponsiveContainer> </div> </div> Container.propTypes = { children: PropTypes.element.isRequired, ratio: PropTypes.number, minHeight: PropTypes.number, maxHeight: PropTypes.number, } export default Container
src/svg-icons/device/battery-60.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery60 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h10V5.33z"/><path d="M7 11v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11H7z"/> </SvgIcon> ); DeviceBattery60 = pure(DeviceBattery60); DeviceBattery60.displayName = 'DeviceBattery60'; export default DeviceBattery60;
src/react-in-isolation/presentation.js
travi/presentations
import React from 'react'; import createTheme from 'spectacle/lib/themes/default'; import {Appear, Deck, Fill, Fit, Heading, Image, Layout, Link, List, ListItem, Slide, Text} from 'spectacle'; import preloader from 'spectacle/lib/utils/preloader'; import Terminal from 'spectacle-terminal'; import CodeSlide from 'spectacle-code-slide'; import 'normalize.css'; import 'spectacle/lib/themes/default/index.css'; import Typist from 'react-typist'; const theme = createTheme({ primary: '#333', secondary: '#fff', tertiary: '#61dafb' }); const images = { enzyme: require('../../assets/react-in-isolation/enzyme.png'), unidirectional: require('../../assets/react-in-isolation/unidirectional-data-flow.png'), userAction: require('../../assets/react-in-isolation/flux-client-action.png') }; preloader(images); const cursor = {show: false, blink: true, element: '|', hideWhenDone: false, hideWhenDoneDelay: 1000}; export default function Presentation() { return ( <Deck transition={['zoom', 'slide']} transitionDuration={500} theme={theme}> <Slide transition={['zoom']} bgDarken={0.75} bgImage={require('../../assets/react-in-isolation/react-logo.svg')} > <Heading size={1} fit caps> Learn React </Heading> <Heading size={2} fit caps> in Isolation </Heading> <Text textColor="#888" textSize="1em" margin="40px 0px 0px" bold> Matt Travi </Text> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Less of an intro to React </Heading> <Heading size={2} fit> Instead, how to learn React </Heading> </Slide> <Slide> <Heading size={2} fit> React, by itself, can be simple </Heading> </Slide> <Slide> <Heading size={2} fit> That simplicity is clouded in an application </Heading> </Slide> <Slide notes="Transpilation, Bundling for the Browser, Auto rebuild when developing, Hot-reload"> <Heading size={2} fit> Build Tools </Heading> </Slide> <Slide notes="Loading data to the browser, State management, Routing, SSR"> <Heading size={2} fit> Application Wiring </Heading> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> How can we isolate React </Heading> <Heading size={2} fit> to learn it without the distractions? </Heading> </Slide> <Slide transition={['zoom']}> <Heading size={1}> Hello World </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/create-element-hello-world.example')} ranges={[ { loc: [2, 9], note: 'JavaScript component', title: 'createElement' } ]} /> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/jsx-hello-world.example')} ranges={[ { loc: [2, 5], title: 'JSX' } ]} /> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/string-hello-world.example')} ranges={[ { loc: [0, 3], note: 'Strings can now be rendered directly', title: 'React 16' } ]} /> <Slide transition={['zoom']}> <Heading size={2} fit> Unit Tests </Heading> </Slide> <Slide> <Layout> <Fill> <Image width="70%" src={require('../../assets/react-in-isolation/airbnb.svg')} /> <Appear> <Link href="https://mochajs.org/" target="_blank"> <Image width="70%" src={require('../../assets/react-in-isolation/mocha.svg')} /> </Link> </Appear> </Fill> <Fill> <Link href="http://airbnb.io/enzyme/" target="_blank"> <Image width="70%" src={images.enzyme.replace('/', '')} /> </Link> <Appear> <Link href="http://chaijs.com/" target="_blank"> <Image width="60%" src={require('../../assets/react-in-isolation/chai.svg')} /> </Link> </Appear> </Fill> </Layout> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/hello-world-test.example')} ranges={[ { loc: [1, 2], title: 'Unit Testing with Enzyme', note: 'enzyme simplifies testing components' }, { loc: [7, 10], title: 'Unit Testing with Enzyme', note: 'render the component with shallow()' }, { loc: [11, 15], title: 'Unit Testing with Enzyme', note: 'verify the behavior' } ]} /> <Slide transition={['zoom']}> <Heading size={1} fit> But what do I do with these components </Heading> <Heading size={2} fit> without an application? </Heading> </Slide> <Slide transition={['zoom']}> <Link href="https://storybook.js.org/" target="_blank"> <Image width="80%" src={require('../../assets/react-in-isolation/storybook.svg')} /> </Link> </Slide> <Slide bgColor="#888"> <Heading size={2} fit> Configuring Storybook </Heading> <Terminal title="~/development/react-in-isolation @ Travi-MBP" output={[ <Typist cursor={cursor} key="storybook cli"> npm i -g @storybook/cli </Typist>, <div key="cli installation"> <div style={{color: 'rgb(48, 53, 57)'}}> . </div> <div> + @storybook/cli@3.2.12 </div> <div> added 379 packages in 93.821s </div> <div style={{color: 'rgb(48, 53, 57)'}}> . </div> </div>, <Typist cursor={cursor} key="storybook init"> getstorybook </Typist>, <div key="init results"> <div style={{color: 'rgb(48, 53, 57)'}}> . </div> <div style={{backgroundColor: 'white', color: 'black'}}> &nbsp;getstorybook - the simplest way to add a storybook to your project. </div> <div style={{color: 'rgb(48, 53, 57)'}}> . </div> <div> &nbsp;• Detecting project type. <span style={{color: '#00ff00'}}> ✓ </span> </div> <div> &nbsp;• Adding storybook support to your &quot;React&quot; app. &nbsp; <span style={{color: '#00ff00'}}> ✓ </span> </div> <div> &nbsp;• Preparing to install dependencies. <span style={{color: '#00ff00'}}> ✓ </span> </div> </div> ]} /> </Slide> <CodeSlide lang="json" code={require('../../assets/package.npm.example')} ranges={[ { loc: [14, 16], title: 'Storybook', note: 'scripts to run and build are added' } ]} /> <Slide> <Heading size={2} fit> Build Details Handled by Storybook </Heading> <List> <ListItem> Transpilation (Babel) </ListItem> <ListItem> Bundling for the browser (Webpack) <List> <ListItem> Dev Server </ListItem> <ListItem> Hot Reload </ListItem> </List> </ListItem> </List> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/hello-world-stories.example')} ranges={[ { loc: [2, 5], note: 'import the components', title: 'Stories' }, { loc: [6, 7], note: 'Define the category', title: 'Stories' }, { loc: [7, 10], note: 'Render the stories', title: 'Stories' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Functional" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Props </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/props.example')} ranges={[ { loc: [8, 11], note: 'variable passed as a prop', title: 'Props' }, { loc: [5, 6], note: 'variable passed as a prop', title: 'Props' }, { loc: [11, 18], note: 'booleans can be passed as a flag', title: 'Props' }, { loc: [15, 16], note: 'booleans can be passed as a flag', title: 'Props' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Props%2FButton" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/handlers.example')} ranges={[ { loc: [8, 15], note: 'functions passed as props', title: 'Handlers' }, { loc: [12, 13], note: 'functions passed as props', title: 'Handlers' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Handlers%2FButton" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <Slide transition={['zoom']}> <Heading size={1}> Encapsulation </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/button.example')} ranges={[ { loc: [2, 7], note: 'props', title: 'Button Component' }, { loc: [17, 18], note: 'label prop', title: 'Button Component' }, { loc: [9, 10], note: 'disabled prop', title: 'Button Component' }, { loc: [15, 16], note: 'click handler', title: 'Button Component' }, { loc: [10, 15], note: 'also leverage `disabled` to determine cursor', title: 'Button Component' } ]} /> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/props.example')} ranges={[ { loc: [18, 21], note: 'variable passed as a prop', title: 'Props' }, { loc: [21, 24], note: 'booleans can be passed as a flag', title: 'Props' } ]} /> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/handlers.example')} ranges={[ { loc: [22, 28], note: 'functions passed as props', title: 'Handlers' }, { loc: [25, 26], note: 'functions passed as props', title: 'Handlers' } ]} /> <Slide transition={['zoom']}> <Heading size={2} fit> Unit Tests </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/button-test.example')} ranges={[ { loc: [13, 20], title: 'Unit Testing with Enzyme', note: 'pass props to the button' }, { loc: [20, 21], title: 'Unit Testing with Enzyme', note: 'select the DOM <button/> within the wrapper' }, { loc: [21, 31], title: 'Unit Testing with Enzyme', note: 'verify that the props were passed down to the <button/>' }, { loc: [42, 46], title: 'Unit Testing with Enzyme', note: 'verify that the pointer is used as the cursor when the button is enabled' }, { loc: [34, 40], title: 'Unit Testing with Enzyme', note: 'being explicit about boolean flags (especially when false) helps clarify the intent of the test' }, { loc: [57, 61], title: 'Unit Testing with Enzyme', note: 'verify that not-allowed is used as the cursor when the button is enabled' }, { loc: [49, 55], title: 'Unit Testing with Enzyme', note: 'being explicit about boolean flags (even when true) helps clarify the intent of the test' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Handlers%2FButton" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Flux </Heading> </Slide> <Slide> <Heading size={2} fit> Unidirectional Data Flow </Heading> <Image src={images.unidirectional.replace('/', '')} /> </Slide> <Slide> <Heading size={2} fit> User Action </Heading> <Image src={images.userAction.replace('/', '')} /> </Slide> <Slide> <Heading size={2} fit> Functional Component </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/jsx-hello-world.example')} ranges={[ { loc: [2, 5], title: 'Functional Component', note: 'the entire component is just a function call' } ]} /> <Slide> <Heading size={2} fit> Container Component </Heading> <List> <Appear> <ListItem> State </ListItem> </Appear> <Appear> <ListItem> Lifecycle Hooks </ListItem> </Appear> <Appear> <ListItem> Instance Methods </ListItem> </Appear> </List> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/simple-container.example')} ranges={[ { loc: [1, 8], title: 'Container Component', note: 'maintains an instance' } ]} /> <Slide transition={['zoom']}> <Heading size={1} fit> State </Heading> <List> <Appear> <ListItem> Application </ListItem> </Appear> <Appear> <ListItem> Component </ListItem> </Appear> </List> </Slide> <Slide> <Heading size={2} fit> Controlled Input </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/controlled-input-stories.example')} ranges={[ { loc: [9, 12], title: 'Controlled Input', note: 'when `value` is set, only React can change the value' }, { loc: [12, 15], title: 'Controlled Input', note: 'when `value` is set, only React can change the value' }, { loc: [6, 9], title: 'Controlled Input', note: 'when `value` is not set, React is not controlling the state of the input' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Inputs" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/controlled-input.example')} ranges={[ { loc: [2, 3], title: 'Container Component', note: 'an instance needs to be created to maintain state' }, { loc: [12, 21], title: 'Container Component', note: 'the `render` function serves the same purpose as a functional component, but has privileged ' + 'access to instance properties' }, { loc: [16, 17], title: 'Container Component', note: 'the `value` is controlled using state' }, { loc: [3, 4], title: 'Container Component', note: 'state of `value` is initialized to an empty string. this could be initialized to a prop value' }, { loc: [5, 11], title: 'Container Component', note: 'the handler passed as `onChange` to the DOM element updates the internal component state' }, { loc: [17, 18], title: 'Container Component', note: 'the change-handler is passed to `onChange`' } ]} /> <Slide transition={['zoom']}> <Heading size={2} fit> Unit Tests </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/input-test.example')} ranges={[ { loc: [9, 10], title: 'Unit Testing with Enzyme', note: 'render the <Input />' }, { loc: [10, 14], title: 'Unit Testing with Enzyme', note: 'verify that the type is set correctly and that the value defaults to empty' }, { loc: [22, 26], title: 'Unit Testing with Enzyme', note: 'simulate a value change' }, { loc: [27, 31], title: 'Unit Testing with Enzyme', note: 'verify that the state was updated and flows down to the <input />' }, { loc: [37, 40], title: 'Unit Testing with Enzyme', note: 'provide an external change handler' }, { loc: [41, 48], title: 'Unit Testing with Enzyme', note: 'simulate a value change' }, { loc: [49, 55], title: 'Unit Testing with Enzyme', note: 'being explicit about boolean flags (even when true) helps clarify the intent of the test' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Inputs" target="_blank"> <Heading size={2}> Demo </Heading> </Link> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Navigation </Heading> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/navigation.example')} ranges={[ { loc: [2, 3], title: 'Navigation with linkTo', note: 'import the linkTo function' }, { loc: [17, 27], title: 'Navigation with linkTo', note: 'define onClick handlers to navigate' }, { loc: [19, 23], title: 'Navigation with linkTo', note: 'define onClick handlers to navigate' }, { loc: [33, 37], title: 'Navigation with linkTo', note: 'define onClick handlers to navigate' }, { loc: [43, 47], title: 'Navigation with linkTo', note: 'define onClick handlers to navigate' }, { loc: [57, 61], title: 'Navigation with linkTo', note: 'define onClick handlers to navigate' }, { loc: [20, 21], title: 'Navigation with linkTo', note: 'define the category that you want to navigate to' }, { loc: [13, 14], title: 'Navigation with linkTo', note: 'define the category that you want to navigate to' }, { loc: [21, 22], title: 'Navigation with linkTo', note: 'and the story name' }, { loc: [29, 30], title: 'Navigation with linkTo', note: 'and the story name' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Navigation%2FPagination%2FlinkTo" target="_blank" > <Heading size={2}> Demo </Heading> </Link> </Slide> <CodeSlide lang="jsx" code={require('../../assets/react-in-isolation/navigation.example')} ranges={[ { loc: [4, 5], title: 'Navigation with storybook-router', note: 'import the storybook-router' }, { loc: [84, 90], title: 'Navigation with storybook-router', note: 'define <Link>s to navigate' }, { loc: [90, 98], title: 'Navigation with storybook-router', note: 'define <Link>s to navigate' }, { loc: [98, 106], title: 'Navigation with storybook-router', note: 'define <Link>s to navigate' }, { loc: [70, 71], title: 'Navigation with storybook-router', note: 'add a decorator to define routes. storybook decorators are applied to each story' }, { loc: [71, 75], title: 'Navigation with storybook-router', note: 'map each route to a linkTo function' }, { loc: [75, 79], title: 'Navigation with storybook-router', note: 'map each route to a linkTo function' }, { loc: [79, 83], title: 'Navigation with storybook-router', note: 'map each route to a linkTo function' } ]} /> <Slide> <Link href="https://travi.github.io/react-in-isolation/?selectedKind=Navigation%2FPagination%2Frouter" target="_blank" > <Heading size={2}> Demo </Heading> </Link> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Next Steps </Heading> <List> <Appear> <ListItem> <Link href="https://storybook.js.org/addons/addon-gallery/" target="_blank" textColor="#888" > Storybook Plugins </Link> <List> <ListItem> <Link href="https://github.com/storybooks/storybook/tree/master/addons/knobs" target="_blank" textColor="#888" > Knobs </Link> {' - '} <Link href="https://www.youtube.com/watch?v=kopW6vzs9dg&feature=youtu.be" target="_blank" textColor="#888" > Demo Video </Link> </ListItem> <ListItem> <Link href="https://github.com/mthuret/storybook-addon-specifications" target="_blank" textColor="#888" > Specifications Addon </Link> </ListItem> </List> </ListItem> </Appear> <Appear> <ListItem> <Link href="https://github.com/facebookincubator/create-react-app" target="_blank" textColor="#888"> Create React App </Link> </ListItem> </Appear> <Appear> <ListItem> <Link href="https://presentations.travi.org/component-library/" target="_blank" textColor="#888"> Build an Interactive Component Library </Link> </ListItem> </Appear> </List> </Slide> <Slide transition={['zoom']}> <Heading size={1} fit> Matt Travi </Heading> <Layout> <Fit style={{paddingRight: 30}}> <Image style={{border: '10px solid #e5e5e5'}} src="https://secure.gravatar.com/avatar/552ffda146c8a19730e4e9a27dafb749?size=250" /> </Fit> <Fill> <List> <ListItem> <Link textColor="#888" target="_blank" href="https://matt.travi.org"> matt.travi.org </Link> </ListItem> <ListItem> <Link textColor="#888" target="_blank" href="https://twitter.com/mtravi"> twitter.com/mtravi </Link> </ListItem> <ListItem> <Link textColor="#888" target="_blank" href="https://github.com/travi/react-in-isolation/tree/icc-nov-2017" > github.com/travi/react-in-isolation </Link> </ListItem> <ListItem> <Link textColor="#888" target="_blank" href="https://presentations.travi.org/react-in-isolation-icc-nov-2017" > presentations.travi.org/react-in-isolation-icc-nov-2017 </Link> </ListItem> </List> </Fill> </Layout> </Slide> </Deck> ); } Presentation.displayName = 'Presentation';
src/svg-icons/av/volume-mute.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVolumeMute = (props) => ( <SvgIcon {...props}> <path d="M7 9v6h4l5 5V4l-5 5H7z"/> </SvgIcon> ); AvVolumeMute = pure(AvVolumeMute); AvVolumeMute.displayName = 'AvVolumeMute'; AvVolumeMute.muiName = 'SvgIcon'; export default AvVolumeMute;
packages/ringcentral-widgets/components/DurationCounter/index.js
ringcentral/ringcentral-js-widget
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import formatDuration from '../../lib/formatDuration'; export default class DurationCounter extends Component { constructor(props) { super(props); this.state = this.calculateState(); } componentDidMount() { this.interval = setInterval(() => { this.setState(this.calculateState()); }, 1000); } componentWillUnmount() { clearInterval(this.interval); } calculateState() { const startTime = this.props.startTime + this.props.offset; return { duration: Math.round((new Date().getTime() - startTime) / 1000), }; } render() { return ( <span className={this.props.className}> {formatDuration(this.state.duration)} </span> ); } } DurationCounter.propTypes = { className: PropTypes.string, startTime: PropTypes.number.isRequired, offset: PropTypes.number, }; DurationCounter.defaultProps = { className: null, offset: 0, };
examples/counter/containers/App.js
ataker/redux-devtools
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import * as reducers from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)), createStore ); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <CounterApp />} </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div> ); } }
cerberus-dashboard/src/components/Header/Header.js
Nike-Inc/cerberus
/* * Copyright (c) 2020 Nike, inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react' import { Component } from 'react' import * as headerActions from '../../actions/headerActions' import * as authActions from '../../actions/authenticationActions' import './Header.scss' import '../../assets/images/cerberus-logo-narrow-off-white.svg' import * as modalActions from '../../actions/modalActions' import ViewTokenModal from '../ViewTokenModal/ViewTokenModal' import { push } from 'connected-react-router'; export default class Header extends Component { render() { return ( <header id='header'> <div id='bottom-header'> <div id='header-logo' onClick={ function(dispatch) { push('/') }.bind(this, this.props.dispatch) }></div> <div id='header-title' className='ncss-brand u-uppercase un-selectable'>Cerberus</div> <UserBox userName={this.props.userName} displayUserContextMenu={this.props.displayUserContextMenu} dispatch={this.props.dispatch} cerberusAuthToken={this.props.cerberusAuthToken} isAdmin={this.props.isAdmin}/> </div> </header> ) } } class UserBox extends Component { constructor(props) { super(props) this.handleMouseClickUserName = function() { this.props.dispatch(headerActions.mouseOverUsername()) }.bind(this) this.handleMouseLeaveUserMenuContext = function() { this.props.dispatch(headerActions.mouseOutUsername()) }.bind(this) this.handleMouseClickSdbSummary = function() { this.props.dispatch(push('/admin/sdb-metadata')) }.bind(this) this.handleMouseClickViewToken = function() { this.props.dispatch(modalActions.pushModal(<ViewTokenModal />)) }.bind(this) this.handleMouseClickLogout = function() { this.props.dispatch(authActions.logoutUser(this.props.cerberusAuthToken)) }.bind(this) } render() { let isAdmin = this.props.isAdmin return ( <div id='user-box' className='ncss-brand u-uppercase'> <div id='u-b-container' onClick={this.handleMouseClickUserName} onMouseLeave={this.handleMouseLeaveUserMenuContext} > <div id='u-b-name'>{this.props.userName}</div> <div id='u-b-ico' className={this.props.displayUserContextMenu ? 'ncss-glyph-arrow-down' : 'ncss-glyph-arrow-down rot-90'}></div> </div> <div id='u-b-context-menu' className={this.props.displayUserContextMenu ? 'show-me-block' : 'hide-me'} onMouseEnter={this.handleMouseClickUserName} onMouseLeave={this.handleMouseLeaveUserMenuContext} > {isAdmin && <div className='context-menu-button' onClick={ this.handleMouseClickSdbSummary }>SDB Summary</div>} <div className='context-menu-button' onClick={ this.handleMouseClickViewToken }>View Token</div> <div className='context-menu-button' onClick={this.handleMouseClickLogout}>Logout</div> </div> </div> ) } }
src/components/RepositoryInfoComponent.js
krzysztofkolek/react-github-client
'use strict'; require('styles//RepositoryInfo.css'); import React from 'react'; import dispatcher from '../dispatcher/Dispatcher' import * as RepositoryInfoAction from '../actions/RepositoryInfoAction' import SearchStore from '../stores/SearchStore' import RepositoryInfoStore from '../stores/RepositoryInfoStore' class RepositoryInfoComponent extends React.Component { constructor(props) { super(props); this.state = { login: '', selectedRepo: '', repos: [] } } componentWillMount() { var self = this; SearchStore.on('usernamechanged', () => { if(self.state.login != SearchStore.getCurrentUserName()) { var response = RepositoryInfoStore.getRepositoryList(); response.then(function(repos) { self.setState({ login: SearchStore.getCurrentUserName(), selectedRepo: repos[0], repos: repos }); }) } }); } availableRepositories() { return this.state.repos.map(function(repo, index) { return <option key={index}>{ repo }</option> }); } renderCommits() { return <div> {this.state.commits.map(function(commit, index){ return <div key={index}> <div> {commit.author.name} </div> <div> {commit.author.email} </div> <div> {commit.author.date} </div> <div> {commit.message} </div> </div> })} </div> } renderForks() { return <div> {this.state.forks.map(function(fork, index){ return <div key={index}> {fork.full_name} </div> })} </div> } renderPullRequests() { return <div> renderPullRequests </div> } renderContributors() { return <div> {this.state.contributors.map(function(contributor, index){ return <div key={index}> {contributor.login} </div> })} </div> } renderContent() { switch (this.state.activeContent) { case 'commits': return this.renderCommits(); case 'forks': return this.renderForks(); case 'pullRequests': return this.renderPullRequests(); case 'contributors': return this.renderContributors(); } } onActiveContentChange(e) { console.log(e.target.name) this.setState({ activeContent: e.target.name }) } onSelectChange(e) { var self = this; self.state.selectedRepo = e.target.value; var response = RepositoryInfoStore.getSelectedRepositoryData(e.target.value); response.then(function(result) { self.setState(result); }); } render() { return ( <div className="repositoryinfo-component"> <div> <div> Repositories: <select onChange={this.onSelectChange.bind(this)} value={this.state.selectedRepo}> {this.availableRepositories()} </select> </div> <div> <button name="commits" onClick={this.onActiveContentChange.bind(this)}>Commits</button> <button name="forks" onClick={this.onActiveContentChange.bind(this)}>Forks</button> <button name="pullRequests" onClick={this.onActiveContentChange.bind(this)}>Pulls</button> <button name="contributors" onClick={this.onActiveContentChange.bind(this)}>Contributors</button> </div> </div> <div> {this.renderContent()} </div> </div> ); } } RepositoryInfoComponent.displayName = 'RepositoryInfoComponent'; // Uncomment properties you need // RepositoryInfoComponent.propTypes = {}; // RepositoryInfoComponent.defaultProps = {}; export default RepositoryInfoComponent;
src/components/DragGroup/DragGroupDropArea.js
Bandwidth/shared-components
import React from 'react'; import PropTypes from 'prop-types'; import { DropTarget } from 'react-dnd'; import * as styles from './styles'; /** * The droppable area of a DragGroup. Connected to react-dnd. * Renders its children when idle, but if a dragging operation is * ongoing, its default Content presenter will render a * drop zone box. * * You may reference this component if you choose to override it * in DragGroup, otherwise it is not needed. See DragGroup docs. */ class DragGroupDropArea extends React.Component { static propTypes = { itemType: PropTypes.string.isRequired, groupId: PropTypes.number.isRequired, Content: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), }; static defaultProps = { Content: styles.DropAreaContent, }; static styles = styles; render() { const { connectDropTarget, Content, canDrop, isOver, children, groupId, ...rest } = this.props; return connectDropTarget( <div {...rest}> <Content canDrop={canDrop} isOver={isOver}> {children} </Content> </div>, ); } } const dropSource = { drop(props) { return { type: 'group', groupId: props.groupId, }; }, }; const collect = (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), canDrop: monitor.canDrop(), isOver: monitor.isOver(), }); export default DropTarget(props => props.itemType, dropSource, collect)( DragGroupDropArea, );
client/containers/LogoutLink.js
nurpax/snap-reactjs-todo
import React from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { logout } from '../auth' const Logout = function ({ logout, to, children }) { return <Link to={to} onClick={(e) => logout()}>{children}</Link> } export default connect(false, { logout })(Logout)
src/utils/ValidComponentChildren.js
bbc/react-bootstrap
import React from 'react'; /** * Maps children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { let index = 0; return React.Children.map(children, child => { if (React.isValidElement(child)) { let lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { let index = 0; return React.Children.forEach(children, child => { if (React.isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { let count = 0; React.Children.forEach(children, child => { if (React.isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { let hasValid = false; React.Children.forEach(children, child => { if (!hasValid && React.isValidElement(child)) { hasValid = true; } }); return hasValid; } function find(children, finder) { let child; forEachValidComponents(children, (c, idx) => { if (!child && finder(c, idx, children)) { child = c; } }); return child; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} findFunc. * @param {*} findContext Context for findContext. * @returns {array} of children that meet the findFunc return statement */ function findValidComponents(children, func, context) { let index = 0; let returnChildren = []; React.Children.forEach(children, child => { if (React.isValidElement(child)) { if (func.call(context, child, index)) { returnChildren.push(child); } index++; } }); return returnChildren; } export default { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, find, findValidComponents, hasValidComponent };
ui/js/components/Button.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class Button extends Component { constructor() { super(); this._layout = this._layout.bind(this); this._onClick = this._onClick.bind(this); this.state = {}; } componentDidMount() { const { left, right } = this.props; if (left || right) { this._layout(); } } componentWillReceiveProps(nextProps) { if ((nextProps.left || nextProps.right) && nextProps.label !== this.props.label) { this._needLayout = true; } } componentDidUpdate() { if (this._needLayout) { this._needLayout = false; this._layout(); } } _layout() { // avoid sub-pixel label width for left/right buttons setTimeout(() => { const width = this._componentRef.offsetWidth; // align to even pixels to avoid gap, who knows why this.setState({ width: width + (width % 2) }); }, 10); } _onClick(event) { const { path, replaceHistory } = this.props; const { router } = this.context; event.preventDefault(); if (replaceHistory) { router.history.replace(path); } else { router.history.push(path); } } render() { const { children, circle, className, icon, label, left, path, plain, right, secondary, tag, type, } = this.props; const { width } = this.state; const { router } = this.context; const Tag = tag || (path ? 'a' : 'button'); const classNames = []; let contents = label || icon || children; let arrow; const style = this.props.style ? { ...this.props.style } : {}; if (circle) { classNames.push('button-circle'); contents = <span className="button__label">{contents}</span>; } else if (left) { classNames.push('button-left'); arrow = ( <svg viewBox="0 0 24 24" preserveAspectRatio="none" width="24" className="button__arrow"> <path d="M24,0 L24,24 L0,12 Z" /> </svg> ); if (width) { style.minWidth = width; } contents = ( <span className="button__label">{contents}</span> ); } else if (right) { classNames.push('button-right'); arrow = ( <svg viewBox="0 0 24 24" preserveAspectRatio="none" width="24" className="button__arrow"> <path d="M0,0 L24,12 L0,24 Z" /> </svg> ); if (width) { style.minWidth = width; } contents = ( <span className="button__label">{contents}</span> ); } else if (icon && !label) { classNames.push('button-icon'); } else if (plain) { classNames.push('button-plain'); } else { classNames.push('button'); } if (secondary) { classNames.push('button--secondary'); } if (className) { classNames.push(className); } let href; let onClick; if (this.props.onClick) { onClick = this.props.onClick; } else if (this.props.path) { href = router.history.createHref({ pathname: this.props.path }); onClick = this._onClick; } return ( <Tag ref={(ref) => { this._componentRef = ref; }} className={classNames.join(' ')} href={href} type={Tag === 'button' ? type : undefined} onClick={onClick} style={style}> {contents} {arrow} </Tag> ); } } Button.propTypes = { children: PropTypes.any, circle: PropTypes.bool, className: PropTypes.string, icon: PropTypes.node, label: PropTypes.node, left: PropTypes.bool, onClick: PropTypes.func, path: PropTypes.string, plain: PropTypes.bool, replaceHistory: PropTypes.bool, right: PropTypes.bool, secondary: PropTypes.bool, style: PropTypes.object, tag: PropTypes.string, type: PropTypes.oneOf(['button', 'submit']), }; Button.defaultProps = { children: undefined, circle: false, className: undefined, icon: undefined, label: undefined, left: false, onClick: undefined, path: undefined, plain: false, replaceHistory: false, right: false, secondary: false, style: undefined, tag: undefined, type: 'button', }; Button.contextTypes = { router: PropTypes.any, };
src/client.js
CalebEverett/soulpurpose
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; import makeRouteHooksSafe from './helpers/makeRouteHooksSafe'; const client = new ApiClient(); // Three different types of scroll behavior available. // Documented here: https://github.com/rackt/scroll-behavior const scrollablehistory = useScroll(createHistory); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), scrollablehistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <ReduxRouter routes={getRoutes(store)} /> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
renderer/vectors/crop.js
wulkano/kap
import React from 'react'; import Svg from './svg'; const CropIcon = props => ( <Svg {...props}> <path d="M7 17V1H5v4H1v2h4v10a2 2 0 0 0 2 2h10v4h2v-4h4v-2m-6-2h2V7a2 2 0 0 0-2-2H9v2h8v8z"/> </Svg> ); export default CropIcon;
core/src/plugins/gui.ajax/res/js/ui/HOCs/selection/selection.js
ChuckDaniels87/pydio-core
/* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio 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. * * Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ import React from 'react'; import { connect } from 'react-redux'; import SelectionModel from './model'; import { EditorActions, getDisplayName } from '../utils'; import { mapStateToProps } from './utils'; const withSelection = (getSelection) => { return (Component) => { class WithSelection extends React.Component { constructor(props) { super(props) const {node, id, dispatch} = this.props if (typeof dispatch === 'function') { // We have a redux dispatch so we use it this.setState = (data) => dispatch(EditorActions.tabModify({id, ...data})) } } static get displayName() { return `WithSelection(${getDisplayName(Component)})` } static get propTypes() { return { node: React.PropTypes.instanceOf(AjxpNode).isRequired } } componentDidMount() { const {id, node, tabModify} = this.props getSelection(node).then(({selection, currentIndex}) => this.setState({id, selection: new SelectionModel(selection, currentIndex)})) } render() { const {id, selection, playing, dispatch, ...remainingProps} = this.props if (!selection) { return ( <Component {...remainingProps} /> ) } return ( <Component {...remainingProps} node={selection.current()} selectionPlaying={playing} onRequestSelectionPlay={() => this.setState({id, node: selection.nextOrFirst(), title: selection.current().getLabel()})} /> ) } } return connect(mapStateToProps)(WithSelection) } } export default withSelection
src/ActivityEditor.js
siiptuo/taimio-spa
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { date, time } from './filters'; import * as activity from './activity'; import { fetchActivity, updateActivity, resumeActivity, removeActivity, } from './actions'; import { getWeekRange } from './List'; function parseLocalDate(input) { return new Date(input.replace(/-/g, '/').replace('T', ' ')); } function isOnSameDay(date1, date2) { return ( date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() ); } export class ActivityEditor extends React.Component { static contextTypes = { router: PropTypes.object, }; static propTypes = { params: PropTypes.shape({ id: PropTypes.string.isRequired, }).isRequired, dispatch: PropTypes.func.isRequired, location: PropTypes.object.isRequired, activity: activity.propType, loading: PropTypes.bool.isRequired, }; constructor(props) { super(props); this.state = {}; } setActivityState = activity => { if (!activity) { return; } const ongoing = activity.finished_at == null; this.setState({ ongoing, startedAtDate: date(activity.started_at), startedAtTime: time(activity.started_at, true), finishedAtTime: time(ongoing ? new Date() : activity.finished_at, true), input: activity.title + (activity.tags.length > 0 ? ' #' + activity.tags.join(' #') : ''), }); }; componentDidMount() { if (this.props.activity) { this.setActivityState(this.props.activity); } else { this.props.dispatch(fetchActivity(this.props.match.params.id)); } } componentWillReceiveProps(nextProps) { this.setActivityState(nextProps.activity); } onStartedAtDateChange = event => { this.setState({ startedAtDate: event.target.value }); }; onStartedAtTimeChange = event => { this.setState({ startedAtTime: event.target.value }); }; onFinishedAtTimeChange = event => { this.setState({ finishedAtTime: event.target.value }); }; onOngoingChange = event => { this.setState({ ongoing: event.target.checked }); }; onInputChange = event => { this.setState({ input: event.target.value }); }; onSave = event => { event.preventDefault(); const { title, tags } = activity.parseInput(this.state.input); const startedAt = parseLocalDate( `${this.state.startedAtDate}T${this.state.startedAtTime}`, ); let finishedAt = null; if (!this.state.ongoing) { finishedAt = parseLocalDate( `${this.state.startedAtDate}T${this.state.finishedAtTime}`, ); if (this.state.finishedAtTime < this.state.startedAtTime) { finishedAt.setDate(finishedAt.getDate() + 1); } } this.props .dispatch( updateActivity({ id: this.props.activity.id, title, tags, started_at: startedAt, finished_at: finishedAt, }), ) .then(() => { this.goBack(); }); }; onCancel = event => { event.preventDefault(); this.goBack(); }; onResume = event => { event.preventDefault(); this.props.dispatch(resumeActivity(this.props.activity.id)).then(() => { this.props.history.push('/'); }); }; onRemove = event => { event.preventDefault(); if (confirm('Remove activity?')) { const activity = { ...this.props.activity }; this.props.dispatch(removeActivity(this.props.activity.id)).then(() => { this.goBack(activity); }); } }; goBack = (activity = this.props.activity) => { // Simply go back if there is history. if (this.props.history.action === 'PUSH') { this.props.history.goBack(); } else { // Try to be smart when there is no history by going to the page where // the activity is listed. if (isOnSameDay(activity.started_at, new Date())) { this.props.history.push('/'); } else { const [start, end] = getWeekRange(activity.started_at).map(date); this.props.history.push({ pathname: '/list', query: { start, end }, }); } } }; render() { if (this.props.loading) { return <div>Loading...</div>; } return ( <form> <fieldset> <legend>Time</legend> <div className="time-input"> <input type="date" value={this.state.startedAtDate} size={10} onChange={this.onStartedAtDateChange} /> <input type="time" value={this.state.startedAtTime} size={5} onChange={this.onStartedAtTimeChange} /> - <input type="time" value={this.state.finishedAtTime} disabled={this.state.ongoing} size={5} onChange={this.onFinishedAtTimeChange} /> <label> <input type="checkbox" checked={this.state.ongoing} onChange={this.onOngoingChange} /> Ongoing </label> </div> </fieldset> <label> Activity: <input type="text" value={this.state.input} onChange={this.onInputChange} /> </label> <div className="action-area"> <button onClick={this.onCancel}>Cancel</button> <button onClick={this.onRemove}>Remove</button> {this.props.activity.finished_at ? ( <button onClick={this.onResume}>Resume</button> ) : null} <button onClick={this.onSave}>Save</button> </div> </form> ); } } function mapStateToProps(state, ownProps) { const activity = state.activities.activities[ownProps.match.params.id]; return { activity, loading: !activity, }; } export default connect(mapStateToProps)(ActivityEditor);
src/js/components/icons/base/SocialMastercard.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-social-mastercard`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'social-mastercard'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="#FF5F00" fillRule="evenodd" d="M9.17131814,12.4194933 C9.17131814,10.0493774 10.2842421,7.94718763 11.9948475,6.58694718 C10.7376556,5.59768141 9.15070843,5 7.41949332,5 C3.31816229,5 0,8.31816229 0,12.4194933 C0,16.5208244 3.31816229,19.8389866 7.41949332,19.8389866 C9.15070843,19.8389866 10.7376556,19.2413052 11.9948475,18.2520395 C10.2842421,16.9124087 9.17131814,14.7896092 9.17131814,12.4194933 L9.17131814,12.4194933 Z M24,12.4194933 C24,16.5208244 20.6818377,19.8389866 16.5805067,19.8389866 C14.8492916,19.8389866 13.2623444,19.2413052 12.0051525,18.2520395 C13.7363676,16.891799 14.8286819,14.7896092 14.8286819,12.4194933 C14.8286819,10.0493774 13.7157579,7.94718763 12.0051525,6.58694718 C13.2623444,5.59768141 14.8492916,5 16.5805067,5 C20.6818377,5 24,8.338772 24,12.4194933 L24,12.4194933 Z" stroke="none"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'SocialMastercard'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
blueocean-material-icons/src/js/components/svg-icons/maps/satellite.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsSatellite = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.99h3C8 6.65 6.66 8 5 8V4.99zM5 12v-2c2.76 0 5-2.25 5-5.01h2C12 8.86 8.87 12 5 12zm0 6l3.5-4.5 2.5 3.01L14.5 12l4.5 6H5z"/> </SvgIcon> ); MapsSatellite.displayName = 'MapsSatellite'; MapsSatellite.muiName = 'SvgIcon'; export default MapsSatellite;
src/CarouselItem.js
justinanastos/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const CarouselItem = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, caption: React.PropTypes.node, index: React.PropTypes.number }, getInitialState() { return { direction: null }; }, getDefaultProps() { return { active: false, animateIn: false, animateOut: false }; }, handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.handleAnimateOutEnd ); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render() { let classes = { item: true, active: (this.props.active && !this.props.animateIn) || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} {this.props.caption ? this.renderCaption() : null} </div> ); }, renderCaption() { return ( <div className="carousel-caption"> {this.props.caption} </div> ); } }); export default CarouselItem;
actor-apps/app-web/src/app/components/DialogSection.react.js
treejames/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; let 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 member</h3> </section> ); } return ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <MessagesSection messages={this.state.messagesToRender} peer={this.state.peer} ref="MessagesSection"/> {memberArea} </section> ); } else { return ( <section className="dialog dialog--empty row middle-xs center-xs"> Select dialog or start a new one. </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/pages/index.js
xiaoxinghu/home
import React from 'react' import style from './_style.module.scss' export default class Index extends React.Component { render() { const { html, meta } = this.props.data.orga const { title } = meta return ( <div> <h1 className={style.title}>{ title }</h1> <div style={{maxWidth: '50rem', margin: '0 auto'}} dangerouslySetInnerHTML={{ __html: html }} /> </div> ) } } /* export default props => { * const { html, meta } = props.data.orga * const { title } = meta * return ( * <div> * <h1 className={style.title}>{ frontmatter.title }</h1> * <div style={{maxWidth: '50rem', margin: '0 auto'}} * dangerouslySetInnerHTML={{ __html: html }} /> * </div> * ) * } * */ export const pageQuery = graphql` query Intro { orga(fileAbsolutePath: {regex: "/intro.org/"}) { html meta } } `
node_modules/react-bootstrap/es/MediaHeading.js
yeshdev1/Everydays-project
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'h4' }; var MediaHeading = function (_React$Component) { _inherits(MediaHeading, _React$Component); function MediaHeading() { _classCallCheck(this, MediaHeading); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaHeading.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaHeading; }(React.Component); MediaHeading.propTypes = propTypes; MediaHeading.defaultProps = defaultProps; export default bsClass('media-heading', MediaHeading);
app/components/PaginationBar/index.js
oliv37/vocab-front
/** * * PaginationBar * */ import React from 'react'; import styles from './styles.css'; function PaginationBar({ currentPage, totalPage, changePage }) { const showPreviousBtn = currentPage > 1; const showNextBtn = totalPage > currentPage; const onPreviousBtnClick = () => { changePage(currentPage - 1); }; const onNextBtnClick = () => { changePage(currentPage + 1); }; return totalPage > 0 ? ( <div className={styles.paginationBar}> {showPreviousBtn && <input type="button" value="<" onClick={onPreviousBtnClick} />} &nbsp; <b>{currentPage} / {totalPage}</b> &nbsp; {showNextBtn && <input type="button" value=">" onClick={onNextBtnClick} />} </div> ) : null; } PaginationBar.propTypes = { currentPage: React.PropTypes.number.isRequired, totalPage: React.PropTypes.number.isRequired, changePage: React.PropTypes.func.isRequired, }; export default PaginationBar;
docs/src/app/components/pages/components/Dialog/ExampleSimple.js
hai-cea/material-ui
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; /** * Dialog with action buttons. The actions are passed in as an array of React objects, * in this example [FlatButtons](/#/components/flat-button). * * You can also close this dialog by clicking outside the dialog, or with the 'Esc' key. */ export default class DialogExampleSimple extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onClick={this.handleClose} />, <FlatButton label="Submit" primary={true} keyboardFocused={true} onClick={this.handleClose} />, ]; return ( <div> <RaisedButton label="Dialog" onClick={this.handleOpen} /> <Dialog title="Dialog With Actions" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > The actions in this window were passed in as an array of React objects. </Dialog> </div> ); } }
consoles/my-joy-templates/src/app.js
yldio/joyent-portal
import React from 'react'; import Helmet from 'react-helmet-async'; import { RootContainer } from 'joyent-ui-toolkit'; import Routes from '@root/routes'; export default () => ( <RootContainer> <Helmet> <title>Templates</title> </Helmet> <Routes /> </RootContainer> );
src/components/entries_new.js
calvincolton/timesheet
import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { createDate } from '../actions'; class EntriesNew extends Component { renderField(field) { const { meta: { touched, error } } = field; const className = `form-group ${touched && error ? 'has-danger' : ''}`; return ( <div className={className}> <label>{field.label}</label> <input type={field.inputType} className={field.inputClass} {...field.input} /> <div className="text-help"> {touched ? error : ''} </div> </div> ); } onSubmit(values) { this.props.createDate(values, () => { this.props.history.push('/'); }); } render() { const { handleSubmit } = this.props; return ( <div> <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <Field name="title" label="Date:" inputType="date" component={this.renderField} /> <Field name="categories" label="Start time:" inputType="time" component={this.renderField} /> <Field name="endTime" label="End Time:" inputType="time" component={this.renderField} /> <Field name="content" label="Notes:" inputType="text" inputClass="form-control" component={this.renderField} /> <button type="submit" className="btn btn-primary">Save Entry</button> <Link to="/" className="btn btn-danger">Cancel</Link> </form> </div> ); } } function validate(values) { const errors = {}; // validate inputs from 'values' if (!values.date) { errors.date = "Please enter a month, day, and the year for the date."; } if (!values.startTime) { errors.startTime = "Please enter the hour and minutes of your start time and indicate AM or PM"; } if (!values.endTime) { errors.endTime = "Please enter the hour and minutes of your end time and indicate AM or PM"; } if (!values.comments) { errors.comments = "Please indicate what you were working on in the Notes section."; } // if errors is empty, the form is ok to submit // if errors has any properties, redux form assumes invalid return errors; } export default reduxForm({ validate, form: 'EntriesNewForm' })( connect(null, { createDate })(EntriesNew) );
packages/react-native-renderer/src/ReactNativeComponent.js
jameszhan/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import type { MeasureInWindowOnSuccessCallback, MeasureLayoutOnSuccessCallback, MeasureOnSuccessCallback, NativeMethodsMixinType, ReactNativeBaseComponentViewConfig, } from './ReactNativeTypes'; import React from 'react'; // Modules provided by RN: import TextInputState from 'TextInputState'; import UIManager from 'UIManager'; import * as ReactNativeAttributePayload from './ReactNativeAttributePayload'; import {mountSafeCallback_NOT_REALLY_SAFE} from './NativeMethodsMixinUtils'; export default function( findNodeHandle: any => ?number, findHostInstance: any => any, ) { /** * Superclass that provides methods to access the underlying native component. * This can be useful when you want to focus a view or measure its dimensions. * * Methods implemented by this class are available on most default components * provided by React Native. However, they are *not* available on composite * components that are not directly backed by a native view. For more * information, see [Direct Manipulation](docs/direct-manipulation.html). * * @abstract */ class ReactNativeComponent<Props, State = void> extends React.Component< Props, State, > { /** * Due to bugs in Flow's handling of React.createClass, some fields already * declared in the base class need to be redeclared below. */ props: Props; state: State; /** * Removes focus. This is the opposite of `focus()`. */ blur(): void { TextInputState.blurTextInput(findNodeHandle(this)); } /** * Requests focus. The exact behavior depends on the platform and view. */ focus(): void { TextInputState.focusTextInput(findNodeHandle(this)); } /** * Measures the on-screen location and dimensions. If successful, the callback * will be called asynchronously with the following arguments: * * - x * - y * - width * - height * - pageX * - pageY * * These values are not available until after natives rendering completes. If * you need the measurements as soon as possible, consider using the * [`onLayout` prop](docs/view.html#onlayout) instead. */ measure(callback: MeasureOnSuccessCallback): void { UIManager.measure( findNodeHandle(this), mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } /** * Measures the on-screen location and dimensions. Even if the React Native * root view is embedded within another native view, this method will give you * the absolute coordinates measured from the window. If successful, the * callback will be called asynchronously with the following arguments: * * - x * - y * - width * - height * * These values are not available until after natives rendering completes. */ measureInWindow(callback: MeasureInWindowOnSuccessCallback): void { UIManager.measureInWindow( findNodeHandle(this), mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } /** * Similar to [`measure()`](#measure), but the resulting location will be * relative to the supplied ancestor's location. * * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. */ measureLayout( relativeToNativeNode: number, onSuccess: MeasureLayoutOnSuccessCallback, onFail: () => void /* currently unused */, ): void { UIManager.measureLayout( findNodeHandle(this), relativeToNativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess), ); } /** * This function sends props straight to native. They will not participate in * future diff process - this means that if you do not include them in the * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ setNativeProps(nativeProps: Object): void { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. // Use findNodeHandle() rather than ReactNative.findNodeHandle() because // We want the instance/wrapper (not the native tag). let maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. try { maybeInstance = findHostInstance(this); } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. if (maybeInstance == null) { return; } const viewConfig: ReactNativeBaseComponentViewConfig<> = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; const updatePayload = ReactNativeAttributePayload.create( nativeProps, viewConfig.validAttributes, ); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. if (updatePayload != null) { UIManager.updateView( maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload, ); } } } // eslint-disable-next-line no-unused-expressions (ReactNativeComponent.prototype: NativeMethodsMixinType); return ReactNativeComponent; }
src/containers/Notify.js
dzwiedziu-nkg/books-collection-frontend
import React from 'react'; import { connect } from 'react-redux'; import Main from '../components/basic/Notify'; class Notify extends React.Component { render() { const { text, style } = this.props; if (text === null) { return null; } return (<Main style={style}>{text}</Main>); } } function mapStateToProps(state, ownProps) { return { text: state.mode.notify, style: state.mode.notify_style } } Notify = connect(mapStateToProps)(Notify); export default Notify;
webpack/scenes/RedHatRepositories/components/RepositorySetRepositories.js
stbenjam/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert, Spinner } from 'patternfly-react'; import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories'; import RepositorySetRepository from './RepositorySetRepository'; class RepositorySetRepositories extends Component { componentDidMount() { const { contentId, productId } = this.props; if (this.props.data.loading) { this.props.loadRepositorySetRepos(contentId, productId); } } render() { const { data } = this.props; if (data.error) { return ( <Alert type="danger"> <span>{data.error.displayMessage}</span> </Alert> ); } const repos = data.repositories .filter(({ enabled }) => !enabled) .map(repo => <RepositorySetRepository key={repo.arch + repo.releasever} {...repo} />); return ( <Spinner loading={data.loading}> {repos.length ? repos : <div>{__('No repositories available.')}</div>} </Spinner> ); } } RepositorySetRepositories.propTypes = { loadRepositorySetRepos: PropTypes.func.isRequired, contentId: PropTypes.string.isRequired, productId: PropTypes.number.isRequired, data: PropTypes.shape({ loading: PropTypes.bool.isRequired, repositories: PropTypes.arrayOf(PropTypes.object), }).isRequired, }; const mapStateToProps = ( { katello: { redHatRepositories: { repositorySetRepositories } } }, props, ) => ({ data: repositorySetRepositories[props.contentId] || { loading: true, repositories: [], error: null, }, }); export default connect(mapStateToProps, { loadRepositorySetRepos, })(RepositorySetRepositories);
src/TableBody.js
archr/react-tables
import React from 'react'; export default class TableBody extends React.Component { static contextTypes = { columns: React.PropTypes.array, loading: React.PropTypes.bool, rows: React.PropTypes.array, classes: React.PropTypes.string, dimentions: React.PropTypes.object } constructor(props, context) { super(props, context); this.getTr = this.getTr.bind(this); } getTr(row, index) { let { columns, rows } = this.context; if (!columns) return null; return ( <tr key={index}> {columns.map(({ Component, formatter, field, title, classes }) => { let style = {}; if (!classes) { style.width = parseFloat((100 / columns.length)).toFixed(2) + '%'; } if (Component) { return <td key={title} className={classes || ''} style={style}> <Component row={row}/> </td>; } else if (formatter) { return <td key={title} className={classes || '' } style={style} dangerouslySetInnerHTML={{__html: formatter(row[field], row)}}></td>; } else { return <td key={title} className={classes || ''} style={style}>{row[field] || '-'}</td>; } })} </tr> ); } render() { let { columns, loading, rows, classes, dimentions } = this.context; return ( <div style={{height: dimentions.height, overflow: 'auto'}}> <table className={classes}> <tbody> { loading ? <tr><td colSpan={columns.length} style={{textAlign: 'center'}}>Loading...</td></tr> : rows.map(this.getTr) } { loading || rows.length ? null : <tr><td colSpan={columns.length} style={{textAlign: 'center'}}>No information</td></tr> } </tbody> </table> </div> ); } }
src/interface/others/AverageTargetsHit.js
FaideWW/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; class AverageTargetsHit extends React.PureComponent { static propTypes = { casts: PropTypes.number.isRequired, hits: PropTypes.number.isRequired, unique: PropTypes.bool, approximate: PropTypes.bool, }; render() { const { casts, hits, unique, approximate } = this.props; const averageHits = ((hits / casts) || 0).toFixed(1); if (!unique) { return ( <> {approximate && '≈'}{averageHits}{' average '}{averageHits > 1 ? ' hits per cast' : 'target per cast'} </> ); } else { return ( <> {approximate && '≈'}{averageHits}{' unique '}{averageHits > 1 ? 'targets per cast' : 'target per cast'} </> ); } } } export default AverageTargetsHit; AverageTargetsHit.defaultProps = { approximate: false, };
src/svg-icons/av/skip-next.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSkipNext = (props) => ( <SvgIcon {...props}> <path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/> </SvgIcon> ); AvSkipNext = pure(AvSkipNext); AvSkipNext.displayName = 'AvSkipNext'; AvSkipNext.muiName = 'SvgIcon'; export default AvSkipNext;
src/svg-icons/av/mic-none.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMicNone = (props) => ( <SvgIcon {...props}> <path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1.2-9.1c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2l-.01 6.2c0 .66-.53 1.2-1.19 1.2-.66 0-1.2-.54-1.2-1.2V4.9zm6.5 6.1c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/> </SvgIcon> ); AvMicNone = pure(AvMicNone); AvMicNone.displayName = 'AvMicNone'; AvMicNone.muiName = 'SvgIcon'; export default AvMicNone;
src/interface/icons/Avoidance.js
sMteX/WoWAnalyzer
import React from 'react'; import Icon from 'common/Icon'; const icon = props => ( <Icon icon="ability_rogue_quickrecovery" {...props} /> ); export default icon;
src/scenes/home/families/facts/facts.js
miaket/operationcode_frontend
import React from 'react'; import styles from './facts.css'; import family3 from '../../../../images/Family-3.jpg'; const Facts = () => ( <div className={styles.facts}> <div className={styles.factsList}> <div className={styles.factsHeading}> <h5>The Facts</h5> </div> <ul> <li className={styles.factItem}> There are approximately 710,000 active duty spouses, 93% of whom are female. An additional 500,000 spouses are married to a Reservist or National Guardsman. </li> <li className={styles.factItem}> 84% have some college education; 25% hold an undergraduate degree; and 10% hold a postgraduate degree. </li> <li className={styles.factItem}> 77% of spouses report that they want or need to work. 38% of military spouses are underemployed, compared to approximately 6% rate for civilian spouses. </li> <li className={styles.factItem}> Only 19% of military spouses have adequate full-time employment. </li> </ul> </div> <div className={styles.factsRight}> <img className={styles.factsImage} src={family3} alt="" /> </div> </div> ); export default Facts;
docs/app/Examples/elements/Button/Content/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ButtonContentExamples = () => ( <ExampleSection title='Content'> <ComponentExample title='Conditionals' description='Button groups can contain conditionals.' examplePath='elements/Button/Content/ButtonExampleConditionals' /> <ComponentExample examplePath='elements/Button/Content/ButtonExampleMultipleConditionals' /> </ExampleSection> ) export default ButtonContentExamples
client/components/header.js
twistedSynapse/nodeServerBareBones
import React from 'react'; import { Link } from 'react-router-dom'; import { AppBar, Navigation, Button } from 'react-toolbox'; import appBarTheme from '../theme/appBar.css'; function Header(props) { return ( <AppBar title='AIoT' leftIcon='menu' theme={appBarTheme}> <Navigation type='horizontal'> <Link to="/home"><Button icon='inbox' label='Home' flat /></Link> {!props.user.authenticated && <Link to="/register" ><Button icon='inbox' label='Register' flat /></Link>} {!props.user.authenticated && <Link to="/login" ><Button icon='inbox' label='Login' flat /></Link>} {props.user.authenticated && <Button icon='inbox' label='Signout' flat onClick={this.props.signoutUser} />} </Navigation> </AppBar> ); } export default Header;
src/js/pages/Results/index.js
nathanuphoff/datahub.client
import React from 'react'; export default class Results extends React.Component { render() { return <h1>Results</h1> } }
frontend/src/components/popup/NewProductAdmin.js
jirkae/BeerCheese
import React from 'react'; import { Modal, ModalBody, Container, Row, Form, FormGroup, Label, Input, Button, Col, InputGroupAddon, InputGroup, } from 'reactstrap'; import api from '../../api'; export default class NewProductAdmin extends React.Component { constructor(props) { super(props); this.state = { categories: [], subCategories: [], suppliers: [] }; } componentDidMount() { this.loadSuppliers(); this.loadCategories(); this.loadSubCategories(1); } loadSuppliers = () => { api.get('suppliers') .then((response) => { if (response) { this.setState({ suppliers: response.data.suppliers.items.map(item => { return item.supplier }) }); } }) .catch(response => { console.log('error ', response); }); }; loadCategories = () => { api.get('categories') .then(response => { if (response) { this.setState({ categories: response.data.categories.items.map(item => { return item.category }) }); } }) .catch(response => { console.log('error ', response); }); }; loadSubCategories = (subCategoryId) => { api.get('categories?mainCategory=' + subCategoryId) .then(response => { if (response) { this.setState({ subCategories: response.data.categories.items.map(item => { return item.category }) }); } }) .catch(response => { console.log('error ', response); }); }; onSubmit = (event) => { event.preventDefault(); api.post('products', new FormData(event.target)) .then(data => { console.log('success ', data); }) .catch(response => { console.log('error ', response); }); }; onCategoryChosen = (event) => { this.loadSubCategories(event.target.value); }; renderCategoryOptions = () => { return this.state.categories.map(category => { return ( <option key={category.id} value={category.id}>{category.name}</option> ); }); }; renderSubCategoryOptions = () => { return this.state.subCategories.map(category => { return ( <option key={category.id} value={category.id}>{category.name}</option> ); }); }; renderSupplierOptions = () => { return this.state.suppliers.map(supplier => { return ( <option key={supplier.id} value={supplier.id}>{supplier.name}</option> ); }); }; render() { return ( <Modal isOpen={true} toggle={this.props.hideModals}> <ModalBody> <Container> <Row> <h3>Přidat produkt</h3> <br/> <br/> <Form onSubmit={this.onSubmit}> <FormGroup row> <Label for="productName" sm={4}>Název</Label> <Col sm={8}> <Input required type="text" name="productName" id="productName"/> </Col> </FormGroup> <FormGroup row> <Label for="productPrice" sm={4}>Cena</Label> <Col sm={8}> <InputGroup> <Input required type="number" name="productPrice" id="productPrice"/> <InputGroupAddon>Kč</InputGroupAddon> </InputGroup> </Col> </FormGroup> <FormGroup row> <Label for="productPriceAfterDiscount" sm={4}>Cena po slevě</Label> <Col sm={8}> <InputGroup> <Input type="number" name="productPriceAfterDiscount" id="productPriceAfterDiscount"/> <InputGroupAddon>Kč</InputGroupAddon> </InputGroup> </Col> </FormGroup> <FormGroup row> <Label for="productQuantity" sm={4}>Skladem</Label> <Col sm={8}> <InputGroup> <Input type="number" name="productQuantity" id="productQuantity" defaultValue="0"/> <InputGroupAddon>Ks</InputGroupAddon> </InputGroup> </Col> </FormGroup> <FormGroup row> <Label for="productCategory" sm={4}>Kategorie</Label> <Col sm={8}> <Input onChange={this.onCategoryChosen} required type="select" name="productCategory" id="productCategory"> {this.renderCategoryOptions()} </Input> </Col> </FormGroup> <FormGroup row> <Label for="productSubCategory" sm={4}>Podkategorie</Label> <Col sm={8}> <Input disabled={this.state.subCategories.length === 0} required type="select" name="productSubCategory" id="productSubCategory"> {this.renderSubCategoryOptions()} </Input> </Col> </FormGroup> <FormGroup row> <Label for="productSupplier" sm={4}>Dodavatel</Label> <Col sm={8}> <Input type="select" name="productSupplier" id="productSupplier"> {this.renderSupplierOptions()} </Input> </Col> </FormGroup> <FormGroup row> <Label for="productDesc" sm={4}>Popis</Label> <Col sm={8}> <Input type="textarea" name="productDesc" id="productDesc"/> </Col> </FormGroup> <FormGroup check row> <Col sm={{size: 10, offset: 2}}> <Button type="submit">Vytvořit</Button> </Col> </FormGroup> </Form> </Row> </Container> </ModalBody> </Modal> ); } }
src/Navbar.js
mmartche/boilerplate-shop
import classNames from 'classnames'; import React from 'react'; import deprecated from 'react-prop-types/lib/deprecated'; import elementType from 'react-prop-types/lib/elementType'; import BootstrapMixin from './BootstrapMixin'; import Grid from './Grid'; import NavBrand from './NavBrand'; import createChainedFunction from './utils/createChainedFunction'; import ValidComponentChildren from './utils/ValidComponentChildren'; const Navbar = React.createClass({ mixins: [BootstrapMixin], propTypes: { fixedTop: React.PropTypes.bool, fixedBottom: React.PropTypes.bool, staticTop: React.PropTypes.bool, inverse: React.PropTypes.bool, fluid: React.PropTypes.bool, role: React.PropTypes.string, /** * You can use a custom element for this component */ componentClass: elementType, brand: deprecated(React.PropTypes.node, 'Use the `NavBrand` component.'), toggleButton: React.PropTypes.node, toggleNavKey: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), onToggle: React.PropTypes.func, navExpanded: React.PropTypes.bool, defaultNavExpanded: React.PropTypes.bool }, getDefaultProps() { return { bsClass: 'navbar', bsStyle: 'default', role: 'navigation', componentClass: 'nav', fixedTop: false, fixedBottom: false, staticTop: false, inverse: false, fluid: false, defaultNavExpanded: false }; }, getInitialState() { return { navExpanded: this.props.defaultNavExpanded }; }, shouldComponentUpdate() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleToggle() { if (this.props.onToggle) { this._isChanging = true; this.props.onToggle(); this._isChanging = false; } this.setState({ navExpanded: !this.state.navExpanded }); }, isNavExpanded() { return this.props.navExpanded != null ? this.props.navExpanded : this.state.navExpanded; }, hasNavBrandChild() { return ValidComponentChildren.findValidComponents( this.props.children, child => child.props.bsRole === 'brand' ).length > 0; }, render() { const { brand, toggleButton, toggleNavKey, fixedTop, fixedBottom, staticTop, inverse, componentClass: ComponentClass, fluid, className, children, ...props } = this.props; const classes = this.getBsClassSet(); classes['navbar-fixed-top'] = fixedTop; classes['navbar-fixed-bottom'] = fixedBottom; classes['navbar-static-top'] = staticTop; classes['navbar-inverse'] = inverse; const showHeader = (brand || toggleButton || toggleNavKey != null) && !this.hasNavBrandChild(); return ( <ComponentClass {...props} className={classNames(className, classes)}> <Grid fluid={fluid}> {showHeader ? this.renderBrandHeader() : null} {ValidComponentChildren.map(children, this.renderChild)} </Grid> </ComponentClass> ); }, renderBrandHeader() { let {brand} = this.props; if (brand) { brand = <NavBrand>{brand}</NavBrand>; } return this.renderHeader(brand); }, renderHeader(brand) { const hasToggle = this.props.toggleButton || this.props.toggleNavKey != null; return ( <div className="navbar-header"> {brand} {hasToggle ? this.renderToggleButton() : null} </div> ); }, renderChild(child, index) { const key = child.key != null ? child.key : index; if (child.props.bsRole === 'brand') { return React.cloneElement(this.renderHeader(child), {key}); } const {toggleNavKey} = this.props; const collapsible = toggleNavKey != null && toggleNavKey === child.props.eventKey; return React.cloneElement(child, { navbar: true, collapsible, expanded: collapsible && this.isNavExpanded(), key }); }, renderToggleButton() { const {toggleButton} = this.props; if (React.isValidElement(toggleButton)) { return React.cloneElement(toggleButton, { className: classNames(toggleButton.props.className, 'navbar-toggle'), onClick: createChainedFunction( this.handleToggle, toggleButton.props.onClick ) }); } let children; if (toggleButton != null) { children = toggleButton; } else { children = [ <span className="sr-only" key={0}>Toggle navigation</span>, <span className="icon-bar" key={1}></span>, <span className="icon-bar" key={2}></span>, <span className="icon-bar" key={3}></span> ]; } return ( <button type="button" onClick={this.handleToggle} className="navbar-toggle" > {children} </button> ); } }); export default Navbar;
packages/icons/src/md/image/Filter4.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFilter4(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M6 10H2v32c0 2.21 1.79 4 4 4h32v-4H6V10zm24 20h4V10h-4v8h-4v-8h-4v12h8v8zM42 2c2.21 0 4 1.79 4 4v28c0 2.21-1.79 4-4 4H14c-2.21 0-4-1.79-4-4V6c0-2.21 1.79-4 4-4h28zm0 32V6H14v28h28z" /> </IconBase> ); } export default MdFilter4;
examples/basic/example.js
alexmnv/react-navtree
import React from 'react' import PropTypes from 'prop-types' import Nav, {navDynamic} from 'react-navtree' import './example.css' class Header extends React.PureComponent { constructor (props) { super(props) this.state = { tab: 'tab-foo' } } render () { return <Nav className='header'> <Nav onNav={path => { if (path) this.setState({ tab: path[0] }) }} func={/* focus open tab first */ (key, navTree, focusedNode) => !navTree.focusedNode ? this.state.tab : navDynamic(key, navTree, focusedNode)} className='tabs' > <Nav navId='tab-foo' className={this.state.tab === 'tab-foo' ? 'selected' : ''}>Foo</Nav> <Nav navId='tab-qux' className={this.state.tab === 'tab-qux' ? 'selected' : ''}>Qux</Nav> </Nav> { this.state.tab === 'tab-foo' && <Nav className='tab-content' > <Nav className='nav-block inline'>Foo</Nav> <Nav className='nav-block inline'>Bar</Nav> <Nav className='nav-block inline'>Baz</Nav> </Nav> } { this.state.tab === 'tab-qux' && <Nav className='tab-content' > <Nav className='nav-block'>Qux</Nav> <Nav className='nav-block'>Quux</Nav> </Nav> } </Nav> } } class Table extends React.PureComponent { constructor (props) { super(props) this.state = { focusedPath: false } } render () { let {children, navId, cols} = this.props return <Nav onNav={path => { this.setState({ focusedPath: path }) }} navId={navId} className='nav-block'> <div className='caption'>{ this.state.focusedPath && 'Focused: ' + this.state.focusedPath.join(' -> ') }</div> <div className={'tbl col' + cols}> { children.map((child, i) => <div key={i}><Nav navId={`row ${Math.ceil((i + 1) / cols)} cell ${(i % cols) + 1}`} className='nav-block'>{child}</Nav></div>) } </div> </Nav> } } Table.propTypes = { children: PropTypes.node, navId: PropTypes.string, cols: PropTypes.number } class Body extends React.PureComponent { render () { return (<div> <Table cols={3}> <div>A</div> <div>B</div> <div>C</div> <div>D</div> <div>E</div> <div>F</div> <div>G</div> <div>H</div> <div>J</div> </Table> <Table cols={2}> <Table navId='table 1' cols={2}> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </Table> <Table navId='table 2' cols={2}> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </Table> </Table> </div>) } } class Footer extends React.PureComponent { render () { return ( <Nav className='footer'> <Nav className='nav-block inline'>Foo</Nav> <Nav className='nav-block inline'>Bar</Nav> <Nav className='nav-block inline'>Baz</Nav> </Nav> ) } } export default function Example () { return <Nav> <Header /> <Body /> <Footer /> </Nav> }
frontend/src/Welcome.js
natsukagami/hakkero-project
import React from 'react'; import { Row, Col, Image } from 'react-bootstrap'; import logo from './logo.png'; export default function Welcome() { return ( <Row> <Col md={3}> <Image src={logo} responsive /> </Col> <Col md={9}> <h2>Hakkero Project!</h2> <h4> A mini web novel game where players strives to win by writing the best collaborative story they can come up with. </h4> <div> The rules are simple: <ul> <li>You are given a topic, along with some other players</li> <li> The goal is to write the best story...<em> together</em> </li> <li>Each take turn and make one sentence in a specified time.</li> <li>You can skip your turn, but there's no turning back.</li> <li>The winner keeps the story alive until sunrise.</li> </ul> <b> Respect other players. If you have no idea, do not spam. Keep the game clear! </b> </div> </Col> </Row> ); }
client-src/components/comparison/header/Price.js
minimus/final-task
import React from 'react' import propTypes from 'prop-types' export default function Price({ price }) { return ( <div className="price-item-wrapper"> <span className="price-item">{price}</span> </div> ) } Price.propTypes = { price: propTypes.number.isRequired, }
docs/src/app/components/pages/components/AppBar/ExampleIconMenu.js
rscnt/material-ui
import React from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; const AppBarExampleIconMenu = () => ( <AppBar title="Title" iconElementLeft={<IconButton><NavigationClose /></IconButton>} iconElementRight={ <IconMenu iconButtonElement={ <IconButton><MoreVertIcon /></IconButton> } targetOrigin={{horizontal: 'right', vertical: 'top'}} anchorOrigin={{horizontal: 'right', vertical: 'top'}} > <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help" /> <MenuItem primaryText="Sign out" /> </IconMenu> } /> ); export default AppBarExampleIconMenu;
src/view/Lib.js
blockkeeper/blockkeeper-frontend-web
import React from 'react' import { Link } from 'react-router-dom' import MenuItem from '@material-ui/core/MenuItem' import Tabs from '@material-ui/core/Tabs' import Tab from '@material-ui/core/Tab' import AppBar from '@material-ui/core/AppBar' import List from '@material-ui/core/List' import ListItem from '@material-ui/core/ListItem' import ListItemIcon from '@material-ui/core/ListItemIcon' import ListItemText from '@material-ui/core/ListItemText' import FormControl from '@material-ui/core/FormControl' import Select from '@material-ui/core/Select' import ScrollToTop from 'react-scroll-up' import Tooltip from '@material-ui/core/Tooltip' import Input from '@material-ui/core/Input' import InputLabel from '@material-ui/core/InputLabel' import Grid from '@material-ui/core/Grid' import Toolbar from '@material-ui/core/Toolbar' import Paper from '@material-ui/core/Paper' import Divider from '@material-ui/core/Divider' import Hidden from '@material-ui/core/Hidden' import Button from '@material-ui/core/Button' import * as CryptoIcons from 'react-cryptocoins' import getSymbolFromCurrency from 'currency-symbol-map' import Snackbar from '@material-ui/core/Snackbar' import IconButton from '@material-ui/core/IconButton' import Typography from '@material-ui/core/Typography' import { UserAgentProvider, UserAgent } from '@quentin-sommer/react-useragent' import LinearProgress from '@material-ui/core/LinearProgress' import { Add, Close, Autorenew, AccountCircle, InfoOutline, KeyboardArrowUp, Error, Feedback, BugReport, Email, ExitToApp, DeleteForever } from '@material-ui/icons' import Dialog from '@material-ui/core/Dialog' import DialogActions from '@material-ui/core/DialogActions' import DialogContent from '@material-ui/core/DialogContent' import DialogContentText from '@material-ui/core/DialogContentText' import DialogTitle from '@material-ui/core/DialogTitle' import MobileStepper from '@material-ui/core/MobileStepper' import SwipeableViews from 'react-swipeable-views' import TransitiveNumber from 'react-transitive-number' import FormHelperText from '@material-ui/core/FormHelperText' import { AreaClosed, Line, Bar, Pie } from '@vx/shape' import { Group } from '@vx/group' import { curveMonotoneX } from '@vx/curve' import { scaleTime, scaleLinear } from '@vx/scale' import { withTooltip, Tooltip as VxTooltip } from '@vx/tooltip' import { localPoint } from '@vx/event' import { extent, max, min, bisector } from 'd3-array' import { withParentSize } from '@vx/responsive' import { LinearGradient } from '@vx/gradient' import { theme, floatBtnStyle, CryptoColors, gridWrap } from './Style' import __ from '../util' const setBxpTrigger = view => { view.cx.tmp.bxp = () => setTimeout(() => { view.info('View update triggered by bxp') view.setSnack('Synchronization complete') view.load() }, 1000) view.cx.tmp.bxpSts = (sts) => { view.info(`View's bxp status set to "${sts}"`) view.setState({ bxpSts: sts }) } } const unsetBxpTrigger = view => { delete view.cx.tmp.bxp delete view.cx.tmp.bxpSts } const TopBar = ({ title, midTitle, action, onClick, iconLeft, onClickLeft, color, noUser, modeCancel, isActionAllowed = true }) => <AppBar position='fixed' color={color || 'default'} elevation={0} style={{ zIndex: 1200 }} > <div style={{ ...gridWrap, width: '100%' }}> <Toolbar style={{ minHeight: '50px' }}> <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}> <div style={{ marginRight: 'auto' }}> {modeCancel && <Typography variant='h5' color='inherit' onClick={onClickLeft} style={{ fontSize: '16px', cursor: 'pointer' }} > Cancel </Typography>} {iconLeft && <IconButton aria-label='Menu' onClick={onClickLeft} color='inherit' style={{ right: theme.spacing.unit * 2, marginRight: 'auto' }} > {iconLeft} </IconButton>} {title && <Typography variant='h5' color='inherit'> <Hidden xsDown> <span>BlockKeeper</span> </Hidden> <Hidden smUp> <span>BK</span> </Hidden> </Typography>} </div> </div> <div> <Typography variant='h5' color='inherit' align='center' style={{ flex: 1, fontSize: '16px', fontWeight: '700' }} > {midTitle || ''} </Typography> </div> <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}> <div style={{ marginLeft: 'auto' }}> {action && <Typography variant='h5' color='inherit' onClick={onClick} style={{ fontSize: '16px', cursor: isActionAllowed ? 'pointer' : 'not-allowed', opacity: isActionAllowed ? 1 : 0.5 }} > {action} </Typography>} {!noUser && <Link to={'/user/edit'} style={{ color: 'white' }}> <IconButton aria-label='Menu' color='inherit' style={{ left: theme.spacing.unit * 2 }} > <AccountCircle /> </IconButton> </Link>} </div> </div> </Toolbar> </div> </AppBar> const SubBar = ({ tabs, ix, onClick }) => <AppBar position='static' style={{ position: 'relative', backgroundColor: 'white' }}> <Tabs centered value={ix} onChange={onClick} indicatorColor='primary' textColor='primary' > {tabs.map(lbl => <Tab key={__.uuid()} label={lbl} /> )} </Tabs> </AppBar> const DepotHoldings = ({ title, subTitle, coin0, coin1, h2ClassName, holdingsClassName, locale }) => <div key='depot-holdings' className={holdingsClassName}> <Typography align='center' variant='h2' color='inherit' className={h2ClassName} > <TransitiveNumber> {title ? __.formatNumber(title, coin0, locale) : __.formatNumber(0, coin0, locale) } </TransitiveNumber>&nbsp; <Hidden xsDown> <CoinIcon coin={coin0} size={35} color={'white'} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={coin0} size={32} color={'white'} alt /> </Hidden> </Typography> <Typography align='center' variant='h5' color='inherit'> <TransitiveNumber> {subTitle ? __.formatNumber(subTitle, coin1, locale) : __.formatNumber(0, coin1, locale)} </TransitiveNumber>&nbsp; {coin1 && <CoinIcon coin={coin1} color={'white'} alt />} </Typography> </div> class DoughnutOrig extends React.Component { render () { const { pWidth, pHeight, data, radius } = this.props const width = pWidth || this.props.parentWidth const height = pHeight || this.props.parentHeight if (width < 10) return null return ( <svg width={width} height={height}> <Group top={height / 2} left={width / 3}> <Pie data={data} pieValue={d => d.amnt} outerRadius={radius} innerRadius={radius - 25} fill={d => d.data.color} centroid={(centroid, arc) => { return <text textAnchor='left' x={width / 4} y={(arc.index * 20) - 30} fontSize={theme.typography.caption.fontSize} fontWeight={'bold'} fill={'#fff'} fontFamily={theme.typography.fontFamily} > <tspan fill={arc.data.color} fontSize={theme.typography.caption.fontSize * 1.3} > &#9679; </tspan> &nbsp; {arc.data.label} </text> }} /> </Group> </svg> ) } } const Doughnut = withParentSize(DoughnutOrig) const DepotDoughnut = ({ doughnutClassName, doughnutData, letters, width, height, radius }) => <div key='depot-doughnut' className={doughnutClassName}> <Doughnut radius={radius} data={doughnutData} /> </div> const Jumbo = ({ title, subTitle, coin0, coin1, h2ClassName, holdingsClassName, doughnutClassName, locale, handleStepChange, activeStep, doughnutData, widthType }) => <div> {doughnutData.length !== 0 ? <div> <SwipeableViews axis='x' index={activeStep} onChangeIndex={handleStepChange} enableMouseEvents > <DepotHoldings title={title} subTitle={subTitle} coin0={coin0} coin1={coin1} h2ClassName={h2ClassName} holdingsClassName={holdingsClassName} locale={locale} /> <DepotDoughnut doughnutClassName={doughnutClassName} doughnutData={doughnutData} radius={widthType === 'xs' ? 50 : 62} /> </SwipeableViews> <MobileStepper steps={2} position='static' activeStep={activeStep} /> </div> : <DepotHoldings title={title} subTitle={subTitle} coin0={coin0} coin1={coin1} h2ClassName={h2ClassName} holdingsClassName={holdingsClassName} locale={locale} /> } </div> const ToTopBtn = ({ className }) => <ScrollToTop showUnder={200} style={{ right: '50%', bottom: theme.spacing.unit * 2 }} > <Button variant='fab' aria-label='top' color='default' classes={{ fab: className }} > <KeyboardArrowUp /> </Button> </ScrollToTop> const FloatBtn = ({ onClick, key, actnBtnClrClassName }) => <Button variant='fab' aria-label='add' color='primary' style={floatBtnStyle} onClick={onClick} key={key || __.uuid()} classes={{ containedPrimary: actnBtnClrClassName }} > <Add /> </Button> const BxpFloatBtn = ({ onClick, bxpSts, second }) => { let icon, lbl, dsbld if (bxpSts === 'blocked') { /* lbl = 'Blocked' icon = <HourglassEmpty /> dsbld = true */ return null } else if (bxpSts === 'run') { lbl = 'Updating' icon = <Autorenew style={{ animation: 'spin 1s linear infinite' }} /> dsbld = true } else { // ready lbl = 'Update' icon = <Autorenew /> dsbld = false } return ( <Button variant='fab' aria-label={lbl} color='default' onClick={onClick} key='bxpFloatBtn' disabled={dsbld} style={{ ...floatBtnStyle, bottom: second ? theme.spacing.unit * 10 : theme.spacing.unit * 2 }} > {icon} </Button> ) } const tscRow = ( addr, tsc, coin0, addrIcon, showAddrInfos, gridWrapClassName, gridGutterClassName, itemClassName, h4ClassName, body1ClassName, tscAmntClassName, tscIconClassname, noTxtDecoClassname, locale, aLength, i ) => { const mx = 40 let modeColor = tsc.mode === 'snd' ? theme.palette.error['500'] : theme.palette.secondary['500'] let modeSign = tsc.mode === 'snd' ? '-' : '+' let tags = tsc.tags.join(' ') if (tags.length > mx) tags = tags.slice(0, mx) + '...' let desc = tsc.desc if (desc.length > mx) desc = desc.slice(0, mx) + '...' return ( <div key={tsc._id} className={gridWrapClassName}> <Link to={`/tsc/${addr._id}/${tsc._id}`} className={noTxtDecoClassname} > <div className={gridGutterClassName}> <div className={itemClassName}> {addrIcon && <div className={tscIconClassname}> <Hidden xsDown> <CoinIcon coin={addr.coin} size={42} /> </Hidden> <Hidden smUp> <CoinIcon coin={addr.coin} size={28} /> </Hidden> </div> } <div style={{flexGrow: 1, minWidth: 0}}> <Typography variant='body1' className={body1ClassName} style={{color: theme.palette.text.secondary}} > {__.ppTme(tsc._t)} </Typography> <Typography variant='h4' className={h4ClassName} style={{ color: theme.palette.text.primary }} noWrap > {showAddrInfos && addr.name} {!showAddrInfos && tsc.name} </Typography> <Typography variant='body1' className={body1ClassName} style={{color: theme.palette.text.secondary}} noWrap > {showAddrInfos && (tsc.name || tsc.desc)} {!showAddrInfos && (tsc.desc || 'No description')} </Typography> </div> <div className={tscAmntClassName}> <Typography variant='h4' style={{ color: modeColor }} className={h4ClassName} > {modeSign} {__.formatNumber(tsc.amnt, addr.coin, locale, true)}&nbsp; <Hidden xsDown> <CoinIcon coin={addr.coin} color={modeColor} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={addr.coin} color={modeColor} size={12} alt /> </Hidden> </Typography> <Typography variant='body1' style={{color: theme.palette.text.secondary}} className={body1ClassName} gutterBottom > {modeSign} {__.formatNumber(tsc.amnt * addr.rates[coin0], coin0, locale, true)} <Hidden xsDown> <CoinIcon coin={coin0} color={theme.palette.text.secondary} size={12} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={coin0} color={theme.palette.text.secondary} size={10} alt /> </Hidden> </Typography> </div> </div> {aLength > 1 && i !== aLength - 1 && <Hidden mdDown> <Divider /> </Hidden>} </div> {aLength > 1 && i !== aLength - 1 && <Hidden lgUp> <Divider /> </Hidden>} </Link> </div> ) } const TscListAddr = ({ addr, tscs, coin0, addrIcon, className, gridGutterClassName, itemClassName, gridWrapClassName, h4ClassName, body1ClassName, tscAmntClassName, noTxtDecoClassname, locale }) => <Paper square className={className} elevation={4} > {tscs.map((tsc, i) => { return tscRow( addr, tsc, coin0, addrIcon, false, gridWrapClassName, gridGutterClassName, itemClassName, h4ClassName, body1ClassName, tscAmntClassName, undefined, noTxtDecoClassname, locale, tscs.length, i ) })} </Paper> const TscListAddresses = ({ addrTscs, coin0, addrIcon, className, gridGutterClassName, itemClassName, gridWrapClassName, h4ClassName, body1ClassName, tscAmntClassName, tscIconClassname, noTxtDecoClassname, locale }) => <Paper square className={className} > {addrTscs.map((addrTsc, i) => { return tscRow( addrTsc[0], addrTsc[1], coin0, addrIcon, true, gridWrapClassName, gridGutterClassName, itemClassName, h4ClassName, body1ClassName, tscAmntClassName, tscIconClassname, noTxtDecoClassname, locale, addrTscs.length, i ) })} </Paper> const Snack = ({msg, onClose}) => <Snackbar open autoHideDuration={3500} transitionDuration={500} anchorOrigin={{vertical: 'top', horizontal: 'center'}} onClose={onClose} ContentProps={{'aria-describedby': 'message-id'}} message={<span id='message-id'>{msg}</span>} action={[ <IconButton key='close' aria-label='Close' color='inherit' style={{width: theme.spacing.unit * 4, height: theme.spacing.unit * 4}} onClick={onClose} > <Close /> </IconButton> ]} /> const ExtLink = ({to, txt, className, style}) => <a href={to} target='_blank' className={className} style={style}> {txt} </a> class Modal extends React.Component { constructor (props) { super(props) this.state = {} this.children = props.children this.open = (props.open == null) ? true : props.open this.onClose = props.onClose this.lbl = props.lbl || 'Error' let acs = props.actions || [{lbl: 'OK', onClick: this.onClose}] if (!props.noCncl && this.lbl.toLowerCase() !== 'error') { acs.push({lbl: 'Cancel', onClick: this.onClose}) } this.btns = [] for (let ac of acs) { this.btns.push( <Button key={ac.key || __.uuid()} onClick={ props.withBusy ? async (...args) => { this.setState({busy: true}) const d = await ac.onClick(...args) return d } : ac.onClick } > {ac.lbl} </Button> ) } } render () { return ( <Dialog open={this.open} onClose={this.onClose} style={{background: theme.palette.background.default}} > <DialogTitle>{this.lbl}</DialogTitle> <DialogContent> <DialogContentText>{this.children}</DialogContentText> </DialogContent> {!this.state.busy && this.btns && <DialogActions>{this.btns}</DialogActions>} {this.state.busy && <LinearProgress />} </Dialog> ) } } class BrowserGate extends React.Component { render () { return ( <UserAgentProvider ua={window.navigator.userAgent}> <UserAgent returnFullParser> {parser => ( <div> {( (parser.getBrowser().name === 'Chrome' && Number(parser.getBrowser().major) >= 60) || (parser.getBrowser().name === 'Edge' && Number(parser.getBrowser().major) >= 16) || (parser.getBrowser().name === 'Safari' && Number(parser.getBrowser().major) >= 11) || (parser.getBrowser().name === 'Mobile Safari' && Number(parser.getBrowser().major) >= 9) || (parser.getBrowser().name === 'Opera' && Number(parser.getBrowser().major) >= 48) || (parser.getBrowser().name === 'Firefox' && Number(parser.getBrowser().major) >= 55) ) ? this.props.allwd : this.props.ntAll} </div> )} </UserAgent> </UserAgentProvider> ) } } class BrowserGateSafarimobile extends React.Component { render () { return ( <UserAgentProvider ua={window.navigator.userAgent}> <UserAgent returnFullParser> {parser => ( <div> {(parser.getBrowser().name === 'Mobile Safari') ? this.props.safari : this.props.rest} </div> )} </UserAgent> </UserAgentProvider> ) } } const NtAllwd = () => { return <div> <Typography variant='h6' align='center' gutterBottom style={{marginTop: '40px', marginBottom: '40px'}} > Your Browser is not supported! <br /> <b>Please upgrade your browser to access <nobr>BlockKeeper</nobr></b>. </Typography> <Typography variant='body1' align='center' gutterBottom> Required: Chrome > 60, Edge > 16, Safari > 11, Opera > 48, Firefox > 55 </Typography> </div> } const CoinIcon = ({coin, alt, color, size, style}) => { color = theme.palette.text[color] || color || CryptoColors[coin.toUpperCase()] coin = __.cap(coin.toLowerCase()) if (CryptoIcons[coin]) { if (alt) { coin = coin + 'Alt' } const IconType = CryptoIcons[coin] return <IconType color={color} size={size || '18'} style={style} /> } return <span>{getSymbolFromCurrency(coin.toUpperCase())}</span> } const DepotEmpty = ({className}) => <div> <Grid container spacing={0} justify='center'> <Grid item xs={6} className={className}> <Typography variant='h3' gutterBottom style={{ color: theme.palette.text.primary, marginTop: '130px' }} > Welcome to BlockKeeper </Typography> <Typography variant='subtitle1' gutterBottom> In order to start using our app, please go ahead and connect your first wallet. </Typography> </Grid> </Grid> </div> const SoonMsg = ({ className, noTxtDecoClassname }) => <Grid container spacing={0} justify='center'> <Grid item xs={6} className={className}> <Typography variant='h3' gutterBottom style={{ marginTop: '80px' }}> Soon™ </Typography> <a href='https://t.me/blockkeeperio' target='_blank' className={noTxtDecoClassname} rel='noopener noreferrer'> <Button color='default' variant='contained' > Tell us your Ideas </Button> </a> </Grid> </Grid> const PortfolioTab = ({ portfolio, className, gridGutterClassName, itemClassName, gridWrapClassName, h4ClassName, body1ClassName, prtfAmntClassName, coinIconClassname, noTxtDecoClassname, locale }) => <Paper square className={className} > {Object.keys(portfolio).map((coin, i) => <div key={coin} className={gridWrapClassName}> <Link to={`/history/${coin}`} className={noTxtDecoClassname} > <div className={gridGutterClassName}> <div className={itemClassName}> <div className={coinIconClassname}> <Hidden xsDown> <CoinIcon coin={coin} size={42} /> </Hidden> <Hidden smUp> <CoinIcon coin={coin} size={28} /> </Hidden> </div> <div style={{flexGrow: 1, minWidth: 0}}> <Typography variant='h4' className={h4ClassName} style={{ color: theme.palette.text.primary }} noWrap > {portfolio[coin].label} </Typography> <Typography variant='body1' className={body1ClassName} style={{color: theme.palette.text.secondary}} noWrap > {__.formatNumber(portfolio[coin].amntCoin, coin, locale)}&nbsp; <Hidden xsDown> <CoinIcon coin={coin} color={theme.palette.text.secondary} size={12} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={coin} color={theme.palette.text.secondary} size={10} alt /> </Hidden> </Typography> </div> <div className={prtfAmntClassName}> <Typography variant='h4' style={{ color: portfolio[coin].color }} className={h4ClassName} > <div style={{ display: 'inline-block', transform: portfolio[coin].percentChange > 0 ? 'rotate(180deg)' : 'rotate(0deg)' }}>▾</div>&nbsp; {__.formatNumber(portfolio[coin].rate, portfolio[coin].pCoin, locale)}&nbsp; <Hidden xsDown> <CoinIcon coin={portfolio[coin].pCoin} color={portfolio[coin].color} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={portfolio[coin].pCoin} color={portfolio[coin].color} size={12} alt /> </Hidden> </Typography> <Typography variant='body1' style={{ color: theme.palette.text.secondary, display: 'inline-block', paddingRight: theme.spacing.unit }} className={body1ClassName} gutterBottom > {portfolio[coin].percentChange.toFixed(2)}% </Typography> <Typography variant='body1' style={{ color: portfolio[coin].color, display: 'inline-block' }} className={body1ClassName} gutterBottom > {__.formatNumber(portfolio[coin].amntByCoinRate, portfolio[coin].pCoin, locale)}&nbsp; <Hidden xsDown> <CoinIcon coin={portfolio[coin].pCoin} color={portfolio[coin].color} size={12} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={portfolio[coin].pCoin} color={portfolio[coin].color} size={10} alt /> </Hidden> </Typography> </div> </div> {Object.keys(portfolio).length > 1 && i !== Object.keys(portfolio).length - 1 && <Hidden mdDown> <Divider /> </Hidden>} </div> {Object.keys(portfolio).length > 1 && i !== Object.keys(portfolio).length - 1 && <Hidden lgUp> <Divider /> </Hidden>} </Link> </div> )} </Paper> const PaperGrid = ({ addrs, coin0, addrUpdIds, addrUpdErrIds, className, itemClassName, addrClassName, amntClassName, h4ClassName, body1ClassName, noTxtDecoClassname, locale }) => { return ( <Paper square elevation={0} className={className} > {addrs.map(addr => { return ( <Link to={`/wallet/${addr._id}`} className={noTxtDecoClassname} key={addr._id} > <Paper elevation={4} className={itemClassName} > <div> <Hidden xsDown> <CoinIcon coin={addr.coin} size={42} /> </Hidden> <Hidden smUp> <CoinIcon coin={addr.coin} size={28} /> </Hidden> </div> <div className={addrClassName}> <Typography variant='h4' className={h4ClassName} style={{ color: theme.palette.text.primary }} noWrap > {addr.name}&nbsp; {addrUpdErrIds.has(addr._id) && <InfoUpdateFailed />} </Typography> <Typography variant='body1' className={body1ClassName} noWrap > {addr.desc && <Hidden smDown> <span>{/* }<b>Note</b>&nbsp; */}</span> </Hidden> } {!addr.desc && addr.hsh && <Hidden smDown> <span><b>Wallet</b>&nbsp;</span> </Hidden> } {!addr.desc && !addr.hsh && <Hidden smDown> <span><b>Manual wallet</b>&nbsp;</span> </Hidden> } {addr.desc || (addr.hsh ? (addr.type === 'hd' ? `${__.shortn(addr.hsh, 7)}...` : addr.hsh ) : '' ) } </Typography> </div> <div className={amntClassName}> <Typography variant='h4' color='primary' className={h4ClassName} > {__.formatNumber(addr.amnt, addr.coin, locale, true)}&nbsp; <Hidden xsDown> <CoinIcon coin={addr.coin} color={theme.palette.primary['500']} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={addr.coin} color={theme.palette.primary['500']} size={12} alt /> </Hidden> </Typography> <Typography variant='body1' className={body1ClassName} style={{color: theme.palette.text.secondary}} > {__.formatNumber( addr.amnt * addr.rates[coin0], coin0, locale, true )} &nbsp; <Hidden xsDown> <CoinIcon coin={coin0} size={14} color={theme.palette.text.secondary} alt /> </Hidden> <Hidden smUp> <CoinIcon coin={coin0} size={10} color={theme.palette.text.secondary} alt /> </Hidden> </Typography> </div> </Paper> </Link> ) })} </Paper> ) } class DropDown extends React.Component { // usage: // <DropDown // _id=<unique_id> // data={this.state.<array_with_objs>} // slctd={this.state.<label_of_selected_item} // action={this.<action_function>} // disabled={this.state.<disabled>} // error={this.state.<inputError>} // errorMsg={this.state.<inputErrorMsg>} // /> constructor (props) { super(props) this._id = props._id this.data = props.data this.title = props.title this.action = props.action this.renderValue = props.renderValue || (value => value) this.state = { slctd: props.slctd, disabled: props.disabled, error: props.error, errorMsg: props.errorMsg } this.handleChange = name => event => { this.setState({ [name]: event.target.value }) this.action(this.data.find((i) => { return i.lbl === event.target.value })) } } static getDerivedStateFromProps (props, state) { return { slctd: props.slctd, disabled: props.disabled, error: props.error, errorMsg: props.errorMsg } } render () { return ( <FormControl fullWidth margin='normal'> <InputLabel htmlFor={this._id}>{this.title}</InputLabel> <Select value={this.state.slctd} onChange={this.handleChange('slctd')} input={<Input id={this._id} />} disabled={this.state.disabled} renderValue={this.renderValue} error={this.state.error} > {this.data.map(d => <MenuItem key={d.key} value={d.lbl}> {d.lbl} </MenuItem>)} </Select> {this.state.error && this.state.errorMsg && <FormHelperText>{this.state.errorMsg}</FormHelperText>} </FormControl> ) } } const InfoUpdateFailed = () => <div style={{display: 'inline'}}> <Hidden xsDown> <Tooltip id='tooltip-icon' title='Update failed' placement='top'> <IconButton aria-label='Error' style={{height: 'auto'}}> <Error style={{ color: theme.palette.error[500], height: theme.spacing.unit * 3, width: theme.spacing.unit * 3 }} /> </IconButton> </Tooltip> </Hidden> <Hidden smUp> <Error style={{ color: theme.palette.error[500], height: theme.spacing.unit * 2, width: theme.spacing.unit * 2 }} /> </Hidden> </div> const Edit = () => <span>Edit</span> const Done = () => <span>Done</span> const UserList = ({ askLogout, askDelete, noTxtDecoClassname }) => <List> <a href='https://blockkeeper.io' target='_blank' className={noTxtDecoClassname} rel='noopener noreferrer' > <ListItem divider button> <ListItemIcon> <InfoOutline /> </ListItemIcon> <ListItemText primary='About' /> </ListItem> </a> <a href='https://t.me/blockkeeperio' target='_blank' className={noTxtDecoClassname} rel='noopener noreferrer' > <ListItem divider button> <ListItemIcon> <Feedback /> </ListItemIcon> <ListItemText primary='Feedback' /> </ListItem> </a> <a href='https://github.com/blockkeeper/blockkeeper-frontend-web/issues' target='_blank' className={noTxtDecoClassname} rel='noopener noreferrer' > <ListItem divider button> <ListItemIcon> <BugReport /> </ListItemIcon> <ListItemText primary='Report errors + bugs' /> </ListItem> </a> <a href='http://eepurl.com/c_4Ar1' target='_blank' className={noTxtDecoClassname} rel='noopener noreferrer' > <ListItem divider button> <ListItemIcon> <Email /> </ListItemIcon> <ListItemText primary='Newsletter' /> </ListItem> </a> <ListItem divider button onClick={askLogout}> <ListItemIcon> <ExitToApp /> </ListItemIcon> <ListItemText primary='Logout' /> </ListItem> <ListItem button onClick={askDelete}> <ListItemIcon> <DeleteForever /> </ListItemIcon> <ListItemText primary='Delete account' /> </ListItem> </List> class Area extends React.Component { constructor (props) { super(props) this.handleTooltip = this.handleTooltip.bind(this) } handleTooltip ({ event, touchData, xStock, xScale, yScale, bisectDate }) { const { showTooltip } = this.props const { x } = localPoint(event) const x0 = xScale.invert(x) const index = bisectDate(touchData, x0, 1) const d0 = touchData[index - 1] const d1 = touchData[index] let d = d0 if (d1 && d1[0]) { d = x0 - xStock(d0) > xStock(d1) - x0 ? d1 : d0 } showTooltip({ tooltipData: d, tooltipLeft: x, tooltipTop: yScale(d[1]) }) } render () { const { pWidth, pHeight, pMargin, hideTooltip, tooltipData, tooltipTop, tooltipLeft, data, pCoin, hour } = this.props const width = pWidth || this.props.parentWidth const height = pHeight || this.props.parentHeight const margin = pMargin || { left: 0, right: 0, top: 0, bottom: 0 } if (width < 10) return null const xMax = width - margin.left - margin.right const yMax = height - margin.top - margin.bottom const xStock = d => new Date(d[0] * 1000) const yStock = d => d[1] const bisectDate = bisector(d => new Date(d[0] * 1000)).left const xScale = scaleTime({ range: [0, xMax], domain: extent(data, xStock) }) const yScale = scaleLinear({ range: [yMax, 70], // 70px margin cause tooltip needs space domain: [(min(data, yStock) - (min(data, yStock) / 100 * 10)), max(data, yStock)], nice: true }) return ( <div style={{height: '100%'}}> <svg width={width} height={height}> <rect x={0} y={0} width={width} height={height} fill='#fff' rx={0} /> <defs> <LinearGradient id='gradient' x1='0%' y1='0%' x2='0%' y2='100%' > <stop offset='0%' stopColor={theme.palette.primary[500]} stopOpacity={1} /> <stop offset='100%' stopColor={theme.palette.background.default} stopOpacity={0.5} /> </LinearGradient> </defs> <AreaClosed data={data} xScale={xScale} yScale={yScale} x={xStock} y={yStock} strokeWidth={1} stroke={'url(#gradient)'} fill={'url(#gradient)'} curve={curveMonotoneX} /> <Bar x={0} y={0} width={width} height={height} fill='transparent' rx={14} data={data} onTouchStart={touchData => event => this.handleTooltip({ event, touchData, xStock, xScale, yScale, bisectDate })} onTouchMove={touchData => event => this.handleTooltip({ event, touchData, xStock, xScale, yScale, bisectDate })} onMouseMove={touchData => event => this.handleTooltip({ event, touchData, xStock, xScale, yScale, bisectDate })} onMouseLeave={data => event => hideTooltip()} /> {tooltipData && ( <g> <Line from={{ x: tooltipLeft, y: 0 }} to={{ x: tooltipLeft, y: yMax }} stroke={theme.palette.background.default} strokeWidth={1} style={{ pointerEvents: 'none' }} /> <circle cx={tooltipLeft} cy={tooltipTop} r={5} fill={theme.palette.background.default} style={{ pointerEvents: 'none' }} /> </g> )} </svg> <div> <VxTooltip top={15} left={(width / 2) - 150} // minus width/2 style={{ backgroundColor: 'transparent', color: theme.palette.background.default, fontFamily: theme.typography.fontFamily, fontSize: theme.typography.h3.fontSize, width: 300, textAlign: 'center', boxShadow: 'none' }} > {yStock(tooltipData || data[data.length - 1])} <CoinIcon coin={pCoin} size={23} color={theme.palette.background.default} alt /> </VxTooltip> <VxTooltip top={55} left={(width / 2) - 150} // minus width/2 style={{ backgroundColor: 'transparent', color: theme.palette.text.secondary, fontFamily: theme.typography.fontFamily, width: 300, textAlign: 'center', boxShadow: 'none' }} > {__.formatTime(new Date((tooltipData || data[data.length - 1])[0] * 1000), hour ? 'DD. MMM YYYY HH:mm' : 'DD. MMM YYYY')} </VxTooltip> </div> </div> ) } } const AreaTooltip = withParentSize(withTooltip(Area)) export { setBxpTrigger, unsetBxpTrigger, TopBar, TscListAddr, TscListAddresses, DepotEmpty, SoonMsg, PortfolioTab, PaperGrid, SubBar, Jumbo, BrowserGate, BrowserGateSafarimobile, NtAllwd, CoinIcon, Snack, Modal, ToTopBtn, FloatBtn, BxpFloatBtn, DropDown, ExtLink, InfoUpdateFailed, Done, Edit, UserList, AreaTooltip }
src/components/PetitionGroup/index.js
iris-dni/iris-frontend
import React from 'react'; import styles from './petition-group.scss'; import TeaserGrid from 'components/TeaserGrid'; import Container from 'components/Container'; import BlockContainer from 'components/BlockContainer'; import Section from 'components/Section'; import Heading2 from 'components/Heading2'; import Link from 'components/Link'; import Loading from 'components/Loading'; const PetitionGroup = ({ petitions, isLoading, title, text, linkText, linkHref }) => ( <Section margin> <Container> <BlockContainer> <header className={styles.head}> <div className={styles.left}> <Heading2 text={title} /> <span className={styles.text}>{text}</span> </div> <Link href={linkHref}>{linkText}</Link> </header> </BlockContainer> <Loading isLoading={isLoading}> <TeaserGrid petitions={petitions} /> </Loading> </Container> </Section> ); export default PetitionGroup;
packages/icons/src/md/image/Tonality.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdTonality(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 4c11.05 0 20 8.95 20 20s-8.95 20-20 20S4 35.05 4 24 12.95 4 24 4zm-2 35.86V8.14C14.11 9.12 8 15.84 8 24s6.11 14.88 14 15.86zm4-31.72V10h5.74C30 9.04 28.06 8.4 26 8.14zM26 14v2h11.84c-.4-.7-.86-1.37-1.36-2H26zm0 6v2h13.87c-.09-.68-.22-1.35-.39-2H26zm0 19.86c2.06-.26 4-.9 5.74-1.86H26v1.86zM36.48 34c.5-.63.96-1.3 1.36-2H26v2h10.48zm3-6c.16-.65.3-1.32.38-2H26v2h13.48z" /> </IconBase> ); } export default MdTonality;
app/scripts/components/troubleshooting-menu.js
hustbill/network-verification-ui
import React from 'react'; import { connect } from 'react-redux'; // -d 'dpdk|192.168.122.224:50051| // 10.0.5.4/0,10.0.207.0/8,0/0,0/0,0/0;sum,volume,1000;32,32,8,16,16;100' class DebugMenu extends React.Component { constructor(props, context) { super(props, context); this.state = { data: 'dpdk|192.168.122.224:50051|10.0.5.4/0,10.0.207.0/8,0/0,0/0,0/0;sum,volume,1000;32,32,8,16,16;100', monitor: 'http://10.104.211.137/'}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } reset() { // ev.preventDefault(); // this.props.resetLocalViewState(); this.setState({ data: 'dpdk' }); } handleChange(e) { this.setState({[e.target.name]: e.target.value}); } /* const result = `${this.state.data} : ${this.state.monitor}`; */ handleSubmit(ev) { const blob = new Blob(this.state.data, {type: 'text/plain'}); fetch(this.state.monitor, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: blob }); ev.preventDefault(); } render() { return ( <div className="troubleshooting-menu-wrapper"> <div className="troubleshooting-menu-content"> <h3>Network Control & Monitor</h3> <h4>{new Date().toLocaleTimeString()}</h4> <h4>{this.props.name}</h4> <div className="troubleshooting-menu-item" style={{height: 600, width: 800}}> <h4>Post Request to Monitor Server:</h4> <form onSubmit={this.handleSubmit}> <label htmlFor="post-request"> Parameter: </label> <br /> <textarea style={{width: 640, height: 360, borderColor: 'gray', borderWidth: 2}} value={this.state.data} name="data" onChange={this.handleChange} /> <br /> <br /> <label htmlFor="monitor-server"> Monitor Server: </label> <br /> <input type="text" style={{width: 540, borderColor: 'gray', borderWidth: 2}} value={this.state.monitor} name="monitor" onChange={this.handleChange} /> <br /> <br /> <input type="submit" value="Submit" /> </form> </div> </div> </div> ); } } export default connect(null)(DebugMenu);
docs/src/app/components/pages/components/Tabs/ExampleControlled.js
ngbrown/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400, }, }; export default class TabsExampleControlled extends React.Component { constructor(props) { super(props); this.state = { value: 'a', }; } handleChange = (value) => { this.setState({ value: value, }); }; render() { return ( <Tabs value={this.state.value} onChange={this.handleChange} > <Tab label="Tab A" value="a" > <div> <h2 style={styles.headline}>Controllable Tab A</h2> <p> Tabs are also controllable if you want to programmatically pass them their values. This allows for more functionality in Tabs such as not having any Tab selected or assigning them different values. </p> </div> </Tab> <Tab label="Tab B" value="b"> <div> <h2 style={styles.headline}>Controllable Tab B</h2> <p> This is another example of a controllable tab. Remember, if you use controllable Tabs, you need to give all of your tabs values or else you wont be able to select them. </p> </div> </Tab> </Tabs> ); } }
page/src/components/LogList.js
swpark6/Dumbledore
import React from 'react'; import PropTypes from 'prop-types'; import { List } from 'semantic-ui-react'; import moment from 'moment'; import './LogList.css'; const LogList = ({ logs }) => { const openType = key => ( <List.Item key={key}> <List.Icon name="compress" color="blue" size="large" verticalAlign="middle" /> <List.Content> <List.Header as="a">Connect successfully</List.Header> </List.Content> </List.Item>); const pointType = (log, key) => { let icon; let color; if (log.op === 'increment') { icon = 'angle double up'; color = 'green'; } else { icon = 'angle double down'; color = 'red'; } return ( <List.Item key={key}> <List.Icon name={icon} size="large" verticalAlign="middle" color={color} /> <List.Content> <List.Header as="a">{`${log.userName} take ${log.amount} point`}</List.Header> <List.Description as="a">{`${moment(log.createdAt).fromNow()}`}</List.Description> </List.Content> </List.Item>); }; return ( <List divided relaxed className="log__container"> {logs.map((log, key) => { return log.type === 'open' ? openType(key) : pointType(log, key); })} </List> ); }; LogList.propTypes = { logs: PropTypes.arrayOf(PropTypes.object).isRequired }; export default LogList;
src/components/svg/icon/Checkbox-Checked.js
ryanabragg/VanguardLARP
import React from 'react'; import PropTypes from 'prop-types'; const CheckedboxChecked = (props) => { const color = props.color == 'inherit' ? undefined : props.color; const aria = props.title ? 'svg-checkedbox-checked-title' : '' + props.title && props.description ? ' ' : '' + props.description ? 'svg-checkedbox-checked-desc' : ''; return ( <svg width={props.width} height={props.height} viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' role='img' aria-labelledby={aria} > {!props.title ? null : <title id='svg-checkedbox-checked-title'>{props.title}</title> } {!props.description ? null : <desc id='svg-checkedbox-checked-desc'>{props.description}</desc> } <path fill={color} d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" /> </svg> ); }; CheckedboxChecked.defaultProps = { color: 'inherit', width: undefined, height: undefined, title: '', description: '' }; CheckedboxChecked.propTypes = { color: PropTypes.string, width: PropTypes.string, height: PropTypes.string, title: PropTypes.string, description: PropTypes.string }; export default CheckedboxChecked;
src/svg-icons/image/compare.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCompare = (props) => ( <SvgIcon {...props}> <path d="M10 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h5v2h2V1h-2v2zm0 15H5l5-6v6zm9-15h-5v2h5v13l-5-6v9h5c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ImageCompare = pure(ImageCompare); ImageCompare.displayName = 'ImageCompare'; export default ImageCompare;
src/svg-icons/communication/stay-current-landscape.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape); CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape'; CommunicationStayCurrentLandscape.muiName = 'SvgIcon'; export default CommunicationStayCurrentLandscape;
src/svg-icons/action/settings-applications.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsApplications = (props) => ( <SvgIcon {...props}> <path d="M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm7-7H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-1.75 9c0 .23-.02.46-.05.68l1.48 1.16c.13.11.17.3.08.45l-1.4 2.42c-.09.15-.27.21-.43.15l-1.74-.7c-.36.28-.76.51-1.18.69l-.26 1.85c-.03.17-.18.3-.35.3h-2.8c-.17 0-.32-.13-.35-.29l-.26-1.85c-.43-.18-.82-.41-1.18-.69l-1.74.7c-.16.06-.34 0-.43-.15l-1.4-2.42c-.09-.15-.05-.34.08-.45l1.48-1.16c-.03-.23-.05-.46-.05-.69 0-.23.02-.46.05-.68l-1.48-1.16c-.13-.11-.17-.3-.08-.45l1.4-2.42c.09-.15.27-.21.43-.15l1.74.7c.36-.28.76-.51 1.18-.69l.26-1.85c.03-.17.18-.3.35-.3h2.8c.17 0 .32.13.35.29l.26 1.85c.43.18.82.41 1.18.69l1.74-.7c.16-.06.34 0 .43.15l1.4 2.42c.09.15.05.34-.08.45l-1.48 1.16c.03.23.05.46.05.69z"/> </SvgIcon> ); ActionSettingsApplications = pure(ActionSettingsApplications); ActionSettingsApplications.displayName = 'ActionSettingsApplications'; ActionSettingsApplications.muiName = 'SvgIcon'; export default ActionSettingsApplications;
Test_ReactNative_NativeModules/js/AppRoot.js
ksti/Test_react-native-nativeModules
/** * Created by GJS on 2017/3/30. */ import React from 'react'; /* * test app * */ import TestApp from './apps/testApp/src/AppRoot' /* * examples * */ /* export */ export default () => <TestApp/>
src/components/Settings/index.js
hasibsahibzada/quran.com-frontend
import React, { Component } from 'react'; import * as customPropTypes from 'customPropTypes'; import * as OptionsActions from 'redux/actions/options.js'; import ChapterInfoToggle from 'components/Settings/ChapterInfoToggle'; import { connect } from 'react-redux'; import FontSizeOptions from 'components/Settings/FontSizeOptions'; import { load } from 'redux/actions/verses.js'; import LocaleSwitcher from 'components/LocaleSwitcher'; import Menu from 'quran-components/lib/Menu'; import NightModeToggle from 'components/Settings/NightModeToggle'; import PropTypes from 'prop-types'; import ReadingModeToggle from 'components/Settings/ReadingModeToggle'; import ReciterDropdown from 'components/Settings/ReciterDropdown'; import TranslationsDropdown from 'components/Settings/TranslationsDropdown'; import TooltipOptions from 'components/Settings/TooltipOptions'; class Settings extends Component { handleOptionChange = (payload) => { const { chapter, setOption, options, versesIds } = this.props; setOption(payload); if (chapter) { const from = [...versesIds][0]; const to = [...versesIds][[...versesIds].length - 1]; const paging = { offset: from - 1, limit: to - from + 1 }; this.props.load(chapter.chapterNumber, paging, { ...options, ...payload }); } }; render() { const { setOption, options } = this.props; return ( <Menu> <ChapterInfoToggle onToggle={setOption} isToggled={options.isShowingSurahInfo} /> <ReadingModeToggle isToggled={options.isReadingMode} onToggle={setOption} /> <NightModeToggle isNightMode={options.isNightMode} onToggle={setOption} /> <hr /> <ReciterDropdown onOptionChange={this.handleOptionChange} /> <TranslationsDropdown onOptionChange={this.handleOptionChange} /> <TooltipOptions tooltip={options.tooltip} onOptionChange={setOption} /> <hr /> <FontSizeOptions fontSize={options.fontSize} onOptionChange={setOption} /> <hr /> <LocaleSwitcher renderAs="menu" /> </Menu> ); } } Settings.propTypes = { setOption: PropTypes.func.isRequired, load: PropTypes.func.isRequired, chapter: customPropTypes.surahType.isRequired, options: customPropTypes.optionsType.isRequired, versesIds: PropTypes.instanceOf(Set) }; function mapStateToProps(state) { return { options: state.options }; } export default connect(mapStateToProps, { ...OptionsActions, load })(Settings);
src/Parser/HolyPaladin/Modules/Items/SoulOfTheHighlord.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Module from 'Parser/Core/Module'; class SoulOfTheHighlord extends Module { on_initialized() { if (!this.owner.error) { this.active = this.owner.selectedCombatant.hasFinger(ITEMS.SOUL_OF_THE_HIGHLORD.id); } } item() { return { item: ITEMS.SOUL_OF_THE_HIGHLORD, result: <span>This gave you <SpellLink id={SPELLS.DIVINE_PURPOSE_TALENT_HOLY.id} />.</span>, }; } } export default SoulOfTheHighlord;
src/screens/Auth/SignUp.js
alphasp/pxview
import React from 'react'; import PXWebView from '../../components/PXWebView'; const signUpUrl = 'https://accounts.pixiv.net/signup'; const SignUp = () => ( <PXWebView source={{ uri: signUpUrl, }} /> ); export default SignUp;
dist/lib/carbon-fields/assets/js/fields/components/sortable-list/index.js
ArtFever911/statrer-kit
/** * The external dependencies. */ import $ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; class SortableList extends React.Component { /** * Lifecycle hook. * * @return {void} */ componentDidMount() { this.handleSortableUpdate = this.handleSortableUpdate.bind(this); this.$node = $(ReactDOM.findDOMNode(this)).sortable({ ...this.props.options, update: this.handleSortableUpdate, }); } /** * Lifecycle hook. * * @return {void} */ componentWillDestroy() { this.$node.sortable('destroy'); this.$node = null; } /** * Render the component. * * @return {React.Element} */ render() { return React.Children.only(this.props.children); } /** * Handle the `update` event from the sortable widget. * * @param {Object} event * @param {Object} ui * @return {void} */ handleSortableUpdate(event, ui) { // Notify the subscribers. this.props.onSort(this.$node.sortable('toArray'), event, ui); // DOM items will be re-ordered by React. this.$node.sortable('cancel'); } } export default SortableList;
app/components/genericComponents/Blackquote/index.js
romainquellec/cuistot
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const StyledBlockquote = styled.blockquote` position: relative; font-style: italic; font-size: 1.2rem; line-height: 2rem; box-sizing: border-box; margin: 1rem 0; padding: 0.5rem 0 0.5rem 1.5rem; `; const Cite = styled.cite` display: block; font-weight: 300; font-style: normal; margin-top: 0.4rem; `; const Blockquote = ({ cite, children, ...props }) => <StyledBlockquote {...props}> <div> {children} </div> {cite && <Cite> {cite} </Cite>} </StyledBlockquote>; Blockquote.propTypes = { cite: PropTypes.string, children: PropTypes.node, }; export default Blockquote;
docs/app/components/layout/main/index.js
rubenmoya/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import { Button } from 'react-toolbox'; import Appbar from '../../../components/appbar'; import Markdown from '../../../components/markdown'; import Playground from './components/playground.js'; import MainNavigation from './components/navigation.js'; import BaseDocs from './modules/components.md'; import components from './modules/components.js'; import style from './style.css'; const LoadExampleButton = props => ( <Button accent icon="code" label="Load in playground" theme={style} onClick={props.onClick} raised /> ); LoadExampleButton.propTypes = { onClick: PropTypes.func }; class Main extends React.Component { static propTypes = { onClick: PropTypes.func, params: PropTypes.object }; state = { playground: false }; componentDidMount () { this.renderExampleLoaders(); } componentDidUpdate () { this.renderExampleLoaders(); } LOAD_EXAMPLE_CLASS = 'js-load-in-playground playground-button'; handlePlayGroundClick = () => { this.setState({ playground: !this.state.playground }); }; handlePlaygroundLoad = (code) => { this.refs.playground.loadCode(code); this.setState({ playground: true }); }; renderExampleLoaders () { const examples = document.getElementsByClassName(this.LOAD_EXAMPLE_CLASS); Array.prototype.forEach.call(examples, (exampleNode, idx) => { const exampleCode = components[this.props.params.component].examples[idx]; ReactDOM.render( <LoadExampleButton onClick={this.handlePlaygroundLoad.bind(this, exampleCode)} />, exampleNode ); }); } resolveMarkdown () { const PLACEHOLDER = /<!-- example -->/g; const NODE = `<span class='${style['load-button']} ${this.LOAD_EXAMPLE_CLASS}'></span>`; if (this.props.params.component) { return components[this.props.params.component].docs.replace(PLACEHOLDER, NODE); } else { return BaseDocs; } } render () { let className = style.root; const docs = this.resolveMarkdown(); if (this.state.playground) className += ` ${style['with-playground']}`; return ( <div className={className}> <Appbar className={style.appbar} /> <Button accent floating className={style['playground-button']} icon={this.state.playground ? 'close' : 'code'} onClick={this.handlePlayGroundClick} /> <MainNavigation className={style.navigation} /> <Markdown className={style.documentation} markdown={docs} /> <Playground ref="playground" className={style.playground} /> </div> ); } } export default Main;
client/src/components/dashboard/Profile/Preferences/common/RepoContainer.js
no-stack-dub-sack/alumni-network
import { connectScreenSize } from 'react-screen-size'; import { mapScreenSizeToProps } from '../../../Community/UserCard'; import propTypes from 'prop-types'; import React from 'react'; import repoHosts from '../../../../../assets/dropdowns/repoHosts'; import RepoInput from './RepoInput'; import RepoListItem from './RepoListItem'; import styled from 'styled-components'; import { Dimmer, Loader, Segment } from 'semantic-ui-react'; import { indexOf, isEmpty } from 'lodash'; import { searchGithubCommits, validateOtherRepos as validateOther, validateGithubRepo as validateRepo } from '../../../../../actions/repoValidations'; /* TODO: 1) Refactor addItem() code - UPDATE - at least partially done */ export const Container = styled.div` margin: 16px 0 !important; `; class RepoContainer extends React.Component { state = { error: {}, icon: 'github', isLoading: false, item: '', items_list: [], label: 'https://github.com/' } componentWillMount() { const items = this.props.prePopulateList; if (items.length > 0) { this.setState({ items_list: items }); } } componentDidMount() { document.addEventListener('keydown', this.handleKeyPress); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyPress); } addItem = () => { this.setState({ isLoading: true }); const { item, items_list, label } = this.state; const [ namespace, repo ] = item.split('/'); // check if nothing entered if (!item) { this.setState({ isLoading: false }); return; } // check if format is valid: NAMESPACE/REPO if (!this.isFormatValid(repo)) { return; } // check if item already exists on list if (this.repoAlreadyAdded(item, items_list, label)) { return; } // HANDLE GITLAB: if (label === 'https://gitlab.com/' && this.isValidGitlabNaming(item, namespace, repo)) { this.validateOtherRepos('GitLab'); } // HANDLE BITBUCKET: if (label === 'https://bitbucket.org/' && this.isValidBitbucketNaming(item, repo)) { this.validateOtherRepos('BitBucket'); } // HANDLE GITHUB: if (label === 'https://github.com/' && this.isValidGithubNaming(item, namespace, repo)) { this.validateGithubRepos(); } } editItem = (item) => { const items_list = this.spliceList(item); this.setState({ item: item.item, items_list }); } handleChange = (e) => { this.setState({ error: '', item: e.target.value }); } handleKeyPress = (e) => { if (e.keyCode === 13) { this.addItem(); } } handleLabelChange = (e) => { let icon; if (e.target.innerText === 'https://github.com/') icon = 'github' if (e.target.innerText === 'https://gitlab.com/') icon = 'gitlab' if (e.target.innerText === 'https://bitbucket.org/') icon = 'bitbucket' this.setState({ icon, label: e.target.innerText }); } isFormatValid = (repo) => { if (!repo) { this.setState({ error: { header: `Invalid entry. Plese enter a valid repo in the format: namespace/repo.`, }, isLoading: false, item: '', }); return false; } return true; } isValidBitbucketNaming = (item, repo) => { if ( (repo.length === 1 && /^\./.test(repo)) || !/[\d\w-]+\/[\d\w-.]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid BitBucket repository path: namespace/repo', namespace: `Namespace: This value must contain only ASCII letters, numbers, dashes and underscores.`, repo: `Repo: This value must contain only ASCII letters, numbers, dashes, underscores and periods.`, }, isLoading: false, item: '', }); return false; } else { return true; } } isValidGitlabNaming = (item, namespace, repo) => { if ( /(^-)|(\.((git)|(atom))?$)/.test(repo) || /(^-)|(\.((git)|(atom))?$)/.test(namespace) || !/[\d\w-.]+\/[\d\w-.]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid GitLab repository path: namespace/repo', namespace: `Repo: This value can only contain letters, digits, '_', '-' and '.'. Cannot start with '-' or end in '.', '.git' or '.atom'`, repo: `Namespace: This value can only contain letters, digits, '_', '-' and '.'. Cannot start with '-' or end in '.', '.git' or '.atom'`, }, isLoading: false, item: '' }); return false; } else { return true; } } isValidGithubNaming = (item, namespace, repo) => { if ( // GitHub naming conventions: /^\./.test(repo) === '.' || /^-|--|-$/.test(namespace) || !/[\d\w-.]+\/[\d\w-]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid GitHub repository path: namespace/repo', namespace: `Namespace: This value may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen.`, repo: `Repo: This value may only contain alphanumeric characters, periods, and hyphens, and cannot begin with a period.`, }, isLoading: false, item: '' }); return false; } return true; } removeItem = (item) => { const items_list = this.spliceList(item); this.setState({ items_list }, () => this.props.saveChanges(items_list)); } repoAlreadyAdded = (item, items_list, label) => { for (var obj of items_list) { if (obj.item.toLowerCase() === item.toLowerCase() && obj.label === label) { this.setState({ error: { header: 'You have already added this repo to your list!', }, isLoading: false, item: '' }); return true; } } return false; } spliceList = (item) => { const { items_list } = this.state; const index = indexOf(items_list, item); items_list.splice(index, 1); return items_list; } validateGithubRepos = () => { const { username } = this.props; const { item, items_list, label } = this.state; const [ namespace, repo ] = item.split('/'); validateRepo(namespace, repo, username) .then((res) => { const contributors = res.contributorsList; let isContributor = false; // first check if user is listed as contributor // if yes, setState & continue for (var contributor of contributors) { if (contributor.author.login === username) { isContributor = true; items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } } // if user is not listed, repo may have > 100 contributors... // then search commit history of repo for commits by user. // prefer to use both checks, becuase this one is in "preview", // github warns changes could happen at any time with no notice. if (!isContributor) { searchGithubCommits(namespace, repo, username) .then((res) => { const commits = res.data.items; if (commits.length > 0) { isContributor = true; items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } }) .catch((err) => { console.warn('There was a problem with GitHub\'s API: ' + err.message); }); } // if user/repo does not pass either check, reject with error if (!isContributor) { this.setState({ error: { header: 'You must be a contributor to the repo you would like to collaborate on.', }, isLoading: false, item: '', }); } }) // this should catch on the first axios.get request if repo does not exist // also handle mystery problem here (hopefully) .catch((err) => { err = 'contributors[Symbol.iterator]'; if (/\[Symbol.iterator\]/.test(err)) { this.setState({ error: { header: 'There was a problem with GitHub\'s API, please try again.', }, isLoading: false, item: '', }); } else { this.setState({ error: { header: 'Repository is private or invalid. Please enter a public, valid GitHub repo.', }, isLoading: false, item: '', }); } }); } validateOtherRepos = (hostSite) => { const { item, items_list, label } = this.state; const hostUrl = hostSite === 'BitBucket' ? 'https://bitbucket.org/' : 'https://gitlab.com/'; validateOther(item, hostUrl).then((res) => { if (res) { items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } else { this.setState({ error: { header: `Repository is private or invalid. Please enter a public, valid ${hostSite} repo.`, }, isLoading: false, item: '', }); } }) .catch(err => { this.setState({ error: { header: `Our bad, it seems like we really messed this one up! Try again soon.`, }, isLoading: false, item: '', }); }); } render() { const { isMobile } = this.props.screen; const { item, isLoading, icon, error } = this.state; const listItems = this.state.items_list.map((el, i) => { var key = i + el.item.slice(0,3); return ( <RepoListItem editItem={() => this.editItem(el)} el={el} index={key} key={key} removeItem={() => this.removeItem(el)} /> ); }); return ( <Container> <RepoInput addItem={this.addItem} error={error} handleChange={this.handleChange} handleDropdownChange={this.handleLabelChange} icon={icon} isMobile={isMobile} item={item} repoHosts={repoHosts} /> <Segment basic style={{ marginTop: 5, minHeight: 50, padding: 0 }}> <Dimmer active={isLoading && true} inverted> <Loader /> </Dimmer> <div className="ui middle aligned divided selection list" style={{ margin: 0 }}> {listItems} </div> </Segment> { !isEmpty(error) && error.repo && error.namespace && <div className="ui error message"> <div className="header">{error.header}</div> <ul className="list"> <li>{error.namespace}</li> <li>{error.repo}</li> </ul> </div> } </Container> ); } } RepoContainer.propTypes = { prePopulateList: propTypes.array, saveChanges: propTypes.func.isRequired, username: propTypes.string.isRequired, } RepoContainer.defaultProps = { prePopulateList: [] } export default connectScreenSize(mapScreenSizeToProps)(RepoContainer);
lib/ui/src/modules/ui/components/left_panel/header.js
bigassdragon/storybook
import PropTypes from 'prop-types'; import React from 'react'; import { baseFonts } from '../theme'; const wrapperStyle = { background: '#F7F7F7', marginBottom: 10, }; const headingStyle = { ...baseFonts, textTransform: 'uppercase', letterSpacing: '1.5px', fontSize: '12px', fontWeight: 'bolder', color: '#828282', border: '1px solid #C1C1C1', textAlign: 'center', borderRadius: '2px', padding: '5px', cursor: 'pointer', margin: 0, float: 'none', overflow: 'hidden', }; const shortcutIconStyle = { textTransform: 'uppercase', letterSpacing: '3.5px', fontSize: 12, fontWeight: 'bolder', color: 'rgb(130, 130, 130)', border: '1px solid rgb(193, 193, 193)', textAlign: 'center', borderRadius: 2, padding: 5, cursor: 'pointer', margin: 0, display: 'inlineBlock', paddingLeft: 8, float: 'right', marginLeft: 5, backgroundColor: 'inherit', outline: 0, }; const linkStyle = { textDecoration: 'none', }; const Header = ({ openShortcutsHelp, name, url }) => ( <div style={wrapperStyle}> <button style={shortcutIconStyle} onClick={openShortcutsHelp}>⌘</button> <a style={linkStyle} href={url} target="_blank" rel="noopener noreferrer"> <h3 style={headingStyle}>{name}</h3> </a> </div> ); Header.propTypes = { openShortcutsHelp: PropTypes.func, name: PropTypes.string, url: PropTypes.string, }; export default Header;
src/utils/ownerDocument.js
BespokeInsights/react-overlays
import React from 'react'; import ownerDocument from 'dom-helpers/ownerDocument'; export default function (componentOrElement) { return ownerDocument(React.findDOMNode(componentOrElement)); }
src/components/icons/MistIcon.js
maximgatilin/weathernow
import React from 'react'; export default function CloudsBrokenIcon() { return ( <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 176.32 148.26"><title>mist</title><path d="M1018.93,943.61h0c0-.25,0-0.5,0-0.75a36.25,36.25,0,1,0-72.51,0s0,0,0,.07a29.59,29.59,0,0,0,1.39,59.16h71.12A29.24,29.24,0,1,0,1018.93,943.61Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/><path d="M1027.71,1020h-89.3a3.77,3.77,0,0,1,0-7.53h89.3A3.77,3.77,0,0,1,1027.71,1020Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/><path d="M1066.31,1020h-19a3.77,3.77,0,0,1,0-7.53h19A3.77,3.77,0,1,1,1066.31,1020Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/><path d="M1062.58,1054.87H922.85a3.77,3.77,0,0,1,0-7.53h139.73A3.77,3.77,0,0,1,1062.58,1054.87Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/><path d="M1002.36,1037.45H897.52a3.77,3.77,0,0,1,0-7.53h104.84A3.77,3.77,0,1,1,1002.36,1037.45Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/><path d="M1054.47,1037.45h-30.68a3.77,3.77,0,1,1,0-7.53h30.68A3.77,3.77,0,1,1,1054.47,1037.45Z" transform="translate(-893.76 -906.61)" fill="#d1d3d4"/></svg> ) }
app/common/components/LockButton/index.js
Kaniwani/KW-Frontend
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from 'common/components/IconButton'; LockButton.propTypes = { size: PropTypes.string, isActionable: PropTypes.bool, isSubmitting: PropTypes.bool, isLocked: PropTypes.bool, children: PropTypes.any, onClick: PropTypes.func.isRequired, }; LockButton.defaultProps = { size: '1.5em', isActionable: true, isSubmitting: false, isLocked: false, children: false, }; function LockButton({ isSubmitting, isActionable, isLocked, children, ...props }) { let title = 'Not allowed'; let icon = 'LOCK_SOLID'; if (isSubmitting) { icon = 'SYNC'; title = 'Syncing'; } else if (isActionable) { icon = isLocked ? 'LOCK_CLOSED' : 'LOCK_OPEN'; title = isLocked ? 'Unlock' : 'Lock'; } return ( <IconButton name={icon} title={title} disabled={!isActionable} {...props} > {children} </IconButton> ); } export default LockButton;
src/components/controls/InlineEditableControl.js
kryptnostic/gallery
/* * @flow */ import React from 'react'; import FontAwesome from 'react-fontawesome'; import styled from 'styled-components'; import { isNonEmptyString } from '../../utils/LangUtils'; const ControlWrapper = styled.div` display: inline-flex; margin: 0; padding: 0; width: 100%; `; const EditableControlWrapper = styled(ControlWrapper)` &:hover { cursor: pointer; .control { border: 1px solid #cfd8dc; } .icon { visibility: visible; } } `; const Icon = styled.div` border-style: solid; border-width: 1px; height: 32px; width: 32px; margin-left: 10px; font-size: 14px; padding: 0; display: flex; flex-shrink: 0; align-items: center; justify-content: center; `; const EditIcon = styled(Icon)` background-color: #ffffff; border-color: #cfd8dc; visibility: hidden; `; const SaveIcon = styled(Icon)` background-color: #4203c5; border-color: #4203c5; color: #ffffff; visibility: visible; `; const TextControl = styled.div` border: 1px solid transparent; position: relative; font-size: ${(props) => { return props.styleMap.fontSize; }}; line-height: ${(props) => { return props.styleMap.lineHeight; }}; margin: ${(props) => { return props.styleMap.margin; }}; padding: ${(props) => { return props.styleMap.padding; }}; `; const TextInputControl = styled.input` border: 1px solid #4203c5; margin: 0; width: 100%; font-size: ${(props) => { return props.styleMap.inputFontSize; }}; line-height: ${(props) => { return props.styleMap.lineHeight; }}; margin: ${(props) => { return props.styleMap.margin; }}; padding: ${(props) => { return props.styleMap.padding; }}; &:focus { outline: none; } `; const TextAreaControl = styled.textarea` border: 1px solid #4203c5; margin: 0; min-height: 100px; width: 100%; font-size: ${(props) => { return props.styleMap.inputFontSize; }}; height: ${(props) => { return props.styleMap.height ? props.styleMap.height : 'auto'; }}; line-height: ${(props) => { return props.styleMap.lineHeight; }}; margin: ${(props) => { return props.styleMap.margin; }}; padding: ${(props) => { return props.styleMap.padding; }}; &:focus { outline: none; } `; const TYPES = { TEXT: 'text', TEXA_AREA: 'textarea' }; /* * the negative margin-left is to adjust for the padding + border offset */ const STYLE_MAP = { small: { fontSize: '14px', inputFontSize: '13px', lineHeight: '16px', margin: '0 0 0 -13px', padding: '6px 12px' }, medium_small: { fontSize: '16px', inputFontSize: '14px', lineHeight: '18px', margin: '0 0 0 -13px', padding: '8px 12px' }, medium: { fontSize: '20px', inputFontSize: '18px', lineHeight: '24px', margin: '0 0 0 -13px', padding: '8px 12px' }, xlarge: { fontSize: '32px', inputFontSize: '30px', lineHeight: '36px', margin: '0 0 0 -13px', padding: '10px 12px' } }; /* * TODO: explore how to handle children. for example, there's a use case where the non-edit view could display * a Badge inside TextControl */ export default class InlineEditableControl extends React.Component { static propTypes = { type: React.PropTypes.string.isRequired, size: React.PropTypes.string.isRequired, placeholder: React.PropTypes.string, value: React.PropTypes.string, viewOnly: React.PropTypes.bool, onChange: React.PropTypes.func, onChangeConfirm: React.PropTypes.func }; static defaultProps = { placeholder: 'Click to edit...', value: '', viewOnly: false, onChange: () => {}, onChangeConfirm: undefined }; control :any state :{ editable :boolean, currentValue :string, previousValue :string } constructor(props :Object) { super(props); const initialValue = isNonEmptyString(this.props.value) ? this.props.value : ''; const initializeAsEditable = !isNonEmptyString(initialValue); this.control = null; this.state = { editable: initializeAsEditable, currentValue: initialValue, previousValue: initialValue }; } componentDidUpdate(prevProps :Object, prevState :Object) { if (this.control && prevState.editable === false && this.state.editable === true) { // BUG: if there's multiple InlineEditableControl components on the page, the focus might not be on the desired // element. perhaps need to take in a prop to indicate focus this.control.focus(); } // going from editable to not editable should invoke the onChange callback only if the value actually changed if (prevState.previousValue !== this.state.currentValue && prevState.editable === true && this.state.editable === false) { if (this.props.onChangeConfirm) { this.props.onChangeConfirm(this.state.currentValue) .then((success) => { if (!success) { this.setState({ currentValue: prevState.previousValue, previousValue: '' }); } }); } else { this.props.onChange(this.state.currentValue); } } } componentWillReceiveProps(nextProps :Object) { if (this.props.value !== nextProps.value) { const newValue = isNonEmptyString(nextProps.value) ? nextProps.value : ''; const initializeAsEditable = !isNonEmptyString(newValue); this.setState({ editable: initializeAsEditable, currentValue: newValue, previousValue: newValue }); } } toggleEditable = () => { if (this.props.viewOnly) { return; } if (!isNonEmptyString(this.state.currentValue)) { return; } this.setState({ editable: !this.state.editable, previousValue: this.state.currentValue }); } handleOnBlur = () => { this.toggleEditable(); } handleOnChange = (event :SyntheticInputEvent) => { this.setState({ currentValue: event.target.value }); } handleOnKeyDown = (event :SyntheticKeyboardEvent) => { switch (event.keyCode) { case 13: // 'Enter' key code case 27: // 'Esc' key code this.toggleEditable(); break; default: break; } } renderTextControl = () => { if (!this.props.viewOnly && this.state.editable) { return ( <TextInputControl styleMap={STYLE_MAP[this.props.size]} placeholder={this.props.placeholder} value={this.state.currentValue} onBlur={this.handleOnBlur} onChange={this.handleOnChange} onKeyDown={this.handleOnKeyDown} innerRef={(element) => { this.control = element; }} /> ); } return ( <TextControl className="control" styleMap={STYLE_MAP[this.props.size]} onClick={this.toggleEditable} innerRef={(element) => { this.control = element; }}> { isNonEmptyString(this.state.currentValue) ? this.state.currentValue : this.props.placeholder } </TextControl> ); } renderTextAreaControl = () => { if (!this.props.viewOnly && this.state.editable) { if (this.control) { // +2 1px border STYLE_MAP[this.props.size].height = `${Math.ceil(this.control.clientHeight) + 2}px`; } return ( <TextAreaControl styleMap={STYLE_MAP[this.props.size]} placeholder={this.props.placeholder} value={this.state.currentValue} onBlur={this.handleOnBlur} onChange={this.handleOnChange} onKeyDown={this.handleOnKeyDown} innerRef={(element) => { this.control = element; }} /> ); } return ( <TextControl className="control" styleMap={STYLE_MAP[this.props.size]} onClick={this.toggleEditable} innerRef={(element) => { this.control = element; }}> { isNonEmptyString(this.state.currentValue) ? this.state.currentValue : this.props.placeholder } </TextControl> ); }; getControl = () => { switch (this.props.type) { case TYPES.TEXT: return this.renderTextControl(); case TYPES.TEXA_AREA: return this.renderTextAreaControl(); default: return this.renderTextControl(); } } getEditButton = () => { if (!this.props.viewOnly && this.state.editable) { return ( <SaveIcon className="icon" onClick={this.toggleEditable}> <FontAwesome name="check" /> </SaveIcon> ); } return ( <EditIcon className="icon" onClick={this.toggleEditable}> <FontAwesome name="pencil" /> </EditIcon> ); } render() { const control = this.getControl(); const editButton = this.getEditButton(); if (this.props.viewOnly) { return ( <ControlWrapper> { control } </ControlWrapper> ); } return ( <EditableControlWrapper> { control } { editButton } </EditableControlWrapper> ); } }
src/svg-icons/maps/rate-review.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsRateReview = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 14v-2.47l6.88-6.88c.2-.2.51-.2.71 0l1.77 1.77c.2.2.2.51 0 .71L8.47 14H6zm12 0h-7.5l2-2H18v2z"/> </SvgIcon> ); MapsRateReview = pure(MapsRateReview); MapsRateReview.displayName = 'MapsRateReview'; MapsRateReview.muiName = 'SvgIcon'; export default MapsRateReview;
src/app/component/star-rating/star-rating.story.js
all3dp/printing-engine-client
import React from 'react' import {storiesOf} from '@storybook/react' import StarRating from '.' storiesOf('StarRating', module).add('default', () => <StarRating stars={3} of={5} />)
Libraries/Image/Image.ios.js
jhen0409/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Image * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const ImageResizeMode = require('ImageResizeMode'); const ImageSourcePropType = require('ImageSourcePropType'); const ImageStylePropTypes = require('ImageStylePropTypes'); const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const NativeModules = require('NativeModules'); const PropTypes = require('react/lib/ReactPropTypes'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheet = require('StyleSheet'); const StyleSheetPropType = require('StyleSheetPropType'); const flattenStyle = require('flattenStyle'); const requireNativeComponent = require('requireNativeComponent'); const resolveAssetSource = require('resolveAssetSource'); const ImageViewManager = NativeModules.ImageViewManager; /** * A React component for displaying different types of images, * including network images, static resources, temporary local images, and * images from local disk, such as the camera roll. * * This exmaples shows both fetching and displaying an image from local storage as well as on from * network. * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image } from 'react-native'; * * class DisplayAnImage extends Component { * render() { * return ( * <View> * <Image * source={require('./img/favicon.png')} * /> * <Image * source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage); * ``` * * You can also add `style` to an image: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image, StyleSheet} from 'react-native'; * * const styles = StyleSheet.create({ * stretch: { * width: 50, * height: 200 * } * }); * *class DisplayAnImageWithStyle extends Component { * render() { * return ( * <View> * <Image * style={styles.stretch} * source={require('./img/favicon.png')} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent( * 'DisplayAnImageWithStyle', * () => DisplayAnImageWithStyle * ); * ``` */ const Image = React.createClass({ propTypes: { /** * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`, * > `stretch`, `center`, `repeat`. */ style: StyleSheetPropType(ImageStylePropTypes), /** * The image source (either a remote URL or a local file resource). */ source: ImageSourcePropType, /** * A static image to display while loading the image source. * * - `uri` - a string representing the resource identifier for the image, which * should be either a local file path or the name of a static image resource * (which should be wrapped in the `require('./path/to/image.png')` function). * - `width`, `height` - can be specified if known at build time, in which case * these will be used to set the default `<Image/>` component dimensions. * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if * unspecified, meaning that one image pixel equates to one display point / DIP. * - `number` - Opaque type returned by something like `require('./image.jpg')`. * * @platform ios */ defaultSource: PropTypes.oneOfType([ // TODO: Tooling to support documenting these directly and having them display in the docs. PropTypes.shape({ uri: PropTypes.string, width: PropTypes.number, height: PropTypes.number, scale: PropTypes.number, }), PropTypes.number, ]), /** * When true, indicates the image is an accessibility element. * @platform ios */ accessible: PropTypes.bool, /** * The text that's read by the screen reader when the user interacts with * the image. * @platform ios */ accessibilityLabel: PropTypes.string, /** * blurRadius: the blur radius of the blur filter added to the image * @platform ios */ blurRadius: PropTypes.number, /** * When the image is resized, the corners of the size specified * by `capInsets` will stay a fixed size, but the center content and borders * of the image will be stretched. This is useful for creating resizable * rounded buttons, shadows, and other resizable assets. More info in the * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets). * * @platform ios */ capInsets: EdgeInsetsPropType, /** * Determines how to resize the image when the frame doesn't match the raw * image dimensions. * * - `cover`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view (minus padding). * * - `contain`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal to * or less than the corresponding dimension of the view (minus padding). * * - `stretch`: Scale width and height independently, This may change the * aspect ratio of the src. * * - `repeat`: Repeat the image to cover the frame of the view. The * image will keep it's size and aspect ratio. (iOS only) */ resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat']), /** * A unique identifier for this element to be used in UI Automation * testing scripts. */ testID: PropTypes.string, /** * Invoked on mount and layout changes with * `{nativeEvent: {layout: {x, y, width, height}}}`. */ onLayout: PropTypes.func, /** * Invoked on load start. * * e.g., `onLoadStart={(e) => this.setState({loading: true})}` */ onLoadStart: PropTypes.func, /** * Invoked on download progress with `{nativeEvent: {loaded, total}}`. * @platform ios */ onProgress: PropTypes.func, /** * Invoked on load error with `{nativeEvent: {error}}`. * @platform ios */ onError: PropTypes.func, /** * Invoked when load completes successfully. */ onLoad: PropTypes.func, /** * Invoked when load either succeeds or fails. */ onLoadEnd: PropTypes.func, }, statics: { resizeMode: ImageResizeMode, /** * Retrieve the width and height (in pixels) of an image prior to displaying it. * This method can fail if the image cannot be found, or fails to download. * * In order to retrieve the image dimensions, the image may first need to be * loaded or downloaded, after which it will be cached. This means that in * principle you could use this method to preload images, however it is not * optimized for that purpose, and may in future be implemented in a way that * does not fully load/download the image data. A proper, supported way to * preload images will be provided as a separate API. * * @param uri The location of the image. * @param success The function that will be called if the image was sucessfully found and width * and height retrieved. * @param failure The function that will be called if there was an error, such as failing to * to retrieve the image. * * @returns void * * @platform ios */ getSize: function( uri: string, success: (width: number, height: number) => void, failure: (error: any) => void, ) { ImageViewManager.getSize(uri, success, failure || function() { console.warn('Failed to get size for image: ' + uri); }); }, /** * Prefetches a remote image for later use by downloading it to the disk * cache * * @param url The remote location of the image. * * @return The prefetched image. */ prefetch(url: string) { return ImageViewManager.prefetchImage(url); }, }, mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'UIView', validAttributes: ReactNativeViewAttributes.UIView }, render: function() { const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined }; const {width, height, uri} = source; const style = flattenStyle([{width, height}, styles.base, this.props.style]) || {}; const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108 const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108 if (uri === '') { console.warn('source.uri should not be an empty string'); } if (this.props.src) { console.warn('The <Image> component requires a `source` property rather than `src`.'); } return ( <RCTImageView {...this.props} style={style} resizeMode={resizeMode} tintColor={tintColor} source={source} /> ); }, }); const styles = StyleSheet.create({ base: { overflow: 'hidden', }, }); const RCTImageView = requireNativeComponent('RCTImageView', Image); module.exports = Image;
src/components/fields/File/Show.js
orionsoft/parts
import React from 'react' import DeleteIcon from 'react-icons/lib/md/delete' import ViewIcon from 'react-icons/lib/md/open-in-browser' import autobind from 'autobind-decorator' import cleanFileURL from './cleanFileURL' import PropTypes from 'prop-types' const styles = { container: { backgroundColor: '#fff', borderRadius: 5, padding: 7, fontSize: 18, color: '#000', display: 'flex', border: '1px solid #c2c2c2' }, name: { overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }, buttons: { width: 70, textAlign: 'right' }, icon: { marginLeft: 10, cursor: 'pointer' } } export default class Show extends React.Component { static propTypes = { value: PropTypes.object, onChange: PropTypes.func } @autobind delete () { this.props.onChange(null) } @autobind open () { window.open(this.props.value.url) } render () { return ( <div style={styles.container}> <div style={styles.name}> {cleanFileURL(this.props.value.url)} </div> <div style={styles.buttons}> <ViewIcon style={styles.icon} size={25} onClick={this.open} /> <DeleteIcon style={styles.icon} size={25} onClick={this.delete} /> </div> </div> ) } }
docs/app/Examples/elements/Container/Variations/ContainerExampleAlignment.js
mohammed88/Semantic-UI-React
/* eslint-disable max-len */ import React from 'react' import { Container, Divider } from 'semantic-ui-react' const ContainerExampleAlignment = () => ( <div> <Container textAlign='left'> Left Aligned </Container> <Container textAlign='center'> Center Aligned </Container> <Container textAlign='right'> Right Aligned </Container> <Container textAlign='justified'> <b>Justified</b> <Divider /> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p> </Container> </div> ) export default ContainerExampleAlignment