path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
rojak-ui-web/src/Routes.js
rawgni/rojak
import { Route, IndexRoute } from 'react-router'; import React from 'react'; import Container from './app/utils/Container'; import HomePage from './app/home/HomePage'; export default ( <Route component={Container}> <Route path="/(search/:keyword)" component={HomePage} /> </Route> )
frontend/src/components/submitcast/ShowInput.js
tanzdervampire/website
// @flow import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import { red500 } from 'material-ui/styles/colors'; import CircularProgress from 'material-ui/CircularProgress'; import { Card, CardHeader, CardText, CardActions } from 'material-ui/Card'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import FlatButton from 'material-ui/FlatButton'; import Done from 'material-ui/svg-icons/action/done'; import ShowPickerDatePicker from '../showpicker/ShowPickerDatePicker'; import ShowTimePicker from '../submitcast/ShowTimePicker'; const Step = { DATE: 1, TIME: 2, LOCATION: 3, }; function getStyles() { return { cardText: { textAlign: 'center', }, dropdown: { width: '100%', }, }; } class ShowInput extends React.Component { static propTypes = { onFinish: PropTypes.func.isRequired, cardStyle: PropTypes.object, }; static defaultProps = { cardStyle: {}, }; state = { selectedDate: null, selectedTime: null, selectedLocation: null, step: Step.DATE, productions: [], filteredProductions: [], fetchFailed: false, }; componentDidMount() { this.loadProductions(); }; loadProductions() { fetch(`/api/productions`, { accept: 'application/json', }).then(response => { if (!response.ok) { throw new Error(); } return response.json(); }).then(productions => { this.setState({ productions }); }).catch(err => { console.log(`Failed to load productions!`); this.setState({ fetchFailed: true }); }); }; handleOnDateSelected = date => { const { productions, step } = this.state; const mDate = moment(date); const filteredProductions = productions.filter(production => { const start = moment(production.start, 'YYYY-MM-DD'); const end = moment(production.end, 'YYYY-MM-DD'); return mDate.isBetween(start, end, 'day', '[]'); }); this.setState({ filteredProductions, selectedDate: date, selectedLocation: filteredProductions[0], step: Math.max(step, Step.TIME), }); }; handleOnTimeSelected = time => { const { step } = this.state; this.setState({ selectedTime: time, step: Math.max(step, Step.LOCATION), }); }; renderDatePicker() { const { selectedDate } = this.state; return ( <ShowPickerDatePicker selectedDate={selectedDate} onDateSelected={this.handleOnDateSelected} /> ); }; renderTimePicker() { const { selectedTime, step } = this.state; if (step < Step.TIME) { return null; } return ( <ShowTimePicker selectedTime={selectedTime} onTimeSelected={this.handleOnTimeSelected} openDialog={!selectedTime} /> ); }; renderLocationPicker() { const { selectedLocation, filteredProductions, step } = this.state; if (step < Step.LOCATION) { return null; } if (filteredProductions.length === 0) { return ( <p>An diesem Datum wurde das Musical nicht aufgeführt.</p> ); } const items = filteredProductions.map(production => { const label = `${production.location}, ${production.theater}`; return ( <MenuItem key={production.location} value={production} primaryText={label} /> ); }); const styles = getStyles(); return ( <DropDownMenu value={selectedLocation} onChange={(_, index, value) => this.setState({ selectedLocation: value })} disabled={filteredProductions.length <= 1} autoWidth={false} style={styles.dropdown} > {items} </DropDownMenu> ); }; renderActions() { const { selectedDate, selectedTime, selectedLocation } = this.state; return ( <FlatButton label="Weiter" onTouchTap={() => this.props.onFinish(selectedDate, selectedTime, selectedLocation)} primary={true} icon={<Done />} disabled={!(selectedDate && selectedTime && selectedLocation)} /> ); }; render() { const { productions, fetchFailed } = this.state; const { cardStyle } = this.props; const styles = getStyles(); return ( <Card style={cardStyle}> <CardHeader title="Vorstellung" subtitle="Wann fand die Vorstellung statt?" expandable={false} /> <CardText style={styles.cardText}> { fetchFailed && ( <p>Ups! Leider gab es ein Problem.</p> ) } { !fetchFailed && productions.length === 0 && ( <CircularProgress color={red500} /> ) } { productions.length !== 0 && ( <div> {this.renderDatePicker()} {this.renderTimePicker()} {this.renderLocationPicker()} </div> ) } </CardText> <CardActions> {this.renderActions()} </CardActions> </Card> ); }; } export default ShowInput;
src/components/topic/platforms/PlatformSizeNotice.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { injectIntl, FormattedMessage } from 'react-intl'; import { Grid, Row, Col } from 'react-flexbox-grid/lib'; import Permissioned from '../../common/Permissioned'; import { PERMISSION_TOPIC_WRITE } from '../../../lib/auth'; import { DetailNotice } from '../../common/Notice'; const localMessages = { maxSize: { id: 'topic.maxSize', defaultMessage: 'Your topic size limit is {limit} stories. If your platforms and spidering discover more than that, your topic will fail to build.' }, maxSizeDetails: { id: 'topic.maxSize.details', defaultMessage: 'Try to keep your start and end dates small, or be more specific in your queries. Email [email protected] if you have questions.' }, }; export function platformIncomplete(initializedPlatform) { return !initializedPlatform; } /** * If the user has a topic size limitation, add a note about it here */ const PlatformSizeNotice = ({ initializedPlatform, isAdmin, userMaxSize, topicMaxSize }) => ( <Permissioned onlyTopic={PERMISSION_TOPIC_WRITE}> {initializedPlatform && !isAdmin && ( <div className="notice detail-background"> <Grid> <Row> <Col lg={12}> <DetailNotice details={localMessages.maxSizeDetails}> <FormattedMessage {...localMessages.maxSize} values={{ limit: Math.max(userMaxSize, topicMaxSize) }} /> </DetailNotice> </Col> </Row> </Grid> </div> )} </Permissioned> ); PlatformSizeNotice.propTypes = { // from state initializedPlatform: PropTypes.bool.isRequired, userMaxSize: PropTypes.number.isRequired, topicMaxSize: PropTypes.number.isRequired, isAdmin: PropTypes.bool.isRequired, // from compositional chain intl: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ userMaxSize: state.user.profile.limits.max_topic_stories, topicMaxSize: state.topics.selected.info.max_stories, isAdmin: state.user.isAdmin, initializedPlatform: state.topics.selected.platforms.all.initialized, }); export default injectIntl( connect(mapStateToProps)( PlatformSizeNotice ) );
examples/html-table/SortableList.js
danielstocks/react-sortable
import React from 'react' import SortableListItem from './SortableItem' export default class SortableList extends React.Component { state = { items: this.props.items }; onSortItems = (items) => { this.setState({ items: items }); } render() { const { items } = this.state; var listItems = items.map((item, i) => { return ( <SortableListItem key={i} onSortItems={this.onSortItems} items={items} sortId={i}>{item}</SortableListItem> ); }); return ( <table className='sortable-list'> <tbody>{listItems}</tbody> </table> ) } }
src/app/components/task/DatetimeTaskResponse.js
meedan/check-web
import React from 'react'; import { FormattedMessage, FormattedDate } from 'react-intl'; import { convertNumbers2English } from '../../helpers'; const DateDisplay = ({ isoDate }) => ( <time dateTime={isoDate}> <FormattedDate value={new Date(isoDate)} day="numeric" month="long" year="numeric" /> </time> ); function tzOffsetHoursToIso8601Offset(nHours) { if (nHours === 0) { return 'Z'; } const sign = nHours > 0 ? '+' : '-'; return `${sign}${String(Math.abs(nHours)).padStart(2, '0')}:00`; } function DateTimeDisplay({ isoDate, hourString, minuteString, tzOffsetHours, tzString, }) { const dateString = `${isoDate}T${hourString.padStart(2, '0')}:${minuteString.padStart(2, '0')}`; const iso8601TzOffset = tzOffsetHoursToIso8601Offset(tzOffsetHours); const date = new Date(`${dateString}${iso8601TzOffset}`); // We can't format `date`, because we don't know its timezone. All we // have is its offset, and that isn't enough: `Intl.DateTimeFormat` needs // an IANA timezone. TODO fix https://mantis.meedan.com/view.php?id=8437, // then format with `value={date}`. // `Date.parse("YYYY-MM-DDThh:mm")` will parse in user's local timezone. // This date may not exist! Hence https://mantis.meedan.com/view.php?id=8437 const displayDate = new Date(dateString); const urlDate = encodeURIComponent(`${isoDate} ${hourString}:${minuteString} ${tzString}`); return ( <time dateTime={date.toISOString()}> <FormattedDate value={displayDate /* https://mantis.meedan.com/view.php?id=8437 */} year="numeric" month="long" day="numeric" hour="numeric" minute="numeric" /> {' '} <FormattedMessage id="datetimeTaskResponse.timeIs" defaultMessage="View this timezone on time.is" > {title => ( <a href={`https://time.is/${urlDate}`} target="_blank" rel="noreferrer noopener" title={title} > {tzString} </a> )} </FormattedMessage> </time> ); } const DatetimeTaskResponse = (props) => { if (!props.response) { return null; } const response = convertNumbers2English(props.response); const values = response.match(/^(\d+-\d+-\d+) (\d+):(\d+) ([+-]?\d+) (.*)$/); if (!values) { return ( <FormattedMessage id="datetimeTaskResponse.invalidTimestamp" defaultMessage="Error: Invalid timestamp" /> ); } const noTime = /notime/.test(response); return noTime ? ( <DateDisplay isoDate={values[1]} /> ) : ( <DateTimeDisplay isoDate={values[1]} hourString={values[2]} minuteString={values[3]} tzOffsetHours={Number(values[4])} tzString={values[5]} /> ); }; export default DatetimeTaskResponse;
src/components/Main.js
chiefwhitecloud/running-man-frontend
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import RacePageLayout from './Races/PageLayout'; import FilterableRaceResults from './FilterableRaceResults'; import RacerContainer from './RacerContainer'; const containerStyle = { maxWidth: '1200px', margin: '0px auto', }; const Main = () => ( <div style={containerStyle}> <Switch> <Route path="/races" component={RacePageLayout} /> <Route path="/race/:raceId" component={FilterableRaceResults} /> <Route path="/racer/:racerId" component={RacerContainer} /> </Switch> </div> ); export default Main;
components/Nav/Social.js
styled-components/styled-components-website
import React from 'react'; import styled from 'styled-components'; import { Github, MediumM } from '@styled-icons/fa-brands'; import rem from '../../utils/rem'; import { navbarHeight } from '../../utils/sizes'; import Link from '../Link'; const Wrapper = styled.nav` display: flex; align-items: center; flex: 1 1 auto; `; const SocialLink = styled(Link).attrs((/* props */) => ({ unstyled: true, }))` display: flex; margin-right: ${rem(20)}; line-height: ${rem(navbarHeight)}; transition: opacity 0.2s, transform 0.2s; cursor: pointer; &:last-child { margin-right: 0; } &:hover, &:focus { opacity: 0.8; } &:active { transform: scale(0.95); opacity: 0.6; } svg { path { fill: currentColor; } } `; const Svg = styled.svg` width: ${p => rem(Number(p.width))}; height: ${p => rem(Number(p.height))}; `; const StyledIcon = styled.div` && { width: ${p => rem(Number(p.width))}; height: ${p => rem(Number(p.height))}; } `; // const Twitter = () => ( // <Svg xmlns="http://www.w3.org/2000/svg" width="19" height="15" viewBox="0 0 19 15" xmlnsXlink="http://www.w3.org/1999/xlink"> // <title>twitter-logo</title> // <use fill="#FFF" xlinkHref="#b"/> // <defs> // <path id="b" d="M18.2 1.8l-2 .6c.6-.5 1.2-1.2 1.5-2l-2.4.8C14.7.5 13.7 0 12.6 0 10.6 0 9 1.7 9 3.8v1C6 4.4 3 3 1.3.8 1 1 .8 1.8.8 2.4c0 1.3.6 2.5 1.6 3-.6 0-1.2 0-1.7-.3 0 2 1.3 3.7 3 4H2c.5 1.6 2 2.7 3.5 2.7-1.2 1-3 1.6-4.6 1.6H0c1.7 1 3.6 1.7 5.7 1.7 7 0 10.7-6 10.7-11v-.5c.7-.5 1.3-1.2 1.8-2z"/> // </defs> // </Svg> // ) const Spectrum = () => ( <Svg width="14" height="14" viewBox="0 0 15 15"> <title>spectrum</title> <path fill="#FFF" d="M0 6.5V1c0-.6.4-1 1-1 9 .3 13.7 5 14 14 0 .6-.4 1-1 1H8.5c-.6 0-1-.4-1-1-.3-4.4-2-6.2-6.5-6.5-.6 0-1-.4-1-1z" /> </Svg> ); const Social = props => ( <Wrapper {...props}> <SocialLink href="https://spectrum.chat/styled-components/"> <Spectrum /> </SocialLink> {/* <SocialLink href="https://twitter.com/someone"> <Twitter /> </SocialLink> */} <SocialLink href="https://github.com/styled-components"> <StyledIcon as={Github} height="18" /> </SocialLink> <SocialLink href="https://medium.com/styled-components"> <StyledIcon as={MediumM} height="18" /> </SocialLink> </Wrapper> ); export default Social;
client/components/operations/label.js
jankeromnes/kresus
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { translate as $t } from '../../helpers'; import { actions } from '../../store'; // If the length of the short label (of an operation) is smaller than this // threshold, the raw label of the operation will be displayed in lieu of the // short label, in the operations list. // TODO make this a parameter in settings const SMALL_TITLE_THRESHOLD = 4; class LabelComponent_ extends React.Component { constructor(props) { super(props); this.state = { editedValue: null }; this.handleChange = this.handleChange.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleKeyUp = this.handleKeyUp.bind(this); this.handleBlur = this.handleBlur.bind(this); } handleChange(e) { this.setState({ editedValue: e.target.value }); } handleFocus(event) { // Set the caret at the end of the text. let end = (event.target.value || '').length; event.target.selectionStart = end; event.target.selectionEnd = end; } handleKeyUp(event) { if (event.key === 'Enter') { event.target.blur(); } else if (event.key === 'Escape') { let { target } = event; this.setState({ editedValue: null }, () => target.blur()); } } handleBlur() { if (this.state.editedValue === null) return; let label = this.state.editedValue.trim(); // If the custom label is equal to the label, remove the custom label. if (label === this.getLabel()) { label = ''; } let { customLabel } = this.props.operation; if (label !== customLabel && (label || customLabel)) { this.props.setCustomLabel(label); } this.setState({ editedValue: null }); } getCustomLabel() { let { customLabel } = this.props.operation; if (customLabel === null || !customLabel.trim().length) { return ''; } return customLabel; } // Returns the label (or even the raw label if the label is too short). getLabel() { let op = this.props.operation; let label; if (op.title.length < SMALL_TITLE_THRESHOLD) { label = op.raw; if (op.title.length) { label += ` (${op.title})`; } } else { label = op.title; } return label.trim(); } getDefaultValue() { let label = this.getCustomLabel(); if (!label && this.props.displayLabelIfNoCustom) { label = this.getLabel(); } return label; } render() { let label = this.state.editedValue !== null ? this.state.editedValue : this.getDefaultValue(); let labelVisibility = 'hidden'; let inputVisibility = ''; if (this.props.readonlyOnSmallScreens) { labelVisibility = 'visible-xs-inline'; inputVisibility = 'hidden-xs'; } return (<div className="label-component-container"> <span className={ `text-uppercase label-component ${labelVisibility}` }> { label } </span> <input className={ `form-control operation-label-input ${inputVisibility}` } type="text" value={ label } onChange={ this.handleChange } onFocus={ this.handleFocus } onKeyUp={ this.handleKeyUp } onBlur={ this.handleBlur } placeholder={ $t('client.operations.add_custom_label') } /> </div>); } } LabelComponent_.propTypes = { // The operation from which to get the label. operation: PropTypes.object.isRequired, // Whether to display the operation label if there is no custom label. displayLabelIfNoCustom: PropTypes.bool, // A function to set the custom label when modified. setCustomLabel: PropTypes.func.isRequired, // Whether the label is readonly on small screens. readonlyOnSmallScreens: PropTypes.bool }; LabelComponent_.defaultProps = { displayLabelIfNoCustom: true, readonlyOnSmallScreens: false }; function mapDispatch(component) { return connect(() => { // no state return {}; }, (dispatch, props) => { return { setCustomLabel(label) { actions.setOperationCustomLabel(dispatch, props.operation, label); } }; })(component); } export const LabelComponent = mapDispatch(LabelComponent_); const OperationListViewLabel_ = props => { let label = ( <LabelComponent operation={ props.operation } setCustomLabel={ props.setCustomLabel } readonlyOnSmallScreens={ true } /> ); if (typeof props.link === 'undefined') { return label; } return ( <div className="input-group"> { props.link } { label } </div> ); }; OperationListViewLabel_.propTypes = { // The operation from which to get the label. operation: PropTypes.object.isRequired, // A function to set the custom label when modified. setCustomLabel: PropTypes.func.isRequired, // A link associated to the label link: PropTypes.object }; export const OperationListViewLabel = mapDispatch(OperationListViewLabel_);
src/containers/Home/index.js
anitrack/anitrack-web
import React, { Component } from 'react'; import { Col, Row, Button, Form, FormGroup, Label, Input, InputGroup, InputGroupButton, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; import MediaQuery from 'react-responsive'; import * as css from './css'; const flexItem = [ {icon: "fa-code", title: "Open Source", desc: "All of the codes used to power this project is available publicly. Anyone can modify and contribute to make it better!"}, {icon: "fa-flash", title: "Simple and Fast", desc: "The Process is extremely simple. Simply enter your username and view the results compiled into a single list."}, {icon: "fa-unlock", title: "Free of Charge", desc: "Best of all, the service is free of charge! Feel free to enjoy and keep track of those anime you can't wait to watch."} ]; class Home extends Component { constructor(props){ super(props); this.state = {userName: "", provider: "mal"}; } linkState(state, val){ const obj = {}; obj[state] = val; this.setState(obj); } onClick(event){ if(this.state.userName !== ''){ this.props.history.push(`/${this.state.provider}/${this.state.userName}`) } event.preventDefault(); } render() { let provider = ""; switch(this.state.provider){ case "mal": provider = "MAL"; break; case "alist": provider = "AniList"; break; default: } return ( <div style={css.background} > <Row style={css.topRow}> <Col> <h1 style={css.heading}><strong>ANIME TRACKER</strong></h1> <Form onSubmit={(e) => {this.onClick(e)}} > <FormGroup style={css.formGroup}> <Label for="userName" style={css.formLabel}>Username</Label> <div style={css.inputDiv}> <InputGroup> <InputGroupButton> <UncontrolledDropdown> <DropdownToggle caret style={css.inputDropdown}> {provider} </DropdownToggle> <DropdownMenu> <DropdownItem onClick={() => {this.setState({provider: "mal"})}}>MAL</DropdownItem> <DropdownItem onClick={() => {this.setState({provider: "alist"})}}>AniList</DropdownItem> </DropdownMenu> </UncontrolledDropdown> </InputGroupButton> <Input style={css.input} placeholder="Username" value={this.state.userName} onChange={(e) => {this.linkState('userName', e.target.value)}} /> </InputGroup> </div> </FormGroup> <Button style={css.inputButton} >Search</Button> </Form> <br /> </Col> </Row> <Row style={css.botRow}> <Col> <div style={css.flexRow}> { flexItem.map((item, i) => { return ( <MediaQuery maxWidth={768} key={i}> {(matches) => { return ( <div style={matches? css.flexItemSmall : css.flexItem }> <i className={`fa ${item.icon}`} style={css.flexLogo} /> <h4>{item.title}</h4> <p style={css.flexDesc}>{item.desc}</p> </div> ) }} </MediaQuery> ) }) } </div> </Col> </Row> </div> ); } } export default Home;
UI/src/components/common/Spinner.js
ssvictorlin/PI
import React from 'react'; import { View, ActivityIndicator } from 'react-native'; const Spinner = ({ size }) => { return ( <View style={ styles.spinnerStyle }> <ActivityIndicator size={ size || 'large' } /> </View> ); }; const styles = { spinnerStyle: { flex: 1, justifyContent: 'center', alignItems: 'center' } } export { Spinner };
ux/Selector.js
rameshvk/j0
'use strict'; import BaseComponent from './BaseComponent.js'; import React from 'react'; import SelectView from './SelectView.js'; function getState(props) { return {optionIndex: props.model.get(React.Children.count(props.children))}; } export default class Selector extends BaseComponent { constructor(props) { super(props); this.state = getState(props); this._onChange = () => this.setState(getState(this.props)); this.props.model.on('change', this._onChange); } componentWillUnmount() { this.props.model.removeListener('change', this._onChange); } render() { return SelectView.create({ optionIndex: this.state.optionIndex, children: this.props.children }); } }; Selector.propTypes = { model: React.PropTypes.object.isRequired };
wwwroot/app/src/components/MealPlannerPage/Meal/index.js
AlinCiocan/PlanEatSave
import React from 'react'; import Routes from '../../../services/Routes'; import Link from '../../base/Link'; import RemoveIcon from '../../base/icons/RemoveIcon'; const Meal = ({ meal, onRemoveMeal }) => ( <div className="pes-meal"> <div className="pes-meal__divider"></div> <Link undecorated to={Routes.viewRecipe(meal.recipeId)} className="pes-meal__recipe-name"> {meal.recipeName} </Link> <button onClick={() => onRemoveMeal(meal.id, meal.recipeName)} className="pes-meal__remove-button"> <RemoveIcon /> </button> </div> ); export default Meal;
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2017-10-23-before-redesign/src/demo/pagination/pagination.js
mcjazzyfunky/js-surface
import { defineClassComponent, defineFunctionalComponent, hyperscript as h, mount } from 'js-surface'; import { Seq } from 'js-essential'; import PaginationHelper from './helper/PaginationHelper.js'; import ComponentHelper from './helper/ComponentHelper.js'; import React from 'react'; import ReactDOM from 'react-dom'; const number = 20, pageSize = 25, totalItemCount = 1220; export const Pagination = defineFunctionalComponent({ displayName: 'Pagination', properties: { className: { type: String, defaultValue: null }, pageIndex: { type: Number, defaultValue: null }, pageSize: { type: Number, defaultValue: null }, totalItemCount: { type: Number, defaultValue: null }, showFirstButton: { type: Boolean, defaultValue: true }, showLastButton: { type: Boolean, defaultValue: true }, showPreviousButton: { type: Boolean, defaultValue: true }, showNextButton: { type: Boolean, defaultValue: true }, onChange: { type: Function, defaultValue: null } }, render(props) { const pageIndex = props.pageIndex, metrics = PaginationHelper.calcPaginationMetrics( props.pageIndex, props.pageSize, props.totalItemCount), paginationInfo = PaginationHelper.determineVisiblePaginationButtons( props.pageIndex, metrics.pageCount, 6), classNameOuter = ComponentHelper.buildCssClass( 'fk-pagination', props.className), classNameInner = 'pagination', moveToPage = targetPage => { if (props.onChange) { props.onChange({targetPage}); } }, firstPageLink = metrics.pageCount > 0 ? buildLinkListItem( 1, pageIndex === 0, () => moveToPage(0)) : null, precedingEllipsis = paginationInfo.firstButtonIndex > 1 ? buildLinkListItem( '...', false) : null, succeedingEllipsis = paginationInfo.lastButtonIndex < metrics.pageCount - 2 ? buildLinkListItem( '...', false) : null, lastPageLink = metrics.pageCount > 0 ? buildLinkListItem( metrics.pageCount, pageIndex === metrics.pageCount - 1, () => moveToPage(metrics.pageCount - 1)) : null, buttons = Seq.range( paginationInfo.firstButtonIndex , paginationInfo.lastButtonIndex + 1) .map( index => buildLinkListItem( index + 1, index === pageIndex, () => moveToPage(index)) ); return ( h('div', {className: classNameOuter}, h('ul', {className: classNameInner}, firstPageLink, precedingEllipsis, buttons.toArray(), succeedingEllipsis, lastPageLink)) ); } }); function buildLinkListItem(text, isActive, moveToPage) { return ( h('li.page-item', { className: isActive ? 'active' : '', key: text !== '...' ? text + '-' + isActive : undefined }, h('a.page-link', { onClick: moveToPage }, text)) ); } const DemoOfPagination = defineClassComponent({ displayName: 'DemoOfPagination', constructor() { this.state = { pageIndex: 0 }; }, moveToPage(pageIndex) { this.state = { pageIndex }; }, render() { return ( h('div', {className: 'container-fluid'}, Seq.range(1, number).map(() => h('div', Pagination({ pageIndex: this.state.pageIndex, pageSize: pageSize, totalItemCount: totalItemCount, onChange: evt => this.moveToPage(evt.targetPage)}))))); } }); // ----------------- class RPaginationClass extends React.Component { render() { const pageIndex = this.props.pageIndex, metrics = PaginationHelper.calcPaginationMetrics( this.props.pageIndex, this.props.pageSize, this.props.totalItemCount), paginationInfo = PaginationHelper.determineVisiblePaginationButtons( this.props.pageIndex, metrics.pageCount, 6), classNameOuter = ComponentHelper.buildCssClass( 'fk-pagination', this.props.className), classNameInner = 'pagination', firstPageLink = metrics.pageCount > 0 ? buildLinkListItem2( 1, pageIndex === 0, this.props, 0) : null, precedingEllipsis = paginationInfo.firstButtonIndex > 1 ? buildLinkListItem2( '...', false, this.props) : null, succeedingEllipsis = paginationInfo.lastButtonIndex < metrics.pageCount - 2 ? buildLinkListItem2( '...', false, this.props) : null, lastPageLink = metrics.pageCount > 0 ? buildLinkListItem2( metrics.pageCount, pageIndex === metrics.pageCount - 1, this.props, metrics.pageCount - 1) : null, buttons = Seq.range( paginationInfo.firstButtonIndex , paginationInfo.lastButtonIndex + 1) .map(index => buildLinkListItem2( index + 1, index === pageIndex, this.props, index)); return ( React.createElement('div', {className: classNameOuter}, React.createElement('ul', {className: classNameInner}, firstPageLink, precedingEllipsis, buttons, succeedingEllipsis, lastPageLink)) ); } } function buildLinkListItem2(text, isActive, props, pageIndexToMove = null) { const onChangeProp = props.onChange, onClick = !isActive && pageIndexToMove !== null && typeof onChangeProp === 'function' ? () => onChangeProp({targetPage: pageIndexToMove}) : null; return ( React.createElement('li', { className: 'page-item ' + (isActive ? 'active' : ''), key: (pageIndexToMove === null ? undefined : pageIndexToMove + text + isActive)}, React.createElement('a', { className: 'page-link', onClick: onClick }, text)) ); } class RDemoOfPaginationClass extends React.Component { constructor() { super(); this.state = {currPageIdx: 0}; } render() { return ( React.createElement('div', {className: 'container-fluid'}, ...Seq.range(1, number).map(() => React.createElement('div', {className: 'row'}, RPagination({ pageIndex: this.state.currPageIdx, pageSize: pageSize, totalItemCount: totalItemCount, onChange: evt => this.setState({currPageIdx: evt.targetPage}) }) ))) ); } } const RPagination = React.createFactory(RPaginationClass), RDemoOfPagination = React.createFactory(RDemoOfPaginationClass); const container = document.getElementById('main-content'); container.innerHTML = '<div class="row" style="margin: 0 0 0 50px">' + '<div class="col-md-6"><b>js-surface:</b></div>' + '<div class="col-md-6"><b>React:</b></div>' + '<div id="section-surface" class="col-md-6"></div>' + '<div id="section-react" class="col-md-6"></div>' + '</div>'; mount( DemoOfPagination(), 'section-surface'); ReactDOM.render( RDemoOfPagination(), document.getElementById('section-react'));
src/components/Footer/Footer.js
stinkyfingers/IsoTest
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.scss'; import Link from '../Link'; class Footer extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/">Home</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/privacy">Privacy</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/not-found">Not Found</Link> </div> </div> ); } } export default withStyles(Footer, s);
src/svg-icons/communication/location-on.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationLocationOn = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); CommunicationLocationOn = pure(CommunicationLocationOn); CommunicationLocationOn.displayName = 'CommunicationLocationOn'; CommunicationLocationOn.muiName = 'SvgIcon'; export default CommunicationLocationOn;
client/components/TableBeta2.js
ForestJS/ForestJS-Production
import React, { Component } from 'react'; class TableBeta2 extends Component { constructor(props) { super(props); this.state = { login: null, user: null } this.createTable = this.createTable.bind(this); this.detailView = this.props.detailView.bind(this); } createTable(){ const activeTree = ''; } render() { let view = this.createTable(); return ( <div id="tablecontainer"> {view} </div> ) } } export default Table;
src/components/sandbox/Sandbox.js
gtdudu/hapi-wurb
import React from 'react'; import PropTypes from 'prop-types'; const Sandbox = () => { return ( <div className="outer_face"> <div className="marker oneseven"></div> <div className="marker twoeight"></div> <div className="marker fourten"></div> <div className="marker fiveeleven"></div> <div className="inner_face"> <div className="hand hour"></div> <div className="hand minute"></div> <div className="hand second"></div> </div> </div> ); }; Sandbox.propTypes = { children : PropTypes.object }; export default Sandbox;
src/app/SelectSpotTypePage.js
EsriJapan/photospot-finder
// Copyright (c) 2016 Esri Japan import React from 'react'; class SelectSpotTypePage extends React.Component { constructor (props) { super(props); } render () { let visibility = 'block'; if (this.props.visibility === false) { visibility = 'none'; } return ( <div className="select-photospot-page" style={{ display: visibility, position: 'absolute', top: 0, width: '100%', marginLeft: '-15px', height: window.innerHeight - 50 + 'px' }}> <style type="text/css">{` .select-photospot-page > div { height: 50%; position: relative; background-size: cover; } .select-photospot-page > div:before { filter: blur(1px); } .select-photospot { background-image: url(img/photospot-bg.jpg); } .select-kujiranspot { background-image: url(img/kujiranspot-bg.jpg); } .select-photospot-page > div > div { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; height: 34px; width: 200px; padding-top: 7px; color: #fff; background-color: rgba(0,0,0,0.3); font-weight: bold; border-radius: 17px; border: solid 1px #fff; text-shadow: none; text-align: center; transition: all 0.3s; cursor: pointer; } .select-photospot-page > div > div:hover { color: #666; background-color: rgba(255,255,255,1); } `}</style> <div className="select-photospot"> <div onClick={this.props.onSelectPhotoSpot}> <p>撮影スポットを探す</p> </div> </div> <div className="select-kujiranspot"> <div onClick={this.props.onSelectKujiranSpot}> <p>くじらんスポットを探す</p> </div> </div> </div> ); } } SelectSpotTypePage.propTypes = { visibility: React.PropTypes.bool, onSelectPhotoSpot: React.PropTypes.func, onSelectKujiranSpot: React.PropTypes.func }; SelectSpotTypePage.displayName = 'SelectSpotTypePage'; export default SelectSpotTypePage;
6.webpack/message/components/Message.js
zhufengnodejs/201608node
import React from 'react'; export default class Message extends React.Component { render() { return ( <li className="list-group-item">{this.props.author}:{this.props.children} <button onClick={()=>{this.props.click(this.props.id)}} className="btn btn-danger">删除</button> <span className="pull-right">{this.props.date&&this.props.date.toLocaleString()}</span> </li> ) } }
app/react-icons/fa/user-md.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaUserMd extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z"/></g> </IconBase> ); } }
tools/public-components.js
joemcbride/react-starter-kit
import React from 'react'; import index from '../src/index'; let components = []; Object.keys(index).forEach(function (item) { if (index[item] instanceof React.Component.constructor) { components.push(item); } }); export default components;
src/svg-icons/navigation/subdirectory-arrow-right.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationSubdirectoryArrowRight = (props) => ( <SvgIcon {...props}> <path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/> </SvgIcon> ); NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight); NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight'; NavigationSubdirectoryArrowRight.muiName = 'SvgIcon'; export default NavigationSubdirectoryArrowRight;
public/js/components/visits/othersvisits.react.js
rajikaimal/Coupley
import React from 'react'; import Avatar from 'material-ui/lib/avatar'; import Card from 'material-ui/lib/card/card'; import CardActions from 'material-ui/lib/card/card-actions'; import CardHeader from 'material-ui/lib/card/card-header'; import CardMedia from 'material-ui/lib/card/card-media'; import CardTitle from 'material-ui/lib/card/card-title'; import FlatButton from 'material-ui/lib/flat-button'; import CardText from 'material-ui/lib/card/card-text'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import TextField from 'material-ui/lib/text-field'; import Divider from 'material-ui/lib/divider'; import IconButton from 'material-ui/lib/icon-button'; import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; import Colors from 'material-ui/lib/styles/colors'; import IconMenu from 'material-ui/lib/menus/icon-menu'; import MenuItem from 'material-ui/lib/menus/menu-item'; import Tabs from 'material-ui/lib/tabs/tabs'; import Tab from 'material-ui/lib/tabs/tab'; import Dialog from 'material-ui/lib/dialog'; import ThreadActions from '../../actions/Thread/ThreadActions'; import VisitsActions from '../../actions/VisitsAction'; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={Colors.grey400} /> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Block</MenuItem> </IconMenu> ); const othervisits = React.createClass({ handleOpen: function () { this.setState({ open: true }); }, handleClose: function () { this.setState({ open: false }); }, deletemyfollow:function () { console.log('follower deleted!'); }, getInitialState: function () { return { open: false, }; }, blockUser: function () { ThreadActions.block(this.props.username, localStorage.getItem('username')); VisitsActions.deleteUserFromOthervisit(this.props.username, localStorage.getItem('username')); this.setState({ open: false }); }, render:function(){ const actions = [ <FlatButton label="No" secondary={true} onTouchTap={this.handleClose} />, <FlatButton label="Yes" primary={true} keyboardFocused={true} onTouchTap={this.blockUser} />, ]; return( <div> <ListItem primaryText={this.props.fistname} leftAvatar={<Avatar src={'img/profilepics/'+this.props.username} />} rightIconButton={ <IconMenu iconButtonElement={iconButtonElement}> <MenuItem onTouchTap={this.handleOpen}>Block</MenuItem> </IconMenu>} /> <Divider/> <Dialog title="Block your Followeres" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > Are you sure you want to Block this user?. </Dialog> </div> ); } }); export default othervisits;
react/features/mobile/navigation/functions.js
jitsi/jitsi-meet
import React from 'react'; import { useTranslation } from 'react-i18next'; import { Platform } from 'react-native'; import { IconClose } from '../../base/icons'; import HeaderNavigationButton from './components/HeaderNavigationButton'; /** * Close icon/text button based on platform. * * @param {Function} goBack - Goes back to the previous screen function. * @returns {React.Component} */ export function screenHeaderCloseButton(goBack: Function) { const { t } = useTranslation(); if (Platform.OS === 'ios') { return ( <HeaderNavigationButton label = { t('dialog.close') } onPress = { goBack } /> ); } return ( <HeaderNavigationButton onPress = { goBack } src = { IconClose } /> ); }
src/Parser/RestoDruid/Modules/Features/NaturesEssence.js
mwwscott0/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellLink from 'common/SpellLink'; import Module from 'Parser/Core/Module'; import SPELLS from 'common/SPELLS'; import Combatants from 'Parser/Core/Modules/Combatants'; const MINOR = 0.07; const AVERAGE = 0.12; const MAJOR = 0.17; class NaturesEssence extends Module { static dependencies = { combatants: Combatants, }; effectiveHealing = 0; overHealing = 0; on_initialized() { this.active = this.combatants.selected.traitsBySpellId[SPELLS.NATURES_ESSENCE_TRAIT.id] > 0; } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (SPELLS.NATURES_ESSENCE_DRUID.id === spellId) { this.effectiveHealing += event.amount + (event.absorbed || 0); this.overHealing += (event.overheal !== undefined ? event.overheal : 0); } } suggestions(when) { const overhealPercent = (this.overHealing + this.effectiveHealing !== 0) ? this.overHealing / (this.effectiveHealing + this.overHealing) : 0; when(overhealPercent).isGreaterThan(MINOR) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your overhealing from <SpellLink id={SPELLS.NATURES_ESSENCE_DRUID.id} /> is high. You may be casting <SpellLink id={SPELLS.WILD_GROWTH.id} /> when few raiders are injured, or you may be casting it before damage. Unlike our other HoTs, <SpellLink id={SPELLS.WILD_GROWTH.id} /> heals quickly and has a strong initial heal, so you should wait until damage has already happened to cast it.</span>) .icon(SPELLS.NATURES_ESSENCE_DRUID.icon) .actual(`${formatPercentage(overhealPercent)}% overhealing`) .recommended(`<${Math.round(formatPercentage(recommended))}% is recommended`) .regular(AVERAGE).major(MAJOR); }); } } export default NaturesEssence;
app/components/AddTask/GMaps/index.js
theterra/newsb
import React from 'react'; import './MapStyle.css'; let searchBox; export default class GMaps extends React.Component { //eslint-disable-line constructor(props) { super(props); this.geolocate = this.geolocate.bind(this); this.initAutocomplete = this.initAutocomplete.bind(this); this.searchBoxPlaces = this.searchBoxPlaces.bind(this); this.emitChanges = this.emitChanges.bind(this); } componentDidMount() { this.initAutocomplete(); } initAutocomplete() { searchBox = new google.maps.places.SearchBox( //eslint-disable-line document.getElementById('places-search')); searchBox.addListener('places_changed', () => { //eslint-disable-line this.searchBoxPlaces(searchBox); }); } geolocate() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { const geolocation = { lat: position.coords.latitude, lng: position.coords.longitude, }; const circle = new google.maps.Circle({ //eslint-disable-line center: geolocation, radius: position.coords.accuracy, }); console.log(circle.getBounds()); //eslint-disable-line searchBox.setBounds(circle.getBounds()); }); } } searchBoxPlaces(searchbox) { let pLat; let pLng; let address = ''; const places = searchbox.getPlaces(); places.forEach((place) => { pLat = place.geometry.location.lat(); pLng = place.geometry.location.lng(); address = place.formatted_address; }); this.props.pickupCord({ pLat, pLng }); if (places.length === 0) { window.alert('We did not find any places matching that search!'); //eslint-disable-line } const { pickup } = this.props.stateAddTask; this.emitChanges({ ...pickup, from_address: address }); } emitChanges(newFormState) { this.props.pickupChange(newFormState); } render() { return ( <div className="locationField"> <input id="places-search" placeholder="Search address" onFocus={this.geolocate} type="text" onChange={this.onChange} required /> </div> ); } }
src/js/components/Box.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import KeyboardAccelerators from '../utils/KeyboardAccelerators'; import Intl from '../utils/Intl'; import Props from '../utils/Props'; import { checkDarkBackground } from '../utils/DOM'; import SkipLinkAnchor from './SkipLinkAnchor'; import CSSClassnames from '../utils/CSSClassnames'; import { announce } from '../utils/Announcer'; const CLASS_ROOT = CSSClassnames.BOX; const BACKGROUND_COLOR_INDEX = CSSClassnames.BACKGROUND_COLOR_INDEX; /** * @description General purpose flexible box layout. This supports many, but not all, of the [flexbox](#) capabilities. * * @example * import Box from 'grommet/components/Box'; * * <Box direction='row' * justify='start' * align='center' * wrap={true} * pad='medium' * margin='small' * colorIndex='light-2' * onClick={...} * onFocus={...}> * <Value value={1} * colorIndex='accent-1' /> * <Box direction='row' * justify='start' * align='center' * wrap={true} * pad='medium' * margin='small' * colorIndex='light-1' * onClick={...} * onFocus={...}> * <Value value={2} /> * </Box> * <Box direction='row' * justify='start' * align='center' * wrap={true} * pad='medium' * margin='small' * colorIndex='light-1' * onClick={...} * onFocus={...}> * <Value value={3} /> * </Box> * </Box> * */ export default class Box extends Component { constructor (props) { super(props); this.state = { mouseActive: false }; } componentDidMount () { const { onClick } = this.props; if (onClick) { let clickCallback = () => { if (this.boxContainerRef === document.activeElement) { onClick(); } }; KeyboardAccelerators.startListeningToKeyboard(this, { enter: clickCallback, space: clickCallback }); } this._setDarkBackground(); } componentWillReceiveProps (nextProps) { if (nextProps.colorIndex !== this.props.colorIndex) { if (nextProps.colorIndex) { this.setState({ updateDarkBackground: true }); } else { this.setState({ darkBackground: undefined }); } } } componentDidUpdate () { if (this.props.announce) { announce(this.boxContainerRef.textContent); } if (this.state.updateDarkBackground) { this.setState({ updateDarkBackground: false }); this._setDarkBackground(); } } componentWillUnmount () { if (this.props.onClick) { KeyboardAccelerators.stopListeningToKeyboard(this); } if (this._checkBackground) { this._checkBackground.stop(); } } _setDarkBackground () { const { colorIndex } = this.props; const box = findDOMNode(this.boxContainerRef); if (this._checkBackground) { this._checkBackground.stop(); } this._checkBackground = checkDarkBackground(colorIndex, box, (darkBackground) => this.setState({ darkBackground })); } _normalize (string) { return string.replace('/', '-'); } _addPropertyClass (classes, property, options = {}) { const value = (options.object || this.props)[property]; const elementName = options.elementName || CLASS_ROOT; const prefix = options.prefix || property; if (value) { if (typeof value === 'string') { classes.push(`${elementName}--${prefix}-${this._normalize(value)}`); } else if (typeof value === 'object') { Object.keys(value).forEach((key) => { this._addPropertyClass(classes, key, { object: value, prefix: `${prefix}-${key}` }); }); } else { classes.push(`${elementName}--${this._normalize(prefix)}`); } } } _backgroundContextClass (darkBackground) { let result; if (undefined === darkBackground) { result = `${BACKGROUND_COLOR_INDEX}--pending`; } else if (darkBackground) { result = `${BACKGROUND_COLOR_INDEX}--dark`; } else { result = `${BACKGROUND_COLOR_INDEX}--light`; } return result; } render () { const { a11yTitle, appCentered, backgroundImage, children, className, colorIndex, containerClassName, focusable, full, id, onClick, onBlur, onFocus, onMouseDown, onMouseUp, pad, primary, role, size, tabIndex, tag, texture } = this.props; const { darkBackground, mouseActive } = this.state; let classes = [CLASS_ROOT]; let containerClasses = [`${CLASS_ROOT}__container`]; let restProps = Props.omit(this.props, Object.keys(Box.propTypes)); this._addPropertyClass(classes, 'full'); if (full && full.responsive === undefined) { // default is true for backwards compatibility sake classes.push(`${CLASS_ROOT}--full-responsive`); } this._addPropertyClass(classes, 'direction'); this._addPropertyClass(classes, 'justify'); this._addPropertyClass(classes, 'align'); this._addPropertyClass(classes, 'alignContent', { prefix: 'align-content' }); this._addPropertyClass(classes, 'alignSelf', { prefix: 'align-self' }); this._addPropertyClass(classes, 'reverse'); this._addPropertyClass(classes, 'responsive'); this._addPropertyClass(classes, 'basis'); this._addPropertyClass(classes, 'flex'); this._addPropertyClass(classes, 'pad'); this._addPropertyClass(classes, 'margin'); this._addPropertyClass(classes, 'separator'); this._addPropertyClass(classes, 'textAlign', { prefix: 'text-align' }); this._addPropertyClass(classes, 'wrap'); if (this.props.hasOwnProperty('flex')) { if (! this.props.flex) { classes.push(`${CLASS_ROOT}--flex-off`); } } if (size) { if (typeof size === 'object') { Object.keys(size).forEach((key) => { this._addPropertyClass(classes, key, { object: size }); }); } else { this._addPropertyClass(classes, 'size'); } if (size) { if (!(size.width && size.width.max)) { // don't apply 100% max-width when size using size.width.max option classes.push(`${CLASS_ROOT}--size`); } if (size.width && size.width.max) { // allow widths to shrink, apply 100% width classes.push(`${CLASS_ROOT}--width-max`); } } } // needed to properly set flex-basis for 1/3 & 2/3 basis boxes if (pad && pad.between && children) { if (React.Children.count(children) % 3 === 0) { classes.push(`${CLASS_ROOT}--pad-between-thirds`); } } if (appCentered) { this._addPropertyClass(containerClasses, 'full', { elementName: `${CLASS_ROOT}__container` }); if (colorIndex) { containerClasses.push(`${BACKGROUND_COLOR_INDEX}-${colorIndex}`); containerClasses.push(this._backgroundContextClass(darkBackground)); } if (containerClassName) { containerClasses.push(containerClassName); } } else if (colorIndex) { classes.push(`${BACKGROUND_COLOR_INDEX}-${colorIndex}`); classes.push(this._backgroundContextClass(darkBackground)); } let a11yProps = {}; let clickableProps = {}; if (onClick) { classes.push(CLASS_ROOT + "--clickable"); clickableProps = { onMouseDown: (event) => { this.setState({ mouseActive: true }); if (onMouseDown) { onMouseDown(event); } }, onMouseUp: (event) => { this.setState({ mouseActive: false }); if (onMouseUp) { onMouseUp(event); } }, onFocus: (event) => { if (mouseActive === false) { this.setState({ focus: true }); } if (onFocus) { onFocus(event); } }, onBlur: (event) => { this.setState({ focus: false }); if (onBlur) { onBlur(event); } } }; if (focusable) { if (this.state.focus) { classes.push(`${CLASS_ROOT}--focus`); } let boxLabel = (typeof a11yTitle !== 'undefined') ? a11yTitle : Intl.getMessage(this.context.intl, 'Box'); a11yProps.tabIndex = tabIndex || 0; a11yProps["aria-label"] = this.props['aria-label'] || boxLabel; a11yProps.role = role || 'group'; } } let skipLinkAnchor; if (primary) { let mainContentLabel = ( Intl.getMessage(this.context.intl, 'Main Content') ); skipLinkAnchor = <SkipLinkAnchor label={mainContentLabel} />; } if (className) { classes.push(className); } let style = {}; if (texture && 'string' === typeof texture) { if (texture.indexOf('url(') !== -1) { style.backgroundImage = texture; } else { style.backgroundImage = `url(${texture})`; } } else if (backgroundImage) { style.background = backgroundImage + " no-repeat center center"; style.backgroundSize = "cover"; } style = {...style, ...restProps.style}; let textureMarkup; if ('object' === typeof texture) { textureMarkup = ( <div className={CLASS_ROOT + "__texture"}>{texture}</div> ); } const Component = tag; if (appCentered) { return ( <div {...restProps} ref={(ref) => this.boxContainerRef = ref} className={containerClasses.join(' ')} style={style} role={role} {...a11yProps} {...clickableProps}> {skipLinkAnchor} <Component id={id} className={classes.join(' ')}> {textureMarkup} {children} </Component> </div> ); } else { return ( <Component {...restProps} ref={(ref) => this.boxContainerRef = ref} id={id} className={classes.join(' ')} style={style} role={role} tabIndex={tabIndex} onClick={onClick} {...a11yProps} {...clickableProps}> {skipLinkAnchor} {textureMarkup} {children} </Component> ); } } } const FIXED_SIZES = ['xsmall', 'small', 'medium', 'large', 'xlarge', 'xxlarge']; const RELATIVE_SIZES = ['full', '1/2', '1/3', '2/3', '1/4', '3/4']; const SIZES = FIXED_SIZES.concat(RELATIVE_SIZES); const MARGIN_SIZES = ['small', 'medium', 'large', 'none']; const PAD_SIZES = ['small', 'medium', 'large', 'xlarge', 'none']; Box.propTypes = { /** * @property {PropTypes.string} a11yTitle - Custom title used by screen readers. Defaults to 'Box'. Only used if onClick handler is specified. */ a11yTitle: PropTypes.string, announce: PropTypes.bool, /** * @property {start|center|end|baseline|stretch} align - How to align the contents along the cross axis. */ align: PropTypes.oneOf(['start', 'center', 'end', 'baseline', 'stretch']), /** * @property {start|center|end|between|around|stretch} alignContent - How to align the contents when there is extra space in the cross axis. Defaults to stretch */ alignContent: PropTypes.oneOf(['start', 'center', 'end', 'between', 'around', 'stretch']), /** * @property {start|center|end|stretch} alignSelf - How to align within its container along the cross axis. */ alignSelf: PropTypes.oneOf(['start', 'center', 'end', 'stretch']), /** * @property {PropTypes.bool} appCentered - Whether the box background should stretch across an App that is centered. */ appCentered: PropTypes.bool, backgroundImage: PropTypes.string, /** * @property {SIZES} basis - Whether to use a fixed or relative size within its container. */ basis: PropTypes.oneOf(SIZES), /** * @property {PropTypes.string} colorIndex - The color identifier to use for the background color. For example: 'neutral-1'. See Color for possible values. */ colorIndex: PropTypes.string, containerClassName: PropTypes.string, /** * @property {row|column} direction - The orientation to layout the child components in. Defaults to column. */ direction: PropTypes.oneOf(['row', 'column']), /** * @property {PropTypes.bool} focusable - Whether keyboard focus should be added for clickable Boxes. Defaults to true. */ focusable: PropTypes.bool, /** * @property {grow|shrink|true|false} flex - Whether flex-grow and/or flex-shrink is true. */ flex: PropTypes.oneOf(['grow', 'shrink', true, false]), /** * @property {PropTypes.bool|PropTypes.string|PropTypes.shape} full - Whether the width and/or height should take the full viewport size.] */ full: PropTypes.oneOfType( [ PropTypes.bool, PropTypes.string, PropTypes.shape({ vertical: PropTypes.bool, horizontal: PropTypes.bool, responsive: PropTypes.bool }) ] ), /** * @property {PropTypes.func} onClick - Optional click handler. */ // remove in 1.0? onClick: PropTypes.func, /** * @property {start|center|between|end|around} justify - How to align the contents along the main axis. */ justify: PropTypes.oneOf(['start', 'center', 'between', 'end', 'around']), /** * @property {none|small|medium|large} margin - The amount of margin around the box. An object can be specified to distinguish horizontal margin, vertical margin, and margin on a particular side of the box: {horizontal: none|small|medium|large, vertical: none|small|medium|large, top|left|right|bottom: none|small|medium|large}. Defaults to none. */ margin: PropTypes.oneOfType([ PropTypes.oneOf(MARGIN_SIZES), PropTypes.shape({ bottom: PropTypes.oneOf(MARGIN_SIZES), horizontal: PropTypes.oneOf(MARGIN_SIZES), left: PropTypes.oneOf(MARGIN_SIZES), right: PropTypes.oneOf(MARGIN_SIZES), top: PropTypes.oneOf(MARGIN_SIZES), vertical: PropTypes.oneOf(MARGIN_SIZES) }) ]), /** * @property {none|small|medium|large} pad - The amount of padding to put around the contents. An object can be specified to distinguish horizontal padding, vertical padding, and padding between child components: {horizontal: none|small|medium|large, vertical: none|small|medium|large, between: none|small|medium|large}. Defaults to none. Padding set using between only affects components based on the direction set (adds horizontal padding between components for row, or vertical padding between components for column). */ pad: PropTypes.oneOfType([ PropTypes.oneOf(PAD_SIZES), PropTypes.shape({ between: PropTypes.oneOf(PAD_SIZES), horizontal: PropTypes.oneOf(PAD_SIZES), vertical: PropTypes.oneOf(PAD_SIZES) }) ]), /** * @property {PropTypes.bool} primary - Whether this is a primary Box that will receive skip to main content anchor. Defaults to false. */ primary: PropTypes.bool, /** * @property {PropTypes.bool} reverse - Whether to reverse the order of the child components. */ reverse: PropTypes.bool, /** * @property {PropTypes.bool} responsive - Whether children laid out in a row direction should be switched to a column layout when the display area narrows. Defaults to true. */ responsive: PropTypes.bool, role: PropTypes.string, /** * @property {top|bottom|left|right|horizontal|vertical|all|none} separator - Add a separator. */ separator: PropTypes.oneOf(['top', 'bottom', 'left', 'right', 'horizontal', 'vertical', 'all', 'none']), /** * @property {auto|xsmall|small|medium|large|xlarge|xxlarge|full|PropTypes.object} size - The width of the Box. Defaults to auto. An object can be specified to distinguish width, height (with additional min and max options for width and height). E.g. {height: small, width: {max: large}}. */ size: PropTypes.oneOfType([ PropTypes.oneOf(['auto', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'xxlarge', 'full']), // remove in 1.0?, use basis PropTypes.shape({ height: PropTypes.oneOfType([ PropTypes.oneOf(SIZES), PropTypes.shape({ max: PropTypes.oneOf(FIXED_SIZES), min: PropTypes.oneOf(FIXED_SIZES) }) ]), width: PropTypes.oneOfType([ PropTypes.oneOf(SIZES), PropTypes.shape({ max: PropTypes.oneOf(FIXED_SIZES), min: PropTypes.oneOf(FIXED_SIZES) }) ]) }) ]), /** * @property {PropTypes.string} tag - The DOM tag to use for the element. Defaults to div. */ tag: PropTypes.string, /** * @property {left|center|right} textAlign - Set text-align for the Box contents. */ textAlign: PropTypes.oneOf(['left', 'center', 'right']), /** * @property {PropTypes.node|PropTypes.string} texture - A texture image URL to apply to the background. */ texture: PropTypes.oneOfType([ PropTypes.node, PropTypes.string ]), /** * @property {PropTypes.bool} wrap - Whether children can wrap if they can't all fit. Defaults to false. */ wrap: PropTypes.bool }; Box.contextTypes = { intl: PropTypes.object }; Box.defaultProps = { announce: false, direction: 'column', pad: 'none', tag: 'div', responsive: true, focusable: true };
packages/material-ui-icons/src/Timer3.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33.22-.08.46-.12.73-.12.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57-.17.16-.38.28-.63.37-.25.09-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36-.17-.16-.3-.34-.39-.56-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23.49-.15.91-.38 1.26-.68.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39s.03-.28.09-.41c.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.68.23.96c.15.28.37.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z" /></g> , 'Timer3');
ui/me/index.js
DannyvanderJagt/portfolio
import React from 'react'; import Telescope from 'telescope'; import Config from '../../../portfolio.config'; import Button from '../button'; import Svg from '../svg'; class Me extends Telescope.Component{ render(){ return ( <div className='me'> <div className='image'> <img src='/assets/images/me.jpg'/> </div> <div className='title'>Danny van der Jagt </div> <div className='subtitle'>A passionated person</div> <div className='description'> Hello! I’m a javascript developer who is interested in everything from front-end to backend and IOT. I'm also a hobby photographer and windsurfer for life! </div> <a href='/danny'> <Button> Read more </Button> </a> or <a href={Config.socialmedia.twitter}> <Svg name='twitter'/> </a> </div> ); } }; export default Me;
app/resources/author/views/Login.react.js
shiminghua/front_end_practice
'use strict'; import React, { Component } from 'react'; import InputText from '../../../components/inputs/InputText.react'; import InputPassword from '../../../components/inputs/InputPassword.react'; import '../../../browser/javascript/mui'; class Login extends Component { constructor(props) { super(props); this.state = { name: '', pass: '' }; } handleChange(event) { let newState = {}; newState[event.target.name] = event.target.value; this.setState(newState); } handleSubmit(event) { event.preventDefault(); console.log(this.state); mui.ajax('/author/login', { type: 'post', data: this.state, dataType: 'json', success: function(data) { if(data.code === 200) { console.log('login success'); window.location.href = '/'; } else { console.log(data.message); } }, error: function() { console.log('login error'); } }); } render() { return ( <form onSubmit={this.handleSubmit.bind(this)}> <InputText className='' name='name' onChange={this.handleChange.bind(this)} placeholder='请输入手机号码或邮箱' /> <InputPassword className='' name='pass' onChange={this.handleChange.bind(this)} placeholder='请输入密码' /> <button type="submit">提交</button> </form> ); } } export default Login;
client/app/components/Settings.Vendors.js
jfanderson/KIM
import React from 'react'; import h from '../helpers.js'; import v from '../services/vendorService.js'; import sign from '../services/sign.js'; import AddVendorForm from './Form.AddVendor.js'; import Cell from './Cell.js'; import Column from './Column.js'; import Table from './Table.js'; class VendorSettings extends React.Component { constructor() { super(); this.state = { vendors: [], removeMode: false, isAddVendorFormOpen: false }; } componentDidMount() { this._updateVendors(); } //----------------------------------- // RENDERING //----------------------------------- render() { return ( <div> <h2 className="with-button" ref={h2 => { this._vendorTitle = h2; }}>Vendors</h2> <button className="add-button inner" onClick={this._handleAddClick.bind(this)}>+</button> <button className="remove-button inner" onClick={this._handleRemoveModeClick.bind(this)}>--</button> <Table classes="inner" data={this.state.vendors} uniqueId="company"> <Column header="Company" cell={vendor => ( <Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'company')}>{vendor.company}</Cell> )} /> <Column header="Address" cell={vendor => ( <Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'address')}>{vendor.address}</Cell> )} /> <Column header="Phone" cell={vendor => ( <Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'phone')}>{vendor.phone}</Cell> )} /> <Column header="Email" cell={vendor => ( <Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'email')}>{vendor.email}</Cell> )} /> {this._renderVendorRemoveColumn()} </Table> {this._renderAddVendorForm()} </div> ); } _renderAddVendorForm() { if (this.state.isAddVendorFormOpen) { return ( <AddVendorForm cancel={this._handleAddClick.bind(this)} submit={this._handleVendorSubmit.bind(this)} top={h.findPopupTopValue(this._vendorTitle)} /> ); } } _renderVendorRemoveColumn() { if (this.state.removeMode) { return ( <Column header="Remove" cell={vendor => ( <Cell className="remove"><div onClick={this._removeVendor.bind(this, vendor)}>X</div></Cell> )} /> ); } } //----------------------------------- // PRIVATE METHODS //----------------------------------- _handleAddClick(event) { if (event) { event.preventDefault(); } this.setState({ isAddVendorFormOpen: !this.state.isAddVendorFormOpen }); } _handleRemoveModeClick() { this.setState({ removeMode: !this.state.removeMode }); } _handleVendorSubmit(vendor) { v.addVendor(vendor).then(() => { this._updateVendors(); }).catch(() => { sign.setError('Failed to add new vendor.'); }); } _modifyVendor(vendorId, key, value) { let vendors = this.state.vendors; for (let i = 0; i < vendors.length; i++) { if (vendors[i].id === vendorId) { vendors[i][key] = value; break; } } this.setState({ vendors }); v.modifyVendor(vendorId, key, value) .catch(() => { sign.setError('Failed to modify vendor. Try refreshing.'); this.state.vendors = null; }); } _removeVendor(vendor) { let confirmed = confirm(`Are you sure you want to remove ${vendor.company}?`); if (confirmed) { v.removeVendor(vendor.id).then(() => { this._updateVendors(); }).catch(() => { sign.setError('Failed to remove vendor.'); }); } } _updateVendors() { v.getVendors().then(vendors => { this.setState({ vendors }); }).catch(() => { sign.setError('Failed to retrieve vendors. Try refreshing.'); }); } } export default VendorSettings;
src/app.js
gj262/my-react-redux-starter-kit
import 'babel-polyfill' import React from 'react' import ReactDOM from 'react-dom' import routes from './routes' import Root from './containers/Root' import { browserHistory } from 'react-router' import { syncHistory, routeReducer } from 'redux-simple-router' import thunkMiddleware from 'redux-thunk' import reducers from './reducers' import { applyMiddleware, createStore, combineReducers } from 'redux' const reducer = combineReducers(Object.assign({}, reducers, { routing: routeReducer })) const reduxRouterMiddleware = syncHistory(browserHistory) const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware, thunkMiddleware)(createStore) const store = createStoreWithMiddleware(reducer) // Render the React application to the DOM ReactDOM.render( <Root history={browserHistory} routes={routes} store={store} />, document.getElementById('root') )
packages/mcs-lite-landing-web/src/containers/Section1/Chart.js
MCS-Lite/mcs-lite
import React from 'react'; import styled from 'styled-components'; import rafThrottle from 'raf-throttle'; import TweenOne from 'rc-tween-one'; import Heading from 'mcs-lite-ui/lib/Heading'; import last from 'ramda/src/last'; import DataPointAreaChart from 'mcs-lite-ui/lib/DataPointAreaChart'; import localTimeFormat from 'mcs-lite-ui/lib/utils/localTimeFormat'; import { IMAGE_WIDTH } from './styled-components'; const Wrapper = styled.div` display: flex; bottom: 0; width: ${IMAGE_WIDTH}px; padding-right: 55px; box-sizing: border-box; > * { background: white; } `; const ChartWrapper = styled.div` width: 420px; height: 120px; transform: translateY(29px); margin-left: 31px; `; const StyledHeading = styled(Heading)` font-size: 18px; text-align: center; width: 68px; margin-left: 94px; margin-right: 20px; margin-top: 62px; margin-bottom: 25px; `; function getRandomValue(min = 20, max = 35, digits = 2) { return Number((Math.random() * (max - min) + min).toFixed(digits)); } class Chart extends React.PureComponent { state = { data: [ { value: 21, updatedAt: '2017-01-13 00:00' }, { value: 24, updatedAt: '2017-01-13 00:00' }, { value: 21, updatedAt: '2017-01-13 00:00' }, { value: 28, updatedAt: '2017-02-13 00:01' }, { value: 25, updatedAt: '2017-02-13 00:01' }, { value: 25.2, updatedAt: '2017-02-13 00:01' }, { value: 28, updatedAt: '2017-03-13 00:02' }, { value: 28.1, updatedAt: '2017-03-13 00:02' }, { value: 21.3, updatedAt: '2017-03-13 00:02' }, { value: 23, updatedAt: '2017-04-13 00:04' }, { value: 24.3, updatedAt: '2017-04-13 00:04' }, { value: 24, updatedAt: '2017-04-13 00:04' }, { value: 20, updatedAt: '2017-05-13 00:05' }, { value: 21.5, updatedAt: '2017-05-13 00:05' }, { value: 24.5, updatedAt: '2017-06-13 00:06' }, ], }; componentDidMount() { this.timeout = setTimeout(() => { this.interval = setInterval(this.appendData, 1500); }, 1000); } componentWillUnmount() { clearInterval(this.interval); clearTimeout(this.timeout); this.appendData.cancel(); } appendData = rafThrottle(() => { this.setState({ data: [ ...this.state.data.slice(1), { value: getRandomValue(), updatedAt: localTimeFormat(new Date()), }, ], }); }); render() { const { data } = this.state; return ( <TweenOne animation={{ opacity: 1, duration: 550, }} style={{ opacity: 0, }} component={Wrapper} > <StyledHeading color="primary">{last(data).value}</StyledHeading> <ChartWrapper> <DataPointAreaChart isAnimationActive data={data} /> </ChartWrapper> </TweenOne> ); } } export default Chart;
fields/types/azurefile/AzureFileColumn.js
dvdcastro/keystone
import React from 'react'; var AzureFileColumn = React.createClass({ renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; return <a href={value.url} target="_blank">{value.url}</a>; }, render () { return ( <td className="ItemList__col"> <div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div> </td> ); }, }); module.exports = AzureFileColumn;
src/router.js
DanielHabib/onboarding
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/http'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; 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('/contact', async () => <ContactPage />); 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;
client/src/components/CoursesPage.js
yegor-sytnyk/contoso-express
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../actions/courseActions'; import {departmentSelectListItem} from '../formatters/entityFromatter'; import CoursesList from './courses/CoursesList'; import CourseSave from './courses/CourseSave'; import CourseDetails from './courses/CourseDetails'; import CourseDelete from './courses/CourseDelete'; import CoursesFilter from './courses/CoursesFilter'; class CoursesPage extends React.Component { constructor(props, context) { super(props, context); this.state = { courses: props.courses, selectedDepartmentId: '', saveModalVisible: false, detailsModalVisible: false, confirmationVisible: false }; this.changeDepartmentState = this.changeDepartmentState.bind(this); this.showSaveModal = this.showSaveModal.bind(this); this.closeSaveModal = this.closeSaveModal.bind(this); this.filterCourses = this.filterCourses.bind(this); this.showDetailsModal = this.showDetailsModal.bind(this); this.closeDetailsModal = this.closeDetailsModal.bind(this); this.showConfirmationModal = this.showConfirmationModal.bind(this); this.closeConfirmationModal = this.closeConfirmationModal.bind(this); } componentWillMount() { this.props.loadCourses(); } changeDepartmentState(event) { let departmentId = event.target.value; return this.setState({selectedDepartmentId: departmentId}); } filterCourses() { this.props.actions.loadCourses(this.state.selectedDepartmentId); } showSaveModal(courseId) { this.props.actions.loadCourse(courseId) .then(() => { this.setState({saveModalVisible: true}); }); } closeSaveModal() { this.setState({saveModalVisible: false}); } showDetailsModal(courseId) { this.props.actions.loadCourse(courseId) .then(() => { this.setState({detailsModalVisible: true}); }); } closeDetailsModal() { this.setState({detailsModalVisible: false}); } showConfirmationModal(courseId) { this.props.actions.loadCourse(courseId) .then(() => { this.setState({confirmationVisible: true}); }); } closeConfirmationModal() { this.setState({confirmationVisible: false}); } render() { return ( <div className="container"> <h2>Courses</h2> <a href="#" onClick={this.showSaveModal}>Create New</a> <CoursesFilter departmentId={this.state.selectedDepartmentId} departments={this.props.departments} onChange={this.changeDepartmentState} onClick={this.filterCourses} /> <CoursesList courses={this.props.courses} onSaveClick={this.showSaveModal} onDetailsClick={this.showDetailsModal} onDeleteClick={this.showConfirmationModal} /> <CourseSave visible={this.state.saveModalVisible} close={this.closeSaveModal} /> <CourseDetails visible={this.state.detailsModalVisible} close={this.closeDetailsModal} /> <CourseDelete visible={this.state.confirmationVisible} close={this.closeConfirmationModal} /> </div > ); } } CoursesPage.propTypes = { courses: React.PropTypes.array.isRequired, actions: React.PropTypes.object.isRequired }; function mapStateToProps(state) { return { courses: state.course.list, departments: departmentSelectListItem(state.department.list) }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch), loadCourses: () => courseActions.loadCourses(null)(dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
admin/client/App/screens/Item/components/FormHeading.js
snowkeeper/keystone
import React from 'react'; import evalDependsOn from '../../../../../../fields/utils/evalDependsOn'; module.exports = React.createClass({ displayName: 'FormHeading', propTypes: { options: React.PropTypes.object, }, render () { if (!evalDependsOn(this.props.options.dependsOn, this.props.options.values)) { return null; } return <h3 className="form-heading">{this.props.content}</h3>; }, });
src/components/Header/Header.js
FAN-CUK/official
import React from 'react'; import FontAwesome from 'react-fontawesome'; import classNames from 'classnames'; import { Link } from 'react-router'; import MenuItem from './MenuItem'; import css from './Header.css'; class Header extends React.Component { render() { const c = [ { name : "김수연조", boardId : 1 }, { name : "유용우조", boardId : 2 }, { name : "김소연조", boardId : 300 }, { name : "이소정조", boardId : 45} ]; const cplus = [ { name : "김수연조", boardId : 1 }, { name : "유용우조", boardId : 2 }, { name : "김소연조", boardId : 300 } ]; const web = [ { name : "김수연조", boardId : 1 }, { name : "유용우조", boardId : 2 }, ]; const java = [ { name : "김수연조", boardId : 1 }, { name : "유용우조", boardId : 2 }, { name : "김소연조", boardId : 300 }, { name : "이소정조", boardId : 45}, { name : "이종원조", boardId : 20} ]; const datastructure = [ { name : "김수연조", boardId : 1 } ]; const mapToComponents = items => { return items.map((item, idx) => { return ( <MenuItem name={item.name} idx={item.boardId} key={idx} /> ); } ); } return( <header> <div className="container-fluid" id="header"> {/* Navigation */} <nav className={classNames(css.menu, "navbar", "navbar-fixed-top")} role="navigation"> <div className="container"> <div className={classNames("navbar-header", "page-scroll")}> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link className={classNames(css.logo, "page-scroll")} to='/#page-top'>F.A.N</Link> </div> {/* Collect the nav links, forms, and other content for toggling */} <div className={classNames("collapse", "navbar-collapse", "navbar-ex1-collapse")}> <ul className={classNames("nav", "navbar-nav", css.menuitem)}> <li><a href="#">Home</a></li> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" href="#">Board<span className="caret"></span></a> <ul className={classNames("dropdown-menu", css.mdd, css.boarddrop)}> <li><a href="#">Notice</a></li> <li><a href="#">Question</a></li> <li> <Link to='/board'>Free Board</Link> </li> <li><a href="#">Library</a></li> </ul> </li> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" href="#">Study<span className="caret"></span></a> <ul className={classNames("dropdown-menu", "multi-level", css.mdd, css.studydrop)}> <li className={css.st}> <p className="text-center">C</p> <ul className={classNames("text-center", css.studydbdrop)}> { mapToComponents(c) } </ul> </li> <li className={css.st}> <p className="text-center">C++</p> <ul className={classNames("text-center", css.studydbdrop)}> {mapToComponents(cplus)} </ul> </li> <li className={css.st}> <p className="text-center">Web</p> <ul className={classNames("text-center", css.studydbdrop)}> { mapToComponents(web) } </ul> </li> <li className={css.st}> <p className="text-center">Java</p> <ul className={classNames("text-center", css.studydbdrop)}> { mapToComponents(java) } </ul> </li> <li className={css.st}> <p className="text-center">자료구조</p> <ul className={classNames("text-center", css.studydbdrop)}> { mapToComponents(datastructure) } </ul> </li> </ul> </li> <li><a href="#">Gallery</a></li> </ul> <ul className={classNames("nav", "navbar-nav", "navbar-right", css.loginInfo)}> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" href="#"><FontAwesome name="sign-in"/>My Info</a> <div id="info_viewer" className={classNames("panel", "panel-info", "dropdown-menu")}> <div className="panel-heading"> <h3 className="panel-title"><span id = "v_title_kr">정보</span> <span id = "v_title_en">My Info</span></h3> </div> <div className="panel-body"> <div id = "user_level" className="alert alert-info" role="alert">회원등급</div> <ul className="list-group"> <li className="list-group-item">이름 : ㅇㅁㅇ</li> <li className="list-group-item">전공 : 컴공</li> <li className="list-group-item">학번 : 123456789</li> <li className="list-group-item">상태 : 휴학</li> <li className="list-group-item"><a href="#"> 소속스터디 : C언어 </a></li> </ul> </div> </div> </li> <li><a href="#">Logout</a></li> </ul> </div> {/* /.navbar-collapse */} </div> {/* /.container */} </nav> </div> </header> ); } } export default Header;
src/base/ActionBar.js
WellerQu/rongcapital-ui
/* 一种另类的尝试 */ import React from 'react'; import clazz from 'classnames'; import PropTypes from 'prop-types'; import * as componentStyles from '../styles/base/actionBar.sass'; const ActionBar = ({ children }) => <ul className={ componentStyles['action-bar'] }>{ children }</ul>; ActionBar.Item = ({ children, right }) => <li className={ clazz({ [componentStyles.right]: right }) }>{ children }</li>; ActionBar.propTypes = { children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element) ]) }; ActionBar.Item.displayName = 'ActionBarItem'; ActionBar.Item.propTypes = { right: PropTypes.bool, children: PropTypes.any }; ActionBar.Item.defaultProps = { right: false }; export default ActionBar;
examples/dynamic-segments/app.js
brownbathrobe/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/expected.js
odapplications/WebView-with-Lower-Tab-Menu
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
src/svg-icons/editor/border-color.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderColor = (props) => ( <SvgIcon {...props}> <path d="M17.75 7L14 3.25l-10 10V17h3.75l10-10zm2.96-2.96c.39-.39.39-1.02 0-1.41L18.37.29c-.39-.39-1.02-.39-1.41 0L15 2.25 18.75 6l1.96-1.96z"/><path fillOpacity=".36" d="M0 20h24v4H0z"/> </SvgIcon> ); EditorBorderColor = pure(EditorBorderColor); EditorBorderColor.displayName = 'EditorBorderColor'; EditorBorderColor.muiName = 'SvgIcon'; export default EditorBorderColor;
src/parser/shared/modules/features/Checklist/PreparationRule.js
anom0ly/WoWAnalyzer
import { Trans } from '@lingui/macro'; import PropTypes from 'prop-types'; import React from 'react'; import Requirement from './Requirement'; import Rule from './Rule'; class PreparationRule extends React.PureComponent { static propTypes = { children: PropTypes.node, thresholds: PropTypes.object.isRequired, }; renderPotionRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={ <Trans id="shared.modules.features.checklist.combatPotionsUsed"> Combat potions used </Trans> } thresholds={thresholds.potionsUsed} /> <Requirement name={ <Trans id="shared.modules.features.checklist.highQualityCombatPotionsUsed"> High quality combat potions used </Trans> } thresholds={thresholds.bestPotionUsed} /> </> ); } renderEnchantRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={<Trans id="shared.modules.features.checklist.enchanted">All items enchanted</Trans>} thresholds={thresholds.itemsEnchanted} /> <Requirement name={ <Trans id="shared.modules.features.checklist.enchantedHigh"> Using high quality enchants </Trans> } thresholds={thresholds.itemsBestEnchanted} /> </> ); } renderWeaponEnhancementRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={<Trans>All weapons enhanced (oils/stones)</Trans>} thresholds={thresholds.weaponsEnhanced} /> <Requirement name={<Trans>Using high quality weapon enhancements</Trans>} thresholds={thresholds.bestWeaponEnhancements} /> </> ); } renderFlaskRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={ <Trans id="shared.modules.features.checklist.flaskHigh">High quality flask used</Trans> } thresholds={thresholds.higherFlaskPresent} /> <Requirement name={<Trans id="shared.modules.features.checklist.flask">Flask used</Trans>} thresholds={thresholds.flaskPresent} /> </> ); } renderFoodRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={ <Trans id="shared.modules.features.checklist.foodHigh">High quality food used</Trans> } thresholds={thresholds.higherFoodPresent} /> <Requirement name={<Trans id="shared.modules.features.checklist.food">Food used</Trans>} thresholds={thresholds.foodPresent} /> </> ); } renderAugmentRuneRequirements() { const { thresholds } = this.props; return ( <> <Requirement name={<Trans id="shared.modules.features.checklist.augmentRune">Augment rune used</Trans>} thresholds={thresholds.augmentRunePresent} /> </> ); } render() { const { children } = this.props; return ( <Rule name={<Trans id="shared.modules.features.checklist.wellPrepared">Be well prepared</Trans>} description={ <Trans id="shared.modules.features.checklist.wellPreparedDetails"> Being well prepared with food, flasks, potions and enchants is an easy way to improve your performance. </Trans> } > {this.renderEnchantRequirements()} {this.renderWeaponEnhancementRequirements()} {this.renderPotionRequirements()} {this.renderFlaskRequirements()} {this.renderFoodRequirements()} {this.renderAugmentRuneRequirements()} {children} </Rule> ); } } export default PreparationRule;
src/components/general/Error.js
OlivierVillequey/hackathon
/** * Error Screen * <Error text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Spacer, Text, Button } from '@ui/'; /* Component ==================================================================== */ const Error = ({ text, tryAgain }) => ( <View style={[AppStyles.container, AppStyles.containerCentered]}> <Icon name={'ios-alert-outline'} size={50} color={'#CCC'} /> <Spacer size={10} /> <Text style={AppStyles.textCenterAligned}>{text}</Text> <Spacer size={20} /> {!!tryAgain && <Button small outlined title={'Try again'} onPress={tryAgain} /> } </View> ); Error.propTypes = { text: PropTypes.string, tryAgain: PropTypes.func }; Error.defaultProps = { text: 'Woops, Something went wrong.', tryAgain: null }; Error.componentName = 'Error'; /* Export Component ==================================================================== */ export default Error;
src/svg-icons/action/watch-later.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionWatchLater = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z"/> </SvgIcon> ); ActionWatchLater = pure(ActionWatchLater); ActionWatchLater.displayName = 'ActionWatchLater'; ActionWatchLater.muiName = 'SvgIcon'; export default ActionWatchLater;
app/javascript/mastodon/components/missing_indicator.js
PlantsNetwork/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const MissingIndicator = () => ( <div className='regeneration-indicator missing-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> </div> ); export default MissingIndicator;
src/components/editor/TuningButton.js
calesce/tab-editor
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { head, last } from 'lodash'; import Popover from 'react-popover'; import { StyleSheet, css } from 'aphrodite'; import { tuningSelector } from '../../util/selectors'; import HoverableText from './HoverableText'; import { changeTuning } from '../../actions/track'; import { nextNote, previousNote, previousOctave, nextOctave } from '../../util/midiNotes'; const styles = StyleSheet.create({ hover: { ':hover': { MozUserSelect: 'none', WebkitUserSelect: 'none', msUserSelect: 'none', cursor: 'pointer', fill: '#b3caf5' }, fill: 'black' }, popover: { zIndex: 5, fill: '#FEFBF7', marginLeft: -20 }, popoverContainer: { display: 'flex', flexDirection: 'row', background: '#FEFBF7' }, arrowButtons: { display: 'flex', flexDirection: 'column', justifyContent: 'center', marginLeft: 5 }, stringsColumn: { display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', marginRight: 5 }, stringRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' }, textInput: { fontFamily: 'Optima, Segoe, Segoe UI, Candara, Calibri, Arial, sans-serif', margin: 5, width: 25, ':focus': { outline: 'none' } } }); const TuningIcon = ({ onClick }) => ( <svg onClick={onClick} width={60} height={50} className={css(styles.hover)}> <path d="M4.416 21.77c-1.058 0-1.916.858-1.916 1.916v3.704c0 1.058.858 1.917 1.916 1.917 1.058 0 1.916-.858 1.916-1.917v-.468h2.652v1.906c0 .575.367 1.328.82 1.683l5.355 4.185v7.07h9.42v-7.16l5.347-4.102c.457-.35.827-1.1.827-1.675v-1.906h2.65v.468c0 1.058.86 1.917 1.918 1.917 1.058 0 1.916-.858 1.916-1.917v-3.704c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.917.858-1.917 1.916v.57h-2.65v-8.52h2.65v.568c0 1.058.86 1.917 1.917 1.917 1.058 0 1.916-.857 1.916-1.916V12.6c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.917.858-1.917 1.916v.47h-2.65V8.678c0-.575-.43-.855-.955-.624l-9.01 3.945c-.528.23-1.383.23-1.91-.002l-8.943-3.94c-.527-.233-.953.046-.953.62v4.395H6.332v-.47c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.916.858-1.916 1.916v3.705c0 1.058.858 1.916 1.916 1.916 1.058 0 1.916-.857 1.916-1.915v-.57h2.652v8.523H6.332v-.572c0-1.058-.858-1.916-1.916-1.916z" /> </svg> ); class TuningStringInput extends Component { componentDidMount() { if (this.props.index === 0) { this.input.select(); } } removeString = () => { this.props.removeString(this.props.index); }; midiStringFromKeyCode(string, keyCode, shiftKey) { switch (keyCode) { case 37: return previousNote(string); case 38: return nextOctave(string); case 39: return nextNote(string); case 40: return previousOctave(string); default: { if (keyCode === 51 && shiftKey) { if (string[0] !== 'e' && string[0] !== 'b' && string.length === 2) { return string[0] + '#' + string[1]; } } else if (keyCode >= 48 && keyCode <= 57) { return string[0] + (keyCode - 48); } else if (keyCode >= 65 && keyCode <= 71) { return ( String.fromCharCode(keyCode).toLowerCase() + last(string.split('')) ); } return string; } } } onTextChanged = e => { const newString = this.midiStringFromKeyCode( this.props.string, e.keyCode, e.shiftKey ); if (newString !== this.props.string) { this.props.onChange(newString, this.props.index); } }; noop() { /* this exists to make React happy */ } setRef = el => { this.input = el; }; render() { return ( <span className={css(styles.stringRow)}> <input className={css(styles.textInput)} type="text" size={2} value={this.props.string} onChange={this.noop} onKeyDown={this.onTextChanged} ref={this.setRef} /> <HoverableText onClick={this.removeString} text="x" weight="normal" /> </span> ); } } class TuningPopover extends Component { constructor(props) { super(props); this.state = { tuning: [].concat(props.tuning) }; } componentWillUnmount() { this.props.changeTuning(this.state.tuning); } removeString = index => { this.setState({ tuning: this.state.tuning.filter( (_, i) => i !== this.state.tuning.length - 1 - index ) }); }; incrementAllStrings = () => { this.setState({ tuning: this.state.tuning.map(nextNote) }); }; decrementAllStrings = () => { this.setState({ tuning: this.state.tuning.map(previousNote) }); }; addTopString = () => { this.setState({ tuning: this.state.tuning.concat(last(this.state.tuning)) }); }; addBottomString = () => { this.setState({ tuning: [head(this.state.tuning)].concat(this.state.tuning) }); }; onChange = (newString, i) => { const { tuning } = this.state; const { length } = tuning; const newTuning = tuning .slice(0, length - 1 - i) .concat(newString) .concat(tuning.slice(length - i, length)); this.setState({ tuning: newTuning }); }; render() { const { tuning } = this.state; const tuningInputs = tuning .slice(0) .reverse() .map((string, i) => ( <TuningStringInput string={string} index={i} key={i} onChange={this.onChange} removeString={this.removeString} /> )); return ( <div className={css(styles.popoverContainer)}> <span className={css(styles.arrowButtons)}> <HoverableText onClick={this.incrementAllStrings} text="▲" /> <HoverableText onClick={this.decrementAllStrings} text="▼" /> </span> <div className={css(styles.stringsColumn)}> <HoverableText onClick={this.addTopString} text="+" weight="heavy" /> {tuningInputs} <HoverableText onClick={this.addBottomString} text="+" weight="heavy" /> </div> </div> ); } } const ConnectedPopover = connect(null, { changeTuning })(TuningPopover); class TuningButton extends Component { constructor() { super(); if (typeof window !== 'undefined') { window.addEventListener('keydown', this.handleKeyPress); } this.state = { popoverOpen: false }; } componentWillUnmount() { window.removeEventListener('keywdown', this.handleKeyPress); } handleKeyPress = e => { if (this.state.popoverOpen) { if (e.keyCode === 13) { // enter this.onPopoverClose(); } else if (e.keyCode === 27) { // escape // TODO make this cancel the tuning change instead of updating it this.onPopoverClose(); } else if (e.keyCode === 37 || e.keyCode === 39) { // left/right arrow e.preventDefault(); } } }; onClick = () => { if (this.state.popoverOpen) { this.onPopoverClose(); } else { this.props.onClick(); this.setState({ popoverOpen: true }); } }; onPopoverClose = () => { this.setState({ popoverOpen: false }); this.props.onClose(); }; render() { const { tuning } = this.props; const body = <ConnectedPopover tuning={tuning} />; return ( <div> <Popover preferPlace="right" className={css(styles.popover)} isOpen={this.state.popoverOpen} onOuterAction={this.onPopoverClose} body={body} > <TuningIcon onClick={this.onClick} /> </Popover> </div> ); } } export default connect(state => ({ tuning: tuningSelector(state) }))( TuningButton );
app/javascript/components/borrow_booking_calendar/BorrowBookingCalendar.js
leihs/leihs_legacy
import React from 'react' import createReactClass from 'create-react-class' import CalendarControls from './CalendarControls' import CalendarContent from './CalendarContent' import DateInput from './DateInput' const inspect = window.Tools.inspect const BorrowBookingCalendar = createReactClass({ displayName: 'BorrowBookingCalendar', propTypes: {}, getInitialState() { const todayDate = moment() const firstDateOfCurrentMonth = moment([todayDate.year(), todayDate.month(), 1]) return { todayDate: todayDate, firstDateOfCurrentMonth: firstDateOfCurrentMonth, startDate: this.props.initialStartDate, endDate: this.props.initialEndDate, selectedDate: null, quantity: (this.props.initialQuantity || 1), isLoading: true, calendarData: [], poolContext: this.props.inventoryPools[0] } }, componentDidMount() { this._fetchAndUpdateCalendarData(this._getLastDateInCalendarView(this.state.endDate)) }, _f: 'YYYY-MM-DD', _fetchAndUpdateCalendarData(toDate = null) { let fromDate if (_.isEmpty(this.state.calendarData)) { fromDate = this._getFirstDateInCalendarView(this.state.todayDate) } else { fromDate = _.last(this.state.calendarData) .date.clone() .add(1, 'day') } if (this.state.isLoading) { this._fetchAvailabilities( fromDate.format(this._f), toDate ? toDate.format(this._f) : this._getLastDateInCalendarView().format(this._f) ).done(data => { const newDates = _.map(data.list, avalObject => { return { date: moment(avalObject.d), availableQuantity: avalObject.quantity, visitsCount: avalObject.visits_count } }) this.setState(prevState => { return { isLoading: false, calendarData: prevState.calendarData.concat(newDates) } }) }) } }, _getFirstDateInCalendarView(date = null) { const firstDateOfMonth = date ? moment([date.year(), date.month()]) : this.state.firstDateOfCurrentMonth let daysShift = firstDateOfMonth.day() - 1 // in the default moment locale week starts on Sunday (index 0) if (daysShift == -1) { daysShift = 6 } return firstDateOfMonth.clone().subtract(daysShift, 'day') }, _getLastDateInCalendarView(date = null) { return this._getFirstDateInCalendarView(date) .clone() .add(41, 'day') }, _dropUntil(arr, func) { if (_.isEmpty(arr) || func(_.head(arr))) { return arr } else { return this._dropUntil(_.rest(arr), func) } }, _getDatesForCurrentMonthView() { const firstDate = this._getFirstDateInCalendarView() const arr1 = this._dropUntil(this.state.calendarData, el => { return el.date.isSame(firstDate) }) return _.take(arr1, 42) }, existingReservations() { // component used for editing existing reservations return (this.props.reservations.length != 0) }, // TODO: a single callback should be given to this component. // right now the component is used in different contextes, where // different callback chains apply: // 1. CREATE NEW RESERVATIONS (from models index; involves ajax post) // 1.1 `createReservations` -> `finishCallback` // 2. UPDATE EXISTING RESERVATIONS (from customer order; involves ajax post) // 2.1 `createReservations` -> `finishCallback` // 2.2 `deleteReservations` -> `finishCallback` // 2.3 `changeTimeRange` -> `finishCallback` // 2.3 `changeTimeRange` -> `createReservations` -> `finishCallback` // 2.3 `changeTimeRange` -> `deleteReservations` -> `finishCallback` // 3. PREPARE RESERVATIONS FOR CUSTOMER ORDER (from template wizard; does not involve ajax post) // 3.3 `exclusiveCallback` getOnClickCallback() { if (this.props.exclusiveCallback) { return () => { this.props.exclusiveCallback({ start_date: this.state.startDate.format(this._f), end_date: this.state.endDate.format(this._f), quantity: Number(this.state.quantity), inventory_pool_id: this.state.poolContext.inventory_pool.id }) } } else { let callback if (this.hasQuantityIncreased()) { callback = this.createReservations } else if (this.hasQuantityDecreased()) { callback = this.deleteReservations } else { callback = this.props.finishCallback } if (this.existingReservations() && this.hasTimeRangeChanged()) { return () => this.changeTimeRange(callback) } else { return callback } } }, changeTimeRange(successCallback) { $.ajax({ url: '/borrow/reservations/change_time_range', method: 'POST', dataType: 'json', data: { line_ids: _.map(this.props.reservations, (r) => r.id), start_date: this.state.startDate.format(this._f), end_date: this.state.endDate.format(this._f), inventory_pool_id: this.state.poolContext.inventory_pool.id }, success: successCallback, error: (xhr) => this.setState({serverError: xhr.responseText}) }) }, deleteReservations() { const reservation_ids = _.map(this.props.reservations, (r) => r.id) $.ajax({ url: '/borrow/reservations', method: 'DELETE', dataType: 'json', data: { line_ids: _.take(reservation_ids, (this.props.initialQuantity - this.state.quantity)) }, success: (data) => this.props.finishCallback(data), error: (xhr) => this.setState({serverError: xhr.responseText}) }) }, createReservations() { $.ajax({ url: '/borrow/reservations', method: 'POST', dataType: 'json', data: { start_date: this.state.startDate.format(this._f), end_date: this.state.endDate.format(this._f), model_id: this.props.model.id, inventory_pool_id: this.state.poolContext.inventory_pool.id, quantity: (this.state.quantity - this.props.initialQuantity) }, success: (data) => this.props.finishCallback(data), error: (xhr) => { this.setState({serverError: xhr.responseText}) } }) }, _fetchAvailabilities(startDate, endDate) { return $.ajax({ url: '/borrow/booking_calendar_availability', method: 'GET', dataType: 'json', data: { start_date: startDate, end_date: endDate, model_id: this.props.model.id, inventory_pool_id: this.state.poolContext.inventory_pool.id, reservation_ids: _.map(this.props.reservations, (r) => r.id) } }) }, _switchMonth(direction) { this.setState( prevState => { let firstDateOfMonth switch (direction) { case 'forward': firstDateOfMonth = prevState.firstDateOfCurrentMonth.add(1, 'month') break case 'backward': firstDateOfMonth = prevState.firstDateOfCurrentMonth.subtract(1, 'month') break default: throw new Error('invalid switch month direction') } const isLoading = !this._isLoadedUptoDate(this._getLastDateInCalendarView()) return { firstDateOfCurrentMonth: firstDateOfMonth, isLoading: isLoading } }, this._fetchAndUpdateCalendarData // second callback argument to setState ) }, _isLoadedUptoDate(date) { return _.any(_.map(this.state.calendarData, el => el.date), d => d.isSame(date)) }, _changeStartDate(sd) { const ed = sd.isAfter(this.state.endDate) ? sd : this.state.endDate this.setState({ startDate: sd, endDate: ed }) }, changeSelectedDate(date) { this.setState({ selectedDate: date }) }, jumpToStartDate() { const firstDateOfJumpMonth = moment([ this.state.startDate.year(), this.state.startDate.month(), 1 ]) this.setState({ firstDateOfCurrentMonth: firstDateOfJumpMonth }) }, jumpToEndDate() { const firstDateOfJumpMonth = moment([this.state.endDate.year(), this.state.endDate.month(), 1]) this.setState({ firstDateOfCurrentMonth: firstDateOfJumpMonth }) }, onClickPopoverStartDateCallback(sd) { const ed = this.state.endDate.isBefore(sd) ? sd : this.state.endDate this.setState({ startDate: sd, endDate: ed, selectedDate: null }) }, onClickPopoverEndDateCallback(ed) { const sd = this.state.startDate.isAfter(ed) ? ed : this.state.startDate this.setState({ endDate: ed, startDate: sd, selectedDate: null }) }, _changeEndDate(ed) { const sd = this.state.startDate.isAfter(ed) ? ed : this.state.startDate if (sd.isValid()) { const loadDate = this._getLastDateInCalendarView(ed) this.setState( { startDate: sd, endDate: ed, isLoading: !this._isLoadedUptoDate(loadDate) }, () => this._fetchAndUpdateCalendarData(loadDate) ) } }, _changeQuantity(event) { this.setState({ quantity: event.target.value }) }, _changeInventoryPool(event) { let toDate if (this.state.endDate.month() > this.state.firstDateOfCurrentMonth.month()) { toDate = this._getLastDateInCalendarView(this.state.endDate) } else { toDate = this._getLastDateInCalendarView(this.state.firstDateOfCurrentMonth) } this.setState( { calendarData: [], isLoading: true, poolContext: _.find( this.props.inventoryPools, ip => ip.inventory_pool.id == event.target.value ) }, () => this._fetchAndUpdateCalendarData(toDate) ) }, _goToNextMonth() { this._switchMonth('forward') }, _goToPreviousMonth() { this._switchMonth('backward') }, _isAvailableForDateRange() { const range = _.select( this.state.calendarData, el => el.date.isSameOrAfter(this.state.startDate) && el.date.isSameOrBefore(this.state.endDate) ) const maxAval = _.min(_.map(range, el => el.availableQuantity)) return this.state.quantity <= maxAval }, _isPoolOpenOn(date, workday = this.state.poolContext.workday) { const daysOfWeek = [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ] return workday[daysOfWeek[date.day()]] }, _isWithinAdvanceDaysPeriod(date, workday = this.state.poolContext.workday) { return date.isBefore( this.state.todayDate.clone().add(workday.reservation_advance_days || 0, 'day'), 'day' ) }, _poolHasStillCapacityFor(date) { const dateContext = _.find(this.state.calendarData, el => el.date.isSame(date, 'day')) return ( dateContext && ( this.state.poolContext.workday.max_visits[dateContext.date.day()] == null || dateContext.visitsCount < this.state.poolContext.workday.max_visits[dateContext.date.day()] ) ) }, getHoliday(date) { return _.find(this.state.poolContext.holidays, holiday => { return ( date.isSameOrAfter(moment(holiday.start_date), 'day') && date.isSameOrBefore(moment(holiday.end_date), 'day') ) }) }, getErrors() { let errors = [] if (this.state.serverError) { errors.push(this.state.serverError) } else if (!this.state.startDate.isValid() || !this.state.endDate.isValid()) { errors.push('Invalid date') } else if ( this.state.startDate.isBefore(this.state.todayDate, 'day') || this.state.endDate.isBefore(this.state.todayDate, 'day') ) { errors.push('Start and end date cannot be in the past') } else if (this.state.startDate.isAfter(this.state.endDate, 'day')) { errors.push('Start date must be before end date') } else { if (!this._isAvailableForDateRange()) { errors.push('Item is not available in that time range') } if (!this._isPoolOpenOn(this.state.startDate) || this.getHoliday(this.state.startDate)) { errors.push('Inventory pool is closed on start date') } if (!this._isPoolOpenOn(this.state.endDate) || this.getHoliday(this.state.endDate)) { errors.push('Inventory pool is closed on end date') } if (this._isWithinAdvanceDaysPeriod(this.state.startDate)) { errors.push('No orders are possible on this start date') } if (!this._poolHasStillCapacityFor(this.state.startDate)) { errors.push('Booking is no longer possible on this start date') } if (!this._poolHasStillCapacityFor(this.state.endDate)) { errors.push('Booking is no longer possible on this end date') } } return errors }, reloadCalendarContent() { this.setState( { serverError: null, isLoading: true, calendarData: [] }, this._fetchAndUpdateCalendarData ) }, _renderErrors(errors) { if (errors.length) { return ( <div id="booking-calendar-errors"> <div className="padding-horizontal-m padding-bottom-m"> <div className="row emboss red text-align-center font-size-m padding-inset-s"> <strong>{errors.push('') && errors.map(el => _jed(el)).join('. ')}</strong> </div> </div> </div> ) } else { return null } }, hasTimeRangeChanged() { return !( this.state.startDate.format(this._f) == this.props.initialStartDate.format(this._f) && this.state.endDate.format(this._f) == this.props.initialEndDate.format(this._f) ) }, hasQuantityDecreased() { return this.state.quantity < this.props.initialQuantity }, hasQuantityIncreased() { return this.state.quantity > this.props.initialQuantity }, hasQuantityChanged() { return (this.hasQuantityDecreased() || this.hasQuantityIncreased()) }, renderAddButton(errors) { const isEnabled = (errors.length == 0 && this.state.quantity > 0) return ( <button className="button green" id="submit-booking-calendar" onClick={this.getOnClickCallback()} disabled={!isEnabled}> {_jed('Add')} </button> ) }, renderContent() { let content if (this.state.isLoading) { content = ( <div> <div className="height-s" /> <div className="loading-bg" /> <div className="height-s" /> </div> ) } else if (this.state.serverError) { content = ( <div> <div className="height-s" /> <div style={{ textAlign: 'center' }}> <button className="button white large" onClick={this.reloadCalendarContent}> {_jed('click here to reload')} </button> </div> <div className="height-s" /> </div> ) } else { content = ( <CalendarContent startDate={this.state.startDate} endDate={this.state.endDate} quantity={this.state.quantity} dates={this._getDatesForCurrentMonthView()} currentMonth={this.state.firstDateOfCurrentMonth.month()} todayDate={this.state.todayDate} poolContext={this.state.poolContext} isPoolOpenOn={this._isPoolOpenOn} onClickPopoverStartDateCallback={this.onClickPopoverStartDateCallback} onClickPopoverEndDateCallback={this.onClickPopoverEndDateCallback} changeSelectedDate={this.changeSelectedDate} selectedDate={this.state.selectedDate} isWithinAdvanceDaysPeriod={this._isWithinAdvanceDaysPeriod} getHoliday={this.getHoliday} /> ) } return content }, render() { const errors = this.getErrors() return ( <div> <div className="modal-header row"> <div className="col3of5"> <h2 className="headline-l">{_jed('Add to order')}</h2> <h3 className="headline-m light"> {this.props.model.product} {this.props.model.version} </h3> </div> <div className="col2of5 text-align-right"> <div className="modal-close">{_jed('Cancel')}</div> {this.renderAddButton(errors)} </div> </div> {!this.state.isLoading && this._renderErrors(errors)} <div className="modal-body" style={{ maxHeight: '895.4px' }}> <form className="padding-inset-m"> <div className="" id="booking-calendar-controls"> <div className="col5of8 float-right"> <div className="row grey padding-bottom-xxs"> <div className="col1of2"> <div className="col1of2 padding-right-xs text-align-left"> <div className="row"> <span>{_jed('Start date')}</span> <a className="grey fa fa-eye position-absolute-right padding-right-xxs" id="jump-to-start-date" onClick={this.jumpToStartDate} /> </div> </div> <div className="col1of2 padding-right-xs text-align-left"> <div className="row"> <span>{_jed('End date')}</span> <a className="grey fa fa-eye position-absolute-right padding-right-xxs" id="jump-to-end-date" onClick={this.jumpToEndDate} /> </div> </div> </div> <div className="col1of2"> <div className="col2of8 text-align-left">{_jed('Quantity')}</div> <div className="col6of8 padding-left-xs text-align-left"> {_jed('Inventory pool')} </div> </div> </div> <div className="row"> <div className="col1of2"> <div className="col1of2 padding-right-xs"> <DateInput id="booking-calendar-start-date" dateString={this.state.startDate.format(i18n.date.L)} onChangeCallback={this._changeStartDate} /> </div> <div className="col1of2 padding-right-xs"> <DateInput id="booking-calendar-end-date" dateString={this.state.endDate.format(i18n.date.L)} onChangeCallback={this._changeEndDate} /> </div> </div> <div className="col1of2"> <div className="col2of8"> <input autoComplete="off" className="text-align-center" id="booking-calendar-quantity" type="number" max={this.state.poolContext.total_borrowable} defaultValue={this.state.quantity} onChange={this._changeQuantity} /> </div> <div className="col6of8 padding-left-xs"> <select autoComplete="off" className="min-width-full text-ellipsis" id="booking-calendar-inventory-pool" value={this.state.poolContext.inventory_pool.id} onChange={this._changeInventoryPool}> {_.map(this.props.inventoryPools, (ipContext, key) => { return ( <option key={key} data-id={ipContext.inventory_pool.id} value={ipContext.inventory_pool.id}> {ipContext.inventory_pool.name} (max. {ipContext.total_borrowable}) </option> ) })} </select> </div> </div> </div> </div> </div> <div className="booking-calendar padding-top-xs fc fc-ltr" id="booking-calendar"> <CalendarControls startDate={this.state.startDate} endDate={this.state.endDate} firstDateOfCurrentMonth={this.state.firstDateOfCurrentMonth} nextMonthCallback={this._goToNextMonth} previousMonthCallback={this._goToPreviousMonth} previousMonthExists={ (this.state.firstDateOfCurrentMonth.year() > this.state.todayDate.year()) || (this.state.firstDateOfCurrentMonth.month() != this.state.todayDate.month()) } /> {this.renderContent()} </div> </form> </div> <div className="modal-footer" /> </div> ) } }) export default BorrowBookingCalendar
src/App.js
sadist007/aladon
import React, { Component } from 'react'; import './App.scss'; class App extends Component { constructor (props) { super(props); this.state = this.getInitialState(); } getInitialState () { return {} } render () { return ( <div className="container-fluid"> <h4 data-selenium-id="wpng-header-prefix">6-2</h4> <h2 data-selenium-id="wpng-header-title">Apply Inventory Cost Flow Methods and Discuss Their Financial Effects</h2> </div> ); } } export default App;
src/js/wpecp-bind-editors.js
kfwebdev/wp-editor-comments-plus
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; var $ = jQuery; function bindCancelClick(editor, settings) { editor.windowManager.windows[0].on('click', function(event){ const clickText = $(event.target).text().toLowerCase(); if (clickText === 'cancel') { $.ajax({ url: wpecp.globals.ajaxUrl, type: 'post', data: $.param({ action: wpecp.globals.imageUploadCancelAction, attachmentId: settings.attachmentId, postId: settings.postId, security: settings.security }) }); } }); } var wpecpBindEditors = function() { // include edit component wpecp.Edit = require( '../components/edit/edit' ); // include delete component wpecp.Delete = require( '../components/delete/delete' ); // include editor component wpecp.Editor = require( '../components/editor/editor' ); wpecp.bindCancelClick = bindCancelClick; // bind button components $( wpecp.globals.wpecp_id_comment_reply ).each(function(){ const $editButton = $(this).siblings('.wpecp-edit'), $deleteButton = $(this).siblings('.wpecp-delete'); $(this).addClass(`${wpecp.globals.wpecp_css_button} ${wpecp.globals.wpecp_css_reply_button}`); if ($editButton.length) { const commentId = $editButton.data( wpecp.globals.wpecp_css_comment_id ), editId = wpecp.globals.wpecp_css_edit + commentId, editorId = wpecp.globals.wpecp_css_editor + commentId; ReactDOM.render( <wpecp.Edit wpecpGlobals={ wpecp.globals } commentId={ commentId } editId={ editId } editorId={ editorId } />, $editButton[0] ); } if ($deleteButton.length) { const commentId = $deleteButton.data( wpecp.globals.wpecp_css_comment_id ), deleteId = wpecp.globals.wpecp_css_delete + commentId, deleteNonce = $deleteButton.data( wpecp.globals.wpecp_css_nonce ); ReactDOM.render( <wpecp.Delete wpecpGlobals={ wpecp.globals } commentId={ commentId } deleteId={ deleteId } deleteNonce={ deleteNonce } />, $deleteButton[0] ); } }); // bind editor components $( '.' + wpecp.globals.wpecp_css_editor ).each(function(){ let commentId = $( this ).data( wpecp.globals.wpecp_css_comment_id ), contentId = wpecp.globals.wpecp_css_comment_content + commentId, editId = wpecp.globals.wpecp_css_edit + commentId, editorId = wpecp.globals.wpecp_css_editor + commentId, imageUploadNonce = $( this ).data( wpecp.globals.wpecp_image_upload_nonce ), postId = $( this ).data( wpecp.globals.wpecp_css_post_id ), updateNonce = $( this ).data( wpecp.globals.wpecp_css_nonce ); ReactDOM.render( <wpecp.Editor commentId={ commentId } contentId={ contentId } editId={ editId } editorId={ editorId } imageUploadNonce={ imageUploadNonce } postId={ postId } updateNonce={ updateNonce } wpecpGlobals={ wpecp.globals } />, this ); }); }; export default wpecpBindEditors;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js
amido/create-react-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(limit) { let i = 1; while (i <= limit) { yield { id: i, name: i }; i++; } } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { const users = []; for (let user of load(4)) { users.push(user); } this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-generators"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
new-lamassu-admin/src/pages/UserManagement/modals/FIDOModal.js
naconner/lamassu-server
import { makeStyles } from '@material-ui/core/styles' import React from 'react' import Modal from 'src/components/Modal' import { Button } from 'src/components/buttons' import { Info2, P } from 'src/components/typography' import styles from '../UserManagement.styles' const useStyles = makeStyles(styles) const ChangeRoleModal = ({ state, dispatch }) => { const classes = useStyles() const handleClose = () => { dispatch({ type: 'close', payload: 'showFIDOModal' }) } return ( <Modal closeOnBackdropClick={true} width={450} height={275} handleClose={handleClose} open={state.showFIDOModal}> <Info2 className={classes.modalTitle}>About FIDO authentication</Info2> <P className={classes.info}> This feature is only available for websites with configured domains, and we detected that a domain is not configured at the moment. </P> <P> Make sure that a domain is configured for this website and try again later. </P> <div className={classes.footer}> <Button className={classes.submit} onClick={() => handleClose()}> Confirm </Button> </div> </Modal> ) } export default ChangeRoleModal
node_modules/react-native-svg/elements/Path.js
MisterZhouZhou/ReactNativeLearing
import React from 'react'; import PropTypes from 'prop-types'; import createReactNativeComponentClass from 'react-native/Libraries/Renderer/shims/createReactNativeComponentClass.js'; import {PathAttributes} from '../lib/attributes'; import Shape from './Shape'; import {pathProps} from '../lib/props'; import extractProps from '../lib/extract/extractProps'; export default class extends Shape { static displayName = 'Path'; static propTypes = { ...pathProps, d: PropTypes.string.isRequired }; setNativeProps = (...args) => { this.root.setNativeProps(...args); }; render() { let props = this.props; return ( <RNSVGPath ref={ele => {this.root = ele;}} {...extractProps(props, this)} d={props.d} /> ); } } const RNSVGPath = createReactNativeComponentClass({ validAttributes: PathAttributes, uiViewClassName: 'RNSVGPath' });
src/components/common/svg-icons/notification/airline-seat-legroom-extra.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomExtra = (props) => ( <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/> </SvgIcon> ); NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra); NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra'; NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomExtra;
versions/v1/components/Debugger/Inspector/JSONInput/index.js
cerebral/cerebral-debugger-prototype
import React from 'react'; import styles from './styles.css'; import {connect} from 'cerebral-view-react'; import { isObject, isArray } from 'common/utils'; @connect() class JSONInput extends React.Component { constructor(props) { super(props); this.state = { isValid: true, value: this.props.value, initialValue: this.props.value }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount(prevProps, prevState) { this.refs.input.select(); } onChange(event) { let value = event.target.value; let isValid = true; let parsedValue = value; try { parsedValue = JSON.parse(value); } catch (e) { isValid = value.length ? true : false; } if (isObject(parsedValue) || isArray(parsedValue)) { return; } else { value = parsedValue; } this.setState({ value, isValid }); } onBlur() { this.setState({ value: this.state.initialValue }); this.props.onBlur(); } onSubmit(event) { event.preventDefault(); this.props.onSubmit(this.state.value); } render() { return ( <form style={{display: 'inline'}} onSubmit={this.onSubmit}> <input ref="input" type="Text" autoFocus onKeyDown={(event) => {event.keyCode === 27 && this.onBlur()}} className={this.state.isValid ? styles.input : styles.invalidInput} value={String(this.state.value)} onChange={this.onChange} onBlur={() => this.onBlur()} /> </form> ); } } export default JSONInput;
React Native/Demos/nearby/Nearby/views/toilet.js
AngryLi/ResourceSummary
/** * Created by Liyazhou on 16/9/6. */ import React from 'react'; import { View, StyleSheet, } from 'react-native'; export default class Toilet extends React.Component { render() { return ( <View></View> ) } } const styles= StyleSheet.create({ })
app/components/HorizonalBarChart/Bar.js
thuy616/react-d3-charts
import React from 'react'; import PropTypes from 'prop-types'; type Props = { data: PropTypes.object.isRequired, xScale: PropTypes.func.isRequired, yScale: PropTypes.func.isRequired, colorScale: PropTypes.func.isRequired } export default ({ data, xScale, yScale, colorScale }: Props) => { return ( <g className="horizontal-bar">> <rect y={yScale(data.name)} height={yScale.rangeBand()} x={0} width={xScale(data.value)} style={{ fill: `${colorScale(data.name)}`}} /> <text className="horizontal-bar-text" y={yScale(data.name) + yScale.rangeBand() / 2 + 4} x={xScale(data.value) + 25} textAnchor="end">{data.value}</text> </g> ); };
src/Input.js
cat-react/form
import React from 'react'; import PropTypes from 'prop-types'; import autoBind from 'react-autobind'; import Form from './Form'; export default function (WrappedComponent) { class Input extends React.Component { constructor(props, context) { super(props, context); this.changeValueTimer = null; this.dependencies = []; for (let dependency of props.dependencies) { this.addDependency(dependency); } this.state = { value: props.value, pristine: true, valid: false, messages: [] }; autoBind(this); for (let validation in props.validations) { const validationRule = Form.validationRules[validation]; if (validationRule && validationRule.createsDependencies) { if (!Array.isArray(props.validations[validation])) { this.addDependency(props.validations[validation]); } else { for (let dependency of props.validations[validation]) { this.addDependency(dependency); } } } } } componentWillMount() { this.context._reactForm.attach(this); } componentWillUnmount() { this.context._reactForm.detach(this); } addDependency(dependency) { if (dependency === this.getName()) { throw new Error('An input cannot have itself as an dependency. Check your validation rules.') } if (this.dependencies.indexOf(dependency) < 0) { this.dependencies.push(dependency); } } getName() { return this.props.name; } hasName(name) { return this.props.name === name; } isRequired() { return !!(this.props.validations && this.props.validations.isRequired); } isPristine() { return this.state.pristine; } isValid() { return this.state.valid; } getValue() { return this.state.value; } setValue(value, suppressTouch) { clearTimeout(this.changeValueTimer); this.context._reactForm.addToValidationQueue(this); this.setState({ value: value }, () => { const startValidation = () => { if (!suppressTouch) { this.touch(); } this.context._reactForm.startValidation(); }; let timeout = this.props.changeValueTimeout; if (timeout !== 0 && !timeout) { timeout = this.context._reactForm.changeValueTimeout; } if (timeout > 0) { this.changeValueTimer = setTimeout(startValidation, timeout); } else { startValidation(); } }); } getMessages() { return this.state.messages; } touch() { if (this.isPristine()) { this.setState({ pristine: false }); } } async validate() { return new Promise((resolve) => { this.runValidationRules(resolve); }); } async runValidationRules(resolve) { let messages = []; let allValid = true; if (this.isRequired() || this.getValue()) { for (let ruleName in this.props.validations) { const ruleConditions = this.props.validations[ruleName]; if (ruleConditions) { // only execute validations if the ruleConditions are valid const valid = await this.runValidationRule(ruleName); if (!valid) { const isWarning = this.props.warnings.indexOf(ruleName) > -1; if (!isWarning) { allValid = false; } if (this.props.messages && this.props.messages[ruleName]) { // TODO: add support for arguments, maybe even different errormessages per validator? messages.push(this.props.messages[ruleName]); } } } } } this.setState({ valid: allValid, messages: messages }, () => { resolve(allValid); }); } async runValidationRule(ruleName) { const ruleConditions = this.props.validations[ruleName]; let valid = true; if (Form.validationRules[ruleName]) { valid = await Form.validationRules[ruleName](this.context._reactForm.getValues(), this.getValue(), ruleConditions); } else if (typeof ruleConditions === 'function') { valid = await ruleConditions(this.context._reactForm.getValues(), this.getValue()); } else if (ruleConditions instanceof Array) { valid = await ruleConditions[0](this.context._reactForm.getValues(), this.getValue(), ruleConditions[1]); } return valid; } reset(value) { if (value || value === '' || value === null) { this.setValue(value, true); } else { this.setValue(this.props.value, true); } this.setState({ pristine: true }); } render() { const props = { ...this.props, isRequired: this.isRequired, isPristine: this.isPristine, isValid: this.isValid, getValue: this.getValue, setValue: this.setValue, getMessages: this.getMessages, touch: this.touch }; return ( <WrappedComponent {...props}/> ); } } Input.propTypes = { value: PropTypes.any, name: PropTypes.string.isRequired, validations: PropTypes.object, warnings: PropTypes.arrayOf(PropTypes.string), messages: PropTypes.object, dependencies: PropTypes.arrayOf(PropTypes.string), changeValueTimeout: PropTypes.number }; Input.defaultProps = { warnings: [], dependencies: [] }; Input.contextTypes = { _reactForm: PropTypes.object }; return Input; }
react/features/settings/components/web/audio/AudioSettingsPopup.js
gpolitis/jitsi-meet
// @flow import InlineDialog from '@atlaskit/inline-dialog'; import React from 'react'; import { areAudioLevelsEnabled } from '../../../../base/config/functions'; import { getAudioInputDeviceData, getAudioOutputDeviceData, setAudioInputDeviceAndUpdateSettings, setAudioOutputDevice as setAudioOutputDeviceAction } from '../../../../base/devices'; import { connect } from '../../../../base/redux'; import { SMALL_MOBILE_WIDTH } from '../../../../base/responsive-ui/constants'; import { getCurrentMicDeviceId, getCurrentOutputDeviceId } from '../../../../base/settings'; import { toggleAudioSettings } from '../../../actions'; import { getAudioSettingsVisibility } from '../../../functions'; import AudioSettingsContent, { type Props as AudioSettingsContentProps } from './AudioSettingsContent'; type Props = AudioSettingsContentProps & { /** * Component's children (the audio button). */ children: React$Node, /** * Flag controlling the visibility of the popup. */ isOpen: boolean, /** * Callback executed when the popup closes. */ onClose: Function, /** * The popup placement enum value. */ popupPlacement: string } /** * Popup with audio settings. * * @returns {ReactElement} */ function AudioSettingsPopup({ children, currentMicDeviceId, currentOutputDeviceId, isOpen, microphoneDevices, setAudioInputDevice, setAudioOutputDevice, onClose, outputDevices, popupPlacement, measureAudioLevels }: Props) { return ( <div className = 'audio-preview'> <InlineDialog content = { <AudioSettingsContent currentMicDeviceId = { currentMicDeviceId } currentOutputDeviceId = { currentOutputDeviceId } measureAudioLevels = { measureAudioLevels } microphoneDevices = { microphoneDevices } outputDevices = { outputDevices } setAudioInputDevice = { setAudioInputDevice } setAudioOutputDevice = { setAudioOutputDevice } /> } isOpen = { isOpen } onClose = { onClose } placement = { popupPlacement }> {children} </InlineDialog> </div> ); } /** * Function that maps parts of Redux state tree into component props. * * @param {Object} state - Redux state. * @returns {Object} */ function mapStateToProps(state) { const { clientWidth } = state['features/base/responsive-ui']; return { popupPlacement: clientWidth <= SMALL_MOBILE_WIDTH ? 'auto' : 'top-start', currentMicDeviceId: getCurrentMicDeviceId(state), currentOutputDeviceId: getCurrentOutputDeviceId(state), isOpen: getAudioSettingsVisibility(state), microphoneDevices: getAudioInputDeviceData(state), outputDevices: getAudioOutputDeviceData(state), measureAudioLevels: areAudioLevelsEnabled(state) }; } const mapDispatchToProps = { onClose: toggleAudioSettings, setAudioInputDevice: setAudioInputDeviceAndUpdateSettings, setAudioOutputDevice: setAudioOutputDeviceAction }; export default connect(mapStateToProps, mapDispatchToProps)(AudioSettingsPopup);
src/svg-icons/device/signal-wifi-3-bar-lock.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi3BarLock = (props) => ( <SvgIcon {...props}> <path opacity=".3" d="M12 3C5.3 3 .8 6.7.4 7l3.2 3.9L12 21.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7.3-.1.5-.2.8-.2.3-.1.6-.1.9-.1.4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4z"/><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16zm-10 5.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7C17.3 9 14.9 8 12 8c-4.8 0-8 2.6-8.5 2.9"/> </SvgIcon> ); DeviceSignalWifi3BarLock = pure(DeviceSignalWifi3BarLock); DeviceSignalWifi3BarLock.displayName = 'DeviceSignalWifi3BarLock'; export default DeviceSignalWifi3BarLock;
app/components/ImageComponent.js
fakob/electron-test-v003
import React, { Component } from 'react'; import PropTypes from 'prop-types'; // import mpLogo from './../img/MoviePrint_Logo_v002_128.jpg'; // import base64ArrayBuffer from './../utils/base64ArrayBuffer' let temp = []; class ImageComponent extends Component { componentDidMount() { const { store } = this.context; this.unsubscribe = store.subscribe(() => this.forceUpdate()); } componentWillUnmount() { this.unsubscribe(); } render() { const { store } = this.context; const state = store.getState(); return ( <div> <img src={temp} alt="mpLogo" width="300px" height="300px" /> </div> ); } } ImageComponent.contextTypes = { store: PropTypes.object }; export default ImageComponent;
example_app/src/components/withViewport.js
blueberryapps/radium-bootstrap-grid
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport} />; } handleResize(value) { this.setState({ viewport: value }); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/index.js
irla/react-cv
//import 'bootstrap/scss/bootstrap.scss' //import 'font-awesome/scss/font-awesome.scss' import 'bootstrap/dist/css/bootstrap.css' import 'font-awesome/css/font-awesome.css' import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import Application from './containers/Application' const render = Component => { ReactDOM.render( <AppContainer> <Component /> </AppContainer>, document.getElementById('root') ) } render(Application) if (module.hot) { module.hot.accept('./containers/Application', () => { render(Application) }) }
view/dva/src/routes/HomePage.js
xuzhenyang/ZeroCola
import React from 'react'; import { connect } from 'dva'; import MyLayout from '../components/MyLayout'; function HomePage({ children }) { return ( <div> <MyLayout> {children} </MyLayout> </div> ); } function mapStateToProps() { return {}; } export default connect(mapStateToProps)(HomePage);
src/renderer/components/MapFilter/ObservationDialog/DateTimeField.js
digidem/ecuador-map-editor
// @flow import React from 'react' import { DateTimePicker } from '@material-ui/pickers' type Props = { value: Date | void, onChange: (string | void) => any } const DateTimeField = ({ value, onChange, ...otherProps }: Props) => { return ( <DateTimePicker fullWidth variant='inline' inputVariant='outlined' margin='normal' value={ // DateTimePicker shows the current date if value is undefined. To show // it as empty, value needs to be null value === undefined ? null : value } onChange={date => date === undefined ? onChange() : onChange(date.toISOString()) } {...otherProps} /> ) } export default DateTimeField
src/svg-icons/communication/chat-bubble-outline.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationChatBubbleOutline = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/> </SvgIcon> ); CommunicationChatBubbleOutline = pure(CommunicationChatBubbleOutline); CommunicationChatBubbleOutline.displayName = 'CommunicationChatBubbleOutline'; CommunicationChatBubbleOutline.muiName = 'SvgIcon'; export default CommunicationChatBubbleOutline;
src/app/App.js
crisu83/timebox
import React from 'react'; import store from './store'; import AppConstants from './constants'; import TimerConstants from '../timer/constants'; import Header from '../header/Header'; import Picker from '../picker/Picker'; import Timer from '../timer/Timer'; import Footer from '../footer/Footer'; class App extends React.Component { componentDidMount() { this.unsubscribe = store.subscribe(() => { this.forceUpdate(); }); } componentWillUnmount() { this.unsubscribe(); } getClassNames() { const state = store.getState(); let classNames = ['timebox']; switch (state.name) { case AppConstants.STATE_RUNNING: classNames.push('state-running'); break; case AppConstants.STATE_DONE: classNames.push('state-done'); break; case AppConstants.STATE_DEFAULT: default: classNames.push('state-default'); break; } return classNames.join(' '); } render() { return ( <div className={this.getClassNames()}> <Header /> <div className="centered"> <Picker buttons={this.props.buttons} /> <Timer /> </div> <Footer /> </div> ); } } export default App;
src/parser/warlock/affliction/modules/talents/Haunt.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Enemies from 'parser/shared/modules/Enemies'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage, formatThousands, formatNumber } from 'common/format'; import Statistic from 'interface/statistics/Statistic'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import { UNSTABLE_AFFLICTION_DEBUFFS } from '../../constants'; const HAUNT_DAMAGE_BONUS = 0.1; class Haunt extends Analyzer { static dependencies = { enemies: Enemies, }; bonusDmg = 0; totalTicks = 0; buffedTicks = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.HAUNT_TALENT.id); this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage); } onDamage(event) { const target = this.enemies.getEntity(event); if (!target) { return; } const hasHaunt = target.hasBuff(SPELLS.HAUNT_TALENT.id, event.timestamp); if (UNSTABLE_AFFLICTION_DEBUFFS.some(spell => spell.id === event.ability.guid)) { this.totalTicks += 1; if (hasHaunt) { this.buffedTicks += 1; } } if (hasHaunt) { this.bonusDmg += calculateEffectiveDamage(event, HAUNT_DAMAGE_BONUS); } } get uptime() { return this.enemies.getBuffUptime(SPELLS.HAUNT_TALENT.id) / this.owner.fightDuration; } get dps() { return this.bonusDmg / this.owner.fightDuration * 1000; } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.9, average: 0.85, major: 0.75, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest( <> Your <SpellLink id={SPELLS.HAUNT_TALENT.id} /> debuff uptime is too low. While it's usually not possible to get 100% uptime due to travel and cast time, you should aim for as much uptime on the debuff as possible. </>, ) .icon(SPELLS.HAUNT_TALENT.icon) .actual(`${formatPercentage(actual)}% Haunt uptime.`) .recommended(`> ${formatPercentage(recommended)}% is recommended`); }); } statistic() { const buffedTicksPercentage = (this.buffedTicks / this.totalTicks) || 1; return ( <Statistic position={STATISTIC_ORDER.OPTIONAL(4)} size="flexible" tooltip={( <> {formatThousands(this.bonusDmg)} bonus damage<br /> You buffed {formatPercentage(buffedTicksPercentage)} % of your Unstable Affliction ticks with Haunt. </> )} > <div className="pad"> <label><SpellLink id={SPELLS.HAUNT_TALENT.id} /></label> <div className="flex"> <div className="flex-main value"> {formatPercentage(this.uptime)} % <small>uptime</small> </div> </div> <div className="flex"> <div className="flex-main value"> {formatNumber(this.dps)} DPS <small>{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDmg))} % of total</small> </div> </div> </div> </Statistic> ); } } export default Haunt;
packages/node_modules/@webex/react-component-button/src/index.js
ciscospark/react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon from '@webex/react-component-icon'; import styles from './styles.css'; const propTypes = { accessibilityLabel: PropTypes.string, buttonClassName: PropTypes.string, children: PropTypes.node, iconColor: PropTypes.string, iconType: PropTypes.string, label: PropTypes.string, labelPosition: PropTypes.string, onClick: PropTypes.func.isRequired, title: PropTypes.string }; const defaultProps = { accessibilityLabel: '', buttonClassName: '', children: undefined, iconColor: 'white-100', iconType: '', label: '', labelPosition: '', title: '' }; function Button(props) { const { accessibilityLabel, buttonClassName, children, iconColor, iconType, label, labelPosition, onClick, title } = props; const ariaLabel = accessibilityLabel || label || title; function handleKeyPress(e) { if (e.key === 'Enter' || e.key === ' ') { onClick(); } } return ( <div className={classNames('webex-button-container', styles.buttonContainer)}> <button aria-label={ariaLabel} className={classNames('webex-button', styles.button, buttonClassName)} onClick={onClick} onKeyPress={handleKeyPress} > { iconType && <div className={classNames('webex-button-icon', styles.buttonIcon)} > <Icon color={iconColor} title={title} type={iconType} /> </div> } { labelPosition !== 'bottom' && label } {children} </button> { label && labelPosition === 'bottom' && <div className={classNames('webex-label', styles.label, styles.labelBottom)}>{label}</div> } </div> ); } Button.propTypes = propTypes; Button.defaultProps = defaultProps; export default Button;
src/components/RadioList.js
angeloocana/angeloocana
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Radio from './Radio'; import { FormattedMessage } from 'react-intl'; import { contains } from 'ramda'; import { InvisibleSpan } from './Invisible'; const Ul = styled.ul` display: flex; flex-flow: row wrap; justify-content: start; margin: 0 0 1rem 0; padding: 0; `; export const getCbListFromArray = (items, checkedItems) => { return items.map(i => ({ label: i, value: i, checked: contains(i, checkedItems) })); }; const RadioList = (props) => { return ( <fieldset> <legend> <FormattedMessage id={props.i18n.title}> {(txt) => ( <InvisibleSpan> {txt} </InvisibleSpan> )} </FormattedMessage> </legend> <Ul> {props.items.map(item => ( <li> <Radio value={item.value} label={item.label} check={props.check} checked={item.checked} /> </li> ))} </Ul> </fieldset> ); }; export const i18nPropTypes = PropTypes.shape({ title: PropTypes.string.isRequired }); RadioList.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ value: PropTypes.any.isRequired, label: PropTypes.string.isRequired, checked: PropTypes.bool.isRequired })).isRequired, check: PropTypes.func.isRequired, i18n: i18nPropTypes }; export default RadioList;
src/pages/404.js
angeloocana/tic-tac-toe-ai
import React from 'react'; class FourOFour extends React.PureComponent { render() { return ( <div> <h1>Page not found</h1> </div> ); } } export default FourOFour;
node_modules/react-native/local-cli/templates/HelloWorld/index.android.js
RahulDesai92/PHR
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
packages/icons/src/md/av/CallToAction.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdCallToAction(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M42 6c2.2 0 4 1.8 4 4v28c0 2.2-1.8 4-4 4H6c-2.2 0-4-1.8-4-4V10c0-2.2 1.8-4 4-4h36zm0 32v-6H6v6h36z" /> </IconBase> ); } export default MdCallToAction;
public/src/components/Layout/Layout.react.js
hugonasciutti/Challenge
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { FlatButton } from 'material-ui'; import AppBar from 'material-ui/AppBar'; import styles from './Layout.scss'; import Icon from '../../../icons/icons'; class _Layout extends React.Component { render() { return ( <div className={styles.LayoutRoot}> <div className={styles.LayoutHeader}> <AppBar title="Hugo Nasciutti App" iconElementRight={<FlatButton label="About" href="http://localhost:3000/about" />} /> </div> <div className={styles.LayoutContent}> {this.props.children} </div> <div className={styles.LayoutFooter}> <div className={styles.footer1}> <a href="https://dribbble.com/"> <Icon className={styles.dribbbleLogo} glyph={Icon.GLYPHS.dribbbleLogo} /> </a> </div> <div className={styles.footer2}> Hugo Nasciutti &copy; 2017 </div> </div> </div> ); } } _Layout.propTypes = { children: PropTypes.element.isRequired, }; const mapStateToProps = () => ({ }); const mapActionsToProps = { }; const Layout = connect(mapStateToProps, mapActionsToProps)(_Layout); export default Layout;
src/svg-icons/places/casino.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesCasino = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.5 18c-.83 0-1.5-.67-1.5-1.5S6.67 15 7.5 15s1.5.67 1.5 1.5S8.33 18 7.5 18zm0-9C6.67 9 6 8.33 6 7.5S6.67 6 7.5 6 9 6.67 9 7.5 8.33 9 7.5 9zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm0-9c-.83 0-1.5-.67-1.5-1.5S15.67 6 16.5 6s1.5.67 1.5 1.5S17.33 9 16.5 9z"/> </SvgIcon> ); PlacesCasino = pure(PlacesCasino); PlacesCasino.displayName = 'PlacesCasino'; PlacesCasino.muiName = 'SvgIcon'; export default PlacesCasino;
src/app/page/order_detail.js
borgnix/solid-winner
/** * Created by luoop on 16-7-14. */ import React from 'react' import {Component} from 'react' import call from '../api' import update from 'immutability-helper'; import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; class OrderDetail extends Component { constructor(props) { super(props) this.state = { hasData: false } } getData() { call('OrderDetailInfo', {orderID: "123"}, (data ,err) => { if(data !== null){ //console.log("data: ", data) this.orderInfo = data; this.setState(update(this.state, {hasData: {$set: true}})); } } ) } componentWillMount() { this.getData(); } render() { //console.log("this.orderInfo: ", this.orderInfo); if(this.state.hasData) { //console.log("this.orderInfo: ", this.orderInfo.details); return<div> <Table> <TableHeader adjustForCheckbox={false} displaySelectAll={false}> <TableRow> <TableRowColumn>订单号</TableRowColumn> <TableRowColumn>{this.orderInfo.id}</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>金额</TableRowColumn> <TableRowColumn>{this.orderInfo.sum}</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>时间</TableRowColumn> <TableRowColumn>{this.orderInfo.time}</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>用户</TableRowColumn> <TableRowColumn>{this.orderInfo.custName}</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>收货地址</TableRowColumn> <TableRowColumn>{this.orderInfo.custAddr}</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>电话</TableRowColumn> <TableRowColumn>{this.orderInfo.custPhone}</TableRowColumn> </TableRow> </TableHeader> </Table> <Table> <TableHeader adjustForCheckbox={false} displaySelectAll={false}> <TableRow> <TableRowColumn>商品名</TableRowColumn> <TableRowColumn>单价</TableRowColumn> <TableRowColumn>数量</TableRowColumn> </TableRow> </TableHeader> <TableBody> {this.orderInfo.details.map((item) => { return <TableRow> <TableRowColumn>{item.name}</TableRowColumn> <TableRowColumn>{item.unitPrice}</TableRowColumn> <TableRowColumn>{item.amount}</TableRowColumn> </TableRow> })}) </TableBody> </Table> </div>; } else { return <p> wait for me </p>; } } } export default OrderDetail;
pages/less.js
rorz/a27-site
import React from 'react' import './example.less' import Helmet from 'react-helmet' import { config } from 'config' export default class Less extends React.Component { render () { return ( <div> <Helmet title={`${config.siteTitle} | Hi lessy friends`} /> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
actor-apps/app-web/src/app/components/modals/Contacts.react.js
luoxiaoshenghustedu/actor-platform
// // Deprecated // import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import ContactStore from 'stores/ContactStore'; import Modal from 'react-modal'; import AvatarItem from 'components/common/AvatarItem.react'; let appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); let getStateFromStores = () => { return { contacts: ContactStore.getContacts(), isShown: ContactStore.isContactsOpen() }; }; class Contacts extends React.Component { componentWillMount() { ContactStore.addChangeListener(this._onChange); } componentWillUnmount() { ContactStore.removeChangeListener(this._onChange); } constructor() { super(); this._onClose = this._onClose.bind(this); this._onChange = this._onChange.bind(this); this.state = getStateFromStores(); } _onChange() { this.setState(getStateFromStores()); } _onClose() { ContactActionCreators.hideContactList(); } render() { let contacts = this.state.contacts; let isShown = this.state.isShown; let contactList = _.map(contacts, (contact, i) => { return ( <Contacts.ContactItem contact={contact} key={i}/> ); }); if (contacts !== null) { return ( <Modal className="modal contacts" closeTimeoutMS={150} isOpen={isShown}> <header className="modal__header"> <a className="modal__header__close material-icons" onClick={this._onClose}>clear</a> <h3>Contact list</h3> </header> <div className="modal__body"> <ul className="contacts__list"> {contactList} </ul> </div> </Modal> ); } else { return (null); } } } Contacts.ContactItem = React.createClass({ propTypes: { contact: React.PropTypes.object }, mixins: [PureRenderMixin], _openNewPrivateCoversation() { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); ContactActionCreators.hideContactList(); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a> </div> </li> ); } }); export default Contacts;
examples/counter/containers/Root.js
phated/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import CounterApp from './CounterApp'; import configureStore from '../store/configureStore'; const store = configureStore(); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <CounterApp />} </Provider> ); } }
src/pages/about.js
stolinski/st2017
import React from 'react'; import Link from 'gatsby-link'; import Layout from '../components/Layout'; import { Title, MainWrapper } from '../components/Headings'; import { Resume, FakeButtons } from '../components/AboutStyles'; export default class About extends React.Component { render() { return ( <Layout {...this.props}> <MainWrapper color="#16a085"> <Title>About</Title> <div> <p>Hi, I'm Scott Tolinski.</p> <p> I'm a Senior Web Developer for Team Detroit and formerly a web applications developer for The University of Michigan and the Senior Developer at{' '} <a target="_blank" href="http://qltd.com"> Q LTD </a> &nbsp;in Ann Arbor, MI. I also do freelance web design and development for projects that I find interesting, challenging or exciting, and give private training or consulting in various web topics. &nbsp;In 2012, I created{' '} <a target="_blank" href="http://www.youtube.com/user/LevelUpTuts/featured"> Level Up Tuts </a> &nbsp;with web developer{' '} <a target="_blank" href="http://benschaaf.com/"> Ben Schaaf </a> . With Level Up Tutorials I have taken our knowledge of web technologies to YouTube to provide free training to developers looking to learn something new. I've also created premium tutorial packages for{' '} <a target="_blank" href="https://www.packtpub.com/getting-started-with-magento/video"> Packt Publishing </a> . </p> <p> I also enjoy{' '} <a target="_blank" href="http://youtu.be/Zcoj4Zfj6_k?t=1m34s"> bboying </a>{' '} also known as breakdancing, and have been dancing for over 8 years doing shows for professional NFL and NBA teams. I'm inspired by a hot cup of green tea, excellent music, and Shaw Bros. kung fu movies. </p> <p> Please <Link to="/contact">contact me</Link> if you would like to work on a project together, or just want to chat. </p> </div> <Resume> <FakeButtons /> <div className="resume-inside"> <h3>&#047;&#042; --Resume-- &#042;&#047;</h3> <h4>&#047;&#042; SUMMARY OF QUALIFICATIONS &#042;&#047;</h4> <ul> <li> Received a Bachelors degree in the Fine Arts at the University of Michigan’s Media Arts program. </li> <li>Excellent organization, self-motivation, and problem-solving skills.</li> <li> Created and runs a popular Youtube coding education channel with over 700 videos, 8.5million views &amp; 85k subscribers. </li> <li>Creative, strong communication skills and consistently meets deadlines.</li> <li>Passionate about web development and new technologies.</li> </ul> <h4>&#047;&#042; Experience &#042;&#047;</h4> <h5>&#047;&#047; SENIOR FRONT-END DEVELOPER, Team Detroit - DEARBORN, MI</h5> <span className="time">&#047;&#047; MAY 2014 - PRESENT</span> <ul> <li>Rapidly prototyped designs for the design process and user testing.</li> <li>Utilized AngularJS to build a component library for Ford.com Global Redesign.</li> <li>Met with Ford executives to display functionality of design experiments.</li> <li>Worked on a team of developers to coordinate and develop compoent library.</li> <li>Built resposive web applications to display potential design and interaction experiences.</li> </ul> <h5>&#047;&#047; OWNER, Level Up Tuts - ANN ARBOR, MI</h5> <span className="time">&#047;&#047; MARCH 2012 - PRESENT</span> <ul> <li> Wrote, produced and recorded over 1000 popular tutorial videos on various topics for Level Up Tuts (www.youtube.com/user/LevelUpTuts) with over 8,550,000 views. </li> <li> Designed websites, interfaces, and layouts to fit clients’ desires including developing responsive layouts to enhance the experience on mobile devices. </li> <li>Consulted on large scale development projects.</li> <li>Provided dedicated training on coding practices and content management systems.</li> <li>Wrote, produced and recorded commercial video tutorial series for Envato and Packt Publishing.</li> </ul> <h5>&#047;&#047; WEB APPLICATIONS DEVELOPER, UM Creative - ANN ARBOR, MI</h5> <span className="time">&#047;&#047; OCT 2013 - MAY 2014</span> <ul> <li>Developed single page applications using Angular.js or Backbone.js.</li> <li>Maintained and built websites for secure University servers.</li> <li>Took initiative on internal projects to advance direction of department.</li> <li> Tested and troubleshot slow application speeds as well as slow front end load times on existing websites. </li> <li>Built responsive, CMS based websites with rapid turnaround.</li> </ul> <h5>&#047;&#047; SENIOR DEVELOPER, Q LTD - ANN ARBOR, MI</h5> <span className="time">&#047;&#047; MARCH 2011 - OCT 2013</span> <ul> <li> Built large, medium, and small scale websites from the ground up using appropriate content management systems (Drupal, Wordpress, Expression Engine, Magento). </li> <li> Utilized latest HTML5 and CSS3 technologies to build semantically correct and visually interesting responsive designs. </li> <li>Created interactive elements with custom JavaScript and Jquery.</li> <li>Worked frequently with clients to train, assist, and troubleshoot their websites.</li> <li> Used Sass, Compass, and Coffee Script to more effectively write clean, fast, and easy to read code. </li> </ul> <h4>&#047;&#042; EDUCATION &#042;&#047;</h4> <ul> <li>University of Michigan - Media Arts Bachelors of the Arts Spring 2008</li> </ul> </div> </Resume> </MainWrapper> </Layout> ); } }
app/components/common/nominationItem/index.js
liujia14/mayi
/* name: listItem desc: 提名团队列表组件 author: 俞雅菲 version:v1.0 */ import React from 'react'; import ReactDOM from 'react-dom'; import './../commonCss/index.less'; import ajax from './../ajax/ajax.js'; import './index.less'; import { message,Modal } from 'antd'; import QueueAnim from 'rc-queue-anim'; //淡入淡出动画 const confirm = Modal.confirm; export default class Items extends React.Component { constructor(props) { super(props); this.state = { visible:false, nomineeCode:undefined }; this.doAgree = this.doAgree.bind(this); this.notAgree = this.notAgree.bind(this); this.recall = this.recall.bind(this); this.handleCancel = this.handleCancel.bind(this); this.handleOk = this.handleOk.bind(this); } doAgree(code,e){ //点赞 let t = $(e.target); if(t.hasClass("icon-dianzan")){ ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞 url:'/platform/nominate/LikeOperate.json', type:"POST", data:{ 'nomineeCode':code, 'type':'YES' }, success:(data)=>{ if(data.success){ t.removeClass("icon-dianzan") .addClass("icon-dianzan-copy") .siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())+1 ); }else{ message.error(data.errors); } }, error : (data) => {} }); }else{ ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞 url:'/platform/nominate/LikeOperate.json', type:"POST", data:{ 'nomineeCode':code, 'type':'NO' }, success:(data)=>{ if(data.success){ t.removeClass("icon-dianzan-copy") .addClass("icon-dianzan") .siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())-1 ); }else{ message.error(data.errors); } }, error : (data) => {} }); } } notAgree(code,e){ //取消点赞 let t = $(e.target); if(t.hasClass("icon-dianzan-copy")){ ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞 url:'/platform/nominate/LikeOperate.json', type:"POST", data:{ 'nomineeCode':code, 'type':'NO' }, success:(data)=>{ if(data.success){ t.removeClass("icon-dianzan-copy") .addClass("icon-dianzan") .siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())-1 ); }else{ message.error(data.errors); } }, error : (data) => {} }); }else{ ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞 url:'/platform/nominate/LikeOperate.json', type:"POST", data:{ 'nomineeCode':code, 'type':'YES' }, success:(data)=>{ if(data.success){ t.removeClass("icon-dianzan") .addClass("icon-dianzan-copy") .siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())+1 ); }else{ message.error(data.errors); } }, error : (data) => {} }); } } recall(ev,code){ //删除事件 let self = this; this.setState({ visible:true, nomineeCode:code }); confirm({ //确认 title: '你确定要删除吗', onOk() { self.handleOk(); }, onCancel() { self.handleCancel(); } }); } handleOk(){ let self = this; let codes = self.state.nomineeCode; ajax({ url:'/platform/nominate/RemoveNominate.json', type:"POST", data:{ 'nomineeCode': codes }, success:(data) => { if(data.success){ message.success("删除成功!3秒后刷新页面"); self.setState({ visible:false }); setTimeout(function(){window.location.reload();},2000); }else{ message.error(data.errors) } }, error : (data) => {} }); } handleCancel(){ this.setState({ visible:false }); } render() { let self = this; let datas = this.props.listData; let nomineeType = this.props.nomineeType; let strTip; if(nomineeType == "nomination"){ strTip = ""; }else{ strTip = "被"; } return ( <div className="clearFix"> <QueueAnim> { datas.length > 0 ? datas.map((item,index)=>{ if(item.nomineeType == 1){ //个人 return( <div className="nominationBox" key={index}> <div className="nomi-caption">{strTip}提名信息</div> <div className="item-leftimg"> <a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}><img src={item.url} alt=""/></a> </div> <div className="item-component"> <div className="item-title"><a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}>个人姓名:{item.nomineeName}</a></div> <div className="item-department-b"><span>所属部门:</span><div className="item-inlb">{item.departmentName}</div></div> <div className="item-type"><span>奖项类型:</span>{item.prizeType == 1 ? <div className="item-inlb">公司</div> : <div className="item-inlb">部门</div>}</div> <div className="item-prize"><span>{strTip}提名奖项:</span><a className="aColor item-inlb" href={"/platform/pageconfig/awardsDetail.htm?prizeCode=" + item.prizeCode}>{item.prizeName}</a></div> <div className="item-reason"><span>{strTip}提名理由:</span><div className="item-inlb">{item.nominatedReason}</div></div> <div className="item-agree" > <i className="iconfont icon-dianzan" ></i> <span className="agreeNum">{ item.likeSum }</span> </div> <div className="item-comment"><i className="iconfont icon-pinglun"></i> {item.messageSum}</div> { item.winStatus == 1 ? <div className="itemAwards"><i className="iconfont icon-huangguan"></i> 获奖</div> : null } { item.type == '0' & (item.prizeStatus == 'normal') ? <div className="item-btngroup"><a className="ant-btn ant-btn-primary" href={"/platform/pageconfig/frontNominationEdit.htm?nomineeCode="+item.nomineeCode}>修改</a><a className="ant-btn ant-btn-primary" onClick={ (ev)=>self.recall(ev,item.nomineeCode) }>删除</a></div> : null } </div> { item.prizeStatus == 'normal' ? <div className="limite-state ongoing">进行中</div> : item.prizeStatus == 'end' ? <div className="limite-state">已结束</div> : item.prizeStatus == 'delete' ? <div className="limite-state">已删除</div> : item.prizeStatus == 'before' ? <div className="limite-state">未开始</div> : null } </div> ) } else if(item.nomineeType == 2){ return( <div className="nominationBox" key={index}> <div className="nomi-caption">{strTip}提名信息</div> <div className="item-leftimg"> <a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}><img src={item.url} alt=""/></a> </div> <div className="item-component"> <div className="item-title"><a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}>团队名称:{item.nomineeName}</a></div> <div className="item-department-b"><span>所属部门:</span><div className="item-inlb">{item.departmentName}</div></div> <div className="item-type"><span>奖项类型:</span>{item.prizeType == 1 ? <div className="item-inlb">公司</div> : <div className="item-inlb">部门</div>}</div> <div className="item-prize"><span>{strTip}提名奖项:</span><a className="aColor item-inlb" href={"/platform/pageconfig/awardsDetail.htm?prizeCode="+item.prizeCode}>{item.prizeName}</a></div> <div className="item-reason"><span>{strTip}提名理由:</span><div className="item-inlb">{item.nominatedReason}</div></div> <div className="item-member"><span>团队名单:</span><div className="item-inlb">{ item.apTeamMembersNameList ? item.apTeamMembersNameList : <span>无</span> }</div> </div> <div className="item-agree" > <i className="iconfont icon-dianzan" ></i> <span className="agreeNum">{ item.likeSum }</span> </div> <div className="item-comment"><i className="iconfont icon-pinglun"></i> {item.messageSum}</div> { item.winStatus == 1 ? <div className="itemAwards"><i className="iconfont icon-huangguan"></i> 获奖</div> : null } { item.type == '0' & (item.prizeStatus == 'normal') ? <div className="item-btngroup"><a className="ant-btn ant-btn-primary" href={"/platform/pageconfig/frontNominationEdit.htm?nomineeCode="+item.nomineeCode}>修改</a><a className="ant-btn ant-btn-primary" onClick={ (ev)=>self.recall(ev,item.nomineeCode) }>删除</a></div> : null } </div> { item.prizeStatus == 'normal' ? <div className="limite-state ongoing">进行中</div> : item.prizeStatus == 'end' ? <div className="limite-state">已结束</div> : item.prizeStatus == 'delete' ? <div className="limite-state">已删除</div> : item.prizeStatus == 'before' ? <div className="limite-state">未开始</div> : null } </div> ) } }) : nomineeType == "nomination" ? <div className="empty"><img src="../../../../static/images/noData.png" alt="无数据"/> <div>你还没有参与提名,赶快行动,表达你的支持!</div></div> : <div className="empty"><img src="../../../../static/images/noData.png" alt="无数据"/> <div>小伙伴们的提名还在路上,先自荐一个?</div></div> } </QueueAnim> </div> ) } }
docs/app/Examples/modules/Dropdown/Types/DropdownExampleMultipleSearchSelectionTwo.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' import { countryOptions } from '../common' // countryOptions = [ { value: 'af', flag: 'af', text: 'Afghanistan' }, ... ] const DropdownExampleMultipleSearchSelectionTwo = () => ( <Dropdown placeholder='Select Country' fluid multiple search selection options={countryOptions} /> ) export default DropdownExampleMultipleSearchSelectionTwo
client/src/js/components/Home.js
KevinBacas/TP2-Web-Semantique
import React from 'react'; import RequestList from './RequestList'; import DocumentActions from '../actions/DocumentActions'; import DocumentStore from '../stores/DocumentStore'; export default class Home extends React.Component { constructor() { super(); this.state = { documents: false } } handleSubmit(e) { e.preventDefault(); let request = document.getElementById('request').value; DocumentActions.fetchDocuments(request); } onChange() { let doc= DocumentStore.getDocuments(); if(doc === []) { doc = false; } this.setState({ documents: doc }); } conponentWillUnmount() { this.setState({}); } componentDidMount() { DocumentStore.onChange = this.onChange.bind(this); } render() { return ( <div className="container" > <form className="homePage" onSubmit={this.handleSubmit} action="return false;"> <input type="text" className="form-control" id="request" placeholder="your request" /> <input className="btn btn-default" type="submit" value="search" /> </form> <RequestList list={this.state.documents} /> </div> ); } };
src/svg-icons/device/usb.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceUsb = (props) => ( <SvgIcon {...props}> <path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"/> </SvgIcon> ); DeviceUsb = pure(DeviceUsb); DeviceUsb.displayName = 'DeviceUsb'; DeviceUsb.muiName = 'SvgIcon'; export default DeviceUsb;
frontend/components/home_show/home_show_container.js
qydchen/SafeHavn
import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import HomeShow from './home_show'; import { fetchHome } from '../../actions/home_actions'; import { openModal } from '../../actions/modal_actions'; import { clearErrors } from '../../actions/session_actions' const mapStateToProps = ({ homes, session }, { match }) => { const homeid = match.params.homeid; const listing = homes[homeid]; return { homeid, listing, currentUser: session.currentUser, reviews: listing ? listing.reviews : [], } } const mapDispatchToProps = (dispatch) => { return { fetchHome: id => dispatch(fetchHome(id)), openModal: (component) => dispatch(openModal(component)), clearErrors: () => dispatch(clearErrors()), } } export default withRouter(connect( mapStateToProps, mapDispatchToProps )(HomeShow));
frontend/node_modules/recharts/demo/component/Sector.js
justdotJS/rowboat
import React, { Component } from 'react'; import { Surface, Sector } from 'recharts'; export default class Demo extends Component { static displayName = 'SectorDemo'; render () { return ( <Surface width={500} height={1000}> <Sector fill="#ff7902" cx={200} cy={200} innerRadius={150} outerRadius={200} endAngle={90} /> <Sector fill="#287902" cx={200} cy={400} innerRadius={180} outerRadius={200} startAngle={45} endAngle={135} cornerRadius={10} /> </Surface> ); } }
webapp-src/src/Modal/Message.js
babelouest/glewlwyd
import React, { Component } from 'react'; import i18next from 'i18next'; class Message extends Component { constructor(props) { super(props); this.state = { title: props.title, label: props.label, message: props.message } this.closeModal = this.closeModal.bind(this); } componentWillReceiveProps(nextProps) { this.setState({ title: nextProps.title, label: nextProps.label, message: nextProps.message }); } closeModal(e, result) { $("#messageModal").modal("hide"); } render() { var messageJsx = [], labelJsx; if (this.state.label) { labelJsx = <h5>{this.state.label}</h5>; } if (this.state.message) { this.state.message.forEach((message, index) => { messageJsx.push(<li key={index}>{message}</li>); }); } return ( <div className="modal fade on-top" id="messageModal" tabIndex="-1" role="dialog" aria-labelledby="messageModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="messageModalLabel">{this.state.title}</h5> <button type="button" className="close" aria-label={i18next.t("modal.close")} onClick={(e) => this.closeModal(e, false)}> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> {labelJsx} <ul> {messageJsx} </ul> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" onClick={(e) => this.closeModal(e, false)}>{i18next.t("modal.close")}</button> </div> </div> </div> </div> ); } } export default Message;
01-basic-example/components/Home.js
nodeyu/jason-react-router-demos-v4
import React from 'react'; class Home extends React.Component { render() { return ( <div> <h2>Home</h2> <p>Welcome To React Full Stack</p> </div> ); } } export default Home;
example/src/screens/types/tabs/TabTwo.js
junedomingo/react-native-navigation
import React from 'react'; import {View, Text} from 'react-native'; class TabOne extends React.Component { render() { return ( <View> <Text>Tab Two</Text> </View> ); } } export default TabOne;
src/svg-icons/action/today.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionToday = (props) => ( <SvgIcon {...props}> <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/> </SvgIcon> ); ActionToday = pure(ActionToday); ActionToday.displayName = 'ActionToday'; ActionToday.muiName = 'SvgIcon'; export default ActionToday;
fields/types/cloudinaryimage/CloudinaryImageField.js
Pylipala/keystone
import _ from 'underscore'; import $ from 'jquery'; import React from 'react'; import Field from '../Field'; import Select from 'react-select'; import { Button, FormField, FormInput, FormNote } from 'elemental'; /** * TODO: * - Remove dependency on jQuery * - Remove dependency on underscore */ const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml']; module.exports = Field.create({ displayName: 'CloudinaryImageField', fileFieldNode () { return this.refs.fileField.getDOMNode(); }, changeImage () { this.refs.fileField.getDOMNode().click(); }, getImageSource () { if (this.hasLocal()) { return this.state.localSource; } else if (this.hasExisting()) { return this.props.value.url; } else { return null; } }, getImageURL () { if (!this.hasLocal() && this.hasExisting()) { return this.props.value.url; } }, /** * Reset origin and removal. */ undoRemove () { this.fileFieldNode().value = ''; this.setState({ removeExisting: false, localSource: null, origin: false, action: null }); }, /** * Check support for input files on input change. */ fileChanged (event) { var self = this; if (window.FileReader) { var files = event.target.files; _.each(files, function (f) { if (!_.contains(SUPPORTED_TYPES, f.type)) { self.removeImage(); alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG'); return false; } var fileReader = new FileReader(); fileReader.onload = function (e) { if (!self.isMounted()) return; self.setState({ localSource: e.target.result, origin: 'local' }); }; fileReader.readAsDataURL(f); }); } else { this.setState({ origin: 'local' }); } }, /** * If we have a local file added then remove it and reset the file field. */ removeImage (e) { var state = { localSource: null, origin: false }; if (this.hasLocal()) { this.fileFieldNode().value = ''; } else if (this.hasExisting()) { state.removeExisting = true; if (this.props.autoCleanup) { if (e.altKey) { state.action = 'reset'; } else { state.action = 'delete'; } } else { if (e.altKey) { state.action = 'delete'; } else { state.action = 'reset'; } } } this.setState(state); }, /** * Is the currently active image uploaded in this session? */ hasLocal () { return this.state.origin === 'local'; }, /** * Do we have an image preview to display? */ hasImage () { return this.hasExisting() || this.hasLocal(); }, /** * Do we have an existing file? */ hasExisting () { return !!this.props.value.url; }, /** * Render an image preview */ renderImagePreview () { var iconClassName; var className = 'image-preview'; if (this.hasLocal()) { className += ' upload-pending'; iconClassName = 'upload-pending mega-octicon octicon-cloud-upload'; } else if (this.state.removeExisting) { className += ' removed'; iconClassName = 'delete-pending mega-octicon octicon-x'; } var body = [this.renderImagePreviewThumbnail()]; if (iconClassName) body.push(<div key={this.props.path + '_preview_icon'} className={iconClassName} />); var url = this.getImageURL(); if (url) { body = <a className="img-thumbnail" href={this.getImageURL()} target="__blank">{body}</a>; } else { body = <div className="img-thumbnail">{body}</div>; } return <div key={this.props.path + '_preview'} className={className}>{body}</div>; }, renderImagePreviewThumbnail () { return <img key={this.props.path + '_preview_thumbnail'} className="img-load" style={ { height: '90' } } src={this.getImageSource()} />; }, /** * Render image details - leave these out if we're uploading a local file or * the existing file is to be removed. */ renderImageDetails (add) { var values = null; if (!this.hasLocal() && !this.state.removeExisting) { values = ( <div className="image-values"> <FormInput noedit>{this.props.value.url}</FormInput> {/* TODO: move this somewhere better when appropriate this.renderImageDimensions() */} </div> ); } return ( <div key={this.props.path + '_details'} className="image-details"> {values} {add} </div> ); }, renderImageDimensions () { return <FormInput noedit>{this.props.value.width} x {this.props.value.height}</FormInput>; }, /** * Render an alert. * * - On a local file, output a "to be uploaded" message. * - On a cloudinary file, output a "from cloudinary" message. * - On removal of existing file, output a "save to remove" message. */ renderAlert () { if (this.hasLocal()) { return ( <FormInput noedit>Image selected - save to upload</FormInput> ); } else if (this.state.origin === 'cloudinary') { return ( <FormInput noedit>Image selected from Cloudinary</FormInput> ); } else if (this.state.removeExisting) { return ( <FormInput noedit>Image {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</FormInput> ); } else { return null; } }, /** * Output clear/delete/remove button. * * - On removal of existing image, output "undo remove" button. * - Otherwise output Cancel/Delete image button. */ renderClearButton () { if (this.state.removeExisting) { return ( <Button type="link" onClick={this.undoRemove}> Undo Remove </Button> ); } else { var clearText; if (this.hasLocal()) { clearText = 'Cancel'; } else { clearText = (this.props.autoCleanup ? 'Delete Image' : 'Remove Image'); } return ( <Button type="link-cancel" onClick={this.removeImage}> {clearText} </Button> ); } }, renderFileField () { return <input ref="fileField" type="file" name={this.props.paths.upload} className="field-upload" onChange={this.fileChanged} tabIndex="-1" />; }, renderFileAction () { return <input type="hidden" name={this.props.paths.action} className="field-action" value={this.state.action} />; }, renderImageToolbar () { return ( <div key={this.props.path + '_toolbar'} className="image-toolbar"> <div className='u-float-left'> <Button onClick={this.changeImage}> {this.hasImage() ? 'Change' : 'Upload'} Image </Button> {this.hasImage() && this.renderClearButton()} </div> {this.props.select && this.renderImageSelect()} </div> ); }, renderImageSelect () { var selectPrefix = this.props.selectPrefix; var getOptions = function(input, callback) { $.get('/keystone/api/cloudinary/autocomplete', { dataType: 'json', data: { q: input }, prefix: selectPrefix }, function (data) { var options = []; _.each(data.items, function (item) { options.push({ value: item.public_id, label: item.public_id }); }); callback(null, { options: options, complete: true }); }); }; return ( <div className="image-select"> <Select placeholder="Search for an image from Cloudinary ..." className="ui-select2-cloudinary" name={this.props.paths.select} id={'field_' + this.props.paths.select} asyncOptions={getOptions} /> </div> ); }, renderUI () { var container = []; var body = []; var hasImage = this.hasImage(); if (this.shouldRenderField()) { if (hasImage) { container.push(this.renderImagePreview()); container.push(this.renderImageDetails(this.renderAlert())); } body.push(this.renderImageToolbar()); } else { if (hasImage) { container.push(this.renderImagePreview()); container.push(this.renderImageDetails()); } else { container.push(<div className="help-block">no image</div>); } } return ( <FormField label={this.props.label} className="field-type-cloudinaryimage"> {this.renderFileField()} {this.renderFileAction()} <div className="image-container">{container}</div> {body} <FormNote note={this.props.note} /> </FormField> ); } });
docs/app/Examples/collections/Message/Types/MessageExampleList.js
aabustamante/Semantic-UI-React
import React from 'react' import { Message } from 'semantic-ui-react' const MessageExampleList = () => ( <Message> <Message.Header>New Site Features</Message.Header> <Message.List> <Message.Item>You can now have cover images on blog pages</Message.Item> <Message.Item>Drafts will now auto-save while writing</Message.Item> </Message.List> </Message> ) export default MessageExampleList
components/Forecast.js
s1hit/react-onsenui-redux-weather-edited
import React from 'react'; import WeatherIcon from '../components/WeatherIcon'; import {weatherCodeToColor} from '../util'; const WEEKDAYS = { 0: 'SUN', 1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI', 6: 'SAT' }; const styles = { forecast: { margin: '0 25px', display: 'flex' }, weekday: { flexGrow: 1, display: 'flex', flexDirection: 'column' }, weekdayName: { fontSize: '16px', margin: '0 0 6px 0', fontWeight: 200 }, weekdayIcon: { fontSize: '24px' }, weekdayMaxTemp: { margin: '6px 0 0 0', fontSize: '12px' }, weekdayMinTemp: { opacity: 0.6, margin: '2px 0 0 0', fontWeight: 200, fontSize: '12px' } }; const Forecast = ({days}) => ( <div style={styles.forecast}> {days.map(({weekday, icon, maxTemp, minTemp}) => { const weatherColor = weatherCodeToColor(icon); return ( <div key={weekday} style={styles.weekday}> <div style={styles.weekdayName}> {WEEKDAYS[weekday]} </div> <div style={styles.weekdayIcon}> <WeatherIcon style={{color: weatherColor}} icon={icon} /> </div> <div style={styles.weekdayMaxTemp}> {maxTemp}&deg;C </div> <div style={styles.weekdayMinTemp}> {minTemp}&deg;C </div> </div> ); })} </div> ); export default Forecast;
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/Before/app/components/Login/index.js
phiratio/Pluralsight-materials
/** * * Login * */ import React from 'react'; import styles from './styles.css'; import validator from 'email-validator'; import classNames from 'classnames'; class Login extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { login: React.PropTypes.func.isRequired, cancelLogin: React.PropTypes.func.isRequired, }; state = {}; login = () => { const email = this.emailField.value; if (!validator.validate(email)) { this.setState({ errorText: 'Please provide a valid email', }); return; } this.setState({ errorText: null, }); this.props.login(email); } render() { const fieldError = this.state.errorText ? ( <div className={styles.errorMessage} > {this.state.errorText} </div> ) : null; return ( <div className={styles.login}> <div className={styles.heading} > Login with your email </div> <input className={classNames(styles.input, { [styles.inputError]: this.state.errorText })} placeholder="Your email" ref={(f) => { this.emailField = f; }} type="text" /> {fieldError} <div className={styles.actionContainer} > <div className={styles.button} onClick={this.props.cancelLogin} > cancel </div> <div className={styles.button} onClick={this.login} > log in </div> </div> </div> ); } } export default Login;
admin/client/components/FooterBar.js
andreufirefly/keystone
import React from 'react'; import blacklist from 'blacklist'; var FooterBar = React.createClass({ propTypes: { style: React.PropTypes.object, }, getDefaultProps () { return { style: {}, }; }, getInitialState () { return { position: 'relative', width: 'auto', height: 'auto', top: 0, }; }, componentDidMount () { // Bail in IE8 because React doesn't support the onScroll event in that browser // Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here if (!window.getComputedStyle) return; var footer = this.refs.footer; this.windowSize = this.getWindowSize(); var footerStyle = window.getComputedStyle(footer); this.footerSize = { x: footer.offsetWidth, y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0'), }; window.addEventListener('scroll', this.recalcPosition, false); window.addEventListener('resize', this.recalcPosition, false); this.recalcPosition(); }, getWindowSize () { return { x: window.innerWidth, y: window.innerHeight, }; }, recalcPosition () { var wrapper = this.refs.wrapper; this.footerSize.x = wrapper.offsetWidth; var offsetTop = 0; var offsetEl = wrapper; while (offsetEl) { offsetTop += offsetEl.offsetTop; offsetEl = offsetEl.offsetParent; } var maxY = offsetTop + this.footerSize.y; var viewY = window.scrollY + window.innerHeight; var newSize = this.getWindowSize(); var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y); this.windowSize = newSize; var newState = { width: this.footerSize.x, height: this.footerSize.y, }; if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) { this.mode = 'inline'; newState.top = 0; newState.position = 'absolute'; this.setState(newState); } else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) { this.mode = 'fixed'; newState.top = window.innerHeight - this.footerSize.y; newState.position = 'fixed'; this.setState(newState); } }, render () { var wrapperStyle = { height: this.state.height, marginTop: 60, position: 'relative', }; var footerProps = blacklist(this.props, 'children', 'style'); var footerStyle = Object.assign({}, this.props.style, { position: this.state.position, top: this.state.top, width: this.state.width, height: this.state.height, }); return ( <div ref="wrapper" style={wrapperStyle}> <div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div> </div> ); }, }); module.exports = FooterBar;
packages/@vega/tracks-tool/src/components/TracksArticlesTable.js
VegaPublish/vega-studio
/* eslint-disable react/jsx-no-bind, complexity */ import React from 'react' import PropTypes from 'prop-types' import styles from './styles/TracksArticlesTable.css' import Menu from 'part:@lyra/components/menus/default' import ArrowDropDown from 'part:@lyra/base/arrow-drop-down' import {filterArticles, stagesSuperset} from '../utils' import TrackStageTableCell from './TrackStageTableCell' import {Portal} from 'part:@lyra/components/utilities/portal' import {Manager, Popper, Target} from 'react-popper' function issueTitle(issue) { return [issue.year, issue.title].filter(Boolean).join(' - ') } class TracksArticlesTable extends React.Component { static propTypes = { onUpdateSelection: PropTypes.func.isRequired, currentTrackName: PropTypes.string, currentIssueId: PropTypes.string, currentStageName: PropTypes.string, articles: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, title: PropTypes.string }) ), issues: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, volume: PropTypes.string, number: PropTypes.number, year: PropTypes.number }) ), tracks: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, title: PropTypes.string, trackStages: PropTypes.arrayOf( PropTypes.shape({ stage: PropTypes.object }) ) }) ) } state = { rootMenuOpen: false } static defaultProps = { articles: [], issues: [], tracks: [], currentTrackName: null, currentIssueId: null, currentStageName: null } rootMenuItems() { const {issues} = this.props return [{title: 'All', key: 'all'}].concat( issues.map(issue => { return { title: issueTitle(issue), key: issue._id } }) ) } handleRootMenuAction = rootMenuItem => { const {onUpdateSelection} = this.props if (rootMenuItem.key === 'all') { onUpdateSelection({track: null, stage: null, issue: null}) } else { onUpdateSelection({issue: rootMenuItem.key}) } this.handleRootMenuClose() } handleRootMenuClose = () => { this.setState({rootMenuOpen: false}) } handleRootMenuOpen = () => { this.setState({rootMenuOpen: true}) } render() { const { issues, tracks, currentTrackName, currentIssueId, currentStageName, onUpdateSelection, articles } = this.props const stages = stagesSuperset(tracks) const selectedIssue = issues.find(issue => issue._id === currentIssueId) const rootMenuTitle = selectedIssue ? issueTitle(selectedIssue) : 'All' if (issues.length < 1 || tracks.length < 1) { return <div>No issues or tracks</div> } return ( <table className={styles.root}> <thead className={styles.tableHead}> <tr> <th className={styles.rootCell}> <Manager> <Target> <div onClick={this.handleRootMenuOpen}> <span>{rootMenuTitle}</span> <span className={styles.arrowDropDown}> <ArrowDropDown /> </span> </div> </Target> {this.state.rootMenuOpen && ( <Portal> <Popper> <Menu items={this.rootMenuItems()} onAction={this.handleRootMenuAction} onClose={this.handleRootMenuClose} onClickOutside={this.handleRootMenuClose} isOpen /> </Popper> </Portal> )} </Manager> </th> {stages.map(stage => { const stageColumnKey = stage.name const handleColumnClick = () => { const selectStage = currentStageName !== stage.name || (currentStageName && currentTrackName) return onUpdateSelection({ stage: selectStage ? stage.name : null, track: null }) } const colorStyle = {color: `${stage.displayColor}`} return ( <th onClick={handleColumnClick} key={stageColumnKey} style={colorStyle} className={` ${styles.stageHeader} ${styles[`stage__${stage.name}`]} ${ currentStageName == stage.name && !currentTrackName ? styles.active : styles.inActive } `} > <div className={styles.stageTitle}>{stage.title}</div> </th> ) })} </tr> </thead> <tbody className={styles.tableBody}> {tracks.map(track => { const trackRowKey = track.name const handleRowClick = () => { const selectTrack = currentTrackName !== track.name || (currentTrackName && currentStageName) return onUpdateSelection({ track: selectTrack ? track.name : null, stage: null }) } return ( <tr key={trackRowKey} className={styles.trackRow}> <th onClick={handleRowClick} className={` ${styles.trackHeader} ${ currentTrackName == track.name && !currentStageName ? styles.active : styles.inActive } `} > {track.title} </th> {stages.map(stage => { const stageCellKey = `${track.name}_${stage.name}` const isActive = (currentStageName == stage.name && currentTrackName == track.name) || (currentStageName == stage.name && !currentTrackName) || (currentTrackName == track.name && !currentStageName) const filterOptions = { track: track.name, stage: stage.name, issue: currentIssueId } const filteredArticles = filterArticles( articles, filterOptions ) return ( <TrackStageTableCell onUpdateSelection={this.props.onUpdateSelection} key={stageCellKey} track={track} stage={stage} articles={filteredArticles} isActive={isActive} /> ) })} </tr> ) })} </tbody> </table> ) } } export default TracksArticlesTable /* eslint-enable react/jsx-no-bind, complexity */
src/ProjectBoard.js
mikadamsterdam/react_for_project
import React from 'react'; import jQuery from 'jquery'; import Project from './Project'; import AddProject from './AddProject'; class ProjectBoard extends React.Component { constructor(){ super(); this.state = { projects: [ ] }; } reloadProjectBoard(){ let component = this; jQuery.getJSON("https://taskpool.herokuapp.com/projects/", function(data){ component.setState({ projects: data.projects }) }); } componentDidMount() { this.reloadProjectBoard(); } renderProject(project){ return <Project id={project.id} name={project.name} goal={project.goal} />; } onAddProject(newName, newGoal){ var currentProjects = this.state.projects; var newProjects = currentProjects.concat(newName, newGoal); this.setState({ projects: newProjects }); } render() { return ( <div> <AddProject onSubmit={this.onAddProject.bind(this)} /> <hr /> <table> <tbody> {this.state.projects.map(this.renderProject.bind(this))} </tbody> </table> </div> ); } } export default ProjectBoard;
components/slider/Slider.js
rubenmoya/react-toolbox
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import styleShape from 'react-style-proptype'; import { themr } from 'react-css-themr'; import { round, range } from '../utils/utils'; import { SLIDER } from '../identifiers'; import events from '../utils/events'; import InjectProgressBar from '../progress_bar/ProgressBar'; import InjectInput from '../input/Input'; const factory = (ProgressBar, Input) => { class Slider extends Component { static propTypes = { buffer: PropTypes.number, className: PropTypes.string, disabled: PropTypes.bool, editable: PropTypes.bool, max: PropTypes.number, min: PropTypes.number, onChange: PropTypes.func, onDragStart: PropTypes.func, onDragStop: PropTypes.func, pinned: PropTypes.bool, snaps: PropTypes.bool, step: PropTypes.number, style: styleShape, theme: PropTypes.shape({ container: PropTypes.string, editable: PropTypes.string, innerknob: PropTypes.string, innerprogress: PropTypes.string, input: PropTypes.string, knob: PropTypes.string, pinned: PropTypes.string, pressed: PropTypes.string, progress: PropTypes.string, ring: PropTypes.string, slider: PropTypes.string, snap: PropTypes.string, snaps: PropTypes.string, }), value: PropTypes.number, }; static defaultProps = { buffer: 0, className: '', editable: false, max: 100, min: 0, onDragStart: () => {}, onDragStop: () => {}, pinned: false, snaps: false, step: 0.01, value: 0, }; state = { inputFocused: false, inputValue: null, sliderLength: 0, sliderStart: 0, }; componentDidMount() { window.addEventListener('resize', this.handleResize); this.handleResize(); } componentWillReceiveProps(nextProps) { if (this.state.inputFocused && this.props.value !== nextProps.value) { this.setState({ inputValue: this.valueForInput(nextProps.value) }); } } shouldComponentUpdate(nextProps, nextState) { return this.state.inputFocused || !nextState.inputFocused; } componentWillUpdate(nextProps, nextState) { if (nextState.pressed !== this.state.pressed) { if (nextState.pressed) { this.props.onDragStart(); } else { this.props.onDragStop(); } } } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); events.removeEventsFromDocument(this.getMouseEventMap()); events.removeEventsFromDocument(this.getTouchEventMap()); events.removeEventsFromDocument(this.getKeyboardEvents()); } getInput() { return this.inputNode && this.inputNode.getWrappedInstance ? this.inputNode.getWrappedInstance() : this.inputNode; } getKeyboardEvents() { return { keydown: this.handleKeyDown, }; } getMouseEventMap() { return { mousemove: this.handleMouseMove, mouseup: this.handleMouseUp, }; } getTouchEventMap() { return { touchmove: this.handleTouchMove, touchend: this.handleTouchEnd, }; } addToValue(increment) { let value = this.state.inputFocused ? parseFloat(this.state.inputValue) : this.props.value; value = this.trimValue(value + increment); if (value !== this.props.value) this.props.onChange(value); } handleInputFocus = () => { this.setState({ inputFocused: true, inputValue: this.valueForInput(this.props.value), }); }; handleInputChange = (value) => { this.setState({ inputValue: value }); }; handleInputBlur = (event) => { const value = this.state.inputValue || 0; this.setState({ inputFocused: false, inputValue: null }, () => { this.props.onChange(this.trimValue(value), event); }); }; handleKeyDown = (event) => { if ([13, 27].indexOf(event.keyCode) !== -1) this.getInput().blur(); if (event.keyCode === 38) this.addToValue(this.props.step); if (event.keyCode === 40) this.addToValue(-this.props.step); }; handleMouseDown = (event) => { if (this.state.inputFocused) this.getInput().blur(); events.addEventsToDocument(this.getMouseEventMap()); this.start(events.getMousePosition(event)); events.pauseEvent(event); }; handleMouseMove = (event) => { events.pauseEvent(event); this.move(events.getMousePosition(event)); }; handleMouseUp = () => { this.end(this.getMouseEventMap()); }; handleResize = (event, callback) => { const { left, right } = ReactDOM.findDOMNode(this.progressbarNode).getBoundingClientRect(); const cb = (callback) || (() => {}); this.setState({ sliderStart: left, sliderLength: right - left }, cb); }; handleSliderBlur = () => { events.removeEventsFromDocument(this.getKeyboardEvents()); }; handleSliderFocus = () => { events.addEventsToDocument(this.getKeyboardEvents()); }; handleTouchEnd = () => { this.end(this.getTouchEventMap()); }; handleTouchMove = (event) => { this.move(events.getTouchPosition(event)); }; handleTouchStart = (event) => { if (this.state.inputFocused) this.getInput().blur(); this.start(events.getTouchPosition(event)); events.addEventsToDocument(this.getTouchEventMap()); events.pauseEvent(event); }; end(revents) { events.removeEventsFromDocument(revents); this.setState({ pressed: false }); } knobOffset() { const { max, min, value } = this.props; return 100 * ((value - min) / (max - min)); } move(position) { const newValue = this.positionToValue(position); if (newValue !== this.props.value) this.props.onChange(newValue); } positionToValue(position) { const { sliderStart: start, sliderLength: length } = this.state; const { max, min, step } = this.props; const pos = ((position.x - start) / length) * (max - min); return this.trimValue((Math.round(pos / step) * step) + min); } start(position) { this.handleResize(null, () => { this.setState({ pressed: true }); this.props.onChange(this.positionToValue(position)); }); } stepDecimals() { return (this.props.step.toString().split('.')[1] || []).length; } trimValue(value) { if (value < this.props.min) return this.props.min; if (value > this.props.max) return this.props.max; return round(value, this.stepDecimals()); } valueForInput(value) { const decimals = this.stepDecimals(); return decimals > 0 ? value.toFixed(decimals) : value.toString(); } renderSnaps() { if (!this.props.snaps) return undefined; return ( <div className={this.props.theme.snaps}> {range(0, (this.props.max - this.props.min) / this.props.step).map(i => <div key={`span-${i}`} className={this.props.theme.snap} />, )} </div> ); } renderInput() { if (!this.props.editable) return undefined; return ( <Input ref={(node) => { this.inputNode = node; }} className={this.props.theme.input} disabled={this.props.disabled} onFocus={this.handleInputFocus} onChange={this.handleInputChange} onBlur={this.handleInputBlur} value={this.state.inputFocused ? this.state.inputValue : this.valueForInput(this.props.value)} /> ); } render() { const { theme } = this.props; const knobStyles = { left: `${this.knobOffset()}%` }; const className = classnames(theme.slider, { [theme.editable]: this.props.editable, [theme.disabled]: this.props.disabled, [theme.pinned]: this.props.pinned, [theme.pressed]: this.state.pressed, [theme.ring]: this.props.value === this.props.min, }, this.props.className); return ( <div className={className} disabled={this.props.disabled} data-react-toolbox="slider" onBlur={this.handleSliderBlur} onFocus={this.handleSliderFocus} style={this.props.style} tabIndex="0" > <div ref={(node) => { this.sliderNode = node; }} className={theme.container} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart} > <div ref={(node) => { this.knobNode = node; }} className={theme.knob} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart} style={knobStyles} > <div className={theme.innerknob} data-value={parseInt(this.props.value, 10)} /> </div> <div className={theme.progress}> <ProgressBar disabled={this.props.disabled} ref={(node) => { this.progressbarNode = node; }} className={theme.innerprogress} max={this.props.max} min={this.props.min} mode="determinate" value={this.props.value} buffer={this.props.buffer} /> {this.renderSnaps()} </div> </div> {this.renderInput()} </div> ); } } return Slider; }; const Slider = factory(InjectProgressBar, InjectInput); export default themr(SLIDER)(Slider); export { factory as sliderFactory }; export { Slider };
pewview/index.js
matthewcodes/PewView
window.$ = window.jQuery = require("jquery"); window.Tether = require('tether'); require('bootstrap'); require('./scss/index.scss'); import React from 'react'; import ReactDOM from 'react-dom'; import PewView from './components/PewView.jsx'; ReactDOM.render(<PewView />, document.getElementById('root'));
src/components/calendar/PersonalInfoSection.js
ChrisWhiten/react-rink
import React from 'react'; import { HelpBlock, FormGroup, FormControl, Col, } from 'react-bootstrap'; import MaskedInput from 'react-text-mask'; import './styles/PersonalInfoSection.css'; function FieldGroup({ id, label, help, validationState, ...props }) { return ( <FormGroup controlId={id} validationState={validationState}> <FormControl {...props} /> {help && <HelpBlock>{help}</HelpBlock>} </FormGroup> ); } class PersonalInfoSection extends React.Component { constructor() { super(); this.state = { selectedBooking: null, firstName: '', }; // this.notEmpty = this._notEmpty.bind(this); this.handleFirstNameChange = this.handleFirstNameChange.bind(this); this.handleLastNameChange = this.handleLastNameChange.bind(this); this.handleEmailChange = this.handleEmailChange.bind(this); this.handlePhoneNumberChange = this.handlePhoneNumberChange.bind(this); } // _notEmpty() { // if (this.state.firstName === null) { // return null; // } // return this.state.firstName.length > 0 ? 'success' : 'error'; // } handleFirstNameChange(e) { this.setState({ firstName: e.target.value, }); } handleLastNameChange(e) { this.setState({ lastName: e.target.value, }); } handleEmailChange(e) { this.setState({ email: e.target.value, }); } handlePhoneNumberChange(e) { this.setState({ phoneNumber: e.target.value, }); } clear() { this.setState({ phoneNumber: '', email: '', lastName: '', firstName: '', }); } render() { return ( <div> <Col md={6} lg={6} sm={6} xs={12}> <FieldGroup id='first-name-id' type='text' placeholder='First name' // validationState={this.notEmpty()} onChange={this.handleFirstNameChange} value={this.state.firstName} /> </Col> <Col md={6} lg={6} sm={6} xs={12}> <FieldGroup id='last-name-id' type='text' onChange={this.handleLastNameChange} placeholder='Last name' /> </Col> <Col md={6} lg={6} sm={6} xs={12}> <FieldGroup id='email-id' type='email' placeholder='Email' onChange={this.handleEmailChange} /> </Col> <Col md={6} lg={6} sm={6} xs={12}> <MaskedInput className='form-control' mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]} placeholder='(613) 555-5555' name='phone-number' id='phone-number-id' type='tel' onChange={this.handlePhoneNumberChange} /> {/* <FieldGroup id='phone-number-id' type='text' placeholder='Phone number' onChange={this.handlePhoneNumberChange} /> */} </Col> </div> ); } } PersonalInfoSection.propTypes = { }; export default PersonalInfoSection;