path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/disco/routes.js
mstriemer/addons-frontend
import React from 'react'; import { Router, Route } from 'react-router'; import App from './containers/App'; import DiscoPane from './containers/DiscoPane'; export default ( <Router component={App}> <Route path="/:lang/firefox/discovery/pane/:version/:platform/:compatibilityMode" component={DiscoPane} /> </Router> );
src/svg-icons/device/signal-cellular-1-bar.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M12 12L2 22h10z"/> </SvgIcon> ); DeviceSignalCellular1Bar = pure(DeviceSignalCellular1Bar); DeviceSignalCellular1Bar.displayName = 'DeviceSignalCellular1Bar'; DeviceSignalCellular1Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular1Bar;
components/AppFooter.js
Meadowcottage/meadowcottagexyz
import React from 'react' import { BounceUp } from 'animate-components' export default class AppFooter extends React.Component { render () { return ( <BounceUp as='div' duration='2s' className='appFooter'> <a href='https://github.com/meadowcottage/meadowcottagexyz'> <i className='fa fa-code' /> made with <i className='fa fa-heart' /> </a> </BounceUp> ) } }
src/components/AddConfig/AddConfig.js
TheModevShop/craft-app
import React from 'react'; import {browserHistory} from 'react-router'; import _ from 'lodash'; import formIsComplete from 'utility/formIsComplete'; import AddConfigForm from 'components/Forms/AddConfigForm'; import './add-config.less'; class AddConfig extends React.Component { constructor(...args) { super(...args); this.state = { form: new AddConfigForm({ onChange: (e) => { this.forceUpdate(); }, controlled: true, initial: {distribution_platform: 'encompass'} }) }; } render() { const error = this.state.error; const isValid = formIsComplete(this.state.form); return ( <div className="add-config-wrapper card"> <h2 className="card-title">Connect A Report</h2> <form onSubmit={this.onSubmit.bind(this)} className={isValid ? 'valid' : ''}> {this.state.form.render(this.props, this.state, error)} </form> </div> ); } async onSubmit(e) { e.preventDefault(); const form = this.state.form; if (form.validate()) { const data = form.cleanedData; this.setState({loading: true}); const config = await this.props.submitConfig(data, this.props.membership.membership_id, this.props.redirect ? 'redirect' : ''); this.setState({loading: false}); if (config) { if (this.props.hideForm) { this.props.hideForm(); } } else { this.setState({error: 'There was an error'}); } } } } AddConfig.propTypes = { }; export default AddConfig;
votrfront/js/coursesStats.js
fmfi-svt/votr
import React from 'react'; var ZNAMKY = {'A': 1, 'B': 1.5, 'C': 2, 'D': 2.5, 'E': 3, 'F': 4}; export function coursesStats(hodnotenia) { var result = {}; ['zima', 'leto', 'spolu'].forEach((type) => { result[type] = { count: 0, creditsEnrolled: 0, creditsObtained: 0 }; }); function add(type, credits, obtained) { result[type].count++; result[type].creditsEnrolled += credits; result[type].creditsObtained += obtained ? credits : 0; } hodnotenia.forEach((row) => { var credits = parseInt(row.kredit); var obtained = row.hodn_znamka && row.hodn_znamka[0] !== 'F'; add('spolu', credits, obtained); if (row.semester == 'Z') add('zima', credits, obtained); if (row.semester == 'L') add('leto', credits, obtained); }); return result; }; export function weightedStudyAverage(hodnotenia) { var weightedSum = 0; var creditsSum = 0; hodnotenia.forEach((row) => { var value = ZNAMKY[row.hodn_znamka[0]]; if (value) { weightedSum += value * parseInt(row.kredit); creditsSum += parseInt(row.kredit); } }); if (creditsSum == 0) return null; return weightedSum / creditsSum; }; export function renderWeightedStudyAverage(hodnotenia) { var average = weightedStudyAverage(hodnotenia); if (average === null) return null; return <span title="Neoficiálny vážený študijný priemer z doteraz ohodnotených predmetov">{average.toFixed(2)}</span> }; export function renderCredits({ creditsObtained, creditsEnrolled }) { return creditsObtained && creditsObtained != creditsEnrolled ? `${creditsObtained}/${creditsEnrolled}` : `${creditsEnrolled}`; } export function currentAcademicYear() { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; if (month < 8) { return (year - 1) + '/' + year; } else { return year + '/' + (year + 1); } };
src/client/components/Radial.react.js
SteveStrongBAH/DataLiftDesktop
import React from 'react'; import classNames from 'classnames'; var Radial = React.createClass({ render: function () { var percentage; if ((this.props.progress !== null && this.props.progress !== undefined) && !this.props.spin && !this.props.error) { percentage = ( <div className="percentage"></div> ); } else { percentage = <div></div>; } var classes = classNames({ 'radial-progress': true, 'radial-spinner': this.props.spin, 'radial-negative': this.props.error, 'radial-thick': this.props.thick || false, 'radial-gray': this.props.gray || false, 'radial-transparent': this.props.transparent || false }); return ( <div className={classes} data-progress={this.props.progress}> <div className="circle"> <div className="mask full"> <div className="fill"></div> </div> <div className="mask half"> <div className="fill"></div> <div className="fill fix"></div> </div> <div className="shadow"></div> </div> <div className="inset"> {percentage} </div> </div> ); } }); module.exports = Radial;
src/forms/CurrentExpenses.js
shp54/cliff-effects
// REACT COMPONENTS import React from 'react'; import { Form, Radio, Checkbox, Header, } from 'semantic-ui-react'; // PROJECT COMPONENTS import { FormPartsContainer, FormHeading, IntervalColumnHeadings, CashFlowRow, ControlledRadioYesNo, } from './formHelpers'; import { ContractRentField, RentShareField, PlainRentRow, } from './rentFields'; import CashFlowRowAfterConfirm from './CashFlowRowAfterConfirm'; // COMPONENT HELPER FUNCTIONS import { getTimeSetter } from '../utils/getTimeSetter'; // LOGIC import { getEveryMember, isHeadOrSpouse, getDependentMembers, isDisabled, isUnder13, } from '../utils/getMembers'; // ======================================== // COMPONENTS // ======================================== const Utilities = function ({ current, type, time, setClientProperty }) { let climate = current.climateControl, electricity = current.nonHeatElectricity, phone = current.phone, fuelAssist = current.fuelAssistance; let setChecked = function (evnt, inputProps) { var obj = { ...inputProps, value: inputProps.checked }; setClientProperty(evnt, obj); }; // End setChecked() return ( <div> <Header as='h4'>Which of these utilities do you pay for?</Header> <Checkbox name={ 'climateControl' } label={ 'Heating or cooling (e.g. A/C during summer)' } checked={ climate } onChange={ setChecked } /> <br /> <Checkbox name={ 'nonHeatElectricity' } label={ 'Electricity for non-heating purposes' } checked={ electricity } onChange={ setChecked } /> <br /> <Checkbox name={ 'phone' } label={ 'Telephone service' } checked={ phone } onChange={ setChecked } /> <br /> <br /> <ControlledRadioYesNo labelText = { 'Do you get Fuel Assistance?' } checked = { fuelAssist } name = { 'fuelAssistance' } onChange = { setClientProperty } /> </div> ); }; // End Utilities(<>) const HousingDetails = function ({ current, type, time, setClientProperty }) { let housing = current.housing, sharedProps = { timeState: current, current: current, type: type, time: time, setClientProperty: setClientProperty, }; if (current.housing === 'voucher') { return ( <div> <ContractRentField { ...sharedProps } /> <RentShareField { ...sharedProps } /> <Utilities { ...sharedProps } /> </div> ); } else if (housing === 'homeless') { return null; } else if (housing === 'renter') { return ( <div> <br /> <PlainRentRow { ...sharedProps } /> <Utilities { ...sharedProps } /> </div> ); } else if (housing === 'homeowner') { return ( <div> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic={ 'mortgage' }> Mortgage </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'housingInsurance' }> Insurance Costs </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'propertyTax' }> Property Tax </CashFlowRow> <Utilities { ...sharedProps } /> </div> ); } // end which expenses }; // End HousingDetails(<>) const HousingRadio = function ({ currentValue, label, time, setClientProperty }) { var value = label.toLowerCase(); return ( <Form.Field> <Radio name={ 'housing' } label={ label } value={ value } checked={ currentValue === value } onChange={ setClientProperty } /> </Form.Field> ); }; // End HousingRadio(<>) /** * @function * @param {object} props * @param {object} props.current - Client data of current user circumstances * @param {string} props.type - 'expense' or 'income', etc., for classes * @param {string} props.time - 'current' or 'future' * @param {function} props.setClientProperty - Sets state values * * @returns React element */ const Housing = function ({ current, type, time, setClientProperty }) { // We're using a bunch of radio buttons. Since `checked` is defined // in Radio components, `setClientProperty()` would store it, but we // want the value, so get rid of checked. /** Makes sure values are propagated to 'current' properties if needed. */ let ensureRouteAndValue = function (evnt, inputProps) { var obj = { ...inputProps, name: inputProps.name, value: inputProps.value, checked: null }; setClientProperty(evnt, obj); }; let sharedProps = { current: current, type: type, time: time, setClientProperty: ensureRouteAndValue, }; return ( <div> <FormHeading>Housing</FormHeading> { current.housing === 'voucher' ? null : <div> <Header as='h4'>What is your housing situation?</Header> <HousingRadio currentValue={ current.housing } label={ 'Homeless' } time={ time } setClientProperty={ ensureRouteAndValue } /> <HousingRadio currentValue={ current.housing } label={ 'Renter' } time={ time } setClientProperty={ ensureRouteAndValue } /> <HousingRadio currentValue={ current.housing } label={ 'Homeowner' } time={ time } setClientProperty={ ensureRouteAndValue } /> </div>} <HousingDetails { ...sharedProps } /> </div> ); }; // End Housing() /** * @function * @param {object} props * @param {object} props.current - Client data of current user circumstances * @param {object} props.time - 'current' or 'future' * @param {object} props.setClientProperty - Sets state values * * @returns React element */ const ExpensesFormContent = function ({ current, time, setClientProperty }) { let type = 'expense', household = current.household, sharedProps = { timeState: current, type: type, time: time, setClientProperty: setClientProperty }; /** @todo Make an age-checking function to * keep household data structure under * control in one place. */ var isOver12 = function (member) { return !isUnder13(member); }; // Won't include head or spouse var allDependents = getDependentMembers(household), under13 = getEveryMember(allDependents, isUnder13), over12 = getEveryMember(allDependents, isOver12); // 'Elderly' here is using the lowest common denominator - SNAP standards. var isElderlyOrDisabled = function (member) { return isDisabled(member) || member.m_age >= 60; }; var elderlyOrDisabled = getEveryMember(household, isElderlyOrDisabled), elderlyOrDisabledHeadOrSpouse = getEveryMember(elderlyOrDisabled, isHeadOrSpouse); return ( <div className='field-aligner two-column'> { under13.length > 0 ? <div> <FormHeading subheading = { 'A "child" is a person 12 or younger. Don\'t include amounts that are paid for by other benefit programs.\n' }> Reasonable Unreimbursed Non-Medical Child(ren) Care </FormHeading> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic={ 'childDirectCare' }> Direct care costs </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'childBeforeAndAfterSchoolCare' }> Before- and after-school care </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'childTransportation' }> Transportation costs </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'childOtherCare' }> Other care </CashFlowRow> <CashFlowRowAfterConfirm { ...sharedProps } generic={ 'earnedBecauseOfChildCare' } confirmLabel={ 'Does childcare allow you to make additional income?' }> <span style={{ textDecoration: 'underline' }}>Income</span> made possible by child care expenses </CashFlowRowAfterConfirm> </div> : null } { current.hasSnap ? <div> <FormHeading>Child Support</FormHeading> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic={ 'childSupportPaidOut' }> <strong>Legally obligated</strong> child support </CashFlowRow> </div> : null } {/* Head or spouse can't be a dependent, so they don't count. */} { over12.length > 0 ? <div> <FormHeading subheading = { 'For the care of people who are older than 12, but are still dependents (those under 18 or disabled). Don\'t include amounts that are paid for by other benefit programs.\n' }> Dependent Care of Persons Over 12 Years of Age </FormHeading> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic={ 'adultDirectCare' }> Direct care costs </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'adultTransportation' }> Transportation costs </CashFlowRow> <CashFlowRow { ...sharedProps } generic={ 'adultOtherCare' }> Other care </CashFlowRow> </div> : null } { elderlyOrDisabled.length > 0 ? <div> <FormHeading>Unreimbursed Disabled/Handicapped/Elderly Assistance</FormHeading> <div>Unreimbursed expenses to cover care attendants and auxiliary apparatus for any family member who is elderly or is a person with disabilities. Auxiliary apparatus are items such as wheelchairs, ramps, adaptations to vehicles, or special equipment to enable a blind person to read or type, but only if these items are directly related to permitting the disabled person or other family member to work.</div> <div>Examples of eligible disability assistance expenses:</div> <ul> <li>The payments made on a motorized wheelchair for the 42 year old son of the head of household enable the son to leave the house and go to work each day on his own. Prior to the purchase of the motorized wheelchair, the son was unable to make the commute to work. These payments are an eligible disability assistance expense.</li> <li>Payments to a care attendant to stay with a disabled 16-year-old child allow the child’s mother to go to work every day. These payments are an eligible disability assistance allowance.</li> </ul> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic={ 'disabledAssistance' }> Disabled/Handicapped assistance </CashFlowRow> <CashFlowRowAfterConfirm { ...sharedProps } generic={ 'earnedBecauseOfAdultCare' } confirmLabel={ 'Do assistance expenses allow you to make additional income?' }> <span style={{ textDecoration: 'underline' }}>Income</span> made possible by assistance expenses </CashFlowRowAfterConfirm> </div> : null } {/** These medical expenses don't count for Section 8 unless * the disabled person is the head or spouse. From * {@link http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf} * Appendix B, item (D) */} { elderlyOrDisabledHeadOrSpouse.length > 0 || (current.hasSnap && elderlyOrDisabled.length > 0) ? <div> <FormHeading>Unreimbursed Medical Expenses</FormHeading> <div>Do not repeat anything you already listed in the section above. Examples of allowable medical expenses:</div> <ul> <li>The orthodontist expenses for a child’s braces.</li> <li>Services of doctors and health care professionals.</li> <li>Services of health care facilities.</li> <li>Medical insurance premiums. </li> <li>Prescription/non-prescription medicines (prescribed by a physician).</li> <li>Transportation to treatment (cab fare, bus fare, mileage).</li> <li>Dental expenses, eyeglasses, hearing aids, batteries.</li> <li>Live-in or periodic medical assistance.</li> <li>Monthly payment on accumulated medical bills (regular monthly payments on a bill that was previously incurred).</li> </ul> <IntervalColumnHeadings type={ type } /> <CashFlowRow { ...sharedProps } generic='disabledMedical'> Disabled/Elderly medical expenses </CashFlowRow> <CashFlowRow { ...sharedProps } generic='otherMedical'> Medical expenses of other members </CashFlowRow> </div> : null } <Housing current={ current } time={ time } type={ type } setClientProperty={ setClientProperty } /> </div> ); }; // End ExpensesFormContent() /** * @todo SNAP: Does a medical assistant's payments count as a medical expense? * (Answer: Yes. @see {@link https://www.mass.gov/service-details/snap-verifications}) * @todo SNAP: Medical expense only matters if household has elder/disabled, but * are they any medical expenses or only those of the disabled person? "Medical * Expenses for Disabled or Elderly". Also, do they sometimes need to * enter medical expenses even if they don't have an elderly or disabled * household member? */ /** * @function * @param {object} props * @param {function} props.changeClient - Setting client state * @param {function} props.previousStep - Go to previous form step * @param {function} props.nextStep - Go to next form step * @param {object} props.client - Object will all the data for calculating benefits * * @returns React element */ // `props` is a cloned version of the original props. References broken. const CurrentExpensesStep = function ({ changeClient, previousStep, nextStep, client }) { const setTimeProp = getTimeSetter('current', changeClient); return ( <Form className = 'expense-form flex-item flex-column'> <FormPartsContainer title = { 'Current Household Expenses' } clarifier = { null } left = {{ name: 'Previous', func: previousStep }} right = {{ name: 'Next', func: nextStep }}> <ExpensesFormContent setClientProperty={ setTimeProp } current={ client.current } time={ 'current' } /> </FormPartsContainer> </Form> ); }; // End CurrentExpensesStep() export { CurrentExpensesStep };
pkg/interface/chat/src/js/components/lib/icons/icon-spinner.js
jfranklin9000/urbit
import React, { Component } from 'react'; export class Spinner extends Component { render() { let classes = !!this.props.classes ? this.props.classes : ""; let text = !!this.props.text ? this.props.text : ""; let awaiting = !!this.props.awaiting ? this.props.awaiting : false; if (awaiting) { return ( <div className={classes + " z-2 bg-white bg-gray0-d white-d"}> <img className="invert-d spin-active v-mid" src="/~chat/img/Spinner.png" width={16} height={16} /> <p className="dib f9 ml2 v-mid inter">{text}</p> </div> ); } else { return null; } } }
lib/components/bundles.js
conveyal/scenario-editor
// @flow import Icon from '@conveyal/woonerf/components/icon' import React from 'react' import type {Children} from 'react' import {Application, Dock, Title} from './base' export default function Bundles ({children}: {children?: Children}) { return ( <Application> <Title><Icon type='database' /> GTFS Bundles</Title> <Dock>{children}</Dock> </Application> ) }
frontend/modules/browse/containers/Browse.js
RyanNoelk/OpenEats
import React from 'react' import PropTypes from 'prop-types' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import queryString from 'query-string' import { injectIntl } from 'react-intl'; import history from '../../common/history' import Search from '../components/Search' import * as SearchActions from '../actions/SearchActions' import * as FilterActions from '../actions/FilterActions' import DefaultFilters from '../constants/DefaultFilters' import documentTitle from '../../common/documentTitle' class Browse extends React.Component { componentDidMount() { documentTitle(this.props.intl.messages['nav.recipes']); this.reloadData(queryString.parse(this.props.location.search)) } componentWillUnmount() { documentTitle(); } componentWillReceiveProps(nextProps) { let query = queryString.parse(this.props.location.search); let nextQuery = queryString.parse(nextProps.location.search); if (query.offset !== nextQuery.offset) { this.reloadData(nextQuery); } else if (query.limit !== nextQuery.limit) { this.reloadData(nextQuery); } else if (query.ordering !== nextQuery.ordering) { this.reloadData(nextQuery); } else if (query.offset !== nextQuery.offset) { this.reloadData(nextQuery); } else if (query.course !== nextQuery.course) { this.reloadData(nextQuery); } else if (query.cuisine !== nextQuery.cuisine) { this.reloadData(nextQuery); } else if (query.rating !== nextQuery.rating) { this.reloadData(nextQuery); } else if (query.search !== nextQuery.search) { this.reloadData(nextQuery); } } reloadData(qs) { window.scrollTo(0, 0); if (!this.props.search.results[queryString.stringify(this.mergeDefaultFilters(qs))]) { this.props.searchActions.loadRecipes(this.mergeDefaultFilters(qs)); } if (!this.props.courses.results[queryString.stringify(this.mergeDefaultFilters(qs))]) { this.props.filterActions.loadCourses(this.mergeDefaultFilters(qs)); } if (!this.props.cuisines.results[queryString.stringify(this.mergeDefaultFilters(qs))]) { this.props.filterActions.loadCuisines(this.mergeDefaultFilters(qs)); } if (!this.props.ratings.results[queryString.stringify(this.mergeDefaultFilters(qs))]) { this.props.filterActions.loadRatings(this.mergeDefaultFilters(qs)); } } doSearch = (value) => { let qs = queryString.parse(this.props.location.search); value !== "" ? qs['search'] = value : delete qs['search']; let str = queryString.stringify(qs); str = str ? '/browse/?' + str : '/browse/'; history.push(str); }; buildUrl = (name, value, multiSelect=false) => { if (!name) return '/browse/'; let qs = queryString.parse(this.props.location.search); delete qs['offset']; if (value !== "") { if (qs[name] && multiSelect) { let query = qs[name].split(','); if (query.includes(value.toString())) { if (query.length === 1) { delete qs[name]; } else { let str = ''; query.map(val => { val != value ? str += val + ',' : ''}); qs[name] = str.substring(0, str.length - 1); } } else { qs[name] = qs[name] + ',' + value; } } else { qs[name] = value; } } else { delete qs[name]; } let str = queryString.stringify(qs); return str ? '/browse/?' + str : '/browse/'; }; mergeDefaultFilters = (query) => { let filter = {}; if (Object.keys(DefaultFilters).length > 0) { for (let key in DefaultFilters) { filter[key] = DefaultFilters[key]; } } if (Object.keys(query).length > 0) { for (let key in query) { filter[key] = query[key]; } } return filter }; render() { const qs = queryString.parse(this.props.location.search); const qsString = queryString.stringify(this.mergeDefaultFilters(qs)); return ( <Search { ...this.props } qs={ qs } qsString={ qsString } doSearch={ this.doSearch } buildUrl={ this.buildUrl } defaultFilters={ DefaultFilters } /> ) } } Browse.propTypes = { search: PropTypes.object.isRequired, courses: PropTypes.object.isRequired, cuisines: PropTypes.object.isRequired, ratings: PropTypes.object.isRequired, location: PropTypes.object.isRequired, filterActions: PropTypes.object.isRequired, searchActions: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ search: state.browse.search, courses: state.browse.filters.courses, cuisines: state.browse.filters.cuisines, ratings: state.browse.filters.ratings, }); const mapDispatchToProps = (dispatch, props) => ({ filterActions: bindActionCreators(FilterActions, dispatch), searchActions: bindActionCreators(SearchActions, dispatch), }); export default injectIntl(connect( mapStateToProps, mapDispatchToProps )(Browse));
template/src/index.js
peterbrinck/pb-react-scripts
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import store from './store'; import App from './App'; import NotFound from './views/NotFound'; ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={App} title="App"/> <Route path="/cases" component={Cases} title="Cases"/> <Route path="*" component={NotFound}/> </Route> </Router> </Provider>, document.getElementById('root') );
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
ONode/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import classnames from 'classnames'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onSelect: React.PropTypes.func, member: React.PropTypes.bool }; constructor(props) { super(props); } onSelect = () => { this.props.onSelect(this.props.contact); }; render() { const contact = this.props.contact; const contactClassName = classnames('contacts__list__item row', { 'contacts__list__item--member': this.props.member }); let controls; if (!this.props.member) { controls = <a className="material-icons" onClick={this.onSelect}>person_add</a>; } else { controls = <i className="material-icons">check</i>; } return ( <li className={contactClassName}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> {controls} </div> </li> ); } } export default ContactItem;
src/components/Header/CustomMenuItem.js
kritikasoni/smsss-react
import React from 'react'; import { LinkContainer } from 'react-router-bootstrap'; import MenuItem from 'react-bootstrap/lib/MenuItem'; import classes from './Tab.scss' export const CustomMenuItem = (props) => ( <LinkContainer to={props.to}> <MenuItem> {props.name} </MenuItem> </LinkContainer> ); export default CustomMenuItem;
fields/types/textarea/TextareaField.js
wmertens/keystone
import Field from '../Field'; import React from 'react'; module.exports = Field.create({ displayName: 'TextareaField', renderField () { var styles = { height: this.props.height, }; return <textarea name={this.props.path} styles={styles} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" className="FormInput" />; }, });
dist/lib/carbon-fields/assets/js/fields/components/radio-image/index.js
ArtFever911/statrer-kit
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { setStatic } from 'recompose'; /** * The internal dependencies. */ import Field from 'fields/components/field'; import { enhance } from 'fields/components/radio'; import { TYPE_RADIO_IMAGE } from 'fields/constants'; /** * Render a radio input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Function} props.handleChange * @param {Function} props.isChecked * @return {React.Element} */ export const RadioImageField = ({ name, field, handleChange, isChecked }) => { return <Field field={field}> <div className="carbon-radio-image-list"> { field.options.map((option, index) => ( <div key={index} className="carbon-radio-image-item"> <label> <input type="radio" name={name} value={option.value} checked={isChecked(option)} disabled={!field.ui.is_visible} onChange={handleChange(option)} {...field.attributes} /> <figure className="carbon-radio-image-holder"> <img src={option.name} /> </figure> </label> </div> )) } </div> </Field>; }; /** * Validate the props. * * @type {Object} */ RadioImageField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ attributes: PropTypes.object, options: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), })), }), handleChange: PropTypes.func, }; export default setStatic('type', [ TYPE_RADIO_IMAGE, ])(enhance(RadioImageField));
src/components/common/svg-icons/social/notifications-off.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialNotificationsOff = (props) => ( <SvgIcon {...props}> <path d="M20 18.69L7.84 6.14 5.27 3.49 4 4.76l2.8 2.8v.01c-.52.99-.8 2.16-.8 3.42v5l-2 2v1h13.73l2 2L21 19.72l-1-1.03zM12 22c1.11 0 2-.89 2-2h-4c0 1.11.89 2 2 2zm6-7.32V11c0-3.08-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68c-.15.03-.29.08-.42.12-.1.03-.2.07-.3.11h-.01c-.01 0-.01 0-.02.01-.23.09-.46.2-.68.31 0 0-.01 0-.01.01L18 14.68z"/> </SvgIcon> ); SocialNotificationsOff = pure(SocialNotificationsOff); SocialNotificationsOff.displayName = 'SocialNotificationsOff'; SocialNotificationsOff.muiName = 'SvgIcon'; export default SocialNotificationsOff;
src/components/Home.js
vsherms/LifeCoach
import React from 'react'; import { Jumbotron, Well, Col, Row } from 'react-bootstrap'; import { inject, observer } from 'mobx-react'; import { LinkContainer } from 'react-router-bootstrap'; import HomeWheel from './HomeWheel'; import HomeGoals from './HomeGoals'; class Home extends React.Component{ constructor(){ super(); } componentDidMount() { this.props.wheelStore.loadWheelsFromServer(this.props.userStore.userId); this.props.goalStore.loadGoalsFromServer(this.props.userStore.userId); } render(){ return ( <div className="parent"> <div className="container"> <h1 className="welcome-header">Welcome, {this.props.userStore.firstName}! </h1> <Col md={2}/> <Col md={8}> <LinkContainer to={{pathname: '/wheel'}}> <div className="home-well" id="well1"> <div> <i className="fa fa-pie-chart fa-5x icon1" aria-hidden="true"></i> </div> <div className= "description"> <h1 className= "home-title"> <strong>THE WHEEL OF LIFE</strong> </h1> <h3>Rate your current standing in eight essential life categories.</h3> </div> </div> </LinkContainer> <LinkContainer to={{pathname: '/lifegoals'}}> <div className="home-well" id="well2"> <div> <i className="fa fa-heart fa-5x icon2" aria-hidden="true"></i> </div> <div className= "description"> <h1 className= "home-title"> <strong>GOALS</strong> </h1> <h3>Set and organize goals for yourself based on which areas you would like to work on.</h3> </div> </div> </LinkContainer> <LinkContainer to={{pathname: '/history'}}> <div className="home-well" id="well3"> <div> <i className="fa fa-database fa-5x icon3" aria-hidden="true"></i> </div> <div className= "description"> <h1 className= "home-title"> <strong>HISTORY</strong> </h1> <h3>Keep track of your progress over time. </h3> </div> </div> </LinkContainer> </Col> <Col md={2}/> </div> </div> ); } } Home.propTypes={ userStore: React.PropTypes.object, wheelStore: React.PropTypes.object, goalStore: React.PropTypes.object }; export default inject('userStore', 'wheelStore', 'goalStore')(observer(Home));
packages/datagrid/src/components/DefaultCellRenderer/DefaultCellRenderer.component.js
Talend/ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { SkeletonParagraph } from '@talend/design-system'; import { AVRO_TYPES } from '../../constants'; import DATAGRID_PROPTYPES from '../DataGrid/DataGrid.proptypes'; import QualityIndicator from './QualityIndicator.component'; import AvroRenderer from './AvroRenderer.component'; import theme from './DefaultCell.scss'; export const CELL_RENDERER_COMPONENT = 'cellRenderer'; function convertValue(value) { if (!value.toJS) { return value; } return value.toJS(); } function DefaultCellRenderer({ avroRenderer, colDef, value, data }) { let content; const plainValue = convertValue(value); if (data.loaded === false) { content = <SkeletonParagraph size="M" />; } else { content = [ <QualityIndicator key="2" qualityIndex={plainValue.quality} />, <AvroRenderer key="3" colDef={colDef} data={plainValue} avroRenderer={avroRenderer} />, ]; } return ( <div aria-label={value.value} className={classNames(theme['td-cell'], 'td-cell')}> {content} </div> ); } DefaultCellRenderer.defaultProps = { value: {}, data: {}, }; DefaultCellRenderer.propTypes = { avroRenderer: DATAGRID_PROPTYPES.avroRenderer, colDef: PropTypes.shape({ avro: PropTypes.shape({ type: PropTypes.shape({ type: PropTypes.oneOf(AVRO_TYPES), }), }), }), value: PropTypes.object, data: PropTypes.object, }; DefaultCellRenderer.theme = theme; export default DefaultCellRenderer;
src/components/App/setViewport.js
yousefmoazzam/ZebraWithFlux
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import { canUseDOM } from 'react/lib/ExecutionEnvironment'; function setViewport(ComposedComponent) { return class AppViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : {width: 1366, height: 768} // Default size for server-side rendering }; this.handleResize = () => { let viewport = {width: window.innerWidth, height: window.innerHeight}; if (this.state.viewport.width !== viewport.width || this.state.viewport.height !== viewport.height) { this.setState({viewport: viewport}); } }; } componentDidMount() { window.addEventListener('resize', this.handleResize); window.addEventListener('orientationchange', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); window.removeEventListener('orientationchange', this.handleResize); } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } }; } export default setViewport;
src/svg-icons/action/assessment.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssessment = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/> </SvgIcon> ); ActionAssessment = pure(ActionAssessment); ActionAssessment.displayName = 'ActionAssessment'; ActionAssessment.muiName = 'SvgIcon'; export default ActionAssessment;
src/components/LoginCallback/LoginCallback.js
City-of-Helsinki/helerm-ui
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router'; import Loader from '../Loader'; export class LoginCallback extends React.Component { componentDidMount() { this.props.handleCallback() } render () { const {isInitialized} = this.props if (!isInitialized) { return ( <div> <h3>Hetkinen, tarkistetaan kirjautumistietoja...</h3> <Loader show={true} /> </div> ); } return ( <Redirect to='/' /> ); } }; LoginCallback.propTypes = { handleCallback: PropTypes.func.isRequired, isInitialized: PropTypes.bool.isRequired, isAuthenticated: PropTypes.bool.isRequired, logout: PropTypes.func.isRequired, user: PropTypes.object.isRequired, }; export default LoginCallback;
docs/src/components/Home/Preface/Preface.js
seekinternational/seek-asia-style-guide
import React from 'react'; import { PageBlock, Section, Columns, Text } from 'seek-asia-style-guide/react'; export default () => ( <PageBlock> <Section header> <Text screaming>A principled design process</Text> </Section> <Section> <Text waving regular>SEEK have developed 10 principles that describe the fundamental goals the design team consider when applying their minds to new design challenges or refining existing work. Their purpose is to enable the creation of content that will assist our users to complete tasks easily and hopefully enjoy the experience.</Text> </Section> <Columns> <div> <Section> <Text strong>Design with empathy</Text> <Text>Understand our customers and end users better than they understand themselves.</Text> </Section> <Section> <Text strong>A Seek interaction is transparent, honest and trustworthy</Text> <Text>A user experience at Seek should be true to the brand & true to how people want to be treated. “If we want users to like our software, we should design it to behave like a likeable person.” – Alan Cooper</Text> </Section> <Section> <Text strong>Use persuasive design to achieve business goals</Text> <Text>It is not enough that our design is usable, it should be used in a way that encourages users towards the goals of SEEK. A registered user action is more valuable than an anonymous one, a searchable profile is more useful than a hidden one.</Text> </Section> <Section> <Text strong>Content is king</Text> <Text>A person’s focus should be on their content, not on the UI. Help people work without interference.</Text> </Section> </div> <div> <Section> <Text strong>Simplicity is powerful</Text> <Text>A minimalist form and function keeps users focused on their goals without distraction. It improves on-screen responsiveness as well as being suited to small-screen implementations.</Text> </Section> <Section> <Text strong>Data informs design</Text> <Text>“One accurate measurement is worth more than a thousand expert opinions.” – Grace Hopper</Text> </Section> <Section> <Text strong>Consistency matters</Text> <Text>Appearance follows behaviour (Form follows function). Designed elements should look like they behave—someone should be able to predict how an interface element will behave merely by looking at it. Embrace consistency, but not homogeneity. If something looks the same it should always act the same.</Text> </Section> <Section> <Text strong>Accessible design is good design</Text> <Text>In principle Seek design should be usable on all devices by all of the people in all situations. Design is simple, touch friendly and clear and aims for AA accessibility.</Text> </Section> </div> <div> <Section> <Text strong>Make it mine</Text> <Text>The jobseeking experience is highly personal one that takes place over extended periods of time. The experience should align to the way that users conduct their jobseeking, allowing them to continue where they left off.</Text> </Section> <Section> <Text strong>Don’t make users think</Text> <Text>Observation shows that users do not read instructions. Interactions should be task focused, eliminating decision points and generally use one clear call to action.</Text> </Section> </div> </Columns> </PageBlock> );
src/components/SvgLine/SvgLine/SvgLine.js
easingthemes/notamagic
import React from 'react'; /** * React component implementation. * * @author dfilipovic * @namespace ReactApp * @class SvgLine * @extends ReactApp */ export class SvgLine extends React.Component { // ------------------------------------------------------------------------------------------------------------------ // React methods // ------------------------------------------------------------------------------------------------------------------ /** * * Set the initial state * * @private */ constructor (props) { super(props); this.state = {}; } /** * When component is mounted add the Change event listeners and get initial data * * @method componentDidMount * @returns void * @public */ componentDidMount () { } // ------------------------------------------------------------------------------------------------------------------ // Render methods // ------------------------------------------------------------------------------------------------------------------ /** * Renders the component * * @method render * @returns {XML} * @public */ render () { const svgTag = ` <svg id="svgLine" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="300" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2000 250" preserveAspectRatio="xMinYMax" > <polygon points="-150,300 200,90 550,140 800,60 1100,150 1400,100 1700,10 1900,50 2500,90 2500,300" fill="url(#BglinierGradient)" stroke="none" > </polygon> <polyline points="-150,244 200,90 550,140 800,60 1100,150 1400,100 1700,10 1900,50 2500,90 2500,500" fill="none" stroke="#7668af" stroke-width="0" > </polyline> <text x="170" y="20" fill="#8b949b" style="font-size: 120%; font-weight: 400;">Days on the project</text> <text x="170" y="60" fill="#5cb85c" style="font-size: 250%; font-weight: 300;">279</text> <text x="510" y="60" fill="#8b949b" style="font-size: 120%; font-weight: 400;">Components (Wrappers)</text> <text x="520" y="100" fill="#5f6467" style="font-size: 250%; font-weight: 300;">27</text> <text x="760" y="0" fill="#8b949b" style="font-size: 120%; font-weight: 400;">Commits</text> <text x="760" y="40" fill="#b2cc71" style="font-size: 250%; font-weight: 300;">1 183</text> <text x="1060" y="70" fill="#8b949b" style="font-size: 120%; font-weight: 400;">Lines of code</text> <text x="1060" y="110" fill="#3c88c6" style="font-size: 250%; font-weight: 300;">288 952</text> <text x="1350" y="30" fill="#8b949b" style="font-size: 120%; font-weight: 400;">Juniors OnBoarded</text> <text x="1350" y="70" fill="#1abc9c" style="font-size: 250%; font-weight: 300;">2</text> <text x="1650" y="90" fill="#333333" style="font-size: 140%; font-weight: 300; font-family: 'Pacifico', cursive;">Counting..</text> <ellipse id="svg_1" rx="15" ry="15" cx="200" cy="90" fill="#5cb85c" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_2" rx="10" ry="10" cx="550" cy="140" fill="#5f6467" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_3" rx="15" ry="15" cx="800" cy="60" fill="#b2cc71" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_4" rx="15" ry="15" cx="1100" cy="150" fill="#3c88c6" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_5" rx="10" ry="10" cx="1400" cy="100" fill="#1abc9c" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_6" rx="10" ry="10" cx="1700" cy="10" fill="#a85ad4" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_7" rx="9" ry="9" cx="1900" cy="50" fill="#ff8b34" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_8" rx="6" ry="6" cx="2500" cy="90" fill="#fd40b3" stroke="#ffffff" stroke-width="5"></ellipse> <ellipse id="svg_9" rx="6" ry="6" cx="2200" cy="90" fill="#fd3635" stroke="#ffffff" stroke-width="5"></ellipse> <defs> <linearGradient id="BglinierGradient" x1="0" y1="0" x2="0" y2="1"> <stop id="BgLinierGradientStop_1" stop-opacity="1" stop-color="#e8f3f5" offset="0"></stop> <stop id="BgLinierGradientStop_2" stop-opacity="1" stop-color="#e8f3f5" offset="1"></stop> </linearGradient> </defs> </svg> `; return ( <div className="svg-container2"> <div dangerouslySetInnerHTML={{__html: svgTag}} /> </div> ); } } SvgLine.propTypes = { }; SvgLine.defaultProps = { }; export default SvgLine;
src/apps/SocketsRegistry/SocketsRegistryInnerToolbar.js
Syncano/syncano-dashboard
import React from 'react'; import SocketsRegistryActions from './SocketsRegistryActions'; import { FlatButton, RaisedButton } from 'material-ui'; import { colors as Colors } from 'material-ui/styles'; const SocketsRegistryInnerToolbar = ({ filter, filterBySyncano }) => { const styles = { root: { width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }, button: { borderRadius: 0 }, border: { border: '1px solid #244273', borderRadius: 0, alignItems: 'center', boxShadow: 'none', fontSize: '26px', height: '100%', lineHeight: '100%', minWidth: '60px' } }; const setFilterAll = () => { SocketsRegistryActions.setFilter('all'); }; const setFilterTrue = () => { SocketsRegistryActions.setFilter(true); }; const setFilterFalse = () => { SocketsRegistryActions.setFilter(false); }; const setSearchFilterAll = () => { SocketsRegistryActions.setSearchFilter('all'); }; const setSearchFilterName = () => { SocketsRegistryActions.setSearchFilter('name'); }; const setSearchFilterAuthor = () => { SocketsRegistryActions.setSearchFilter('author'); }; const setSearchFilterDescription = () => { SocketsRegistryActions.setSearchFilter('description'); }; const activeButtonColor = '#244273'; const inactiveButtonColor = Colors.white; const activeTextColor = '#a8b5c7'; const activeColorConfigObj = { button: activeButtonColor, label: activeTextColor }; const inactiveColorConfigObj = { button: inactiveButtonColor, label: activeButtonColor }; const defaultFilterByColorConfig = (currentFilterType) => { const isCurrentFilterType = currentFilterType === filterBySyncano; return isCurrentFilterType ? activeColorConfigObj : inactiveColorConfigObj; }; const defaultAuthorColorConfig = (currentFilter) => { const isCurrentFilter = currentFilter === filter; return isCurrentFilter ? activeColorConfigObj : inactiveColorConfigObj; }; return ( <div className="vm-3-b" style={styles.root} > <div> <FlatButton label="Author:" disabled={true} /> <RaisedButton backgroundColor={defaultAuthorColorConfig('all').button} style={styles.border} buttonStyle={styles.button} labelColor={defaultAuthorColorConfig('all').label} label="All" onTouchTap={setFilterAll} /> <RaisedButton backgroundColor={defaultAuthorColorConfig(true).button} style={styles.border} buttonStyle={styles.button} labelColor={defaultAuthorColorConfig(true).label} label="Syncano" onTouchTap={setFilterTrue} /> <RaisedButton backgroundColor={defaultAuthorColorConfig(false).button} style={styles.border} buttonStyle={styles.button} labelColor={defaultAuthorColorConfig(false).label} label="Community" onTouchTap={setFilterFalse} /> </div> <div> <FlatButton label="Filter by:" disabled={true} /> <RaisedButton backgroundColor={defaultFilterByColorConfig('all').button} style={styles.border} buttonStyle={styles.button} labelColor={defaultFilterByColorConfig('all').label} label="All" onTouchTap={setSearchFilterAll} /> <RaisedButton backgroundColor={defaultFilterByColorConfig('name').button} style={styles.border} buttonStyle={styles.button} labelColor={defaultFilterByColorConfig('name').label} label="Name" onTouchTap={setSearchFilterName} /> <RaisedButton backgroundColor={defaultFilterByColorConfig('author').button} style={styles.border} buttonStyle={styles.button} labelColor={defaultFilterByColorConfig('author').label} label="Author" onTouchTap={setSearchFilterAuthor} /> <RaisedButton backgroundColor={defaultFilterByColorConfig('description').button} style={styles.border} buttonStyle={styles.button} labelColor={defaultFilterByColorConfig('description').label} label="Description" onTouchTap={setSearchFilterDescription} /> </div> </div> ); }; export default SocketsRegistryInnerToolbar;
src/frontend/characters/components/CharacterProfile.js
plotify/plotify
import { getProfileGroupIds, isCharacterEditModeEnabled, isProfileEmpty, isProfileFetching } from '../selectors' import CharacterProfileGroup from './CharacterProfileGroup' import { CircularProgress } from 'material-ui/Progress' import ProfileEmptyHint from './ProfileEmptyHint' import ProfileName from './CharacterProfileName' import PropTypes from 'prop-types' import React from 'react' import classNames from 'classnames' import { connect } from 'react-redux' import { withStyles } from 'material-ui/styles' const CharacterProfile = ({ classes, className, profile, editMode, profileEmpty, groups, name, fetching }) => { return ( <div className={classNames(className, classes.root)}> <div className={classes.wrapper}> <ProfileName /> <div className={ classNames( classes.profileEmptyHint, { [classes.hidden]: !fetching } ) }> <CircularProgress /> </div> {groups.map(id => ( <CharacterProfileGroup key={id} groupId={id} className={classes.profileGroup} paperClass={classes.profilePaperClass} /> ))} {!editMode && profileEmpty && !fetching && <ProfileEmptyHint className={classes.profileEmptyHint} /> } </div> </div> ) } const styles = (theme) => { return { root: { display: 'flex', justifyContent: 'space-around', flexDirection: 'row', paddingTop: theme.spacing.unit * 2, paddingRight: theme.spacing.unit * 3, boxSizing: 'border-box' }, wrapper: { flex: '0.5 0.1 400px', display: 'flex', flexDirection: 'column' }, profileGroup: { width: '100%', maxWidth: '850px', margin: '0 auto', padding: theme.spacing.unit * 2 }, profilePaperClass: { display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }, profileEmptyHint: { flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '100%', width: '100%' }, hidden: { display: 'none' } } } CharacterProfile.propTypes = { classes: PropTypes.object.isRequired, className: PropTypes.string.isRequired, groups: PropTypes.array.isRequired } const mapStateToProps = (state) => ({ groups: getProfileGroupIds(state), editMode: isCharacterEditModeEnabled(state), profileEmpty: isProfileEmpty(state), fetching: isProfileFetching(state) }) export default connect(mapStateToProps)(withStyles(styles)(CharacterProfile))
cheesecakes/plugins/users-permissions/admin/src/components/BoundRoute/index.js
strapi/strapi-examples
/** * * BoundRoute * */ import React from 'react'; import { get, includes, map, tail, toLower } from 'lodash'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import cn from 'classnames'; import styles from './styles.scss'; function BoundRoute({ route }) { const title = get(route, 'handler'); const formattedRoute = get(route, 'path') ? tail(get(route, 'path').split('/')) : []; const [ controller = '', action = '' ] = title ? title.split('.') : []; return ( <div className="col-md-12"> <div className={styles.title}> <FormattedMessage id="users-permissions.BoundRoute.title" /> &nbsp; <span>{controller}</span> <span>.{action} </span> </div> <div className={styles.boundRoute}> <div className={cn(styles.verb, styles[toLower(get(route, 'method'))])}> {get(route, 'method')} </div> <div className={styles.path}> {map(formattedRoute, value => ( <span key={value} style={includes(value, ':') ? { color: '#787E8F' } : {}} > /{value} </span> ))} </div> </div> </div> ); } BoundRoute.defaultProps = { route: { handler: 'Nocontroller.error', method: 'GET', path: '/there-is-no-path', }, }; BoundRoute.propTypes = { route: PropTypes.object, }; export default BoundRoute;
examples/check-lists/index.js
ashutoshrishi/slate
import { Editor } from 'slate-react' import { Value } from 'slate' import React from 'react' import initialValue from './value.json' /** * Check list item. * * @type {Component} */ class CheckListItem extends React.Component { /** * On change, set the new checked value on the block. * * @param {Event} event */ onChange = event => { const checked = event.target.checked const { editor, node } = this.props editor.change(c => c.setNodeByKey(node.key, { data: { checked } })) } /** * Render a check list item, using `contenteditable="false"` to embed the * checkbox right next to the block's text. * * @return {Element} */ render() { const { attributes, children, node, readOnly } = this.props const checked = node.data.get('checked') return ( <div className={`check-list-item ${checked ? 'checked' : ''}`} contentEditable={false} {...attributes} > <span> <input type="checkbox" checked={checked} onChange={this.onChange} /> </span> <span contentEditable={!readOnly} suppressContentEditableWarning> {children} </span> </div> ) } } /** * The rich text example. * * @type {Component} */ class CheckLists extends React.Component { /** * Deserialize the initial editor value. * * @type {Object} */ state = { value: Value.fromJSON(initialValue), } /** * On change, save the new value. * * @param {Change} change */ onChange = ({ value }) => { this.setState({ value }) } /** * On key down... * * If enter is pressed inside of a check list item, make sure that when it * is split the new item starts unchecked. * * If backspace is pressed when collapsed at the start of a check list item, * then turn it back into a paragraph. * * @param {Event} event * @param {Change} change * @return {Value|Void} */ onKeyDown = (event, change) => { const { value } = change if (event.key == 'Enter' && value.startBlock.type == 'check-list-item') { change.splitBlock().setBlocks({ data: { checked: false } }) return true } if ( event.key == 'Backspace' && value.isCollapsed && value.startBlock.type == 'check-list-item' && value.selection.startOffset == 0 ) { change.setBlocks('paragraph') return true } } /** * Render. * * @return {Element} */ render() { return ( <div> <div className="editor"> <Editor spellCheck placeholder="Get to work..." value={this.state.value} onChange={this.onChange} onKeyDown={this.onKeyDown} renderNode={this.renderNode} /> </div> </div> ) } /** * Render a Slate node. * * @param {Object} props * @return {Element} */ renderNode = props => { switch (props.node.type) { case 'check-list-item': return <CheckListItem {...props} /> } } } /** * Export. */ export default CheckLists
src/interface/report/FightSelectionPanel.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Panel from 'interface/others/Panel'; import './FightSelection.scss'; import FightSelectionPanelList from './FightSelectionPanelList'; const FightSelectionPanel = props => { const { report, killsOnly } = props; return ( <> <Panel pad={false}> <FightSelectionPanelList report={report} fights={report.fights} killsOnly={killsOnly} /> </Panel> </> ); }; FightSelectionPanel.propTypes = { report: PropTypes.shape({ fights: PropTypes.array.isRequired, }).isRequired, killsOnly: PropTypes.bool.isRequired, }; export default FightSelectionPanel;
app/javascript/mastodon/features/account_gallery/index.js
TootCat/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { fetchAccount, fetchAccountMediaTimeline, expandAccountMediaTimeline, } from '../../actions/accounts'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import Immutable from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { getAccountGallery } from '../../selectors'; import MediaItem from './components/media_item'; import HeaderContainer from '../account_timeline/containers/header_container'; import { FormattedMessage } from 'react-intl'; import { ScrollContainer } from 'react-router-scroll'; import LoadMore from '../../components/load_more'; const mapStateToProps = (state, props) => ({ medias: getAccountGallery(state, Number(props.params.accountId)), isLoading: state.getIn(['timelines', 'accounts_media_timelines', Number(props.params.accountId), 'isLoading']), hasMore: !!state.getIn(['timelines', 'accounts_media_timelines', Number(props.params.accountId), 'next']), autoPlayGif: state.getIn(['meta', 'auto_play_gif']), }); class AccountGallery extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, medias: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool, hasMore: PropTypes.bool, autoPlayGif: PropTypes.bool, }; componentDidMount () { this.props.dispatch(fetchAccount(Number(this.props.params.accountId))); this.props.dispatch(fetchAccountMediaTimeline(Number(this.props.params.accountId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(Number(nextProps.params.accountId))); this.props.dispatch(fetchAccountMediaTimeline(Number(this.props.params.accountId))); } } handleScrollToBottom = () => { if (this.props.hasMore) { this.props.dispatch(expandAccountMediaTimeline(Number(this.props.params.accountId))); } } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; const offset = scrollHeight - scrollTop - clientHeight; if (150 > offset && !this.props.isLoading) { this.handleScrollToBottom(); } } handleLoadMore = (e) => { e.preventDefault(); this.handleScrollToBottom(); } render () { const { medias, autoPlayGif, isLoading, hasMore } = this.props; let loadMore = null; if (!medias && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } if (!isLoading && medias.size > 0 && hasMore) { loadMore = <LoadMore onClick={this.handleLoadMore} />; } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='account_gallery'> <div className='scrollable' onScroll={this.handleScroll}> <HeaderContainer accountId={this.props.params.accountId} /> <div className='account-section-headline'> <FormattedMessage id='account.media' defaultMessage='Media' /> </div> <div className='account-gallery__container'> {medias.map(media => <MediaItem key={media.get('id')} media={media} autoPlayGif={autoPlayGif} /> )} {loadMore} </div> </div> </ScrollContainer> </Column> ); } } export default connect(mapStateToProps)(AccountGallery);
test/fixtures/with-custom-handlers/input.js
kadirahq/babel-plugin-react-docgen
import React from 'react'; import './styles.css'; class ErrorBox extends React.Component { render() { const { children } = this.props; return ( <div className="error-box"> {children} </div> ); } } ErrorBox.propTypes = { /** @deprecated This is the description for prop */ deprecatedProp: React.PropTypes.number, }; export default ErrorBox;
src/app/components/LayoutTwo/LayoutTwo.js
harsh376/Hector
import React from 'react'; import { Link } from 'react-router'; import SidebarContainer from './components/SidebarContainer'; function LayoutTwo({ content, routes }) { const depth = routes.length; return ( <div> <SidebarContainer /> <div className="contentTwo"> <ul className="breadcrumbs-list fixed"> {routes.map((item, index) => <li key={item.path}> <Link onlyActiveOnIndex activeClassName="breadcrumb-active" to={item.path || ''} > {item.component.title} </Link> {(index + 1) < depth && '/'} </li>, )} </ul> <div className="routeBody"> {content} </div> </div> </div> ); } LayoutTwo.propTypes = { content: React.PropTypes.oneOfType([ React.PropTypes.arrayOf(React.PropTypes.node), React.PropTypes.node, ]), routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, }; LayoutTwo.defaultProps = { content: null, }; export default LayoutTwo;
src/components/TextInput/TextInput.js
tlraridon/ps-react-train-tlr
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { return ( <div style={{marginBottom: 16}}> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} style={error && {border: 'solid 1px red'}} {...props}/> {children} {error && <div className="error" style={{color: 'red'}}>{error}</div>} </div> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
app/welcome/Welcome.js
stefanKuijers/aw-fullstack-app
// @flow import React, { Component } from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; import styles from './Welcome.css'; const removeLoader = function () { const element = document.getElementById('app-container'); element.className = 'app-loaded'; } export default class Welcome extends Component { componentWillMount() { this.props.checkActivation(); } activate = () => { if (this.props.profile.username && this.props.profile.username.length > 3) { this.props.activate(); } } renderWelcome() { return( <section> <header> <h1>Welcome<br />{this.props.profile.username}</h1> </header> </section> ); } renderActivate() { return( <section> <header> <h1>Hi there!</h1> <h2>What's your name?</h2> </header> <section> <TextField onChange={(e, val) => {this.props.updateName(val);}} onKeyDown={(e, el) => {if (e.keyCode === 13) this.activate() }} value={this.props.profile.username} style={{width: '100%'}} hintText="please enter your name" /> </section> <footer> <RaisedButton label="Activate" primary={true} onTouchTap={this.activate} /> </footer> </section> ); } render() { removeLoader(); return ( <article className={styles.container}> {(this.props.profile.activated) ? this.renderWelcome() : this.renderActivate()} </article> ); } }
src/components/visualization/index.js
Ameobea/noise-asmjs
//! Wrapper around the visualization's core that only loads once `redux-form` has been initialized. import React from 'react'; import { connect } from 'react-redux'; import { setStageContainerSize } from 'src/actions/stage'; import VizCanvas from './VizCanvas'; const Vizualization = ({enginePointer, setStageContainerSize}) => ( <div style={{marginBottom: 20, height: '100%', width: '100%'}}> <VizCanvas /> </div> ); const mapStateToProps = ({ enginePointer }) => ({ enginePointer: enginePointer.pointer }); export default connect(mapStateToProps, {setStageContainerSize})(Vizualization);
src/Async.js
esleducation/react-select
import React from 'react'; import Select from './Select'; import stripDiacritics from './utils/stripDiacritics'; let requestId = 0; function initCache (cache) { if (cache && typeof cache !== 'object') { cache = {}; } return cache ? cache : null; } function updateCache (cache, input, data) { if (!cache) return; cache[input] = data; } function getFromCache (cache, input) { if (!cache) return; for (let i = input.length; i >= 0; --i) { let cacheKey = input.slice(0, i); if (cache[cacheKey] && (input === cacheKey || cache[cacheKey].complete)) { return cache[cacheKey]; } } } function thenPromise (promise, callback) { if (!promise || typeof promise.then !== 'function') return; return promise.then((data) => { callback(null, data); }, (err) => { callback(err); }); } const Async = React.createClass({ propTypes: { cache: React.PropTypes.any, // object to use to cache results, can be null to disable cache loadOptions: React.PropTypes.func.isRequired, // function to call to load options asynchronously ignoreAccents: React.PropTypes.bool, // whether to strip diacritics when filtering (shared with Select) ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering (shared with Select) isLoading: React.PropTypes.bool, // overrides the isLoading state when set to true loadingPlaceholder: React.PropTypes.string, // replaces the placeholder while options are loading minimumInput: React.PropTypes.number, // the minimum number of characters that trigger loadOptions noResultsText: React.PropTypes.string, // placeholder displayed when there are no matching search results (shared with Select) placeholder: React.PropTypes.oneOfType([ // field placeholder, displayed when there's no value (shared with Select) React.PropTypes.string, React.PropTypes.node ]), searchingText: React.PropTypes.string, // message to display while options are loading searchPromptText: React.PropTypes.string, // label to prompt for search input }, getDefaultProps () { return { cache: true, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', minimumInput: 1, searchingText: 'Searching...', searchPromptText: 'Type to search', }; }, getInitialState () { return { cache: initCache(this.props.cache), isLoading: false, options: this.props.options || [], }; }, componentWillMount () { this._lastInput = ''; }, componentDidMount () { this.loadOptions(''); }, componentWillReceiveProps (nextProps) { if (nextProps.cache !== this.props.cache) { this.setState({ cache: initCache(nextProps.cache), }); } if( ! this.props.options && nextProps.options) { this.setState({ options: nextProps.options }); } else if(this.props.value === undefined && nextProps.value && ! nextProps.options) { this.loadOptions(nextProps.value); } }, focus () { this.refs.select.focus(); }, resetState () { this._currentRequestId = -1; this.setState({ isLoading: false, options: [], }); }, getResponseHandler (input) { let _requestId = this._currentRequestId = requestId++; return (err, data) => { if (err) throw err; if (!this.isMounted()) return; updateCache(this.state.cache, input, data); if (_requestId !== this._currentRequestId) return; this.setState({ isLoading: false, options: data && data.options || [], }); }; }, loadOptions (input) { if ( ! input.length) return; if (this.props.ignoreAccents) input = stripDiacritics(input); if (this.props.ignoreCase) input = input.toLowerCase(); this._lastInput = input; if (input.length < this.props.minimumInput) { return this.resetState(); } let cacheResult = getFromCache(this.state.cache, input); if (cacheResult) { return this.setState({ options: cacheResult.options, }); } this.setState({ isLoading: true, }); let responseHandler = this.getResponseHandler(input); return thenPromise(this.props.loadOptions(input, responseHandler), responseHandler); }, onChange (newValue) { this.props.onChange(newValue); let value; if (newValue === null) { value = []; } else { value = [newValue]; } this.setState({ options: value }); }, render () { let { noResultsText } = this.props; let { isLoading, options } = this.state; if (this.props.isLoading) isLoading = true; let placeholder = isLoading ? this.props.loadingPlaceholder : this.props.placeholder; if (!options.length) { if (this._lastInput.length < this.props.minimumInput) noResultsText = this.props.searchPromptText; if (isLoading) noResultsText = this.props.searchingText; } return ( <Select {...this.props} ref="select" onChange={this.onChange} isLoading={isLoading} noResultsText={noResultsText} onInputChange={this.loadOptions} options={options} placeholder={placeholder} /> ); } }); module.exports = Async;
react-boilerplate/internals/templates/containers/HomePage/index.js
Sakuyakun/Yorha-Experiment
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
react-redux/src/index.js
jasonrhodes/how-to-react
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' import App from './components/app' // reducers import reducers from './reducers' const store = createStore(reducers) ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.querySelector('.container'))
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js
zipongo/react-router
/*globals COURSES:true */ import React from 'react' class Announcement extends React.Component { render() { let { courseId, announcementId } = this.props.params let { title, body } = COURSES[courseId].announcements[announcementId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ) } } module.exports = Announcement
Paths/React/05.Building Scalable React Apps/9-react-boilerplate-building-scalable-apps-m9-exercise-files/Before/app/containers/NavigationContainer/index.js
phiratio/Pluralsight-materials
/* * * NavigationContainer * */ import React from 'react'; import { connect } from 'react-redux'; import selectNavigationContainer from './selectors'; import Navigation from '../../components/Navigation'; import { requestTopics, selectTopic, toggleDrawer } from './actions'; export class NavigationContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { requestTopics: React.PropTypes.func.isRequired, } componentWillMount() { this.props.requestTopics(); } render() { return ( <Navigation {...this.props} /> ); } } const mapStateToProps = selectNavigationContainer(); function mapDispatchToProps(dispatch) { return { requestTopics: () => dispatch(requestTopics()), selectTopic: (topic) => dispatch(selectTopic(topic)), toggleDrawer: () => dispatch(toggleDrawer()), }; } export default connect(mapStateToProps, mapDispatchToProps)(NavigationContainer);
dev/react-subjects/subjects/Components/solution.js
AlanWarren/dotfiles
//////////////////////////////////////////////////////////////////////////////// // Exercise: // // - Render a tab for each country with its name in the tab // - Make it so that you can click on a tab and it will appear active // while the others appear inactive // - Make it so the panel renders the correct content for the selected tab // // Got extra time? // // - Make <Tabs> generic so that it doesn't know anything about // country data (Hint: good propTypes help) //////////////////////////////////////////////////////////////////////////////// import React from 'react' import ReactDOM from 'react-dom' const styles = {} styles.tab = { display: 'inline-block', padding: 10, margin: 10, borderBottom: '4px solid', borderBottomColor: '#ccc', cursor: 'pointer' } styles.activeTab = { ...styles.tab, borderBottomColor: '#000' } styles.panel = { padding: 10 } class Tabs extends React.Component { state = { activeTabIndex: 0 } selectTabIndex(activeTabIndex) { this.setState({ activeTabIndex }) } render() { const { data } = this.props const { activeTabIndex } = this.state const tabs = data.map((country, index) => { const isActive = index === activeTabIndex const style = isActive ? styles.activeTab : styles.tab return ( <div key={country.id} className="Tab" style={style} onClick={() => this.selectTabIndex(index)} >{country.name}</div> ) }) const activeCountry = data[activeTabIndex] const content = activeCountry && activeCountry.description return ( <div className="Tabs"> {tabs} <div className="TabPanel" style={styles.panel}> {content} </div> </div> ) } } class App extends React.Component { render() { return ( <div> <h1>Countries</h1> <Tabs data={this.props.countries}/> </div> ) } } const DATA = [ { id: 1, name: 'USA', description: 'Land of the Free, Home of the brave' }, { id: 2, name: 'Brazil', description: 'Sunshine, beaches, and Carnival' }, { id: 3, name: 'Russia', description: 'World Cup 2018!' } ] ReactDOM.render(<App countries={DATA}/>, document.getElementById('app'), function () { require('./tests').run(this) })
src/svg-icons/image/filter.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter = (props) => ( <SvgIcon {...props}> <path d="M15.96 10.29l-2.75 3.54-1.96-2.36L8.5 15h11l-3.54-4.71zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/> </SvgIcon> ); ImageFilter = pure(ImageFilter); ImageFilter.displayName = 'ImageFilter'; ImageFilter.muiName = 'SvgIcon'; export default ImageFilter;
src/map/js/components/Modals/AboutModal.js
wri/gfw-water
import AboutWrapper from 'components/Modals/AboutWrapper'; import {modalStore} from 'stores/ModalStore'; import {aboutModalConfig} from 'js/config'; import React from 'react'; let toolsSvg = '<use xlink:href="#about-icon-tools" />'; let economicsSvg = '<use xlink:href="#about-icon-economics" />'; let guidanceSvg = '<use xlink:href="#about-icon-guidance" />'; let infrastructureSvg = '<use xlink:href="#about-icon-natural-infrastructure" />'; let otherSvg = '<use xlink:href="#about-icon-other" />'; export default class AboutModal extends React.Component { constructor (props) { super(props); let defaultState = modalStore.getState(); this.state = { aboutModalSelection: defaultState.aboutModalSelection }; modalStore.listen(::this.storeUpdated); } storeUpdated () { let newState = modalStore.getState(); this.setState({ aboutModalSelection: newState.aboutModalSelection }); } render () { let currentSelection = this.state.aboutModalSelection; let displayNumbers, svgSelected; displayNumbers = aboutModalConfig[currentSelection]; switch (currentSelection) { case 'spatialMapping': svgSelected = toolsSvg; break; case 'economics': svgSelected = economicsSvg; break; case 'guidance': svgSelected = guidanceSvg; break; case 'naturalInfrastructure': svgSelected = infrastructureSvg; break; case 'otherWRI': svgSelected = otherSvg; break; default: svgSelected = null; } return ( <AboutWrapper> <div className='about-modal-content'> {svgSelected ? <div className='modal-icon'> <div className='top-icon'> <svg dangerouslySetInnerHTML={{ __html: svgSelected }}/> </div></div> : null } {displayNumbers ? <div className='modal-title'>{displayNumbers.title}</div> : null} <ul className='about-modal-list'> {displayNumbers ? displayNumbers.bullets.map(this.bulletMap) : null} </ul> </div> </AboutWrapper> ); } bulletMap (item) { if (item.length) { return ( <ul> {item.map(listItem => <li dangerouslySetInnerHTML={{ __html: listItem.label }} />)} </ul> ); } else { return ( <li dangerouslySetInnerHTML={{ __html: item.label }} /> ); } } }
src/App/shared/TrainerTable/index.js
findjanice/node-api-server
/*** @jsx React.DOM */ import React from 'react'; var TrainerTable = React.createClass({ render: function() { var trainerRows = this.props.trainers.map(function(trainer) { var trainerLink = `#/trainers/${trainer.id}`; return ( <tr key={trainer.id}> <td>{trainer.id}</td> <td> <a href={trainerLink}>{trainer.name}</a> </td> </tr> ); }); return ( <table className="trainer-table"> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> {trainerRows} </tbody> </table> ); } }); export default TrainerTable;
packages/material-ui-icons/src/HdrOn.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let HdrOn = props => <SvgIcon {...props}> <path d="M21 11.5v-1c0-.8-.7-1.5-1.5-1.5H16v6h1.5v-2h1.1l.9 2H21l-.9-2.1c.5-.3.9-.8.9-1.4zm-1.5 0h-2v-1h2v1zm-13-.5h-2V9H3v6h1.5v-2.5h2V15H8V9H6.5v2zM13 9H9.5v6H13c.8 0 1.5-.7 1.5-1.5v-3c0-.8-.7-1.5-1.5-1.5zm0 4.5h-2v-3h2v3z" /> </SvgIcon>; HdrOn = pure(HdrOn); HdrOn.muiName = 'SvgIcon'; export default HdrOn;
packages/@lyra/default-login/src/LoginDialogContent.js
VegaPublish/vega-studio
/* eslint-disable react/no-multi-comp */ import React from 'react' import PropTypes from 'prop-types' import config from 'config:lyra' import BrandLogo from 'part:@lyra/base/brand-logo?' import styles from './styles/LoginDialogContent.css' const projectName = (config.project && config.project.name) || '' /* eslint-disable max-len */ const GithubLogo = () => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 438.55 438.55"> <path d="M409.13 114.57a218.32 218.32 0 0 0-79.8-79.8Q278.94 5.36 219.27 5.36T109.21 34.77a218.29 218.29 0 0 0-79.8 79.8Q0 165 0 224.63q0 71.67 41.83 128.91t108.06 79.23q7.71 1.43 11.42-2a11.17 11.17 0 0 0 3.69-8.57q0-.86-.14-15.42t-.14-25.41l-6.57 1.14a83.77 83.77 0 0 1-15.85 1 120.73 120.73 0 0 1-19.84-2 44.34 44.34 0 0 1-19.11-8.51 36.23 36.23 0 0 1-12.56-17.6l-2.86-6.57a71.34 71.34 0 0 0-9-14.56q-6.14-8-12.42-10.85l-2-1.43a21 21 0 0 1-3.71-3.43 15.66 15.66 0 0 1-2.57-4q-.86-2 1.43-3.29C61.2 310.42 64 310 68 310l5.71.85q5.71 1.14 14.13 6.85a46.08 46.08 0 0 1 13.85 14.84q6.57 11.71 15.85 17.85t18.7 6.14a81.19 81.19 0 0 0 16.27-1.42 56.78 56.78 0 0 0 12.85-4.29q2.57-19.14 14-29.41a195.49 195.49 0 0 1-29.36-5.13 116.52 116.52 0 0 1-26.83-11.14 76.86 76.86 0 0 1-23-19.13q-9.14-11.42-15-30t-5.8-42.81q0-34.55 22.56-58.82-10.57-26 2-58.24 8.28-2.57 24.55 3.85t23.84 11q7.57 4.56 12.13 7.71a206.2 206.2 0 0 1 109.64 0l10.85-6.85a153.65 153.65 0 0 1 26.26-12.56q15.13-5.71 23.13-3.14 12.84 32.26 2.28 58.24 22.55 24.27 22.56 58.82 0 24.27-5.85 43t-15.12 30a79.82 79.82 0 0 1-23.13 19 116.74 116.74 0 0 1-26.84 11.14 195.29 195.29 0 0 1-29.23 5.07q14.8 12.84 14.81 40.58v60.2a11.37 11.37 0 0 0 3.57 8.56q3.57 3.42 11.28 2 66.24-22 108.07-79.23t41.83-128.91q-.03-59.62-29.43-110.05z" /> </svg> ) const GoogleLogo = () => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"> <path d="M11 24a13 13 0 0 1 .66-4.08l-7.4-5.66a22.18 22.18 0 0 0 0 19.49l7.4-5.67A13 13 0 0 1 11 24z" fill="#fbbc05" /> <path d="M24 11a12.72 12.72 0 0 1 8.1 2.9l6.4-6.4a22 22 0 0 0-34.24 6.75l7.4 5.66A13 13 0 0 1 24 11z" fill="#ea4335" /> <path d="M24 37a13 13 0 0 1-12.34-8.92l-7.4 5.66A21.93 21.93 0 0 0 24 46a21 21 0 0 0 14.33-5.48l-7-5.44A13.59 13.59 0 0 1 24 37zm-12.35-8.93l-7.4 5.67 7.4-5.66z" fill="#34a853" /> <path d="M44.5 20H24v8.5h11.8a9.91 9.91 0 0 1-4.49 6.58l7 5.44C42.37 36.76 45 31.17 45 24a18.25 18.25 0 0 0-.5-4z" fill="#4285f4" /> </svg> ) const QuestionmarkLogo = () => ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" fill="#666" > <path d="M500,9.9c270.1,0,490.5,220.6,490,490.3c-0.5,270.7-220.6,490.6-490.3,489.9C229.2,989.4,10.4,770.5,10,500.1C9.6,230.3,229.9,9.9,500,9.9z M943.7,499.9c0-244.4-198-443-443.5-443.5C255.5,55.9,56.6,254.5,56.3,499.9c-0.3,244.4,198.3,442.9,443.4,443.6C743.8,944.2,943.8,744.5,943.7,499.9z" /> <path d="M527.3,658.3c-20.9,0-41.3,0-62.2,0c0-12.4-0.7-24.6,0.1-36.7c1.6-24.4,7.3-47.9,20-69.2c9.9-16.6,22.6-30.9,36.7-44c17.5-16.3,35.1-32.4,52.3-49.1c10.1-9.8,19-20.8,23.7-34.4c11.2-32.7,4-61.8-17.7-87.8c-36.1-43.1-96.4-44.6-133.4-23c-23.3,13.6-37.3,34.4-45.4,59.5c-3.7,11.2-6.2,22.8-9.5,35.1c-21.5-2.5-43.5-5.2-66.3-7.9c0.9-5.7,1.5-11,2.5-16.3c5.7-29.6,15.9-57.2,35.3-80.8c23.5-28.8,54.2-45.6,90.3-52.5c37.7-7.2,75.3-6.5,112,5.5c46.9,15.2,81.6,45,97.4,92.4c15.1,45.5,7.7,88.5-22.1,127c-18.9,24.4-42.4,44.2-64.5,65.4c-9.7,9.3-19.6,18.7-28,29.2c-12.5,15.5-17.3,34.3-18.8,53.9C528.6,635.5,528.1,646.6,527.3,658.3z" /> <path d="M461,790c0-24.6,0-48.9,0-73.7c24.6,0,49,0,73.7,0c0,24.5,0,48.9,0,73.7C510.3,790,485.8,790,461,790z" /> </svg> ) /* eslint-enable max-len */ function getProviderLogo(provider) { switch (provider.name) { case 'google': return GoogleLogo case 'github': return GithubLogo default: return function CustomLogo() { return provider.logo ? ( <img src={provider.logo} /> ) : ( <QuestionmarkLogo /> ) } } } export default class LoginDialogContent extends React.Component { static propTypes = { title: PropTypes.node.isRequired, description: PropTypes.node, providers: PropTypes.array, onLoginButtonClick: PropTypes.func, LyraLogo: PropTypes.func } static defaultProps = { description: null, title: null, providers: null, onLoginButtonClick: null, LyraLogo: null } handleLoginButtonClicked = (provider, event) => { const {onLoginButtonClick} = this.props if (onLoginButtonClick) { this.props.onLoginButtonClick(provider, event) } else { console.warn( 'LoginDialogContent is missing the onLoginButtonClick property' ) // eslint-disable-line no-console } } render() { const {title, description, providers, LyraLogo} = this.props return ( <div className={styles.root}> <div className={styles.inner}> {LyraLogo && ( <div className={styles.lyraLogo}> <LyraLogo /> </div> )} <div className={styles.branding}> <h1 className={ BrandLogo ? styles.projectNameHidden : styles.projectName } > {projectName} </h1> {BrandLogo && ( <div className={styles.brandLogoContainer}> <BrandLogo projectName={projectName} /> </div> )} </div> <h2 className={styles.title}>{title}</h2> {description && ( <div className={styles.description}>{description}</div> )} <ul className={styles.providers}> {providers.map(provider => { const ProviderLogo = getProviderLogo(provider) const onLoginClick = this.handleLoginButtonClicked.bind( this, provider ) return ( <li key={provider.name} className={styles.provider}> <button type="button" onClick={onLoginClick} className={styles.providerButton} > <span className={styles.providerLogo}> <ProviderLogo /> </span> <span className={styles.providerName}> {provider.title} </span> </button> </li> ) })} </ul> </div> </div> ) } }
CurrencyCharts/source/components/currencySelector/CurrencySelector.js
matheusrabelo/CurrencyCharts
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as currencyActions from '../../actions/currencyActions'; class CurrencySelector extends React.Component { constructor(props, context) { super(props, context); this.state = { currency: 'AED', currencies: [], }; // Changing reference for 'this' in methods this.showCurrency = this.showCurrency.bind(this); this.changeCurrency = this.changeCurrency.bind(this); } changeCurrency(event) { const currency = event.target.value; this.setState({ currency }); } showCurrency() { this.props.actions.loadHistory(this.state.currency); } refreshCurrencyPicker() { // refresh selectPicker setTimeout(function() { $('#currencyPicker').selectpicker('refresh'); }, 0); } render() { this.refreshCurrencyPicker(); return ( <div> <select onChange={this.changeCurrency} id="currencyPicker" className="selectpicker"> {this.props.currencies.map((currency) => <option key={currency.title.toString()} value={currency.title}> {currency.title} - {currency.name} </option> )} </select> <button style={style.showCurrency} onClick={this.showCurrency} className="btn btn-primary"> Show exchange rate </button> </div> ); } } const style = { showCurrency: { marginLeft: '0.5em', }, }; CurrencySelector.propTypes = { actions: PropTypes.object.isRequired, }; function mapStateToProps(state, ownProps) { return { currencies: state.currencies, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(currencyActions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(CurrencySelector);
src/components/tabs/index.js
LINKIWI/react-elemental
import PropTypes from 'prop-types'; import React from 'react'; import Spacing from 'components/spacing'; import Text from 'components/text'; import PrimaryTabOption from 'components/tabs/primary-tab-option'; import SecondaryTabOption from 'components/tabs/secondary-tab-option'; import noop from 'util/noop'; /** * Horizontally organized segments of options. */ const Tabs = ({ options, value: selected, secondary, fit, invert, onChange, style: overrides, ...proxyProps }) => { const containerStyle = { alignItems: 'end', display: 'flex', justifyContent: fit ? 'inherit' : 'space-around', ...overrides, }; const buttonIdleStyle = { backgroundColor: 'inherit', borderRadius: 0, cursor: 'pointer', textAlign: 'center', width: '100%', }; const TabOption = secondary ? SecondaryTabOption : PrimaryTabOption; return ( <div style={containerStyle} {...proxyProps}> {options.map(({ value, label }, idx) => ( <div key={value} style={fit ? {} : { flex: 1 }}> <TabOption baseStyle={buttonIdleStyle} isIntermediate={idx < options.length - 1} isSelected={selected === value} isInvert={invert} onClick={() => onChange(value)} > {typeof label === 'string' ? ( <Spacing size="tiny" top bottom padding> <Text color="gray60"> {label} </Text> </Spacing> ) : label} </TabOption> </div> ))} </div> ); }; Tabs.propTypes = { options: PropTypes.arrayOf(PropTypes.shape({ value: PropTypes.string.isRequired, label: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]).isRequired, })), value: PropTypes.string, secondary: PropTypes.bool, fit: PropTypes.bool, invert: PropTypes.bool, onChange: PropTypes.func, style: PropTypes.object, }; Tabs.defaultProps = { options: [], value: null, secondary: false, fit: false, invert: false, onChange: noop, style: {}, }; export default Tabs;
packages/icons/src/md/maps/LocalBar.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLocalBar(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M42 10L26 28v10h10v4H12v-4h10V28L6 10V6h36v4zm-27.13 4h18.26l3.56-4H11.31l3.56 4z" /> </IconBase> ); } export default MdLocalBar;
src/components/HomePage.js
tsaarni/docker-npm-builder
import React from 'react'; import {Link} from 'react-router'; const HomePage = () => { return ( <div> <h1>React Slingshot</h1> <h2>Get Started</h2> <ol> <li>Review the <Link to="fuel-savings">demo app</Link></li> <li>Remove the demo and start coding: npm run remove-demo</li> </ol> </div> ); }; export default HomePage;
src/js/components/icons/base/DocumentCloud.js
odedre/grommet-final
/** * @description DocumentCloud SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L19,23 M18,1 L18,6 L23,6 M11,13 L6.00166547,13 C4.34389141,13 3,14.3465171 3,16 L3,16 C3,17.6568542 4.34306961,19 5.9906311,19 L7,19 L7,20.0093689 C7,21.6610488 8.33902013,23 10.0016655,23 L11.9983345,23 C13.6561086,23 15,21.6569304 15,20.0093689 L15,19 M11,19 L15.9983345,19 C17.6561086,19 19,17.6534829 19,16 L19,16 C19,14.3431458 17.6569304,13 16.0093689,13 L15,13 L15,11.9906311 C15,10.3389512 13.6609799,9 11.9983345,9 L10.0016655,9 C8.34389141,9 7,10.3430696 7,11.9906311 L7,13"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-document-cloud`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-cloud'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L19,23 M18,1 L18,6 L23,6 M11,13 L6.00166547,13 C4.34389141,13 3,14.3465171 3,16 L3,16 C3,17.6568542 4.34306961,19 5.9906311,19 L7,19 L7,20.0093689 C7,21.6610488 8.33902013,23 10.0016655,23 L11.9983345,23 C13.6561086,23 15,21.6569304 15,20.0093689 L15,19 M11,19 L15.9983345,19 C17.6561086,19 19,17.6534829 19,16 L19,16 C19,14.3431458 17.6569304,13 16.0093689,13 L15,13 L15,11.9906311 C15,10.3389512 13.6609799,9 11.9983345,9 L10.0016655,9 C8.34389141,9 7,10.3430696 7,11.9906311 L7,13"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentCloud'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
packages/node_modules/@ciscospark/react-component-activity-text/src/index.js
bzang/react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import {filterSync} from '@ciscospark/helper-html'; import styles from './styles.css'; export default function ActivityText(props) { const { content, displayName } = props; /* eslint-disable-reason content is considered safe from server */ /* eslint-disable react/no-danger */ if (content) { const cleaned = filterSync(() => {}, { // eslint-disable-line no-empty-function 'spark-mention': [`data-object-type`, `data-object-id`, `data-object-url`], a: [`href`], b: [], blockquote: [`class`], strong: [], i: [], em: [], pre: [], code: [`class`], br: [], hr: [], p: [], ul: [], ol: [], li: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [] }, [], content); const htmlContent = {__html: cleaned}; return ( <div className={classNames(`ciscospark-activity-text`, styles.activityText)} dangerouslySetInnerHTML={htmlContent} /> ); } return ( <div className={classNames(`ciscospark-activity-text`, styles.activityText)} > {displayName} </div> ); /* eslint-enable react/no-danger */ } ActivityText.propTypes = { content: PropTypes.string, displayName: PropTypes.string };
node_modules/react-icons/md/equalizer.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdEqualizer = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m26.6 15h6.8v18.4h-6.8v-18.4z m-20 18.4v-13.4h6.8v13.4h-6.8z m10 0v-26.8h6.8v26.8h-6.8z"/></g> </Icon> ) export default MdEqualizer
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbExampleTinySize.js
shengnian/shengnian-ui-react
import React from 'react' import { Breadcrumb } from 'shengnian-ui-react' const BreadcrumbExampleTinySize = () => ( <Breadcrumb size='tiny'> <Breadcrumb.Section link>Home</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section link>Registration</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section active>Personal Information</Breadcrumb.Section> </Breadcrumb> ) export default BreadcrumbExampleTinySize
src/ProfessionField.js
greenteamer/form
import React, { Component } from 'react'; import Select2 from './Select2'; import _ from 'underscore'; export default class ProfessionField extends Component { constructor(props) { super(props); this.state = { list: this.props.professions, isOpen: false, value: {}, text: "", keyIndex: undefined }; } changeChars(e){ // фильтр списка по вводимым символам this.openSelect(); console.log("e.target.value: ", e.target.value, this.state.list) this.setState({ text: e.target.value }) let new_list = _.filter(this.props.professions, (prof)=>{ let str = prof.text.toLowerCase(); if (str.indexOf(e.target.value) >= 0){ return true; } else if (prof.text.indexOf(e.target.value) >= 0) { return true; } }) this.setState({ list: new_list }) } openSelect(){ setTimeout(()=>{ this.setState({ isOpen: true }) }, 100); } closeSelect(){ setTimeout(()=>{ this.setState({ isOpen: false }) }, 100); } _selectProfession(prof, e){ this.setState({ value: prof, text: prof.text }) } preparationList(){ let list = _.map(this.state.list, (prof)=>{ // преобразуем строку в массив let split_text_arr = ""; if (this.state.text) { split_text_arr = prof.text.split(this.state.text); if (split_text_arr.length == 1) { // если слово начинается с большой буквы split_text_arr = prof.text.split(this.state.text[0].toUpperCase() + this.state.text.substr(1)); } } return( <div className="select-item" key={ prof.id } onClick={this._selectProfession.bind(this, prof)}> <a name="">{(split_text_arr.length > 0) ? splitText(split_text_arr, this.state.text) : prof.text}</a> </div> ) }) return list; } selectByKeyPress(e){ if (e.keyCode == 40) { // нажатие на стрелку вниз console.log("satart key up 40, keyIndex: ", this.state.keyIndex) let keyIndex = ((this.state.keyIndex || this.state.keyIndex == 0) && this.state.keyIndex < this.state.list.length) ? this.state.keyIndex + 1 : 0; this.setState({ keyIndex: keyIndex, value: this.state.list[keyIndex], text: this.state.list[keyIndex].text }) }else if (e.keyCode == 38){ // нажатие на стрелку вверх let index = this.state.keyIndex; console.log("satrt key up 38, keyIndex: ", this.state.keyIndex) let keyIndex = (index >= 0 || index) ? index - 1 : this.state.list.length-1; console.log("end key up 38, keyIndex: ", keyIndex) this.setState({ keyIndex: keyIndex, value: this.state.list[keyIndex], text: this.state.list[keyIndex].text }) }else if(e.keyCode == 13){ // нажати на Enter e.preventDefault(); e.stopPropagation(); this.closeSelect(); } console.log("satart key up 40, keyIndex: ", this.state.keyIndex) } cancelEnter(e){ if(e.keyCode == 13){ // нажати на Enter e.preventDefault(); e.stopPropagation(); this.closeSelect(); this.setState({ keyIndex: undefined }) } return false; } render() { if (!this.state.list) { return null } return ( <div className="form-group align-left profession-group" onBlur={this.closeSelect.bind(this)}> <label for="formControlsText" className="control-label">Профессия</label> <input ref="tags" type="text" value={this.state.text} className="form-control inline-input profession" onChange={this.changeChars.bind(this)} onFocus={this.openSelect.bind(this)} onBlur={this.closeSelect.bind(this)} onKeyUp={this.selectByKeyPress.bind(this)} onKeyDown={this.cancelEnter.bind(this)}/> <div className={(this.state.isOpen) ? "dropdown-select open" : "dropdown-select"}> {this.preparationList()} </div> </div> ); } } function splitText(arr, text){ // выделяем жирным нужные символы return _.map(arr, (word, index)=>{ if (index == 0 || index & 1) { return ( <span key={index}> <span>{word}</span>{(index == (arr.length-1)) ? "" : <strong>{text}</strong>} </span> ) } else { return <span key={index}>{word}</span> } }) }
docs/app/Examples/elements/List/Types/ListExampleTree.js
aabustamante/Semantic-UI-React
import React from 'react' import { List } from 'semantic-ui-react' const ListExampleTree = () => ( <List> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>src</List.Header> <List.Description>Source files for project</List.Description> <List.List> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>site</List.Header> <List.Description>Your site's theme</List.Description> </List.Content> </List.Item> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>themes</List.Header> <List.Description>Packaged theme files</List.Description> <List.List> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>default</List.Header> <List.Description>Default packaged theme</List.Description> </List.Content> </List.Item> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>my_theme</List.Header> <List.Description>Packaged themes are also available in this folder</List.Description> </List.Content> </List.Item> </List.List> </List.Content> </List.Item> <List.Item> <List.Icon name='file' /> <List.Content> <List.Header>theme.config</List.Header> <List.Description>Config file for setting packaged themes</List.Description> </List.Content> </List.Item> </List.List> </List.Content> </List.Item> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>dist</List.Header> <List.Description>Compiled CSS and JS files</List.Description> <List.List> <List.Item> <List.Icon name='folder' /> <List.Content> <List.Header>components</List.Header> <List.Description>Individual component CSS and JS</List.Description> </List.Content> </List.Item> </List.List> </List.Content> </List.Item> <List.Item> <List.Icon name='file' /> <List.Content> <List.Header>semantic.json</List.Header> <List.Description>Contains build settings for gulp</List.Description> </List.Content> </List.Item> </List> ) export default ListExampleTree
src/svg-icons/action/grade.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGrade = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ActionGrade = pure(ActionGrade); ActionGrade.displayName = 'ActionGrade'; export default ActionGrade;
blueocean-material-icons/src/js/components/svg-icons/hardware/toys.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareToys = (props) => ( <SvgIcon {...props}> <path d="M12 12c0-3 2.5-5.5 5.5-5.5S23 9 23 12H12zm0 0c0 3-2.5 5.5-5.5 5.5S1 15 1 12h11zm0 0c-3 0-5.5-2.5-5.5-5.5S9 1 12 1v11zm0 0c3 0 5.5 2.5 5.5 5.5S15 23 12 23V12z"/> </SvgIcon> ); HardwareToys.displayName = 'HardwareToys'; HardwareToys.muiName = 'SvgIcon'; export default HardwareToys;
src/templates/tags-list-template.js
colmdoyle/colmdoyle.github.io
// @flow strict import React from 'react'; import { Link } from 'gatsby'; import kebabCase from 'lodash/kebabCase'; import Layout from '../components/Layout'; import Sidebar from '../components/Sidebar'; import Page from '../components/Page'; import { useSiteMetadata, useTagsList } from '../hooks'; const TagsListTemplate = () => { const { title, subtitle } = useSiteMetadata(); const tags = useTagsList(); return ( <Layout title={`Tags - ${title}`} description={subtitle}> <Sidebar /> <Page title="Tags"> <ul> {tags.map((tag) => ( <li key={tag.fieldValue}> <Link to={`/tag/${kebabCase(tag.fieldValue)}/`}> {tag.fieldValue} ({tag.totalCount}) </Link> </li> ))} </ul> </Page> </Layout> ); }; export default TagsListTemplate;
src/svg-icons/maps/local-shipping.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalShipping = (props) => ( <SvgIcon {...props}> <path d="M20 8h-3V4H3c-1.1 0-2 .9-2 2v11h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm13.5-9l1.96 2.5H17V9.5h2.5zm-1.5 9c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); MapsLocalShipping = pure(MapsLocalShipping); MapsLocalShipping.displayName = 'MapsLocalShipping'; MapsLocalShipping.muiName = 'SvgIcon'; export default MapsLocalShipping;
packages/insights-web/src/scenes/explorer/sidebar/models/index.js
mariusandra/insights
import React from 'react' import { useActions, useValues } from 'kea' import { Empty, Icon, Tree } from 'antd' import HighlightText from 'lib/utils/highlight-text' import connectionLogic from '../../connection/logic' import explorerLogic from '../../logic' import logic from './logic' const { TreeNode } = Tree; export default function Models () { const { connectionId } = useValues(connectionLogic) const { models, filteredModels, search, selectedKey } = useValues(explorerLogic) const { pinnedPerModel, viewsPerModel } = useValues(logic) const { openModel } = useActions(explorerLogic) if (!connectionId) { return ( <div /> ) } if (models.length === 0) { return <Empty description='No Models exported by this connection...' style={{ marginTop: 60 }} /> } return ( <div className='model-list'> <Tree showIcon blockNode selectable selectedKeys={[selectedKey]} onSelect={([model]) => openModel(model || selectedKey)} onExpand={([model]) => openModel(model || selectedKey)} expandedKeys={[]} > {filteredModels.map(model => ( <TreeNode title={ <div> {search ? <HighlightText highlight={search}>{model}</HighlightText> : model} <span className='icons-sidebar-part'> {viewsPerModel[model] ? <Icon type='star' theme='filled' title={`${viewsPerModel[model]} star${viewsPerModel[model] === 1 ? '' : 's'}`} style={{ color: 'hsl(42, 98%, 45%)' }} /> : null} {pinnedPerModel[model] ? <Icon type='pushpin' theme='filled' title={`${pinnedPerModel[model]} pin${pinnedPerModel[model] === 1 ? '' : 's'}`} style={{ color: 'hsl(3, 77%, 42%)' }} /> : null} </span> </div> } key={model} switcherIcon={<Icon type='table' style={{ color: 'hsla(209, 66%, 54%, 1)', transform: "scale(0.833)" }} />} > <TreeNode key={`${model}.inside`} /> </TreeNode> ))} </Tree> </div> ) }
src/frontend/containers/auth/check.js
PiTeam/garage-pi
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getAuthPropType, getDoorPropType, getUserPropType } from 'proptypes'; import { fetchUsers, fetchDoors, fetchUserDoors, checkAuthToken } from 'actions'; export function checkAuth(Component) { class CheckAuthentication extends React.Component { constructor(props) { super(props); this.checkAuth = this.checkAuth.bind(this); this.state = { ready: false, isAuthenticating: false, isFetching: false, }; } componentWillMount() { this.checkAuth(this.props); } componentWillReceiveProps(nextProps) { this.checkAuth(nextProps); } getStyles() { return { main: { textAlign: 'center', minHeight: '100%', position: 'relative', }, }; } checkAuth(props) { if (props.auth.get('status') === 'success') { if (!this.state.isFetching) { if (props.auth.get('admin')) { props.fetchUsers(props.auth.get('token')); props.fetchDoors(props.auth.get('token')); } else { props.fetchUserDoors(props.auth.get('token')); } return this.setState({ isFetching: true }); } if (props.auth.get('admin') && props.doors.get('status') === 'success' && props.users.get('status') === 'success') { return this.setState({ ready: true }); } if (!props.auth.get('admin') && props.doors.get('status') === 'success') { return this.setState({ ready: true }); } } else if (props.auth.get('status') === 'error') { return this.setState({ ready: true }); } if (!this.state.isAuthenticating) { this.props.checkAuthToken(); } return this.setState({ isAuthenticating: true }); } render() { const styles = this.getStyles(); return ( <div style={styles.main}> {this.state.ready ? <Component {...this.props} /> : null } </div> ); } } function mapStateToProps({ auth, users, doors }) { return { auth, users, doors }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ checkAuthToken, fetchDoors, fetchUsers, fetchUserDoors }, dispatch); } CheckAuthentication.propTypes = { auth: getAuthPropType(), checkAuthToken: React.PropTypes.func, doors: getDoorPropType(), users: getUserPropType(), }; return connect(mapStateToProps, mapDispatchToProps)(CheckAuthentication); }
client/src/components/Application.js
codefordenver/Circular
import React from 'react'; import PropTypes from 'prop-types'; import NavBar from '../components/Navigation/Navbar'; const Application = ({ auth, closeMap, firebaseSignInGoogle, firebaseSignInFacebook, firebaseSignOut, userSignatures, ...props }) => ( <div className="app-container"> <NavBar auth={auth} closeMap={closeMap} firebaseSignOut={firebaseSignOut} firebaseSignInGoogle={firebaseSignInGoogle} firebaseSignInFacebook={firebaseSignInFacebook} userSignatures={userSignatures} {...props} /> {props.children} </div> ); Application.propTypes = { auth: PropTypes.shape({ status: PropTypes.string.isRequried }).isRequired, children: PropTypes.shape({}).isRequired, closeMap: PropTypes.func.isRequired, firebaseSignInGoogle: PropTypes.func.isRequired, firebaseSignInFacebook: PropTypes.func.isRequired, firebaseSignOut: PropTypes.func.isRequired, fetchUserSignatures: PropTypes.func.isRequired, userSignatures: PropTypes.shape({}).isRequired }; export default Application;
src/apps/DataObjects/DataObjectsTable/ColumnsFilterMenu.js
Syncano/syncano-dashboard
import React from 'react'; import { IconButton, IconMenu } from 'material-ui'; import ColumnsFilterMenuListItem from './ColumnsFilterMenuListItem'; const ColumnsFilterMenu = ({ columns, checkToggleColumn }) => ( <IconMenu iconButtonElement={<IconButton iconClassName="synicon-view-column" />} closeOnItemTouchTap={false} > {columns.map((column) => ( <ColumnsFilterMenuListItem column={column} checkToggleColumn={checkToggleColumn} /> ))} </IconMenu> ); export default ColumnsFilterMenu;
src/containers/DevTools.js
magnusbae/laughing-octo-eureka
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> );
packages/components/src/SidePanel/SidePanel.stories.js
Talend/ui
/* eslint-disable react/no-multi-comp */ import React from 'react'; import { action } from '@storybook/addon-actions'; import Layout from '../Layout'; import SidePanel from './SidePanel.component'; import appStyle from '../../stories/config/themes.scss'; const actions = [ { label: 'Preparations', icon: 'talend-dataprep', onClick: action('Preparations clicked'), active: true, }, { label: 'Datasets', icon: 'talend-download', onClick: action('Datasets clicked'), }, { label: 'Favorites', icon: 'talend-star', onClick: action('Favorites clicked'), }, ]; const actionsLinks = [ { label: 'Preparations', icon: 'talend-dataprep', href: '/preparations', active: true, }, { label: 'Datasets', icon: 'talend-download', href: '/datasets', }, { label: 'Favorites', icon: 'talend-star', href: '/favorites', }, ]; const items = [ { key: 'preparations', label: 'Preparations', icon: 'talend-dataprep', }, { key: 'datasets', label: 'Datasets', icon: 'talend-download', }, { key: 'favorites', label: 'Favorites', icon: 'talend-star', }, ]; const other = [ { key: 'users', label: 'Users', icon: 'talend-user-circle', }, { key: 'groups', label: 'Groups', icon: 'talend-group-circle', }, { key: 'roles', label: 'Roles', icon: 'talend-roles', }, { key: 'licenses', label: 'Licenses', icon: 'talend-license', }, { key: 'projects', label: 'Projects', icon: 'talend-projects', }, { key: 'activity', label: 'Activity', icon: 'talend-activity', }, ]; export default { title: 'Navigation/SidePanel', }; export const Uncontrolled = () => ( <SidePanel id="context" actions={actions} onSelect={action('onItemSelect')} tooltipPlacement="top" /> ); export const Controlled = () => ( <SidePanel id="context" actions={actions} onSelect={action('onItemSelect')} onToggleDock={action('onToggleDock')} tooltipPlacement="top" /> ); export const Links = () => <SidePanel id="context" actions={actionsLinks} tooltipPlacement="top" />; export const Docked = () => <SidePanel actions={actions} docked tooltipPlacement="top" />; export const Minimised = () => ( <SidePanel actions={actions} onToggleDock={action('Toggle dock clicked')} minimised tooltipPlacement="top" /> ); export const WithALargeAmountOfItems = () => ( <SidePanel actions={[...items, ...other, ...other, ...other]} onSelect={action('onItemSelect')} selected={items[1]} tooltipPlacement="top" /> ); export const Reverse = () => ( <SidePanel actions={items} onSelect={action('onItemSelect')} selected={items[1]} reverse tooltipPlacement="top" /> ); export const ReverseLargeDocked = () => ( <SidePanel actions={items} onSelect={action('onItemSelect')} selected={items[1]} reverse large minimised dockable={false} tooltipPlacement="top" /> ); export const _WithLayout = () => { class WithLayout extends React.Component { constructor() { super(); this.state = { docked: false }; } render() { const panel = ( <SidePanel actions={[...items, ...other, ...other, ...other]} onSelect={action('onItemSelect')} docked={this.state.docked} tooltipPlacement="top" /> ); return ( <Layout mode="TwoColumns" one={panel}> <ol> {new Array(100).fill('This is some random content').map((item, num) => ( <li key={num}>{item}</li> ))} </ol> </Layout> ); } } return <WithLayout />; }; export const ReverseWithLayout = () => { const panelItems = items.concat([ { key: 'longname', label: 'Some super super super long name', icon: 'talend-world', }, ]); const panel = ( <SidePanel actions={panelItems} onSelect={action('onItemSelect')} reverse tooltipPlacement="top" /> ); return ( <Layout mode="TwoColumns" one={panel}> <ol> {new Array(100).fill('This is some random content').map((item, num) => ( <li key={num}>{item}</li> ))} </ol> </Layout> ); }; export const PortalReverse = () => ( <div className={appStyle.portal}> <h1>SidePanel</h1> <p> Keep sidePanel reverse style even if <em>t7</em> styles are applied. </p> <div className={Layout.TALEND_T7_THEME_CLASSNAME} style={{ height: '100vh' }}> <SidePanel id="context" actions={actions} tooltipPlacement="top" reverse /> </div> </div> );
node_modules/react-router/es/MemoryRouter.js
Aznachang/CompanyPersonelReactJS
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createMemoryHistory'; import Router from './Router'; /** * The public API for a <Router> that stores location in memory. */ var MemoryRouter = function (_React$Component) { _inherits(MemoryRouter, _React$Component); function MemoryRouter() { var _temp, _this, _ret; _classCallCheck(this, MemoryRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } MemoryRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return MemoryRouter; }(React.Component); MemoryRouter.propTypes = { initialEntries: PropTypes.array, initialIndex: PropTypes.number, getUserConfirmation: PropTypes.func, keyLength: PropTypes.number, children: PropTypes.node }; export default MemoryRouter;
src/svg-icons/content/low-priority.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentLowPriority = (props) => ( <SvgIcon {...props}> <path d="M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z"/> </SvgIcon> ); ContentLowPriority = pure(ContentLowPriority); ContentLowPriority.displayName = 'ContentLowPriority'; ContentLowPriority.muiName = 'SvgIcon'; export default ContentLowPriority;
react/components/HousingDisplay.js
sonicolasj/gitehub
import React from 'react' import { Text, View, Image, Button, Share } from 'react-native' import RNCalendarEvents from 'react-native-calendar-events'; export default class HousingDisplay extends React.Component { constructor(props) { super(props); this.props.housing = this.props.housing || { listing: {}, pricing_quote: {} }; this.addToCalendar = this.addToCalendar.bind(this); this.share = this.share.bind(this); } render() { return ( <View> <Image style={{width: 64, height: 64}} source={{uri: this.props.housing.listing.picture_url}} /> <Text>{this.props.housing.listing.name}</Text> <Button title="Ajouter à l'agenda" onPress={() => this.addToCalendar()} /> <Button title="Partager par SMS" onPress={() => this.share()} /> </View> ); } addToCalendar() { let housing = this.props.housing; RNCalendarEvents.saveEvent(housing.listing.name, { location: housing.listing.public_address, startDate: housing.pricing_quote.check_in, endDate: housing.pricing_quote.check_out }); } share() { let housing = this.props.housing; Share.share({ title: 'Réservation GiteHub', message: `Réservation GiteHub\n\nDate de début : ${housing.pricing_quote.check_in}\nDate de fin : ${housing.pricing_quote.check_out}\n\nAdresse : ${housing.listing.public_address}\nDescription : "${housing.listing.name}"` }); } }
form/views/ReCaptchaFieldView.js
ExtPoint/yii2-frontend
import React from 'react'; import PropTypes from 'prop-types'; import ReCaptcha from 'react-google-recaptcha'; import {html} from 'components'; import FieldWrapper from './FieldWrapper'; const bem = html.bem('ReCaptchaFieldView'); export default class ReCaptchaFieldView extends React.Component { static propTypes = { className: PropTypes.string, reCaptchaProps: PropTypes.object, }; render() { return ( <FieldWrapper {...this.props} className={bem( bem.block(), this.props.className, )} > <div className={bem.element('container')}> <ReCaptcha {...this.props.reCaptchaProps} className={bem.element('captcha')} /> </div> </FieldWrapper> ); } }
app/components/Footer/index.js
michiganhackers/website
/* * Footer * */ import React from 'react'; import styled from 'styled-components'; import SectionHeader from 'components/SectionHeader'; const SocialLinkContainer = styled.div` display: flex; justify-content: center; `; const SocialLink = styled.div` width: 60px; height: 60px; margin: 15px; border-radius: 50%; background-color: white; `; const FooterWrapper = styled.div` background-color: #f38552; padding: 30px 0; `; class Footer extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <FooterWrapper> <SocialLinkContainer> <SocialLink /> <SocialLink /> <SocialLink /> </SocialLinkContainer> </FooterWrapper> ); } } export default Footer;
public/kibana-integrations/kibana-vis.js
wazuh/wazuh-kibana-app
/* * Wazuh app - React component for custom kibana visualizations. * Copyright (C) 2015-2022 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component } from 'react'; import $ from 'jquery'; import dateMath from '@elastic/datemath'; import { DiscoverPendingUpdates } from '../factories/discover-pending-updates'; import { connect } from 'react-redux'; import { LoadedVisualizations } from '../factories/loaded-visualizations'; import { RawVisualizations } from '../factories/raw-visualizations'; import { VisHandlers } from '../factories/vis-handlers'; import { AppState } from '../react-services'; import { TabVisualizations } from '../factories/tab-visualizations'; import store from '../redux/store'; import { updateMetric } from '../redux/actions/visualizationsActions'; import { GenericRequest } from '../react-services/generic-request'; import { createSavedVisLoader } from './visualizations/saved_visualizations'; import { WzDatePicker } from '../components/wz-date-picker/wz-date-picker'; import { EuiLoadingChart, EuiLoadingSpinner, EuiToolTip, EuiIcon, EuiFlexItem, EuiFlexGroup, EuiEmptyPrompt } from '@elastic/eui'; import { getAngularModule, getToasts, getVisualizationsPlugin, getSavedObjects, getDataPlugin, getChrome, getOverlays, getPlugins, } from '../kibana-services'; import { KnownFields } from '../utils/known-fields'; import { union } from 'lodash'; import { getFilterWithAuthorizedAgents } from '../react-services/filter-authorization-agents'; import { AUTHORIZED_AGENTS } from '../../common/constants'; class KibanaVis extends Component { _isMounted = false; constructor(props) { super(props); this.lockFields = false; this.implicitFilter = ''; this.rawFilters = []; this.rendered = false; this.visualization = null; this.visHandler = null; this.renderInProgress = false; this.deadField = false; this.mapClicked = false; this.updateMetric = updateMetric; this.genericReq = GenericRequest; this.discoverPendingUpdates = new DiscoverPendingUpdates(); this.loadedVisualizations = new LoadedVisualizations(); this.rawVisualizations = new RawVisualizations(); this.visHandlers = new VisHandlers(); this.tabVisualizations = new TabVisualizations(); this.state = { visRefreshingIndex: false, }; const services = { savedObjectsClient: getSavedObjects().client, indexPatterns: getDataPlugin().indexPatterns, search: getDataPlugin().search, chrome: getChrome(), overlays: getOverlays(), savedObjects: getPlugins().savedObjects, }; const servicesForVisualizations = { ...services, ...{ visualizationTypes: getVisualizationsPlugin() }, }; this.savedObjectLoaderVisualize = createSavedVisLoader(servicesForVisualizations); this.visID = this.props.visID; this.tab = this.props.tab; } showToast = (color, title, text, time) => { getToasts().add({ color: color, title: title, text: text, toastLifeTimeMs: time, }); }; componentDidMount() { this._isMounted = true; const app = getAngularModule(); this.$rootScope = app.$injector.get('$rootScope'); } componentWillUnmount() { if (this._isMounted) { this._isMounted = false; this.updateVis(); this.destroyAll(); } } componentDidUpdate() { if (this.props.state.shouldUpdate && !this.state.visRefreshingIndex) { this.updateVis(); } } updateVis() { if (this.deadField) { return this.renderComplete(); } const rawVis = this.rawVisualizations.getList(); if (Array.isArray(rawVis) && rawVis.length) { this.myRender(rawVis); } } async callUpdateMetric() { try { if (this.visHandler) { const data = await this.visHandler.handler.execution.getData(); if ( data && data.value && data.value.visData && data.value.visData.rows && this.props.state[this.visID] !== data.value.visData.rows['0']['col-0-1'] ) { store.dispatch( this.updateMetric({ name: this.visID, value: data.value.visData.rows['0']['col-0-1'], }) ); } // This check if data.value.visData.tables exists and dispatch that value as stat // FIXME: this is correct? if ( data && data.value && data.value.visData && data.value.visData.tables && data.value.visData.tables.length && data.value.visData.tables['0'] && data.value.visData.tables['0'].rows && data.value.visData.tables['0'].rows['0'] && this.props.state[this.visID] !== data.value.visData.tables['0'].rows['0']['col-0-2'] ) { store.dispatch( this.updateMetric({ name: this.visID, value: data.value.visData.tables['0'].rows['0']['col-0-2'], }) ); } } } catch (error) { this.showToast('danger', 'Error', error.message || error, 4000); } } calculateTimeFilterSeconds = ({ from, to }) => { try { const fromParsed = dateMath.parse(from); const toParsed = dateMath.parse(to); const totalSeconds = (toParsed - fromParsed) / 1000; return totalSeconds; } catch (error) { return 0; } }; setSearchSource = (discoverList) => { try { const isCluster = this.visID.includes('Cluster'); if (isCluster) { // Checks for cluster.name or cluster.node filter existence const monitoringFilter = discoverList[1].filter( (item) => item && item.meta && item.meta.key && (item.meta.key.includes('cluster.name') || item.meta.key.includes('cluster.node')) ); // Applying specific filter to cluster monitoring vis if (Array.isArray(monitoringFilter) && monitoringFilter.length) { this.visualization.searchSource.setField('filter', monitoringFilter); } } } catch (error) { this.showToast('danger', 'Error', error.message || error, 4000); } }; myRender = async (raw) => { const timefilter = getDataPlugin().query.timefilter.timefilter; try { const discoverList = this.discoverPendingUpdates.getList(); const isAgentStatus = this.visID === 'Wazuh-App-Overview-General-Agents-status'; const timeFilterSeconds = this.calculateTimeFilterSeconds(timefilter.getTime()); const timeRange = isAgentStatus && timeFilterSeconds < 900 ? { from: 'now-15m', to: 'now', mode: 'quick' } : timefilter.getTime(); let filters = isAgentStatus ? [ { meta: { index: 'wazuh-monitoring-*', alias: null, negate: false, disabled: false, }, query: { bool: { should: [ { term: AppState.getClusterInfo().status === 'enabled' ? { 'cluster.name': AppState.getClusterInfo().cluster } : { 'manager.keyword': AppState.getClusterInfo().manager }, }, ], }, }, $state: { store: 'appState', }, }, ] : discoverList[1] || []; const query = !isAgentStatus ? discoverList[0] : {}; const rawVis = raw ? raw.filter((item) => item && item.id === this.visID) : []; if (rawVis.length && discoverList.length) { let vizPattern; try { vizPattern = JSON.parse(rawVis[0].attributes.kibanaSavedObjectMeta.searchSourceJSON) .index; } catch (ex) { console.warn(`plugin platform-vis exception: ${ex.message || ex}`); } if (!filters.find((filter) => filter.meta.controlledBy === AUTHORIZED_AGENTS)) { const agentsFilters = getFilterWithAuthorizedAgents(this.props.allowedAgents, vizPattern); filters = agentsFilters ? union(filters, [agentsFilters]) : filters; } const visInput = { timeRange, filters, query, }; // There are pending updates from the discover (which is the one who owns the true app state) if (!this.visualization && !this.rendered && !this.renderInProgress) { // There's no visualization object -> create it with proper filters this.renderInProgress = true; this.visualization = await this.savedObjectLoaderVisualize.get(this.visID, rawVis[0]); this.visualization.searchSource = await getDataPlugin().search.searchSource.create(); // Visualization doesn't need the "_source" this.visualization.searchSource.setField('source', false); // Visualization doesn't need "hits" this.visualization.searchSource.setField('size', 0); const visState = await getVisualizationsPlugin().convertToSerializedVis( this.visualization ); const vis = await getVisualizationsPlugin().createVis( this.visualization.visState.type, visState ); this.visHandler = await getVisualizationsPlugin().__LEGACY.createVisEmbeddableFromObject( vis, visInput ); await this.visHandler.render($(`[id="${this.visID}"]`)[0]); this.visHandler.handler.data$.subscribe(this.renderComplete()); this.visHandlers.addItem(this.visHandler); this.setSearchSource(discoverList); } else if (this.rendered && !this.deadField) { // There's a visualization object -> just update its filters if (this.props.isMetric) { this.callUpdateMetric(); } this.rendered = true; this.$rootScope.rendered = 'true'; this.visHandler.updateInput(visInput); this.setSearchSource(discoverList); } if (this.state.visRefreshingIndex) this.setState({ visRefreshingIndex: false }); } } catch (error) { if (((error || {}).message || '').includes('not locate that index-pattern-field')) { if (this.deadField) { this.tabVisualizations.addDeadVis(); return this.renderComplete(); } const match = error.message.match(/id:(.*)\)/); this.deadField = match[1] || true; if (this.props.refreshKnownFields && !this.hasRefreshed) { this.hasRefreshed = true; this.setState({ visRefreshingIndex: true }); this.deadField = false; this.visualization = null; this.renderInProgress = false; this.rendered = false; // if there's a field name it looks for known fields structures const foundField = match[1] && KnownFields.find((field) => field.name === match[1].trim()); await this.props.refreshKnownFields(foundField); } this.renderInProgress = false; return this.myRender(raw); } else { console.error(error); } } return; }; destroyAll = () => { try { this.visualization.destroy(); } catch (error) {} // eslint-disable-line try { this.visHandler.destroy(); this.visHandler = null; } catch (error) {} // eslint-disable-line }; renderComplete = async () => { const visId = this.visID.toLowerCase(); if (!visId.includes(this.props.tab)) { this.destroyAll(); return; } this.rendered = true; this.loadedVisualizations.addItem(true); const currentLoaded = this.loadedVisualizations.getList().length; const deadVis = this.props.tab === 'ciscat' ? 0 : this.tabVisualizations.getDeadVis(); const totalTabVis = this.tabVisualizations.getItem(this.props.tab) - deadVis; this.$rootScope.loadingStatus = 'Fetching data...'; if (totalTabVis < 1) { this.$rootScope.resultState = 'none'; } else { const currentCompleted = Math.round((currentLoaded / totalTabVis) * 100); if (currentCompleted >= 100) { this.$rootScope.rendered = 'true'; if (visId.includes('AWS-geo')) { const canvas = $('.visChart.leaflet-container .leaflet-control-zoom-in'); setTimeout(() => { if (!this.mapClicked) { this.mapClicked = true; canvas[0].click(); } }, 1000); } } else if (this.visID !== 'Wazuh-App-Overview-General-Agents-status') { this.$rootScope.rendered = 'false'; } } }; showDateRangePicker = () => { return !this.deadField && !this.state.visRefreshingIndex && this.visID === 'Wazuh-App-Overview-General-Agents-status' } DateRangePickerComponent = () => { return ( <EuiFlexItem className="agents-evolutions-dpicker"> <WzDatePicker condensed={true} onTimeChange={() => {}} /> </EuiFlexItem> ) } render() { const isLoading = this.props.resultState === 'loading'; return ( this.visID && ( <span> <div style={{ display: this.state.visRefreshingIndex ? 'block' : 'none', textAlign: 'center', paddingTop: 100, }} > <EuiFlexGroup style={{ placeItems: 'center' }}> <EuiFlexItem></EuiFlexItem> <EuiFlexItem grow={false}> <EuiLoadingSpinner size="xl" /> </EuiFlexItem> <EuiFlexItem grow={false}>Refreshing Index Pattern.</EuiFlexItem> <EuiFlexItem></EuiFlexItem> </EuiFlexGroup> </div> <div style={{ display: isLoading && !this.state.visRefreshingIndex ? 'block' : 'none', textAlign: 'center', paddingTop: 100, }} > <EuiLoadingChart size="xl" /> </div> <div style={{ display: this.deadField && !isLoading && !this.state.visRefreshingIndex ? 'block' : 'none', textAlign: 'center', paddingTop: 100, }} > No results found &nbsp; <EuiToolTip position="top" content={ <span> No alerts were found with the field: <strong>{this.deadField}</strong> </span> } > <EuiIcon type="iInCircle" /> </EuiToolTip> </div> { !this.isLoading && this.showDateRangePicker() && this.DateRangePickerComponent() } <div id={this.visID} vis-id={this.visID} style={{ display: isLoading ? 'none' : 'block', height: '100%', paddingTop: '2%' }} ></div> <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', }}> {(isLoading && <div><EuiLoadingChart size="xl" /></div>) || (this.deadField && !isLoading && !this.state.visRefreshingIndex && ( <div> No results found &nbsp; <EuiToolTip position="top" content={ <span> No alerts were found with the field: <strong>{this.deadField}</strong> </span> } > <EuiIcon type="iInCircle" /> </EuiToolTip> </div> )) || (this.state.visRefreshingIndex && ( <EuiFlexGroup justifyContent="center" alignItems="center"> <EuiFlexItem grow={false}> <EuiLoadingSpinner size="xl" /> </EuiFlexItem> <EuiFlexItem grow={false}>Refreshing Index Pattern.</EuiFlexItem> </EuiFlexGroup> )) } </div> </span> ) ); } } const mapStateToProps = (state) => { return { state: state.visualizationsReducers, allowedAgents: state.appStateReducers.allowedAgents, }; }; export default connect(mapStateToProps, null)(KibanaVis);
src/container/user/login.js
mxczpiscioneri/ipaday-react-native
import React, { Component } from 'react'; import { StyleSheet, AsyncStorage, View, Image } from 'react-native'; import { Container, Header, Left, Body, Button, Icon, Title, Content, Text, Spinner } from 'native-base'; import { connect } from 'react-redux'; import FBSDK, { FBLoginManager, LoginButton, AccessToken } from 'react-native-fbsdk'; import firebase from '../../utils/firebase'; const LOGO = require('../../images/logo-circle.png'); const BACKGROUND = require('../../images/background-login.jpg'); class Beers extends Component { constructor(props) { super(props); this.state = { drawer: false, user: null }; } componentWillMount() { const { params } = this.props.navigation.state; const Drawer = params || {}; this.setState({drawer: Drawer.Drawer}); } render() { return ( this.state.user ? ( <Container> <Header style={{ backgroundColor: '#f94840' }} androidStatusBarColor='#f83830'></Header> <Content style={{ backgroundColor: '#fff' }}> <Spinner /> </Content> </Container> ) : ( <Container> <Header style={{ backgroundColor: '#f94840' }} androidStatusBarColor='#f83830'> {this.state.drawer ? ( <Left> <Button transparent onPress={() => this.props.navigation.navigate('DrawerOpen')}> <Icon name='menu' /> </Button> </Left> ) : ( null )} <Body> <Title>Login</Title> </Body> </Header> <Image style={styles.backgroundImage} source={BACKGROUND} > <Image square style={styles.logo} source={LOGO} /> <Text style={styles.title}>IPA DAY</Text> <LoginButton readPermissions={["public_profile", "email"]} onLoginFinished={ (error, result) => { if (error) { alert("Login failed with error: " + result.error); } else if (result.isCancelled) { alert("Login was cancelled"); } else { const { navigate } = this.props.navigation; AccessToken.getCurrentAccessToken().then((data) => { const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken); firebase.auth().signInWithCredential(credential).then(async (result) => { const user = result._user; user.token = credential.token; await AsyncStorage.setItem('user', JSON.stringify(user)); navigate("Beers"); }, (error) => { console.log(error); }); }, (error) => { console.log(error); }); } } } onLogoutFinished={async () => { this.setState({drawer: false}); await AsyncStorage.removeItem('user'); }}/> </Image> </Container> ) ); } } const styles = StyleSheet.create({ logo: { marginTop: 50, height: 200, width: 200 }, title: { color: "#004226", fontSize: 48, fontWeight: "bold", marginTop: 30, marginBottom: 60, }, backgroundImage: { flex: 1, width: undefined, height: undefined, alignItems: 'center', } }); const mapStateToProps = state => { return ( { } ) } export default connect(mapStateToProps, { })(Beers)
src/components/Nav.js
nickeblewis/walkapp
/** * Component that lists all Posts */ import React from 'react' import { Link } from 'react-router' import { graphql } from 'react-apollo' import { withRouter } from 'react-router' import gql from 'graphql-tag' class Nav extends React.Component { static propTypes = { router: React.PropTypes.object.isRequired, data: React.PropTypes.object, } _logout = () => { // remove token from local storage and reload page to reset apollo client window.localStorage.removeItem('graphcoolToken') location.reload() // this.props.router.push('/') } _showLogin = () => { this.props.router.push('/login') } _showSignup = () => { this.props.router.push('/signup') } _isLoggedIn = () => { return this.props.data.user } renderLoggedIn() { return ( <header className="bg-black-90 w-100 ph3 pv3 pv4-ns ph4-m ph5-l"> <nav className="f6 fw6 ttu tracked"> <Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/" >Home</Link> {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/events" >Events</Link> */} {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/walks" >Walks</Link> */} {/* <Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/photos" >Photos</Link> */} {/* <Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/places" >Places</Link> */} {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/contacts" >Search</Link> */} {/* <span className="f6 fw4 hover-white no-underline white-50 dn dib-l pv2 ph3"> Logged in as {this.props.data.user.name} </span> <span onClick={this._logout} className="f6 fw4 hover-white no-underline white-70 dib ml2 pv2 ph3 ba">Logout</span> */} </nav> </header> ) } renderLoggedOut() { return ( <header className="bg-black-90 w-100 ph3 pv3 pv4-ns ph4-m ph5-l"> <nav className="f6 fw6 ttu tracked"> <Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/" >Home</Link> {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/events" >Events</Link> */} {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" to="/walks" >Walks</Link> */} {/* <Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/photos" >Photos</Link> */} {/* <Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/places" >Places</Link> */} {/*<Link className="f6 fw4 hover-white no-underline white-70 dn dib-l pv2 ph3" to="/contacts" >Search</Link> */} {/* <span onClick={this._showLogin} className="f6 fw4 hover-white no-underline white-70 dib ml2 pv2 ph3 ba">Login</span> <span onClick={this._showSignup} className="f6 fw4 hover-white no-underline white-70 dib ml2 pv2 ph3 ba">Sign Up</span> */} </nav> </header> ) } render () { // const headerImg = '../assets/iStock-504241498.jpg'; // const headerImg = 'http://mrmrs.io/photos/u/011.jpg'; //./iStock-504241498.jpg'; if (this._isLoggedIn()) { return this.renderLoggedIn() } else { return this.renderLoggedOut() } } } const userQuery = gql` query { user { id name } } ` export default graphql(userQuery, { options: {forceFetch: true }})(withRouter(Nav))
client/components/AmountWell.js
robinmoussu/kresus
import React from 'react'; import T from './Translated'; export class AmountWell extends React.Component { constructor(props) { // this.props = { // backgroundColor, // title, // subtitle, // operations, // initialAmount, // filterFunction // } super(props); } ComputeTotal(operations) { var total = operations .filter(this.props.filterFunction) .reduce((a,b) => a + b.amount, this.props.initialAmount); return (total * 100 | 0) / 100; } getTotal() { return this.ComputeTotal(this.props.operations); } render() { let style = "well " + this.props.backgroundColor; return ( <div className={this.props.size}> <div className={style}> <span className="operation-amount">{this.getTotal()} €</span><br/> <span className="well-title">{this.props.title}</span><br/> <span className="well-sub">{this.props.subtitle}</span> </div> </div>); } } export class FilteredAmountWell extends AmountWell { constructor(props) { // this.props = { // hasFilteredOperations, // filteredOperations, // operations // } super(props); } static FilterOperationsThisMonth(operations) { var now = new Date(); return operations.filter(function(op) { var d = new Date(op.date); return d.getFullYear() == now.getFullYear() && d.getMonth() == now.getMonth() }); } getTotal() { if (this.props.hasFilteredOperations) return super.ComputeTotal(this.props.filteredOperations); return super.ComputeTotal(FilteredAmountWell.FilterOperationsThisMonth(this.props.operations)); } render() { let style = "well " + this.props.backgroundColor; let filtered = this.props.hasFilteredOperations; let sub = filtered ? <T k='amount_well.current_search'>For this search</T> : <T k='amount_well.this_month'>This month</T>; return ( <div className={this.props.size}> <div className={style}> <span className="operation-amount">{this.getTotal()} €</span><br/> <span className="well-title">{this.props.title}</span><br/> <span className="well-sub">{sub}</span> </div> </div>); } }
src/index.js
chenqingspring/react-lottie
import React from 'react'; import PropTypes from 'prop-types'; import lottie from 'lottie-web'; export default class Lottie extends React.Component { componentDidMount() { const { options, eventListeners, } = this.props; const { loop, autoplay, animationData, rendererSettings, segments, } = options; this.options = { container: this.el, renderer: 'svg', loop: loop !== false, autoplay: autoplay !== false, segments: segments !== false, animationData, rendererSettings, }; this.options = { ...this.options, ...options }; this.anim = lottie.loadAnimation(this.options); this.registerEvents(eventListeners); } componentWillUpdate(nextProps /* , nextState */) { /* Recreate the animation handle if the data is changed */ if (this.options.animationData !== nextProps.options.animationData) { this.deRegisterEvents(this.props.eventListeners); this.destroy(); this.options = {...this.options, ...nextProps.options}; this.anim = lottie.loadAnimation(this.options); this.registerEvents(nextProps.eventListeners); } } componentDidUpdate() { if (this.props.isStopped) { this.stop(); } else if (this.props.segments) { this.playSegments(); } else { this.play(); } this.pause(); this.setSpeed(); this.setDirection(); } componentWillUnmount() { this.deRegisterEvents(this.props.eventListeners); this.destroy(); this.options.animationData = null; this.anim = null; } setSpeed() { this.anim.setSpeed(this.props.speed); } setDirection() { this.anim.setDirection(this.props.direction); } play() { this.anim.play(); } playSegments() { this.anim.playSegments(this.props.segments); } stop() { this.anim.stop(); } pause() { if (this.props.isPaused && !this.anim.isPaused) { this.anim.pause(); } else if (!this.props.isPaused && this.anim.isPaused) { this.anim.pause(); } } destroy() { this.anim.destroy(); } registerEvents(eventListeners) { eventListeners.forEach((eventListener) => { this.anim.addEventListener(eventListener.eventName, eventListener.callback); }); } deRegisterEvents(eventListeners) { eventListeners.forEach((eventListener) => { this.anim.removeEventListener(eventListener.eventName, eventListener.callback); }); } handleClickToPause = () => { // The pause() method is for handling pausing by passing a prop isPaused // This method is for handling the ability to pause by clicking on the animation if (this.anim.isPaused) { this.anim.play(); } else { this.anim.pause(); } } render() { const { width, height, ariaRole, ariaLabel, isClickToPauseDisabled, title, } = this.props; const getSize = (initial) => { let size; if (typeof initial === 'number') { size = `${initial}px`; } else { size = initial || '100%'; } return size; }; const lottieStyles = { width: getSize(width), height: getSize(height), overflow: 'hidden', margin: '0 auto', outline: 'none', ...this.props.style, }; const onClickHandler = isClickToPauseDisabled ? () => null : this.handleClickToPause; return ( // Bug with eslint rules https://github.com/airbnb/javascript/issues/1374 // eslint-disable-next-line jsx-a11y/no-static-element-interactions <div ref={(c) => { this.el = c; }} style={lottieStyles} onClick={onClickHandler} title={title} role={ariaRole} aria-label={ariaLabel} tabIndex="0" /> ); } } Lottie.propTypes = { eventListeners: PropTypes.arrayOf(PropTypes.object), options: PropTypes.object.isRequired, height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), isStopped: PropTypes.bool, isPaused: PropTypes.bool, speed: PropTypes.number, segments: PropTypes.arrayOf(PropTypes.number), direction: PropTypes.number, ariaRole: PropTypes.string, ariaLabel: PropTypes.string, isClickToPauseDisabled: PropTypes.bool, title: PropTypes.string, style: PropTypes.string, }; Lottie.defaultProps = { eventListeners: [], isStopped: false, isPaused: false, speed: 1, ariaRole: 'button', ariaLabel: 'animation', isClickToPauseDisabled: false, title: '', };
src/server/render.js
nefa/Leeact
import DocumentTitle from 'react-document-title'; import Html from './html'; import Promise from 'bluebird'; import React from 'react'; import Router from 'react-router'; import config from './config'; import initialState from './initialstate'; import routes from '../client/routes'; import {state} from '../client/state'; var ReactDOMServer = require('react-dom/server') export default function render(req, res, locale) { const path = req.path; return loadData(path, locale) .then((appState) => renderPage(req, res, appState, path)); } function loadData(path, locale) { // TODO: Preload and merge user specific state. const appState = initialState; return new Promise((resolve, reject) => { resolve(appState); }); } // TODO: Refactor. function renderPage(req, res, appState, path) { return new Promise((resolve, reject) => { const router = Router.create({ routes, location: path, onError: reject, onAbort: (abortReason) => { if (abortReason.constructor.name === 'Redirect') { const {to, params, query} = abortReason; const path = router.makePath(to, params, query); res.redirect(path); resolve(); return; } reject(abortReason); } }); router.run((Handler, routerState) => { state.load(appState); const html = getPageHtml(Handler, appState, req.hostname); const notFound = routerState.routes.some(route => route.name === 'not-found'); const status = notFound ? 404 : 200; res.status(status).send(html); resolve(); }); }); } function renderSpinner() { return '<div class="LoadingBox">' + '<div class="LoadingSymbol">' + '<img class="LoadingImage" src="/assets/img/bbloading.gif" width="160" height="36" alt="Loading..." />' + '</div>' + '<span class="LoadingText">Loading BetBrain...</span>' + '</div>' } function getPageHtml(Handler, appState, hostname) { const appHtml = `<div id="app">${ReactDOMServer.renderToString(<Handler />)}</div>`; const appScriptSrc = config.isProduction ? '/build/app.js?v=' + config.version : `\/\/${hostname}:8888/build/app.js`; let scriptHtml = ` <script> (function() { window._appState = ${JSON.stringify(appState)}; var app = document.createElement('script'); app.type = 'text/javascript'; app.async = true; var src = '${appScriptSrc}'; // IE<11 and Safari need Intl polyfill. if (!window.Intl) src = src.replace('.js', 'intl.js'); app.src = src; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(app, s); })(); </script>`; if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X') scriptHtml += ` <script> (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.getElementsByTagName(i)[0]; e.src='//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','${config.googleAnalyticsId}');ga('send','pageview'); </script>`; const title = DocumentTitle.rewind(); return '<!DOCTYPE html>' + ReactDOMServer.renderToStaticMarkup( <Html bodyHtml={appHtml + scriptHtml} isProduction={config.isProduction} title={title} version={config.version} /> ); }
examples/huge-apps/components/GlobalNav.js
barretts/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); export default GlobalNav;
src/rsg-components/Props/PropsRenderer.js
bluetidepro/react-styleguidist
import React from 'react'; import PropTypes from 'prop-types'; import Group from 'react-group'; import objectToString from 'javascript-stringify'; import Arguments from 'rsg-components/Arguments'; import Argument from 'rsg-components/Argument'; import Code from 'rsg-components/Code'; import JsDoc from 'rsg-components/JsDoc'; import Markdown from 'rsg-components/Markdown'; import Name from 'rsg-components/Name'; import Type from 'rsg-components/Type'; import Text from 'rsg-components/Text'; import Para from 'rsg-components/Para'; import Table from 'rsg-components/Table'; import { unquote, getType, showSpaces } from './util'; function renderType(type) { if (!type) { return 'unknown'; } const { name } = type; switch (name) { case 'arrayOf': return `${type.value.name}[]`; case 'objectOf': return `{${renderType(type.value)}}`; case 'instanceOf': return type.value; default: return name; } } function renderFlowType(type) { if (!type) { return 'unknown'; } const { name, raw, value } = type; switch (name) { case 'enum': return name; case 'literal': return value; case 'signature': return renderComplexType(type.type, raw); case 'union': case 'tuple': return renderComplexType(name, raw); default: return raw || name; } } function renderComplexType(name, title) { return ( <Text size="small" underlined title={title}> <Type>{name}</Type> </Text> ); } function renderEnum(prop) { if (!Array.isArray(getType(prop).value)) { return <span>{getType(prop).value}</span>; } const values = getType(prop).value.map(({ value }) => ( <Code key={value}>{showSpaces(unquote(value))}</Code> )); return ( <span> One of:{' '} <Group separator=", " inline> {values} </Group> </span> ); } function renderShape(props) { const rows = []; for (const name in props) { const prop = props[name]; const defaultValue = renderDefault(prop); const description = prop.description; rows.push( <div key={name}> <Name>{name}</Name> {': '} <Type>{renderType(prop)}</Type> {defaultValue && ' — '} {defaultValue} {description && ' — '} {description && <Markdown text={description} inline />} </div> ); } return rows; } const defaultValueBlacklist = ['null', 'undefined']; function renderDefault(prop) { // Workaround for issue https://github.com/reactjs/react-docgen/issues/221 // If prop has defaultValue it can not be required if (prop.defaultValue) { if (prop.type || prop.flowType) { const propName = prop.type ? prop.type.name : prop.flowType.type; if (defaultValueBlacklist.indexOf(prop.defaultValue.value) > -1) { return <Code>{showSpaces(unquote(prop.defaultValue.value))}</Code>; } else if (propName === 'func' || propName === 'function') { return ( <Text size="small" color="light" underlined title={showSpaces(unquote(prop.defaultValue.value))} > Function </Text> ); } else if (propName === 'shape' || propName === 'object') { try { // We eval source code to be able to format the defaultProp here. This // can be considered safe, as it is the source code that is evaled, // which is from a known source and safe by default // eslint-disable-next-line no-eval const object = eval(`(${prop.defaultValue.value})`); return ( <Text size="small" color="light" underlined title={objectToString(object, null, 2)}> Shape </Text> ); } catch (e) { // eval will throw if it contains a reference to a property not in the // local scope. To avoid any breakage we fall back to rendering the // prop without any formatting return ( <Text size="small" color="light" underlined title={prop.defaultValue.value}> Shape </Text> ); } } } return <Code>{showSpaces(unquote(prop.defaultValue.value))}</Code>; } else if (prop.required) { return ( <Text size="small" color="light"> Required </Text> ); } return ''; } function renderDescription(prop) { const { description, tags = {} } = prop; const extra = renderExtra(prop); const args = [...(tags.arg || []), ...(tags.argument || []), ...(tags.param || [])]; const returnDocumentation = (tags.return && tags.return[0]) || (tags.returns && tags.returns[0]); return ( <div> {description && <Markdown text={description} />} {extra && <Para>{extra}</Para>} <JsDoc {...tags} /> {args.length > 0 && <Arguments args={args} heading />} {returnDocumentation && <Argument {...returnDocumentation} returns />} </div> ); } function renderExtra(prop) { const type = getType(prop); if (!type) { return null; } switch (type.name) { case 'enum': return renderEnum(prop); case 'union': return renderUnion(prop); case 'shape': return renderShape(prop.type.value); case 'arrayOf': if (type.value.name === 'shape') { return renderShape(prop.type.value.value); } return null; case 'objectOf': if (type.value.name === 'shape') { return renderShape(prop.type.value.value); } return null; default: return null; } } function renderUnion(prop) { const type = getType(prop); if (!Array.isArray(type.value)) { return <span>{type.value}</span>; } const values = type.value.map((value, index) => ( <Type key={`${value.name}-${index}`}>{renderType(value)}</Type> )); return ( <span> One of type:{' '} <Group separator=", " inline> {values} </Group> </span> ); } function renderName(prop) { const { name, tags = {} } = prop; return <Name deprecated={!!tags.deprecated}>{name}</Name>; } function renderTypeColumn(prop) { if (prop.flowType) { return <Type>{renderFlowType(getType(prop))}</Type>; } return <Type>{renderType(getType(prop))}</Type>; } export function getRowKey(row) { return row.name; } export const columns = [ { caption: 'Prop name', render: renderName, }, { caption: 'Type', render: renderTypeColumn, }, { caption: 'Default', render: renderDefault, }, { caption: 'Description', render: renderDescription, }, ]; export default function PropsRenderer({ props }) { return <Table columns={columns} rows={props} getRowKey={getRowKey} />; } PropsRenderer.propTypes = { props: PropTypes.array.isRequired, };
app/js/components/Header.js
raulalgo/scales-react
'use strict'; import React from 'react'; class Header extends React.Component { constructor(props) { super(props); } render() { return ( <header> helmantica </header> ); } } export default Header;
src/containers/TodoPage.js
kclowes/new-edit-blog-fe
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createNewTodo, getTodos } from '../store/todos/actions'; import TodoForm from '../components/TodoForm'; import TodosList from '../components/TodosList'; export class TodoPage extends Component { constructor(props) { super(props); this.state = { name: '', }; } componentDidMount() { this.props.dispatch(getTodos()); } handleChange = e => { this.setState({ name: e.target.value }); }; handleSubmit = () => { this.props.dispatch(createNewTodo(this.state.name)); this.setState({ name: '' }); }; render() { const { history, todos } = this.props; return ( <div> <TodoForm name={this.state.name} handleChange={e => this.handleChange(e)} handleSubmit={this.handleSubmit} /> <TodosList history={history} todos={todos} /> </div> ); } } TodoPage.propTypes = { dispatch: PropTypes.func, todos: PropTypes.array, }; function mapStateToProps(state) { return { todos: state.todos.list, }; } export default connect(mapStateToProps)(TodoPage);
src/js/components/icons/base/Volume.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-volume`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'volume'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M15,16 C17.209,16 19,14.209 19,12 C19,9.791 17.209,8 15,8 M15,20 C20,20 23,16.411 23,12 C23,7.589 19.411,4 15,4 M1,12 L1,8 L6,8 L12,3 L12,21 L6,16 L1,16 L1,12"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Volume'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
react-router-demo/lessons/12-navigating/modules/About.js
zhangjunhd/react-examples
import React from 'react' export default React.createClass({ render() { return <div>About</div> } })
client/views/admin/settings/inputs/PasswordSettingInput.stories.js
VoiSmart/Rocket.Chat
import { Field } from '@rocket.chat/fuselage'; import { action } from '@storybook/addon-actions'; import React from 'react'; import PasswordSettingInput from './PasswordSettingInput'; export default { title: 'admin/settings/inputs/PasswordSettingInput', component: PasswordSettingInput, decorators: [(storyFn) => <Field>{storyFn()}</Field>], }; export const _default = () => ( <PasswordSettingInput _id='setting_id' label='Label' placeholder='Placeholder' onChangeValue={action('changeValue')} onChangeEditor={action('changeEditor')} /> ); export const disabled = () => ( <PasswordSettingInput _id='setting_id' label='Label' placeholder='Placeholder' disabled /> ); export const withValue = () => ( <PasswordSettingInput _id='setting_id' label='Label' value='5w0rdf15h' placeholder='Placeholder' /> ); export const withResetButton = () => ( <PasswordSettingInput _id='setting_id' label='Label' placeholder='Placeholder' hasResetButton onChangeValue={action('changeValue')} onResetButtonClick={action('resetButtonClick')} /> );
components/illustrations/binary-search/item.js
skidding/illustrated-algorithms
import PropTypes from 'prop-types'; import React from 'react'; import EmojiBlock from '../shared/emoji-block'; export default function Item({ frame }, { layout }) { const { value, opacity, rotation, } = frame.item; const { top, left, } = layout.item; if (!value) { return null; } return ( <div className="item" style={{ opacity, transform: ` translate(${left}px, ${top}px) rotate(${rotation}deg) ` }} > <EmojiBlock name={value} glow={0.4}/> <style jsx>{` .item { position: absolute; will-change: opacity, transform; } `} </style> </div> ); } Item.propTypes = { frame: PropTypes.object.isRequired, }; Item.contextTypes = { layout: PropTypes.object, };
src/containers/Form/NumberPage.js
Aus0049/react-component
/** * Created by Aus on 2017/7/31. */ import React from 'react' import ListTitle from '../../components/DataDisplay/ListTitle/' import {Number} from '../../components/Form/' import Tools from '../../components/Tools/Tools' class NumberPage extends React.Component { constructor (props) { super(props); this.state = { value1: 12.2, value2: 0, value3: '1.2' }; } handleChange (type, value) { this.setState({ [type]: value.value }); } render () { const {value1, value2, value3} = this.state; return ( <div className="page number"> <h1 className="title"> <i className="fa fa-home" onClick={()=>{Tools.linkTo('/index')}} /> Number </h1> <ListTitle title="普通" /> <div className='zby-form-box'> <Number required labelName="数值" value={value1} placeHolder="请输入数值" unit="%" onChange={this.handleChange.bind(this, 'value1')} /> <Number required controlled={false} labelName="不受控组件" value={value2} placeHolder="请输入数值" unit="万" /> <Number readOnly labelName="readOnly" value={value3} placeHolder="请输入数值" unit="单位" /> </div> </div> ) } } export default NumberPage
src/app/powerRanger/components/PowerRangerDetail.js
brandondewitt/react-transform-boilerplate
import React, { Component } from 'react'; import { Link } from 'react-router'; export class PowerRangerDetail extends Component { render() { let { powerRanger } = this.props; return ( <div> <Link className='btn btn-default' to={`/powerRangers/${powerRanger.id}/edit`}>Edit</Link> <div>id: {powerRanger.id}</div> <div>name: {powerRanger.name}</div> </div> ); } }
src/client/config/routes.js
trippian/trippian
import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import { App, Home, About, JoinUs, NotFound, Press, Destination, DestinationDetail, DestinationPost, Contact, InquiryAdd, InquiryDetail, InquiryList, Login, LoginWrapper, LoginSuccess, Logout, PopularTrips, TripWrapper, Trip, TripDetail, DestinationWrapper, PopularDestinations, DestinationSearchResults, Trippian, Terms, TrippianDetail, TrippianSignUp, TrippianList, TrippianEdit, IntlDemo, Admin, AdminDestinationList, AdminDestinationListItem, AdminDestinationListItemEdit, AdminTrippianList, AdminTrippianListItem, AdminTrippianListItemEdit, AdminInquiryList, AdminTripList, AdminInquiryListItem, AdminInquiryListItemEdit, AdminTripListItem, AdminTripListItemEdit, AdminUserList, AdminUserListItem, AdminUserListItemEdit, Dashboard, MyProfile, MyInquiries, MyTripBox, MyPostedTrips, MyDestinationPost, SignupWrapper, Signup, SignupSuccess } from '../containers/index' export default ( <Router history={browserHistory}> <Route component={App} path="/"> <Route component={About} path="about" /> <Route component={DestinationPost} path="destination-post" /> <Route component={JoinUs} path="join-us" /> <Route component={InquiryDetail} path="inquiry/:id" /> <Route component={InquiryList} path="my-inquiries" /> <Route component={IntlDemo} path="intl" /> //login <Route component={LoginWrapper} path="login" > <Route component={Login} path="login" /> <Route component={LoginSuccess} path="success" /> <Route component={Logout} path="logout" /> <IndexRoute component={Login} /> </Route> // signup <Route component={SignupWrapper} path="signup" > <Route component={Signup} path="signup" /> <Route component={SignupSuccess} path="success" /> <Route component={Logout} path="logout" /> <IndexRoute component={Signup} /> </Route> <Route component={NotFound} path="not-found" /> <Route component={Press} path="press" /> <Route component={Terms} path="terms" /> //Destination <Route component={DestinationWrapper} path="destination" > <Route component={Destination} path=":id" > <IndexRoute component={DestinationDetail}/> // may add some route later </Route> <Route component={DestinationSearchResults} path="search/:q" /> <IndexRoute component={PopularDestinations}/> </Route> // Trip <Route component={TripWrapper} path="trip" > <Route component={Trip} path=":id" > <IndexRoute component={TripDetail}/> </Route> <IndexRoute component={PopularTrips}/> </Route> //Trippian <Route component={Trippian} path="trippian/:id" > <Route component={Contact} path="contact" /> <IndexRoute component={TrippianDetail}/> </Route> <Route component={TrippianSignUp} path="become-a-trippian" /> <Route component={TrippianList} path="trippian" /> // Dashboard <Route component={Dashboard} path="dashboard"> <Route component={TrippianEdit} path="trippian-edit" /> <Route component={MyProfile} path="my-profile" /> <Route component={MyInquiries} path="my-inquiries" /> <Route component={MyPostedTrips} path="my-posted-trips" /> <Route component={MyDestinationPost} path="destination-post" /> // create trip, vote, favs, saves <Route component={MyTripBox} path="my-trip-box" /> <IndexRoute component={MyProfile}/> </Route> //admin routes <Route component={Admin} path="admin"> <Route component={AdminTrippianList} path="trippian" /> <Route component={AdminTrippianListItem} path="trippian/:id" /> <Route component={AdminTrippianListItemEdit} path="trippian/:id/edit" /> <Route component={AdminTripList} path="trip" /> <Route component={AdminTripListItem} path="trip/:id" /> <Route component={AdminTripListItemEdit} path="trip/:id/edit" /> <Route component={AdminDestinationList} path="destination" /> <Route component={AdminDestinationListItem} path="destination/:id" /> <Route component={AdminDestinationListItemEdit} path="destination/:id/edit" /> <Route component={AdminInquiryList} path="inquiry" /> // <Route component={AdminInquiryListItem} path="inquiry/:id" /> // <Route component={AdminInquiryListItemEdit} path="inquiry/:id/edit" /> <Route component={AdminUserList} path="user" /> <Route component={AdminUserListItem} path="user/:id" /> <Route component={AdminUserListItemEdit} path="user/:id/edit" /> <IndexRoute component={AdminDestinationList}/> </Route> <IndexRoute component={Home}/> </Route> </Router> )
stories/index.js
xclix/modalo
import React from 'react'; import { storiesOf } from '@storybook/react'; import { createModal } from '../src'; import '../src/Renderer/Renderer.scss'; storiesOf('Modal', module) .add('default renderer', () => { const SimpleModal = () => ( <div style={{ padding: '30px' }}> <h1>Hi!</h1> <p>I am modal.</p> </div> ); const Modal = createModal({ 'simple-modal': SimpleModal }); class ModalStateContainer extends React.Component { constructor() { super(); this.toggleModal = this.toggleModal.bind(this); this.state = { component: '' }; } toggleModal() { this.setState({ component: this.state.component ? '' : 'simple-modal' }); } render() { return ( <div> <button onClick={this.toggleModal}>Open modal</button> <Modal component={this.state.component} onOverlayClick={this.toggleModal} /> </div> ); } } return <ModalStateContainer />; });
src/container/UnreadMessage/index.js
ztplz/CNode-react-native
/** * React Native App * https://github.com/ztplz/CNode-react-native * email: mysticzt@gmail.com */ import React, { Component } from 'react'; import { View, Text, Image, FlatList, Keyboard, Platform, TextInput, RefreshControl, TouchableHighlight, TouchableOpacity, StyleSheet } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import MessageRow from '../../components/MessageRow'; import MessageReplyTextInput from '../../components/MessageReplyTextInput'; import * as actions from '../../actions/unreadMessageActions'; import LoadingPage from '../../components/LoadingPage'; import { DeviceHeight, DeviceWidth, pixel } from '../../utils/deviceSize'; import NetErrorPage from '../../components/NetErrorPage'; import { NIGHT_HEADER_COLOR, NIGHT_BACKGROUND_COLOR, NIGHT_REFRESH_COLOR, NIGHT_MESSAGE_FLATLIST_HEADER } from '../../constants/themecolor'; class UnreadMessage extends Component { static navigationOptions = ({ navigation, screenProps }) => ({ title: '未读消息', headerTintColor: '#ffffff', headerStyle: { backgroundColor: screenProps.isNightMode? NIGHT_HEADER_COLOR : screenProps.themeColor }, }); constructor(props) { super(props); this.listeners = null; this.state = { keyboardHeight: 0, isKeyboardOpened: false, text: null, }; this.updateKeyboardSpace = this.updateKeyboardSpace.bind(this); this.resetKeyboardSpace = this.resetKeyboardSpace.bind(this); } componentDidMount() { this.props.actions.getUnreadMessageData({isLoading: true, isloaded: false, accesstoken: this.props.accesstoken, error: '', timeout: 10000}); const updateListener = Platform.OS === 'android' ? 'keyboardDidShow' : 'keyboardWillShow'; const resetListener = Platform.OS === 'android' ? 'keyboardDidHide' : 'keyboardWillHide'; this.listeners = [ Keyboard.addListener(updateListener, this.updateKeyboardSpace), Keyboard.addListener(resetListener, this.resetKeyboardSpace) ]; } componentWillUnmount() { this.listeners.forEach(listener => listener.remove()); } updateKeyboardSpace(event) { if (!event.endCoordinates) { return; } const keyboardSpaceHeight = DeviceHeight - event.endCoordinates.screenY; this.setState({ keyboardHeight: keyboardSpaceHeight, isKeyboardOpened: true }); } resetKeyboardSpace(event) { this.setState({ keyboardHeight: 0, isKeyboardOpened: false }); } refreshUnreadMessage() { this.props.actions.refreshUnreadMessageData({isRefreshing: true, accesstoken: this.props.accesstoken, error: '', timeout: 10000}) } sendReply() { this.props.actions.unreadMessageReply({timeout: 10000, topic_id: this.props.replyTopicId, params: { reply_id: this.props.replyId, accesstoken: this.props.accesstoken, content: '@' + this.props.replyName + ' ' + this.props.replyText}}); this.props.actions.replyTextInputShow({isReply: false, replyName: '', text: '', replyId: '', replyTopicId: ''}); Keyboard.dismiss(); } renderHeader() { if(this.props.data.length === 0) { return ( <View style={styles.flatlistHeader}> <Text style={[styles.flatlistHeaderText, { color: this.props.screenProps.isNightMode? NIGHT_MESSAGE_FLATLIST_HEADER : null}]}>列表为空</Text> </View> ) } return null; } render() { const { screenProps, isLoading, isLoaded, isRefreshing, isReply, replyName, replyId, replyTopicId, replyText, accesstoken, error, data, actions, navigation } = this.props; if(isLoading) { return ( <LoadingPage screenProps={screenProps} title='正在加载未读消息...' /> ) } if(!isLoading && isLoaded) { return ( <View style={[styles.container, { backgroundColor: screenProps.isNightMode? NIGHT_BACKGROUND_COLOR : null }]}> <FlatList data={data} renderItem={({item}) => <MessageRow replyTextInputShow={actions.replyTextInputShow} item={item} navigation={navigation} currentReplyName={replyName} currentText={replyText} />} ListHeaderComponent={() => this.renderHeader() } ItemSeparatorComponent={() => <View style={{paddingLeft: 8, paddingRight: 8, height: pixel, backgroundColor: '#85757a'}}></View>} refreshControl={ <RefreshControl refreshing={isRefreshing} onRefresh={() => this.refreshUnreadMessage() } tintColor={screenProps.isNightMode? NIGHT_REFRESH_COLOR : null } /> } keyExtractor={(item, index) => 'hasnot_read_messages' + item.id + index } /> { this.state.isKeyboardOpened? <View style={{marginBottom: this.state.keyboardHeight, flexDirection: 'row', alignItems: 'center', borderWidth: pixel, paddingTop: 5, paddingBottom: 5}}> <MessageReplyTextInput style={{width: DeviceWidth - 61, borderWidth: 1, borderColor: '#79757e', borderRadius: 5, marginLeft: 8, marginRight: 8, paddingLeft: 10}} placeholder={' 回复 ' + replyName + ':'} fontSize={17} autoCapitalize='none' value={replyText} onChangeText={(text) => actions.unreadMessageTextChange({text})} /> <TouchableOpacity onPress={() => this.sendReply()} > <View style={{backgroundColor: '#72aad9', height: 30, width: 37, alignItems: 'center', justifyContent: 'center', borderRadius: 5, marginRight: 8}}> <Text>发送</Text> </View> </TouchableOpacity> </View> : null } { isReply? <TextInput onBlur={() => this.props.actions.replyTextInputShow({isReply: false, replyName: this.props.replyName, text: replyText, replyId: replyId, replyTopicId: replyTopicId})} autoFocus={isReply} caretHidden={true} style={styles.textinputStyle} /> : null} </View> ) } if(error) { return ( <NetErrorPage error={error} handler={() => actions.getUnreadMessageData({isLoading: true, isLoaded: false, accesstoken: accesstoken, error: '', timeout: 10000})} /> ) } return null; } } const styles = StyleSheet.create({ container: { flex: 1 }, textinputStyle: { // height: 40 }, flatlistHeader: { height: 45, alignItems: 'center', justifyContent: 'center' }, flatlistHeaderText: { fontSize: 20 } }); const mapStateToProps = state => { // const stateOfMessage = state.MessageState.toJS(); const stateOfUnreadMessage = state.UnreadMessageState.toJS(); return { isLoading: stateOfUnreadMessage.isLoading, isLoaded: stateOfUnreadMessage.isLoaded, isRefreshing: stateOfUnreadMessage.isRefreshing, isReply: stateOfUnreadMessage.isReply, replyName: stateOfUnreadMessage.replyName, replyId: stateOfUnreadMessage.replyId, replyTopicId: stateOfUnreadMessage.replyTopicId, replyText: stateOfUnreadMessage.replyText, error: stateOfUnreadMessage.error, data: stateOfUnreadMessage.data, accesstoken: state.GlobalState.get('accesstoken') } } const mapDispatchToProps = dispatch => { return { actions: bindActionCreators(actions, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(UnreadMessage);
src/WebApp.js
Tsarpf/babel-webpack-react-router-eslint-boilerplate
import React from 'react'; import Application from './containers/application'; import createBrowserHistory from 'history/lib/createBrowserHistory'; React.render( <Application history={ createBrowserHistory() }/>, document.getElementById( 'app' ) );
src/index.js
Jalissa/rss-feed-client
import React from 'react'; import { render } from 'react-dom'; import getStore from './store/store'; import { Provider } from 'react-redux'; import { BrowserRouter, Route } from 'react-router-dom'; import App from './App'; import RssSeekerContainer from './components/RssSeeker'; import RssViewer from './components/RssViewer'; import FeedViewer from './components/FeedViewer'; import Home from './components/Home'; import Bookmarks from './components/Bookmarks'; import './react-select.css'; import '../node_modules/bootstrap/dist/css/bootstrap.css'; import './index.css'; import localforage from 'localforage'; import options from './storage/config'; const store = getStore(); localforage.config(options(localforage)); let bookmarks = []; localforage.iterate((value) => { bookmarks.push(value); }).then(() => { store.dispatch({type: 'SET_BOOKMARKS', bookmarks: bookmarks }); }); render( <Provider store={store}> <BrowserRouter> <App> <Route path="/" exact render={() => { return ( <Home> <RssSeekerContainer/> </Home> ); }}/> <Route path="/rss/:id/:title" component={RssViewer}/> <Route path="/feed/:id/:title" component={FeedViewer}/> <Route path="/bookmarks" component={Bookmarks}/> </App> </BrowserRouter> </Provider>, document.getElementById('root') );
src/containers/AttributesPanel.js
crp2002/ID3-React
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getScatterPlot, updateWidth, updateHeight, updateTop, updateBottom, updateRight, updateLeft, update_x_name, update_x_nameColor, update_x_ticks, update_x_axisColor, update_y_name, update_y_nameColor, update_y_ticks, update_y_axisColor } from '../actions/ScatterPlotActions'; import { getD3ParserObj, updateValue } from '../actions/D3ParserActions'; import { ScatterPlotReducer, D3ParserReducer } from '../reducers/index'; import AttrListItem from '../components/attributes/d3-parsed/AttrListItem'; import Dimensions from '../components/attributes/scatter-plot/Dimensions'; import Axes from '../components/attributes/scatter-plot/Axes'; import LocalAttributes from '../components/attributes/scatter-plot/LocalAttributes'; import Data from '../components/attributes/scatter-plot/Data'; const d3parser = require('../d3-parser/d3parser'); import { editor } from '../components/editor/textEditor'; import fs from 'fs'; const { ipcRenderer } = require('electron'); class AttributesPanel extends Component { componentDidMount() { let fileUpLoadBtn = document.getElementById('upload-file'); fileUpLoadBtn.addEventListener('change', (event) => { setTimeout(() => { this.props.getD3ParserObj(); this.forceUpdate(); }, 0) }); ipcRenderer.on('updateAttr', (event) => { this.props.getD3ParserObj(); this.forceUpdate(); }); } handleSubmit(e, obj) { e.preventDefault(); let d3string = JSON.stringify(obj, null, '\t') fs.writeFileSync('./src/d3ParserObj.js', d3string); let htmlString = d3parser.reCode(JSON.parse(d3string)); fs.writeFileSync('./src/components/temp/temp.html', htmlString); editor.setValue(htmlString); document.querySelector('webview').reload(); ipcRenderer.send('updateNewWebView'); } render() { // State from ScatterPlotReducer const ScatterPlotObj = this.props.ScatterPlotReducer; // Attributes For Scatter Plot const margin = ScatterPlotObj.margin; const width = ScatterPlotObj.width; const height = ScatterPlotObj.height; const responsiveResize = ScatterPlotObj.responsiveResize; const axes = ScatterPlotObj.axes; const gridLines = ScatterPlotObj.gridLines; const regressionLine = ScatterPlotObj.regressionLine; const toolTip = ScatterPlotObj.toolTip; const scatterPlot = ScatterPlotObj.scatterPlot; const data = ScatterPlotObj.data; const D3ParserObj = this.props.D3ParserReducer; if (D3ParserObj.length > 0) { const attrObj = D3ParserObj.filter((el, i) => { if (typeof el === 'object' && el.hasOwnProperty('args')) { el.id = i; return true; } }); let sortedAttr = []; for (let i = 0; i < attrObj.length; i += 1) { let objholder = [attrObj[i]]; if (attrObj[i+1] && objholder[0].methodObject !== "d3" && objholder[0].methodObject === attrObj[i+1].methodObject) { for (let j = i + 1; j < attrObj.length; j += 1) { if (objholder[0].methodObject === attrObj[j].methodObject) { objholder.push(attrObj[j]); } else { break; } i = j; } } sortedAttr.push(objholder); } const attrList = sortedAttr.map((arr, i) => { return <AttrListItem key={i} updateValue={this.props.updateValue} info={arr} /> }); return ( <div className="pane-one-fourth"> <header className="toolbar toolbar-header attr-main-header"> <h1 className="title main-header">Attributes Panel</h1> <button className="btn btn-primary generate-btn" id="d3parser" onClick={(e)=>getD3ParserObj()}> Generate </button> </header> <div id="attr-panel"> <div className="parsed-attr-container"> <form id="attrForm" onSubmit={(e) => this.handleSubmit(e, D3ParserObj)}> {attrList} </form> </div> </div> <div className="submit-btn"> <button type="submit" className="btn btn-default attr-submit-btn" form="attrForm">Save</button> </div> </div> ) } return ( <div className="pane-one-fourth"> <header className="toolbar toolbar-header attr-main-header"> <h1 className="title main-header">Attributes Panel</h1> <button className="btn btn-default generate-btn" id="d3parser" onClick={(e) => getD3ParserObj()}> Generate </button> </header> <div id="attr-panel"> <Dimensions margin={margin} width={width} height={height} responsiveResize={responsiveResize} controlWidth={this.props.updateWidth} controlHeight={this.props.updateHeight} controlTop={this.props.updateTop} controlBottom={this.props.updateBottom} controlRight={this.props.updateRight} controlLeft={this.props.updateLeft} /> <Axes axes={axes} controlNameX={this.props.update_x_name} controlXnameColor={this.props.update_x_nameColor} controlXticks={this.props.update_x_ticks} controlColorAxisX={this.props.update_x_axisColor} controlNameY={this.props.update_y_name} controlYNameColor={this.props.update_y_nameColor} controlYticks={this.props.update_y_ticks} controlColorAxisY={this.props.update_y_axisColor} /> <LocalAttributes gridLines={gridLines} regressionLine={regressionLine} tooTip={toolTip} scatterPlot={scatterPlot} /> <Data /> </div> <div className="submit-btn"> <button className="btn btn-default attr-submit-btn" type="submit">Save</button> </div> </div> ); } } function mapStateToProps({ ScatterPlotReducer, D3ParserReducer }) { return { ScatterPlotReducer, D3ParserReducer } } function mapDispatchToProps(dispatch) { return bindActionCreators({ getScatterPlot, updateWidth, getD3ParserObj, updateValue, updateHeight, updateTop, updateBottom, updateRight, updateLeft, update_x_name, update_x_nameColor, update_x_ticks, update_x_axisColor, update_y_name, update_y_nameColor, update_y_ticks, update_y_axisColor }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(AttributesPanel);
src/Profile/index.js
reinaldoferreira/macmillan-gamification
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import './Profile.css'; import SocialBadge from '../SocialBadge' import Table from '../Table' class Profile extends Component { constructor(props) { super(props); this.state = { badge: null } } componentDidMount() { fetch('http://hack-day-donation.azurewebsites.net/api/Donations/DonationAmount?userId=1') .then(r => r.json()) .then(x => { const amount = x.DonationAmount; const rangeElem = Array.from(document.querySelectorAll('[data-range]')); rangeElem.map(x => { const [min, max] = [ x.getAttribute('data-min'), x.getAttribute('data-max')]; if (amount > min && amount < max) { x.classList.add('is-this-one'); this.setState({ badge: x.getAttribute('data-range') }); } }); }) } render() { return ( <div className="container profile"> <h1>Profile</h1> <Table /> <br /> <SocialBadge badge={this.state.badge} /> </div> ); } } export default Profile;
src/docs/examples/EyeIcon/Example.js
vonZ/rc-vvz
import React from 'react'; import EyeIcon from 'ps-react/EyeIcon'; export default function EyeIconExample() { return <EyeIcon />; }
generators/app/templates/src/utils/form.js
gmmendezp/generator-nyssa-fe
import React from 'react'; import Autocomplete from 'react-md/lib/Autocompletes'; import Checkbox from 'react-md/lib/SelectionControls/Checkbox'; import DatePicker from 'react-md/lib/Pickers/DatePickerContainer'; import SelectionControlGroup from 'react-md/lib/SelectionControls/SelectionControlGroup'; import SelectField from 'react-md/lib/SelectFields'; import Switch from 'react-md/lib/SelectionControls/Switch'; import TextField from 'react-md/lib/TextFields'; import TimePicker from 'react-md/lib/Pickers/TimePickerContainer'; export const FIELD_NAME = { AUTOCOMPLETE: 'autocomplete', CHECKBOX: 'checkbox', DATE: 'date', PASSWORD: 'password', RADIO: 'radio', SELECT: 'select', SWITCH: 'switch', TEXT: 'text', TEXTAREA: 'textarea', TIME: 'time' }; export const FIELD_TYPE = { [FIELD_NAME.AUTOCOMPLETE]: 'text', [FIELD_NAME.CHECKBOX]: 'checkbox', [FIELD_NAME.DATE]: 'text', [FIELD_NAME.PASSWORD]: 'password', [FIELD_NAME.RADIO]: 'text', [FIELD_NAME.SELECT]: 'select', [FIELD_NAME.SWITCH]: 'text', [FIELD_NAME.TEXT]: 'text', [FIELD_NAME.TIME]: 'text' }; export const FIELD_COMPONENTS = { [FIELD_NAME.AUTOCOMPLETE]: (...props) => { let { type, ...inputProps } = Object.assign({}, ...props); return ( <Autocomplete onAutocomplete={inputProps.onChange} {...inputProps} /> ); }, [FIELD_NAME.CHECKBOX]: (...props) => ( <Checkbox {...Object.assign({}, ...props)} /> ), [FIELD_NAME.DATE]: (...props) => ( <DatePicker {...Object.assign({}, ...props)} /> ), [FIELD_NAME.PASSWORD]: (...props) => ( <TextField {...Object.assign({}, ...props)} /> ), [FIELD_NAME.RADIO]: (...props) => ( <SelectionControlGroup {...Object.assign({}, ...props)} /> ), [FIELD_NAME.SELECT]: (...props) => ( <SelectField {...Object.assign({}, ...props)} /> ), [FIELD_NAME.SWITCH]: (...props) => ( <Switch {...Object.assign({}, ...props)} /> ), [FIELD_NAME.TEXT]: (...props) => ( <TextField {...Object.assign({}, ...props)} /> ), [FIELD_NAME.TIME]: (...props) => ( <TimePicker {...Object.assign({}, ...props)} /> ) };
src/js/components/icons/base/Tip.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-tip`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'tip'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M16.0073529,18 L22,18 L22,2 L2,2 L2,18 L8.24264706,18 L12.125,22 L16.0073529,18 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Tip'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
packages/react/src/components/StructuredList/StructuredList.Skeleton.js
carbon-design-system/carbon-components
/** * 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 PropTypes from 'prop-types'; import React from 'react'; import cx from 'classnames'; import { usePrefix } from '../../internal/usePrefix'; const StructuredListSkeleton = ({ rowCount, border, className, ...rest }) => { const prefix = usePrefix(); const StructuredListSkeletonClasses = cx(className, { [`${prefix}--skeleton`]: true, [`${prefix}--structured-list`]: true, [`${prefix}--structured-list--border`]: border, }); const rows = []; for (var i = 0; i < rowCount; i++) { rows.push( <div className={`${prefix}--structured-list-row`} key={i}> <div className={`${prefix}--structured-list-td`} /> <div className={`${prefix}--structured-list-td`} /> <div className={`${prefix}--structured-list-td`} /> </div> ); } return ( <div className={StructuredListSkeletonClasses} {...rest}> <div className={`${prefix}--structured-list-thead`}> <div className={`${prefix}--structured-list-row ${prefix}--structured-list-row--header-row`}> <div className={`${prefix}--structured-list-th`}> <span /> </div> <div className={`${prefix}--structured-list-th`}> <span /> </div> <div className={`${prefix}--structured-list-th`}> <span /> </div> </div> </div> <div className={`${prefix}--structured-list-tbody`}>{rows}</div> </div> ); }; StructuredListSkeleton.propTypes = { /** * Specify whether a border should be added to your StructuredListSkeleton */ border: PropTypes.bool, /** * Specify an optional className to add. */ className: PropTypes.string, /** * number of table rows */ rowCount: PropTypes.number, }; StructuredListSkeleton.defaultProps = { rowCount: 5, border: false, }; export default StructuredListSkeleton;
src/components/settings.js
jorgerobles/LaserWeb4
import React from 'react'; import ReactDOM from 'react-dom' import { connect } from 'react-redux'; import stringify from 'json-stringify-pretty-compact'; import { FileStorage, LocalStorage } from '../lib/storages'; import update from 'immutability-helper'; import omit from 'object.omit'; import Validator from 'validatorjs'; import { setSettingsAttrs, uploadSettings, downloadSettings, uploadMachineProfiles, downloadMachineProfiles, uploadSnapshot, downloadSnapshot, storeSnapshot, recoverSnapshot } from '../actions/settings'; import { SETTINGS_VALIDATION_RULES, ValidateSettings } from '../reducers/settings'; import MachineProfile from './machine-profiles'; import { MaterialDatabaseButton } from './material-database'; import { Macros } from './macros' import { NumberField, TextField, ToggleField, QuadrantField, FileField, CheckBoxListField, SelectField } from './forms'; import { PanelGroup, Panel, Tooltip, OverlayTrigger, FormControl, InputGroup, ControlLabel, FormGroup, ButtonGroup, Label, Collapse, Badge, ButtonToolbar, Button } from 'react-bootstrap'; import Icon from './font-awesome'; import { PerspectiveWebcam, VideoDeviceField, VideoControls, VideoResolutionField } from './webcam'; export class ApplicationSnapshot extends React.Component { constructor(props) { super(props); this.state = { keys: [] } this.handleChange.bind(this) } getExportData(keys) { let state = this.props.state; let exp = {} keys.forEach((o) => { exp[o] = state[o] }) return exp; } handleChange(data) { this.setState({ keys: data }) } render() { let data = Object.keys(omit(this.props.state, "history")); return ( <div className="well well-sm " id="ApplicationSnapshot"> <CheckBoxListField onChange={(data) => this.handleChange(data)} data={data} /> <section> <ApplicationSnapshotToolbar loadButton saveButton stateKeys={this.state.keys} label="On File" saveAs="laserweb-snapshot.json" /> </section> <section> <ApplicationSnapshotToolbar recoverButton storeButton stateKeys={this.state.keys} label="On LocalStorage" /> </section> </div> ) } } export class ApplicationSnapshotToolbar extends React.Component { constructor(props) { super(props); this.handleDownload.bind(this) this.handleUpload.bind(this) this.handleStore.bind(this) this.handleRecover.bind(this) } getExportData(keys) { let state = this.props.state; let exp = {} keys.forEach((o) => { exp[o] = state[o] }) return exp; } handleDownload(statekeys) { statekeys = Array.isArray(statekeys) ? statekeys : (this.props.stateKeys || []); let file = prompt("Save as", this.props.saveAs || "laserweb-snapshot.json") let settings = this.getExportData(statekeys); let action = downloadSnapshot; this.props.handleDownload(file, settings, action) } handleUpload(file, statekeys) { statekeys = Array.isArray(statekeys) ? statekeys : (this.props.stateKeys || []); this.props.handleUpload(file, uploadSnapshot, statekeys) } handleStore(statekeys) { statekeys = Array.isArray(statekeys) ? statekeys : (this.props.stateKeys || []); this.props.handleStore("laserweb-snapshot", this.getExportData(statekeys), storeSnapshot) } handleRecover(statekeys) { statekeys = Array.isArray(statekeys) ? statekeys : (this.props.stateKeys || []); this.props.handleRecover("laserweb-snapshot", uploadSnapshot) } render() { let buttons = []; if (this.props.loadButton) { buttons.push(<FileField dispatch={(e) => this.handleUpload(e.target.files[0], this.props.loadButton)} label="Load" buttonClass="btn btn-danger btn-xs" icon="upload" />); } if (this.props.saveButton) { buttons.push(<Button onClick={() => this.handleDownload(this.props.saveButton)} className="btn btn-success btn-xs">Save <Icon name="download" /></Button>); } if (this.props.recoverButton) { buttons.push(<Button onClick={(e) => this.handleRecover(this.props.recoverButton)} bsClass="btn btn-danger btn-xs">Load <Icon name="upload" /></Button>); } if (this.props.storeButton) { buttons.push(<Button onClick={(e) => this.handleStore(this.props.storeButton)} bsClass="btn btn-success btn-xs">Save <Icon name="download" /></Button>); } return <div className={this.props.className}><strong>{this.props.label || "Snapshot"}</strong> <ButtonGroup style={{ float: "right", clear: "right" }}>{buttons.map((button, i) => React.cloneElement(button, { key: i }))}</ButtonGroup> <br style={{ clear: 'both' }} /> </div> } } class SettingsPanel extends React.Component { render() { let filterProps = omit(this.props, ['header', 'errors', 'defaultExpanded']); let childrenFields = this.props.children.map((item) => { if (item) return item.props.field }) let hasErrors = Object.keys(this.props.errors || []).filter((error) => { return childrenFields.includes(error) }).length; filterProps['defaultExpanded'] = (this.props.defaultExpanded || hasErrors) ? true : false let children = this.props.children.map((child, i) => { if (!child) return let props = { key: i } if (child.props.field) props['errors'] = this.props.errors; return React.cloneElement(child, props); }) let icon = hasErrors ? <Label bsStyle="warning">Please check!</Label> : undefined; return <Panel {...filterProps} header={<span>{icon}{this.props.header}</span>} >{children}</Panel> } } export function SettingsValidator({style, className = 'badge', noneOnSuccess = false, ...rest}) { let validator = ValidateSettings(false); let errors = (validator.fails()) ? ("Please review Settings:\n\n" + Object.values(validator.errors.errors)) : undefined if (noneOnSuccess && !errors) return null; return <span className={className} title={errors ? errors : "Good to go!"} style={style}><Icon name={errors ? 'warning' : 'check'} /></span> } class Settings extends React.Component { constructor(props) { super(props); this.state = { errors: null, showVideoControls: false } } validate(data, rules) { let check = new Validator(data, rules); if (check.fails()) { console.error("Settings Error:" + JSON.stringify(check.errors.errors)); return check.errors.errors; } return null; } rules() { return SETTINGS_VALIDATION_RULES; } componentWillMount() { this.setState({ errors: this.validate(this.props.settings, this.rules()) }) } componentWillReceiveProps(nextProps) { this.setState({ errors: this.validate(nextProps.settings, this.rules()) }) } render() { const showVideoControls = (e) => { this.setState({ showVideoControls: !this.state.showVideoControls }) } let isVideoDeviceSelected = Boolean(this.props.settings['toolVideoDevice'] && this.props.settings['toolVideoDevice'].length); return ( <div className="form"> <PanelGroup> <Panel header="Machine Profiles" bsStyle="primary" collapsible defaultExpanded={true} eventKey="0"> <MachineProfile onApply={this.props.handleApplyProfile} /> <MaterialDatabaseButton>Launch Material Database</MaterialDatabaseButton> </Panel> <SettingsPanel collapsible header="Machine" eventKey="1" bsStyle="info" errors={this.state.errors} > <NumberField {...{ object: this.props.settings, field: 'machineWidth', setAttrs: setSettingsAttrs, description: 'Machine Width', units: 'mm' }} /> <NumberField {...{ object: this.props.settings, field: 'machineHeight', setAttrs: setSettingsAttrs, description: 'Machine Height', units: 'mm' }} /> <NumberField {...{ object: this.props.settings, field: 'machineBeamDiameter', setAttrs: setSettingsAttrs, description: (<span>Beam <abbr title="Diameter">&Oslash;</abbr></span>), units: 'mm' }} /> <hr /> <ToggleField {... { object: this.props.settings, field: 'machineZEnabled', setAttrs: setSettingsAttrs, description: 'Machine Z stage' }} /> <Collapse in={this.props.settings.machineZEnabled}> <div> <NumberField {...{ errors: this.state.errors, object: this.props.settings, field: 'machineZToolOffset', setAttrs: setSettingsAttrs, description: 'Tool offset', labelAddon: false, units: 'mm' }} /> </div> </Collapse> <hr /> <ToggleField {...{ errors: this.state.errors, object: this.props.settings, field: 'machineBlowerEnabled', setAttrs: setSettingsAttrs, description: 'Air Assist' }} /> <Collapse in={this.props.settings.machineBlowerEnabled}> <div> <TextField {...{ object: this.props.settings, field: 'machineBlowerGcodeOn', setAttrs: setSettingsAttrs, description: 'Gcode AA ON', rows: 5, style: { resize: "vertical" } }} /> <TextField {...{ object: this.props.settings, field: 'machineBlowerGcodeOff', setAttrs: setSettingsAttrs, description: 'Gcode AA OFF', rows: 5, style: { resize: "vertical" } }} /> </div> </Collapse> </SettingsPanel> <SettingsPanel collapsible header="File Settings" eventKey="2" bsStyle="info" errors={this.state.errors}> <h4>SVG</h4> <NumberField {...{ object: this.props.settings, field: 'pxPerInch', setAttrs: setSettingsAttrs, description: 'PX Per Inch', units: 'pxpi' }} /> <h4>BMP</h4> <NumberField {...{ object: this.props.settings, field: 'dpiBitmap', setAttrs: setSettingsAttrs, description: 'Bitmap DPI', units: 'dpi' }} /> </SettingsPanel> <SettingsPanel collapsible header="Gcode" eventKey="3" bsStyle="info" errors={this.state.errors}> <h4>Gcode generation</h4> <TextField {...{ object: this.props.settings, field: 'gcodeStart', setAttrs: setSettingsAttrs, description: 'Gcode Start', rows: 5, style: { resize: "vertical" } }} /> <TextField {...{ object: this.props.settings, field: 'gcodeEnd', setAttrs: setSettingsAttrs, description: 'Gcode End', rows: 5, style: { resize: "vertical" } }} /> <TextField {...{ object: this.props.settings, field: 'gcodeHoming', setAttrs: setSettingsAttrs, description: 'Gcode Homing', rows: 5, style: { resize: "vertical" } }} /> <TextField {...{ object: this.props.settings, field: 'gcodeToolOn', setAttrs: setSettingsAttrs, description: 'Tool ON', rows: 5, style: { resize: "vertical" } }} /> <TextField {...{ object: this.props.settings, field: 'gcodeToolOff', setAttrs: setSettingsAttrs, description: 'Tool OFF', rows: 5, style: { resize: "vertical" } }} /> <NumberField {...{ object: this.props.settings, field: 'gcodeSMaxValue', setAttrs: setSettingsAttrs, description: 'PWM Max S value' }} /> </SettingsPanel> <SettingsPanel collapsible header="Application" eventKey="4" bsStyle="info" errors={this.state.errors}> <SelectField {...{ object: this.props.settings, field: 'toolFeedUnits', setAttrs: setSettingsAttrs, data: ['mm/s', 'mm/min'], defaultValue: 'mm/min', description: 'Feed Units', selectProps: { clearable: false } }} /> <ToggleField {... { object: this.props.settings, field: 'toolSafetyLockDisabled', setAttrs: setSettingsAttrs, description: 'Disable Safety Lock' }} /> <ToggleField {... { object: this.props.settings, field: 'toolCncMode', setAttrs: setSettingsAttrs, description: 'Enable CNC Mode' }} /> <ToggleField {... { object: this.props.settings, field: 'toolUseNumpad', setAttrs: setSettingsAttrs, description: 'Use Numpad' }} /> <QuadrantField {... { object: this.props.settings, field: 'toolImagePosition', setAttrs: setSettingsAttrs, description: 'Raster Image Position' }} /> </SettingsPanel> <Panel collapsible header="Camera" bsStyle="info" eventKey="6"> <table width="100%"><tbody><tr> <td width="45%"><VideoDeviceField {...{ object: this.props.settings, field: 'toolVideoDevice', setAttrs: setSettingsAttrs, description: 'Video Device' }} /></td> <td width="45%"><VideoResolutionField {...{ object: this.props.settings, field: 'toolVideoResolution', setAttrs: setSettingsAttrs, deviceId: this.props.settings['toolVideoDevice'] }} /></td> <td width="10%" style={{verticalAlign:'bottom'}}><FormGroup><Button onClick={showVideoControls} bsStyle="primary" active={this.state.showVideoControls} disabled={!(this.props.settings['toolVideoDevice'] && this.props.settings['toolVideoDevice'].length)} ><Icon name="gears" /></Button></FormGroup></td> </tr></tbody></table> {isVideoDeviceSelected ? <PerspectiveWebcam showCoordinators={this.state.showVideoControls} width="640" height="480" device={this.props.settings['toolVideoDevice']} perspective={this.props.settings['toolVideoPerspective']} lens={this.props.settings['toolVideoLens']} fov={this.props.settings['toolVideoFov']} resolution={this.props.settings['toolVideoResolution']} onStop={(perspective) => { this.props.handleSettingChange({ toolVideoPerspective: perspective }) }} /> : undefined} <Collapse in={this.state.showVideoControls && isVideoDeviceSelected}><div><VideoControls lens={this.props.settings['toolVideoLens']} fov={this.props.settings['toolVideoFov']} videoWidth="640" videoHeight="480" perspective={this.props.settings['toolVideoPerspective']} resolution={this.props.settings['toolVideoResolution']} onChange={(v) => this.props.handleSettingChange({ toolVideoLens: v.lens, toolVideoFov: v.fov, toolVideoPerspective: v.perspective })} /></div></Collapse> <TextField {... { object: this.props.settings, field: 'toolWebcamUrl', setAttrs: setSettingsAttrs, description: 'Webcam Url' }} /> </Panel> <Panel collapsible header="Macros" bsStyle="info" eventKey="7"> <Macros /> </Panel> <Panel collapsible header="Tools" bsStyle="danger" eventKey="8" > <ApplicationSnapshotToolbar loadButton saveButton stateKeys={['settings']} label="Settings" saveAs="laserweb-settings.json" /><hr /> <ApplicationSnapshotToolbar loadButton saveButton stateKeys={['machineProfiles']} label="Machine Profiles" saveAs="laserweb-profiles.json" /><hr /> <h5 >Application Snapshot <Label bsStyle="warning">Experimental!</Label></h5> <small className="help-block">This dialog allows to save an entire snapshot of the current state of application.</small> <ApplicationSnapshot /> </Panel> </PanelGroup> </div> ); } } const mapStateToProps = (state) => { return { settings: state.settings, profiles: state.machineProfiles } }; const mapDispatchToProps = (dispatch) => { return { handleSettingChange: (attrs) => { dispatch(setSettingsAttrs(attrs, 'settings')) }, handleDownload: (file, settings, action) => { FileStorage.save(file, stringify(settings), "application/json") dispatch(action(settings)); }, handleUpload: (file, action, onlyKeys) => { FileStorage.load(file, (file, result) => { dispatch(action(file, result, onlyKeys)); }) }, handleStore: (name, settings, action) => { try { LocalStorage.save(name, stringify(settings), "application/json") } catch (e) { console.error(e); alert(e); } dispatch(action(settings)); }, handleRecover: (name, action) => { LocalStorage.load(name, (file, result) => dispatch(action(file, result))); }, handleApplyProfile: (settings) => { dispatch(setSettingsAttrs(settings)); }, }; }; export { Settings } ApplicationSnapshot = connect((state) => { return { state: state } }, mapDispatchToProps)(ApplicationSnapshot); ApplicationSnapshotToolbar = connect((state) => { return { state: state } }, mapDispatchToProps)(ApplicationSnapshotToolbar); export default connect(mapStateToProps, mapDispatchToProps)(Settings);
src/containers/search-bar.js
alexnsl/ipmaps
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { filterIpMap } from 'ipmaps/actions/'; import { bindActionCreators } from 'redux'; class SearchBar extends Component { constructor(props) { super(props); this.state = { searchText: '' }; } onInputChange(event) { this.props.filterIpMap(event.target.value); this.setState({ searchText: event.target.value }); } render() { return ( <input placeholder="Search a customer" type="text" value={this.state.searchText} onChange={this.onInputChange.bind(this)} className="form-control" /> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ filterIpMap: filterIpMap }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
app/src/pages/User.js
darjanin/xp-library
import React from 'react' import databaseUtils from './utils/DatabaseUtils' import {userRequired} from '../ValidationUtils' export default class User extends React.Component { constructor(props) { super(props) this.state = { errors: [], userInfo: null, userBooks: null, userComments: null, } } componentDidUpdate(prevProps, prevState){ if (prevProps.userId !== this.props.userId){ databaseUtils.getUserInfo(this.props.userId, this.userInfoCallback.bind(this)) } } componentDidMount() { databaseUtils.getUserInfo(this.props.userId, this.userInfoCallback.bind(this)) } userInfoCallback(userInfo){ databaseUtils.getUserBooks(this.props.userId, this.userBooksCallback.bind(this), userInfo) } userBooksCallback(userBooks, userInfo){ databaseUtils.getUserComments(this.props.userId, this.userCommentsCallback.bind(this), userInfo, userBooks) } userCommentsCallback(userComments, userInfo, userBooks){ this.setState({ userInfo: userInfo, userBooks: userBooks, userComments: userComments }) } render() { const { showBookFn, deleteBookFn, loggedUser, userId, showUser} = this.props let userBooks = this.state.userBooks let userComments = this.state.userComments let userInfo = this.state.userInfo if (!userInfo || !userComments || !userBooks) { return (<div className="hero-content"></div>) } return ( <div className="hero-content"> <h1 className="title"> {userInfo.username} </h1> <h3 className="subtitle"> Basic information </h3> <div className="columns box"> <div className="card-content"> <div className="title is-5">{'Username:'} {userInfo.username}</div> <div className="title is-5">{'Email:'} {userInfo.email}</div> </div> </div> <h3 className="subtitle"> Books </h3> { Object.keys(userBooks) && Object.keys(userBooks).length != 0 ? <div className="columns is-multiline t-books"> { Object.keys(userBooks).map(key => <UserBook key={key} data={userBooks[key]} showFn={() => showBookFn(key)} loggedUserId={loggedUser()} deleteFn={() => {if (confirm('Are you sure?')) deleteBookFn(key)}} showUser={showUser} /> ) } </div> : <div className="columns box"> <div className="card-content"> <div className="title is-5">{'You don\'t have any book yet...'}</div> </div> </div> } <h3 className="subtitle"> Comments </h3> { Object.keys(userComments) && Object.keys(userComments).length != 0 ? Object.keys(userComments).map(key => <UsrComment key = {key} data ={userComments[key]} showFn = {() => showBookFn(userComments[key].bookId)} /> ) : <div className="columns box"> <div className="card-content"> <div className="title is-5">{'You don\'t have any comment of book yet...'}</div> </div> </div> } </div> ) } } const UserBook = ({key, data: {title, author, year, description, userId, lend: {lend, lendUserName, lendUserId}}, showFn, deleteFn, loggedUserId, showUser}) => ( <div key={key} className="column is-half"> <div className="card is-fullwidth" key={Math.random()}> <div className="card-header"> <div className="card-header-title" style={lend ? {backgroundColor: '#fdeeed', color: '#ed6c63'} : {}} > {title} {lend && loggedUserId == userId ? <a onClick={() => {showUser(lendUserId)}} style={{color: '#ed6c63'}}> {': is lend to'} - {lendUserName} </a> : ''} </div> </div> <div className="card-content"> <div className="title is-5">{author} - {year}</div> <div className="content"> {description} </div> </div> <footer className="card-footer"> <a className="card-footer-item" onClick={showFn}>Show</a> <a className="card-footer-item">Edit</a> {userId === loggedUserId && !lend && <a className="card-footer-item" onClick={deleteFn}>Delete</a> } </footer> </div> </div> ) const UsrComment = ({key, data: {authorId, date, text, book: {title, author}}, showFn}) => ( <div key={key} className="card is-fullwidth"> <div className="card-header"> <div className="card-header-title" style={{backgroundColor: '#d3d3d3'}} > <a onClick={showFn} style={{color: '#000000'}}> {author} - {title} </a> </div> </div> <div className="card-content"> <p>{text}</p> <p><small>{new Date(date).toLocaleString()}</small></p> </div> </div> )