path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/chat/groups/GroupView.js
elarasu/roverz-chat
/** * Groups Screen */ import React, { Component } from 'react'; import { Actions } from 'react-native-router-flux'; import { ScrollView, Text, View, StatusBar, TouchableOpacity, StyleSheet, AppState, } from 'react-native'; import { ListView } from 'realm/react-native'; import moment from 'moment'; import { Badge, Icon } from 'react-native-elements'; import { isIphoneX } from 'react-native-iphone-x-helper'; import { List, ListItem } from '../../components/ui'; import Loading from '../../components/general/Loading'; // Consts and Libs import { AppStyles, AppSizes, AppColors } from '../../theme/'; import Network from '../../network'; import { ListItemAvatar, } from '../ui'; import t from '../../i18n'; /* Styles ==================================================================== */ const addIconColor = '#fff'; const styles = StyleSheet.create({ mainContainer: { flex: 1, position: 'relative', }, lItemTitle: { paddingRight: 40 }, lItemSubTitle: { paddingTop: 0, marginLeft: 0, flex: 1, flexDirection: 'column' }, row: { flexDirection: 'row' }, subTitleText01: { textAlign: 'left', color: AppColors.brand().gV_subTitleText01, fontSize: 14, flex: 1 }, subTitleText02: { textAlign: 'right', color: AppColors.brand().gV_subTitleText02, fontSize: 12 }, subTitleMessage: { textAlign: 'left', color: AppColors.brand().gV_subTitleMessage, fontSize: 12, marginRight: 40 }, badgeText: { color: AppColors.brand().gV_badgeTextColor, width: 24, height: 24, paddingTop: 5, textAlign: 'center', backgroundColor: 'transparent', fontSize: 11, }, badgeContainer: { position: 'absolute', flex: 1, justifyContent: 'center', alignItems: 'center', right: 0, top: 0, backgroundColor: AppColors.brand().gV_badgeContainerBg, width: 24, height: 24, borderRadius: 12, }, plusButton: { width: 45, height: 45, borderRadius: 23, position: 'absolute', bottom: 90, right: 30, zIndex: 200, shadowColor: AppColors.brand().gV_plusButtonShadowColor, shadowOffset: { width: 1, height: 1, }, shadowRadius: 2, shadowOpacity: 0.3, alignItems: 'center', }, toastContainer: { flex: 1, position: 'absolute', top: AppSizes.navbarHeight + 10, width: AppSizes.screen.width, alignItems: 'center', justifyContent: 'center', zIndex: 100, }, toastView: { paddingVertical: 5, paddingHorizontal: 15, borderRadius: 5, }, toastText: { color: AppColors.brand().gV_toastTextColor, fontSize: 12 }, list: { paddingBottom: 110 }, }); /* Component ==================================================================== */ class GroupList extends Component { static componentName = 'GroupList'; constructor(props) { super(props); this._service = new Network(); const dataSource = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }); this._mounted = false; this.state = { dataSource: dataSource.cloneWithRows(dataSource), loaded: false, items: this._service.chat.service.availableChannels, connected: false, appState: AppState.currentState, }; } componentWillMount() { } componentDidMount() { // this._service.onLogin(() => { // console.log('APPSTATE GV - onLogin'); // // on login, lets sync // if (this._mounted && this._service.currentUser) { // this._service.switchToLoggedInUser(); // this.setState({ connected: true }); // console.log('APPSTATE GV - switchToLoggedInUser'); // } // }); this._insideStateUpdate = false; this._service.db.groups.list.addListener(() => { if (!this._mounted || this._insideStateUpdate || !this._service.service.loggedInUser || this.state.appState.match(/inactive|background/)) return; this._insideStateUpdate = true; this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.state.items), loaded: true, connected: this._service.service.loggedInUser, }, () => { this._insideStateUpdate = false; }); }); this._mounted = true; setTimeout(() => { if (this._mounted && this.state.items && this.state.items.length > 0 && !this.state.loaded) { this.setState({ loaded: true, dataSource: this.state.dataSource.cloneWithRows(this.state.items), }, () => { // this._service.chat.setAppState(1); // this._service.chat.setUserPresence('online'); // console.log('APPSTATE GV - setTimeout callback'); }); } }, 100); AppState.addEventListener('change', this._handleAppStateChange); } componentWillUnmount() { this._mounted = false; AppState.removeEventListener('change', this._handleAppStateChange); } getUser = (msg) => { const usr = 'None'; if (msg && msg.user) { if (msg.user.name) return msg.user.name; return msg.user.username ? msg.user.username : usr; } return usr; } getLastMsgText(lastMsg) { if (!lastMsg) { return ''; } if (lastMsg.image) { return t('txt_image'); } if (lastMsg.remoteFile) { return t('txt_attachment'); } return lastMsg.text; } _handleAppStateChange = (nextAppState) => { this.setState({ appState: nextAppState }); this._service.handleAppStateChange(nextAppState); } renderRow = (data, sectionID) => { const lastMsg = data.lastMessage; return ( <ListItem key={`list-row-${sectionID}`} testID={`user-${data.name}`} onPress={() => { Actions.chatDetail({ obj: data, title: data.heading, duration: 0 }); }} title={data.heading} titleStyle={[styles.lItemTitle]} subtitle={ <View style={[styles.lItemSubTitle]}> <View style={[styles.row]} > <Text style={styles.subTitleText01} numberOfLines={1} >{lastMsg ? this.getUser(lastMsg) : t('txt_no_messages')}:</Text> <Text style={[styles.subTitleText02]} >{lastMsg ? moment(lastMsg && lastMsg.createdAt).fromNow() : t('hyphen')}</Text> </View> <View style={{ width: 20 }} /> <Text style={[styles.subTitleMessage]} numberOfLines={1} >{this.getLastMsgText(lastMsg)}</Text> </View> } badge={data.unread > 0 ? { element: <Badge value={data.unread < 50 ? data.unread : t('txt_50_plus')} textStyle={[styles.badgeText]} containerStyle={[styles.badgeContainer]} />, } : null} hideChevron={true} roundAvatar leftIcon={<ListItemAvatar source={data.avatar} name={data.title ? data.title : data.name} avType={data.type} />} /> ); } render = () => { if (!this.state.loaded) { return (<Loading />); } return ( <View style={[styles.mainContainer, { marginTop: isIphoneX() ? 26 : null }]} testID={'group-view'} > <TouchableOpacity style={[styles.plusButton, { backgroundColor: AppColors.brand().third }]} onPress={Actions.searchRoom} > <Icon name="add" type="MaterialIcons" size={45} color={addIconColor} /> </TouchableOpacity> { !this.state.connected && <View style={[styles.toastContainer]} > <View style={[styles.toastView, { backgroundColor: AppColors.brand().third }]} > <Text style={[styles.toastText, AppStyles.baseFont]}>{t('txt_connecting')}</Text> </View> </View> } <ScrollView automaticallyAdjustContentInsets={false} style={[AppStyles.container, { marginTop: AppSizes.navbarHeight, position: 'relative', }]} > <StatusBar barStyle="light-content" hidden={false} /> <List style={[styles.list]}> <ListView renderRow={this.renderRow} dataSource={this.state.dataSource} enableEmptySections={true} /> </List> </ScrollView> </View> ); } } /* Export Component ==================================================================== */ export default GroupList;
lens-ui/app/components/AdhocQueryComponent.js
sushilmohanty/incubator-lens
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 { RouteHandler } from 'react-router'; import QueryBox from './QueryBoxComponent'; import Sidebar from './SidebarComponent'; import RequireAuthentication from './RequireAuthenticationComponent'; class AdhocQuery extends React.Component { render () { return ( <section className='row'> <div className='col-md-2'> <Sidebar {...this.props}/> </div> <div className='col-md-10'> <QueryBox {...this.props}/> <RouteHandler/> </div> </section> ); } } let AuthenticatedAdhocQuery = RequireAuthentication(AdhocQuery); export default AuthenticatedAdhocQuery;
screens/home/Home.js
keuss/react-router-redux-sandbox
import React from 'react' import {connect} from 'react-redux' import _ from 'lodash' import {fetchAccounts, setSelectedAccount} from './actions' import {AccountDetails, AccountList, BalanceGraph} from './components' class Home extends React.Component { constructor(props){ super(props) this.handleAccountClick = this.handleAccountClick.bind(this) } componentDidMount() { this.props.fetchAccounts() } handleAccountClick(newId) { console.log(`in handleAccountClick with newId = ${newId}`) this.props.changeAccount(newId) } render() { if(!_.isEmpty(this.props.accounts)) { return ( <AccountList accounts={this.props.accounts} selectedId={this.props.selectedAccount.id} onClick={this.handleAccountClick}> <AccountDetails expenses={this.props.selectedAccount.expenses} /> <BalanceGraph {...this.props} /> </AccountList> ) } else { return null } } } const mapStateToProps = (state) => ({ accounts: state.home.accounts, selectedAccount: state.home.selectedAccount || state.home.accounts[0] }) const mapDispatchToProps = (dispatch) => ({ fetchAccounts: () => dispatch(fetchAccounts()), changeAccount: (id) => dispatch(setSelectedAccount(id)) }) export default connect(mapStateToProps, mapDispatchToProps)(Home)
src/components/App/index.js
koden-km/sc-react-redux
import React from 'react'; function App({ children }) { return <div>{children}</div>; } export default App;
v21/v21.0.0/sdk/barcodescanner.js
ccheever/expo-docs
import markdown from 'markdown-in-js' import withDoc, { components } from '~/lib/with-doc' import { expoteam } from '~/data/team' // import { InternalLink, ExternalLink } from "~/components/text/link"; // import { P } from "~/components/text/paragraph"; // import Image from '~/components/base/image' import { Code } from '~/components/base/code' // import { // TerminalInput, // TerminalOutput // } from "~/components/text/terminal"; // prettier-ignore export default withDoc({ title: 'BarCodeScanner', authors: [expoteam], })(markdown(components)` A React component that renders a viewfinder for the device's either front or back camera viewfinder and will detect bar codes that show up in the frame. Requires \`Permissions.CAMERA\`. ## Supported formats ${<Code>{` | Bar code format | iOS | Android | | --------------- | --- | ------- | | aztec | Yes | Yes | | codabar | No | Yes | | code39 | Yes | Yes | | code93 | Yes | Yes | | code128 | Yes | Yes | | code138 | Yes | No | | code39mod43 | Yes | No | | datamatrix | Yes | Yes | | ean13 | Yes | Yes | | ean8 | Yes | Yes | | interleaved2of5 | Yes | Yes | | itf14 | Yes | No | | maxicode | No | Yes | | pdf417 | Yes | Yes | | rss14 | No | Yes | | rssexpanded | No | Yes | | upc_a | No | Yes | | upc_e | Yes | Yes | | upc_ean | No | Yes | | qr | Yes | Yes | `}</Code>} ### Example ${<Code>{` import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { BarCodeScanner, Permissions } from 'expo'; export default class BarcodeScannerExample extends React.Component { state = { hasCameraPermission: null, } async componentWillMount() { const { status } = await Permissions.askAsync(Permissions.CAMERA); this.setState({hasCameraPermission: status === 'granted'}); } render() { const { hasCameraPermission } = this.state; if (hasCameraPermission === null) { return <View />; } else if (hasCameraPermission === false) { return <Text>No access to camera</Text>; } else { return ( <View style={{flex: 1}}> <BarCodeScanner onBarCodeRead={this._handleBarCodeRead} style={StyleSheet.absoluteFill} /> </View> ); } } _handleBarCodeRead = (data) => { alert(JSON.stringify(data)); } } `}</Code>} ### props - \`type\` When \`'front'\`, use the front-facing camera. When \`'back'\`, use the back-facing camera. Default: \`'back'\`. - \`torchMode\` When \`'on'\`, the flash on your device will turn on, when \`'off'\`, it will be off. Defaults to \`'off'\`. - \`barCodeTypes\` An array of bar code types. Usage: \`BarCodeScanner.Constants.BarCodeType.<codeType>\` where \`codeType\` is one of the listed above. Default: all supported bar code types. `)
tests/Rules-isEmail-spec.js
bitgaming/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isEmail" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with "foo"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with "foo@foo.com"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo@foo.com"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={''}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } };
index.ios.js
ericmasiello/TrailReporter
import {Provider} from 'react-redux'; import store from './src/redux/store'; import AppViewContainer from './src/modules/AppViewContainer'; import React from 'react'; import {AppRegistry} from 'react-native'; const TrailReporter = React.createClass({ render() { return ( <Provider store={store}> <AppViewContainer /> </Provider> ); } }); AppRegistry.registerComponent('TrailReporter', () => TrailReporter);
js/jqwidgets/demos/react/app/calendar/restrictdaterange/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxCalendar from '../../../jqwidgets-react/react_jqxcalendar.js'; class App extends React.Component { render() { return ( <div> <div>The navigation is restricted from 01/01/2010 to 01/01/2015</div> <br /> <JqxCalendar width={220} height={220} min={new Date(2010, 0, 1)} max={new Date(2014, 11, 31)} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/components/CanvasComponent.js
nchathu2014/canvas_react
import React from 'react'; import ReactDOM from 'react-dom'; import MenuComponent from './MenuComponent'; import ViewComponent from './ViewComponent'; var CanvasComponent = React.createClass({ popUpClose:function(){ $(".popUpModal").show().hide("slide", {direction: "right" }, 500 );//slide animated to popup dialog }, render:function(){ return( <div className="container-fluid"> <div className="row"> <div className="col-lg-3"> <h3>Build a Quiz/Poll</h3> </div> <div className="col-lg-9" style={{textAlign:'right'}}> <button type="button" className="btn btn-md btn-primary" style={{width:'auto'}}>Save as Draft </button> <span>&nbsp;</span> <button type="button" className="btn btn-md btn-primary" style={{width:'auto'}}>Publish </button> </div> </div> <div className="row"> <div className="col-lg-3 leftDiv"> <MenuComponent/> </div> <div className="col-lg-9 rightDiv"> <ViewComponent/> </div> </div> {/*popup modal*/} <div className="popUpModal"> <button type="button" className="close pull-left" onClick={this.popUpClose} data-dismiss="modal" aria-hidden="true">×</button> </div> </div> ); } }); ReactDOM.render( <CanvasComponent/>, document.getElementById('container') );
app/config/routes.js
cbrwizard/cbr-landing
//import React from 'react'; //import Router from 'react-router'; //import App from './../components/app/main'; //import Index from './../components/regular/pages/index/main'; //import Admin from './../components/admin/pages/index/main'; // //const Route = Router.Route; //const DefaultRoute = Router.DefaultRoute; // //const routes = ( // <Route name='app' path='/' handler={App}> // <Route name='index' handler={Index}/> // <Route name='admin' handler={Admin}/> // // <DefaultRoute handler={Index}/> // </Route> //); // //export default routes;
src/routes/Users/containers/userDetailContainer.js
roslaneshellanoo/react-redux-tutorial
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' class UserDetail extends React.Component { render () { if (!this.props.user) { return ( <h4>Select a user...</h4> ) } return ( <ul className='wrap-user-detail list-group'> <li className='list-group-item'>Name: {this.props.user.name}</li> <li className='list-group-item'>Age: {this.props.user.born}</li> <li className='list-group-item'>Description: {this.props.user.description}</li> </ul> ) } } UserDetail.propTypes = { user: PropTypes.object, born: PropTypes.any, description: PropTypes.string, } const mapStateToProps = (state) => ({ user: state.activeUser }) export default connect(mapStateToProps)(UserDetail)
src/applications/find-forms/widgets/createFindVaFormsPDFDownloadHelper/DownloadPDFGuidance.js
department-of-veterans-affairs/vets-website
// Dependencies. import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // relative imports import DownloadPDFModal from './DownloadPDFModal'; import InvalidFormDownload from './InvalidFormAlert'; import recordEvent from 'platform/monitoring/record-event'; import { sentryLogger } from './index'; import { showPDFModal } from '../../helpers/selectors'; import { doesCookieExist, setCookie } from '../../helpers'; const removeReactRoot = () => { const pdf = document.querySelector('.faf-pdf-alert-modal-root'); pdf.remove(); }; // DownloadPDFGuidance sole purpose is to render the react widget depending on params (PDF is valid or not) const DownloadPDFGuidance = ({ downloadUrl, form, formNumber, formPdfIsValid, formPdfUrlIsValid, link, listenerFunction, netWorkRequestError, reduxStore, }) => { const div = document.createElement('div'); div.className = 'faf-pdf-alert-modal-root'; const parentEl = link.parentNode; if (formPdfIsValid && formPdfUrlIsValid && !netWorkRequestError) { // feature flag if ( reduxStore?.getState && showPDFModal(reduxStore.getState()) && !doesCookieExist() ) { ReactDOM.render( <Provider store={reduxStore}> <DownloadPDFModal formNumber={formNumber} removeNode={removeReactRoot} url={downloadUrl} /> </Provider>, div, ); parentEl.insertBefore(div, link); // Insert modal on DOM setCookie(); // SET 24 hr cookie since it did not exist recordEvent({ // Record GA event event: 'int-modal-click', 'modal-status': 'opened', 'modal-title': 'Download this PDF and open it in Acrobat Reader', }); } else { // if the Feature Flag for the Modal is turned off link.removeEventListener('click', listenerFunction); link.click(); } } else { let errorMessage = 'Find Forms - Form Detail - invalid PDF accessed'; if (netWorkRequestError) errorMessage = 'Find Forms - Form Detail - onDownloadLinkClick function error'; if (!formPdfIsValid && !formPdfUrlIsValid) errorMessage = 'Find Forms - Form Detail - invalid PDF accessed & invalid PDF link'; if (formPdfIsValid && !formPdfUrlIsValid) errorMessage = 'Find Forms - Form Detail - invalid PDF link'; sentryLogger(form, formNumber, downloadUrl, errorMessage); const alertBox = <InvalidFormDownload downloadUrl={downloadUrl} />; ReactDOM.render(alertBox, div); parentEl.insertBefore(div, link); parentEl.removeChild(link); } }; export default DownloadPDFGuidance;
src/routes/savoringYourPet/SavoringYourPet.js
goldylucks/adamgoldman.me
// @flow /* eslint-disable react/no-unescaped-entities */ import React from 'react' import axios from 'axios' import withStyles from 'isomorphic-style-loader/lib/withStyles' import MessengerFixed from './MessengerFixed' import testimonials from './testimonialsData' import FAQContainer from './FAQContainer' import MobileNav from './MobileNav' import { cloudImg, scrollToTopOfNode } from '../../utils' import Link from '../../components/Link' import Footer from '../../components/Footer' import ExternalA from '../../components/ExternalA' import Benefits from '../../components/Benefits' import Testimonials from '../../components/Testimonials' import './SavoringYourPet.css' export const TOP_BAR_HRIGHT = 56 type Props = {} type State = { isCouponApplied: boolean, isProcessingCoupon: boolean, couponInputValue: string, } class SavoringYourPet extends React.Component<Props, State> { state = { isCouponApplied: false, isProcessingCoupon: false, couponInputValue: '', } render() { return ( <div style={{ paddingTop: TOP_BAR_HRIGHT }}> <MessengerFixed /> {this.renderTopBar()} <div className='container'> <div className={`mainheading ${s.widthContainer}`}> <h1 className='sitetitle text-center'> How to honor your furry friend&apos;s memory after the transition </h1> <p className='lead text-center'> And savor the relationship in a healing way </p> <div className='text-center'> <div> <img src={cloudImg('adamgoldman.me/until-loved-animal')} alt='Grief for pet love' style={{ maxWidth: '100%' }} /> </div> <span> Source:{' '} <ExternalA href='https://me.me/i/until-one-has-loved-an-animal-a-part-of-ones-21452968'> me.me </ExternalA> </span> </div> </div> <div className={s.widthContainer}> <p> Losing your beloved pet is one of{' '} <strong> the most devastating experiences a human can go through </strong> . The pain can be greater than losing a family member. </p> <p> The unconditional love, the acceptance, the beloved companionship ... It’s something you rarely get anywhere else. </p> <hr className={s.hr} /> <h4 ref={el => { this.elTrauma = el }} className='text-center' > “The death of a pet can be a truly traumatic experience and create a large void in our hearts and lives” <br />-{' '} <strong>Ralph Ryback M.D.</strong> </h4> <hr className={s.hr} /> <h2 className='text-center' style={{ marginBottom: 20 }}> Do you feel any of the following? </h2> <ul> <li> <strong>Emptiness</strong> as you go through your day? </li> <li> <strong>Guilt & regret</strong> about what you did or didn’t do? </li> <li> <strong>Doubt</strong> you will ever fill this void? </li> </ul> <p> You need to know <strong>you are NOT alone</strong> in this, and what you are going through is very, VERY understandable. It’s not uncommon to hear the following outcries from fellow grieving souls who’ve shared similar fate: </p> <ul> <li>"I have nothing to look forward to"</li> <li> <strong>“A big part of me has died”</strong> </li> <li>"Will this pain ever go away?"</li> </ul> <hr className={s.hr} /> <h4 className='text-center'> “Unattended grief is one of the leading underlying causes for depression” <br />- <strong>Steve Andreas, M.A.</strong> </h4> <hr className={s.hr} /> <p> This is exactly the reason why{' '} <strong>I’ve been dedicating the last year to</strong> develop and refine a method to{' '} <strong> soften this pain, and alleviate much of the suffering </strong>{' '} you and others are feeling right now. </p> <p> I’ve talked and listened to hundreds of people just like you, and helped dozens experiencing crippling grief and unbearable pain, while consulting with two amazing people (see below) whose work has impacted thousands of lives already. </p> <p> Our combined work gave birth to a new program, unlike anything we’ve seen or experienced before. </p> <hr className={s.hr} /> <strong className='text-center'>Presenting ...</strong> <h1 ref={el => { this.elProgram = el }} className='text-center' > Savoring Your Pet </h1> <p className='lead'> A step by step gentle journey from grief to appreciation, that will show you how to transform and soften your grief in a healthier way, alleviate much of your pain, so you can expect to ... </p> {this.renderBenefitsSection()} <h2 className='text-center' style={{ marginTop: 20, marginBottom: 20 }} > How is this program different? </h2> <p> I know we all had our share of things that did not work, so let me start by listing what we will NOT be doing together: </p> <div> <div>❌ Medication</div> <div>❌ Life advice or coaching</div> <div>❌ Positive affirmations</div> <div>❌ Traditional therapy and psychoanalysis</div> <div>❌ Mediums / channeling / other dimension communication</div> <div>❌ New age woo-woo methods</div> </div> <h5 className='text-center' style={{ marginTop: 20, marginBottom: 20 }} > It’s not about saying goodbye </h5> <p> Most people (even professionals!) make the common mistake of thinking grief is about learning to say goodbye. I have NOT found this to be useful! </p> <p> Why would any of us would want to say goodbye to such a beautiful, ever loving, unconditionally accepting relationship? </p> <p> I don't want you to say goodbye, I want you to{' '} <strong>learn how to say hello again</strong>. How to think of your loved one in a way that honors them, and{' '} <strong>treasure the good experiences</strong> you shared, and everything that relationship has given you. </p> <p> One of the first things you’ll soon learn is how to gently implement the following simple yet beautiful wisdom: </p> <div className='text-center'> <img src={cloudImg('adamgoldman.me/dr-sauss-it-happened')} alt='Smile because it happened' style={{ maxWidth: '100%' }} /> <span> Source:{' '} <ExternalA href='https://www.scoopnest.com/user/Jestepar/758043485618528257-don-t-cry-because-it-s-over-smile-because-it-happened-dr-seuss-quote-thankfulthursday'> scoopnest.com </ExternalA> </span> </div> <hr className={s.hr} /> <h2 ref={el => { this.elModules = el }} className='text-center' style={{ marginBottom: 30 }} > Here’s what you’re getting when you get your copy of the program today: </h2> {this.renderModules()} {this.renderBuyNowScrollButton()} <hr className={s.hr} /> <div className='text-center'> <h2>Trusted by a leading brand</h2> <img src={cloudImg('i-love-vet-cover_y5radw')} alt='Animal grief partners' style={{ maxWidth: '100%' }} /> <ExternalA href='https://iloveveterinary.com/'> I Love Veterinary </ExternalA> </div> </div> <div className={s.widthContainer}> <hr className={s.hr} /> </div> {this.renderAndreas()} <div className={s.widthContainer}> <hr className={s.hr} /> <div className={s.widthContainer}> {this.renderAboutMeSection()} </div> <hr className={s.hr} /> </div> {this.renderTestimonialsSection()} <div className={s.widthContainer}> <hr className={s.hr} /> <h2 ref={el => { this.elBuyNow = el }} className='text-center' > “So how much will it cost me?” </h2> <p> I have invested thousands of dollars, and countless days and nights of work and research into this program, but I want to keep it affordable for you and others who are going through this, so I am asking a lot less than the actual value of the program. </p> <div> <h4 className='text-center'> <small>Instead of the full price of </small> <s>312$</s> </h4> {this.renderFinalPrice()} {this.renderPaymentButton()} {this.renderPaypalSecure()} </div> <hr className={s.hr} /> <p> That’s right, you can <strong>guarantee</strong> your{' '} <strong>lifetime access</strong> to this program{' '} <strong>for less than the price of 1 therapy session</strong>. </p> <p> I am so confident this will help you beyond your expectations, I’m willing to personally take all the risk off your hands when you invest in this today, with a double guarantee: </p> <div ref={el => { this.elGuarantee = el }} className='text-center' style={{ marginBottom: 40 }} > <h4 className='text-center'> 30 days no hassle money back guarantee </h4> <img src={cloudImg('30-day-refund-guarantee_ug806q')} alt='30 day refund guarantee' /> </div> <h4 className='text-center' style={{ marginBottom: 40 }}> Complementary private session guarantee (100$ value) </h4> <p> In fact, I’m willing to make this even easier for you to get on board today. I charge 200$ for a private 1 hour session. and after you’re done with this program, if you still don’t feel this is one of the best decisions you ever took since embarking on your journey of grief, I will not only refund you in full, I will get on a complementary one on one 30 minute private video session with you, to explore other methods to assist you and facilitate in your healing. </p> <p> You either get immense benefits from this program, or you get a 100$ worth free session. Either way, it’s a win-win for you. </p> <hr className={s.hr} /> <h5 style={{ marginBottom: 30 }} className='text-center'> No need to continue suffering more than you have to </h5> <p> <strong>Instead of feeling pain</strong> as you think of your beloved close companion, you have the opportunity to literally rewire your mind to{' '} <strong> reclaim the good feelings, warmth and appreciation </strong>{' '} about everything you valued and didn’t want to lose. </p> <p> <strong>Instead of losing sleep</strong> and missing any more opportunities for a better life, you can learn how to{' '} <strong>let the qualities you appreciate</strong> in your furry friend, compel and <strong>draw you forward</strong> to an ever{' '} <strong>brightening future</strong>. </p> <p> I am very curious to hear about all the ways the decision you took today has brought peace, comfort and love to your life. </p> <p> Best to you on your journey, <br />- <strong>Adam Goldman</strong> </p> {this.renderBuyNowScrollButton()} <p style={{ marginTop: 40 }}> <strong>Ps.</strong>Yes, you can literally rewire your mind, body and feelings, to transform your current grief to feeling of appreciation, in way that will honor your lost furry friend in a comprehensive way. </p> <p> <strong>Ps.s. </strong>Remember all the risk is on me, so when you gain access today there’s nothing for you to lose other than unwanted negative feelings. </p> <section style={{ marginTop: 40 }}> <FAQContainer /> </section> </div> </div> <div className='container container-footer'> <Footer /> </div> </div> ) } renderTopBar() { const navitems = [ { text: 'Trauma', nodeId: 'elTrauma' }, { text: 'Program', nodeId: 'elProgram' }, { text: 'Modules', nodeId: 'elModules' }, { text: 'Research', nodeId: 'elResearch' }, { text: 'About Me', nodeId: 'elAboutMe' }, { text: 'Guarantee', nodeId: 'elGuarantee' }, ] const title = 'Savoring Your Pet' return ( <nav className='navbar navbar-expand-lg fixed-top main-nav navbar-light'> <div className='container'> <MobileNav items={navitems} onItemClick={this.scrollTo} title={title} /> <Link className='navbar-brand mr-auto' to='/savoring-your-pet'> {title} </Link> <div className='collapse navbar-collapse'> <ul className='navbar-nav ml-auto'> {navitems.map(({ text, nodeId }) => ( <li className='nav-item' key={nodeId}> <a className='nav-link' onClick={() => this.scrollTo(nodeId)}> {text} </a> </li> ))} <li className='nav-item' key='buyNow'> <a className='nav-link btn btn-primary btn-sm' onClick={() => this.scrollTo('elBuyNow')} > Claim Access </a> </li> </ul> </div> </div> </nav> ) } scrollTo = nodeId => { scrollToTopOfNode(this[nodeId], { duration: 1000, topOffest: TOP_BAR_HRIGHT, }) } renderBenefitsSection() { return ( <section> <div className='row justify-content-md-center'> <div className='col col-lg-10'> <Benefits benefits={[ 'Enjoy thinking about your beloved furry friend again', 'Focus on the good experiences shared', 'Feel their love & presence even more', 'Look forward to a brightening future', 'Increase the peace & love in your life', ]} /> </div> </div> <small> * Results may vary ( <ExternalA href='/legal-stuff' style={{ color: 'inherit' }}> full disclaimer </ExternalA> ) </small> </section> ) } renderModules() { return ( <div> <div> <h3>Module 1: Clarity and order</h3> <p> We’ll go over 6 common aspects of grief and carefully separate them to distinct concepts, before we examine and transform them one by one. <br /> <strong>✔️ Value: 30$</strong> </p> </div> <div> <h3>Module 2: Peaceful Ending</h3> <p> Soften the unpleasantness and negative feelings regarding the moment of transition, and the events regarding the transition, and rewire your mind to go back to the happy memories. This will also pacify disturbing or graphic images you might still have. <br />{' '} <strong>✔️ Value: 47$</strong> </p> </div> <div> <h3>Module 3: Savoring future plans</h3> <p> Increase the peace and acceptance towards the future that will not be, and events you might have planned with your beloved furry friend. <br /> <strong>✔️ Value: 47$</strong> </p> </div> <div> <h3>Module 4: Reunion</h3> <p> Say “hello” again, and regain access to the good times shared, and what you valued in the relationship and didn’t want to lose. <br />{' '} <strong>✔️ Value: 47$</strong> </p> </div> <div> <h3>Module 5: Relationship Consolidation</h3> <p> Every relationship has ups and downs. Learn how to intensify the good feelings from the good experiences, and soften and discharge bad experiences and events you had. <br />{' '} <strong>✔️ Value: 47$</strong> </p> </div> <div> <h3>Module 6: Special Days</h3> <p> Some days of the year are usually harder than others, like memorial days, anniversary days for getting or adopting your pet, or their birthday. In this process you learn how to use these days as an opportunity to remind yourself how lucky you are to have had them in your life, reminisce about your relationship and honor it even more.{' '} <br /> <strong>✔️ Value: 47$</strong> </p> </div> <div> <h3>Module 7: Re-engaging the future</h3> <p> Now that we transformed much of the emptiness to presence and appreciation, it’s time to create a compelling ever brightening future, as you learn how to let the qualities in this valued relationship draw you forward. <br /> <strong>✔️ Value: 47$</strong> </p> </div> <div className='text-center'> <h2>How much does it worth?</h2> 30$ + 47$ + 47$ + 47$ + 47$ + 47$ + 47$ = <h3 style={{ marginTop: 20 }}>312$</h3> </div> </div> ) } renderBuyNowScrollButton() { return ( <button onClick={() => scrollToTopOfNode(this.elBuyNow, 1000)} className={`btn btn-primary ${s.getStartedButton}`} > Get Started </button> ) } renderAndreas() { return ( <div ref={el => { this.elResearch = el }} > <div className={s.widthContainer}> <h2 className='text-center'> Made possible by decades of research and field experience </h2> <p> Many parts of this program are based on the work of Steve and Connirae Andreas, a couple of humble and extremely precise personal change practitioners, with{' '} <strong> more than 80+ years of experience in the field of psychology and personal change </strong> . </p> <h6 className='text-center'>Connirae & Steve Andreas</h6> </div> <div className={s.andreasContainerBoth}> <div className={s.andreasContainerIndividual}> <img src={cloudImg('adamgoldman.me/Connirae_Andreas')} alt='Connirae Andreas' /> <ExternalA className={s.andreasCaption} href='https://andreasnlptrainings.com/connirae-andreas-bio/' > Connirae Andreas, Ph.D., master trainer </ExternalA> </div> <div className={s.andreasContainerIndividual}> <img src={cloudImg('adamgoldman.me/Steve_Andreas')} alt='Steve Andreas' /> <ExternalA className={s.andreasCaption} href='http://steveandreas.com/cv.html' > Steve Andreas, M.A., master trainer </ExternalA> </div> </div> <div className={s.widthContainer}> <blockquote style={{ marginTop: 20 }}> Adam Goldman is a brilliant new colleague whose depth and breadth of understanding of the principles of personal change is exceptional, combined with the hands-on skills to manifest this in the experience of clients. <br /> <br /> Perceptive, intelligent, creative, confident, one of the fastest and most thorough learners I’ve ever met, able and willing to question established wisdom and discuss differences of opinion openly when that’s appropriate. <br /> <br /> He has created online programs to guide participants through effective change processes on their own, a huge opportunity for so many who would otherwise not be able to even think of affording it. <br /> <br /> His work is a detailed challenge to the rest of us to learn how to “up our game” or be left behind in the dustbin of history. <br /> <strong>- Steve Andreas, MA, master trainer and author.</strong> </blockquote> </div> </div> ) } renderTestimonialsSection() { return ( <section> <div className={s.widthContainer}> <p className='text-center'> But don’t take my word for it, listen to what people I’ve worked with on grief have to say ...{' '} <span className={s.asterixDisclaimer}>*</span> </p> </div> <Testimonials testimonials={testimonials} /> <small> * Results may vary ( <ExternalA href='/legal-stuff' style={{ color: 'inherit' }}> full disclaimer </ExternalA> ) </small> </section> ) } renderAboutMeSection() { return ( <section ref={el => { this.elAboutMe = el }} id='about-me' > <h1 className='text-center'> Who am I to guide you through this journey? </h1> <div className={s.aboutContainer}> <img src={cloudImg('adamgoldman.me/profile-smiling')} alt='About Adam Goldman' /> <p className='lead'> I&apos;ve been guiding people through and developing personal change processes for almost a decade. <br /> <br /> I’ve gone through countless courses, videos, books, and programs, and <strong>my passion is distilling</strong> the most useful and{' '} <strong> powerful processes into easy to follow, step by step personal journeys </strong>{' '} for people just like you to experience in a very gentle and comfortable way. </p> </div> </section> ) } renderFinalPrice() { const { isCouponApplied } = this.state if (!isCouponApplied) { return ( <h3 className='text-center'> <small>Order today for</small> <br /> <strong>Only 97$</strong> </h3> ) } return ( <div> <h3 className='text-center' style={{ textDecoration: 'line-through' }}> <small>Order today for</small> <br /> <strong>Only 97$</strong> </h3> <h2 className='text-center'> Limited time offer for I Love Veterinary customers! </h2> <h3 className='text-center'> <small>Order today for</small> <br /> <strong>Only 47$</strong> </h3> </div> ) } renderPaymentButton() { const { isCouponApplied, couponInputValue, isProcessingCoupon } = this.state return ( <div> <form action='https://www.paypal.com/cgi-bin/webscr' method='post' target='_blank' className='text-center' > <input type='hidden' name='cmd' value='_s-xclick' /> <input type='hidden' name='landing_page' value='billing' /> <input type='hidden' name='hosted_button_id' value={isCouponApplied ? 'RHHHM7QUDJRXE' : '5RVFWYZP5HMBG'} /> <input type='image' src='http://res.cloudinary.com/goldylucks/image/upload/v1531924994/get-access-now_pqssf4.jpg' border='0' name='submit' alt='PayPal - The safer, easier way to pay online!' /> <img alt='' border='0' src='https://www.paypalobjects.com/en_US/i/scr/pixel.gif' width='1' height='1' /> </form> <form onSubmit={this.onSubmitCoupon} className='text-center'> <input type='text' value={couponInputValue} onChange={this.onCouponInputChange} placeholder='Coupon' /> <button>Validate Coupon</button> </form> {isProcessingCoupon && <p>Loading, please wait ...</p>} </div> ) } onCouponInputChange = evt => { this.setState({ couponInputValue: evt.target.value }) } onSubmitCoupon = async evt => { const { couponInputValue, isProcessingCoupon } = this.state evt.preventDefault() if (isProcessingCoupon) { return } this.setState({ isProcessingCoupon: true }) try { const { data: isValid } = await axios.post('/api/savoringPetCoupon', { coupon: couponInputValue, }) if (isValid) { global.alert('Valid coupon, enjoy your discount') this.setState({ isCouponApplied: true, isProcessingCoupon: false }) } else { global.alert( 'invalid coupon, please contact me if you think it is a mistake', ) this.setState({ isProcessingCoupon: false }) } } catch (err) { this.setState({ isProcessingCoupon: false }) global.alert('error validating the coupon, please try again') } } renderPaypalSecure() { return ( <div className='text-center'> <img src={cloudImg('pay-pal-secured_z1lxgq')} alt='Paypal secured' style={{ maxWidth: '100px', marginTop: 10, marginBottm: 10 }} /> <div> <span> Source:{' '} <ExternalA href='https://e-trimas.com/page/payment-method'> e-trimas.com </ExternalA> </span> </div> </div> ) } } export default withStyles(s)(SavoringYourPet)
ZWRNProject/app/src/views/UI/KeyboardAvoidingView/KeyboardAvoidingViewExample.js
MisterZhouZhou/ReactNativeLearing
import React, { Component } from 'react'; import {KeyboardAvoidingView, Modal, SegmentedControlIOS,StyleSheet,Text,TextInput,TouchableHighlight,View} from 'react-native'; const UIExplorerBlock = require('../../UIExplorer/UIExplorerBlock'); const UIExplorerPage = require('../../UIExplorer/UIExplorerPage'); export default class KeyboardAvoidingViewExample extends Component { static title = '<KeyboardAvoidingView>'; static description = 'Base component for views that automatically adjust their height or position to move out of the way of the keyboard.'; state = { behavior: 'padding', modalOpen: false, }; onSegmentChange = (segment: String) => { this.setState({behavior: segment.toLowerCase()}); }; renderExample = () => { return ( <View style={styles.outerContainer}> <Modal animationType="fade" visible={this.state.modalOpen}> <KeyboardAvoidingView behavior={this.state.behavior} style={styles.container}> <SegmentedControlIOS onValueChange={this.onSegmentChange} selectedIndex={this.state.behavior === 'padding' ? 0 : 1} style={styles.segment} values={['Padding', 'Position']} /> <TextInput placeholder="<TextInput />" style={styles.textInput} /> </KeyboardAvoidingView> <TouchableHighlight onPress={() => this.setState({modalOpen: false})} style={styles.closeButton}> <Text>Close</Text> </TouchableHighlight> </Modal> <TouchableHighlight onPress={() => this.setState({modalOpen: true})}> <Text>Open Example</Text> </TouchableHighlight> </View> ); }; render() { return ( <UIExplorerPage title="Keyboard Avoiding View"> <UIExplorerBlock title="Keyboard-avoiding views move out of the way of the keyboard."> {this.renderExample()} </UIExplorerBlock> </UIExplorerPage> ); } } const styles = StyleSheet.create({ outerContainer: { flex: 1, }, container: { flex: 1, justifyContent: 'center', paddingHorizontal: 20, paddingTop: 20, }, textInput: { borderRadius: 5, borderWidth: 1, height: 44, paddingHorizontal: 10, }, segment: { marginBottom: 10, }, closeButton: { position: 'absolute', top: 30, left: 10, } });
blueocean-material-icons/src/js/components/svg-icons/action/view-module.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionViewModule = (props) => ( <SvgIcon {...props}> <path d="M4 11h5V5H4v6zm0 7h5v-6H4v6zm6 0h5v-6h-5v6zm6 0h5v-6h-5v6zm-6-7h5V5h-5v6zm6-6v6h5V5h-5z"/> </SvgIcon> ); ActionViewModule.displayName = 'ActionViewModule'; ActionViewModule.muiName = 'SvgIcon'; export default ActionViewModule;
src/components/top-level-entity-modal/top-level-entity-modal.js
mpigsley/sectors-without-number
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactHintFactory from 'react-hint'; import { RefreshCw, X, Plus } from 'react-feather'; import { FormattedMessage, intlShape } from 'react-intl'; import Modal from 'primitives/modal/modal'; import Button from 'primitives/other/button'; import Label from 'primitives/form/label'; import IconInput from 'primitives/form/icon-input'; import Input from 'primitives/form/input'; import Dropdown from 'primitives/form/dropdown'; import FlexContainer from 'primitives/container/flex-container'; import Dice from 'primitives/icons/dice'; import Header, { HeaderType } from 'primitives/text/header'; import Entities from 'constants/entities'; import { createId, coordinatesFromKey } from 'utils/common'; import EntityGenerators from 'utils/entity-generators'; import { filter, map, mapValues, zipObject, omit, values, size, pickBy, flatten, } from 'constants/lodash'; import './style.scss'; const ReactHint = ReactHintFactory(React); const TopLevelLevelEntities = filter(Entities, entity => entity.topLevel); const generateChildrenNames = (parentEntity, currentSector, customTags) => { let names = {}; let currentSort = 0; Entities[parentEntity].children.forEach(child => { const { children } = EntityGenerators[child].generateAll({ sector: currentSector, parentEntity, customTags, parent: createId(), }); names = { ...names, [child]: zipObject( children.map(createId), children.map(({ name }) => { currentSort += 1; return { name, generate: true, sort: currentSort, }; }), ), }; }); return { children: names, currentSort }; }; export default class TopLevelEntityModal extends Component { constructor(props) { super(props); const { isOpen, currentSector, customTags } = props; this.state = { isOpen, // eslint-disable-line currentSort: 0, name: Entities.system.nameGenerator(), ...generateChildrenNames(Entities.system.key, currentSector, customTags), entityType: Entities.system.key, }; } static getDerivedStateFromProps(props, state) { if (props.isOpen && !state.isOpen) { return { isOpen: props.isOpen, name: Entities[state.entityType].nameGenerator(), ...generateChildrenNames( state.entityType, props.currentSector, props.customTags, ), }; } return { ...state, isOpen: props.isOpen }; } onNewEntityName = () => { const { entityType } = this.state; this.setState({ name: Entities[entityType].nameGenerator() }); }; onEditEntity = ({ target }) => { this.setState({ [target.dataset.key]: target.value }); }; onChangeChildType = (entityType, entityId) => item => { const { children } = this.state; if (entityType !== item.value) { const oldEntity = children[entityType][entityId]; this.setState({ children: { ...children, [entityType]: omit(children[entityType], entityId), [item.value]: { ...children[item.value], [entityId]: { ...oldEntity, name: Entities[item.value].nameGenerator(), }, }, }, }); } }; onEditChild = (entityType, entityId) => ({ target }) => { const { children } = this.state; this.setState({ children: { ...children, [entityType]: { ...children[entityType], [entityId]: { ...children[entityType][entityId], name: target.value, }, }, }, }); }; onChangeGenerate = (entityType, entityId) => ({ target }) => { const { children } = this.state; this.setState({ children: { ...children, [entityType]: { ...children[entityType], [entityId]: { ...children[entityType][entityId], generate: target.checked, }, }, }, }); }; onNewChildName = (entityType, entityId) => { const { children } = this.state; this.setState({ children: { ...children, [entityType]: { ...children[entityType], [entityId]: { ...children[entityType][entityId], name: Entities[entityType].nameGenerator(), }, }, }, }); }; onDeleteChild = (entityType, entityId) => { const { children } = this.state; this.setState({ children: pickBy( { ...children, [entityType]: omit(children[entityType], entityId), }, size, ), }); }; onAddChild = () => { const { children, currentSort } = this.state; const nextSort = currentSort + 1; this.setState({ currentSort: nextSort, children: { ...children, [Entities.planet.key]: { ...children[Entities.planet.key], [createId()]: { name: Entities.planet.nameGenerator(), generate: true, sort: nextSort, }, }, }, }); }; onSubmit = () => { const { name, entityType, children } = this.state; const { generateEntity, currentSector, topLevelKey, intl } = this.props; generateEntity( { name, entityType }, { generate: true, children: mapValues(children, child => values(child)), ...coordinatesFromKey(topLevelKey), parent: currentSector, parentEntity: Entities.sector.key, }, intl, ); }; renderEditRow = (rowType, { name, generate }, key) => { const { entityType } = this.state; const { intl } = this.props; return ( <FlexContainer className="TopLevelEntityModal-Planet" key={key} align="center" > <X className="TopLevelEntityModal-Delete" size={25} onClick={() => this.onDeleteChild(rowType, key)} /> <Dropdown wrapperClassName="TopLevelEntityModal-Type" value={rowType} clearable={false} onChange={this.onChangeChildType(rowType, key)} options={Entities[entityType].children.map(child => ({ value: child, label: intl.formatMessage({ id: Entities[child].name }), }))} /> <IconInput className="TopLevelEntityModal-Name" name="name" icon={RefreshCw} value={name} onChange={this.onEditChild(rowType, key)} onIconClick={() => this.onNewChildName(rowType, key)} /> <Input className="TopLevelEntityModal-Generate" onChange={this.onChangeGenerate(rowType, key)} checked={generate} name="checkbox" type="checkbox" /> </FlexContainer> ); }; renderChildren() { const { entityType, children } = this.state; const { intl } = this.props; if (Entities[entityType].children.length) { return ( <FlexContainer direction="column"> <FlexContainer justify="spaceBetween" align="flexEnd"> <Label> <FormattedMessage id="misc.children" /> </Label> <Dice data-rh={intl.formatMessage({ id: 'misc.selectGenerateEntity', })} size={22} /> </FlexContainer> <FlexContainer direction="column"> {flatten( map(children, (entities, type) => map(entities, (child, key) => ({ type, child, key })), ), ) .sort((a, b) => a.child.sort - b.child.sort) .map(({ type, child, key }) => this.renderEditRow(type, child, key), )} <FlexContainer className="TopLevelEntityModal-Add" align="center" onClick={this.onAddChild} > <Plus className="TopLevelEntityModal-Plus" size={20} /> <FormattedMessage id="misc.addChild" /> </FlexContainer> </FlexContainer> </FlexContainer> ); } return ( <FlexContainer justify="center"> <Header type={HeaderType.header4} className="TopLevelEntityModal-EmptyText" > <FormattedMessage id="misc.selectedNoChilden" /> </Header> </FlexContainer> ); } render() { const { isOpen, cancelTopLevelEntityCreate, intl, currentSector, customTags, } = this.props; const { entityType, name } = this.state; return ( <Modal width={600} isOpen={isOpen} onCancel={cancelTopLevelEntityCreate} title={intl.formatMessage({ id: 'misc.createEntity' })} actionButtons={[ <Button primary key="create" onClick={this.onSubmit}> <FormattedMessage id="misc.create" /> </Button>, ]} > <ReactHint events position="left" /> <FlexContainer> <FlexContainer direction="column" className="TopLevelEntityModal-Type" > <Label noPadding htmlFor="name"> <FormattedMessage id="misc.entityType" /> </Label> <Dropdown value={entityType} clearable={false} onChange={item => { const newType = (item || {}).value; this.setState({ entityType: newType, ...generateChildrenNames(newType, currentSector, customTags), }); }} options={TopLevelLevelEntities.map(attr => ({ value: attr.key, label: intl.formatMessage({ id: attr.name }), }))} /> </FlexContainer> <FlexContainer direction="column" className="TopLevelEntityModal-Name" > <Label noPadding htmlFor="name"> <FormattedMessage id="misc.entityName" values={{ entity: intl.formatMessage({ id: Entities[entityType].name, }), }} /> </Label> <IconInput id="name" name="name" data-key="name" icon={RefreshCw} value={name} onChange={this.onEditEntity} onIconClick={this.onNewEntityName} /> </FlexContainer> </FlexContainer> {this.renderChildren()} </Modal> ); } } TopLevelEntityModal.propTypes = { isOpen: PropTypes.bool.isRequired, topLevelKey: PropTypes.string, currentSector: PropTypes.string.isRequired, cancelTopLevelEntityCreate: PropTypes.func.isRequired, generateEntity: PropTypes.func.isRequired, customTags: PropTypes.shape().isRequired, intl: intlShape.isRequired, }; TopLevelEntityModal.defaultProps = { topLevelKey: '', };
src/app/components/gooey-nav/gooeyNavItem.js
lmcjt37/kulor-reactify
import React from 'react'; export default ({ onClick, theme, icon, label }) => ( <a href="#" {...{onClick}} className={ theme['menu-item'] } > <i className="material-icons" >{icon}</i> <span className={ theme['menu-item-span']}>{label}</span> </a> );
src/app/utils/SlateEditor/Image.js
TimCliff/steemit.com
import React from 'react'; import { connect } from 'react-redux'; export default connect( (state, ownProps) => ownProps, dispatch => ({ uploadImage: (file, dataUrl, filename, progress) => { dispatch({ type: 'user/UPLOAD_IMAGE', payload: { file, dataUrl, filename, progress }, }); }, }) )( class Image extends React.Component { state = { progress: {}, }; componentWillMount() { const file = this.props.node.data.get('file'); // Save `file` for "Retry" // Try to load incase data url was loaded from a draft this.setState({ file }); } componentDidMount() { console.log('** image mounted..', this.state, this.props); this.load(); } setImageSrc(src, filename) { const { editor, node } = this.props; const state = editor.getState(); const next = state .transform() .setNodeByKey(node.key, { data: { src, alt: filename } }) .apply(); editor.onChange(next); } load = () => { let dataUrl, filename; const { file } = this.state; if (file) { // image dropped -- show a quick preview console.log('** image being loaded.. ----->', file); const reader = new FileReader(); reader.addEventListener('load', () => { dataUrl = reader.result; this.setImageSrc(dataUrl, file.name); }); reader.readAsDataURL(file); filename = file.name; } else { // draft, recover data using the preview data url const { data } = this.props.node; const src = data.get('src'); if (/^data:/.test(src)) { dataUrl = src; filename = data.get('alt'); } } if (!file && !dataUrl) return; this.setState({ progress: {}, uploading: true }, () => { const { uploadImage } = this.props; uploadImage(file, dataUrl, filename, progress => { this.setState({ progress, uploading: false }); if (progress.url) { this.setImageSrc(progress.url, filename); } }); }); }; render() { const { node, state, attributes } = this.props; const isFocused = state.selection.hasEdgeIn(node); const className = isFocused ? 'active' : null; const prefix = $STM_Config.img_proxy_prefix ? $STM_Config.img_proxy_prefix + '0x0/' : ''; const alt = node.data.get('alt'); const src = node.data.get('src'); console.log( '** rendering image... src:', src ? src.substring(0, 30) + '...' : '(null)', state ); if (!src) return <small className="info">Loading Image&hellip;</small>; if (/^https?:\/\//.test(src)) return ( <img {...attributes} src={prefix + src} alt={alt} className={className} /> ); const img = <img src={src} alt={alt} className={className} />; const { uploading } = this.state; if (uploading) return ( <div {...attributes}> {img} <br /> <small className="info">Uploading Image&hellip;</small> </div> ); const { error } = this.state.progress; return ( <div {...attributes}> {img} <div className="error"> <small> Image was not Saved (<a onClick={this.load}> retry </a>) <br /> {error} </small> </div> </div> ); } } );
src/icons/DeviceHubIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class DeviceHubIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M17 16l-4-4V8.82C14.16 8.4 15 7.3 15 6c0-1.66-1.34-3-3-3S9 4.34 9 6c0 1.3.84 2.4 2 2.82V12l-4 4H3v5h5v-3.05l4-4.2 4 4.2V21h5v-5h-4z"/></svg>;} };
src/components/UserMenu.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Scrollbars } from 'react-custom-scrollbars'; import { FormattedMessage, FormattedNumber } from 'react-intl'; import './UserMenu.less'; class UserMenu extends React.Component { static propTypes = { onChange: PropTypes.func, defaultKey: PropTypes.string, followers: PropTypes.number, following: PropTypes.number, }; static defaultProps = { onChange: () => {}, defaultKey: 'discussions', followers: 0, following: 0, }; constructor(props) { super(props); this.state = { current: props.defaultKey ? props.defaultKey : 'discussions', }; } componentWillReceiveProps(nextProps) { this.setState({ current: nextProps.defaultKey ? nextProps.defaultKey : 'discussions', }); } getItemClasses = key => classNames('UserMenu__item', { 'UserMenu__item--active': this.state.current === key }); handleClick = (e) => { const key = e.currentTarget.dataset.key; this.setState({ current: key }, () => this.props.onChange(key)); }; render() { return ( <div className="UserMenu"> <div className="container menu-layout"> <div className="left" /> <Scrollbars autoHide style={{ width: '100%', height: 46 }}> <ul className="UserMenu__menu center"> <li className={this.getItemClasses('discussions')} onClick={this.handleClick} role="presentation" data-key="discussions"> <FormattedMessage id="discussions" defaultMessage="Discussions" /> </li> <li className={this.getItemClasses('comments')} onClick={this.handleClick} role="presentation" data-key="comments"> <FormattedMessage id="comments" defaultMessage="Comments" /> </li> <li className={this.getItemClasses('followers')} onClick={this.handleClick} role="presentation" data-key="followers"> <FormattedMessage id="followers" defaultMessage="Followers" /> <span className="UserMenu__badge"> <FormattedNumber value={this.props.followers} /> </span> </li> <li className={this.getItemClasses('followed')} onClick={this.handleClick} role="presentation" data-key="followed"> <FormattedMessage id="following" defaultMessage="Following" /> <span className="UserMenu__badge"> <FormattedNumber value={this.props.following} /> </span> </li> <li className={this.getItemClasses('transfers')} onClick={this.handleClick} role="presentation" data-key="transfers"> <FormattedMessage id="wallet" defaultMessage="Wallet" /> </li> </ul> </Scrollbars> </div> </div> ); } } export default UserMenu;
client/app/components/auth/PasswordInput.js
joelseq/SourceGrade
import React from 'react'; import { FormGroup, FormControl, ControlLabel, Alert, } from 'react-bootstrap'; /* eslint-disable react/prop-types */ const PasswordInput = ({ input, meta: { touched, error }, ...custom }) => { let validationState = null; if (touched) { validationState = error ? 'error' : 'success'; } return ( <FormGroup controlId="password" validationState={validationState} > <ControlLabel>Password</ControlLabel> <FormControl type="password" placeholder="Password" required {...input} {...custom} /> {touched && error && <Alert bsStyle="danger">{error}</Alert>} </FormGroup> ); }; /* eslint-enable react/prop-types */ export default PasswordInput;
src/svg-icons/alert/warning.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertWarning = (props) => ( <SvgIcon {...props}> <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/> </SvgIcon> ); AlertWarning = pure(AlertWarning); AlertWarning.displayName = 'AlertWarning'; AlertWarning.muiName = 'SvgIcon'; export default AlertWarning;
packages/reactor-kitchensink/src/App.js
markbrocato/extjs-reactor
import React from 'react' import Layout from './Layout'; import { HashRouter as Router, Route } from 'react-router-dom' import createHistory from 'history/createHashHistory' import { Provider } from 'react-redux'; import { createStore, combineReducers } from 'redux'; import reducer from './reducer'; import { routeDidChange } from './actions'; const store = createStore( reducer, undefined, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('./reducer', () => { store.replaceReducer(reducer); }); } const history = createHistory(); // load new component when the route changes history.listen(location => store.dispatch(routeDidChange(location))); // load the component for the initial route store.dispatch(routeDidChange(history.location)); export default function App() { return ( <Provider store={store}> <Router history={history}> <Route path="*" component={Layout} /> </Router> </Provider> ) }
admin/client/App/screens/List/components/Filtering/ListFilters.js
everisARQ/keystone
import React from 'react'; import filterComponents from '../../../../../fields/filters'; import Popout from '../../../../shared/Popout'; import { Pill } from 'elemental'; import { setFilter, clearFilter, clearAllFilters } from '../../actions'; const Filter = React.createClass({ propTypes: { filter: React.PropTypes.object.isRequired, }, getInitialState () { return { isOpen: false, }; }, open () { this.setState({ isOpen: true, filterValue: this.props.filter.value, }); }, close () { this.setState({ isOpen: false, }); }, updateValue (filterValue) { this.setState({ filterValue: filterValue, }); }, updateFilter (e) { this.props.dispatch(setFilter(this.props.filter.field.path, this.state.filterValue)); this.close(); e.preventDefault(); }, removeFilter () { this.props.dispatch(clearFilter(this.props.filter.field.path)); }, render () { const { filter } = this.props; const filterId = `activeFilter__${filter.field.path}`; const FilterComponent = filterComponents[filter.field.type]; return ( <span> <Pill label={filter.field.label} onClick={this.open} onClear={this.removeFilter} type="primary" id={filterId} showClearButton /> <Popout isOpen={this.state.isOpen} onCancel={this.close} relativeToID={filterId}> <form onSubmit={this.updateFilter}> <Popout.Header title="Edit Filter" /> <Popout.Body> <FilterComponent field={filter.field} filter={this.state.filterValue} onChange={this.updateValue} /> </Popout.Body> <Popout.Footer ref="footer" primaryButtonIsSubmit primaryButtonLabel="Apply" secondaryButtonAction={this.close} secondaryButtonLabel="Cancel" /> </form> </Popout> </span> ); }, }); const ListFilters = React.createClass({ clearAllFilters () { this.props.dispatch(clearAllFilters()); }, render () { if (!this.props.filters.length) return <div />; const currentFilters = this.props.filters.map((filter, i) => { return ( <Filter key={'f' + i} filter={filter} dispatch={this.props.dispatch} /> ); }); // append the clear button if (currentFilters.length > 1) { currentFilters.push( <Pill key="listFilters__clear" label="Clear All" onClick={this.clearAllFilters} /> ); } return ( <div className="ListFilters mb-2"> {currentFilters} </div> ); }, }); module.exports = ListFilters;
app/javascript/mastodon/features/list_adder/index.js
primenumber/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { injectIntl } from 'react-intl'; import { setupListAdder, resetListAdder } from '../../actions/lists'; import { createSelector } from 'reselect'; import List from './components/list'; import Account from './components/account'; import NewListForm from '../lists/components/new_list_form'; // hack const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ listIds: getOrderedLists(state).map(list=>list.get('id')), }); const mapDispatchToProps = dispatch => ({ onInitialize: accountId => dispatch(setupListAdder(accountId)), onReset: () => dispatch(resetListAdder()), }); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class ListAdder extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onInitialize: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired, listIds: ImmutablePropTypes.list.isRequired, }; componentDidMount () { const { onInitialize, accountId } = this.props; onInitialize(accountId); } componentWillUnmount () { const { onReset } = this.props; onReset(); } render () { const { accountId, listIds } = this.props; return ( <div className='modal-root__modal list-adder'> <div className='list-adder__account'> <Account accountId={accountId} /> </div> <NewListForm /> <div className='list-adder__lists'> {listIds.map(ListId => <List key={ListId} listId={ListId} />)} </div> </div> ); } }
client/index.js
kieusonlam/feathers-react-mobx-starter
import React from 'react' import { render } from 'react-dom' import { Provider } from 'mobx-react' import { Router, RouterContext, browserHistory } from 'react-router' import { createClientState } from './state' import createRoutes from './routes' import autorun from './autorun.js' // Get actions object import actions from './actions' // Import our styles require('./assets/css/index.scss') // Initialize stores const state = createClientState() // Setup autorun ( for document title change ) autorun(state) // Wrap RouterContext with Provider for state transfer function createElement(props) { return <Provider state={state} actions={actions} > <RouterContext {...props} /> </Provider> } var ignoreFirstLoad = true function onRouterUpdate() { if (ignoreFirstLoad){ ignoreFirstLoad=false return } // Page changed, executing fetchData let params = this.state.params let query = this.state.location.query this.state.components.filter(c => c.fetchData).forEach(c => { c.fetchData({ state, params, actions, query }) }) } // Render HTML on the browser function renderRouter() { render(<Router history={browserHistory} render={createElement} onUpdate={onRouterUpdate} routes={createRoutes()}/>, document.getElementById('root')) } renderRouter()
src/components/MultiSelect/FilterableMultiSelect.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import Downshift from 'downshift'; import isEqual from 'lodash.isequal'; import { settings } from 'carbon-components'; import WarningFilled16 from '@carbon/icons-react/lib/warning--filled/16'; import ListBox from '../ListBox'; import Checkbox from '../Checkbox'; import Selection from '../../internal/Selection'; import { sortingPropTypes } from './MultiSelectPropTypes'; import { defaultItemToString } from './tools/itemToString'; import { defaultSortItems, defaultCompareItems } from './tools/sorting'; import { defaultFilterItems } from '../ComboBox/tools/filter'; const { prefix } = settings; export default class FilterableMultiSelect extends React.Component { static propTypes = { ...sortingPropTypes, /** * 'aria-label' of the ListBox component. */ ariaLabel: PropTypes.string, /** * Disable the control */ disabled: PropTypes.bool, /** * Specify a custom `id` */ id: PropTypes.string.isRequired, /** * We try to stay as generic as possible here to allow individuals to pass * in a collection of whatever kind of data structure they prefer */ items: PropTypes.array.isRequired, /** * Allow users to pass in arbitrary items from their collection that are * pre-selected */ initialSelectedItems: PropTypes.array, /** * Helper function passed to downshift that allows the library to render a * given item to a string label. By default, it extracts the `label` field * from a given item to serve as the item label in the list. */ itemToString: PropTypes.func, /** * Specify the locale of the control. Used for the default `compareItems` * used for sorting the list of items in the control. */ locale: PropTypes.string, /** * `onChange` is a utility for this controlled component to communicate to a * consuming component what kind of internal state changes are occuring. */ onChange: PropTypes.func, /** * Generic `placeholder` that will be used as the textual representation of * what this field is for */ placeholder: PropTypes.string.isRequired, /** * Specify title to show title on hover */ useTitleInItem: PropTypes.bool, /** * `true` to use the light version. */ light: PropTypes.bool, /** * Is the current selection invalid? */ invalid: PropTypes.bool, /** * If invalid, what is the error? */ invalidText: PropTypes.string, /** * Initialize the component with an open(`true`)/closed(`false`) menu. */ open: PropTypes.bool, /** * Specify feedback (mode) of the selection. * `top`: selected item jumps to top * `fixed`: selected item stays at it's position * `top-after-reopen`: selected item jump to top after reopen dropdown */ selectionFeedback: PropTypes.oneOf(['top', 'fixed', 'top-after-reopen']), /** * Callback function for translating ListBoxMenuIcon SVG title */ translateWithId: PropTypes.func, }; static getDerivedStateFromProps({ open }, state) { /** * programmatically control this `open` prop */ const { prevOpen } = state; return prevOpen === open ? null : { isOpen: open, prevOpen: open, }; } static defaultProps = { ariaLabel: 'Choose an item', compareItems: defaultCompareItems, disabled: false, filterItems: defaultFilterItems, initialSelectedItems: [], itemToString: defaultItemToString, locale: 'en', sortItems: defaultSortItems, light: false, open: false, selectionFeedback: 'top-after-reopen', }; constructor(props) { super(props); this.state = { highlightedIndex: null, isOpen: props.open, inputValue: '', topItems: [], }; } handleOnChange = changes => { if (this.props.onChange) { this.props.onChange(changes); } }; handleOnToggleMenu = () => { this.setState(state => ({ isOpen: !state.isOpen, })); }; handleOnOuterClick = () => { this.setState({ isOpen: false, inputValue: '', }); }; handleOnStateChange = (changes, downshift) => { if (changes.isOpen && !this.state.isOpen) { this.setState({ topItems: downshift.selectedItem }); } const { type } = changes; switch (type) { case Downshift.stateChangeTypes.keyDownArrowUp: case Downshift.stateChangeTypes.itemMouseEnter: this.setState({ highlightedIndex: changes.highlightedIndex }); break; case Downshift.stateChangeTypes.keyDownArrowDown: this.setState({ highlightedIndex: changes.highlightedIndex, isOpen: true, }); break; case Downshift.stateChangeTypes.keyDownEscape: case Downshift.stateChangeTypes.mouseUp: this.setState({ isOpen: false }); break; // Opt-in to some cases where we should be toggling the menu based on // a given key press or mouse handler // Reference: https://github.com/paypal/downshift/issues/206 case Downshift.stateChangeTypes.clickButton: case Downshift.stateChangeTypes.keyDownSpaceButton: this.setState(() => { let nextIsOpen = changes.isOpen || false; if (changes.isOpen === false) { // If Downshift is trying to close the menu, but we know the input // is the active element in thedocument, then keep the menu open if (this.inputNode === document.activeElement) { nextIsOpen = true; } } return { isOpen: nextIsOpen, }; }); break; } }; handleOnInputKeyDown = event => { event.stopPropagation(); }; handleOnInputValueChange = (inputValue, { type }) => { if (type === Downshift.stateChangeTypes.changeInput) this.setState(() => { if (Array.isArray(inputValue)) { return { inputValue: '', }; } return { inputValue: inputValue || '', }; }); }; clearInputValue = event => { event.stopPropagation(); this.setState({ inputValue: '' }); this.inputNode && this.inputNode.focus && this.inputNode.focus(); }; render() { const { highlightedIndex, isOpen, inputValue } = this.state; const { ariaLabel, className: containerClassName, disabled, filterItems, items, itemToString, titleText, helperText, type, initialSelectedItems, id, locale, placeholder, sortItems, compareItems, light, invalid, invalidText, useTitleInItem, translateWithId, } = this.props; const inline = type === 'inline'; const wrapperClasses = cx( `${prefix}--multi-select__wrapper`, `${prefix}--list-box__wrapper`, { [`${prefix}--multi-select__wrapper--inline`]: inline, [`${prefix}--list-box__wrapper--inline`]: inline, [`${prefix}--multi-select__wrapper--inline--invalid`]: inline && invalid, [`${prefix}--list-box__wrapper--inline--invalid`]: inline && invalid, } ); const titleClasses = cx(`${prefix}--label`, { [`${prefix}--label--disabled`]: disabled, }); const title = titleText ? ( <label htmlFor={id} className={titleClasses}> {titleText} </label> ) : null; const helperClasses = cx(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: disabled, }); const helper = helperText ? ( <div className={helperClasses}>{helperText}</div> ) : null; const input = ( <Selection onChange={this.handleOnChange} initialSelectedItems={initialSelectedItems} render={({ selectedItems, onItemChange, clearSelection }) => ( <Downshift highlightedIndex={highlightedIndex} isOpen={isOpen} inputValue={inputValue} onInputValueChange={this.handleOnInputValueChange} onChange={onItemChange} itemToString={itemToString} onStateChange={this.handleOnStateChange} onOuterClick={this.handleOnOuterClick} selectedItem={selectedItems} render={({ getButtonProps, getInputProps, getItemProps, getRootProps, isOpen, inputValue, selectedItem, }) => { const className = cx( `${prefix}--multi-select`, `${prefix}--combo-box`, `${prefix}--multi-select--filterable`, containerClassName, { [`${prefix}--multi-select--invalid`]: invalid, [`${prefix}--multi-select--open`]: isOpen, [`${prefix}--multi-select--inline`]: inline, [`${prefix}--multi-select--selected`]: selectedItem.length > 0, } ); return ( <ListBox className={className} disabled={disabled} light={light} invalid={invalid} invalidText={invalidText} isOpen={isOpen} {...getRootProps({ refKey: 'innerRef' })}> {invalid && ( <WarningFilled16 className={`${prefix}--list-box__invalid-icon`} /> )} <ListBox.Field id={id} {...getButtonProps({ disabled })}> {selectedItem.length > 0 && ( <ListBox.Selection clearSelection={clearSelection} selectionCount={selectedItem.length} translateWithId={translateWithId} /> )} <input className={`${prefix}--text-input`} aria-controls={`${id}__menu`} aria-autocomplete="list" ref={el => (this.inputNode = el)} {...getInputProps({ disabled, id, placeholder, onKeyDown: this.handleOnInputKeyDown, })} /> {inputValue && isOpen && ( <ListBox.Selection clearSelection={this.clearInputValue} /> )} <ListBox.MenuIcon isOpen={isOpen} translateWithId={translateWithId} /> </ListBox.Field> {isOpen && ( <ListBox.Menu aria-label={ariaLabel} id={id}> {sortItems( filterItems(items, { itemToString, inputValue }), { selectedItems: { top: selectedItems, fixed: [], 'top-after-reopen': this.state.topItems, }[this.props.selectionFeedback], itemToString, compareItems, locale, } ).map((item, index) => { const itemProps = getItemProps({ item }); const itemText = itemToString(item); const isChecked = selectedItem.filter(selected => isEqual(selected, item) ).length > 0; return ( <ListBox.MenuItem key={itemProps.id} isActive={isChecked} isHighlighted={highlightedIndex === index} {...itemProps}> <Checkbox id={itemProps.id} title={useTitleInItem ? itemText : null} name={itemText} checked={isChecked} readOnly={true} tabIndex="-1" labelText={itemText} /> </ListBox.MenuItem> ); })} </ListBox.Menu> )} </ListBox> ); }} /> )} /> ); return ( <div className={wrapperClasses}> {title} {!inline && helper} {input} </div> ); } }
src/profile/details/EditPassword.js
VasilyShelkov/ClientRelationshipManagerUI
import React from 'react'; import { Field, reduxForm, SubmissionError } from 'redux-form'; import { loader } from 'graphql.macro'; import { graphql } from 'react-apollo'; import { renderTextField, required, minLength, } from '../../shared/FormElements'; import StandardForm from '../../shared/StandardForm'; const EditUserPassword = loader('./EditUserPassword.gql'); const EditPassword = ({ handleSubmit, handleCancelEditProfilePassword, error, editInProgress, }) => ( <StandardForm handleSubmit={handleSubmit} handleCancel={handleCancelEditProfilePassword} error={error} editingInProgress={editInProgress} fields={[ <Field key="profile__password" name="password" type="password" component={renderTextField} label="New Password" validate={[required, minLength]} fullWidth />, <Field key="profile__confirmPassword" name="confirmPassword" type="password" component={renderTextField} label="Confirm New Password" validate={[required, minLength]} fullWidth />, ]} /> ); export const EditPasswordForm = reduxForm({ form: 'profilePassword' })( EditPassword, ); export default graphql(EditUserPassword, { props: ({ ownProps, mutate }) => ({ onSubmit: async values => { if (values.password === values.confirmPassword) { try { await mutate({ variables: { id: ownProps.userId, password: values.password }, }); } catch (error) { throw new SubmissionError({ _error: error.graphQLErrors[0].message }); } } else { throw new SubmissionError({ _error: 'Passwords do not match', }); } }, ...ownProps, }), })(EditPasswordForm);
src/browser/me/ProfilePage.js
chad099/react-native-boilerplate
// @flow import React from 'react'; import linksMessages from '../../common/app/linksMessages'; import { Box, Paragraph } from '../../common/components'; import { FormattedMessage } from 'react-intl'; import { Title } from '../components'; const ProfilePage = () => ( <Box> <Title message={linksMessages.profile} /> <FormattedMessage {...linksMessages.profile}> {message => <Paragraph>{message}</Paragraph>} </FormattedMessage> </Box> ); export default ProfilePage;
imports/ui/pages/Miscellaneous/Signup/Signup.js
haraneesh/mydev
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { Panel, Row, Col, FormGroup, ControlLabel, Button, } from 'react-bootstrap'; import PropTypes from 'prop-types'; import { toast } from 'react-toastify'; import { acceptInvitation } from '../../../../api/Invitations/methods'; // import OAuthLoginButtons from '../../../components/OAuthLoginButtons/OAuthLoginButtons'; import InputHint from '../../../components/InputHint/InputHint'; import { formValChange, formValid } from '../../../../modules/validate'; import AccountPageFooter from '../../../components/AccountPageFooter/AccountPageFooter'; const defaultState = { signUpRequestSent: false, isError: { emailAddress: '', password: '', firstName: '', lastName: '', whMobilePhone: '', deliveryAddress: '', confirmPassword: '', eatingHealthyMeaning: '', }, }; class SignUp extends React.Component { constructor(props) { super(props); this.onValueChange = this.onValueChange.bind(this); this.validateForm = this.validateForm.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { ...defaultState }; } onValueChange(e) { e.preventDefault(); const { isError } = this.state; const newState = formValChange(e, { ...isError }, { password: document.querySelector('[name="password"]').value, confirmPassword: document.querySelector('[name="confirmPassword"]').value, }); this.setState(newState); } validateForm(e) { e.preventDefault(); const { isError } = this.state; if (formValid({ isError })) { this.handleSubmit(); } else { this.setState({ isError }); } } handleSubmit() { const { history } = this.props; const { match } = this.props; const user = { username: this.whMobilePhone.value, email: this.emailAddress.value, password: document.querySelector('[name="password"]').value, profile: { name: { first: this.firstName.value, last: this.lastName.value, }, whMobilePhone: this.whMobilePhone.value, deliveryAddress: this.deliveryAddress.value, eatingHealthyMeaning: this.eatingHealthyMeaning.value, }, }; if (match.params.token) { acceptInvitation.call({ user, token: match.params.token }, (error) => { if (error) { toast.error(error.reason); } else { toast.success(`Welcome ${this.firstName.value} ${this.lastName.value}!`); history.push('/'); } }); } else { Meteor.call('users.signUp', user, (error) => { if (error) { toast.error(error.reason); } else { toast.success(`Welcome ${this.firstName.value} ${this.lastName.value}!`); this.setState({ signUpRequestSent: true, }); } }); } } render() { const { signUpRequestSent } = this.state; const { isError } = this.state; return (!signUpRequestSent ? ( <div className="Signup offset-sm-1"> <div> <Col xs={12} sm={10}> <h3 className="page-header">Sign Up</h3> <div className="panel text-center"> <div className="panel-body"> <h3 className="text-primary"> Welcome to Suvai </h3> <br /> <p> Suvai is a community of like minded families who have been together for more than {' '} <b className="text-info h4">5 years</b> . </p> <p> We are committed to eating healthy and leaving behind a small ecological footprint. </p> <p> We are happy to Welcome you, Please introduce yourself. </p> </div> </div> { /* <Row> <Col xs={12}> <OAuthLoginButtons services={['facebook']} emailMessage={{ offset: 0, text: '- OR -', }} /> </Col> </Row> */ } <form ref={(form) => (this.form = form)} onSubmit={this.validateForm}> <Row> <Col xs={6}> <FormGroup validationState={isError.firstName.length > 0 ? 'error' : ''} style={{ paddingRight: '1px' }} > <ControlLabel>First Name</ControlLabel> <input type="text" name="firstName" ref={(firstName) => (this.firstName = firstName)} onBlur={this.onValueChange} className="form-control" /> </FormGroup> </Col> <Col xs={6}> <FormGroup validationState={isError.lastName.length > 0 ? 'error' : ''} style={{ paddingLeft: '1px' }} > <ControlLabel>Last Name</ControlLabel> <input type="text" name="lastName" ref={(lastName) => (this.lastName = lastName)} onBlur={this.onValueChange} className="form-control" /> </FormGroup> </Col> </Row> <FormGroup validationState={isError.emailAddress.length > 0 ? 'error' : ''}> <ControlLabel>Email Address</ControlLabel> <input type="email" name="emailAddress" ref={(emailAddress) => (this.emailAddress = emailAddress)} onBlur={this.onValueChange} className="form-control" /> </FormGroup> <FormGroup validationState={isError.whMobilePhone.length > 0 ? 'error' : ''}> <ControlLabel>Mobile Number</ControlLabel> <input type="text" ref={(whMobilePhone) => (this.whMobilePhone = whMobilePhone)} name="whMobilePhone" placeholder="10 digit number example, 8787989897" className="form-control" onBlur={this.onValueChange} /> </FormGroup> <FormGroup validationState={isError.deliveryAddress.length > 0 ? 'error' : ''}> <ControlLabel>Delivery Address</ControlLabel> <textarea ref={(deliveryAddress) => (this.deliveryAddress = deliveryAddress)} name="deliveryAddress" placeholder="Complete address to deliver at, including Landmark, Pincode." rows="6" className="form-control" onBlur={this.onValueChange} /> </FormGroup> <FormGroup validationState={isError.eatingHealthyMeaning.length > 0 ? 'error' : ''}> <ControlLabel>What does eating healthy mean to you?</ControlLabel> <textarea ref={(eatingHealthyMeaning) => (this.eatingHealthyMeaning = eatingHealthyMeaning)} name="eatingHealthyMeaning" placeholder="You are never wrong, tell us what is in your mind." rows="6" className="form-control" onBlur={this.onValueChange} /> </FormGroup> <FormGroup validationState={isError.password.length > 0 ? 'error' : ''}> <ControlLabel>Password</ControlLabel> <input id="password" type="password" name="password" // ref={(password) => (this.password = password)} className="form-control" onBlur={this.onValueChange} /> <InputHint>Use at least six characters.</InputHint> {isError.password.length > 0 && ( <span className="control-label">{isError.password}</span> )} </FormGroup> <FormGroup validationState={isError.confirmPassword.length > 0 ? 'error' : ''}> <ControlLabel>Confirm Password</ControlLabel> <input type="password" name="confirmPassword" ref={(confirmPassword) => (this.confirmPassword = confirmPassword)} className="form-control" onBlur={this.onValueChange} /> {isError.confirmPassword.length > 0 && ( <span className="control-label">{isError.confirmPassword}</span> )} </FormGroup> <p> <small> By Signing up you are sharing your commitment towards healthy and sustainable lifestyle. </small> </p> <Button type="submit" bsStyle="primary">Sign Up</Button> <AccountPageFooter> <div className="panel text-center" style={{ marginBottom: '0px', padding: '6px' }}> <span> {'Already have an account? '} <a href="/login" className="login-signup">Log In</a> </span> </div> </AccountPageFooter> </form> </Col> </div> </div> ) : ( <Panel style={{ marginTop: '1.5em' }}> <Row className="text-center"> <Col xs={12}> <h3>Thanks for your interest in Suvai!</h3> <br /> <p> Please give us a few days for our admins to review the request and send an invite to join our community. </p> </Col> <Col xs={12} style={{ marginTop: '2rem' }}> <p> While you are waiting, here is our manifesto on Healthy Living. </p> <h4> <a className="text-primary" href="/healthprinciples"> Suvai's Health Principles</a> </h4> </Col> </Row> </Panel> ) ); } } SignUp.propTypes = { history: PropTypes.object.isRequired, match: PropTypes.object.isRequired, }; export default SignUp;
docs/src/components/usage-example.js
kwangkim/nuclear-js
import React from 'react' import { Reactor, Store, toImmutable } from 'nuclear-js' import Code from './code' const storeCode = `import { Reactor, Store, toImmutable } from 'nuclear-js' import React from 'react' const reactor = new Reactor({ debug: true }); reactor.registerStores({ typeFilter: Store({ getInitialState() { return null; }, initialize() { this.on('FILTER_TYPE', (state, type) => type) } }), items: Store({ getInitialState() { return toImmutable([ { type: 'food', name: 'banana', price: 1 }, { type: 'food', name: 'doritos', price: 4 }, { type: 'clothes', name: 'shirt', price: 15 }, { type: 'clothes', name: 'pants', price: 20 }, ]) }, initialize() { this.on('ADD_ITEM', (state, item) => state.push(item)) } }) })` const getterCode = `const filteredItemsGetter = [ ['typeFilter'], ['items'], (filter, items) => { return (filter) ? items.filter(i => i.get('type') === filter) : items } ]` const componentCode = `const ItemViewer = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return { items: filteredItemsGetter } }, render() { return ( <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Price</th> </tr> </thead> <tbody> {this.state.items.map(item => { return <tr> <td>{item.get('name')}</td> <td>{item.get('type')}</td> <td>{item.get('price')}</td> </tr> })} </tbody> </table> ) } })` const dispatchCode = `const actions = { setFilter(type) { reactor.dispatch('FILTER_TYPE' type) }, addItem(name, type, price) { reactor.dispatch('ADD_ITEM', toImmutable({ name, type, price })) } } actions.addItem('computer', 'electronics', 1999) actions.setFilter('electronics')` const evaluateCode = `// Evaluate by key path var itemsList = reactor.evaluate(['items']) var item0Price = reactor.evaluate(['items', 0, 'price']) // Evaluate by getter var filteredItems = reactor.evaluate(filteredItemsGetter) // Evaluate and coerce to plain JavaScript var itemsPOJO = reactor.evaluateToJS(filteredItemsGetter) // Observation reactor.observe(filteredItemsGetter, items => { console.log(items) }) ` export default React.createClass({ render() { return ( <div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript">{storeCode}</Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Create a <code>Reactor</code> </h3> <p className="tour-section--bullet-item"> In NuclearJS the <code>reactor</code> acts as the dispatcher, maintains the application state and provides an API for data access and observation. </p> <h3 className="tour-section--bullet-title"> Register stores </h3> <p className="tour-section--bullet-item"> Stores determine the shape of your application state. Stores define two methods: </p> <p> <code>getInitialState()</code> - Returns the initial state for that stores specific key in the application state. </p> <p> <code>initialize()</code> - Sets up any action handlers, by specifying the action type and a function that transforms <pre><code>(storeState, action) => (newStoreState)</code></pre> </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {getterCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Accessing your data </h3> <p> Getters allow you to easily compose and transform your application state in a reusable way. </p> <h3 className="tour-section--bullet-title"> </h3> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {componentCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Automatic component data binding </h3> <p> Simply use the <code>reactor.ReactMixin</code> and implement the <code>getDataBindings()</code> function to automatically sync any getter to a <code>this.state</code> property on a React component. </p> <p> Since application state can only change after a dispatch then NuclearJS can be intelligent and only call <code>this.setState</code> whenever the actual value of the getter changes. Meaning less pressure on React's DOM diffing. </p> <h3 className="tour-section--bullet-title"> Framework agnostic </h3> <p> This example shows how to use NuclearJS with React, however the same concepts can be extended to any reactive UI framework. In fact, the ReactMixin code is only about 40 lines. </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {dispatchCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Dispatching actions </h3> <p> NuclearJS maintains a very non-magical approach to dispatching actions. Simply call <code>reactor.dispatch</code> with the <code>actionType</code> and <code>payload</code>. </p> <p> All action handling is done synchronously, leaving the state of the system very predictable after every action. </p> <p> Because actions are simply functions, it is very easy to compose actions together using plain JavaScript. </p> </div> </div> <div className="row code-explanation--row"> <div className="col s12 m12 l7"> <Code lang="javascript"> {evaluateCode} </Code> </div> <div className="col s12 m12 l5 code-explanation"> <h3 className="tour-section--bullet-title"> Reading application state </h3> <p> NuclearJS also provides imperative mechanisms for evaluating and observing state. </p> <p> In fact any getter can synchronously and imperatively evaluated or observed. The entire <code>ReactMixin</code> is built using only those two functions. </p> </div> </div> </div> ) } })
client/admin/users/Skeleton.js
Sing-Li/Rocket.Chat
import React from 'react'; import { Box, Skeleton } from '@rocket.chat/fuselage'; export const FormSkeleton = (props) => <Box w='full' pb='x24' {...props}> <Skeleton mbe='x8' /> <Skeleton mbe='x4'/> <Skeleton mbe='x4'/> <Skeleton mbe='x8'/> <Skeleton mbe='x4'/> <Skeleton mbe='x8'/> </Box>;
projects/yanset/src/App.js
taoxiang1995/taoxiang1995.github.io
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Header from './components/header'; import Config from './config'; import Tab from './components/tab'; import TabsContainer from './containers/TabsContainer'; class App extends Component { render() { return ( <div> <Header header = {Config.header} body = {Config.body} /> <TabsContainer store={this.props.store} /> </div> ); } } export default App;
packages/material-ui-icons/src/AlarmAdd.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let AlarmAdd = props => <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z" /> </SvgIcon>; AlarmAdd = pure(AlarmAdd); AlarmAdd.muiName = 'SvgIcon'; export default AlarmAdd;
imports/ui/layouts/App.js
KyneSilverhide/team-manager
import React from 'react'; import { Grid } from 'react-bootstrap'; import AppNavigation from '../containers/AppNavigation.js'; const App = ({ children }) => ( <div> <AppNavigation /> <Grid> { children } </Grid> </div> ); App.propTypes = { children: React.PropTypes.node, }; export default App;
src/svg-icons/editor/functions.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFunctions = (props) => ( <SvgIcon {...props}> <path d="M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"/> </SvgIcon> ); EditorFunctions = pure(EditorFunctions); EditorFunctions.displayName = 'EditorFunctions'; EditorFunctions.muiName = 'SvgIcon'; export default EditorFunctions;
src/svg-icons/image/landscape.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLandscape = (props) => ( <SvgIcon {...props}> <path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/> </SvgIcon> ); ImageLandscape = pure(ImageLandscape); ImageLandscape.displayName = 'ImageLandscape'; ImageLandscape.muiName = 'SvgIcon'; export default ImageLandscape;
app/scripts/main.js
dburdick/react-material-starterkit
import React from 'react'; import Router from 'react-router'; import routes from './routes'; //Needed for onTouchTap //Can go away when react 1.0 release //Check this repo: //https://github.com/zilverline/react-tap-event-plugin var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin(); Router.run(routes, Handler => React.render(<Handler />, document.body));
src/components/Sidebar/InterestingPeople.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import User from './User'; import './InterestingPeople.less'; const InterestingPeople = ({ users, onRefresh }) => ( <div className="InterestingPeople"> <div className="InterestingPeople__container"> <h4 className="InterestingPeople__title"> <i className="iconfont icon-group InterestingPeople__icon" /> {' '} <FormattedMessage id="interesting_people" defaultMessage="Interesting People" /> <i role="presentation" onClick={onRefresh} className="iconfont icon-refresh InterestingPeople__icon-refresh" /> </h4> <div className="InterestingPeople__divider" /> {users && users.map(user => <User key={user.name} user={user} />)} <h4 className="InterestingPeople__more"> <Link to={'/latest-comments'}> <FormattedMessage id="discover_more_people" defaultMessage="Discover More People" /> </Link> </h4> </div> </div> ); InterestingPeople.propTypes = { users: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string })), onRefresh: PropTypes.func, }; InterestingPeople.defaultProps = { users: [], onRefresh: () => {}, }; export default InterestingPeople;
src/components/MenuItemFactory.js
dkozar/react-data-menu
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; var classnames = require('classnames'); export default class MenuItemFactory { constructor(renderers, classPrefix) { this.renderers = renderers; this.classPrefix = classPrefix; } createItem(data, key, classes, config) { var isExpandable = !!data.items, renderer = this.renderers[data.type], additions = {}, classPrefix = this.classPrefix, className; additions[this.classPrefix + 'menu-item'] = true; additions[this.classPrefix + 'menu-item-expandable'] = isExpandable; className = classnames(classes, additions); if (!renderer) { throw 'Undefined renderer for type [' + data.type + ']'; } return React.createElement(renderer, { data, key, isExpandable, className, classPrefix, config }); } }
src/index.js
isairz/Chess
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('root'));
5.3.0/src/routes.js
erikras/redux-form-docs
import React from 'react' import { Router, Route, hashHistory } from 'react-router' import markdownPage from 'components/markdownPage' import App from 'pages/App' import Home from 'pages/Home' import Simple from 'pages/examples/Simple' import ComplexValues from 'pages/examples/ComplexValues' import File from 'pages/examples/File' import Wizard from 'pages/examples/Wizard' import Deep from 'pages/examples/Deep' import SynchronousValidation from 'pages/examples/SynchronousValidation' import SubmitFromParent from 'pages/examples/SubmitFromParent' import SubmitValidation from 'pages/examples/SubmitValidation' import AsynchronousBlurValidation from 'pages/examples/AsynchronousBlurValidation' import AlternateMountPoint from 'pages/examples/AlternateMountPoint' import Multirecord from 'pages/examples/Multirecord' import Normalizing from 'pages/examples/Normalizing' import Dynamic from 'pages/examples/Dynamic' import InitializingFromState from 'pages/examples/InitializingFromState' import Examples from 'pages/examples/Examples.md' import Faq from 'pages/faq/Faq.md' import FaqEnterToSubmit from 'pages/faq/EnterToSubmit.md' import FaqSubmitFunction from 'pages/faq/SubmitFunction.md' import FaqHandleVsOn from 'pages/faq/HandleVsOn.md' import FaqHowToClear from 'pages/faq/HowToClear.md' import FaqReactNative from 'pages/faq/ReactNative.md' import FaqImmutableJs from 'pages/faq/ImmutableJs.md' import FaqCustomComponent from 'pages/faq/CustomComponent.md' import FaqWebsockets from 'pages/faq/WebsocketSubmit.md' import GettingStarted from 'pages/GettingStarted.md' import Api from 'pages/api/Api.md' import ApiReduxForm from 'pages/api/ReduxForm.md' import ApiReducer from 'pages/api/Reducer.md' import ApiReducerNormalize from 'pages/api/ReducerNormalize.md' import ApiReducerPlugin from 'pages/api/ReducerPlugin.md' import ApiProps from 'pages/api/Props.md' import ApiActionCreators from 'pages/api/ActionCreators.md' import ApiGetValues from 'pages/api/GetValues.md' const routes = ( <Router history={hashHistory}> <Route component={App}> <Route path="/" component={Home}/> <Route path="/api" component={markdownPage(Api)}/> <Route path="/api/action-creators" component={markdownPage(ApiActionCreators)}/> <Route path="/api/get-values" component={markdownPage(ApiGetValues)}/> <Route path="/api/props" component={markdownPage(ApiProps)}/> <Route path="/api/reduxForm" component={markdownPage(ApiReduxForm)}/> <Route path="/api/reducer" component={markdownPage(ApiReducer)}/> <Route path="/api/reducer/normalize" component={markdownPage(ApiReducerNormalize)}/> <Route path="/api/reducer/plugin" component={markdownPage(ApiReducerPlugin)}/> <Route path="/getting-started" component={markdownPage(GettingStarted)}/> <Route path="/examples" component={markdownPage(Examples)}/> <Route path="/examples/asynchronous-blur-validation" component={AsynchronousBlurValidation}/> <Route path="/examples/alternate-mount-point" component={AlternateMountPoint}/> <Route path="/examples/deep" component={Deep}/> <Route path="/examples/initializing-from-state" component={InitializingFromState}/> <Route path="/examples/dynamic" component={Dynamic}/> <Route path="/examples/multirecord" component={Multirecord}/> <Route path="/examples/normalizing" component={Normalizing}/> <Route path="/examples/simple" component={Simple}/> <Route path="/examples/complex" component={ComplexValues}/> <Route path="/examples/file" component={File}/> <Route path="/examples/wizard" component={Wizard}/> <Route path="/examples/submit-validation" component={SubmitValidation}/> <Route path="/examples/synchronous-validation" component={SynchronousValidation}/> <Route path="/examples/submit-from-parent" component={SubmitFromParent}/> <Route path="/faq" component={markdownPage(Faq)}/> <Route path="/faq/submit-function" component={markdownPage(FaqSubmitFunction)}/> <Route path="/faq/handle-vs-on" component={markdownPage(FaqHandleVsOn)}/> <Route path="/faq/how-to-clear" component={markdownPage(FaqHowToClear)}/> <Route path="/faq/enter-to-submit" component={markdownPage(FaqEnterToSubmit)}/> <Route path="/faq/immutable-js" component={markdownPage(FaqImmutableJs)}/> <Route path="/faq/react-native" component={markdownPage(FaqReactNative)}/> <Route path="/faq/custom-component" component={markdownPage(FaqCustomComponent)}/> <Route path="/faq/websockets" component={markdownPage(FaqWebsockets)}/> <Route path="*" component={Home}/> </Route> </Router> ) export default routes
app/javascript/mastodon/features/direct_timeline/components/conversation.js
gol-cha/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContent from 'mastodon/components/status_content'; import AttachmentList from 'mastodon/components/attachment_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container'; import AvatarComposite from 'mastodon/components/avatar_composite'; import Permalink from 'mastodon/components/permalink'; import IconButton from 'mastodon/components/icon_button'; import RelativeTimestamp from 'mastodon/components/relative_timestamp'; import { HotKeys } from 'react-hotkeys'; import { autoPlayGif } from 'mastodon/initial_state'; import classNames from 'classnames'; const messages = defineMessages({ more: { id: 'status.more', defaultMessage: 'More' }, open: { id: 'conversation.open', defaultMessage: 'View conversation' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, markAsRead: { id: 'conversation.mark_as_read', defaultMessage: 'Mark as read' }, delete: { id: 'conversation.delete', defaultMessage: 'Delete conversation' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, }); export default @injectIntl class Conversation extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { conversationId: PropTypes.string.isRequired, accounts: ImmutablePropTypes.list.isRequired, lastStatus: ImmutablePropTypes.map, unread:PropTypes.bool.isRequired, scrollKey: PropTypes.string, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, markRead: PropTypes.func.isRequired, delete: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } handleClick = () => { if (!this.context.router) { return; } const { lastStatus, unread, markRead } = this.props; if (unread) { markRead(); } this.context.router.history.push(`/@${lastStatus.getIn(['account', 'acct'])}/${lastStatus.get('id')}`); } handleMarkAsRead = () => { this.props.markRead(); } handleReply = () => { this.props.reply(this.props.lastStatus, this.context.router.history); } handleDelete = () => { this.props.delete(); } handleHotkeyMoveUp = () => { this.props.onMoveUp(this.props.conversationId); } handleHotkeyMoveDown = () => { this.props.onMoveDown(this.props.conversationId); } handleConversationMute = () => { this.props.onMute(this.props.lastStatus); } handleShowMore = () => { this.props.onToggleHidden(this.props.lastStatus); } render () { const { accounts, lastStatus, unread, scrollKey, intl } = this.props; if (lastStatus === null) { return null; } const menu = [ { text: intl.formatMessage(messages.open), action: this.handleClick }, null, ]; menu.push({ text: intl.formatMessage(lastStatus.get('muted') ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMute }); if (unread) { menu.push({ text: intl.formatMessage(messages.markAsRead), action: this.handleMarkAsRead }); menu.push(null); } menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDelete }); const names = accounts.map(a => <Permalink to={`/@${a.get('acct')}`} href={a.get('url')} key={a.get('id')} title={a.get('acct')}><bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /></bdi></Permalink>).reduce((prev, cur) => [prev, ', ', cur]); const handlers = { reply: this.handleReply, open: this.handleClick, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleShowMore, }; return ( <HotKeys handlers={handlers}> <div className={classNames('conversation focusable muted', { 'conversation--unread': unread })} tabIndex='0'> <div className='conversation__avatar' onClick={this.handleClick} role='presentation'> <AvatarComposite accounts={accounts} size={48} /> </div> <div className='conversation__content'> <div className='conversation__content__info'> <div className='conversation__content__relative-time'> {unread && <span className='conversation__unread' />} <RelativeTimestamp timestamp={lastStatus.get('created_at')} /> </div> <div className='conversation__content__names' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <FormattedMessage id='conversation.with' defaultMessage='With {names}' values={{ names: <span>{names}</span> }} /> </div> </div> <StatusContent status={lastStatus} onClick={this.handleClick} expanded={!lastStatus.get('hidden')} onExpandedToggle={this.handleShowMore} collapsable /> {lastStatus.get('media_attachments').size > 0 && ( <AttachmentList compact media={lastStatus.get('media_attachments')} /> )} <div className='status__action-bar'> <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} /> <div className='status__action-bar-dropdown'> <DropdownMenuContainer scrollKey={scrollKey} status={lastStatus} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> </div> </div> </div> </div> </HotKeys> ); } }
dashboard/client/src/js/components/modules/ExperimentHeader.js
jigarjain/sieve
import React from 'react'; import {Link} from '../../utils/router'; // Returns the `Start/Pause` button component for Experiment function getExperimentStatusButton(experiment, errorType, onStatusToggle) { let btnTxt; let isDisabled = Boolean(errorType); if (experiment.isActive) { btnTxt = 'Pause'; isDisabled = false; } else { btnTxt = 'Start'; } return ( <button type="button" disabled={isDisabled} onClick={onStatusToggle} className="button is-warning" > {btnTxt} </button> ); } export default function (props) { return ( <div className="is-clearfix"> <h1 className="title is-3 is-pulled-left"> {props.experiment.name} &nbsp;&nbsp;<span className="tag is-primary">{props.experiment.isActive ? 'Running' : 'Paused'}</span> </h1> <div className="is-pulled-right"> <div className="control is-grouped"> <div className="control"> {getExperimentStatusButton(props.experiment, props.experimentErrorType, props.onExperimentStatusToggle)} </div> <div className="control"> <Link to={`/experiments/${props.experiment.id}/edit`} className="button is-info" > Edit </Link> </div> <div className="control"> <button type="button" onClick={props.onExperimentDelete} className="button is-danger" > Delete </button> </div> </div> </div> </div> ); }
local-cli/templates/HelloWorld/index.ios.js
DannyvanderJagt/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
packages/zensroom/lib/components/common/Home.js
SachaG/Zensroom
/* Home */ import React from 'react'; import { Components, registerComponent, withCurrentUser } from 'meteor/vulcan:core'; import { FormattedMessage } from 'meteor/vulcan:i18n'; import compose from 'recompose/compose'; // import RoomsList from '../rooms/RoomsList'; // import RoomsSearchForm from '../rooms/RoomsSearchForm'; const Home = ({currentUser}) => <div> {currentUser ? <Components.BookingsPending terms={{view: 'userPendingBookings', userId: currentUser._id}}/> : null} <Components.RoomsSearchForm/> <div className="home-section"> <h3 className="section-title"><FormattedMessage id="rooms.featured"/></h3> <Components.RoomsList terms={{limit: 3}}/> </div> <div className="home-section"> <h3 className="section-title"><FormattedMessage id="rooms.with_fireplace"/></h3> <Components.RoomsList terms={{limit: 3, filters: ['fireplace']}}/> </div> </div> registerComponent('Home', Home, withCurrentUser); // export default compose( // withCurrentUser, // )(Home);
src/pages/sorting/Pigeonhole/Pigeonhole.js
hyy1115/react-redux-webpack2
import React from 'react' class Pigeonhole extends React.Component { render() { return ( <div>Pigeonhole</div> ) } } export default Pigeonhole
examples/counter/containers/CounterApp.js
olegsxm/redux
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'redux/react'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; @connect(state => ({ counter: state.counter })) export default class CounterApp { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } }
docs/app/Examples/views/Card/Content/CardExampleContentBlock.js
shengnian/shengnian-ui-react
import React from 'react' import { Card, Feed } from 'shengnian-ui-react' const CardExampleContentBlock = () => ( <Card> <Card.Content> <Card.Header> Recent Activity </Card.Header> </Card.Content> <Card.Content> <Feed> <Feed.Event> <Feed.Label image='/assets/images/avatar/small/jenny.jpg' /> <Feed.Content> <Feed.Date content='1 day ago' /> <Feed.Summary> You added <a>Jenny Hess</a> to your <a>coworker</a> group. </Feed.Summary> </Feed.Content> </Feed.Event> <Feed.Event> <Feed.Label image='/assets/images/avatar/small/molly.png' /> <Feed.Content> <Feed.Date content='3 days ago' /> <Feed.Summary> You added <a>Molly Malone</a> as a friend. </Feed.Summary> </Feed.Content> </Feed.Event> <Feed.Event> <Feed.Label image='/assets/images/avatar/small/elliot.jpg' /> <Feed.Content> <Feed.Date content='4 days ago' /> <Feed.Summary> You added <a>Elliot Baker</a> to your <a>musicians</a> group. </Feed.Summary> </Feed.Content> </Feed.Event> </Feed> </Card.Content> </Card> ) export default CardExampleContentBlock
src/containers/grid_old.js
bryankle/dungeoncrawler
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { storeDamage } from '../actions/store-damage'; //import Hero from '../img/Hero'; import Dungeon from './generateDungeon'; import Hero from '../components/hero'; import Rat from '../components/rat'; import Grass from '../../img/grass.jpg'; import whiteKnight from '../../img/knight-front.png'; import Rock from '../../img/rock.jpg'; //import critter from '../../img/pikachu.png'; // IDEAS // Create a random map generated with rocks and grass with collision data stored in objects // When spawning character in dungeon, save the center points for each generated room and randomly select from array as initial character spawn point const renderGrass = <img src={Grass} /> class Grid extends Component { constructor(props) { super(props) this.state = { charPosition: [7, 7], // Switch over to charPosition later mapPosition: [0, 0], entireGrid: [], // Can be as large as neccessary visibleGrid: [], // Only 15 x 15 is visible in camera view mapSize: 150, // Adjust all references to mapSize to height & width later and delete height: 150, width: 150, cameraSize: 15, heroDirection: '', critterCount: 0, critters: {}, target: '', objectInformation: { whiteKnight: { solid: true }, _: { // Set to grass temporarily solid: false }, GRASS: { solid: false }, R: { // Rock // Switched to false for testing solid: true }, RAT: { solid: false } } } } componentWillMount() { // Listen to arrow keys for character movement document.addEventListener('keydown', this._handleKeydown.bind(this)) this.setState({ // Removed this._helperTranspose; add in later if needed entireGrid: this.buildMap() //this._createGrid('_', this.state.mapSize, this.state.mapSize) }) //this.createCritter(this.state.entireGrid, 'rat', 10, 10); // Set critter movement here } componentDidMount() { console.log('componentDidMount'); const that = this; //setInterval(this.eachCritter(that.state.critters, that.moveCritter), 1000) // Uncomment below // CONTINUE HERE // Uncomment this and begin transferring behavior into grid render setInterval(() => { this.heroTargetCritter(); // Intermittent scans area surrounding critter to target }, 1000) setInterval(() => { // Scan for critter as long as hero has no current target this.eachCritter(this.state.critters, this.moveCritter) }, 500) } _handleKeydown(e) { if (e.keyCode == 37) { console.log('Going left...') this._moveCharPosition('left'); } else if (e.keyCode == 38) { console.log('Going up...'); this._moveCharPosition('up'); } else if (e.keyCode == 39) { console.log('Going right...'); this._moveCharPosition('right'); } else if (e.keyCode == 40) { console.log('Going down...'); this._moveCharPosition('down'); } } // Render random map and place the array in local state or Redux // Set character position in center of the map // Divide map width and length by 2 and place character on map // Create an object of different types of map tiles // Include image location // Include collision data // Collision logic // Ex: In _moveCharPosition // Perform pre render calculation to determine if character's next step is walking into a solid object // If true, do not increment/decrement character position // If false, perform move // Character animation walking direction // Set latest direction and link it to character sprite walking in that direction in Redux // Output character sprite based on last direction walked // Seperate the logic between grid creation and grid display // Create entire grid (whole map) --> determine character camera view of grid --> render view into UI _moveCharPosition(direction) { // Create copy of map position and char position before manipulating and updating back into state let cloneMapPosition = Array.prototype.slice.call(this.state.mapPosition); let cloneCharPosition = Array.prototype.slice.call(this.state.charPosition); let X = cloneCharPosition[0]; let Y = cloneCharPosition[1]; let grid = this.state.entireGrid[X][Y]; let tileType = this.state.entireGrid[X][Y]; console.log(this.state.objectInformation[tileType].solid) switch(direction) { case 'up': // Local state array corrected for transposition if (cloneMapPosition[1] > 0) { Y--; if (this.state.objectInformation[this.state.entireGrid[Y][X]].solid) { break; } else { cloneMapPosition[1]--; cloneCharPosition[1]--; } } this.setState({ heroDirection: 'up' }) break; case 'down': if (cloneMapPosition[1] < this.state.mapSize) { // Prevent user from going off grid Y++; if (this.state.objectInformation[this.state.entireGrid[Y][X]].solid) { break; } cloneMapPosition[1]++; cloneCharPosition[1]++; } this.setState({ heroDirection: 'down' }) break; case 'left': if (cloneMapPosition[0] > 0) { X--; if (this.state.objectInformation[this.state.entireGrid[Y][X]].solid) { break; } cloneMapPosition[0]--; cloneCharPosition[0]--; } this.setState({ heroDirection: 'left' }) break; case 'right': if (cloneMapPosition[0] < this.state.mapSize) { X++; if (this.state.objectInformation[this.state.entireGrid[Y][X]].solid) { break; } cloneMapPosition[0]++; cloneCharPosition[0]++; } this.setState({ heroDirection: 'right' }) break; default: break; } // grid[X][Y] = ['_', 'KNIGHT'] this.setState({ mapPosition: cloneMapPosition, charPosition: cloneCharPosition }) } // Creates initial grid - initiated during componentWillMount _createGrid (type, cols, rows) { let grid = [], tile; for (let i = 0; i < cols; i++) { let row = []; for (let j = 0; j < rows; j++) { let random = Math.random(); // Creates border around map // i controls height and j controls width; below set to 8 because glitch if set to 7 if (i < 7 || j < 7 || i > this.state.mapSize - 8 || j > this.state.mapSize - 7) { tile = 'R'; } else { // Adjust to generate random obstacles for testing // Randomly generate grass or rock on tile //tile = random > 0.4 ? '_' : 'R'; tile = '_' } row.push(tile) } grid.push(row); } return grid } // Expected parameters: grid to be manipulated and number of desired rooms _generateRooms(grid, rooms) { const that = this; let roomCenterPoints = []; function helperGeneratePosition() { // cols & rows will temporarily be substituted for 150 let randomX = Math.floor(Math.random() * 150); let randomY = Math.floor(Math.random() * 150); return [randomX, randomY] } function helperGenerateRoomSize() { let randomWidth = Math.floor(Math.random() * 10) + 5; let randomHeight = Math.floor(Math.random() * 10) + 5; return [randomWidth, randomHeight]; } function helperFindCenterOfRoom(x, y, w, h) { return [Math.floor(x + w / 2), Math.floor(y + h / 2)] } function generateRoom() { // console.log('Log generateRoom activity'); // Recursion count let randomPosition = helperGeneratePosition(); let randomSize = helperGenerateRoomSize(); console.log('randomPosition:' + randomPosition); console.log('randomSize: ' + randomSize); let x = randomPosition[0]; let y = randomPosition[1]; let width = randomSize[0]; let height = randomSize[1]; if (x + width > that.state.width - 1 || // Added -1 to width and height to determine if generateRoom error still occurs y + height > that.state.height - 1 ||// Added -1 to width and height to determine if generateRoom error still occurs grid[x][y] !== '_' || grid[x][y + height] !== '_' || grid[x + width][y] !== '_' || grid[y + width][y + height] !== '_' ) { generateRoom(); } else { roomCenterPoints.push(helperFindCenterOfRoom(x, y, width, height)) for (let i = x; i < x + width; i++) { for (let j = y; j < y + height; j++) { grid[i][j] = 'R'; } } } } for (let i = 0; i < rooms; i++) { generateRoom() } // Links dungeons together // Begins with first dungeon created then sorts by next closest dungeons to minimize overlapping tunnels let curriedDrawPath = that._drawPath(grid); let paths = that._sortByDistance(roomCenterPoints) console.log(paths) for (let path in paths) { let start = paths[path].start; let sx = start[0]; let sy = start[1]; let end = paths[path].end; let ex = end[0]; let ey = end[1]; grid = curriedDrawPath(sx, sy, ex, ey) } return grid; } // Helper function for generateDungeons; used in _calculatePath // Distance formula utilized for calculating dynamically calculating distance from all // potential directions (up, down, left, right) to determine closest path _distance(x2, y2) { return function(x1, y1) { var dx = x2 - x1; var dy = y2 - y1; return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)) } } // Helper function for generateDungeons; initiated by _drawPath // Path finding algorithm utilized in calculating path from origin to destination // Adapted to link rooms together _calculatePath(x0, y0, x1, y1) { const that = this; let arr = []; let start = { x: x0, y: y0 } let end = { x: x1, y: y1 } function helper(x, y) { arr.push([x, y]); let setEndPoint = that._distance(end.x, end.y); let D1 = { x: x + 1, y: y, distance: setEndPoint(x + 1, y) } let D2 = { x: x, y: y + 1, distance: setEndPoint(x, y + 1) } let D3 = { x: x - 1, y: y, distance: setEndPoint(x - 1, y) } let D4 = { x: x, y: y - 1, distance: setEndPoint(x, y - 1) } // Array of objects for 4 directions let directions = [D1, D2, D3, D4]; // Sort directions by closest distance to furthest distance directions.sort(function(a, b) { return a.distance > b.distance; }); // Loop through all 4 directions subject to conditions and decides on final direction to take for (let d = 0; d < directions.length; d++) { let dir = directions[d]; // Ensures projected coordinates stay on grid if (dir.x >= that.width || dir.y >= that.length) { continue; } else if (dir.x == end.x && dir.y == end.y) { return arr; } helper (dir.x, dir.y); break; } } helper(start.x, start.y); return arr; } // Helper function for generateRoms; draws paths between each room generated _drawPath(grid) { var that = this; return function(x0, y0, x1, y1) { that._calculatePath(x0, y0, x1, y1).forEach(function(coordinate, idx) { let x = coordinate[0]; let y = coordinate[1]; if (idx !== 0) { grid[x][y] = 'R' // Changed from X to R for testing } }) return grid; } } // Helper function for generateRooms; links dungeons together by proximity _sortByDistance(arr) { var that = this; var idx = 0, links = {}, linkNo = 0, currCoordinate, x, y; while (arr.length > 1) { var rooms = []; currCoordinate = arr[idx]; var x0 = currCoordinate[0]; var y0 = currCoordinate[1]; arr.splice(idx, 1) arr.forEach(function(nextCoordinate, i) { var obj = {}; var x1 = nextCoordinate[0]; var y1 = nextCoordinate[1]; obj = { 'coordinates': [x1, y1], 'distance': that._distance(x1, y1)(x0, y0) } rooms.push(obj) }) var closestRoom = rooms.sort(function(a, b) { return a.distance > b.distance; })[0].coordinates links['link'+linkNo] = { start: [x0, y0], end: closestRoom } linkNo++; // Updates idx number for next iteration arr.forEach(function(subArray, i) { var sx = subArray[0]; var sy = subArray[1]; var cx = closestRoom[0]; var cy = closestRoom[1]; console.log(sx, sy); if (sx == cx && sy == cy) { //console.log(idx) //return arr.splice(idx, 1); idx = i; } }) } // End of while loop return links; } // setInterval to alter direction of critter and setState to update all critter locations. This will force a rerender // Spawn critter at (10, 10) for now createCritter(grid, total) { let crittersClone = Object.assign({}, this.state.critters); let totalCritters = 0; function helper(type, x, y, i) { let critter = { type: type, x: x, y: y, direction: 'down', aggressive: false, latest: [], health: 100 } crittersClone['critter' + totalCritters] = critter; totalCritters++; let tileUnderCritter = grid[x][y]; grid[x][y] = ['RAT', tileUnderCritter] } for (let i = 0; i < total; i++) { helper('RAT', 8 + i, 8, i); } // if (!x && !y) --> generateRandomCoordinates within dungeon this.setState({ critterCount: this.state.critterCount + 1, critters: crittersClone }) return grid; } // Take in copy of critters in state and apply callback function eachCritter(critters, fn1) { console.log('eachCritter...') let updatedCritters = {}; for (let critter in critters) { console.log(critter) updatedCritters[critter] = fn1(critters[critter]) // Returns updated object // if (critters[critter].health > 0) { // updatedCritters[critter] = fn1(critters[critter]) // Returns updated object // } } // Update state for each critter here console.log('STATE') console.log(this.state) this.setState({ critters: updatedCritters }) } // Accepts critter object and returns an critter object with updated coordinates // Takes arguments from this.eachCritter1 moveCritter = (critter) => { const that = this; // console.log('moveCritter...'); // console.log('charposition'); // console.log(this.state.charPosition) let grid = Array.prototype.slice.call(this.state.entireGrid); let cx = critter.x; let cy = critter.y; // console.log('cx, cy'); // console.log(cx, cy) let hy = that.state.charPosition[0]; let hx = that.state.charPosition[1]; // console.log('hx, hy'); // console.log(hx, hy) let coordinateCache = [cx, cy]; let tileCache = grid[cx][cy][1]; // Sprite and directions do not correlate function _moveRight() { console.log('_moveRight') cx++; critter.direction = 'down'; } function _moveLeft() { console.log('_moveLeft') cx--; critter.direction = 'up'; } function _moveUp() { console.log('_moveUp') cy--; critter.direction = 'right'; } function _moveDown() { console.log('_moveDown') cy++; critter.direction = 'left'; } let moves = [_moveRight, _moveLeft, _moveUp, _moveDown]; function _generateCoordinateChase() { // Critter will avoid taking the same way back if initial path calculation does not work // let latest = []; // console.log('latest') // console.log(latest) function latestQueue(item) { console.log('latest queue working') console.log(critter.latest) if (critter.latest.length > 1) { console.log('LATEST 1') critter.latest.shift(); critter.latest.push(item); } else { console.log('LATEST 2') critter.latest.push(item); } } //console.log('_generateCoordinateChase WORKING') function helper(x, y) { // Accepts critter current location let distanceToHero = that._distance(hx, hy); let D1 = { x: x + 1, y: y, move: _moveRight, distance: distanceToHero(x + 1, y) } let D2 = { x: x, y: y + 1, move: _moveUp, distance: distanceToHero(x, y + 1) } let D3 = { x: x - 1, y: y, move: _moveLeft, distance: distanceToHero(x - 1, y) } let D4 = { x: x, y: y - 1, move: _moveDown, distance: distanceToHero(x, y - 1) } let directions = [D1, D2, D3, D4]; //console.log(directions) directions.sort(function(a, b) { return a.distance > b.distance; }) // If critter is 1 square away from hero in any of 8 surrounding directions; do not move if ( // Left and right of critter !((cx - 1 == hx && cy == hy) || (cx + 1 == hx && cy == hy) || // Top of critter (cx + 1 == hx && cy + 1 == hy) || (cx == hx && cy + 1 == hy) || (cx - 1 == hx && cy + 1 == hy) || // Bottom of critter (cx + 1 == hx && cy - 1 == hy) || (cx == hx && cy - 1 == hy) || (cx - 1 == hx && cy - 1 == hy)) ) { for (let d = 0; d < directions.length; d++) { let dir = directions[d]; let dx = dir.x let dy = dir.y // that.state.objectInformation[that.state.entireGrid[dx][dy]].solid if (that.state.entireGrid[dx][dy] == 'R' || dx == hx && dy == hy) { continue; } // Implement at a later time - dead lock critter // Feature: critter will permanently target hero until it dies regardless proximity to hero on map // if (critter.latest.length > 1) { // // If the currently projected coordinates matches the previous location, skip coordinates and proceed to next projection // if (dx == critter.latest[0][0] && dy == critter.latest[0][1]) { // continue; // } // } // If critter is trapped and all potential directions are exhausted; do nothing else { dir.move(); critter.x = dx; critter.y = dy; latestQueue([dx, dy]) break; } } } } helper(cx, cy) } function _generateCoordinateRandom() { let random = Math.floor(Math.random() * 4); // Tests to ensure direction generated from variable 'random' will not collide with any solid objects // Collision avoidance to avoid solid objects and hero console.log('direction'); // If critter moves up and object north of critter is solid, generate another random direction // If going up if (random === 2 && (that.state.objectInformation[that.state.entireGrid[cx][cy - 1]].solid || (cx == hx && cy - 1 == hy))) { console.log('random: 2') console.log(cx, cy - 1) _generateCoordinateRandom(); } // If critter moves down and object south of critter is solid, generate another random direction // If going down else if (random === 3 && (that.state.objectInformation[that.state.entireGrid[cx][cy + 1]].solid || (cx == hx && cy + 1 == hy))) { console.log('random: 3') console.log(cx, cy + 1) _generateCoordinateRandom(); } // If critter moves left and object west of critter is solid, generate another random direction // If going left else if (random === 1 && (that.state.objectInformation[that.state.entireGrid[cx - 1][cy]].solid || (cx - 1 == hx && cy == hy))) { console.log('random: 1') console.log(cx - 1, cy) _generateCoordinateRandom(); } // If critter moves right and object right of critter is solid, generate another random direction // If going right else if (random === 0 && (that.state.objectInformation[that.state.entireGrid[cx + 1][cy]].solid || (cx + 1 == hx && cy == hy))) { console.log('random: 0') console.log(cx + 1, cy) _generateCoordinateRandom(); } // Continue else { // Directions to not match sprite // Execute move moves[random](); } critter.x = cx; critter.y = cy; console.log(critter) } if (!critter.aggressive) { _generateCoordinateRandom() } else if (critter.aggressive) { _generateCoordinateChase(); } this.renderCritter(critter, coordinateCache, tileCache) return critter } checkCritter = (critter) => { if (critter.health == 0) { } } // Attacking critter mechanism heroTargetCritter() { console.log('HEROTARGETCRITTER TESTING') console.log(this.state.charPosition) let cx = this.state.charPosition[0]; let cy = this.state.charPosition[1]; console.log(cx, cy) let surroundingCoordinates = [ [cx - 1, cy - 1], [cx , cy - 1], [cx + 1, cy - 1], [cx - 1, cy ], [cx + 1, cy ], [cx - 1, cy + 1], [cx , cy + 1], [cx + 1, cy + 1] ] surroundingCoordinates.forEach((coordinate) => { console.log("SURROUNDING COORDINATES") let x = coordinate[0]; let y = coordinate[1]; if (this.state.entireGrid[x][y].includes('RAT')) { console.log('INCLUDES RAT') console.log(this.state.entireGrid[x][y]) this.attackCritter(this.findCritter(x, y)) this.setState({ target: this.findCritter(x, y) // Returns specific critter }) console.log(this.state) } else { this.setState({ target: '' }) } }) } attackCritter(critter) { console.log('CURRENTLY ATTACKING CRITTER') // Generate damage between 0 - 10 let damage = Math.floor(Math.random() * 10); this.props.storeDamage(damage) // Insert Redux method to take damage and send to store let crittersClone = Object.assign({}, this.state.critters); crittersClone[critter].health = crittersClone[critter].health - damage; this.setState({ critters: crittersClone }) } // Function for dead critter deadCritter() { } // Function to identify critter in 'critters' object given x and y coordinate on grid; findCritter(x, y) { for (let critter in this.state.critters) { if (this.state.critters[critter].x == x && this.state.critters[critter].y == y) { return critter } } } renderCritter(critter, prevCoordinates, prevTile) { // console.log('mapPosition'); // console.log(this.state.mapPosition) let px = prevCoordinates[0]; let py = prevCoordinates[1]; let cx = critter.x; let cy = critter.y; console.log('render critter') console.log(prevTile) let grid = Array.prototype.slice.call(this.state.entireGrid); // Required to avoid rendering issues when critter is within hero's immediate proximity (8 tiles surrounding hero) if (!(grid[cx][cy].length > 1)) { let tileUnderCritter = grid[cx][cy]; grid[px][py] = prevTile; grid[cx][cy] = ['RAT', tileUnderCritter]; } this.setState({ entireGrid: grid }) } // Must reflect critters on state grid at all times buildMap() { var that = this; let grid = this._helperTranspose(this._createGrid('_', this.state.mapSize, this.state.mapSize)); grid = this._generateRooms(grid, 13) // Set initial critters here // Reasoning for placing critter creation here: when placing in componentWillMount, grid updates on state later than critter creation grid = this.createCritter(grid, 1); // function critterWrapper() { // this.createCritter(grid, 'rat', 8, 8); // } return grid; } // Transpose array to convert grid to true [x][y] _helperTranspose(a) { return Object.keys(a[0]).map(function(c) { return a.map(function(r) { return r[c]; }); }) } // cameraGrid accepts an array (this.state.grid) and translates into player's camera screen cameraGrid (grid) { // get camera position from state const position = this.state.mapPosition; // Adjust everything to mapPosition later on const x = position[0]; const y = position[1]; let gridView = []; for (let i = y; i < y + this.state.cameraSize; i++) { let row = []; // Temporary switched to 20 to widen camera view for (let j = x; j < x + this.state.cameraSize; j++) { row.push(grid[i][j]) } gridView.push(row); } let center = this.state.cameraSize / 2; // Change 10 to Math.floor(center) later let tileUnderKnight = gridView[Math.floor(center)][Math.floor(center)]; //gridView[Math.floor(center)][Math.floor(center)] = 'KNIGHT' // ORIGINAL SETTINGS; also go to style.css and remove position: absolute gridView[Math.floor(center)][Math.floor(center)] = ['KNIGHT', tileUnderKnight]//gridView[Math.floor(center)][Math.floor(center)].concat(', KNIGHT') // console.log(gridView[Math.floor(center)]) // console.log(Math.floor(center)); // console.log(this.state.charPosition[0]) return gridView; } // renderGrid accepts an array (cameraGrid) and translates the array into tile sprites renderGrid(grid) { let renderGrid = []; const that = this; grid.forEach(function(row, idx1) { let renderRow = []; row.forEach(function(tile, idx2) { // Special case render if knight is on top of a tile if (Array.isArray(tile)) { tile.forEach(function(type) { switch(type) { case '_': renderRow.push(<img src={Grass} />) break; case 'GRASS': renderRow.push(<img src={Grass} />) break; case 'KNIGHT': renderRow.push(<Hero direction={that.state.heroDirection ? that.state.heroDirection : 'down'}/>) // Default position front facing on initial load break; case 'R': renderRow.push(<img src={Rock} />) break; case 'RAT': for (let i = 0; i < Object.keys(that.state.critters).length; i++){ var thisCritter = that.state.critters['critter' + i]; if (thisCritter.x == (idx1 + that.state.mapPosition[1]) && thisCritter.y == (idx2 + that.state.mapPosition[0])) { renderRow.push(<Rat direction={thisCritter.direction}/>) } console.log('this critters') console.log(thisCritter.x, thisCritter.y); console.log('this map position') console.log(that.state.mapPosition) console.log('this index'); console.log(idx1, idx2) // (function(num) { // renderRow.push(<Rat direction={that.state.critters['critter' + num].direction}/>) // })(i) } default: break; } }) } // Regular case - render tile normally switch(tile) { case '_': renderRow.push(<img src={Grass} />) break; case 'GRASS': renderRow.push(<img src={Grass} />) break; case 'KNIGHT': renderRow.push(<Hero />) break; case 'R': renderRow.push(<img src={Rock} />) break; default: break; } }) renderGrid.push(<div>{renderRow}</div>) }) return renderGrid; } render() { // TESTING console.log("TESTING!!!!!!!!!!!!!!!!!!!!!!!") console.log(this.props) return( <div> <div className="grid">{this.renderGrid(this.cameraGrid(this.state.entireGrid))}</div> </div> ) } } function mapStateToProps(state) { return { grid: state.grid, damage: state.damage } } function mapDispatchToProps(dispatch) { return bindActionCreators({storeDamage}, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(Grid); // {this.renderGrid(this.cameraGrid(this.createGrid('GRASS', this.state.mapSize, this.state.mapSize)))}
src/client.js
KeKs0r/evodemo
/* global __DEVTOOLS__ */ import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import createStore from './redux/create'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const location = new Location(document.location.pathname, document.location.search); universalRouter(location, history, store) .then(({component}) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.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.'); } }
src/website/app/demos/Radio/RadioGroup/propsComment.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; export default ( <p> Unlike most other components, which apply undocumented properties to the root element, RadioGroup applies undocumented properties, including{' '} <a href="/styling#customization-techniques-try-theming-first-{{8}}-{{14}}-prop"> <code>as</code> </a>{' '} and{' '} <a href="/styling#customization-techniques-try-theming-first-{{22}}-prop"> <code>css</code> </a> , to the <em>Radio</em> component. </p> );
src/common/ui/Button/index.js
MadeInHaus/react-redux-webpack-starter
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from '@ui'; import cx from 'classnames'; import styles from './Button.scss'; const Button = ({ className, href, theme, to, ...props }) => { const classNames = cx(styles.root, className, styles[theme]); if (to || href) { return <Link {...props} className={classNames} to={to} href={href} />; } return <button {...props} className={classNames} />; }; Button.propTypes = { className: PropTypes.string, href: PropTypes.string, theme: PropTypes.oneOf(Object.keys(styles)), to: PropTypes.string, }; Button.defaultProps = { className: null, href: null, theme: 'body', to: null, }; export default Button;
src/components/noteDetailsList.js
onepiece8971/rememberNote
import React from 'react'; import {FlatList} from 'react-native'; import CS from '../css/convertSize'; import { ContentView, TopView, TopText, DetailsContentView, DetailsSmallView, TextView, TitleText, MiddleTextView, MiddleText, FootTextView, FootLeftTex, FootRightTex, RightViewForAllNote } from '../css/noteStyles'; import Svg, {Polygon} from 'react-native-svg'; import {MainView} from '../css/styles' import Menu from '../containers/menu' import Top from '../containers/top'; const DetailsView = ({navigation, item, userBooksId, getPost}) => ( <DetailsContentView> <DetailsSmallView> <TextView> <TitleText onPress={() => { getPost(userBooksId, item.page); navigation.navigate('NoteDetails'); }}>{item.name}</TitleText> <MiddleTextView> <MiddleText>{item.content}</MiddleText> </MiddleTextView> <FootTextView> <FootLeftTex>熟练度: </FootLeftTex> <FootRightTex>{item.level}</FootRightTex> </FootTextView> </TextView> <RightViewComp isMemory={item.level} /> </DetailsSmallView> </DetailsContentView> ); const RightViewComp = ({isMemory}) => { return isMemory ? ( <RightViewForAllNote> <Svg width={CS.w(12)} height={CS.h(16)} viewBox="0 0 9 12"> <Polygon points="0 0.00184591254 0 11.9664853 4.47141075 7.97608219 8.99312842 11.9949669 8.99312842 0" fill="rgba(252, 200, 194, 0.58)"/> </Svg> </RightViewForAllNote> ) : ( <RightViewForAllNote> <Svg width={CS.w(12)} height={CS.h(16)} viewBox="0 0 14 18"> <Polygon points="0 0.00246224944 0 15.9620086 5.96643643 10.6392386 12 16 12 0" fill="none" stroke="rgba(94, 105, 115, 0.38)" strokeWidth="2"/> </Svg> </RightViewForAllNote> ) }; const PostMax = 50; export default NoteDetailsList = ({navigation, posts, userBooksId, userBooksName, getPost, getPosts}) => { if (posts) { const data = []; for (let i in posts) { let v = posts[i]; const content = v.Content.split("\n")[3]; data.push({ key: i, id: v.Id, name: v.Name, content: content.substr(0, 26), level: v.Level, page: v.Page, }); } return ( <Menu> <MainView> <Top back={true} navigation={navigation} search={{type: 'postsList', data: userBooksId}} /> <ContentView> <TopView> <TopText>{userBooksName}</TopText> </TopView> <FlatList data={data} renderItem={ ({item}) => (<DetailsView item={item} userBooksId={userBooksId} getPost={getPost} navigation={navigation} />) } getItemLayout={(data, index) => ( {length: CS.h(84), offset: CS.h(84) * index, index} )} refreshing={true} onEndReached={() => getPosts(userBooksId, Math.ceil(Object.keys(posts).length / PostMax) + 1)} onEndReachedThreshold={0.2} /> </ContentView> </MainView> </Menu> ) } else { return ( <TitleText>Loading...</TitleText> ) } };
fixtures/blocks/src/index.js
cpojer/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. */ import React from 'react'; import {unstable_createRoot as createRoot} from 'react-dom'; import './index.css'; import Router from './Router'; createRoot(document.getElementById('root')).render(<Router />);
app/main_app.js
GDGVIT/website-stat-electron
import React from 'react'; import Card from './card.js'; import Screenshot from './screenshot.js'; import LoadTime from './loadtime'; import Requests from './requests'; import Rulelist from './rule_list'; import PageGrade from './page_grade'; import Size from './size'; import Preloader from './preloader'; import CircularProgressbar from 'react-circular-progressbar' class MainApp extends React.Component { constructor(){ super(); this.state={ percent:0, inurl:'', data:[], dataurl:'http://', datatitle:'Title', datagrade:0, dataresources:0, datahosts:0, databytes:0, datastaticresources:0, datahtmlbytes:0, datacssbytes:0, dataimagebytes:0, datajsbytes:0, datajs:0, datacss:0, loadervisibility:'hidden', screenshot:'_9j_4AAQSkZJRgABAQAAAQABAAD_2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj_2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj_wAARCADwAUADASIAAhEBAxEB_8QAHAABAAEFAQEAAAAAAAAAAAAAAAYBAgMEBQcI_8QAShAAAQMCAwIICQwBAwIGAwAAAQIDBAARBRIhBjETFCJBUVRhcRYyM3KBkZKT0QcVFyM0UlWUobHB0lMkQnNi8CVDY4Lh8YOEov_EABsBAQACAwEBAAAAAAAAAAAAAAABAgMFBgQH_8QAOBEAAgECAgYHBwQCAwEAAAAAAAECAxEEURITFSExkQUUQWFxodEWUlNUgdLwkrHB4QYiMnLC8f_aAAwDAQACEQMRAD8A-qaUpQClKUApSlAKUpQClKUApSlAKUoaAXHTSvFPk_xybNkbKJh4rjkzFZZW7iTM1K-LGOkKC1oK0gXCy0BwZO_XTWuzs5toqZ8orqVYvHewvEnn4ESGl5BU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4e0TTjuIOyVIYhRnhHSVNOZ1Kva50tqdLDUaX310HMaw9t1DbkgIWsJNlIUMubxcxtySehVql1cUnbSlzZWOH6PkrqEOSJx4e7S_iZ90j-tPD3aX8TPukf1qDnGsPEwxTJAeDvAkZFWSs2skqtYE3FtdaphWLM4k_NaZQ6kxXeCUVoUkK0BuLjt3b9L84qNdiUruUubLLC4BtRUIX8ETnw92l_Ez7pH9aeHu0v4mfdI_rUJGLQTLVFEhJeBItlNiQLlIVaxIHMDerIWN4dNUBGlJVdvhgSlSQUc6gSACBfW26mvxXHSlzZPVcBe2hDlEnPh7tL-Jn3SP608PdpfxM-6R_WoBCxxmdi6IsRQcZMZT5WUqSbhSQLXAuCCdeyuxUSxGIhulN82TTwWBqK8KcWv-q9CT-Hu0v4mfdI_rTw92l_Ez7pH9ajFKr1qv775svs7CfCj-lehJ_D3aX8TPukf1p4e7S_iZ90j-tRilOtV_ffNjZ2E-FH9K9CT-Hu0v4mfdI_rTw92l_Ez7pH9ajFKdar---bGzsJ8KP6V6En8PdpfxM-6R_Wh292ltf5yOn_pI_rUYqh8U91Ot1_ffNk7Ownwo_pXofUENanIrK1-MpCVHvIrNWvh_2GP_AMaf2FbFdsuB8nlxFKUqSBSlKA__2Q==', datarules: {"AvoidLandingPageRedirects": { "localizedRuleName": "Avoid landing page redirects", "ruleImpact": 0, "groups": [ "SPEED" ], "summary": { "format": "Your page has no redirects. Learn more about {{BEGIN_LINK}}avoiding landing page redirects{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/AvoidRedirects" } ] } }, "EnableGzipCompression": { "localizedRuleName": "Enable compression", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "You have compression enabled. Learn more about {{BEGIN_LINK}}enabling compression{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/EnableCompression" } ] } }, "LeverageBrowserCaching": { "localizedRuleName": "Leverage browser caching", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network." }, "urlBlocks": [ { "header": { "format": "{{BEGIN_LINK}}Leverage browser caching{{END_LINK}} for the following cacheable resources:", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/LeverageBrowserCaching" } ] }, "urls": [ { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbadg.png" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbgit.png" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbkrs.png" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/css/materialize.min.css" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/material-design-icons/Material-Design-Icons.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/roboto/Roboto-Bold.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/roboto/Roboto-Light.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/roboto/Roboto-Medium.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/roboto/Roboto-Regular.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/font/roboto/Roboto-Thin.woff" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } }, { "result": { "format": "{{URL}} ({{LIFETIME}})", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/js/materialize.min.js" }, { "type": "DURATION", "key": "LIFETIME", "value": "10 minutes" } ] } } ] } ] }, "MainResourceServerResponseTime": { "localizedRuleName": "Reduce server response time", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Your server responded quickly. Learn more about {{BEGIN_LINK}}server response time optimization{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/Server" } ] } }, "MinifyCss": { "localizedRuleName": "Minify CSS", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Your CSS is minified. Learn more about {{BEGIN_LINK}}minifying CSS{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/MinifyResources" } ] } }, "MinifyHTML": { "localizedRuleName": "Minify HTML", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Your HTML is minified. Learn more about {{BEGIN_LINK}}minifying HTML{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/MinifyResources" } ] } }, "MinifyJavaScript": { "localizedRuleName": "Minify JavaScript", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Your JavaScript content is minified. Learn more about {{BEGIN_LINK}}minifying JavaScript{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/MinifyResources" } ] } }, "MinimizeRenderBlockingResources": { "localizedRuleName": "Eliminate render-blocking JavaScript and CSS in above-the-fold content", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.", "args": [ { "type": "INT_LITERAL", "key": "NUM_SCRIPTS", "value": "1" }, { "type": "INT_LITERAL", "key": "NUM_CSS", "value": "2" } ] }, "urlBlocks": [ { "header": { "format": "None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML." } }, { "header": { "format": "{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/BlockingJS" } ] }, "urls": [ { "result": { "format": "{{URL}}", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/js/materialize.min.js" } ] } } ] }, { "header": { "format": "{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery" } ] }, "urls": [ { "result": { "format": "{{URL}}", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/materialize/css/materialize.min.css" } ] } }, { "result": { "format": "{{URL}}", "args": [ { "type": "URL", "key": "URL", "value": "https://fonts.googleapis.com/css?family=Source+Code+Pro" } ] } } ] } ] }, "OptimizeImages": { "localizedRuleName": "Optimize images", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "Properly formatting and compressing images can save many bytes of data." }, "urlBlocks": [ { "header": { "format": "{{BEGIN_LINK}}Optimize the following images{{END_LINK}} to reduce their size by {{SIZE_IN_BYTES}} ({{PERCENTAGE}} reduction).", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/OptimizeImages" }, { "type": "BYTES", "key": "SIZE_IN_BYTES", "value": "1.3MiB" }, { "type": "PERCENTAGE", "key": "PERCENTAGE", "value": "93%" } ] }, "urls": [ { "result": { "format": "Compressing and resizing {{URL}} could save {{SIZE_IN_BYTES}} ({{PERCENTAGE}} reduction).", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbkrs.png" }, { "type": "BYTES", "key": "SIZE_IN_BYTES", "value": "829.8KiB" }, { "type": "PERCENTAGE", "key": "PERCENTAGE", "value": "93%" } ] } }, { "result": { "format": "Compressing and resizing {{URL}} could save {{SIZE_IN_BYTES}} ({{PERCENTAGE}} reduction).", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbadg.png" }, { "type": "BYTES", "key": "SIZE_IN_BYTES", "value": "430.3KiB" }, { "type": "PERCENTAGE", "key": "PERCENTAGE", "value": "94%" } ] } }, { "result": { "format": "Compressing and resizing {{URL}} could save {{SIZE_IN_BYTES}} ({{PERCENTAGE}} reduction).", "args": [ { "type": "URL", "key": "URL", "value": "http://rahulakrishna.github.io/images/rkbgit.png" }, { "type": "BYTES", "key": "SIZE_IN_BYTES", "value": "71.3KiB" }, { "type": "PERCENTAGE", "key": "PERCENTAGE", "value": "85%" } ] } } ] } ] }, "PrioritizeVisibleContent": { "localizedRuleName": "Prioritize visible content", "ruleImpact":0, "groups": [ "SPEED" ], "summary": { "format": "You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.", "args": [ { "type": "HYPERLINK", "key": "LINK", "value": "https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent" } ] } } }, progressstyle:{ width:'0%' } }; this.processForm=this.processForm.bind(this); this.handleChange=this.handleChange.bind(this); } handleChange(e){ this.setState({ inurl:e.target.value }); } processForm(e){ e.preventDefault(); const url=this.state.inurl; this.setState({ loadervisibility:'visible' }); console.log(this.state.loadervisibility); /*const expression=[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*); const regex=new RegExp(expression);*/ if(1) { $.ajax({ url: 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=http%3A%2F%2F' + url + '&screenshot=true&key=AIzaSyBKuUWqMYnnvt4JpJzL55a7MsYns7Jzxv8', /*url:'./public/mock/mock_webdata.json',*/ dataType: 'json', cache: false, xhr(){ const xhr = new window.XMLHttpRequest(); //Upload progress xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { let percentComplete = evt.loaded / evt.total; //Do something with upload progress this.state={ percent:percentComplete } } else { console.log('fuck happened beforehand'); } }, false); //Download progress xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { let percentComplete = evt.loaded / evt.total; //Do something with download progress console.log(percentComplete); console.log(evt.loaded); console.log(evt.total); this.state={ percent:percentComplete } } else { console.log('fuck happened'); } }, false); return xhr; }, success: (data) => { this.setState({ data: data, dataurl: data.id, datatitle: data.title, datagrade: data.ruleGroups.SPEED.score, dataresources: data.pageStats.numberResources, datahosts: data.pageStats.numberHosts, databytes: data.pageStats.totalRequestBytes, datastaticresources: data.pageStats.numberStaticResources, datahtmlbytes: data.pageStats.htmlResponseBytes, datacssbytes: data.pageStats.cssResponseBytes, dataimagebytes: data.pageStats.imageResponseBytes, datajsbytes: data.pageStats.javascriptResponseBytes, datajs: data.pageStats.numberJsResources, datacss: data.pageStats.numberCssResources, datarules: data.formattedResults.ruleResults, screenshot:data.screenshot.data, loadervisibility:'hidden' }); console.log(this.state.screenshot); this.updateProgress(); this.removePreloader(); }, error: (xhr, status, err) => { console.error(status, err.toString()); alert("Error occured! Either the URL is wrong or your connection is lost!"); } }); } else{ alert('Invalid URL!'); } } updateProgress(){ this.setState({ progressstyle: { width: this.state.datagrade+'%' } }); console.log(progresstyle); } removePreloader(){ this.setState({ loadervisibility:'hidden' }); } checkremovePreloader(){ if(this.state.loadervisibility==='hidden'){ this.removePreloader(); } } render() { console.log(this.state.loadervisibility); var loader; if(this.state.loadervisibility==='visible'){ loader=<Preloader/>; this.checkremovePreloader(); } else if(this.state.loadervisibility==='hidden'){ loader=<div>Success!</div>; } return ( <div> <div className="row col s12"> <form className="col s12"> <div className="col m8 push-m2"> <div className="card col s12"> <div className="card-content row"> <input type="text" placeholder="mysite.com" value={this.state.inurl} onChange={this.handleChange}/> <input type="submit" className="btn red col m4 push-m4" value="Process" onClick={this.processForm}/> </div> </div> </div> </form> <div className="row center"> {loader} <div className="col s6 push-s3"> <Screenshot className="col s6 push-s6" base64={this.state.screenshot}/> </div> </div> </div> {/*The details will begin from here*/} <div className="row"> <h3 className="center">Summary</h3> <div className="col s2 push-s5"> <CircularProgressbar percentage={this.state.datagrade}/> </div> </div> <div className="row center"> <div className="col s4 push-s4"> <PageGrade speed={this.state.datagrade}/> </div> </div> <div className="col s8 push-s2"> <Card title={this.state.dataurl} content={this.state.datatitle}/> </div> <div className="row"> <div className="col s3"> <Card title="No. of Resources" content={this.state.dataresources}/> </div> <div className="col s3"> <Card title="No. of Hosts" content={this.state.datahosts}/> </div> <div className="col s3"> {/*TODO: Remove these from Cards and make a new Size card which will convert Bytes to MBs*/} <Size title="Size" size={this.state.databytes} postdata=" bytes" color="red"/> </div> <div className="col s3"> <Card title="Static Resources" content={this.state.datastaticresources} className="red"/> </div> </div> <div className="row"> <div className="col s3"> <Size title="Size of HTML" size={this.state.datahtmlbytes} postdata=" bytes"/> </div> <div className="col s3"> <Card title="Size of CSS" content={this.state.datacssbytes} postdata=" bytes"/> </div> <div className="col s3"> <Size title="Size of Images" size={this.state.dataimagebytes} postdata=" bytes"/> </div> <div className="col s3"> <Card title="Size of Javascript" content={this.state.datajsbytes} postdata=" bytes"/> </div> </div> <div className="row"> <div className="col s3"> <Card title="No. of JS files" content={this.state.datajs}/> </div> <div className="col s3"> <Card title="No. of CSS files" content={this.state.datacss}/> </div> </div> <Rulelist rules={this.state.datarules}/> <div className="row"> The list of files should come up here. </div> </div> ); } } export default MainApp;
assets/javascripts/sso/components/AdminListGroupCard.js
wchaoyi/sso
import StyleSheet from 'react-style'; import React from 'react'; import {History} from 'react-router'; import {Admin} from '../models/Models'; let AdminListGroupCard = React.createClass({ mixins: [History], getInitialState() { return { groups: [], }; }, componentDidMount() { this.reload(); }, render() { return ( <div className="mdl-card mdl-shadow--2dp" styles={[this.styles.card, this.props.style]}> <div className="mdl-card__title"> <h2 className="mdl-card__title-text">我的用户组列表</h2> </div> <table className="mdl-data-table mdl-js-data-table" style={this.styles.table}> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">名称</th> <th className="mdl-data-table__cell--non-numeric">描述</th> <th className="mdl-data-table__cell--non-numeric">身份</th> <th className="mdl-data-table__cell--non-numeric"></th> </tr> </thead> <tbody> { this.state.groups.map((group, index) => { return ( <tr key={`group-${index}`}> <td className="mdl-data-table__cell--non-numeric"> <a href="javascript:;" onClick={(evt) => this.goDetail(group.name)}>{group.name}</a> </td> <td className="mdl-data-table__cell--non-numeric" style={this.styles.breaklineTd}>{group.fullname}</td> <td className="mdl-data-table__cell--non-numeric">{group.role === "admin" ? "管理员" : "成员"}</td> <td className="mdl-data-table__cell--non-numeric"> { !this.canDelete(group) ? null : <a href="javascript:;" onClick={(evt) => this.deleteGroup(group.name)}>删除</a> } </td> </tr> ); }) } </tbody> </table> <div className="mdl-card__actions"> <button className="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--colored" onClick={this.reload}>刷新</button> </div> </div> ); }, goDetail(name) { const {token, tokenType} = this.props; this.history.pushState({token, tokenType}, `/spa/admin/groups/${name}`); }, canDelete(group) { return !(group.name === 'admins' || group.role !== 'admin' || _.startsWith(group.name, ".")); }, deleteGroup(name) { let yes = confirm(`确定要删除用户组 - ${name} 吗?`); if (yes) { const {token, tokenType} = this.props; Admin.deleteGroup(token, tokenType, name, (ok, status) => ok ? this.reload() : null); } }, reload() { const {token, tokenType} = this.props; Admin.listGroups(token, tokenType, (groups) => { this.setState({ groups }); }); }, styles: StyleSheet.create({ card: { width: '100%', marginBottom: 16, minHeight: 50, }, table: { width: '100%', borderLeft: 'none', borderRight: 'none', }, breaklineTd: { whiteSpace: 'pre-line', wordWrap: 'break-word', wordBreak: 'break-word', }, }), }); export default AdminListGroupCard;
docs/src/app/components/pages/components/IconButton/ExampleSimple.js
rscnt/material-ui
import React from 'react'; import IconButton from 'material-ui/IconButton'; const IconButtonExampleSimple = () => ( <div> <IconButton iconClassName="muidocs-icon-custom-github" /> <IconButton iconClassName="muidocs-icon-custom-github" disabled={true} /> </div> ); export default IconButtonExampleSimple;
antd-dva/ant-design-pro-demo/test/src/routes/Profile/BasicProfile.js
JianmingXia/StudyTest
import React, { Component } from 'react'; import { connect } from 'dva'; import { Card, Badge, Table, Divider } from 'antd'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import DescriptionList from '../../components/DescriptionList'; import styles from './BasicProfile.less'; const { Description } = DescriptionList; const progressColumns = [{ title: '时间', dataIndex: 'time', key: 'time', }, { title: '当前进度', dataIndex: 'rate', key: 'rate', }, { title: '状态', dataIndex: 'status', key: 'status', render: text => ( text === 'success' ? <Badge status="success" text="成功" /> : <Badge status="processing" text="进行中" /> ), }, { title: '操作员ID', dataIndex: 'operator', key: 'operator', }, { title: '耗时', dataIndex: 'cost', key: 'cost', }]; @connect(({ profile, loading }) => ({ profile, loading: loading.effects['profile/fetchBasic'], })) export default class BasicProfile extends Component { componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'profile/fetchBasic', }); } render() { const { profile, loading } = this.props; const { basicGoods, basicProgress } = profile; let goodsData = []; if (basicGoods.length) { let num = 0; let amount = 0; basicGoods.forEach((item) => { num += Number(item.num); amount += Number(item.amount); }); goodsData = basicGoods.concat({ id: '总计', num, amount, }); } const renderContent = (value, row, index) => { const obj = { children: value, props: {}, }; if (index === basicGoods.length) { obj.props.colSpan = 0; } return obj; }; const goodsColumns = [{ title: '商品编号', dataIndex: 'id', key: 'id', render: (text, row, index) => { if (index < basicGoods.length) { return <a href="">{text}</a>; } return { children: <span style={{ fontWeight: 600 }}>总计</span>, props: { colSpan: 4, }, }; }, }, { title: '商品名称', dataIndex: 'name', key: 'name', render: renderContent, }, { title: '商品条码', dataIndex: 'barcode', key: 'barcode', render: renderContent, }, { title: '单价', dataIndex: 'price', key: 'price', align: 'right', render: renderContent, }, { title: '数量(件)', dataIndex: 'num', key: 'num', align: 'right', render: (text, row, index) => { if (index < basicGoods.length) { return text; } return <span style={{ fontWeight: 600 }}>{text}</span>; }, }, { title: '金额', dataIndex: 'amount', key: 'amount', align: 'right', render: (text, row, index) => { if (index < basicGoods.length) { return text; } return <span style={{ fontWeight: 600 }}>{text}</span>; }, }]; return ( <PageHeaderLayout title="基础详情页"> <Card bordered={false}> <DescriptionList size="large" title="退款申请" style={{ marginBottom: 32 }}> <Description term="取货单号">1000000000</Description> <Description term="状态">已取货</Description> <Description term="销售单号">1234123421</Description> <Description term="子订单">3214321432</Description> </DescriptionList> <Divider style={{ marginBottom: 32 }} /> <DescriptionList size="large" title="用户信息" style={{ marginBottom: 32 }}> <Description term="用户姓名">付小小</Description> <Description term="联系电话">18100000000</Description> <Description term="常用快递">菜鸟仓储</Description> <Description term="取货地址">浙江省杭州市西湖区万塘路18号</Description> <Description term="备注">无</Description> </DescriptionList> <Divider style={{ marginBottom: 32 }} /> <div className={styles.title}>退货商品</div> <Table style={{ marginBottom: 24 }} pagination={false} loading={loading} dataSource={goodsData} columns={goodsColumns} rowKey="id" /> <div className={styles.title}>退货进度</div> <Table style={{ marginBottom: 16 }} pagination={false} loading={loading} dataSource={basicProgress} columns={progressColumns} /> </Card> </PageHeaderLayout> ); } }
fields/types/geopoint/GeoPointField.js
jstockwin/keystone
import Field from '../Field'; import React from 'react'; import { FormRow, FormField, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'GeopointField', statics: { type: 'Geopoint', }, focusTargetRef: 'lat', handleLat (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [value[0], newVal], }); }, handleLong (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [newVal, value[1]], }); }, renderValue () { const { value } = this.props; if (value && value[1] && value[0]) { return <FormInput noedit>{value[1]}, {value[0]}</FormInput>; // eslint-disable-line comma-spacing } return <FormInput noedit>(not set)</FormInput>; }, renderField () { const { value = [], path } = this.props; return ( <FormRow> <FormField width="one-half"> <FormInput name={this.getInputName(path + '[1]')} placeholder="Latitude" ref="lat" value={value[1]} onChange={this.handleLat} autoComplete="off" /> </FormField> <FormField width="one-half"> <FormInput name={this.getInputName(path + '[0]')} placeholder="Longitude" ref="lng" value={value[0]} onChange={this.handleLong} autoComplete="off" /> </FormField> </FormRow> ); }, });
src/esm/components/graphics/icons-next/airplane-icon-next/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "title"]; import React from 'react'; import PropTypes from 'prop-types'; export var AirplaneIconNext = function AirplaneIconNext(_ref) { var color = _ref.color, title = _ref.title, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("svg", _extends({ width: "20", height: "19", viewBox: "0 0 20 19", xmlns: "http://www.w3.org/2000/svg" }, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", { fill: color, d: "M10.747 18.697c.38-.238.704-.566.946-.961l7.916-12.93c.29-.473.453-1.023.468-1.59A3.235 3.235 0 0 0 19.7 1.6 2.942 2.942 0 0 0 18.59.44a2.658 2.658 0 0 0-1.51-.36l-14.342.93a2.697 2.697 0 0 0-1.353.473c-.407.28-.74.667-.969 1.125a3.248 3.248 0 0 0 .042 2.97l.041.077c.18.337.418.633.702.873l4.479 3.8.814 6.085c.05.384.17.754.349 1.09l.042.078c.376.7.993 1.21 1.717 1.419.724.21 1.495.1 2.145-.303Zm-2.353-2.16a1.185 1.185 0 0 1-.122-.389l-.792-5.825 4.395-2.735-.895-1.673-4.396 2.736-4.282-3.653a1.105 1.105 0 0 1-.252-.308l-.041-.078a1.183 1.183 0 0 1-.013-1.083 1.09 1.09 0 0 1 .35-.41.99.99 0 0 1 .493-.176l14.35-.934a.975.975 0 0 1 .552.13c.17.099.31.246.407.427.097.18.144.384.138.592-.005.208-.065.41-.17.582L10.19 16.675a1.065 1.065 0 0 1-.387.371.973.973 0 0 1-1.003-.033 1.084 1.084 0 0 1-.365-.397l-.042-.079Z" })); }; AirplaneIconNext.propTypes = { color: PropTypes.string, title: PropTypes.string }; AirplaneIconNext.defaultProps = { color: '#222', title: null };
app/components/packages.component.js
karlitos/Android-Adb-Tweaker
import React from 'react'; class Packages extends React.Component { constructor(props) { super(props); this.state = {filesToInstall: []}; } // handles the drop event handleApkDrop(event) { const droppedFiles = event.dataTransfer.files; // convert the FileList collection to flat array containing only APKs let droppedFilesArray = Array.prototype.filter.call(droppedFiles, (file) => { return file.type == 'application/vnd.android.package-archive'; }) this.setState({ filesToInstall: droppedFilesArray }); event.preventDefault(); }; // prevent default handling of events preventDefaultHandling(event) { event.preventDefault(); } render(){ return ( <div className="packages"> <h4>Install and manage packages on selected device.</h4> <div className="drag-n-drop-for-packages" onDragOver={::this.preventDefaultHandling} onDragEnd={::this.preventDefaultHandling} onDrop={::this.handleApkDrop}> <p> <strong>Drop your APKs here.</strong> </p> </div> <textarea className="form-control files-to-install" placeholder="Slected files to install" rows="3" readOnly value={this.state.filesToInstall.map((file) => {return file.name}).join('\n')}> </textarea> <button className={`btn ${this.props.adbClientBusy ? 'btn-negative busy' : 'btn-positive'} pull-right install-packages-padded-buton`} onClick={() => this.props.handleFilesInstallSubmit(this.state.filesToInstall)} disabled={this.props.adbClientBusy}> {this.props.adbClientBusy ? 'Busy' : 'Install'} {this.props.adbClientBusy && <span className="icon icon-hourglass icon-hourglass-busy"></span>} </button> </div> ) } } export default Packages
app/components/Container/index.js
sekkithub/wg
import React from 'react'; import styles from './styles.css'; function Container(props) { return ( <div className={ styles.container } { ...props } /> ); } export default Container;
node_modules/semantic-ui-react/src/collections/Form/FormRadio.js
IgorKilipenko/KTS_React
import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' import Radio from '../../addons/Radio' import FormField from './FormField' /** * Sugar for <Form.Field control={Radio} /> * @see Form * @see Radio */ function FormRadio(props) { const { control } = props const rest = getUnhandledProps(FormRadio, props) const ElementType = getElementType(FormRadio, props) return <ElementType {...rest} control={control} /> } FormRadio._meta = { name: 'FormRadio', parent: 'Form', type: META.TYPES.COLLECTION, } FormRadio.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** A FormField control prop */ control: FormField.propTypes.control, } FormRadio.defaultProps = { as: FormField, control: Radio, } export default FormRadio
admin/client/App/shared/Popout/PopoutPane.js
jacargentina/keystone
/** * Render a popout pane, calls props.onLayout when the component mounts */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutPane = React.createClass({ displayName: 'PopoutPane', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, onLayout: React.PropTypes.func, }, getDefaultProps () { return { onLayout: () => {}, }; }, componentDidMount () { this.props.onLayout(this.refs.el.offsetHeight); }, render () { const className = classnames('Popout__pane', this.props.className); const props = blacklist(this.props, 'className', 'onLayout'); return ( <div ref="el" className={className} {...props} /> ); }, }); module.exports = PopoutPane;
js/components/entryCounter.js
yyankowski/relay-notes
import React from 'react'; import Relay from 'react-relay'; class EntryCounter extends React.Component { render() { let {entryNum} = this.props; let strLabelText = entryNum == 1 ? "item" : "items"; return ( <div id="notes-counter">{entryNum} {strLabelText}.</div> ); } } export default EntryCounter
src/svg-icons/action/history.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHistory = (props) => ( <SvgIcon {...props}> <path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/> </SvgIcon> ); ActionHistory = pure(ActionHistory); ActionHistory.displayName = 'ActionHistory'; ActionHistory.muiName = 'SvgIcon'; export default ActionHistory;
src/containers/ProfileListItem.js
JustPeople/app
import React from 'react' import { connect } from 'react-redux' import { Link } from 'react-router-dom' import styled from 'styled-components' import LocationName from './LocationName' import * as Selectors from '../selectors' function ProfileBackgroundColor(props) { switch (props.gender) { case 'f': return 'hsla(0, 100%, 90%, 1)' case 'm': return 'hsla(210, 100%, 90%, 1)' case 't': return 'hsla(270, 100%, 90%, 1)' default: return 'hsla(0, 0%, 90%, 1)' } } var Profile = styled.div` display: grid; grid-template-areas: "avatar" "info"; background-color: ${ProfileBackgroundColor}; width: 190px; transition: all 0.3s; box-shadow: 2px 2px 5px #bbb; &:hover { box-shadow: 2px 2px 5px #888; } ` var ProfileAvatarDiv = styled.div` grid-area: avatar; ` var ProfileInfoDiv = styled.div` display: grid; grid-area: info; grid-template-columns: 1fr; color: #333; ` var ProfileAvatar = connect((state, ownProps) => { var profile = state.profiles.find(p => p.id === ownProps.id) return { src: profile.avatar } })(props => ( <ProfileAvatarDiv> <img alt="avatar" src={props.src} style={{ width: '190px', height: '190px' }} /> </ProfileAvatarDiv> )) var ProfileListItem = props => { var { id, name, phone, locationId } = props return ( <Profile {...props}> <Link to={'/profiles/' + id}> <ProfileAvatar id={id} /> <ProfileInfoDiv> <strong>{name}</strong> <div>{phone}</div> <div> <LocationName id={locationId} /> </div> </ProfileInfoDiv> </Link> </Profile> ) } export default connect((state, ownProps) => { var profile = Selectors.getProfileById(state, ownProps.id) return { ...profile } })(ProfileListItem)
src/svg-icons/notification/personal-video.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPersonalVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12z"/> </SvgIcon> ); NotificationPersonalVideo = pure(NotificationPersonalVideo); NotificationPersonalVideo.displayName = 'NotificationPersonalVideo'; NotificationPersonalVideo.muiName = 'SvgIcon'; export default NotificationPersonalVideo;
assets/js/src/index.js
nathandao/git.report
require('../../css/main.css'); import React from 'react'; import ReactDOM from 'react-dom'; import { Router } from 'react-router'; import routes from 'routes'; import createHistory from 'history/lib/createBrowserHistory'; import RepoServices from 'services/RepoServices'; RepoServices.initData(); const history = createHistory(); ReactDOM.render( <Router routes={ routes } history={ history } />, document.getElementById('wrapper') );
fields/types/relationship/RelationshipFilter.js
mikaoelitiana/keystone
import async from 'async'; import React from 'react'; import xhr from 'xhr'; import { Button, FormField, FormInput, InputGroup, SegmentedControl } from 'elemental'; import PopoutList from '../../../admin/client/components/PopoutList'; const TOGGLE_OPTIONS = [ { label: 'Linked To', value: false }, { label: 'NOT Linked To', value: true }, ]; function getDefaultValue () { return { inverted: TOGGLE_OPTIONS[0].value, value: [], }; } var RelationshipFilter = React.createClass({ statics: { getDefaultValue: getDefaultValue, }, propTypes: { field: React.PropTypes.object, filter: React.PropTypes.shape({ inverted: React.PropTypes.bool, value: React.PropTypes.array, }), onHeightChange: React.PropTypes.func, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, getInitialState () { return { searchIsLoading: false, searchResults: [], searchString: '', selectedItems: [], valueIsLoading: true, }; }, componentDidMount () { this._itemsCache = {}; this.loadSearchResults(true); }, componentWillReceiveProps (nextProps) { if (nextProps.filter.value !== this.props.filter.value) { this.populateValue(nextProps.filter.value); } }, isLoading () { return this.state.searchIsLoading || this.state.valueIsLoading; }, populateValue (value) { async.map(value, (id, next) => { if (this._itemsCache[id]) return next(null, this._itemsCache[id]); xhr({ url: Keystone.adminPath + '/api/' + this.props.field.refList.path + '/' + id + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, items) => { if (err) { // TODO: Handle errors better console.error('Error loading items:', err); } this.setState({ valueIsLoading: false, selectedItems: items || [], }, () => { this.refs.focusTarget.focus(); }); }); }, cacheItem (item) { this._itemsCache[item.id] = item; }, loadSearchResults (thenPopulateValue) { let searchString = this.state.searchString; xhr({ url: Keystone.adminPath + '/api/' + this.props.field.refList.path + '?basic&search=' + searchString, responseType: 'json', }, (err, resp, data) => { if (err) { // TODO: Handle errors better console.error('Error loading items:', err); this.setState({ searchIsLoading: false, }); return; } data.results.forEach(this.cacheItem); if (thenPopulateValue) { this.populateValue(this.props.filter.value); } if (searchString !== this.state.searchString) return; this.setState({ searchIsLoading: false, searchResults: data.results, }, this.updateHeight); }); }, updateHeight () { if (this.props.onHeightChange) { this.props.onHeightChange(this.refs.container.offsetHeight); } }, toggleInverted (inverted) { this.updateFilter({ inverted }); }, updateSearch (e) { this.setState({ searchString: e.target.value }, this.loadSearchResults); }, selectItem (item) { let value = this.props.filter.value.concat(item.id); this.updateFilter({ value }); }, removeItem (item) { let value = this.props.filter.value.filter(i => { return i !== item.id; }); this.updateFilter({ value }); }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, renderItems (items, selected) { let itemIconHover = selected ? 'x' : 'check'; return items.map((item, i) => { return ( <PopoutList.Item key={`item-${i}-${item.id}`} icon="dash" iconHover={itemIconHover} label={item.name} onClick={() => { if (selected) this.removeItem(item); else this.selectItem(item); }} /> ); }); }, render () { let selectedItems = this.state.selectedItems; let searchResults = this.state.searchResults.filter(i => { return this.props.filter.value.indexOf(i.id) === -1; }); let placeholder = this.isLoading() ? 'Loading...' : 'Find a ' + this.props.field.label + '...'; return ( <div ref="container"> <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.props.filter.inverted} onChange={this.toggleInverted} /> </FormField> <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <FormInput autofocus ref="focusTarget" value={this.state.searchString} onChange={this.updateSearch} placeholder={placeholder} /> </FormField> {selectedItems.length ? ( <PopoutList> <PopoutList.Heading>Selected</PopoutList.Heading> {this.renderItems(selectedItems, true)} </PopoutList> ) : null} {searchResults.length ? ( <PopoutList> <PopoutList.Heading style={selectedItems.length ? { marginTop: '2em' } : null}>Items</PopoutList.Heading> {this.renderItems(searchResults)} </PopoutList> ) : null} </div> ); } }); module.exports = RelationshipFilter;
react/features/chat/components/native/GifMessage.js
jitsi/jitsi-meet
import React from 'react'; import { Image, View } from 'react-native'; import { GIF_PREFIX } from '../../../gifs/constants'; import styles from './styles'; type Props = { /** * The formatted gif message. */ message: string } const GifMessage = ({ message }: Props) => { const url = message.substring(GIF_PREFIX.length, message.length - 1); return (<View style = { styles.gifContainer }> <Image source = {{ uri: url }} style = { styles.gifImage } /> </View>); }; export default GifMessage;
pages/skills.js
xzin/homepage
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Helmet from 'react-helmet' import { config } from 'config' const styles={ item:{ listStyleType:'square', fontFamily:'Ubuntu' } } export default class Index extends React.Component { render() { return ( <div> <h1> Skills </h1> <ul> <li style={styles.item}>HTML5</li> <li style={styles.item}>CSS3</li> <li style={styles.item}>SCSS</li> <li style={styles.item}>JavaScript</li> <li style={styles.item}>JQuery</li> <li style={styles.item}>AngularJS</li> <li style={styles.item}>NodeJS</li> <li style={styles.item}>Mongodb</li> </ul> </div> ) } }
src/Tabs/Tab.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; const propTypes = { active: PropTypes.bool, className: PropTypes.string, component: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, PropTypes.func ]), cssPrefix: PropTypes.string, onTabClick: PropTypes.func, style: PropTypes.object, tabId: PropTypes.number }; const defaultProps = { style: {} }; const Tab = (props) => { const { active, className, component, children, cssPrefix, onTabClick, style, tabId, ...otherProps } = props; const classes = classNames({ [`${cssPrefix}__tab`]: true, 'is-active': active }, className); const finalStyle = { ...style, cursor: 'pointer' }; return React.createElement(component || 'a', { className: classes, onClick: () => onTabClick(tabId), style: finalStyle, ...otherProps }, children); }; Tab.propTypes = propTypes; Tab.defaultProps = defaultProps; export default Tab;
src/svg-icons/communication/call-merge.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallMerge = (props) => ( <SvgIcon {...props}> <path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/> </SvgIcon> ); CommunicationCallMerge = pure(CommunicationCallMerge); CommunicationCallMerge.displayName = 'CommunicationCallMerge'; CommunicationCallMerge.muiName = 'SvgIcon'; export default CommunicationCallMerge;
actor-apps/app-web/src/app/utils/require-auth.js
boneyao/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
src/components/Header.js
weitaiting/jstrainingproject
import React from 'react'; const Header = ({ message }) => { return ( <h2 className="Header text-center"> {message} </h2> ); }; Header.propTypes = { message: React.PropTypes.string }; export default Header;
app/javascript/mastodon/features/compose/components/compose_form.js
robotstart/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import { debounce } from 'lodash'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Toggle from 'react-toggle'; import Collapsable from '../../../components/collapsable'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import SensitiveButtonContainer from '../containers/sensitive_button_container'; import EmojiPickerDropdown from './emoji_picker_dropdown'; import UploadFormContainer from '../containers/upload_form_container'; import TextIconButton from './text_icon_button'; import WarningContainer from '../containers/warning_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Content warning' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' } }); class ComposeForm extends ImmutablePureComponent { constructor (props, context) { super(props, context); this.handleChange = this.handleChange.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this); this.onSuggestionsFetchRequested = debounce(this.onSuggestionsFetchRequested.bind(this), 500); this.onSuggestionSelected = this.onSuggestionSelected.bind(this); this.handleChangeSpoilerText = this.handleChangeSpoilerText.bind(this); this.setAutosuggestTextarea = this.setAutosuggestTextarea.bind(this); this.handleEmojiPick = this.handleEmojiPick.bind(this); } handleChange (e) { this.props.onChange(e.target.value); } handleKeyDown (e) { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } handleSubmit () { this.autosuggestTextarea.reset(); this.props.onSubmit(); } onSuggestionsClearRequested () { this.props.onClearSuggestions(); } onSuggestionsFetchRequested (token) { this.props.onFetchSuggestions(token); } onSuggestionSelected (tokenStart, token, value) { this._restoreCaret = null; this.props.onSuggestionSelected(tokenStart, token, value); } handleChangeSpoilerText (e) { this.props.onChangeSpoilerText(e.target.value); } componentWillReceiveProps (nextProps) { // If this is the update where we've finished uploading, // save the last caret position so we can restore it below! if (!nextProps.is_uploading && this.props.is_uploading) { this._restoreCaret = this.autosuggestTextarea.textarea.selectionStart; } } componentDidUpdate (prevProps) { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. // - If we've just finished uploading an image, and have a saved caret position, // restores the cursor to that position after the text changes! if (this.props.focusDate !== prevProps.focusDate || (prevProps.is_uploading && !this.props.is_uploading && typeof this._restoreCaret === 'number')) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this._restoreCaret === 'number') { selectionStart = this._restoreCaret; selectionEnd = this._restoreCaret; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); } } setAutosuggestTextarea (c) { this.autosuggestTextarea = c; } handleEmojiPick (data) { const position = this.autosuggestTextarea.textarea.selectionStart; this._restoreCaret = position + data.shortname.length + 1; this.props.onPickEmoji(position, data); } render () { const { intl, onPaste } = this.props; const disabled = this.props.is_submitting; const text = [this.props.spoiler_text, this.props.text].join(''); let publishText = ''; let reply_to_other = false; if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><i className='fa fa-lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = intl.formatMessage(messages.publish) + (this.props.privacy !== 'unlisted' ? '!' : ''); } return ( <div className='compose-form'> <Collapsable isVisible={this.props.spoiler} fullHeight={50}> <div className="spoiler-input"> <input placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoiler_text} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} type="text" className="spoiler-input__input" id='cw-spoiler-input'/> </div> </Collapsable> <WarningContainer /> <ReplyIndicatorContainer /> <div className='compose-form__autosuggest-wrapper'> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} /> <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> </div> <div className='compose-form__modifiers'> <UploadFormContainer /> </div> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PrivacyDropdownContainer /> <SensitiveButtonContainer /> <SpoilerButtonContainer /> </div> <div className='compose-form__publish'> <div className='character-counter__wrapper'><CharacterCounter max={500} text={text} /></div> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={disabled || text.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "_").length > 500 || (text.length !==0 && text.trim().length === 0)} block /></div> </div> </div> </div> ); } } ComposeForm.propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestion_token: PropTypes.string, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoiler_text: PropTypes.string, focusDate: PropTypes.instanceOf(Date), preselectDate: PropTypes.instanceOf(Date), is_submitting: PropTypes.bool, is_uploading: PropTypes.bool, me: PropTypes.number, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired }; export default injectIntl(ComposeForm);
public/js/components/selector.js
MelanistOnca/bookList
import React from 'react'; import { render } from 'react-dom'; export default class Selector extends React.Component{ selectedListChanged(selectList,e){ // console.log('selection was changed'); // console.log(selectList, 'selectList passed to selectedListChanged() in components/updateLists.js'); let chosen = e.target.value; // console.log(chosen, 'was chosen in selectedListChanged() in updateLists'); e.preventDefault(); selectList(chosen); } render(){ //option names copied from listCollection keys. there's gotta be a programmatic way to do this, but this is the band-aid/duct-tape/wd-40 for now. // console.log(this.props, 'was this.props in components/selector.js'); let selectedList; this.props.selectedListKey[0] ? selectedList = this.props.selectedListKey[0] : selectedList = undefined ; //NOTE: THIS IS NO LONGER USED, PROBABLY ELLIGIBLE FOR DELITION //COUNTER NOTE:repurposing to general selector list //additional NOTE: need to have select's value based on store //this is done via the selectedList ternary above return( <div id="listSelectorContainer"> <form> <label>Edit List: </label> <select id="listSelector" value={selectedList} onChange={this.selectedListChanged.bind(this, this.props.selectList)} > <option value="undefined">Select</option> <option value="toBeReadList"> To Be Read List</option> <option value="currentlyReadingList"> Currently Reading List</option> <option value="haveReadList"> Have Read List</option> </select> </form> </div> ) } }
frontend/link/disputeverify/Container.js
datoszs/czech-lawyers
import React from 'react'; import {PageHeader} from 'react-bootstrap'; import {Msg, PageTitle} from '../../containers'; import ResultContainer from './ResultContainer'; import CaseButton from './CaseButton'; export default () => ( <section> <PageTitle msg="case.dispute.verify.title" /> <PageHeader><Msg msg="case.dispute.verify.title" /></PageHeader> <ResultContainer /> <CaseButton /> </section> );
src/PageHeader.js
jamon/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const PageHeader = React.createClass({ render() { return ( <div {...this.props} className={classNames(this.props.className, 'page-header')}> <h1>{this.props.children}</h1> </div> ); } }); export default PageHeader;
examples/Aviato/app/components/index.js
jmurzy/react-router-native
/* @noflow */ import React from 'react'; import { View, } from 'react-native'; import { Header, } from 'react-router-native'; import styles from './styles'; export const component = (backgroundColor) => (props) => ( <View style={[styles.component, { backgroundColor }]}> {props.children} </View> ); export const stackHeaderComponent = (backgroundColor) => (props) => { const { scene } = props; const title = String(scene.route.key || ''); return ( <Header {...props} title={title} leftButtonText="Back" style={{ backgroundColor }} /> ); }; export const tabHeaderComponent = (backgroundColor) => (props) => { const { scene } = props; const title = String(scene.route.key || ''); return ( <Header {...props} title={title} style={{ backgroundColor }} /> ); };
frontend/routes.js
StefanKjartansson/drf-react-skeleton
import React from 'react'; import { Router, Route, IndexRoute, hashHistory, Redirect, } from 'react-router'; import ErrorPage from './pages/ErrorPage'; import Home from './pages/Home'; import Login from './pages/Login'; import Master from './master'; import API from 'api'; import Radium from 'radium'; const {Style, StyleRoot} = Radium; import LoginStore, {AuthCheck, UserWrapper} from 'stores/LoginStore'; function createElement(Component, props) { return <UserWrapper Component={Component} API={API} {...props}/>; } export const routes = ( <StyleRoot> <Router history={hashHistory} createElement={createElement}> <Route path="/" component={Master} onEnter={AuthCheck}> <Route path="login" component={Login}/> <IndexRoute component={Home}/> <Route path="*" component={ErrorPage}/> </Route> </Router> </StyleRoot> );
app/components/CopyToClipboard.js
surrealroad/electron-react-boilerplate
// @flow import React, { Component } from 'react'; // import { Link } from 'react-router-dom'; import { Button } from 'hig-react'; export default class CopyToClipboard extends Component { props: { copy: () => void }; render() { const { copy } = this.props; return ( <div> <Button onClick={copy} title="Copy to Clipboard" type="secondary" /> </div> ); } }
app/components/Toggle/index.js
ParAnton/ngps-gui-core
/** * * LocaleToggle * */ import React from 'react'; import Select from './Select'; import ToggleOption from '../ToggleOption'; function Toggle(props) { let content = (<option>--</option>); // If we have items, render them if (props.values) { content = props.values.map((value) => ( <ToggleOption key={value} value={value} message={props.messages[value]} /> )); } return ( <Select value={props.value} onChange={props.onToggle}> {content} </Select> ); } Toggle.propTypes = { onToggle: React.PropTypes.func, values: React.PropTypes.array, value: React.PropTypes.string, messages: React.PropTypes.object, }; export default Toggle;
examples/todos-with-undo/containers/AddTodo.js
naoishii/ohk2016C
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <input ref={node => { input = node }} /> <button onClick={() => { dispatch(addTodo(input.value)) input.value = '' }}> Add Todo </button> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
test/assertions/TreePaneAsserter.js
tomkp/react-tree-pane
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import chai from 'chai'; const expect = chai.expect; import NodeAsserter from './NodeAsserter'; export default class TreePaneAsserter { constructor(jsx) { this.element = document.createElement('div'); ReactDOM.render(jsx, this.element); } findRootNode() { let childNode = this.element.children[0].children[0]; return new NodeAsserter(this, childNode); } }
app/javascript/mastodon/components/load_more.js
KnzkDev/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class LoadMore extends React.PureComponent { static propTypes = { onClick: PropTypes.func, disabled: PropTypes.bool, visible: PropTypes.bool, } static defaultProps = { visible: true, } render() { const { disabled, visible } = this.props; return ( <button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}> <FormattedMessage id='status.load_more' defaultMessage='Load more' /> </button> ); } }
ui/src/js/findTree/TreesFound.js
Dica-Developer/weplantaforest
import counterpart from 'counterpart'; import React, { Component } from 'react'; import { Link } from 'react-router'; export default class TreesFound extends Component { constructor(props) { super(props); this.state = { treeCount: 0, treeWord: '' }; } componentDidMount() { var treeCount = 0; for (var cnt = 0; cnt < this.props.children.length; cnt++) { treeCount = treeCount + this.props.children[cnt].props.content.amount; } if (treeCount > 1) { this.setState({ treeCount: treeCount, treeWord: 'Bäumen' }); } else { this.setState({ treeCount: treeCount, treeWord: 'Baum' }); } } render() { return ( <div className="col-md-12"> <div className="align-center"> <div className="foundTreesHead"> <h1> {counterpart.translate('CERTIFICATE_WORD')}&nbsp;#{this.props.certificateId.replace(/#/gi, '')} </h1> {counterpart.translate('FROM')}:&nbsp;<Link to={'/user/' + encodeURIComponent(this.props.certificate.creator.name)}>{this.props.certificate.creator.name}</Link> <br /> {counterpart.translate('ABOUT_PLANTING')}&nbsp;<span className="bold">{this.state.treeCount}</span>&nbsp;{this.state.treeWord} </div> <div className="text">{this.props.certificate.text}</div> {this.props.children} </div> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
src/components/dashboard/setlist_card.js
jmdelcarmen/gartist
import React, { Component } from 'react'; import { browserHistory } from 'react-router'; import { connect } from 'react-redux'; import actions from '../../actions'; class SetlistCard extends Component { render() { const { _id, artist, performanceDate, songs, venue, comment, thumbnailUrl } = this.props.setlist; return ( <div className="card col-md-4"> <img className="card-img-top" src={thumbnailUrl} alt="" /> <div className="card-block"> <h4 className="card-title text-xs-center">{artist.name}</h4> <hr></hr> <div className="text-xs-center"> <small>{`${venue.name} ${new Date(performanceDate).getFullYear()} - ${new Date(performanceDate).toDateString()}`}</small> </div> </div> <div className="card-block"> <a onClick={() => { this.props.fetchSetlist(_id); browserHistory.push(`/setlists/${_id}/view`); }} className="card-link btn btn-block btn-primary"> View Setlist </a> </div> </div> ); } } export default connect(null, actions)(SetlistCard);
src/container.js
tea-js/chameleon
/** * container组件 */ import React from 'react'; /** * Usage: * import {Container} from 'chameleon'; * * React.createClass({ * render() { * return ( * <Container> * </Container> * ); * } * }); */ export default React.createClass({ getDefaultProps() { return { fluid: false //类用于 100% 宽度,占据全部视口(viewport)的容器 }; }, render() { let fluid = this.props.fluid; return ( <div className={fluid ? 'container-fluid' : 'container'}> {this.props.children} </div> ); } });
clients/components/ProSettings/ProFreeTrial/ProFreeTrial.js
CalderaWP/Caldera-Forms
import React from 'react'; import propTypes from 'prop-types'; import classNames from 'classnames'; import {Button} from 'react'; /** * Create the ProFreeTrial UI * @param {Object} props * @return {*} * @constructor */ export const ProFreeTrial = (props) => { const documentationHref = `https://calderaforms.com/doc/caldera-forms-pro-getting-started/?utm_source=wp-admin&utm_campaign=pro-screen&utm_term=not-connected`; const trialHref = `https://calderaforms.com/checkout?edd_action=add_to_cart&download_id=64101&edd_options[price_id]=1?utm_source=wp-admin&utm_campaign=pro-screen&utm_term=not-connected`; return( <div className={classNames(props.className,ProFreeTrial.classNames.wrapper)} > <p>Ready to try Caldera Forms Pro? Plans start at just 14.99/ month with a 7 day free trial.</p> <div> <a href={documentationHref} target={'_blank'} className={'button'} > Documentation </a> <a target={'_blank'} href={trialHref} className={'button button-primary'} > Start Free Trial </a> </div> </div> ) }; /** * Prop types for the ProFreeTrial component * @type {{}} */ ProFreeTrial.propTypes = { classNames: propTypes.string }; /** * Class names used in ProFreeTrial component * @type {{wrapper: string}} */ ProFreeTrial.classNames = { wrapper: 'caldera-forms-pro-free-trial' }
src/client.js
dieface/react-redux-universal-hot-example
/** * 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 ); }
app/src/components/Folder/FolderPopover.js
GetStream/Winds
import React from 'react'; import PropTypes from 'prop-types'; import Popover from 'react-popover'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import FeedToFolderModal from './FeedToFolderModal'; import Loader from '../Loader'; import { updateFolder } from '../../api/folderAPI'; import { ReactComponent as FolderIcon } from '../../images/icons/folder.svg'; import { ReactComponent as FolderSelectedIcon } from '../../images/icons/folder-select.svg'; class FolderPopover extends React.Component { constructor(props) { super(props); this.state = { folderPopover: false, folderModal: false, loading: false, }; } updateFolder = (targetId) => { if (this.state.loading) return; this.setState({ loading: true }); const currFolder = this.getCurrentFolder(); let data = {}; data[this.props.isRss ? 'rss' : 'podcast'] = this.props.feedID; if (currFolder === targetId) data = { ...data, action: 'remove' }; //todo Update url updateFolder( this.props.dispatch, targetId, data, () => { const url = this.props.history.location.pathname.replace( this.props.match.params.folderID, currFolder === targetId ? 'undefined' : targetId, ); this.props.history.replace(url); this.setState({ loading: false }); this.toggleFolderPopover(); }, () => this.setState({ loading: false }), ); }; toggleFolderModal = () => { this.setState((prevState) => ({ folderModal: !prevState.folderModal })); }; toggleFolderPopover = () => { this.setState((prevState) => ({ folderPopover: !prevState.folderPopover })); }; getCurrentFolder = () => { const folder = this.props.folders.find((folder) => this.isCurrentFolder(folder)); return folder && folder._id; }; isCurrentFolder = (folder) => { for (const feed of folder[this.props.isRss ? 'rss' : 'podcast']) if (this.props.feedID === feed._id) return true; return false; }; render() { const folderPopover = ( <div className="popover-panel feed-popover"> {this.props.folders.map((folder) => ( <div className="panel-element menu-item" key={folder._id} onClick={() => this.updateFolder(folder._id)} > {this.isCurrentFolder(folder) ? ( <FolderSelectedIcon /> ) : ( <FolderIcon /> )} <span>{folder.name}</span> </div> ))} <div className="panel-element menu-item" onClick={this.toggleFolderModal}> <span className="green">Create new folder</span> </div> </div> ); return ( <> <Popover body={folderPopover} isOpen={this.state.folderPopover} onOuterAction={this.toggleFolderPopover} preferPlace="below" tipSize={0.1} > <div onClick={this.toggleFolderPopover}> {this.state.loading ? ( <Loader defaultLoader={false} radius={18} /> ) : ( <FolderIcon /> )} </div> </Popover> <FeedToFolderModal currFolderID={this.getCurrentFolder()} dispatch={this.props.dispatch} feedID={this.props.feedID} history={this.props.history} isOpen={this.state.folderModal} isRss={this.props.isRss} toggleModal={this.toggleFolderModal} /> </> ); } } FolderPopover.defaultProps = { folders: [], }; FolderPopover.propTypes = { folders: PropTypes.array, isRss: PropTypes.bool, feedID: PropTypes.string, dispatch: PropTypes.func.isRequired, history: PropTypes.shape({ location: PropTypes.shape({ pathname: PropTypes.string.isRequired }).isRequired, replace: PropTypes.func.isRequired, }).isRequired, match: PropTypes.shape({ params: PropTypes.shape({ folderID: PropTypes.string }), }), }; const mapStateToProps = (state) => ({ folders: state.folders || [], }); export default withRouter(connect(mapStateToProps)(FolderPopover));
demo/demoFactory/components/groupComponents/Group.js
gearz-lab/redux-autoform
import React from 'react'; import { array, object, string } from 'prop-types'; export default class Group extends React.Component { static propTypes = { component: string, fields: array.isRequired, layout: object.isRequired, componentFactory: object.isRequired }; getComponents = () => { let {layout, componentFactory, fields} = this.props; let components; if (layout.fields) { components = layout.fields.map(field => { let fieldMetadata = fields.find(cp => cp.name === field.name); if (!fieldMetadata) { throw Error(`Could not find field. Field: ${field.name}`); } // in case the field is going to render layouts internally, it's going to need information about the // layout and fields. I'm not sure if this is the best way to do it, probably not. TODO: Review it. fieldMetadata._extra = {layout, fields}; return { data: fieldMetadata, length: layout.fields.length, component: componentFactory.buildFieldComponent(fieldMetadata) } }); } else if (layout.groups) { components = layout.groups.map(group => { return { data: group, length: layout.groups.length, component: componentFactory.buildGroupComponent({ component: group.component, layout: group, fields: fields, componentFactory: componentFactory }) } }); } return components; }; getDefaultSize = (component, gridLength = 12) => { let {layout} = this.props; return layout.orientation == 'horizontal' ? Math.floor(gridLength / component.length) : gridLength; }; getContent = () => { let components = this.getComponents(); return components.map((component, i) => { let componentContent, size = 12; // invisible components should be hidden if (component.data.visible === false) { componentContent = null; } else { size = component.data.size || this.getDefaultSize(component); componentContent = component.component; } return ( <div key={`component-${i}-wrapper`} className={`col-md-${size}`}> { componentContent } </div> ); }); }; getHeader = () => { let {layout} = this.props; if (layout.title) { return ( <header> <span> { layout.title } </span> </header> ); } else { return null; } }; render() { // the passed in layout can contain either fields or groups. // in case it contains 'fields', we're gonna render each of the fields. // in case it contains 'groups', we're gonna render render each group, passing the fields as a parameter try { let content = this.getContent(); let header = this.getHeader(); return ( <section> <div> <div> { header } <div> { content } </div> </div> </div> </section> ); } catch (ex) { return ( <h4> Could not render the MetaFormGroup component. The schema is not valid. </h4> ) } } }
src/client/auth/login.react.js
jaegerpicker/GLDice
import './login.styl'; import * as actions from './actions'; import Component from '../components/component.react'; import React from 'react'; import exposeRouter from '../components/exposerouter.react'; import immutable from 'immutable'; import {focusInvalidField} from '../lib/validation'; import {msg} from '../intl/store'; @exposeRouter class Login extends Component { static propTypes = { auth: React.PropTypes.instanceOf(immutable.Map).isRequired, pendingActions: React.PropTypes.instanceOf(immutable.Map).isRequired, router: React.PropTypes.func }; getForm() { return this.props.auth.get('form'); } onFormSubmit(e) { e.preventDefault(); const fields = this.getForm().fields.toJS(); actions.login(fields) .then(() => { this.redirectAfterLogin(); }) .catch(focusInvalidField(this)); } redirectAfterLogin() { const {router} = this.props; const nextPath = router.getCurrentQuery().nextPath; router.replaceWith(nextPath || 'home'); } render() { const form = this.getForm(); const {pendingActions} = this.props; return ( <div className="login"> <form onSubmit={(e) => this.onFormSubmit(e)}> <fieldset disabled={pendingActions.has(actions.login.toString())}> <legend>{msg('auth.form.legend')}</legend> <input autoFocus name="email" onChange={actions.updateFormField} placeholder={msg('auth.form.placeholder.email')} value={form.fields.email} /> <br /> <input name="password" onChange={actions.updateFormField} placeholder={msg('auth.form.placeholder.password')} type="password" value={form.fields.password} /> <br /> <button children={msg('auth.form.button.login')} type="submit" /> {/* <button type="submit">{msg('auth.form.button.signup')}</button> */} {form.error && <span className="error-message">{form.error.message}</span> } <div>{msg('auth.form.hint')}</div> </fieldset> </form> </div> ); } } export default Login;
actor-apps/app-web/src/app/components/DialogSection.react.js
winiceo/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 ConnectionState from 'components/common/ConnectionState.react'; import DialogStore from 'stores/DialogStore'; import MessageStore from 'stores/MessageStore'; import GroupStore from 'stores/GroupStore'; import DialogActionCreators from 'actions/DialogActionCreators'; // On which scrollTop value start loading older messages const LoadMessagesScrollTop = 100; const initialRenderMessagesCount = 20; const renderMessagesStep = 20; let renderMessagesCount = initialRenderMessagesCount; let lastPeer = null; let lastScrolledFromBottom = 0; const getStateFromStores = () => { const messages = MessageStore.getAll(); let messagesToRender; if (messages.length > renderMessagesCount) { messagesToRender = messages.slice(messages.length - renderMessagesCount); } else { messagesToRender = messages; } return { peer: DialogStore.getSelectedDialogPeer(), messages: messages, messagesToRender: messagesToRender }; }; class DialogSection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); DialogStore.addSelectListener(this.onSelectedDialogChange); MessageStore.addChangeListener(this.onMessagesChange); } componentWillUnmount() { DialogStore.removeSelectListener(this.onSelectedDialogChange); MessageStore.removeChangeListener(this.onMessagesChange); } componentDidUpdate() { this.fixScroll(); this.loadMessagesByScroll(); } render() { const peer = this.state.peer; if (peer) { let isMember = true, memberArea; if (peer.type === PeerTypes.GROUP) { const group = GroupStore.getGroup(peer.id); isMember = DialogStore.isGroupMember(group); } if (isMember) { memberArea = ( <div> <TypingSection/> <ComposeSection peer={this.state.peer}/> </div> ); } else { memberArea = ( <section className="compose compose--disabled row center-xs middle-xs"> <h3>You are not a member</h3> </section> ); } return ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <ConnectionState/> <div className="messages"> <MessagesSection messages={this.state.messagesToRender} peer={this.state.peer} ref="MessagesSection"/> </div> {memberArea} </section> ); } else { return ( <section className="dialog dialog--empty row center-xs middle-xs"> <ConnectionState/> <h2>Select dialog or start a new one.</h2> </section> ); } } fixScroll = () => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); node.scrollTop = node.scrollHeight - lastScrolledFromBottom; } }; onSelectedDialogChange = () => { renderMessagesCount = initialRenderMessagesCount; if (lastPeer != null) { DialogActionCreators.onConversationClosed(lastPeer); } lastPeer = DialogStore.getSelectedDialogPeer(); DialogActionCreators.onConversationOpen(lastPeer); }; onMessagesChange = _.debounce(() => { this.setState(getStateFromStores()); }, 10, {maxWait: 50, leading: true}); loadMessagesByScroll = _.debounce(() => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); let scrollTop = node.scrollTop; lastScrolledFromBottom = node.scrollHeight - scrollTop; if (node.scrollTop < LoadMessagesScrollTop) { DialogActionCreators.onChatEnd(this.state.peer); if (this.state.messages.length > this.state.messagesToRender.length) { renderMessagesCount += renderMessagesStep; if (renderMessagesCount > this.state.messages.length) { renderMessagesCount = this.state.messages.length; } this.setState(getStateFromStores()); } } } }, 5, {maxWait: 30}); } export default DialogSection;
src/svg-icons/device/nfc.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNfc = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/> </SvgIcon> ); DeviceNfc = pure(DeviceNfc); DeviceNfc.displayName = 'DeviceNfc'; DeviceNfc.muiName = 'SvgIcon'; export default DeviceNfc;
assets/node_modules/react-router/es6/IndexLink.js
janta-devs/janta
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
app/components/PlayControl/index.js
scampersand/sonos-front
import React from 'react' import PlayPauseButton from 'components/PlayPauseButton'; import BackButton from 'components/BackButton'; import NextButton from 'components/NextButton'; import styles from './styles.css'; export default function PlayControl(props) { return ( <div className={styles.playControl}> <BackButton onClick={props.onBackClicked} /> <PlayPauseButton transportState={props.transportState} onPlayClicked={props.onPlayClicked} onPauseClicked={props.onPauseClicked} /> <NextButton onClick={props.onNextClicked} /> </div> ); }