path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
packages/wix-style-react/src/SidebarHeader/SidebarHeader.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import { st, classes } from './SidebarHeader.st.css'; import { dataHooks } from './constants'; import Text from '../Text'; import { SidebarContext } from '../Sidebar/SidebarAPI'; import { sidebarSkins } from '../Sidebar/constants'; import Box from '../Box'; /** A header within the sidebar with title, subtitle and custom content at the bottom. */ class SidebarHeader extends React.PureComponent { static displayName = 'SidebarHeader'; static propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** A text to show as the header title */ title: PropTypes.string, /** A text to show as the header subtitle */ subtitle: PropTypes.string, /** A custom node to render from the bottom */ children: PropTypes.node, }; render() { const { dataHook, title, subtitle, children } = this.props; return ( <SidebarContext.Consumer> {context => { const skin = (context && context.getSkin()) || sidebarSkins.dark; return ( <div data-hook={dataHook} className={st(classes.root, { skin })}> {title && ( <Box> <Text dataHook={dataHooks.title} className={classes.title} size="medium" weight="bold" ellipsis light={skin === sidebarSkins.dark} > {title} </Text> </Box> )} {subtitle && ( <Box> <Text dataHook={dataHooks.subtitle} className={classes.subtitle} size="tiny" weight="thin" ellipsis light={skin === sidebarSkins.dark} > {subtitle} </Text> </Box> )} {children && <div data-hook={dataHooks.children}>{children}</div>} </div> ); }} </SidebarContext.Consumer> ); } } export default SidebarHeader;
src/client/components/containers/RegisterFormComponent.js
annesofie/microtasking-react
/** * Created by AnneSofie on 02.03.2017. */ import React, { Component } from 'react'; import * as taskApi from '../../../client/api/task-api'; import * as resultApi from '../../../client/api/result-api'; //View import RegisterFormView from '../views/registerFormView'; import AfterEachTaskView from '../views/afterEachTaskSurvey'; export default class RegisterFormComponent extends Component { constructor(props) { super(props); this.state = { value: null, showMessage: false }; this.participantValues = { age: 0, gender: 'not selected', nationality: 'need input', experienced: 'not selected', microtasking: 'not selected' }; this.handleRegisterSubmit = this.handleRegisterSubmit.bind(this); } handleRegisterSubmit(data, isRegistration) { this.participantValues = Object.assign({}, this.participantValues, data); if (isRegistration) { taskApi.saveParticipant(this.participantValues) .then(resp => { if (resp.response && resp.response.status == 400) { this.setState({showMessage: true}); } else { const participant = resp.data; this.props._setParticipantId(participant); } }) } else if (!isRegistration){ data.taskresult = this.props.taskresultId; resultApi.saveTaskSurvey(data).then(resp => { if (resp.response && resp.response.status == 400) { this.setState({showMessage: true}); } else { this.props._handleModeChange(); } }) } } render() { if (this.props.mode == 'register') { return ( <div className="container-fluid"> <div className="d-flex flex-row justify-content-center padding-top"> <h4>Registration</h4> <RegisterFormView handleRegisterSubmit={this.handleRegisterSubmit} fieldValues={this.participantValues} showMessage={this.state.showMessage} /> </div> </div> ) } else if (this.props.mode == 'survey') { return ( <div className="padding-survey"> <div className="d-flex flex-row justify-content-center"> <h4>Survey</h4> </div> <div className=""> {(this.props.task.id == this.props.testTaskId) ? <div><hr/><p className="survey-info-testtask"><i>After each task there will be a survey. The survey is shown under. Select one option at every question and write any comments if you have. The training task is now finish, fill out the form and press the button to get started on the tasks.</i></p><hr/></div>: <div><hr/><p className="survey-info-testtask"><i>Select one option at every question, and write a comment if you have, then click submit to start the next task</i></p><hr/></div> } </div> <div className="d-flex flex-row justify-content-center"> <AfterEachTaskView participant={this.props.participant} task={this.props.task} testTaskId={this.props.testTaskId} handleRegisterSubmit={this.handleRegisterSubmit} showMessage={this.state.showMessage} /> </div> </div> ); } } }
src/home/Music.js
crosslandwa/chippanfire-site
import React from 'react' import SectionHeader from './SectionHeader' import ExternalLink from '../external-link' const Music = props => ( <> <SectionHeader id="music" label="Music" /> <h2 className="cpf-header--small">Dry Stone Will</h2> <p>Dark pop, an English folk lilt and lush guitar-led backing</p> <iframe className="cpf-music-player__iframe--bandcamp" src="https://bandcamp.com/EmbeddedPlayer/album=3956288530/size=large/bgcol=ffffff/linkcol=63b2cc/transparent=true/" seamless> <a href="https://drystonewill.bandcamp.com/album/at-once-easily">at once easily by Dry Stone Will</a> </iframe> <h2 className="cpf-header--small">Socco Chico</h2> <p>I make some music (sometimes with <ExternalLink href="https://soundcloud.com/adamparkinson">Adam Parkinson</ExternalLink>) for the dancefloor</p> <iframe className="cpf-music-player__iframe--soundcloud" scrolling="no" frameBorder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/1644437&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe> <h2 className="cpf-header--small">Kilclinton</h2> <p>Disco synth jams and drum edits with Brett Lambe</p> <iframe className="cpf-music-player__iframe--soundcloud" scrolling="no" frameBorder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/87360&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe> </> ) export default Music
app/javascript/mastodon/features/home_timeline/index.js
rainyday/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { expandHomeTimeline } from '../../actions/timelines'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { Link } from 'react-router-dom'; import { fetchAnnouncements, toggleShowAnnouncements } from 'mastodon/actions/announcements'; import AnnouncementsContainer from 'mastodon/features/getting_started/containers/announcements_container'; import classNames from 'classnames'; import IconWithBadge from 'mastodon/components/icon_with_badge'; const messages = defineMessages({ title: { id: 'column.home', defaultMessage: 'Home' }, show_announcements: { id: 'home.show_announcements', defaultMessage: 'Show announcements' }, hide_announcements: { id: 'home.hide_announcements', defaultMessage: 'Hide announcements' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0, isPartial: state.getIn(['timelines', 'home', 'isPartial']), hasAnnouncements: !state.getIn(['announcements', 'items']).isEmpty(), unreadAnnouncements: state.getIn(['announcements', 'items']).count(item => !item.get('read')), showAnnouncements: state.getIn(['announcements', 'show']), }); export default @connect(mapStateToProps) @injectIntl class HomeTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, isPartial: PropTypes.bool, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasAnnouncements: PropTypes.bool, unreadAnnouncements: PropTypes.number, showAnnouncements: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HOME', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { this.props.dispatch(expandHomeTimeline({ maxId })); } componentDidMount () { this.props.dispatch(fetchAnnouncements()); this._checkIfReloadNeeded(false, this.props.isPartial); } componentDidUpdate (prevProps) { this._checkIfReloadNeeded(prevProps.isPartial, this.props.isPartial); } componentWillUnmount () { this._stopPolling(); } _checkIfReloadNeeded (wasPartial, isPartial) { const { dispatch } = this.props; if (wasPartial === isPartial) { return; } else if (!wasPartial && isPartial) { this.polling = setInterval(() => { dispatch(expandHomeTimeline()); }, 3000); } else if (wasPartial && !isPartial) { this._stopPolling(); } } _stopPolling () { if (this.polling) { clearInterval(this.polling); this.polling = null; } } handleToggleAnnouncementsClick = (e) => { e.stopPropagation(); this.props.dispatch(toggleShowAnnouncements()); } render () { const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn, hasAnnouncements, unreadAnnouncements, showAnnouncements } = this.props; const pinned = !!columnId; let announcementsButton = null; if (hasAnnouncements) { announcementsButton = ( <button className={classNames('column-header__button', { 'active': showAnnouncements })} title={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)} aria-label={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)} aria-pressed={showAnnouncements ? 'true' : 'false'} onClick={this.handleToggleAnnouncementsClick} > <IconWithBadge id='bullhorn' count={unreadAnnouncements} /> </button> ); } return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='home' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} extraButton={announcementsButton} appendContent={hasAnnouncements && showAnnouncements && <AnnouncementsContainer />} > <ColumnSettingsContainer /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`home_timeline-${columnId}`} onLoadMore={this.handleLoadMore} timelineId='home' emptyMessage={<FormattedMessage id='empty_column.home' defaultMessage='Your home timeline is empty! Visit {public} or use search to get started and meet other users.' values={{ public: <Link to='/timelines/public'><FormattedMessage id='empty_column.home.public_timeline' defaultMessage='the public timeline' /></Link> }} />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
presentation/examples/blog-example/client/components/About.js
iansinnott/react-static-presentation
import React from 'react'; import s from './About.styl'; export const About = React.createClass({ render() { return ( <div className={s.page}> <div className={s.siteTitle}> <h1>About</h1> </div> <p>Welcome, to about us.</p> </div> ); }, });
gatsby-strapi-tutorial/cms/plugins/content-manager/admin/src/components/SelectOne/index.js
strapi/strapi-examples
/** * * SelectOne * */ import React from 'react'; import Select from 'react-select'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import 'react-select/dist/react-select.css'; import { cloneDeep, map, includes, isArray, isNull, isUndefined, isFunction, get, findIndex } from 'lodash'; import request from 'utils/request'; import templateObject from 'utils/templateObject'; import styles from './styles.scss'; class SelectOne extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { isLoading: true, options: [], toSkip: 0, }; } componentDidMount() { this.getOptions(''); } componentDidUpdate(prevProps, prevState) { if (prevState.toSkip !== this.state.toSkip) { this.getOptions(''); } } getOptions = (query) => { const params = { _limit: 20, _start: this.state.toSkip, source: this.props.relation.plugin || 'content-manager', }; // Set `query` parameter if necessary if (query) { delete params._limit; delete params._start; params[`${this.props.relation.displayedAttribute}_contains`] = query; } // Request URL const requestUrlSuffix = query && get(this.props.record, [this.props.relation.alias]) ? get(this.props.record, [this.props.relation.alias]) : ''; const requestUrl = `/content-manager/explorer/${this.props.relation.model || this.props.relation.collection}/${requestUrlSuffix}`; // Call our request helper (see 'utils/request') return request(requestUrl, { method: 'GET', params, }) .then(response => { const options = isArray(response) ? map(response, item => ({ value: item, label: templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField, })) : [{ value: response, label: templateObject({ mainField: this.props.relation.displayedAttribute }, response).mainField, }]; const newOptions = cloneDeep(this.state.options); options.map(option => { // Don't add the values when searching if (findIndex(newOptions, o => o.value.id === option.value.id) === -1) { return newOptions.push(option); } }); return this.setState({ options: newOptions, isLoading: false, }); }) .catch(() => { strapi.notification.error('content-manager.notification.error.relationship.fetch'); }); } handleChange = (value) => { const target = { name: `record.${this.props.relation.alias}`, value, type: 'select', }; this.props.setRecordAttribute({ target }); } handleBottomScroll = () => { this.setState(prevState => { return { toSkip: prevState.toSkip + 20, }; }); } // Redirect to the edit page handleClick = (item = {}) => { this.props.onRedirect({ model: this.props.relation.collection || this.props.relation.model, id: item.value.id || item.value._id, source: this.props.relation.plugin, }); } handleInputChange = (value) => { const clonedOptions = this.state.options; const filteredValues = clonedOptions.filter(data => includes(data.label, value)); if (filteredValues.length === 0) { return this.getOptions(value); } } render() { const description = this.props.relation.description ? <p>{this.props.relation.description}</p> : ''; const value = get(this.props.record, this.props.relation.alias); const excludeModel = ['role', 'permission', 'file'].includes(this.props.relation.model || this.props.relation.collection); // Temporary. const entryLink = (isNull(value) || isUndefined(value) || excludeModel ? '' : ( <FormattedMessage id='content-manager.containers.Edit.clickToJump'> {title => ( <a onClick={() => this.handleClick({value})} title={title}><FormattedMessage id='content-manager.containers.Edit.seeDetails' /></a> )} </FormattedMessage> ) ); /* eslint-disable jsx-a11y/label-has-for */ return ( <div className={`form-group ${styles.selectOne}`}> <nav className={styles.headline}> <label htmlFor={this.props.relation.alias}>{this.props.relation.alias}</label> {entryLink} </nav> {description} <Select onChange={this.handleChange} options={this.state.options} id={this.props.relation.alias} isLoading={this.state.isLoading} onMenuScrollToBottom={this.handleBottomScroll} onInputChange={this.handleInputChange} onSelectResetsInput={false} simpleValue value={isNull(value) || isUndefined(value) ? null : { value: isFunction(value.toJS) ? value.toJS() : value, label: templateObject({ mainField: this.props.relation.displayedAttribute }, isFunction(value.toJS) ? value.toJS() : value).mainField || (isFunction(value.toJS) ? get(value.toJS(), 'id') : get(value, 'id')), }} /> </div> ); /* eslint-disable jsx-a11y/label-has-for */ } } SelectOne.propTypes = { onRedirect: PropTypes.func.isRequired, record: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]).isRequired, relation: PropTypes.object.isRequired, setRecordAttribute: PropTypes.func.isRequired, }; export default SelectOne;
ios/versioned-react-native/ABI11_0_0/Libraries/Text/Text.js
jolicloud/exponent
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactNativeComponentClass = require('react/lib/createReactNativeComponentClass'); const merge = require('merge'); const mergeFast = require('mergeFast'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, ellipsizeMode: true, allowFontScaling: true, selectable: true, adjustsFontSizeToFit: true, minimumFontScale: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the `fontFamily` from *`styles.baseText`, but the title provides its own additional styles. The title and body will * stack on top of each other on account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}<br /><br /> * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // App registration and rendering * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` */ const Text = React.createClass({ propTypes: { /** * This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * `numberOfLines` must be set in conjunction with this prop. * * > `clip` is working only for iOS */ ellipsizeMode: React.PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `ellipsizeMode`. */ numberOfLines: React.PropTypes.number, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}`` */ onPress: React.PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>`` */ onLongPress: React.PropTypes.func, /** * Lets the user select text, to use the native copy and paste functionality. * * @platform android */ selectable: React.PropTypes.bool, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * * @platform ios */ suppressHighlighting: React.PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: React.PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility setting on iOS. The * default is `true`. * * @platform ios */ allowFontScaling: React.PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](/react-native/docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: React.PropTypes.bool, /** * Specifies whether font should be scaled down automatically to fit given style constraints. * @platform ios */ adjustsFontSizeToFit: React.PropTypes.bool, /** * Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0). * @platform ios */ minimumFontScale: React.PropTypes.number, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, ellipsizeMode: 'tail', }; }, getInitialState: function(): Object { return mergeFast(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, contextTypes: { isInAParentText: React.PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): ReactElement<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = (e: SyntheticEvent) => { this.props.onPress && this.props.onPress(e); }; this.touchableHandleLongPress = (e: SyntheticEvent) => { this.props.onLongPress && this.props.onLongPress(e); }; this.touchableGetPressRectOffset = function(): RectOffset { return PRESS_RECT_OFFSET; }; } return setResponder; }, onResponderGrant: function(e: SyntheticEvent, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number, left: number, right: number, bottom: number, } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass(viewConfig); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass({ validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', }); } module.exports = Text;
src/containers/CounterList.js
jshack3r/ws-redux-counters-router
import React from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { incrementCounter, removeCounter } from '../actions' import Counter from '../components/counter/Counter' let CounterList = ({isFetching, counterList, boldButtons, incrementCounter, removeCounter}) => <div> <div hidden={!isFetching}> <i className="glyphicon glyphicon-hourglass" style={{fontSize:'25px'}}></i> </div> <br /> {counterList.map(counter => <Counter {...counter} key={counter.id} onClick={e => e.button === 0 ? incrementCounter(counter.id) : removeCounter(counter.id)} boldButtons={boldButtons} /> )} <br /><br /> </div> CounterList.propTypes = { isFetching: React.PropTypes.bool.isRequired, counterList: React.PropTypes.array.isRequired, boldButtons: React.PropTypes.bool.isRequired, incrementCounter: React.PropTypes.func.isRequired, removeCounter: React.PropTypes.func.isRequired, } const mapStateToProps = (state) => ({ isFetching: state.counters.present.isFetching, counterList: state.counters.present.counterList, boldButtons: state.header.boldButtons }) /* instead of only sending the dispatch object as a prop by default, use bindActionCreators to send individual actions */ const mapDispatchToProps = (dispatch) => bindActionCreators({ incrementCounter, removeCounter }, dispatch) CounterList = connect(mapStateToProps, mapDispatchToProps)(CounterList); export default CounterList
src/app/components/Header.js
MarcusKolman/www
import React, { Component } from 'react'; import Menu from './Menu'; import Svg from '../../../public/assets/sigfox.svg'; class Header extends Component { render() { return ( <Menu> </Menu> ); } } export default Header;
frontend-new/src/js/util/helper.js
leapfrogtechnology/vyaguta-resource
import React from 'react'; /* These functions build the start and end date for the timeline for a given date */ export function setStartDate(date) { return `${date} 00:00:00`; } export function setEndDate(date) { return `${date} 23:50:00`; } /* This function builds the content inside the item of Timeline */ export function itemContentBuilder(percent, content) { return `<span class="allocated"><span class="allocated-${percent}"><em class="allocated-by">${percent}%</em></span></span> ${content}`; } /* Helper function to parse the data into meaningful notification */ export function buildNotificationTitle(notification) { let retString = null; switch (notification.allocationHistory.event) { case 1://add event retString = notification.allocationHistory.employee.firstName; if(notification.allocationHistory.employee.middleName !== null) { retString += ` ${notification.allocationHistory.employee.middleName}`; } retString += ` ${notification.allocationHistory.employee.lastName + ' was added in ' + notification.allocationHistory.project.title}!`; break; case 2://update event retString = `Allocation for ${notification.allocationHistory.employee.firstName}`; if(notification.allocationHistory.employee.middleName !== null) { retString += ` ${notification.allocationHistory.employee.middleName}`; } retString += ` ${notification.allocationHistory.employee.lastName} was updated!`; break; case 3://delete event retString = `Allocation for ${notification.allocationHistory.employee.firstName}`; if(notification.allocationHistory.employee.middleName !== null) { retString += ` ${notification.allocationHistory.employee.middleName}`; } retString += ` ${notification.allocationHistory.employee.lastName} was deleted!`; break; } return retString; } export function buildNotificationBody(notification) { let retString = null; switch (notification.allocationHistory.event) { case 1://add event retString = ( <div className="updated-notif-holder"> <p><span>Project</span> : {notification.allocationHistory.project.title}</p> <p><span>Allocated Date</span> : {notification.allocationHistory.startDate} - {notification.allocationHistory.endDate}</p> <p><span>Allocated Percent</span> : {notification.allocationHistory.allocationPercent}</p> <p><span>Note</span> : {notification.allocationHistory.note}</p> </div> ); break; case 2://update event retString = ( <div className="updated-notif-holder"> <div className="prev-column"> <p><span>Previous Project</span> : {notification.allocationHistory.prevProject.title}</p> <p><span>Allocated Previous Date</span> : {notification.allocationHistory.prevStartDate} - {notification.allocationHistory.prevEndDate}</p> <p><span>Allocated Previous Percent</span> : {notification.allocationHistory.prevAllocationPercent}</p> <p><span>Note</span> : {notification.allocationHistory.note}</p> </div> <div className="updated-column"> <p><span>Updated Project</span> : {notification.allocationHistory.project.title}</p> <p><span>Allocated Updated Date</span> : {notification.allocationHistory.startDate} - {notification.allocationHistory.endDate}</p> <p><span>Allocated Updated Percent</span> : {notification.allocationHistory.allocationPercent}</p> </div> </div> ); break; case 3://delete event retString = ( <div className="updated-notif-holder"> <p><span>Project</span> : {notification.allocationHistory.project.title}</p> <p><span>Allocated Date</span> : {notification.allocationHistory.startDate} - {notification.allocationHistory.endDate}</p> <p><span>Allocated Percent</span> : {notification.allocationHistory.allocationPercent}</p> <p><span>Note</span> : {notification.allocationHistory.note}</p> </div> ); break; } return retString; }
local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js
gilesvangruisen/react-native
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, Image, ListView, Platform, StyleSheet, View, } from 'react-native'; import ListItem from '../../components/ListItem'; import Backend from '../../lib/Backend'; export default class ChatListScreen extends Component { static navigationOptions = { title: 'Chats', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./chat-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { isLoading: true, dataSource: ds, }; } async componentDidMount() { const chatList = await Backend.fetchChatList(); this.setState((prevState) => ({ dataSource: prevState.dataSource.cloneWithRows(chatList), isLoading: false, })); } // Binding the function so it can be passed to ListView below // and 'this' works properly inside renderRow renderRow = (name) => { return ( <ListItem label={name} onPress={() => { // Start fetching in parallel with animating this.props.navigation.navigate('Chat', { name: name, }); }} /> ); } render() { if (this.state.isLoading) { return ( <View style={styles.loadingScreen}> <ActivityIndicator /> </View> ); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} style={styles.listView} /> ); } } const styles = StyleSheet.create({ loadingScreen: { backgroundColor: 'white', paddingTop: 8, flex: 1, }, listView: { backgroundColor: 'white', }, icon: { width: 30, height: 26, }, });
src/js/components/icons/base/SocialSnapchat.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}-social-snapchat`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'social-snapchat'); 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="#FFFC00" fillRule="evenodd" d="M12.1511006,22.5316101 C12.0830801,22.5316101 12.0181804,22.5291262 11.9688209,22.5267697 C11.9296518,22.5301452 11.8892088,22.5316101 11.8487022,22.5316101 C10.4196979,22.5316101 9.46422593,21.8560541 8.62103883,21.259537 C8.01668787,20.8326253 7.44672931,20.4295973 6.77900716,20.3185226 C6.45106922,20.2641317 6.12485091,20.236554 5.8096509,20.236554 C5.24173041,20.236554 4.79290954,20.3246368 4.46522636,20.3887086 C4.26358497,20.4280051 4.08971226,20.4618243 3.95532713,20.4618243 C3.81457303,20.4618243 3.64356636,20.4306164 3.57229765,20.1872583 C3.51580495,19.9952977 3.47529834,19.809324 3.4361929,19.6302287 C3.33836562,19.1826816 3.26741536,18.9095168 3.09984793,18.8835951 C1.30755787,18.6070547 0.248590282,18.1996958 0.0376502063,17.7063558 C0.0155499024,17.6545125 0.00319411295,17.6023507 0.00045545858,17.5507621 C-0.00776050453,17.4037027 0.096053603,17.2747312 0.241011216,17.2507202 C1.66434721,17.0163423 2.92992398,16.2640403 4.00277591,15.0140038 C4.83386197,14.0462398 5.24198516,13.1215937 5.28580363,13.0194992 C5.28771432,13.0149135 5.28994346,13.0100731 5.29223629,13.0056785 C5.49903654,12.5860912 5.54018004,12.2235061 5.41490253,11.9283046 C5.18396391,11.3836946 4.41911506,11.141037 3.9131009,10.9804755 C3.78725018,10.9406695 3.66821425,10.9029652 3.57338038,10.8653246 C3.12481427,10.68814 2.38709721,10.3137724 2.48537032,9.79705834 C2.55695747,9.42027045 3.05532887,9.15786915 3.45810214,9.15786915 C3.56994114,9.15786915 3.66904221,9.17748555 3.75247564,9.21665468 C4.20760178,9.42988758 4.61706245,9.5379689 4.96920245,9.5379689 C5.40713239,9.5379689 5.61864568,9.37122943 5.66978845,9.32384434 C5.65717791,9.09023075 5.64176501,8.84324234 5.62686164,8.60962875 C5.62686164,8.609374 5.62654319,8.60657165 5.62654319,8.60657165 C5.52374812,6.97134023 5.39554088,4.93632897 5.91607628,3.76934376 C7.47405217,0.276158264 10.7780794,0.00452196419 11.7532952,0.00452196419 C11.7792805,0.00452196419 12.1783598,0.000573206729 12.1783598,0.000573206729 C12.196384,0.000254758546 12.2159367,0 12.23619,0 C13.2140807,0 16.5249864,0.271954748 18.0839176,3.767242 C18.604453,4.93499149 18.4761184,6.97172237 18.3730049,8.60867341 L18.3681645,8.68701166 C18.3540254,8.90928849 18.340969,9.11965536 18.3299507,9.32358958 C18.3781001,9.36791757 18.5716529,9.52077269 18.9654459,9.53624928 C19.301154,9.52338397 19.6869221,9.41581217 20.111732,9.21690944 C20.24306,9.15525787 20.3884635,9.14245625 20.4871824,9.14245625 C20.6364072,9.14245625 20.7882433,9.17149873 20.9147946,9.22429744 L20.9215457,9.22690871 C21.2820291,9.35486119 21.5181265,9.61057508 21.5232217,9.87921797 C21.5277437,10.1296456 21.3416426,10.5039496 20.4262951,10.865452 C20.332544,10.902583 20.2129348,10.9405421 20.0865746,10.9806029 C19.5801146,11.1413555 18.8159026,11.3838856 18.584964,11.9281773 C18.4594954,12.2233787 18.5007663,12.5858365 18.7076303,13.0052964 C18.7099231,13.0098821 18.7118975,13.0145314 18.7141266,13.0193718 C18.7778162,13.1686603 20.3194239,16.683755 23.758919,17.2504017 C23.9038129,17.2745401 24.0078181,17.403639 23.9995385,17.5504436 C23.9964814,17.6031786 23.9837434,17.6559137 23.9614521,17.7074386 C23.7519768,18.1980398 22.693073,18.6048256 20.9002734,18.8817481 C20.7320054,18.9077335 20.6611188,19.1796882 20.5641832,19.6248788 C20.5240587,19.8087507 20.4832336,19.9889924 20.4275052,20.1784054 C20.3753434,20.3565453 20.2593009,20.443609 20.072945,20.443609 L20.0448579,20.443609 C19.9235291,20.443609 19.7516308,20.4215724 19.5348313,20.3791551 C19.1558779,20.3054025 18.730877,20.2367451 18.1904067,20.2367451 C17.8752704,20.2367451 17.5491158,20.2643864 17.2207957,20.3187137 C16.5537741,20.4297884 15.9838793,20.8321795 15.380611,21.2586453 C14.535768,21.8559904 13.5799776,22.5316101 12.1511006,22.5316101" stroke="none"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'SocialSnapchat'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/containers/home/react-native-zss-rich-text-editor/src/RichTextToolbar.js
airingursb/two-life
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import {ListView, View, TouchableOpacity, Image} from 'react-native'; import {actions} from './const'; const defaultActions = [ actions.insertImage, actions.setBold, actions.setItalic, actions.insertBulletsList, actions.insertOrderedList, actions.insertLink ]; function getDefaultIcon() { // const texts = {}; // texts[actions.insertImage] = require('../img/icon_format_media.png'); // texts[actions.setBold] = require('../img/icon_format_bold.png'); // texts[actions.setItalic] = require('../img/icon_format_italic.png'); // texts[actions.insertBulletsList] = require('../img/icon_format_ul.png'); // texts[actions.insertOrderedList] = require('../img/icon_format_ol.png'); // texts[actions.insertLink] = require('../img/icon_format_link.png'); // return texts; } export default class RichTextToolbar extends Component { static propTypes = { getEditor: PropTypes.func.isRequired, actions: PropTypes.array, onPressAddLink: PropTypes.func, onPressAddImage: PropTypes.func, onPressIdentifyDiary: PropTypes.func, selectedButtonStyle: PropTypes.object, iconTint: PropTypes.any, selectedIconTint: PropTypes.any, unselectedButtonStyle: PropTypes.object, renderAction: PropTypes.func, iconMap: PropTypes.object, selectedAction: PropTypes.func }; constructor(props) { super(props); const actions = this.props.actions ? this.props.actions : defaultActions; this.state = { editor: undefined, selectedItems: [], actions, ds: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(this.getRows(actions, [])) }; } componentWillReceiveProps(newProps) { const actions = newProps.actions ? newProps.actions : defaultActions; this.setState({ actions, ds: this.state.ds.cloneWithRows(this.getRows(actions, this.state.selectedItems)) }); } getRows(actions, selectedItems) { return actions.map((action) => {return {action, selected: selectedItems.includes(action)};}); } componentDidMount() { const editor = this.props.getEditor(); if (!editor) { throw new Error('Toolbar has no editor!'); } else { editor.registerToolbar((selectedItems) => this.setSelectedItems(selectedItems)); this.setState({editor}); } } setSelectedItems(selectedItems) { if (selectedItems !== this.state.selectedItems) { this.setState({ selectedItems, ds: this.state.ds.cloneWithRows(this.getRows(this.state.actions, selectedItems)) }); } } _getButtonIcon(action) { if (this.props.iconMap && this.props.iconMap[action]) { return this.props.iconMap[action]; } else if (getDefaultIcon()[action]){ return getDefaultIcon()[action]; } else { return undefined; } } _defaultRenderAction(action, selected) { const icon = this._getButtonIcon(action); return ( <TouchableOpacity key={action} style={[ { width: 42, height: 50, flex: 1, alignItems: 'center', justifyContent: 'center', marginRight: action === actions.insertImage ? 10 : 0 } ]} onPress={() => this._onPress(action, selected)} > {icon ? <Image source={icon} style={{tintColor: selected ? this.props.selectedIconTint : this.props.iconTint}}/> : null} </TouchableOpacity> ); } _renderAction(action, selected) { return this.props.renderAction ? this.props.renderAction(action, selected) : this._defaultRenderAction(action, selected); } render() { return ( <View style={[{height: 50, alignItems: 'center'}, this.props.style]} > <ListView horizontal contentContainerStyle={{flexDirection: 'row'}} dataSource={this.state.ds} renderRow={(row) => this._renderAction(row.action, row.selected)} /> </View> ); } _onPress(action, selected) { switch(action) { case actions.setBold: case actions.setItalic: case actions.insertBulletsList: case actions.insertOrderedList: case actions.setUnderline: case actions.heading1: case actions.heading2: case actions.heading3: case actions.heading4: case actions.heading5: case actions.heading6: case actions.setParagraph: // case actions.setBlockquote: case actions.removeFormat: case actions.alignLeft: case actions.alignCenter: case actions.alignRight: case actions.alignFull: case actions.setSubscript: case actions.setSuperscript: case actions.setStrikethrough: case actions.setHR: case actions.setIndent: case actions.setOutdent: this.props.selectedAction(action, selected ? 0 : 1, this.state.selectedItems) this.state.editor._sendAction(action); break; case actions.insertLink: this.state.editor.prepareInsert(); if(this.props.onPressAddLink) { this.props.onPressAddLink(); } else { this.state.editor.getSelectedText().then(selectedText => { this.state.editor.showLinkDialog(selectedText); }); } break; case actions.insertImage: this.props.onPressAddImage(); break; case actions.identifyDiary: this.props.onPressIdentifyDiary(); break; } } }
src/svg-icons/notification/sync-disabled.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSyncDisabled = (props) => ( <SvgIcon {...props}> <path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z"/> </SvgIcon> ); NotificationSyncDisabled = pure(NotificationSyncDisabled); NotificationSyncDisabled.displayName = 'NotificationSyncDisabled'; NotificationSyncDisabled.muiName = 'SvgIcon'; export default NotificationSyncDisabled;
admin/client/App/screens/Item/components/EditFormHeader.js
alobodig/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { connect } from 'react-redux'; import Toolbar from './Toolbar'; import ToolbarSection from './Toolbar/ToolbarSection'; import EditFormHeaderSearch from './EditFormHeaderSearch'; import { Link } from 'react-router'; import Drilldown from './Drilldown'; import { GlyphButton, ResponsiveText } from '../../../elemental'; export const EditFormHeader = React.createClass({ displayName: 'EditFormHeader', propTypes: { data: React.PropTypes.object, list: React.PropTypes.object, toggleCreate: React.PropTypes.func, }, getInitialState () { return { searchString: '', }; }, toggleCreate (visible) { this.props.toggleCreate(visible); }, searchStringChanged (event) { this.setState({ searchString: event.target.value, }); }, handleEscapeKey (event) { const escapeKeyCode = 27; if (event.which === escapeKeyCode) { findDOMNode(this.refs.searchField).blur(); } }, renderDrilldown () { return ( <ToolbarSection left> {this.renderDrilldownItems()} {this.renderSearch()} </ToolbarSection> ); }, renderDrilldownItems () { const { data, list } = this.props; const items = data.drilldown ? data.drilldown.items : []; let backPath = `${Keystone.adminPath}/${list.path}`; const backStyles = { paddingLeft: 0, paddingRight: 0 }; // Link to the list page the user came from if (this.props.listActivePage && this.props.listActivePage > 1) { backPath = `${backPath}?page=${this.props.listActivePage}`; } // return a single back button when no drilldown exists if (!items.length) { return ( <GlyphButton component={Link} data-e2e-editform-header-back glyph="chevron-left" position="left" style={backStyles} to={backPath} variant="link" > {list.plural} </GlyphButton> ); } // prepare the drilldown elements const drilldown = []; items.forEach((item, idx) => { // FIXME @jedwatson // we used to support relationships of type MANY where items were // represented as siblings inside a single list item; this got a // bit messy... item.items.forEach(link => { drilldown.push({ href: link.href, label: link.label, title: item.list.singular, }); }); }); // add the current list to the drilldown drilldown.push({ href: backPath, label: list.plural, }); return ( <Drilldown items={drilldown} /> ); }, renderSearch () { var list = this.props.list; return ( <form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search"> <EditFormHeaderSearch value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} /> {/* <GlyphField glyphColor="#999" glyph="search"> <FormInput ref="searchField" type="search" name="search" value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} placeholder="Search" style={{ paddingLeft: '2.3em' }} /> </GlyphField> */} </form> ); }, renderInfo () { return ( <ToolbarSection right> {this.renderCreateButton()} </ToolbarSection> ); }, renderCreateButton () { const { nocreate, autocreate, singular } = this.props.list; if (nocreate) return null; let props = {}; if (autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => { this.toggleCreate(true); }; } return ( <GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" {...props}> <ResponsiveText hiddenXS={`New ${singular}`} visibleXS="Create" /> </GlyphButton> ); }, render () { return ( <Toolbar> {this.renderDrilldown()} {this.renderInfo()} </Toolbar> ); }, }); export default connect((state) => ({ listActivePage: state.lists.page.index, }))(EditFormHeader);
src/js/SecondPage.js
merlox/dapp-transactions
import React from 'react' import Header from './Header' import { Link } from 'react-router-dom' import './../stylus/index.styl' import './../stylus/secondpage.styl' import LINKS from './utils.js' class SecondPage extends React.Component { constructor(props){ super(props) this.state = { dialog1: false, dialog2: false, dialog3: false, dialog4: false, oneActive: false, isMobile: false, } this.updateWindowDimensions = this.updateWindowDimensions.bind(this) } componentDidMount() { this.updateWindowDimensions() window.addEventListener('resize', this.updateWindowDimensions) } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions) } updateWindowDimensions() { if(window.innerWidth <= 750 && this.state.isMobile === false) this.setState({ isMobile: true }) else if(window.innerWidth > 750 && this.state.isMobile) this.setState({ isMobile: false }) } render(){ return ( <div style={{height: '100%'}}> <div style={{display: this.props.showRetailers ? 'block' : 'none'}} className="retailers-container"> <h1 className="title">Choose a Retailer</h1> <div className="icon-box-container"> <div className="icon-box"> <img src="../img/retailer/garden.png" onClick={() => { this.setState({ dialog1: !this.state.dialog1, dialog2: false, dialog3: false, dialog4: false, oneActive: !this.state.dialog1, }) }} /> <p>Garden Gear</p> <input ref="retailer1-address" type="hidden" value="8 sloane square, South Kensignton" /> <input ref="retailer1-city" type="hidden" value="London" /> <input ref="retailer1-code" type="hidden" value="SW75RD" /> <Dialog extraClass="dialog-number-1" style={{ display: this.state.dialog1 ? 'block' : 'none' }} checkoutItem={data => { this.props.checkoutItem({ ...data, retailerName: 'Garden Gear', retailerImage: '../img/retailer/garden.png', retailerAddress: this.refs['retailer1-address'].value, retailerCity: this.refs['retailer1-city'].value, retailerCode: this.refs['retailer1-code'].value, }) }} item1={{ image: LINKS.baseUrl + "img/retailer/lawnmover.png", name: "Lawnmover", price: "12.99", }} item2={{ image: LINKS.baseUrl + "img/retailer/hedgetrimmer.png", name: "Hedgetrimmer", price: "12.99", }} item3={{ image: LINKS.baseUrl + "img/retailer/mover.png", name: "Wheelbarrow", price: "12.99", }} /> </div> <div className="icon-box" ref="second-box"> <img src="../img/retailer/suits.png" onClick={() => { this.setState({ dialog1: false, dialog2: !this.state.dialog2, dialog3: false, dialog4: false, oneActive: !this.state.dialog2, }) }} /> <p>Sharp Suits</p> <input ref="retailer2-address" type="hidden" value="8 sloane square, South Kensignton" /> <input ref="retailer2-city" type="hidden" value="London" /> <input ref="retailer2-code" type="hidden" value="SW75RD" /> <Dialog extraClass="dialog-number-2" style={{ display: this.state.dialog2 ? 'block' : 'none' }} checkoutItem={data => { this.props.checkoutItem({ ...data, retailerName: 'Sharp Suits', retailerImage: "../img/retailer/suits.png", retailerAddress: this.refs['retailer2-address'].value, retailerCity: this.refs['retailer2-city'].value, retailerCode: this.refs['retailer2-code'].value, }) }} item1={{ image: LINKS.baseUrl + "img/retailer/suit-jacket.png", name: "Suit Jacket", price: "12.99", }} item2={{ image: LINKS.baseUrl + "img/retailer/tie.png", name: "Tie", price: "12.99", }} item3={{ image: LINKS.baseUrl + "img/retailer/shirt.png", name: "Shirt", price: "12.99", }} /> </div> <div className="icon-box"> <img src="../img/retailer/box.png" onClick={() => { this.setState({ dialog1: false, dialog2: false, dialog3: !this.state.dialog3, dialog4: false, oneActive: !this.state.dialog3, }) }} /> <p>Toy Box</p> <input ref="retailer3-address" type="hidden" value="8 sloane square, South Kensignton" /> <input ref="retailer3-city" type="hidden" value="London" /> <input ref="retailer3-code" type="hidden" value="SW75RD" /> <Dialog extraClass="dialog-number-3" style={{ display: this.state.dialog3 ? 'block' : 'none' }} checkoutItem={data => { this.props.checkoutItem({ ...data, retailerName: 'Toy Box', retailerImage: "../img/retailer/box.png", retailerAddress: this.refs['retailer3-address'].value, retailerCity: this.refs['retailer3-city'].value, retailerCode: this.refs['retailer3-code'].value, }) }} item1={{ image: LINKS.baseUrl + "img/retailer/teddy-bear.png", name: "Teddy Bear", price: "12.99", }} item2={{ image: LINKS.baseUrl + "img/retailer/doll.png", name: "Doll", price: "12.99", }} item3={{ image: LINKS.baseUrl + "img/retailer/scooter.png", name: "Scooter", price: "12.99", }} /> </div> <div className="icon-box"> <img src="../img/retailer/jewelry.png" onClick={() => { this.setState({ dialog1: false, dialog2: false, dialog3: false, dialog4: !this.state.dialog4, oneActive: !this.state.dialog4, }) }} /> <p>Rhombus Jewelry</p> <input ref="retailer4-address" type="hidden" value="8 sloane square, South Kensignton" /> <input ref="retailer4-city" type="hidden" value="London" /> <input ref="retailer4-code" type="hidden" value="SW75RD" /> <Dialog extraClass="dialog-number-4" style={{ display: this.state.dialog4 ? 'block' : 'none' }} checkoutItem={data => { this.props.checkoutItem({ ...data, retailerName: 'Rhombus Jewelry', retailerImage: "../img/retailer/jewelry.png", retailerAddress: this.refs['retailer4-address'].value, retailerCity: this.refs['retailer4-city'].value, retailerCode: this.refs['retailer4-code'].value, }) }} item1={{ image: LINKS.baseUrl + "img/retailer/diamond-necklace.png", name: "Diamond Necklace", price: "12.99", }} item2={{ image: LINKS.baseUrl + "img/retailer/diamond-bracelet.png", name: "Diamond Bracelet", price: "12.99", }} item3={{ image: LINKS.baseUrl + "img/retailer/diamond-ring.png", name: "Diamond Ring", price: "12.99", }} /> </div> </div> </div> <div style={{display: this.props.showRetailers ? 'none' : 'block'}} className={ !this.state.isMobile && this.state.oneActive ? 'wholesalers-container expand-retailers' : 'wholesalers-container' }> <h2>Wholesalers</h2> <div className="icon-box-container"> <div className="icon-box"> <Link to={LINKS.counterSign}><img src={LINKS.baseUrl + "img/retailer/menswear.png"} /></Link> <p>Menswear Stockist</p> </div> <div className="icon-box"> <Link to={LINKS.counterSign}><img src={LINKS.baseUrl + "img/retailer/toydealer.png"} /></Link> <p>Toy Dealer</p> </div> <div className="icon-box"> <Link to={LINKS.counterSign}><img src={LINKS.baseUrl + "img/retailer/diamondis.png"} /></Link> <p>Diamondis</p> </div> <div className="icon-box"> <Link to={LINKS.counterSign}><img src={LINKS.baseUrl + "img/retailer/gardenerworld.png"} /></Link> <p>Gardener's World</p> </div> </div> </div> </div> ) } } class Dialog extends React.Component { constructor(props){ super(props) } render(){ return ( <div className={'dialog-box ' + (this.props.extraClass ? this.props.extraClass : '')} style={this.props.style} > <h3>Choose a product</h3> <div className="dialog-box-items"> <DialogItem image={this.props.item1.image} name={this.props.item1.name} price={this.props.item1.price} checkoutItem={data => this.props.checkoutItem(data)} /> <div className="dialog-border"></div> <DialogItem image={this.props.item2.image} name={this.props.item2.name} price={this.props.item2.price} checkoutItem={data => this.props.checkoutItem(data)} /> <div className="dialog-border"></div> <DialogItem image={this.props.item3.image} name={this.props.item3.name} price={this.props.item3.price} checkoutItem={data => this.props.checkoutItem(data)} /> </div> </div> ) } } class DialogItem extends React.Component{ constructor(props){ super(props) this.state = { quantity: 1 } } updateQuantity(increase){ if(increase) this.setState({ quantity: this.state.quantity + 1 }) else if(this.state.quantity > 1) this.setState({ quantity: this.state.quantity - 1 }) } render(){ return ( <div className="dialog-box-item"> <img src={this.props.image} /> <p className="product-title">{this.props.name}</p> <p className="product-price">$ {this.props.price}</p> <p className="qty">QTY</p> <div className="counter-container"> <button className="counter-sign" onClick={e => { e.preventDefault() this.updateQuantity(false) }} >-</button> <span className="qty-selected">{this.state.quantity}</span> <button className="counter-sign" onClick={e => { e.preventDefault() this.updateQuantity(true) }} >+</button> </div> <button className="checkout-button" onClick={() => { this.props.checkoutItem({ itemName: this.props.name, itemPrice: this.props.price, itemQuantity: this.state.quantity, }) }} >Checkout</button> </div> ) } } export default SecondPage
src/svg-icons/KeyboardArrowRight.js
AndriusBil/material-ui
// @flow import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../SvgIcon'; /** * @ignore - internal component. */ let KeyboardArrowRight = props => ( <SvgIcon {...props}> <path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z" /> </SvgIcon> ); KeyboardArrowRight = pure(KeyboardArrowRight); KeyboardArrowRight.muiName = 'SvgIcon'; export default KeyboardArrowRight;
node_modules/react-bootstrap/es/ButtonToolbar.js
superKaigon/TheCave
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var ButtonToolbar = function (_React$Component) { _inherits(ButtonToolbar, _React$Component); function ButtonToolbar() { _classCallCheck(this, ButtonToolbar); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ButtonToolbar.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { role: 'toolbar', className: classNames(className, classes) })); }; return ButtonToolbar; }(React.Component); export default bsClass('btn-toolbar', ButtonToolbar);
src/components/about/AboutPage.js
Keaws/react-redux-pl
import React from 'react'; class AboutPage extends React.Component { render() { return( <div> <h1>About</h1> <p>This app uses react and other stuff</p> </div> ); } } export default AboutPage;
Ethereum-based-Roll4Win/node_modules/react-overlays/es/DropdownToggle.js
brett-harvey/Smart-Contracts
import PropTypes from 'prop-types'; import React from 'react'; import DropdownContext from './DropdownContext'; var propTypes = { /** * A render prop that returns a Toggle element. The `props` * argument should spread through to **a component that can accept a ref**. Use * the `onToggle` argument to toggle the menu open or closed * * @type {Function ({ * show: boolean, * toggle: (show: boolean) => void, * props: { * ref: (?HTMLElement) => void, * aria-haspopup: true * aria-expanded: boolean * }, * }) => React.Element} */ children: PropTypes.func.isRequired }; function DropdownToggle(_ref) { var children = _ref.children; return React.createElement(DropdownContext.Consumer, null, function (_ref2) { var show = _ref2.show, toggle = _ref2.toggle, toggleRef = _ref2.toggleRef; return children({ show: show, toggle: toggle, props: { ref: toggleRef, 'aria-haspopup': true, 'aria-expanded': !!show } }); }); } DropdownToggle.displayName = 'ReactOverlaysDropdownToggle'; DropdownToggle.propTypes = propTypes; export default DropdownToggle;
js/components/createPet/index.js
phamngoclinh/PetOnline_vs2
import React, { Component } from 'react'; import { MapView, Image, TextInput, UselessTextInput, Alert, AsyncStorage } from 'react-native'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Text, Button, Icon, Fab, View, Thumbnail, InputGroup, Input, Spinner } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import template from '../../themes/style-template'; import { setIndex } from '../../actions/list'; import styles from './styles'; const { popRoute, pushRoute, replaceAt, } = actions; var Platform = require('react-native').Platform; var ImagePicker = require('react-native-image-picker'); var AUTH_TOKEN = ''; var authToken = ''; var FROM_PET_ID = ''; // More info on all the options is below in the README...just some common use cases shown here var options = { title: 'Select Avatar', customButtons: [ {name: 'fb', title: 'Choose Photo from Facebook'}, ], storageOptions: { skipBackup: true, path: 'images' } }; var userAuthInfoId = ''; class CreatePet extends Component { static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, setIndex: React.PropTypes.func, popRoute: React.PropTypes.func, pushRoute: React.PropTypes.func, replaceAt: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } constructor(props) { super(props); this.state = { active: 'true', avatarSource: null, avatarSourceBase64: '', petName: '', petDate: '', petPrice: 100000, petOther: '', is_loading: false, authenticateToken: '', createPetMessage: '', is_search: false, search: '' }; } componentDidMount() { let _this = this; _this._loadInitialState(); } popRoute() { this.props.popRoute(this.props.navigation.key); } pushRoute(route, index) { this.props.setIndex(index); this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key); } replaceRoute(route) { // this.setUser(this.state.name); this.props.replaceAt('createPet', { key: route }, this.props.navigation.key); } loadImageFromDevice() { /** * The first arg is the options object for customization (it can also be null or omitted for default options), * The second arg is the callback which sends object: response (more info below in README) */ ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { // You can display the image using either data... const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true}; this.setState({ avatarSourceBase64: response.data }); // const source = {uri: response.data, isStatic: true}; // or a reference to the platform specific asset location if (Platform.OS === 'ios') { const source = {uri: response.uri.replace('file://', ''), isStatic: true}; } else { const source = {uri: response.uri, isStatic: true}; } this.setState({ avatarSource: source }); console.log("Source: ", source); } }); } createPet() { let _this = this; if( this.state.avatarSourceBase64 == '' || this.state.petName == '' || this.state.petDate == '' || this.state.petPrice == '' ) { _this.setState({ createPetMessage: 'Vui lòng điền đầy đủ thông tin' }); } else { _this.setState({ is_loading: true }); // ... fetch('http://210.211.118.178/PetsAPI/api/pets', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Auth-Token': authToken }, body: JSON.stringify({ "name": this.state.petName, "birthDate": this.state.petDate, "price": this.state.petPrice, "userAuthInfoId": userAuthInfoId, "thumbNailInBase64": this.state.avatarSourceBase64 }) }) .then((response) => response.json()) .then((responseJson) => { // Store the results in the state variable results and set loading to console.log(responseJson); if(responseJson.errorCode) { console.log("Code: "+ responseJson.errorMsg); _this.setState({ is_loading: false }); Alert.alert( "Thông báo", responseJson.errorMsg, [ {text: 'Quay lại', onPress: () => console.log('Quay lại pressed'), style: 'cancel'} ] ); } else { console.log("PEt created: ", responseJson); AsyncStorage.setItem('PET_ID', responseJson.id.toString()); _this.setState({ is_loading: false }); Alert.alert( "Tạo pet thành công", "Tiếp tục tạo bài viết cho Pet", [ {text: 'OK', onPress: () => this.replaceRoute('createArticle'), style: 'ok'} ] ); } }) .catch((error) => { _this.setState({ is_loading: false }); Alert.alert( "Lỗi", "Lỗi phát sinh trong quá trình đăng ký. Vui lòng thử lại!", [ {text: 'Tìm hiểu thêm', onPress: () => console.log('Tìm hiểu thêm pressed')}, {text: 'OK', onPress: () => console.log('OK Pressed')}, ] ); console.error(error); }); } } _loadInitialState () { AsyncStorage.getItem('AUTH_TOKEN').then( (value) => { authToken = value; }); AsyncStorage.getItem('USER_ID').then( (value) => { userAuthInfoId = value; }); // try { // authToken = await AsyncStorage.getItem(AUTH_TOKEN); // // alert(authToken); // if (authToken !== null){ // // this.replaceRoute('home'); // this.setState({ // authenticateToken : authToken // }); // } else { // try { // // // } catch (error) { // // // } // } // } catch (error) { // // // } }; search() { // Set loading to true when the search starts to display a Spinner AsyncStorage.setItem('SEARCH_TEXT', this.state.search); this.pushRoute('search', 3); } render() { const { props: { name, index, list } } = this; return ( <Container style={styles.container}> { this.state.is_search ? ( <Header searchBar rounded> <InputGroup> <Icon name="ios-search" /> <Input placeholder="Tìm kiếm thú cưng..." value={this.state.search} onChangeText={(text) => this.setState({search:text})} onSubmitEditing={()=>this.search()}/> <Button transparent onPress={()=> this.setState({is_search: false})}><Icon style={{color: '#333333'}} name='ios-close-circle' /></Button> </InputGroup> <Button transparent>Search</Button> </Header> ) : null } <Header> <Button transparent onPress={() => this.popRoute()}> <Icon name="ios-arrow-back" /> </Button> <Title>{(name) ? this.props.name : 'Tạo thú cưng'}</Title> <Button transparent onPress={() => this.setState({is_search: true})}> <Icon name="ios-search" /> </Button> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Header> <Content padder style={styles.wrapper}> <View style={styles.imageWrapper}> <Image style={styles.imageUploaded} source={this.state.avatarSource} /> <Button bordered style={styles.buttonUpload} onPress={() => this.loadImageFromDevice()}> {this.state.avatarSource ? 'Thay đổi hình ảnh' : 'Chọn ảnh tải lên'} </Button> </View> <View> <InputGroup iconRight style={styles.myInput}> <Icon name='ios-swap' style={{color:'#00C497'}}/> <Input placeholder="Tên thú cưng" onChangeText={petName => this.setState({ petName })} /> </InputGroup> <InputGroup iconRight style={styles.myInput}> <Icon name='ios-swap' style={{color:'#00C497'}}/> <Input placeholder="Ngày sinh" onChangeText={petDate => this.setState({ petDate })} /> </InputGroup> <InputGroup iconRight style={styles.myInput}> <Icon name='ios-swap' style={{color:'#00C497'}}/> <Input placeholder="Giá" onChangeText={petPrice => this.setState({ petPrice })} /> </InputGroup> <InputGroup iconRight style={styles.myInput}> <Icon name='ios-swap' style={{color:'#00C497'}}/> <Input placeholder="Thông tin khác" onChangeText={petOther => this.setState({ petOther })} /> </InputGroup> {this.state.createPetMessage ? <Text style={{ color: template.danger, alignSelf: 'center', marginTop: 15 }}>{this.state.createPetMessage}</Text> : null} {this.state.is_loading ? <Spinner color='blue' visible={this.state.is_loading} /> : null} <Button large style={styles.createPet} onPress={() => this.createPet()}>TẠO THÚ CƯNG</Button> </View> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), setIndex: index => dispatch(setIndex(index)), pushRoute: (route, key) => dispatch(pushRoute(route, key)), replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(CreatePet);
public/src/components/main/main.js
white87332/react-redux-sample
import React from 'react'; import './main.scss'; class Main extends React.Component { constructor(props) { super(props); } render() { return ( <div> {this.props.children} </div> ); } } export default Main;
src/events/event-channel.js
FederationOfFathers/ui
import React, { Component } from 'react'; import Event from './event' // props = channel, state class EventChannel extends Component { constructor(props) { super(props) this.state={ expanded: false, } } clickHandler = () => { this.setState({expanded: !this.state.expanded}) } channelEvents = () => { if (!this.state.expanded) { return null } let eventComponents = [] let events = this.props.channel.events; for (let i in events) { eventComponents.push(<Event key={i} event={events[i]} state={this.props.state} />) } return eventComponents } render = () => { // don't display if no events if (this.props.channel.events.length <= 0) { return null } let channelName = "" if (this.props.channel.categoryname !== "") { channelName += this.props.channel.categoryName + ": "; } channelName += this.props.channel.name; return ( <div className="channel"> <button className="btn btn-block btn-primary" onClick={this.clickHandler}>{channelName}</button> <div className="channel events"> {this.channelEvents()} </div> </div> ) } } export default EventChannel
src/pages/Login.js
alex-cory/sf-hacks-react-starter
import React from 'react' import { Paper, RaisedButton, TextField } from 'material-ui' const styles = { container: { maxWidth: 300, margin: 'auto', marginTop: 10, padding: 20 }, header: { margin: '5px 0', fontSize: 20 } } const LoginPage = ({ setUserName }) => { let input = null return ( <Paper style={styles.container}> <h1 style={styles.header}>Sign In</h1> <TextField name="Username" placeholder="What people should call you" ref={r => input = r} /> <RaisedButton fullWidth onClick={() => setUserName(input.input.value)} label="Set your username" /> </Paper> ) } export default LoginPage
src/components/EyeIcon/EyeIcon.js
ibenavides/ps-react-ibenavides
import React from 'react'; /** SVG Eye Icon */ function EyeIcon() { // Attribution: Fabián Alexis at https://commons.wikimedia.org/wiki/File:Antu_view-preview.svg return ( <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22"> <g transform="matrix(.02146 0 0 .02146 1 1)" fill="#4d4d4d"> <path d="m466.07 161.53c-205.6 0-382.8 121.2-464.2 296.1-2.5 5.3-2.5 11.5 0 16.9 81.4 174.9 258.6 296.1 464.2 296.1 205.6 0 382.8-121.2 464.2-296.1 2.5-5.3 2.5-11.5 0-16.9-81.4-174.9-258.6-296.1-464.2-296.1m0 514.7c-116.1 0-210.1-94.1-210.1-210.1 0-116.1 94.1-210.1 210.1-210.1 116.1 0 210.1 94.1 210.1 210.1 0 116-94.1 210.1-210.1 210.1" /> <circle cx="466.08" cy="466.02" r="134.5" /> </g> </svg> ) } export default EyeIcon;
src/Accounts/AccountsMenu/AccountsMenu.js
DarthVictor/bank-chat
import React from 'react' import { Link } from 'react-router' import {TextConstants} from '../../resources' import './AccountsMenu.scss' export default function AccountsMenu() { return ( <div role="nav" className="accounts__tab-selector"> <Link className="accounts__tab-button" activeClassName="is-active" to="/">{TextConstants.ACCOUNTS_TEXT}</Link> <Link className="accounts__tab-button" activeClassName="is-active" to="/deposites">{TextConstants.DEPO_TEXT}</Link> </div> ) }
src/js/ui.js
tsuckow/sunxi-fel-chrome-extension
require('styles/ui.less'); import React from 'react'; import ReactDOM from 'react-dom'; import Searching from 'views/searching.jsx'; import usb from 'services/usb.js'; class App extends React.Component { componentDidMount() { chrome.usb.onDeviceAdded.addListener(() => usb.checkForDevices()); chrome.usb.onDeviceRemoved.addListener(() => usb.checkForDevices()); setTimeout(usb.checkForDevices.bind(usb),500); } render() { return <Searching />; } } ReactDOM.render(<App/>, document.getElementById('app')); /* chrome.usb.findDevices({vendorId:0x1f3a,productId:0xefe8},function(devices){ console.log(devices, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); chrome.usb.listInterfaces( devices[0], function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); }); }) */ /* chrome.usb.getDevices({},function(devices){ if( devices.length > 0 ) { chrome.usb.openDevice(devices[0], function(handle) { if(!handle) { console.error(chrome.runtime.lastError.message); return; } console.log("Device",handle); chrome.usb.listInterfaces( handle, function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); }); */ /* chrome.usb.claimInterface( handle, 0, function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); }) */ /* var buffer = new ArrayBuffer(32); var view = new DataView(buffer); view.setUint32(0, 0x41575543, false); //AWUC view.setUint32(4, 0, true); view.setUint32(8, 16, true); view.setUint16(12, 0, true); view.setUint8(14, 0); view.setUint8(15, 0); view.setUint8(16, 0xC); view.setUint8(17, 0x12); // Write view.setUint32(18, 16, true); //Reserved 0 //view.setUint64(22, 0, true); //view.setUint16(30, 0, true); chrome.usb.bulkTransfer(handle, { direction: 'out', endpoint: 0, data: buffer }, function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); var buffer = new ArrayBuffer(16); var view = new DataView(buffer); view.setUint16(0, 0x1, true); //FEL_VERIFY_DEVICE view.setUint16(2, 0, true); //Reserved 0 //view.setUint64(4, 0, true); //view.setUint32(12, 0, true); chrome.usb.bulkTransfer(handle, { direction: 'out', endpoint: 0, data: buffer }, function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); chrome.usb.bulkTransfer(handle, { direction: 'in', endpoint: 0, length: 13 }, function(info){ console.log(info, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); }) }) }) */ /* }); } console.log("Devices",devices, chrome.runtime.lastError ? chrome.runtime.lastError.message : undefined); }); */
src/Cards.js
qiubit/wason-selection-parallel
import _ from 'lodash'; import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class Cards extends Component { constructor(props) { super(props); this.state = { Pactive: false, nPactive: false, Qactive: false, nQactive: false, cardsOrder: _.shuffle(_.range(4)), Ptstamps: [], nPtstamps: [], Qtstamps: [], nQtstamps: [], } this.onPclick = this.onPclick.bind(this); this.onnPclick = this.onnPclick.bind(this); this.onQclick = this.onQclick.bind(this); this.onnQclick = this.onnQclick.bind(this); } onPclick(evt) { evt.preventDefault(); let Ptstamps = this.state.Ptstamps; Ptstamps.push(Date.now()); this.setState({ Pactive: !this.state.Pactive, Ptstamps: Ptstamps }); } onnPclick(evt) { evt.preventDefault(); let nPtstamps = this.state.nPtstamps; nPtstamps.push(Date.now()); this.setState({ nPactive: !this.state.nPactive, nPtstamps: nPtstamps }); } onQclick(evt) { evt.preventDefault(); let Qtstamps = this.state.Qtstamps; Qtstamps.push(Date.now()); this.setState({ Qactive: !this.state.Qactive, Qtstamps: Qtstamps }); } onnQclick(evt) { evt.preventDefault(); let nQtstamps = this.state.nQtstamps; nQtstamps.push(Date.now()); this.setState({ nQactive: !this.state.nQactive, nQtstamps: nQtstamps }); } componentWillUnmount() { const cardsStats = { P: this.state.Pactive, nP: this.state.nPactive, Q: this.state.Qactive, nQ: this.state.nQactive, Ptstamps: this.state.Ptstamps, nPtstamps: this.state.nPtstamps, Qtstamps: this.state.Qtstamps, nQtstamps: this.state.nQtstamps, cardsOrder: this.state.cardsOrder.map((cardId) => { switch (cardId) { case 0: return "P"; case 1: return "nP"; case 2: return "Q"; case 3: return "nQ"; default: return "wrong cardId"; } }), } if (this.props.onCardsUnmount) { this.props.onCardsUnmount(cardsStats); } } render() { return ( <div style={{ padding: 10 }} className="text-center"> {this.state.cardsOrder.map((cardId) => { switch (cardId) { case 0: return (<Button style={{ width: "25%", height: 150, whiteSpace: "normal" }} key="P" bsSize="large" active={this.state.Pactive} onClick={this.onPclick}>{this.props.P}</Button>); case 1: return (<Button style={{ width: "25%", height: 150, whiteSpace: "normal" }} key="nP" bsSize="large" active={this.state.nPactive} onClick={this.onnPclick}>{this.props.nP}</Button>); case 2: return (<Button style={{ width: "25%", height: 150, whiteSpace: "normal" }} key="Q" bsSize="large" active={this.state.Qactive} onClick={this.onQclick}>{this.props.Q}</Button>); case 3: return (<Button style={{ width: "25%", height: 150, whiteSpace: "normal" }} key="nQ" bsSize="large" active={this.state.nQactive} onClick={this.onnQclick}>{this.props.nQ}</Button>); default: console.log("Cards: wrong cardId"); return null; } })} </div> ); } } Cards.propTypes = { P: React.PropTypes.string.isRequired, nP: React.PropTypes.string.isRequired, Q: React.PropTypes.string.isRequired, nQ: React.PropTypes.string.isRequired, onCardsUnmount: React.PropTypes.func, }; export default Cards;
src/style/styles.js
vasi1796/food_ordering
'use strict'; import React from 'react'; import {StyleSheet} from 'react-native'; module.exports = StyleSheet.create({ text: { color: 'white', fontWeight: 'bold' }, mainPage_generalView: { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, choices_view: { padding:20, alignItems: 'center', justifyContent: 'center', marginBottom:5, borderRadius:50, width:170, backgroundColor:"#1676e2" }, parentView: { flex: 1, flexDirection: 'column', justifyContent: 'center', backgroundColor: '#fcfcfc' }, orderMenu: { flex: 1, flexDirection: 'column', backgroundColor: '#f2f2f2' }, totalBoxText: { padding: 15, borderWidth: 0.1, backgroundColor: '#1676e2', justifyContent: 'center', alignItems: 'center' }, placeOrder: { padding: 15, backgroundColor: '#1565C0', justifyContent: 'center', alignItems: 'center', }, menuDescription: { flex:1, backgroundColor: '#f2f2f2', borderWidth: 0.1 }, peopleInCaffeteria: { flexDirection: 'column', flex: 1, padding:5, alignSelf: 'stretch', justifyContent: 'center', alignItems: 'center', backgroundColor: '#1565C0' }, noTicket: { alignSelf: 'center', flex:1, height:60, justifyContent: 'center', alignItems: 'center', }, orderDescription: { flex:1, padding: 20, backgroundColor: '#fcfcfc', borderWidth: 0.1 }, orderTotalBoxText: { padding: 15, borderWidth: 0.1, backgroundColor: '#1676e2', justifyContent: 'center', alignItems: 'center' } });
src/App/ItemsPage.js
haroldSanchezb/ml-react
import React from 'react'; import { Route, Switch } from 'react-router-dom'; import ItemsSearch from './ItemsSearch'; import ItemsList from './ItemsList'; import ItemsDetail from './ItemsDetail'; import styles from './ItemsPage.scss'; const ItemsPage = props => ( <div className={styles.container}> <ItemsSearch {...props} /> <Switch> <Route path="/items/:productId" render={() => <ItemsDetail {...props} />} /> <Route path="/items" render={() => <ItemsList {...props} />} /> </Switch> </div> ); export default ItemsPage;
src/components/ContactLink.js
jonatanramhoj/single-page
import React from 'react'; import ReactDOM from 'react-dom'; class ContactLink extends React.Component { constructor () { super(); this.focus = this.focus.bind(this); this.blur = this.blur.bind(this); } focus () { const body = document.querySelector('body'); body.classList.add('focus'); } blur () { const body = document.querySelector('body'); body.classList.remove('focus'); } render () { const href = this.props.href; const label = this.props.label; const index = this.props.index; return( <span> <a href={href} className="intro__link ghost" ref="link" onMouseEnter={this.focus} onMouseLeave={this.blur}> {label} </a> {`${index !== 4 ? `,\u00A0` : ''}`} </span> ); } } export default ContactLink;
test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js
mangomint/create-react-app
import React, { Component } from 'react'; import { bar as bar2 } from './AppUnknownExport'; class App extends Component { componentDidMount() { bar2(); } render() { return <div />; } } export default App;
app/ui/src/pages/Home.js
pequalsnp/eve-isk-tracker
import React, { Component } from 'react'; class Home extends Component { render() { return ( <div> Home </div> ); } } export default Home;
docs/src/app/components/pages/components/IconMenu/ExampleNested.js
matthewoates/material-ui
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider'; import Download from 'material-ui/svg-icons/file/file-download'; import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; const IconMenuExampleNested = () => ( <div> <IconMenu iconButtonElement={<IconButton><MoreVertIcon /></IconButton>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} > <MenuItem primaryText="Copy & Paste" rightIcon={<ArrowDropRight />} menuItems={[ <MenuItem primaryText="Cut" />, <MenuItem primaryText="Copy" />, <Divider />, <MenuItem primaryText="Paste" />, ]} /> <MenuItem primaryText="Case Tools" rightIcon={<ArrowDropRight />} menuItems={[ <MenuItem primaryText="UPPERCASE" />, <MenuItem primaryText="lowercase" />, <MenuItem primaryText="CamelCase" />, <MenuItem primaryText="Propercase" />, ]} /> <Divider /> <MenuItem primaryText="Download" leftIcon={<Download />} /> <Divider /> <MenuItem value="Del" primaryText="Delete" /> </IconMenu> </div> ); export default IconMenuExampleNested;
src/js/app_1.js
pfb3cn/react_bootcamp_exercise
import React from 'react'; import ReactDOM from 'react-dom'; const oldBlue = { id: 0, make: "Oldsmobile", model: "Cutlass Ciera", year: 1993, color: "Blue", price: 1 } const mercy = { id: 1, make: "Mitsubishi", model: "Lancer", year: 2005, color: "Silver", price: 13000 } const MCM = { id: 2, make: "MINI", model: "Cooper Clubman", year: 2013, color: "Red", price: 25000 } const cars = [oldBlue, mercy, MCM]; const colors = ['green', 'yellow', 'black', 'red', 'white', 'blue']; // import { ColorTool } from './components/color-tool'; // // ReactDOM.render(<ColorTool items={colors} />, document.querySelector('main')); import { CarTool } from './components/car-tool'; ReactDOM.render(<CarTool myCars={cars} />, document.querySelector('main'));
docs/app/Examples/collections/Form/States/FormExampleLoading.js
mohammed88/Semantic-UI-React
import React from 'react' import { Button, Form, Input } from 'semantic-ui-react' const FormExampleLoading = () => ( <Form loading> <Form.Input label='Email' placeholder='joe@schmoe.com' /> <Button>Submit</Button> </Form> ) export default FormExampleLoading
src/ToggleInput.js
curious-containers/cc-ui
import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import { checkJSON } from './utils'; export default createReactClass({ propTypes: { onChange: PropTypes.func.isRequired, heading: PropTypes.string, value: PropTypes.string, className: PropTypes.string, open: PropTypes.bool, }, getDefaultProps() { return { onChange() {}, heading: 'Toggle Input', value: '', className: '', open: false, }; }, getInitialState() { return { open: this.props.open, value: this.props.value, }; }, onChange(ev) { this.setState({ value: ev.target.value }); }, onSubmit(ev) { ev.preventDefault(); this.props.onChange(this.state.value); }, toggleInput() { this.setState({ open: !this.state.open }); }, render() { const borderColor = checkJSON(this.state.value) ? '#e0e0e0' : '#f44336'; return ( <form className={`form ${this.props.className}`}> <button type="button" className="btn btn-default pull-right" style={{ zIndex: 1 }} onClick={this.toggleInput} >{this.props.heading} {this.state.open ? '▲' : '▼'}</button> <textarea rows="10" className="full-width" style={{ border: `2px solid ${borderColor}` }} hidden={!this.state.open} onChange={this.onChange} value={this.state.value} /> <button type="button" className="btn btn-primary full-width" hidden={!this.state.open} onClick={this.onSubmit} >Save</button> </form> ); }, });
scripts/alertSettings.js
diakov2100/YaStreamDesktop
import React from 'react'; import ReactDOM from 'react-dom'; import AlertSettingsMain from '../views/alertSettings/alertSettingsMain.jsx' const $ = require('./jquery.js') const remote = require('electron').remote const BrowserWindow = remote.BrowserWindow let previewWindow = null window.onload = function(){ ReactDOM.render(<AlertSettingsMain />, document.getElementsByClassName('container')[0]); $('#input-height').text(50) $('input[type="range"]').on("change mousemove input", function () { var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min')); $('#input-height').text(Math.round(val*100)) $(this).css('background-image', '-webkit-gradient(linear, left top, right top, ' + 'color-stop(' + val + ', #f3c647), ' + 'color-stop(' + val + ', #979797)' + ')' ) let num = Math.floor(100*val) $('.max').text(num + ' px') }) $('.color').on('change', function() { console.log(1) }) document.getElementsByClassName('button')[0].onclick = () => { previewWindow = new BrowserWindow({ width: 270, height: 265, resizable: false, fullscreenable: false, show: false, autoHideMenuBar: true, useContentSize: true }) previewWindow.loadURL('file://' + __dirname + '/../HTMLs/qrCode.html'); previewWindow.on('closed', () => { previewWindow = null; }) previewWindow.once('ready-to-show', () => { previewWindow.show() }) } /*document.getElementsByClassName('button')[1].onclick = () => { if ($('#indi-color').val() == ''){ localStorage.setItem('goalsSettings_indiColor', 'rgb(243, 198, 71)') } else { localStorage.setItem('goalsSettings_indiColor', $('#indi-color').val()) } if ($('#indiBack-color').val() == ''){ localStorage.setItem('goalsSettings_indiBackColor', 'rgb(41, 41, 44)') } else { localStorage.setItem('goalsSettings_indiBackColor', $('#indiBack-color').val()) } if ($('#font-color').val() == ''){ localStorage.setItem('goalsSettings_fontColor', 'rgb(0, 0, 0)') } else { localStorage.setItem('goalsSettings_fontColor', $('#font-color').val()) } if ($('#back-color').val() == ''){ localStorage.setItem('goalsSettings_backColor', 'rgba(0, 0, 0, 0)') } else { localStorage.setItem('goalsSettings_backColor', $('#back-color').val()) } localStorage.setItem('goalsSettings_indiHeight', $('#input-height').text()) localStorage.setItem('goalsSettings_showHeading', $('#showHeading').val()) localStorage.setItem('goalsSettings_showAmount', $('#showAmount').val()) localStorage.setItem('goalsSettings_showLimits', $('#showLimits').val()) localStorage.setItem('HasGoalSettings', 'True') remote.getCurrentWindow().close() }*/ let returnBtn = document.getElementsByClassName('return')[0] returnBtn.onclick = () => { remote.getCurrentWindow().close() } returnBtn.onmouseover = function(){ this.childNodes[0].childNodes[0].src = '../images/arrowActive.png' } returnBtn.onmouseleave = function(){ this.childNodes[0].childNodes[0].src = '../images/bitmap.png' } }
node_modules/react-bootstrap/es/HelpBlock.js
NickingMeSpace/questionnaire
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var HelpBlock = function (_React$Component) { _inherits(HelpBlock, _React$Component); function HelpBlock() { _classCallCheck(this, HelpBlock); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } HelpBlock.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return HelpBlock; }(React.Component); export default bsClass('help-block', HelpBlock);
src/svg-icons/image/looks.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooks = (props) => ( <SvgIcon {...props}> <path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/> </SvgIcon> ); ImageLooks = pure(ImageLooks); ImageLooks.displayName = 'ImageLooks'; ImageLooks.muiName = 'SvgIcon'; export default ImageLooks;
public/assets/scripts/components/apps/common/single.js
luisfbmelo/reda
import React from 'react'; import { Component, PropTypes } from 'react'; import Link from 'react-router/lib/Link' // Boostrap import { Tooltip, OverlayTrigger } from 'react-bootstrap'; // Components import SvgComponent from '@/components/common/svg'; import { truncate, setUrl } from '@/utils'; import AppPopup from './popup'; // // Handle button click // const onClickApp = (e) => { if (!confirm('Está a sair do sítio REDA da Direção Regional de Educação dos Açores, para ir para um recurso externo. A DRE não se responsabiliza, nem tem qualquer controlo, sobre as opiniões expressas ou a informação contida na página que irá aceder. Os Termos e Condições e de privacidade da plataforma REDA não se aplicam à página que irá aceder.Obrigado por nos visitar e volte sempre!')){ e.preventDefault(); } } export const AppElement = (props) => { if (!props.el){ return null } const { el, classColCount, index, maxcol, config } = props; // Clearfix classes let breaker = ""; breaker = (index)%maxcol == 0 ? ' floatnone floatnone__lg' : ""; breaker = (index)%maxcol == 0 ? breaker + ' floatnone__md' : breaker; breaker = (index)%3 == 0 ? breaker + ' floatnone__sm' : breaker; return( <article className={"col-xs-12 col-sm-4 col-md-" + classColCount + " col-lg-" + classColCount + breaker} > <div className="app__element"> <header> <div className="app__element--picture"> {el.Image && <img src={config.files+"/apps/"+el.slug+"/"+el.Image.name+"."+el.Image.extension} />} </div> <section> <h1 title={el.title}>{truncate(el.title, 4)}</h1> <ul> {el.Systems.map((system, index) => { return <li key={index}><i className={"fa fa-"+ system.icon}></i>{system.title}</li> })} </ul> </section> </header> <section> <p>{truncate(el.description, 40)}</p> </section> <footer className="text-center"> { el.Systems.map((system, index) => { return <AppPopup key={index} target={system.app_system.link} className="cta primary outline block no-border">Ver na Loja</AppPopup> }) } </footer> </div> </article> ); } AppElement.propTypes = { el: PropTypes.object.isRequired, maxcol: PropTypes.number, classColCount: PropTypes.number, config: PropTypes.object }
src/components/Navigation/index.js
on3iro/Gloomhaven-scenario-creator
/** * Renders a Navigation with react-router Links * * @namespace Navigation */ import React from 'react'; import NavBar from './NavBar'; import NavLink from './NavLink'; const Navigation = () => { return ( <NavBar> <NavLink to="/"> Home </NavLink> </NavBar> ); }; export default Navigation;
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
princesadie/SnapDrop-react
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
src/entypo/Briefcase.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Briefcase'; let EntypoBriefcase = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M9,10h2v2h9c0,0-0.149-4.459-0.2-5.854C19.75,4.82,19.275,4,17.8,4h-3.208c-0.497-0.938-1.032-1.945-1.197-2.256C13.064,1.121,12.951,1,12.216,1H7.783C7.048,1,6.936,1.121,6.604,1.744C6.439,2.055,5.904,3.062,5.408,4H2.199c-1.476,0-1.945,0.82-2,2.146C0.145,7.473,0,12,0,12h9V10z M7.649,2.916C7.879,2.484,7.957,2.4,8.466,2.4h3.067c0.509,0,0.588,0.084,0.816,0.516c0.086,0.16,0.318,0.6,0.575,1.084H7.074C7.331,3.516,7.563,3.076,7.649,2.916z M11,15H9v-2H0.5c0,0,0.124,1.797,0.199,3.322C0.73,16.955,0.917,18,2.499,18H17.5c1.582,0,1.765-1.047,1.8-1.678C19.387,14.754,19.5,13,19.5,13H11V15z"/> </EntypoIcon> ); export default EntypoBriefcase;
src/svg-icons/action/swap-vertical-circle.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVerticalCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM6.5 9L10 5.5 13.5 9H11v4H9V9H6.5zm11 6L14 18.5 10.5 15H13v-4h2v4h2.5z"/> </SvgIcon> ); ActionSwapVerticalCircle = pure(ActionSwapVerticalCircle); ActionSwapVerticalCircle.displayName = 'ActionSwapVerticalCircle'; ActionSwapVerticalCircle.muiName = 'SvgIcon'; export default ActionSwapVerticalCircle;
app/screens/social/notifications.js
andry-baka/dapur-ngebul-app
import React from 'react'; import { ListView, View, Image } from 'react-native'; import {RkStyleSheet, RkText} from 'react-native-ui-kitten'; import {Avatar} from '../../components'; import {data} from '../../data'; let moment = require('moment'); export class Notifications extends React.Component { static navigationOptions = { title: 'Notifications' }; constructor(props) { super(props); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.data = ds.cloneWithRows(data.getNotifications()); } renderRow(row) { let username = `${row.user.firstName} ${row.user.lastName}`; let hasAttachment = row.attach !== undefined; let attachment = <View/>; let mainContentStyle; if (hasAttachment) { mainContentStyle = styles.mainContent; attachment = <Image style={styles.attachment} source={row.attach}/> } return ( <View style={styles.container}> <Avatar img={row.user.photo} rkType='circle' style={styles.avatar} badge={row.type}/> <View style={styles.content}> <View style={mainContentStyle}> <View style={styles.text}> <RkText> <RkText rkType='header6'>{username}</RkText> <RkText rkType='primary2'> {row.description}</RkText> </RkText> </View> <RkText rkType='secondary5 hintColor'>{moment().add(row.time, 'seconds').fromNow()}</RkText> </View> {attachment} </View> </View> ) } render() { return ( <ListView style={styles.root} dataSource={this.data} renderRow={this.renderRow}/> ) } } let styles = RkStyleSheet.create(theme => ({ root: { backgroundColor: theme.colors.screen.base }, container: { padding: 16, flexDirection: 'row', borderBottomWidth: 1, borderColor: theme.colors.border.base, alignItems: 'flex-start' }, avatar: {}, text: { marginBottom: 5, }, content: { flex: 1, marginLeft: 16, marginRight: 0 }, mainContent: { marginRight: 60 }, img: { height: 50, width: 50, margin: 0 }, attachment: { position: 'absolute', right: 0, height: 50, width: 50 } }));
src/containers/shopping/ItemBrowser.js
eventures-io/ldn-retail-demo
import React, { Component } from 'react'; import { View, Image, Modal, Text, Alert, ListView, FlatList, ScrollView, StyleSheet, TouchableOpacity, TouchableHighlight, } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { connect } from 'react-redux'; import Carousel from 'react-native-snap-carousel'; import { FirebaseImgRef } from '@constants/'; import { AppColors, AppStyles, AppSizes} from '@theme/'; import { Alerts, Button, Card, Spacer, List, ListItem, FormInput, FormLabel, } from '@components/ui/'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column' }, slide: { width: AppSizes.screen.widthThreeQuarters, height: AppSizes.screen.height / 2.5, borderBottomColor: AppColors.base.grey, borderBottomWidth: 1, backgroundColor: AppColors.base.white }, productContainer: { flexDirection: 'row', paddingLeft: 30 }, titleText: { textAlign: 'center', fontSize: 17, fontWeight: 'bold', padding: 15 }, productImage: { width: 110, height: 160, }, productPrice: { padding: 12, fontStyle: 'italic', fontWeight: 'bold' }, header: { height: AppSizes.screen.heightThird, alignItems: 'center', paddingTop: 15 }, card: { flexDirection: 'column' } }); const mapStateToProps = state => ({ products: state.products.products }); class ItemBrowser extends Component { slides = this.props.products.map((item, index) => { return ( <View key={`entry-${index}`} style={styles.slide}> <View style={styles.card}> <Text style={styles.titleText}>{item.title}</Text> <View style={styles.productContainer}> <Image style={styles.productImage} source={{uri: item.img}}/> <Text style={styles.productPrice}>£{item.price}</Text> </View> </View> </View> ); }); render = () => { return ( <View style={styles.container}> <View style={styles.header}> <Text style={AppStyles.h1}>{'Item browser'}</Text> </View> <Carousel ref={(carousel) => { this._carousel = carousel; }} sliderWidth={AppSizes.screen.width} itemWidth={AppSizes.screen.widthThreeQuarters} itemheight={AppSizes.screen.heightThreeQuarters} > { this.slides } </Carousel> </View> ); } } export default connect(mapStateToProps)(ItemBrowser);
lib/cli/generators/REACT_SCRIPTS/template/src/stories/Button.js
nfl/react-storybook
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import PropTypes from 'prop-types'; import React from 'react'; const buttonStyles = { border: '1px solid #eee', borderRadius: 3, backgroundColor: '#FFFFFF', cursor: 'pointer', fontSize: 15, padding: '3px 10px', margin: 10, }; const Button = ({ children, onClick }) => <button style={buttonStyles} onClick={onClick}> {children} </button>; Button.propTypes = { children: PropTypes.string.isRequired, onClick: PropTypes.func, }; Button.defaultProps = { onClick: () => {}, }; export default Button;
src/svg-icons/image/tag-faces.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTagFaces = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); ImageTagFaces = pure(ImageTagFaces); ImageTagFaces.displayName = 'ImageTagFaces'; ImageTagFaces.muiName = 'SvgIcon'; export default ImageTagFaces;
packages/ui/src/components/widget/table/WidgetTableHeadCell.js
plouc/mozaik
import React from 'react' import styled from 'styled-components' import PropTypes from 'prop-types' const HeadCell = styled.th` padding: 1vmin 2vmin; text-align: left; font-weight: normal; ` const WidgetTableHeadCell = ({ children }) => <HeadCell>{children}</HeadCell> WidgetTableHeadCell.propTypes = { children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired, } export default WidgetTableHeadCell
src/svg-icons/maps/zoom-out-map.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsZoomOutMap = (props) => ( <SvgIcon {...props}> <path d="M15 3l2.3 2.3-2.89 2.87 1.42 1.42L18.7 6.7 21 9V3zM3 9l2.3-2.3 2.87 2.89 1.42-1.42L6.7 5.3 9 3H3zm6 12l-2.3-2.3 2.89-2.87-1.42-1.42L5.3 17.3 3 15v6zm12-6l-2.3 2.3-2.87-2.89-1.42 1.42 2.89 2.87L15 21h6z"/> </SvgIcon> ); MapsZoomOutMap = pure(MapsZoomOutMap); MapsZoomOutMap.displayName = 'MapsZoomOutMap'; export default MapsZoomOutMap;
webpack/scenes/Subscriptions/UpstreamSubscriptions/UpstreamSubscriptionsTableSchema.js
tstrachota/katello
import React from 'react'; import { FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; import helpers from '../../../move_to_foreman/common/helpers'; import { headerFormatter, cellFormatter, selectionHeaderCellFormatter, selectionCellFormatter, } from '../../../move_to_foreman/components/common/table'; export const columns = (controller, selectionController) => [ { property: 'select', header: { label: __('Select all rows'), formatters: [label => selectionHeaderCellFormatter(selectionController, label)], }, cell: { formatters: [ (value, additionalData) => selectionCellFormatter(selectionController, additionalData), ], }, }, { property: 'id', header: { label: __('Subscription Name'), formatters: [headerFormatter], }, cell: { formatters: [ (value, { rowData }) => ( <td> <a href={helpers.urlBuilder('subscriptions', '', rowData.id)}> {rowData.product_name} </a> </td> ), ], }, }, { property: 'contract_number', header: { label: __('Contract'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, // TODO: use date formatter from tomas' PR { property: 'start_date', header: { label: __('Start Date'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, { property: 'end_date', header: { label: __('End Date'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, { property: 'available', header: { label: __('Available Entitlements'), formatters: [headerFormatter], }, cell: { formatters: [ value => ( <td> {value === -1 ? __('Unlimited') : value } </td> ), ], }, }, { property: 'consumed', header: { label: __('Quantity to Allocate'), formatters: [headerFormatter], }, cell: { formatters: [ (value, { rowData }) => ( <td> <FormGroup validationState={controller.quantityValidationInput(rowData)} > <ControlLabel srOnly>{__('Number to Allocate')}</ControlLabel> <FormControl type="text" onBlur={e => controller.onChange(e.target.value, rowData)} defaultValue={rowData.updatedQuantity} onChange={(e) => { controller.onChange(e.target.value, rowData); }} onKeyDown={(e) => { const key = e.charCode ? e.charCode : e.keyCode; if (key === 13) { controller.saveUpstreamSubscriptions(); e.preventDefault(); } }} /> {controller.quantityValidationInput(rowData) === 'error' && <HelpBlock>{controller.quantityValidation(rowData)[1]}</HelpBlock>} </FormGroup> </td> ), ], }, }, ]; export default columns;
src/components/compat/toolbar-buttons.js
ambrinchaudhary/alloy-editor
/** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ import React from 'react'; import Lang from '../../oop/lang'; /** * ToolbarButtons is a mixin which provides a list of buttons which have * to be displayed on the current toolbar depending on user preferences * and given state. * * @class ToolbarButtons */ const ToolbarButtons = { /** * Analyses the current selection and returns the buttons or button * groups to be rendered. * * @instance * @method getToolbarButtonGroups * @param {Array} buttons The buttons could be shown, prior to the state filtering. * @param {Object} additionalProps Additional props that should be passed down to the buttons. * @return {Array} An Array which contains the buttons or button groups that should be rendered. */ getToolbarButtonGroups(buttons, additionalProps) { const instance = this; if (Lang.isFunction(buttons)) { buttons = buttons.call(this) || []; } return buttons.reduce((list, button) => { if (Array.isArray(button)) { list.push(instance.getToolbarButtons(button, additionalProps)); return list; } else { return instance.getToolbarButtons(buttons, additionalProps); } }, []); }, /** * Analyzes the current selection and the buttons exclusive mode value to figure out which * buttons should be present in a given state. * * @instance * @memberof ToolbarButtons * @method getToolbarButtons * @param {Array} buttons The buttons could be shown, prior to the state filtering. * @param {Object} additionalProps Additional props that should be passed down to the buttons. * @return {Array} An Array which contains the buttons that should be rendered. */ getToolbarButtons(buttons, additionalProps) { const buttonProps = {}; const nativeEditor = this.props.editor.get('nativeEditor'); const buttonCfg = nativeEditor.config.buttonCfg || {}; if (Lang.isFunction(buttons)) { buttons = buttons.call(this) || []; } const toolbarButtons = this.filterExclusive( buttons .filter(button => { return ( button && (AlloyEditor.Buttons[button] || AlloyEditor.Buttons[button.name]) ); }) .map(button => { if (Lang.isString(button)) { buttonProps[button] = buttonCfg[button]; button = AlloyEditor.Buttons[button]; } else if (Lang.isString(button.name)) { buttonProps[ AlloyEditor.Buttons[button.name].key ] = CKEDITOR.tools.merge(buttonCfg[button], button.cfg); button = AlloyEditor.Buttons[button.name]; } return button; }) ).map(function(button, index) { let props = this.mergeExclusiveProps( { editor: this.props.editor, key: button.key !== 'separator' ? button.key : `${button.key}-${index}`, tabKey: button.key, tabIndex: this.props.trigger && this.props.trigger.props.tabKey === button.key ? 0 : -1, trigger: this.props.trigger, }, button.key ); props = this.mergeDropdownProps(props, button.key); if (additionalProps) { props = CKEDITOR.tools.merge(props, additionalProps); } props = CKEDITOR.tools.merge(props, buttonProps[button.key]); return React.createElement(button, props); }, this); return toolbarButtons; }, }; export default ToolbarButtons;
app/containers/ProcessViewPage/components/Tile/index.js
BrewPi/brewpi-ui
/** * * Tile * */ import React from 'react'; import styles from './styles.css'; const classNames = require('classnames'); const Tile = (props) => { const x = props.x; const y = props.y; let coordinates; let gridStyle; if (props.showCoordinates) { coordinates = <span className={styles.coordinates}>{x},{y}</span>; } if (props.showGrid) { gridStyle = styles.grid; } return ( <div className={classNames(styles.tile, gridStyle)}> <div className={styles.content}>{props.children}</div> {coordinates} </div> ); }; Tile.propTypes = { x: React.PropTypes.number.isRequired, y: React.PropTypes.number.isRequired, showCoordinates: React.PropTypes.bool, children: React.PropTypes.node, showGrid: React.PropTypes.bool, }; Tile.defaultProps = { x: -1, y: -1, showCoordinates: false, showGrid: false, }; export default Tile;
src/components/MorphDisplay.js
jcuenod/react-lafwebpy-client
import React from 'react' import {toast} from 'react-toastify'; import EventPropagator from 'events/EventPropagator' import { term_to_english, category_weights } from 'data/MorphCodes' class MorphDisplay extends React.Component { constructor(props) { super(props) this.state = {"data": [], "selected": {}} } componentDidMount() { EventPropagator.registerListener({ eventType: "word_clicked", callback: (payload) => { $.post(window.root_url + "/api/word_data", JSON.stringify({ word_id: payload.wid }), (result) => { var morph_data = Object.keys(result).map((key, i) => { return { "selected": false, "k": key, "v": result[key] } }) this.setState({ "data": morph_data }) }) } }) } addSearchTermClickHandler(e) { var search_term = this.state.data.reduce((previousValue, currentValue) => { if (currentValue.selected) previousValue[currentValue.k] = currentValue.v return previousValue }, {}) var morph_state = this.state.data.slice() var new_morph_state = morph_state.map((m) => { m.selected = false return m }) this.setState(new_morph_state) var default_attr_to_add = "lex" if (Object.keys(search_term).length === 0) { var lex_attr = this.state.data.find((attr) => attr.k == default_attr_to_add) if (lex_attr) { search_term[default_attr_to_add] = lex_attr.v toast('We have automatically added ' + term_to_english["categories"][default_attr_to_add] + '. You can choose attributes by clicking on them to construct custom search terms.', { type: toast.TYPE.INFO }); } } EventPropagator.fireEvent({ eventType: "add_search_term", payload: {term: search_term} }) } clickMorphData(key) { var morph_state = this.state.data.slice() var index = morph_state.map((m) => m.k).indexOf(key) morph_state[index].selected = !morph_state[index].selected this.setState({data: morph_state}) } render() { var morph_data = this.state.data.slice() morph_data.sort((a, b) => { var keyA = category_weights.hasOwnProperty(a.k) ? category_weights[a.k] : 0, keyB = category_weights.hasOwnProperty(b.k) ? category_weights[b.k] : 0 return keyA < keyB ? -1 : ((keyA > keyB) ? 1 : 0) }) var newHere = this.state.data.length > 0 ? "" : (<div> <span href="#" className="newhere" onClick={() => EventPropagator.fireEvent({ "eventType": "show_help", "payload": {"slide": "help"} })}></span> </div>) return ( <div className="morph_displayer">{newHere} <table> <tbody> {morph_data.map((morph, i) => { var kv_key = term_to_english["categories"][morph.k] var kv_value = term_to_english.hasOwnProperty(morph.k) ? term_to_english[morph.k][morph.v] : morph.v return ( <tr key={i} className={morph.selected ? "active" : ""} onClick={() => this.clickMorphData(morph.k)}> <td>{kv_key}</td> <td>{kv_value}</td> </tr> ) }, this)} </tbody> </table> <div style={{ backgroundColor: this.state.data.reduce((p, c) => { return p |= c.selected }, false) ? "green" : "gray", display: this.state.data.length > 0 ? "block" : "none" }} className="add_search_term" onClick={this.addSearchTermClickHandler.bind(this)}> add search term </div> </div> ) } } export default MorphDisplay
src/utils/highlight.js
jasonslyvia/react-redux-async-example
/** * @file 在字符串中高亮指定的文本 * @author shuangyang.ys */ /* eslint new-cap:0 */ import React from 'react'; /** * 在 sentence 中匹配并高亮 keyword * @param {string} sentence 被搜索文本 * @param {string} keyword 需要高亮的文本 * @param {number} maxLength 最多匹配多少个字符的文本,默认无限大 * @param {string} highlightClassName 高亮文本的className * @return {array} */ export default function highlight(sentence, keyword, maxLength, highlightClassName = 'highlight') { if (!sentence || !keyword) { return []; } let highlightItems = [], lastIndex = 0; let key = 0; maxLength = maxLength || Number.POSITIVE_INFINITY; sentence.replace(new RegExp(keyword, 'gi'), function(match, index, str){ //如果匹配到的index已经大于最大长度,直接返回 sentence if (index > maxLength) { highlightItems.push(<span key={key++}>{sentence.substring(0, maxLength)}</span>); lastIndex = index; return; } //若匹配到 keyword 字段,把 0-index 部分存为一个 span,把 index-(keyword.length) //部分存为一个高亮的 span 。 //同时判断要被高亮的 span 所在的 index 还在最大指标长度之内,若不在则直接跳过 else if (match !== undefined && index !== undefined) { highlightItems.push(<span key={key++}>{str.substring(lastIndex, index)}</span>); lastIndex = index + match.length; if (lastIndex > maxLength) { return; } highlightItems.push(<span className={highlightClassName} key={key++}>{match}</span>); } //继续下一轮匹配 }); //若匹配完成还有剩余的sentence没有被加入,如 //sentence 为「无线端访客数」, keyword 为 「访客」,经过上述匹配出的结果为 // <span>无线端</span><span className="dip-highlight">访客</span> //则把剩余的「数」加入 <span>数</span> if (lastIndex < sentence.length && lastIndex < maxLength) { highlightItems.push(<span key={key++}>{sentence.substring(lastIndex)}</span>); } return highlightItems; }
ui/src/index.js
oyiptong/splice
import 'babel-core/polyfill'; import React from 'react'; import ReactDOM from 'react-dom' import { Provider } from 'react-redux'; import Routes from './containers/Routes'; import configureStore from './store/configureStore'; const store = configureStore({}); ReactDOM.render( <Provider store={store}> <Routes /> </Provider>, document.getElementById('root') );
app/javascript/mastodon/features/ui/index.js
mstdn-jp/mastodon
import classNames from 'classnames'; import React from 'react'; import NotificationsContainer from './containers/notifications_container'; import PropTypes from 'prop-types'; import LoadingBarContainer from './containers/loading_bar_container'; import TabsBar from './components/tabs_bar'; import ModalContainer from './containers/modal_container'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import { isMobile } from '../../is_mobile'; import { debounce } from 'lodash'; import { uploadCompose, resetCompose } from '../../actions/compose'; import { expandHomeTimeline } from '../../actions/timelines'; import { expandNotifications } from '../../actions/notifications'; import { clearHeight } from '../../actions/height_cache'; import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers'; import UploadArea from './components/upload_area'; import ColumnsAreaContainer from './containers/columns_area_container'; import { Compose, Status, GettingStarted, KeyboardShortcuts, PublicTimeline, CommunityTimeline, AccountTimeline, AccountGallery, HomeTimeline, Followers, Following, Reblogs, Favourites, DirectTimeline, HashtagTimeline, Notifications, FollowRequests, GenericNotFound, FavouritedStatuses, ListTimeline, Blocks, DomainBlocks, Mutes, PinnedStatuses, Lists, } from './util/async-components'; import { HotKeys } from 'react-hotkeys'; import { me } from '../../initial_state'; import { defineMessages, injectIntl } from 'react-intl'; // Dummy import, to make sure that <Status /> ends up in the application bundle. // Without this it ends up in ~8 very commonly used bundles. import '../../components/status'; const messages = defineMessages({ beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' }, }); const mapStateToProps = state => ({ isComposing: state.getIn(['compose', 'is_composing']), hasComposingText: state.getIn(['compose', 'text']) !== '', dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null, }); const keyMap = { help: '?', new: 'n', search: 's', forceNew: 'option+n', focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'], reply: 'r', favourite: 'f', boost: 'b', mention: 'm', open: ['enter', 'o'], openProfile: 'p', moveDown: ['down', 'j'], moveUp: ['up', 'k'], back: 'backspace', goToHome: 'g h', goToNotifications: 'g n', goToLocal: 'g l', goToFederated: 'g t', goToDirect: 'g d', goToStart: 'g s', goToFavourites: 'g f', goToPinned: 'g p', goToProfile: 'g u', goToBlocked: 'g b', goToMuted: 'g m', toggleHidden: 'x', }; class SwitchingColumnsArea extends React.PureComponent { static propTypes = { children: PropTypes.node, location: PropTypes.object, onLayoutChange: PropTypes.func.isRequired, }; state = { mobile: isMobile(window.innerWidth), }; componentWillMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentDidUpdate (prevProps) { if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) { this.node.handleChildrenContentChange(); } } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } handleResize = debounce(() => { // The cached heights are no longer accurate, invalidate this.props.onLayoutChange(); this.setState({ mobile: isMobile(window.innerWidth) }); }, 500, { trailing: true, }); setRef = c => { this.node = c.getWrappedInstance().getWrappedInstance(); } render () { const { children } = this.props; const { mobile } = this.state; const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />; return ( <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}> <WrappedSwitch> {redirect} <WrappedRoute path='/getting-started' component={GettingStarted} content={children} /> <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} /> <WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} /> <WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} /> <WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ onlyMedia: true }} /> <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} /> <WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ onlyMedia: true }} /> <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} /> <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} /> <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} /> <WrappedRoute path='/notifications' component={Notifications} content={children} /> <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} /> <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} /> <WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} /> <WrappedRoute path='/statuses/new' component={Compose} content={children} /> <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} /> <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} /> <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} /> <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} /> <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ withReplies: true }} /> <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} /> <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} /> <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} /> <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} /> <WrappedRoute path='/blocks' component={Blocks} content={children} /> <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} /> <WrappedRoute path='/mutes' component={Mutes} content={children} /> <WrappedRoute path='/lists' component={Lists} content={children} /> <WrappedRoute component={GenericNotFound} content={children} /> </WrappedSwitch> </ColumnsAreaContainer> ); } } @connect(mapStateToProps) @injectIntl @withRouter export default class UI extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { dispatch: PropTypes.func.isRequired, children: PropTypes.node, isComposing: PropTypes.bool, hasComposingText: PropTypes.bool, location: PropTypes.object, intl: PropTypes.object.isRequired, dropdownMenuIsOpen: PropTypes.bool, }; state = { draggingOver: false, }; handleBeforeUnload = (e) => { const { intl, isComposing, hasComposingText } = this.props; if (isComposing && hasComposingText) { // Setting returnValue to any string causes confirmation dialog. // Many browsers no longer display this text to users, // but we set user-friendly message for other browsers, e.g. Edge. e.returnValue = intl.formatMessage(messages.beforeUnload); } } handleLayoutChange = () => { // The cached heights are no longer accurate, invalidate this.props.dispatch(clearHeight()); } handleDragEnter = (e) => { e.preventDefault(); if (!this.dragTargets) { this.dragTargets = []; } if (this.dragTargets.indexOf(e.target) === -1) { this.dragTargets.push(e.target); } if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) { this.setState({ draggingOver: true }); } } handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); try { e.dataTransfer.dropEffect = 'copy'; } catch (err) { } return false; } handleDrop = (e) => { e.preventDefault(); this.setState({ draggingOver: false }); if (e.dataTransfer && e.dataTransfer.files.length === 1) { this.props.dispatch(uploadCompose(e.dataTransfer.files)); } } handleDragLeave = (e) => { e.preventDefault(); e.stopPropagation(); this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el)); if (this.dragTargets.length > 0) { return; } this.setState({ draggingOver: false }); } closeUploadModal = () => { this.setState({ draggingOver: false }); } handleServiceWorkerPostMessage = ({ data }) => { if (data.type === 'navigate') { this.context.router.history.push(data.path); } else { console.warn('Unknown message type:', data.type); } } componentWillMount () { window.addEventListener('beforeunload', this.handleBeforeUnload, false); document.addEventListener('dragenter', this.handleDragEnter, false); document.addEventListener('dragover', this.handleDragOver, false); document.addEventListener('drop', this.handleDrop, false); document.addEventListener('dragleave', this.handleDragLeave, false); document.addEventListener('dragend', this.handleDragEnd, false); if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage); } this.props.dispatch(expandHomeTimeline()); this.props.dispatch(expandNotifications()); } componentDidMount () { this.hotkeys.__mousetrap__.stopCallback = (e, element) => { return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName); }; } componentWillUnmount () { window.removeEventListener('beforeunload', this.handleBeforeUnload); document.removeEventListener('dragenter', this.handleDragEnter); document.removeEventListener('dragover', this.handleDragOver); document.removeEventListener('drop', this.handleDrop); document.removeEventListener('dragleave', this.handleDragLeave); document.removeEventListener('dragend', this.handleDragEnd); } setRef = c => { this.node = c; } handleHotkeyNew = e => { e.preventDefault(); const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea'); if (element) { element.focus(); } } handleHotkeySearch = e => { e.preventDefault(); const element = this.node.querySelector('.search__input'); if (element) { element.focus(); } } handleHotkeyForceNew = e => { this.handleHotkeyNew(e); this.props.dispatch(resetCompose()); } handleHotkeyFocusColumn = e => { const index = (e.key * 1) + 1; // First child is drawer, skip that const column = this.node.querySelector(`.column:nth-child(${index})`); if (column) { const status = column.querySelector('.focusable'); if (status) { status.focus(); } } } handleHotkeyBack = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } setHotkeysRef = c => { this.hotkeys = c; } handleHotkeyToggleHelp = () => { if (this.props.location.pathname === '/keyboard-shortcuts') { this.context.router.history.goBack(); } else { this.context.router.history.push('/keyboard-shortcuts'); } } handleHotkeyGoToHome = () => { this.context.router.history.push('/timelines/home'); } handleHotkeyGoToNotifications = () => { this.context.router.history.push('/notifications'); } handleHotkeyGoToLocal = () => { this.context.router.history.push('/timelines/public/local'); } handleHotkeyGoToFederated = () => { this.context.router.history.push('/timelines/public'); } handleHotkeyGoToDirect = () => { this.context.router.history.push('/timelines/direct'); } handleHotkeyGoToStart = () => { this.context.router.history.push('/getting-started'); } handleHotkeyGoToFavourites = () => { this.context.router.history.push('/favourites'); } handleHotkeyGoToPinned = () => { this.context.router.history.push('/pinned'); } handleHotkeyGoToProfile = () => { this.context.router.history.push(`/accounts/${me}`); } handleHotkeyGoToBlocked = () => { this.context.router.history.push('/blocks'); } handleHotkeyGoToMuted = () => { this.context.router.history.push('/mutes'); } render () { const { draggingOver } = this.state; const { children, isComposing, location, dropdownMenuIsOpen } = this.props; const handlers = { help: this.handleHotkeyToggleHelp, new: this.handleHotkeyNew, search: this.handleHotkeySearch, forceNew: this.handleHotkeyForceNew, focusColumn: this.handleHotkeyFocusColumn, back: this.handleHotkeyBack, goToHome: this.handleHotkeyGoToHome, goToNotifications: this.handleHotkeyGoToNotifications, goToLocal: this.handleHotkeyGoToLocal, goToFederated: this.handleHotkeyGoToFederated, goToDirect: this.handleHotkeyGoToDirect, goToStart: this.handleHotkeyGoToStart, goToFavourites: this.handleHotkeyGoToFavourites, goToPinned: this.handleHotkeyGoToPinned, goToProfile: this.handleHotkeyGoToProfile, goToBlocked: this.handleHotkeyGoToBlocked, goToMuted: this.handleHotkeyGoToMuted, }; return ( <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}> <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}> <TabsBar /> <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}> {children} </SwitchingColumnsArea> <NotificationsContainer /> <LoadingBarContainer className='loading-bar' /> <ModalContainer /> <UploadArea active={draggingOver} onClose={this.closeUploadModal} /> </div> </HotKeys> ); } }
src/linkClass.js
fanhc019/react-css-modules
import React from 'react'; import makeConfiguration from './makeConfiguration'; import _ from 'lodash'; let linkClass; /** * @param {ReactElement} element * @param {Object} styles CSS modules class map. * @param {CSSModules~Options} userConfiguration * @return {ReactElement} */ linkClass = (element, styles = {}, userConfiguration) => { let appendClassName, clonedElement, configuration, newChildren, newProps, styleNames; configuration = makeConfiguration(userConfiguration); styleNames = element.props.styleName; if (styleNames) { styleNames = styleNames.split(' '); if (configuration.allowMultiple === false && styleNames.length > 1) { throw new Error(`ReactElement styleName property defines multiple module names ("${element.props.styleName}").`); } appendClassName = styleNames.map((styleName) => { if (styles[styleName]) { return styles[styleName]; } else { if (configuration.errorWhenNotFound === true) { throw new Error(`"${styleName}" CSS module is undefined.`); } return ''; } }); appendClassName = appendClassName.filter((className) => { return className.length; }); appendClassName = appendClassName.join(' '); } // element.props.children can be one of the following: // 'text' // ['text'] // [ReactElement, 'text'] // ReactElement // console.log(`element.props.children`, element.props.children, `React.Children.count(element.props.children)`, React.Children.count(element.props.children)); if (React.isValidElement(element.props.children)) { newChildren = linkClass(React.Children.only(element.props.children), styles, configuration); } else if (_.isArray(element.props.children)) { newChildren = React.Children.map(element.props.children, (node) => { if (React.isValidElement(node)) { return linkClass(node, styles, configuration); } else { return node; } }); // https://github.com/facebook/react/issues/4723#issuecomment-135555277 // Forcing children into an array produces the following error: // Warning: A ReactFragment is an opaque type. Accessing any of its properties is deprecated. Pass it to one of the React.Children helpers. // newChildren = _.values(newChildren); } if (appendClassName) { if (element.props.className) { appendClassName = `${element.props.className} ${appendClassName}`; } newProps = { className: appendClassName }; } if (newChildren) { clonedElement = React.cloneElement(element, newProps, newChildren); } else { clonedElement = React.cloneElement(element, newProps); } return clonedElement; }; export default linkClass;
2021/src/pages/Home/Contact/index.js
sjamcsclub/jamhacks.ca
import React, { Component } from 'react'; import Newsletter from '../../../components/Newsletter'; import './Contact.css'; import Header from '../../../components/Typography/Header'; import Text from '../../../components/Typography/Text'; class Contact extends Component { constructor(props) { super(props); this.state = {}; } render() { return ( <div className="contact-div" id="contact-section"> <div className="contact-content-div"> <div className="contact-content-half" data-aos="fade-up"> <Header>Still got a question?</Header> <Text> Feel free to send us an email at <a rel="noopener noreferrer" href="mailto:contact@jamhacks.ca"> {' '} contact@jamhacks.ca </a> </Text> <Header>Subscribe to Newsletter</Header> <Newsletter /> </div> </div> </div> ); } } export default Contact;
ui/src/main/js/components/Layout.js
medallia/aurora
import React from 'react'; import Icon from 'components/Icon'; import { addClass } from 'utils/Common'; export function ContentPanel({ children }) { return <div className='content-panel'>{children}</div>; } export function StandardPanelTitle({ title }) { return <div className='content-panel-title'>{title}</div>; } export function PanelSubtitle({ title }) { return <div className='content-panel-subtitle'>{title}</div>; } export function IconPanelTitle({ title, className, icon }) { return (<div className={`content-icon-title ${className}`}> <div className='content-icon-title-text'> <Icon name={icon} /> {title} </div> </div>); } export default function PanelGroup({ children, title, noPadding }) { const extraClass = noPadding ? ' content-panel-fluid' : ''; return (<div className={addClass('content-panel-group', extraClass)}> {title} {React.Children.map(children, (p) => <ContentPanel>{p}</ContentPanel>)} </div>); } export function PanelRow({ children }) { return (<div className='flex-row'> {children} </div>); } export function Container({ children, className }) { const width = 12 / (children.length || 1); return (<div className={addClass('container', className)}> <div className='row'> {React.Children.map(children, (c) => <div className={`col-md-${width}`}>{c}</div>)} </div> </div>); }
src/interface/others/CastEfficiency.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SpellLink from 'common/SpellLink'; import Abilities from 'parser/core/modules/Abilities'; import { TooltipElement } from 'common/Tooltip'; const CastEfficiency = ({ categories, abilities }) => { if (!abilities) { return <div>Loading...</div>; } return ( <div style={{ marginTop: -10, marginBottom: -10 }}> <table className="data-table" style={{ marginTop: 10, marginBottom: 10 }}> {Object.keys(categories) .filter(key => abilities.some(item => item.ability.category === categories[key])) // filters out categories without any abilities in it .filter(key => categories[key] !== Abilities.SPELL_CATEGORIES.HIDDEN) //filters out the hidden category .map(key => ( <tbody key={key}> <tr> <th><b>{categories[key]}</b></th> <th className="text-center"><TooltipElement content="Casts Per Minute">CPM</TooltipElement></th> <th className="text-right"><TooltipElement content="Maximum possible casts are based on the ability's cooldown and the fight duration. For abilities that can have their cooldowns dynamically reduced or reset, it's based on the average actual time it took the ability to cooldown over the course of this encounter.">Casts</TooltipElement></th> <th className="text-center"><TooltipElement content="The percentage of time the spell was kept on cooldown. For spells without charges this also includes when the spell was unavailable due to cast time or time spent waiting for a GCD when the spell was reset due to a proc. Spells with multiple charges count as on cooldown as long as you have fewer than maximum charges. For spells with long cooldowns, it's possible to have well below 100% on cooldown and still achieve maximum casts.">Time on Cooldown</TooltipElement></th> <th /> </tr> {abilities .filter(item => item.ability.category === categories[key]) .map(({ ability, cpm, maxCpm, casts, maxCasts, efficiency, canBeImproved }) => { const name = ability.castEfficiency.name || ability.name; return ( <tr key={name}> <td style={{ width: '35%' }}> <SpellLink id={ability.primarySpell.id} style={{ color: '#fff' }} icon iconStyle={{ height: undefined, marginTop: undefined }}> {name} </SpellLink> </td> <td className="text-center" style={{ minWidth: 80 }}> {cpm.toFixed(2)} </td> <td className="text-right" style={{ minWidth: 110 }}> {casts}{maxCasts === Infinity ? '' : `/${Math.floor(maxCasts)}`} casts </td> <td style={{ width: '20%' }}> {maxCasts === Infinity ? '' : ( <div className="flex performance-bar-container"> <div className="flex-sub performance-bar" style={{ width: `${efficiency * 100}%`, backgroundColor: (canBeImproved && ability.castEfficiency && ability.castEfficiency.suggestion) ? '#ff8000' : '#70b570' }} /> </div> )} </td> <td className="text-left" style={{ minWidth: 50, paddingRight: 5 }}> {maxCpm !== null ? `${(efficiency * 100).toFixed(2)}%` : ''} </td> <td style={{ width: '25%', color: 'orange' }}> {canBeImproved && ability.castEfficiency && ability.castEfficiency.suggestion && 'Can be improved.'} </td> </tr> ); })} </tbody> ))} </table> </div> ); }; CastEfficiency.propTypes = { abilities: PropTypes.arrayOf(PropTypes.shape({ ability: PropTypes.shape({ name: PropTypes.string, category: PropTypes.string.isRequired, primarySpell: PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, }).isRequired, castEfficiency: PropTypes.shape({ name: PropTypes.string, }).isRequired, }), cpm: PropTypes.number.isRequired, maxCpm: PropTypes.number, casts: PropTypes.number.isRequired, maxCasts: PropTypes.number.isRequired, castEfficiency: PropTypes.number, canBeImproved: PropTypes.bool, })).isRequired, categories: PropTypes.object, }; export default CastEfficiency;
console/src/app/tasks/tasks.js
alfredking12/hp-scheduler
import React from 'react'; import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import BaseComponent from '../libs/BaseComponent'; import IconButton from 'material-ui/IconButton'; import ActionEdit from 'material-ui/svg-icons/editor/mode-edit'; import DeleteEdit from 'material-ui/svg-icons/action/delete'; import request from 'superagent/lib/client'; import TaskDetail from './task_detail'; import config from '../config/config'; const styles = { smallIcon: { width: 18, height: 18, }, small: { float: 'right', marginRight: 0, width: 24, height: 24, padding: 0, }, } export default class Tasks extends BaseComponent { constructor(props, context) { super(props, context); Object.assign(this.state, { fixedHeader: true, fixedFooter: true, stripedRows: true, showRowHover: false, height: (window.innerHeight - 190) + 'px', data: [] }); } handleResize(e) { super.handleResize(e); this.setState({height: (window.innerHeight - 190) + 'px'}); } componentDidMount() { super.componentDidMount(); this.load(); } _render() { var _this = this; return ( <div> <div style={{ overflow: 'hidden' }}> <FlatButton label="新建任务" primary={true} style={{marginLeft: 10}} onTouchTap={this.handleCreate.bind(this)} /> </div> <Table height={this.state.height} fixedHeader={this.state.fixedHeader} fixedFooter={this.state.fixedFooter} selectable={false} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow displayBorder={true}> <TableHeaderColumn tooltip="序号" style={{width: '20px'}}>#</TableHeaderColumn> <TableHeaderColumn>任务名称</TableHeaderColumn> <TableHeaderColumn>任务类型</TableHeaderColumn> <TableHeaderColumn>触发器标识</TableHeaderColumn> <TableHeaderColumn style={{textAlign: 'right', paddingRight: '48px'}}>操作</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} showRowHover={this.state.showRowHover} stripedRows={this.state.stripedRows} > {this.state.data.map((row, index) => ( <TableRow key={index} style={{height: '28px'}}> <TableRowColumn style={{height: '28px', width: '20px'}}>{index + 1}</TableRowColumn> <TableRowColumn style={{height: '28px'}}>{row.name}</TableRowColumn> <TableRowColumn style={{height: '28px'}}>{'MQ类型'}</TableRowColumn> <TableRowColumn style={{height: '28px'}}>{row.trigger_code}</TableRowColumn> <TableRowColumn style={{height: '28px'}}> <IconButton iconStyle={styles.smallIcon} style={styles.small} onTouchTap={_this.handleEdit.bind(_this, row)} > <ActionEdit /> </IconButton> <IconButton iconStyle={styles.smallIcon} style={styles.small} onTouchTap={_this.handleDelete.bind(_this, row)} > <DeleteEdit /> </IconButton> </TableRowColumn> </TableRow> )) } </TableBody> </Table> </div> ); } handleCreate() { var _this = this; this.showDialog({ title: '新建任务', type: TaskDetail.Create, callback: function() { _this.load(); _this.showSnack('任务创建成功'); } }); } handleEdit(item) { var _this = this; this.showDialog({ title: '修改任务', type: TaskDetail.Edit, props: { id: item.id }, callback: function() { _this.load(); _this.showSnack('任务更新成功'); } }); } handleDelete(item) { var _this = this; this.showAlert('操作提示', '确认是否要删除任务吗?', ['取消', '删除'], function(index){ if (index == 1) { request .delete(config.api_server + '/tasks/' + item.id) .set('Accept', 'application/json') .end(function (err, res) { if (err || res.body.ret) { _this.showAlert('错误提示', '删除任务失败', '知道了'); } else { _this.load(); _this.showSnack('任务删除成功'); } }); } }) } _load(cb) { request .get(config.api_server + '/tasks') .set('Accept', 'application/json') .end(function (err, res) { if (err) { cb(err); } else { cb(null, res.body); } }); } load(cb) { var _this = this; _this.showLoading(); this._load(function (err, data) { _this.hideLoading(); if (err) { _this.showAlert('提示', '加载任务列表失败', '重新加载', function() { setTimeout(function(){ _this.load(cb); }, 0); }); } else { _this.setState({ data: data.data }); } }); } }
blueocean-material-icons/src/js/components/svg-icons/maps/transfer-within-a-station.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsTransferWithinAStation = (props) => ( <SvgIcon {...props}> <path d="M16.49 15.5v-1.75L14 16.25l2.49 2.5V17H22v-1.5zm3.02 4.25H14v1.5h5.51V23L22 20.5 19.51 18zM9.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5.75 8.9L3 23h2.1l1.75-8L9 17v6h2v-7.55L8.95 13.4l.6-3C10.85 12 12.8 13 15 13v-2c-1.85 0-3.45-1-4.35-2.45l-.95-1.6C9.35 6.35 8.7 6 8 6c-.25 0-.5.05-.75.15L2 8.3V13h2V9.65l1.75-.75"/> </SvgIcon> ); MapsTransferWithinAStation.displayName = 'MapsTransferWithinAStation'; MapsTransferWithinAStation.muiName = 'SvgIcon'; export default MapsTransferWithinAStation;
src/routes.js
luigiplr/udormio-react
import React from 'react'; import { Router } from 'react-routing'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import LoginPage from './components/LoginPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/profile', async (state) => { console.log(state); //Here we can parse state.cookies & perform validation }); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
resources/assets/javascript/components/summaryList.js
colinjeanne/garden
import React from 'react'; import SummaryItem from './summaryItem'; const sum = items => items.reduce((current, item) => current + item, 0); const aggregateEvents = (events, plants) => events.reduce((aggregated, event) => { const aggregatedEvent = aggregated.find(element => element.plantName === event.plantName); if (aggregatedEvent) { ++aggregatedEvent.totalAmount; aggregatedEvent.harvested += sum(event.harvests); if (event.isDead) { ++aggregatedEvent.amountDead; } if (event.isDelayed) { ++aggregatedEvent.amountDelayed; } } else { const plant = plants.find(plant => plant.name === event.plantName); aggregated.push({ amountDead: event.isDead ? 1 : 0, amountDelayed: event.isDelayed ? 1 : 0, harvested: sum(event.harvests), totalAmount: 1, plantName: event.plantName, unit: plant.unit }); } return aggregated; }, []); const summaryList = props => { const aggregatedEvents = aggregateEvents( props.calendarEvents, props.plants); const calendarItems = aggregatedEvents.map( item => ( <SummaryItem {...item} key={item.plantName} /> ) ); return ( <ol className="plantSummaryList"> {calendarItems} </ol> ); }; summaryList.propTypes = { calendarEvents: React.PropTypes.array.isRequired, plants: React.PropTypes.arrayOf(React.PropTypes.object).isRequired }; export default summaryList;
client/components/Dashbord/recipeForm.js
kenware/more-recipes
import React, { Component } from 'react'; import { BrowserRouter, Route, Switch, Redirect, Link } from 'react-router-dom'; import { PropTypes } from 'react'; import * as actions from '../../redux/Action/action.js'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import RichTextEditor from 'react-rte'; import "./dashbord.scss"; import Dropzone from 'react-dropzone'; import FormData from 'form-data'; class RecipeForm extends Component { constructor(props){ super(props) this.state = { value: RichTextEditor.createEmptyValue(), file:[], title:"", val:"", ingredients:"", continue:false, show:"show", submit:'Submit', inform:false, message:'show' } this.onChange = this.onChange.bind(this); this.change = this.change.bind(this); this.onSubmit = this.onSubmit.bind(this); this.onCancel = this.onCancel.bind(this) } componentWillReceiveProps(newProps){ if((newProps.message.createRecipeSuccess || newProps.message.createRecipeError) && this.state.inform){ this.setState({submit:'Submit',message:''}) } } change(e){ const state = this.state; state[e.target.name] = e.target.value; this.setState(state); } onChange(value){ this.setState({value}); }; onDrop(file) { this.setState({file}) } onSubmit(e){ e.preventDefault(); this.setState({show:"show",inform:true}) const description = this.state.value.toString('html'); //this.setState({val:description}) const title = this.state.title; const ingredients = this.state.ingredients; const payload = new FormData(); let file = this.state.file if(file.length==0 && !this.state.continue){ this.setState({show:""}) this.setState({continue:true}) }else{ if(description.length <= 11){ this.setState({continue:false}) return this.setState({val:"this field is required"}) }else if(description.length <= 30){ this.setState({continue:false}) return this.setState({val:"Proper description of recipe greater than "+ description.length +" is required"}) } this.setState({submit:'Sending..'}) for(let x=0;x<file.length;x++){ payload.append('file',file[x]);} payload.append('title',title); payload.append('content',description) payload.append('ingredients',ingredients) this.props.actions.creatRecipe(payload); this.setState({continue:false}) } } onCancel(e){ this.setState({show:"show"}) this.setState({continue:false}) } render() { const {file}=this.state; return ( <div> <div className="col-sm-12"> <h3 className="text-center text-primary">Add a recipe</h3> <div className="card my-4 bg-add-recipe text-default"> <h5 className="card-header text-primary">Enter Recipe Details</h5> <div className="card-body"> <form onSubmit={this.onSubmit}> <fieldset className="form-group text-primary"> <label for="last_name">Recipe Tittle</label> <input type="text" className="form-control" onChange={this.change} id="tittle" name="title" placeholder="recipe name" required/> </fieldset> <fieldset className="form-group text-primary"> <label for="last_name">List important ingredients</label> <textarea cols="6" rows="8" className="form-control" onChange={this.change} id="ingredients" name="ingredients" required> </textarea> <div className="content emptyPhoto" id={this.state.show}> <div className="modal-header"> <h4 className="modal-title text-danger">warning</h4> <button type="button" onClick={ this.onCancel } className="close" data-dismiss="modal">&times;</button> </div> <div className="modal-body text-danger text-center"> You have not added uploaded any photo/image of a recipe. The photo below will be used as the photo of your recipe <img src={`upload/g.jpg`} className="rounded-circle img-default"/> </div> <div className="modal-footer"> <button className="delete btn btn-info" type="button" onClick={ this.onSubmit }><i className="fa fa-trash-o" aria-hidden="true"></i>&nbsp;Continue</button> <button type="button" onClick={ this.onCancel } className="btn btn-info" data-dismiss="modal">Cancel</button> </div> </div> </fieldset> <fieldset className="form-group" style={{background:"white"}}> <div className="row"> <div className="col text-primary" style={{marginLeft:"1rem"}}> <label for="image">Photo of recipe(Optional)</label> <Dropzone onDrop={this.onDrop.bind(this)} accept="image/jpeg,image/jpg,image/tiff,image/gif,image/png" ref="dropzone" multiple={false}> Drag and drop or click to select an image to upload. </Dropzone> </div> <div className="col"> {file.map(fil=><img src={fil.preview} className="img-fluid"/>)} </div> </div> </fieldset> <fieldset className="form-group text-primary"> <label for="message">Description</label> <font color="red"> {this.state.val} </font> <RichTextEditor value={this.state.value} onChange={this.onChange} /> </fieldset> <button type="submit" className="btn btn-warning">{this.state.submit}</button> <div className="alert alert-warning alert-dismissible" role="alert" id={this.state.message}> <button type="button" className="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong> <span><font color='red'> {this.props.message.createRecipeError}&nbsp; {this.props.message.createRecipeSuccess} </font> </span> </strong> </div> </form> </div> </div> </div> </div> ); } } function mapStateToProps(state, ownProps) { return{ message: state.message } } function mapDispatchToProps(dispatch) { return {actions: bindActionCreators(actions, dispatch)} } export default connect(mapStateToProps, mapDispatchToProps)(RecipeForm);
src/index.js
ibujs/decaffeinater
// @flow // Import React. import React from 'react' import { render } from 'react-dom' // Import components from material-ui :D import AppBar from 'material-ui/AppBar' import Toolbar from 'material-ui/Toolbar' import Typography from 'material-ui/Typography' import Paper from 'material-ui/Paper' // Import main App component. import App from './App' // Define the chat sheet contents. /* eslint-disable no-multi-str */ const cheatSheet1 = "Type in the name of the PROCESS in process name, not the name of the gam\ e. ps ax is your buddy, run this command to find all running processes. If you opened your game j\ ust now, it'll be the 3rd last or so." const cheatSheet2 = '1 hour = 60 minutes and 1 minute = 60 seconds. You can use both fields a\ t once and the values will be converted and added.' /* eslint-enable no-multi-str */ // Define our style sheet. const indexComponentCSS = { appBar: { position: 'relative', marginBottom: 10, background: '#00796B' }, paper: { marginTop: 10 }, cheatSheetStyle: { marginLeft: 10, marginRight: 10 }, cheatSheetStyle2: { margin: 10 } } // Define main component. const Index = () => ( <div> <AppBar style={indexComponentCSS.appBar}> <Toolbar> <Typography type='title'> Decaffeinater - For those who spend too much time on apps :3 </Typography> </Toolbar> </AppBar> <App /> <Paper elevation={8} style={indexComponentCSS.paper}> <br /> <Typography type='headline' component='h3' align='center' style={indexComponentCSS.cheatSheetStyle}>Cheat sheet!</Typography> <Typography type='body1' component='p' style={indexComponentCSS.cheatSheetStyle2}>{cheatSheet1}</Typography> <Typography type='body1' component='p' style={indexComponentCSS.cheatSheetStyle}>{cheatSheet2}</Typography> <br /> </Paper> </div> ) render(<Index />, document.getElementById('root'))
src/forms/form.js
ikanedo/react-redux-simple-validate
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import * as FormActions from './formActions'; import FormGroup from './formGroup'; class FormDefault extends Component { /* istanbul ignore next */ constructor() { super(); this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); const { triggerValidate, formName } = this.props; triggerValidate(formName); } render() { const { children, className, ...otherProps } = this.props; return ( <form onSubmit={this.onSubmit} className={className} noValidate> <FormGroup {...otherProps}>{children}</FormGroup> </form> ); } } FormDefault.propTypes = { className: PropTypes.string, formName: PropTypes.string.isRequired, children: PropTypes.node.isRequired, triggerValidate: PropTypes.func.isRequired }; export default connect(null, FormActions)(FormDefault);
src/components/Footer/VkIcon.js
Galernaya20/galernaya20.com
//@flow import React from 'react' import {Svg} from '../Svg/Svg' export const VkIcon = (props: Object) => ( <Svg {...props}> <path d="M41,4H9C6.24,4,4,6.24,4,9v32c0,2.76,2.24,5,5,5h32c2.76,0,5-2.24,5-5V9C46,6.24,43.76,4,41,4z M37.72,33l-3.73-0.01 c0,0-0.08,0.01-0.21,0.01c-0.3,0-0.92-0.08-1.65-0.58c-1.31-0.91-2.56-3.17-3.55-3.17c-0.07,0-0.13,0.01-0.19,0.03 c-0.86,0.27-1.12,1.13-1.12,2.18c0,0.37-0.26,0.54-0.96,0.54h-1.93c-2.16,0-4.25-0.05-6.6-2.62c-3.46-3.79-6.7-10.53-6.7-10.53 s-0.18-0.39,0.01-0.62c0.18-0.21,0.6-0.23,0.76-0.23c0.04,0,0.06,0,0.06,0h4c0,0,0.37,0.07,0.64,0.27c0.23,0.17,0.35,0.48,0.35,0.48 s0.68,1.32,1.53,2.81c1.43,2.46,2.2,3.28,2.75,3.28c0.09,0,0.18-0.02,0.27-0.07c0.82-0.45,0.58-4.09,0.58-4.09s0.01-1.32-0.42-1.9 c-0.33-0.46-0.96-0.59-1.24-0.63c-0.22-0.03,0.14-0.55,0.62-0.79c0.62-0.3,1.65-0.36,2.89-0.36h0.6c1.17,0.02,1.2,0.14,1.66,0.25 c1.38,0.33,0.91,1.62,0.91,4.71c0,0.99-0.18,2.38,0.53,2.85c0.05,0.03,0.12,0.05,0.21,0.05c0.46,0,1.45-0.59,3.03-3.26 c0.88-1.52,1.56-3.03,1.56-3.03s0.15-0.27,0.38-0.41c0.22-0.13,0.22-0.13,0.51-0.13h0.03c0.32,0,3.5-0.03,4.2-0.03h0.08 c0.67,0,1.28,0.01,1.39,0.42c0.16,0.62-0.49,1.73-2.2,4.03c-2.82,3.77-3.14,3.49-0.8,5.67c2.24,2.08,2.7,3.09,2.78,3.22 C39.68,32.88,37.72,33,37.72,33z" /> </Svg> )
App/Components/GoogleMap.js
OUCHUNYU/Ralli
import React, { Component } from 'react'; import Button from './Common/button' import GroupsPage from './GroupsPage' import UserProfilePage from './UserProfilePage' import GroupsInvitePage from './GroupsInvitePage' import EventFeed from './EventFeed' import CreateMarker from './CreateMarker' import markersApi from '../Utils/markersApi' import messagesApi from '../Utils/messagesApi' import Firebase from 'firebase' import QuestionBox from './QuestionBox' import MapView from 'react-native-maps' import CustomCallout from './CustomCallout' import { StyleSheet, PropTypes, View, Text, Dimensions, TouchableOpacity, NavigatorIOS, AlertIOS, Image, TouchableHighlight, LinkingIOS, Animated } from 'react-native'; var { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class GoogleMap extends Component { componentWillMount(){ this.markerRef.on("value", function(res) { var allMarkers = []; for(var i in res.val()) { allMarkers.push(res.val()[i]) } this.setState({ markers: allMarkers }) this.render() }.bind(this)) } constructor(props) { super(props); this.markerRef = new Firebase('https://ralli.firebaseio.com/markers'); this.state = { bounceValue: new Animated.Value(0), region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, markers: ["placeholder"] }; } onMarkerPress() {} onPressGroups() { this.props.navigator.push ({ title: 'Groups Page', component: GroupsPage, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressProfile() { this.props.navigator.push ({ title: 'Profile Page', component: UserProfilePage, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressFeed() { this.props.navigator.push ({ title: 'Feed', component: EventFeed, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressCreateMarker () { this.props.navigator.push ({ title: 'Make a Rally', component: CreateMarker, passProps: { userId: this.props.userId, userData: this.props.userData } }) } onPressSurprise() { // function to get a a random number between range because js if (this.props.userData.markers) { function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // need latest array of user markers (realtime) let len = this.props.userData.markers.length let eventIndex = getRandomIntInclusive(0, len) let randEventId = this.props.userData.markers[eventIndex] new Firebase('https://ralli.firebaseio.com/markers/' + randEventId) .once("value") .then((res) => this.props.navigator.push ({ title: 'Surprise', component: QuestionBox, passProps: { userId: this.props.userId, userData: this.props.userData, eventInfo: res.val() } }) ) } else { AlertIOS.alert( 'Sorry ' + this.props.userData.username, "Looks like you've not been invited to any events." ) } } iAmGoingButton(item) { let eventOwnerId = item.creator; let message = this.props.userData.username + " is going to your event: " + item.title messagesApi.individualUserMessenger(eventOwnerId, message) } onRegionChange(region) { this.state.region = region; } onLikeButton() { this.state.bounceValue.setValue(1.5); Animated.spring( this.state.bounceValue, { toValue: 0.8, friction: 1, } ).start(); } markerCenter() { } render() { const { region, markers } = this.state; let markersList = this.state.markers.map((item, index) => { return ( <MapView.Marker ref="m3" key={index} image={this.state.iconLoaded ? 'markerLoaded' : 'marker'} showsUserLocation={true} followUserLocation={true} coordinate={markers[index].coordinate} calloutAnchor={{ x: 0.1, y: 0.1 }} calloutOffset={{ x: -8, y: 29 }} > <Image source={require('./Common/other-small-icon.png')} onLoadEnd={() => {if (!this.state.iconLoaded) this.setState({iconLoaded: true});}}/> <MapView.Callout tooltip> <TouchableOpacity onPress={this.markerCenter.bind(this)}> <CustomCallout style={styles.calloutOpacity}> <View style={styles.wrapper}> <Text style={styles.calloutHeader}>{markers[index].title}</Text> </View> <Text style={styles.calloutText}> {markers[index].address}</Text> <Text style={styles.calloutText}> {markers[index].description}</Text> <Text style={styles.calloutText}> {markers[index].timeStart}</Text> <Text style={styles.calloutText}> Group: {markers[index].groups}</Text> <Image style={styles.calloutImage} source={require('./Common/sbpete.png')}/> <Button onPress={this.iAmGoingButton.bind(this, item)} text="I'm Going"></Button> </CustomCallout> </TouchableOpacity> </MapView.Callout> </MapView.Marker> ) }); return ( <View style={styles.container}> <MapView style={styles.map} initialRegion={region} showsUserLocation={true} followUserLocation={true}> {markersList} </MapView> <View style={styles.buttonContainer}> <TouchableOpacity onPress={this.onPressGroups.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/usergroup.png')} style={styles.icongood} /> </TouchableOpacity> <TouchableOpacity onPress={this.onPressProfile.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/profile.png')} style={styles.icon}/> </TouchableOpacity> <TouchableOpacity onPress={this.onPressCreateMarker.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/Untitled.png')} style={styles.middleicon}/> </TouchableOpacity> <TouchableOpacity onPress={this.onPressFeed.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/activityfeed.png')} style={styles.icon} /> </TouchableOpacity> <TouchableOpacity onPress={this.onPressSurprise.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/question.png')} style={styles.icon} /> </TouchableOpacity> </View> </View> ); } } let styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', }, map: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'red', }, bubble: { flex: 1, backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, }, latlng: { width: 200, alignItems: 'stretch', }, button: { height: height * .08, width: width * .20, alignItems: 'center', justifyContent: 'center' }, buttonContainer: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'flex-end', backgroundColor: 'transparent', }, calloutHeader: { fontSize: 24, color: '#fff', marginBottom: 5, flex: 1 }, calloutText: { color: '#fff', flex: 1 }, calloutOpacity: { borderRadius: 8, opacity: .8 }, icon: { height: 25, width: 25, }, icongood: { height: 32, width: 32, }, middleicon: { height: 33, width: 33 }, calloutImage: { height: height * .15, width: width * .25, alignSelf: 'center', marginTop: 5, borderRadius: 3, borderWidth: 1, }, wrapper: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, likebutton: { marginTop: -10, flex: 1, height: 32, width: 22 } }); GoogleMap.propTypes = { userData: React.PropTypes.object.isRequired, userId: React.PropTypes.string.isRequired }; export default GoogleMap
Rosa_Madeira/Revendedor/src/components/notificacoes/NotificacoesDetalhes.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, Text, Image, Linking } from 'react-native'; import { Icon, Button } from 'native-base'; import { Card, CardSection, ButtonForm } from '../common'; import { Actions } from 'react-native-router-flux'; import axios from 'axios'; class NotificacoesDetalhes extends Component { renderContent(){ const { headerContentStyle, thumbnailStyle, thumbnailContentStyle, titleStyle, imageStyle, iconStyle, containerStyle } = styles; } render(){ return( <View> {this.renderContent()} </View> ); } } const styles = { headerContentStyle: { flexDirection: 'column', justifyContent: 'space-around', flex: 1 }, titleStyle: { fontSize: 18, marginBottom: 5 }, thumbnailStyle: { height: 50, width: 50 }, thumbnailContentStyle:{ justifyContent: 'center', alignItems:'center', marginLeft: 10, marginRight: 10 }, imageStyle:{ height: 300, flex: 1, width: null }, iconStyle: { fontSize: 50, color: '#737373' }, containerStyle:{ borderBottomWidth: 1, padding: 5, backgroundColor: "#f2f2f2", justifyContent: 'flex-start', flexDirection: 'row', borderColor: '#cccccc', position: 'relative' } } export default NotificacoesDetalhes;
src/styles/theme-decorator.js
Zadielerick/material-ui
import React from 'react'; export default (customTheme) => { return function(Component) { return React.createClass({ childContextTypes: { muiTheme: React.PropTypes.object, }, getChildContext() { return { muiTheme: customTheme, }; }, render() { return React.createElement(Component, this.props); }, }); }; };
src/components/WelcomeNote.js
jpkbeddu/keep-app
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { margin: 20, padding: '40px 20px', textAlign: 'center' }; const WelcomeNote = () => ( <div> <Paper style={style} zDepth={1} rounded={false}> <h2>Welcome to Keep App</h2> <p> This is a Google Keep clone app build using {' '} <code>create-react-app</code> . </p> </Paper> </div> ); export default WelcomeNote;
ee/client/omnichannel/BusinessHoursTable.stories.js
iiet/iiet-chat
import React from 'react'; import { Box } from '@rocket.chat/fuselage'; import { BusinessHoursTable } from './BusinessHoursTable'; export default { title: 'omnichannel/businessHours/ee/BusinessHoursTable', component: BusinessHoursTable, }; const businessHours = [ { name: '', timezone: { name: 'America/Sao_Paulo' }, workHours: [ { day: 'Monday', open: true }, { day: 'Tuesday', open: true }, { day: 'Wednesday', open: true }, { day: 'Saturday', open: true }, ], }, { name: 'Extra', timezone: { name: 'America/Sao_Paulo' }, workHours: [ { day: 'Monday', open: true }, { day: 'Tuesday', open: true }, { day: 'Saturday', open: true }, ], }, { name: 'Extra2', timezone: { name: 'America/Sao_Paulo' }, workHours: [ { day: 'Saturday', open: true }, { day: 'Sunday', open: true }, { day: 'Monday', open: false }, ], }, { name: 'Extra3', timezone: { name: 'America/Sao_Paulo' }, workHours: [ { day: 'Monday', open: true }, { day: 'Saturday', open: true }, ], }, ]; export const Default = () => <Box maxWidth='x600' alignSelf='center' w='full' m='x24'> <BusinessHoursTable businessHours={businessHours} businessHoursTotal={businessHours.length} params={{}} onChangeParams={() => {}}/> </Box>;
docs/src/pages/demos/tabs/IconLabelTabs.js
cherniavskii/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; import Tabs, { Tab } from 'material-ui/Tabs'; import PhoneIcon from '@material-ui/icons/Phone'; import FavoriteIcon from '@material-ui/icons/Favorite'; import PersonPinIcon from '@material-ui/icons/PersonPin'; export default class IconLabelTabs extends React.Component { state = { value: 0, }; handleChange = (event, value) => { this.setState({ value }); }; render() { return ( <Paper style={{ width: 500 }}> <Tabs value={this.state.value} onChange={this.handleChange} fullWidth indicatorColor="secondary" textColor="secondary" > <Tab icon={<PhoneIcon />} label="RECENTS" /> <Tab icon={<FavoriteIcon />} label="FAVORITES" /> <Tab icon={<PersonPinIcon />} label="NEARBY" /> </Tabs> </Paper> ); } }
public/js/components/profile/visitor/MockChat.react.js
MadushikaPerera/Coupley
import React from 'react'; import Avatar from 'material-ui/lib/avatar'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import CommunicationChatBubble from 'material-ui/lib/svg-icons/communication/chat-bubble'; const ChatData = [{ "name": "Rajika Imal", "uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png" },{ "name": "Stephanie Hwang", "uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png" },{ "name": "Anne Hathway", "uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png" }] const ChatData_2 = [{ "name": "Rajika Imal", "uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png" },{ "name": "Stephanie Hwang", "uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png" }] const MockChat = React.createClass({ _renderPrevList: function() { return ChatData_2.map((chatitem) => { return ( <div> <ListItem primaryText={chatitem.name} leftAvatar={<Avatar src={chatitem.uri} />} rightIcon={<CommunicationChatBubble />} /> <Divider /> </div> ); }); }, _renderChatList: function() { return ChatData.map((chatitem) => { return ( <div> <ListItem primaryText={chatitem.name} leftAvatar={<Avatar src={chatitem.uri} />} rightIcon={<CommunicationChatBubble />} /> <Divider /> </div> ); }); }, render: function() { return ( <div> <List subheader="Recent chats"> {this._renderChatList()} </List> <List subheader="Previous chats"> {this._renderPrevList()} </List> </div> ); } }); export default MockChat;
packages/@lyra/state-router/demo-server/entry.js
VegaPublish/vega-studio
// @flow import React from 'react' import ReactDOM from 'react-dom' import Main from './components/Main' import route from '../src/route' import RouterProvider from '../src/components/RouterProvider' import createHistory from 'history/createBrowserHistory' import NotFound from './components/NotFound' import type {Router} from '../src/types' const router: Router = route('/omg/lol', [ route.scope('product', '/products/:id', [ route('/:detailView'), route('/user/:userId') ]), route('/users/:userId', params => { if (params.userId === 'me') { return route('/:profileSection') } }), route.intents('/intents2') ]) const history = createHistory() function handleNavigate(nextUrl, {replace} = {}) { if (replace) { history.replace(nextUrl) } else { history.push(nextUrl) } } function render(state, pathname) { ReactDOM.render( <div> <RouterProvider router={router} onNavigate={handleNavigate} state={state}> {router.isNotFound(pathname) ? ( <NotFound pathname={pathname} /> ) : ( <Main /> )} </RouterProvider> <div> <h2>Components outside provider context</h2> <Main /> </div> </div>, document.getElementById('main') ) } if (router.isRoot(location.pathname)) { const basePath = router.getBasePath() if (basePath !== location.pathname) { history.replace(basePath) } } const intentHandlers = [] intentHandlers.push({ canHandle: (intent, params) => intent === 'open' && params.type === 'product', resolveRedirectState(intent, params) { return {product: {id: params.id}} } }) function checkPath() { const pathname = document.location.pathname const state = router.decode(pathname) if (state && state.intent) { // get intent redirect url const handler = intentHandlers.find(candidate => candidate.canHandle(state.intent, state.params) ) if (handler) { handleNavigate( router.encode(handler.resolveRedirectState(state.intent, state.params)), { replace: true } ) return } // eslint-disable-next-line no-console console.log( 'No intent handler for intent "%s" with params %o', state.intent, state.params ) } render(state || {}, pathname) } checkPath() history.listen(checkPath)
src/index.js
eduarmreyes/ReactWeatherApp
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from "redux-promise"; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
internals/templates/containers/NotFoundPage/index.js
mattmanske/nnsb-admin
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a 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 NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/index.js
adithengky/react2602
import _ from 'lodash'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import SearchBar from './components/search_bar'; import YTSearch from 'youtube-api-search'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; const API_KEY = 'AIzaSyDi341XZPKzKunq9E_uFPOYNCWzY_cizmI'; class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('isyana sarasvati') } videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => {this.videoSearch(term)}, 300); return( <div> <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo}/> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo})} videos={this.state.videos} /> </div> ); } } ReactDOM.render(<App/>, document.querySelector('.container'));
app/javascript/mastodon/features/directory/index.js
imas/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from 'mastodon/components/column'; import ColumnHeader from 'mastodon/components/column_header'; import { addColumn, removeColumn, moveColumn, changeColumnParams } from 'mastodon/actions/columns'; import { fetchDirectory, expandDirectory } from 'mastodon/actions/directory'; import { List as ImmutableList } from 'immutable'; import AccountCard from './components/account_card'; import RadioButton from 'mastodon/components/radio_button'; import classNames from 'classnames'; import LoadMore from 'mastodon/components/load_more'; import { ScrollContainer } from 'react-router-scroll-4'; const messages = defineMessages({ title: { id: 'column.directory', defaultMessage: 'Browse profiles' }, recentlyActive: { id: 'directory.recently_active', defaultMessage: 'Recently active' }, newArrivals: { id: 'directory.new_arrivals', defaultMessage: 'New arrivals' }, local: { id: 'directory.local', defaultMessage: 'From {domain} only' }, federated: { id: 'directory.federated', defaultMessage: 'From known fediverse' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'directory', 'items'], ImmutableList()), isLoading: state.getIn(['user_lists', 'directory', 'isLoading'], true), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class Directory extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, columnId: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, domain: PropTypes.string.isRequired, params: PropTypes.shape({ order: PropTypes.string, local: PropTypes.bool, }), }; state = { order: null, local: null, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('DIRECTORY', this.getParams(this.props, this.state))); } } getParams = (props, state) => ({ order: state.order === null ? (props.params.order || 'active') : state.order, local: state.local === null ? (props.params.local || false) : state.local, }); handleMove = dir => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch } = this.props; dispatch(fetchDirectory(this.getParams(this.props, this.state))); } componentDidUpdate (prevProps, prevState) { const { dispatch } = this.props; const paramsOld = this.getParams(prevProps, prevState); const paramsNew = this.getParams(this.props, this.state); if (paramsOld.order !== paramsNew.order || paramsOld.local !== paramsNew.local) { dispatch(fetchDirectory(paramsNew)); } } setRef = c => { this.column = c; } handleChangeOrder = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['order'], e.target.value)); } else { this.setState({ order: e.target.value }); } } handleChangeLocal = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['local'], e.target.value === '1')); } else { this.setState({ local: e.target.value === '1' }); } } handleLoadMore = () => { const { dispatch } = this.props; dispatch(expandDirectory(this.getParams(this.props, this.state))); } render () { const { isLoading, accountIds, intl, columnId, multiColumn, domain, shouldUpdateScroll } = this.props; const { order, local } = this.getParams(this.props, this.state); const pinned = !!columnId; const scrollableArea = ( <div className='scrollable' style={{ background: 'transparent' }}> <div className='filter-form'> <div className='filter-form__column' role='group'> <RadioButton name='order' value='active' label={intl.formatMessage(messages.recentlyActive)} checked={order === 'active'} onChange={this.handleChangeOrder} /> <RadioButton name='order' value='new' label={intl.formatMessage(messages.newArrivals)} checked={order === 'new'} onChange={this.handleChangeOrder} /> </div> <div className='filter-form__column' role='group'> <RadioButton name='local' value='1' label={intl.formatMessage(messages.local, { domain })} checked={local} onChange={this.handleChangeLocal} /> <RadioButton name='local' value='0' label={intl.formatMessage(messages.federated)} checked={!local} onChange={this.handleChangeLocal} /> </div> </div> <div className={classNames('directory__list', { loading: isLoading })}> {accountIds.map(accountId => <AccountCard id={accountId} key={accountId} />)} </div> <LoadMore onClick={this.handleLoadMore} visible={!isLoading} /> </div> ); return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='address-book-o' title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} /> {multiColumn && !pinned ? <ScrollContainer scrollKey='directory' shouldUpdateScroll={shouldUpdateScroll}>{scrollableArea}</ScrollContainer> : scrollableArea} </Column> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
ConnectedHomes/create-react-web-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-and-default"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
src/components/BookingForm/Name.js
humancatfood/bat-fe-test
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import MenuItem from '@material-ui/core/MenuItem'; const useStyles = makeStyles(theme => ({ select: { marginLeft: 0, minWidth: 60, }, textField: { marginLeft: theme.spacing(1), flexGrow: 1, }, })); function Name ({ booking = {}, onChange: onChangeProp /* loading, errors */ }) { const { title, firstName, lastName } = booking; const onChange = e => onChangeProp(e.target.name, e.target.value); const classes = useStyles(); return ( <> <TextField select value={title} onChange={onChange} name="title" label=" " className={classes.select} > { ['Mr', 'Mrs', 'Miss', 'Ms', 'Dr'].map(addr => ( <MenuItem key={ addr } value={ addr }>{ addr }</MenuItem> )) } </TextField> <TextField name="firstName" value={firstName} onChange={onChange} label="First Name" maxLength={20} className={classes.textField} required /> <TextField name="lastName" value={ lastName } onChange={ onChange } label="Last Name" maxLength={20} className={classes.textField} required /> </> ); } Name.propTypes = { booking: PropTypes.shape({ // TODO: share this somewhere title: PropTypes.string, firstName: PropTypes.string, lastName: PropTypes.string, time: PropTypes.string, partySize: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), status: PropTypes.string, notes: PropTypes.string, }), onChange: PropTypes.func.isRequired, loading: PropTypes.bool, errors: PropTypes.array, //TODO: define error-shape }; export default Name;
src/component/Header.js
chengfh11/react
import React, { Component } from 'react'; import logo from '../logo.svg'; export default class Header extends React.Component { render() { return <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to Cappuccino</h2> </div>; } }
client/components/ui/external-link.js
ZeHiro/kresus
import React from 'react'; export default props => ( <a href={props.href} rel="noopener noreferrer" target="_blank"> {props.children} </a> );
entry_types/scrolled/package/src/frontend/Widget.js
tf/pageflow
import React from 'react'; import {api} from './api'; import {useWidget} from '../entryState'; export function Widget({role}) { const widget = useWidget({role}); if (!widget) { return null; } const Component = api.widgetTypes.getComponent(widget.typeName); return ( <Component configuration={widget.configuration} /> ); }
app/components/Counter.js
aaronjameslang/nhshd17
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Counter.css'; import {ipcRenderer} from 'electron'; class Counter extends Component { props: { increment: () => void, incrementIfOdd: () => void, incrementAsync: () => void, decrement: () => void, counter: number }; constructor(props) { super(props) this.state = { filepath: '/tmp/followapp', record: 'Enter patient record here', records: '' } ipcRenderer.on('all-records', (event, records) => { this.setState({records: records}) }) } handleChange(name, event) { const state = {} state[name] = event.target.value this.setState(state); } createRecord() { ipcRenderer.send('create-record', this.state.filepath, this.state.record) } render() { const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props; return ( <div> <div className={styles.backButton}> <Link to="/"> <i className="fa fa-arrow-left fa-3x" /> </Link> </div> <div className={`counter ${styles.counter}`}> TEST {counter} </div> <div className={styles.btnGroup}> <button className={styles.btn} onClick={increment}> <i className="fa fa-plus" /> </button> <button className={styles.btn} onClick={decrement}> <i className="fa fa-minus" /> </button> <button className={styles.btn} onClick={incrementIfOdd}>odd</button> <button className={styles.btn} onClick={() => incrementAsync()}>async</button> </div> <form> <textarea value={this.state.records}/><br/> <input type="text" value={this.state.filepath} onChange={this.handleChange.bind(this, 'filepath')}/><br/> <input type="text" value={this.state.record} onChange={this.handleChange.bind(this, 'record' )}/><br/> <button onClick={() => this.createRecord()}>Create Record</button><br/> </form> </div> ); } } export default Counter;
app/ShotList.js
future-challenger/react-native-dribbble-app
//@flow import React from 'react'; import { ActivityIndicatorIOS, ListView, StyleSheet, Text, TextInput, View, } from 'react-native'; import * as api from "./helpers/api"; import ShotCell from "./ShotCell"; import ShotDetails from "./ShotDetails"; import Loading from "./Loading"; // Results should be cached keyed by the query // with values of null meaning "being fetched" // and anything besides null and undefined // as the result of a valid query var resultsCache = { dataForQuery: [], nextPageNumberForQuery: [], totalForQuery: [], }; let LOADING = {}; export default class ShotList extends React.Component { constructor(props) { super(props); this.state = { isLoading: false, isLoadingTail: false, dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), filter: this.props.filter, queryNumber: 0, }; // bind this.getShots = this.getShots.bind(this); this.hasMore = this.hasMore.bind(this); this.onEndReached = this.onEndReached.bind(this); this.getDataSource = this.getDataSource.bind(this); this.selectShot = this.selectShot.bind(this); this.renderFooter = this.renderFooter.bind(this); this.renderRow = this.renderRow.bind(this); } componentWillMount() { this.getShots(this.state.filter); } getShots(query: string) { var cachedResultsForQuery = resultsCache.dataForQuery[query]; if (cachedResultsForQuery) { if (!LOADING[query]) { this.setState({ dataSource: this.getDataSource(cachedResultsForQuery), isLoading: false }); } else { this.setState({isLoading: true}); } return; } LOADING[query] = true; resultsCache.dataForQuery[query] = null; this.setState({ isLoading: true, queryNumber: this.state.queryNumber + 1, isLoadingTail: false, }); api.getShotsByType(query, 1) .catch((error) => { LOADING[query] = false; resultsCache.dataForQuery[query] = undefined; this.setState({ dataSource: this.getDataSource([]), isLoading: false, }); }).then((responseData) => { LOADING[query] = false; resultsCache.dataForQuery[query] = responseData; resultsCache.nextPageNumberForQuery[query] = 2; this.setState({ isLoading: false, dataSource: this.getDataSource(responseData), }); }) .done(); } hasMore(): boolean { var query = this.state.filter; if (!resultsCache.dataForQuery[query]) { return true; } return ( resultsCache.totalForQuery[query] !== resultsCache.dataForQuery[query].length ); } onEndReached() { var query = this.state.filter; if (!this.hasMore() || this.state.isLoadingTail) { // We"re already fetching or have all the elements so noop return; } if (LOADING[query]) { return; } LOADING[query] = true; this.setState({ queryNumber: this.state.queryNumber + 1, isLoadingTail: true, }); var page = resultsCache.nextPageNumberForQuery[query]; api.getShotsByType(query, page) .catch((error) => { LOADING[query] = false; this.setState({ isLoadingTail: false, }); }) .then((responseData) => { var shotsForQuery = resultsCache.dataForQuery[query].slice(); LOADING[query] = false; // We reached the end of the list before the expected number of results if (!responseData) { resultsCache.totalForQuery[query] = shotsForQuery.length; } else { for (var i in responseData) { shotsForQuery.push(responseData[i]); } resultsCache.dataForQuery[query] = shotsForQuery; resultsCache.nextPageNumberForQuery[query] += 1; } this.setState({ isLoadingTail: false, dataSource: this.getDataSource(resultsCache.dataForQuery[query]), }); }) .done(); } getDataSource(shots: Array<any>): ListView.DataSource { return this.state.dataSource.cloneWithRows(shots); } selectShot(shot: Object) { this.props.navigator.push({ component: ShotDetails, passProps: {shot}, title: shot.title }); } renderFooter() { return <View style={styles.scrollSpinner}> <Loading /> </View>; } renderRow(shot: Object) { return ( <ShotCell onSelect={() => this.selectShot(shot)} shot={shot} /> ); } render() { var content = this.state.dataSource.getRowCount() === 0 ? <Loading/> : <ListView ref="listview" dataSource={this.state.dataSource} renderFooter={this.renderFooter} renderRow={this.renderRow} onEndReached={this.onEndReached} automaticallyAdjustContentInsets={false} keyboardDismissMode="on-drag" keyboardShouldPersistTaps={true} showsVerticalScrollIndicator={false} />; return ( <View style={styles.container}> <View style={styles.separator} /> {content} </View> ); } }; ShotList.defaultProps = { filter: "" }; ShotList.propTypes = { filter: React.PropTypes.string.isRequired }; var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "white", flexDirection: "column", justifyContent: "center" }, separator: { height: 1, backgroundColor: "#eeeeee", }, scrollSpinner: { marginVertical: 20, }, });
client/src/components/nav/NavNoAuth.js
kevinladkins/newsfeed
import React from 'react' import {NavLink} from 'react-router-dom' const NavNoAuth = () => <nav className="navbar"> <NavLink className="navlink" to="/" >Login</NavLink> <NavLink className="navlink" to="/signup" >Sign Up</NavLink> </nav> export default NavNoAuth
app/containers/AcquisitionPage/form.cc.js
rvsiqueira/client
import React from 'react'; import { reduxForm, Field } from 'redux-form/immutable'; import RenderField from 'components/RenderField'; import validate from './validate'; import FormFooter from 'components/FormFooter'; import messages from './messages'; import { FormattedMessage } from 'react-intl'; import P from 'components/P'; import payment from '../../assets/icon/payment.svg'; import Header from 'components/Header'; import Body from 'components/Body'; const formatCard = value => { if (value) { let formattedNumber = value; const num = value.replace(/\D*/g, ''); if (num.length > 4) { formattedNumber = splice(4, num, ' '); if (num.length > 8) { formattedNumber = splice(9, formattedNumber, ' '); if (num.length > 12) { formattedNumber = splice(14, formattedNumber, ' '); } } } else { formattedNumber = num; } return formattedNumber; } return ''; }; const formatValid = value => { if (value) { let formattedNumber = value; const num = value.replace(/\D*/g, ''); if (num.length > 2) { formattedNumber = splice(2, num, '/'); } else { formattedNumber = num; } return formattedNumber; } return ''; }; const splice = (pos, mainStr, appendStr) => mainStr.slice(0, pos) + appendStr + mainStr.slice(pos); const Cc = (props) => { const { handleSubmit, submitting, valid } = props; return ( <Body relaxed offsetExtra offsetBottom> <Header title={<FormattedMessage {...messages.group3} />} back={props.previousPage} /> <form onSubmit={handleSubmit}> <img src={payment} alt="payment" /> <P className="body1"> <FormattedMessage {...messages.ccPrimaryHeadingMessage} /> </P> <Field name="cardNumber" type="text" maxLength={19} component={RenderField} placeholder="1111 2222 3333 4444" format={formatCard} label={messages.ccCardHeadingMessage} /> <Field name="nameOnCard" type="text" component={RenderField} placeholder="Nome do Cartão" label={messages.ccCardNameOnCardMessage} /> <Field name="cardValidity" type="text" maxLength={5} component={RenderField} placeholder="MM/YY" format={formatValid} label={messages.ccValidHeadingMessage} /> <Field name="cvv" type="text" maxLength={4} component={RenderField} placeholder="000" format={value => (value ? value.replace(/\D*/g, '') : '')} label={messages.ccCvvHeadingMessage} /> <FormFooter disabled={submitting || !valid} /> </form> </Body> ); }; Cc.propTypes = { handleSubmit: React.PropTypes.func, previousPage: React.PropTypes.func, submitting: React.PropTypes.bool, valid: React.PropTypes.bool, }; export default reduxForm({ form: 'wizard', destroyOnUnmount: false, validate, })(Cc);
gatsby-strapi-tutorial/cms/plugins/users-permissions/admin/src/components/Policies/index.js
strapi/strapi-examples
/** * * Policies * */ import React from 'react'; import cn from 'classnames'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { get, isEmpty, map, takeRight, toLower, without } from 'lodash'; import Input from 'components/InputsIndex'; import BoundRoute from '../BoundRoute'; import styles from './styles.scss'; class Policies extends React.Component { // eslint-disable-line react/prefer-stateless-function handleChange = (e) => this.context.onChange(e); render() { const baseTitle = 'users-permissions.Policies.header'; const title = this.props.shouldDisplayPoliciesHint ? 'hint' : 'title'; const value = get(this.props.values, this.props.inputSelectName); const path = without(this.props.inputSelectName.split('.'), 'permissions', 'controllers', 'policy'); const controllerRoutes = get(this.props.routes, without(this.props.inputSelectName.split('.'), 'permissions', 'controllers', 'policy')[0]); const routes = isEmpty(controllerRoutes) ? [] : controllerRoutes.filter(o => toLower(o.handler) === toLower(takeRight(path, 2).join('.'))); return ( <div className={cn('col-md-5',styles.policies)}> <div className="container-fluid"> <div className={cn('row', styles.inputWrapper)}> <div className={cn('col-md-12', styles.header)}> <FormattedMessage id={`${baseTitle}.${title}`} /> </div> {!this.props.shouldDisplayPoliciesHint ? ( <Input customBootstrapClass="col-md-12" label={{ id: 'users-permissions.Policies.InputSelect.label' }} name={this.props.inputSelectName} onChange={this.handleChange} selectOptions={this.props.selectOptions} type="select" validations={{}} value={value} /> ) : ''} </div> <div className="row"> {!this.props.shouldDisplayPoliciesHint ? ( map(routes, (route, key) => <BoundRoute key={key} route={route} />) ) : ''} </div> </div> </div> ); } } Policies.contextTypes = { onChange: PropTypes.func.isRequired, }; Policies.defaultProps = { routes: {}, }; Policies.propTypes = { inputSelectName: PropTypes.string.isRequired, routes: PropTypes.object, selectOptions: PropTypes.array.isRequired, shouldDisplayPoliciesHint: PropTypes.bool.isRequired, values: PropTypes.object.isRequired, }; export default Policies;
webapp-src/src/Login/scheme/MockSchemeForm.js
babelouest/glewlwyd
import React, { Component } from 'react'; import i18next from 'i18next'; import apiManager from '../../lib/APIManager'; import messageDispatcher from '../../lib/MessageDispatcher'; class MockSchemeForm extends Component { constructor(props) { super(props); this.state = { config: props.config, scheme: props.scheme, identify: props.identify, identifyUsername: "", currentUser: props.currentUser, triggerResult: false, mockValue: "" }; this.triggerScheme = this.triggerScheme.bind(this); this.validateMockValue = this.validateMockValue.bind(this); this.handleChangeMockValue = this.handleChangeMockValue.bind(this); this.handleChangeIdentifyUsernameValue = this.handleChangeIdentifyUsernameValue.bind(this); this.triggerScheme(); } componentWillReceiveProps(nextProps) { this.setState({ config: nextProps.config, scheme: nextProps.scheme, identify: nextProps.identify, identifyUsername: "", currentUser: nextProps.currentUser, triggerResult: false, mockValue: "" }, () => { this.triggerScheme(); }); } triggerScheme() { if (this.state.scheme) { if (this.state.currentUser.username) { var scheme = { scheme_type: this.state.scheme.scheme_type, scheme_name: this.state.scheme.scheme_name, username: this.state.currentUser.username, value: { description: "This is a mock trigger" } }; } else { var scheme = { scheme_type: this.state.scheme.scheme_type, scheme_name: this.state.scheme.scheme_name, value: { description: "This is a mock trigger" } }; } apiManager.glewlwydRequest("/auth/scheme/trigger/", "POST", scheme, true) .then((res) => { this.setState({triggerResult: res.code}); }) .fail((err) => { if (err.status === 401) { messageDispatcher.sendMessage('Notification', {type: "info", message: i18next.t("login.mock-trigger-must-register")}); } else { messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-mock-trigger")}); } }); } } handleChangeMockValue(e) { this.setState({mockValue: e.target.value}); } handleChangeIdentifyUsernameValue(e) { this.setState({identifyUsername: e.target.value}); } validateMockValue(e) { e.preventDefault(); var scheme = { scheme_type: this.state.scheme.scheme_type, scheme_name: this.state.scheme.scheme_name, username: this.state.currentUser.username, value: { code: this.state.mockValue } }; if (!this.state.currentUser.username) { scheme.value.username = this.state.identifyUsername; } apiManager.glewlwydRequest("/auth/", "POST", scheme) .then(() => { messageDispatcher.sendMessage('App', {type: 'loginSuccess', loginSuccess: true}); }) .fail(() => { messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-mock-value")}); }); } render() { if (this.state.triggerResult) { var usernameJsx; if (!this.state.currentUser.username) { usernameJsx = <div className="form-group"> <div className="input-group mb-3"> <div className="input-group-prepend"> <label className="input-group-text" htmlFor="identifyUsername">{i18next.t("login.login")}</label> </div> <input type="text" className="form-control" name="identifyUsername" id="identifyUsername" autoFocus={true} required="" placeholder={i18next.t("login.login-placeholder")} value={this.state.identifyUsername||""} onChange={this.handleChangeIdentifyUsernameValue} autoComplete="false"/> </div> </div> } return ( <form action="#" id="mockSchemeForm"> <div className="form-group"> <h5>{i18next.t("login.enter-mock-scheme-value")}</h5> </div> {usernameJsx} <div className="form-group"> <div className="input-group mb-3"> <div className="input-group-prepend"> <label className="input-group-text" htmlFor="mockValue">{i18next.t("login.mock-value-label")}</label> </div> <input type="text" className="form-control" name="mockValue" id="mockValue" autoFocus={true} required="" placeholder={i18next.t("login.error-mock-expected", {value: (this.state.triggerResult)})} value={this.state.mockValue||""} onChange={this.handleChangeMockValue} autoComplete="false"/> </div> </div> <button type="submit" name="mockbut" id="mockbut" className="btn btn-primary" onClick={(e) => this.validateMockValue(e)} title={i18next.t("login.mock-value-button-title")}> {i18next.t("login.btn-ok")} </button> </form> ); } else { return (<button type="button" className="btn btn-primary" onClick={this.triggerScheme}>{i18next.t("login.btn-reload")}</button>); } } } export default MockSchemeForm;
examples/js/manipulation/default-search-table.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; const fruits = [ 'banana', 'apple', 'orange', 'tomato', 'strawberries' ]; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Fruit name is ' + fruits[i], price: 2100 + i }); } } addProducts(5); const options = { defaultSearch: 'banana' }; export default class SearchTable extends React.Component { render() { return ( <BootstrapTable data={ products } search={ true } options={ options }> <TableHeaderColumn dataField='id' isKey={ true } searchable={ false }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Fruit Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/svg-icons/image/crop-7-5.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop75 = (props) => ( <SvgIcon {...props}> <path d="M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm0 8H5V9h14v6z"/> </SvgIcon> ); ImageCrop75 = pure(ImageCrop75); ImageCrop75.displayName = 'ImageCrop75'; export default ImageCrop75;
app/containers/MarkerOverlay/index.js
thebakeryio/openmic
/* * * MarkerOverlay * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import markersSelector from 'markersSelector'; import projectSelector from 'projectSelector'; import { addMarker, clickOutsideOfMarkerOverlay } from './actions'; import Marker from 'Marker'; class MarkerOverlay extends React.Component { componentDidMount() { document.querySelector('body').addEventListener('click', this.handleBodyClick); } componentWillUnmount() { document.querySelector('body').removeEventListener('click', this.handleBodyClick); } onAddMarker = (e) => { const { readOnly, recording } = this.props; if (!readOnly && !recording) { this.props.addMarker(e, this.props.project.id); } }; handleBodyClick = (e) => { if (['markers', 'record'].indexOf(e.target.className) === -1) { this.props.dispatch(clickOutsideOfMarkerOverlay()); } }; render() { return ( <div className="markers-container"> <div className="marker-wrapper" onClick={this.onAddMarker}> <div className="markers"> { this.props.markers.map( (m) => <Marker readOnly={this.props.readOnly} marker={m} key={m.get('id')} /> ) } </div> </div> </div> ); } } function mapDispatchToProps(dispatch) { return { dispatch, addMarker: (e, projectId) => { const scrollTop = Math.max( document.querySelector('html').scrollTop, document.querySelector('body').scrollTop, ); const relX = e.pageX - e.target.getBoundingClientRect().left; const relY = (e.pageY - scrollTop) - e.target.getBoundingClientRect().top; dispatch(addMarker({ projectId, id: Math.floor(Math.random() * 1000), x: relX / e.target.parentElement.clientWidth, y: relY / e.target.parentElement.clientHeight, })); }, }; } function selectMarkersAndProject(markers, project) { return { markers: markers.get('items'), project: project.get('project'), recording: project.get('recording'), }; } export default connect( createSelector([markersSelector, projectSelector], selectMarkersAndProject), mapDispatchToProps )(MarkerOverlay);
src-client/components/NamespaceCard.js
ipselon/structor
/* * Copyright 2017 Alexander Pustovalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import defaultScreenshotSrc from 'assets/app/css/img/screenshot.png'; const titleStyle = { margin: '0px', position: 'relative', padding: '3px', backgroundColor: '#f5f5f5', borderRadius: '3px' }; const containerStyle = { display: 'flex', flexDirection: 'row', flexFlow: 'nowrap', alignItems: 'center', width: '600px', }; const screenshotSectionStyle = { flexGrow: 0, minWidth: '200px', width: '200px', padding: '0.5em', }; const mainSectionStyle = { marginLeft: '1.5em', flexGrow: 2, padding: '0.5em 0.5em 0.5em 0', height: '200px', overflow: 'auto', }; const installBtnSectionStyle = { flexGrow: 0, minWidth: '200px', width: '200px', padding: '0.5em', alignItems: 'center', }; const bottomToolbarStyle = { flexGrow: 2, display: 'flex', flexDirection: 'row', padding: '0.5em 0.5em 0.5em 0', alignItems: 'center', justifyContent: 'flex-end', }; class NamespaceCard extends Component { constructor (props) { super(props); this.handleInstallClick = this.handleInstallClick.bind(this); } handleInstallClick (e) { e.stopPropagation(); e.preventDefault(); const tarballUrl = e.currentTarget.dataset.url; const {onInstallClick} = this.props; if (onInstallClick) { onInstallClick(tarballUrl); } } render () { const {style, repoData, currentVersion} = this.props; const { gitHubRepo, gitHubOwner, description, screenshotUrl, releases, structorVersion } = repoData; const repoUrl = `https://github.com/${gitHubOwner}/${gitHubRepo}`; return ( <div style={style}> <div className="panel panel-default"> <div className="panel-body"> <h5 style={titleStyle}> {releases && releases.length > 0 && <div style={{display: 'inline'}}> <div className="btn-group"> <button type="button" className="btn btn-default" data-url={releases[0].tarballUrl} onClick={this.handleInstallClick} > <i className="fa fa-download"/> <span style={{marginLeft: '0.5em'}}> Install </span> </button> <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > <i className="fa fa-caret-down"/> </button> <ul className="dropdown-menu"> {releases.map((release, index) => { return ( <li key={release.name + index}> <a href="#" data-url={release.tarballUrl} onClick={this.handleInstallClick} > <span>{release.name}</span> {index === 0 && <i className="fa fa-check" style={{margin: '0 0.5em'}} /> } </a> </li> ); })} </ul> </div> </div> } <span style={{marginLeft: '1em'}}>{gitHubRepo}</span> </h5> <div style={containerStyle}> <div style={screenshotSectionStyle}> <img style={{width: '100%'}} src={screenshotUrl || defaultScreenshotSrc} alt="" /> </div> <div style={mainSectionStyle}> <h4> {description} </h4> </div> </div> <div style={containerStyle}> <div style={installBtnSectionStyle}> <span style={{marginRight: '0.5em'}} title="Compatible Structor version with this package" > Structor version: </span> <span className={structorVersion === currentVersion ? 'text-success' : 'text-danger'} title={structorVersion === currentVersion ? 'Structor version is compatible' : 'Structor version is not compatible'} > {structorVersion} </span> </div> <div style={bottomToolbarStyle}> <div style={{marginLeft: '0.5em'}}> <a href={repoUrl} className="btn btn-link" target="_blank" > <i className="fa fa-github-alt"/> <span style={{marginLeft: '0.5em'}}> Open on GitHub </span> </a> </div> </div> </div> </div> </div> </div> ); } } export default NamespaceCard;
src/components/TraitList.js
hunt-genes/fasttrack
import React from 'react'; import Relay from 'react-relay'; import ExternalLink from './ExternalLink'; import Link from './Link'; class TraitList extends React.Component { static propTypes = { introduction: React.PropTypes.string, viewer: React.PropTypes.object, } static contextTypes = { relay: Relay.PropTypes.Environment, } render() { return ( <div style={{ padding: '0 15px' }}> {this.props.introduction ? <p style={{ margin: '0 auto', textAlign: 'center' }}> <em>{this.props.introduction}</em> </p> : null } <ul style={{ WebkitColumnCount: 3, MozColumnCount: 3, columnCount: 3, listStyle: 'none', paddingLeft: 0 }}> {this.props.viewer.traits.map((trait) => { return ( <li key={trait.id}> <Link to={`?q=${trait.id}`}>{trait.id}</Link> <ExternalLink href={trait.uri} /> </li> ); })} </ul> </div> ); } } export default Relay.createContainer(TraitList, { fragments: { viewer: () => { return Relay.QL` fragment on User { traits { id, uri } }`; }, }, });
src/js/components/icons/base/Manual.js
odedre/grommet-final
/** * @description Manual 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="M14,9 L14,17 L14,9 Z M10,9 L10,17 L10,9 Z M8,5 C8,7.209 9.791,9 12,9 C14.209,9 16,7.209 16,5 C16,2.791 14.209,1 12,1 C9.791,1 8,2.791 8,5 Z M4,23 L20,23 L20,20 L4,20 L4,23 Z M7,20 L17,20 L17,17 L7,17 L7,20 Z"/></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}-manual`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'manual'); 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="M14,9 L14,17 L14,9 Z M10,9 L10,17 L10,9 Z M8,5 C8,7.209 9.791,9 12,9 C14.209,9 16,7.209 16,5 C16,2.791 14.209,1 12,1 C9.791,1 8,2.791 8,5 Z M4,23 L20,23 L20,20 L4,20 L4,23 Z M7,20 L17,20 L17,17 L7,17 L7,20 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Manual'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/native/main.js
xiankai/triple-triad-solver
/* @flow */ import FBSDK from 'react-native-fbsdk'; import React from 'react'; import ReactNativeI18n from 'react-native-i18n'; import Root from './app/Root'; import configureStore from '../common/configureStore'; import initialState from './initialState'; import uuid from 'react-native-uuid'; import { AppRegistry, AsyncStorage, Platform } from 'react-native'; const getDefaultDeviceLocale = () => { const { defaultLocale, locales } = initialState.intl; const deviceLocale = ReactNativeI18n.locale.split('-')[0]; const isSupported = locales.indexOf(deviceLocale) !== -1; return isSupported ? deviceLocale : defaultLocale; }; const createNativeInitialState = () => ({ ...initialState, device: { ...initialState.device, isReactNative: true, platform: Platform.OS, }, intl: { ...initialState.intl, currentLocale: getDefaultDeviceLocale(), }, }); const store = configureStore({ initialState: createNativeInitialState(), platformDeps: { FBSDK, uuid, storageEngine: AsyncStorage }, }); const Este = () => ( <Root store={store} /> ); AppRegistry.registerComponent('Este', () => Este);