path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
actor-apps/app-web/src/app/components/sidebar/RecentSection.react.js
stonegithubs/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import DialogActionCreators from 'actions/DialogActionCreators'; import DialogStore from 'stores/DialogStore'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import RecentSectionItem from './RecentSectionItem.react'; import CreateGroupModal from 'components/modals/CreateGroup.react'; import CreateGroupStore from 'stores/CreateGroupStore'; const ThemeManager = new Styles.ThemeManager(); const LoadDialogsScrollBottom = 100; const getStateFromStore = () => { return { isCreateGroupModalOpen: CreateGroupStore.isModalOpen(), dialogs: DialogStore.getAll() }; }; class RecentSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = getStateFromStore(); DialogStore.addChangeListener(this.onChange); DialogStore.addSelectListener(this.onChange); CreateGroupStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } componentWillUnmount() { DialogStore.removeChangeListener(this.onChange); DialogStore.removeSelectListener(this.onChange); CreateGroupStore.removeChangeListener(this.onChange); } onChange = () => { this.setState(getStateFromStore()); } openCreateGroup = () => { CreateGroupActionCreators.openModal(); } onScroll = event => { if (event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight <= LoadDialogsScrollBottom) { DialogActionCreators.onDialogsEnd(); } } render() { let dialogs = _.map(this.state.dialogs, (dialog, index) => { return ( <RecentSectionItem dialog={dialog} key={index}/> ); }, this); let createGroupModal; if (this.state.isCreateGroupModalOpen) { createGroupModal = <CreateGroupModal/>; } return ( <section className="sidebar__recent"> <ul className="sidebar__list sidebar__list--recent" onScroll={this.onScroll}> {dialogs} </ul> <footer> <RaisedButton label="Create group" onClick={this.openCreateGroup} style={{width: '100%'}}/> {createGroupModal} </footer> </section> ); } } export default RecentSection;
packages/shared/ReactSharedInternals.js
rickbeerendonk/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; const ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { ReactSharedInternals.ReactCurrentDispatcher = { current: null, }; } if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null, }; } export default ReactSharedInternals;
demo.js
tweinfeld/backscatter
import _ from 'underscore'; import Backbone from 'backbone'; import Backscatter from './lib/backscatter.js'; import React from 'react'; class MyCustomComponent extends React.Component { render(){ return <div>{ this.props.title }, { this.props.name }</div> } } // This model is an example of an existing model that's extended to enable backscatter updates (see "createFactory") let MyExistingModel = Backbone.Model.extend({ defaults: { id: "name", name: "John Doe" } }); let A = new Backscatter.Model({ id: "title", "title": `Howdy` }), B = new (Backscatter.createFactory(MyExistingModel)), C = new Backscatter.Model({ "a": A, "b": B }), D = new Backscatter.Collection([C]); let renderComponent = function(){ React.render(React.createElement(MyCustomComponent, { title: D.at(0).get('a').get('title'), name: D.at(0).get('b').get('name') }), document.querySelector('body')); }; // Set backscatter to render your component whenever there are changes to your model D.backscatterOn(_.debounce(function(...[target, name]){ console.log(`We've got a change on "${target.id}" with event name "${name}"`) renderComponent(); })); // Perform a change somewhere in your model, and let backscatter react setTimeout(function(){ // Let's touch our model somewhere in a deep nested location A.set({ "title": `Hello` }) }, 1000); setTimeout(function(){ // Let's touch our model somewhere else in a deep nested location B.set({ "name": `Mark Smith` }) }, 2000); renderComponent();
guess/app/app.js
ekepes/reactplay
import React from 'react'; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var GuessBox = React.createClass({ getInitialState: function() { return { answer: getRandomInt(1, 10), guess: 0, message: "" }; }, handleChange: function(event) { this.setState({ guess: event.target.value }); }, checkGuess: function() { if (this.state.guess != 0) { if (this.state.guess == this.state.answer) { this.setState({ message: "You guessed it!" }); } else if (this.state.guess < this.state.answer) { this.setState({ message: "You guessed too low." }); } else if (this.state.guess > this.state.answer) { this.setState({ message: "You guessed too high." }); } else { this.setState({ message: "Please enter a guess!" }); } } }, render: function() { return ( <div className="well clearfix"> <h1>Guess My Number!</h1> <label>Guess (1-10):</label> <input id="guess-field" type="number" min="1" max="10" onChange={this.handleChange}></input> <button className="btn btn-default pull-right" onClick={this.checkGuess}>Guess</button> <div> <strong>{ this.state.message }</strong> </div> </div> ); } }); export default GuessBox;
demo.js
jrowny/react-absolute-grid
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; // import Perf from 'react-addons-perf'; import createAbsoluteGrid from './index.js'; import SampleDisplay from './demo/SampleDisplay.jsx'; import * as data from './demo/sampleData.js'; import * as _ from 'lodash'; demo(); /** * This demo is meant to show you all of the things that are possible with ReactAbsoluteGrid * If implemented in a Flux project, the grid would be in a render method with the * event handlers calling Actions which would update a Store. For the sake of brevity, * the "store" is implemented locally and the changes re-rendered manually * * TODO: implement inside a react component rather than doing this all manually **/ function demo() { let sampleItems = data.screens; let render; let zoom = 0.7; //We set a property on each item to let the grid know not to show it var onFilter = function(event){ var search = new RegExp(event.target.value, 'i'); sampleItems = sampleItems.map(function(item){ const isMatched = !item.name.match(search); if(!item.filtered || isMatched !== item.filtered) { return { ...item, filtered: isMatched } } return item; }); render(); }; //Change the item's sort order var onMove = function(source, target){ source = _.find(sampleItems, {key: parseInt(source, 10)}); target = _.find(sampleItems, {key: parseInt(target, 10)}); const targetSort = target.sort; //CAREFUL, For maximum performance we must maintain the array's order, but change sort sampleItems = sampleItems.map(function(item){ //Decrement sorts between positions when target is greater if(item.key === source.key) { return { ...item, sort: targetSort } } else if(target.sort > source.sort && (item.sort <= target.sort && item.sort > source.sort)){ return { ...item, sort: item.sort - 1 }; //Increment sorts between positions when source is greater } else if (item.sort >= target.sort && item.sort < source.sort){ return { ...item, sort: item.sort + 1 }; } return item; }); //Perf.start(); render(); //Perf.stop(); //Perf.printWasted(); }; var onMoveDebounced = _.debounce(onMove, 40); var unMountTest = function(){ if(ReactDOM.unmountComponentAtNode(document.getElementById('Demo'))){ ReactDOM.render(<button onClick={unMountTest}>Remount</button>, document.getElementById('UnmountButton')); }else{ render(); ReactDOM.render(<button onClick={unMountTest}>Test Unmount</button>, document.getElementById('UnmountButton')); } }; const AbsoluteGrid = createAbsoluteGrid(SampleDisplay); render = function(){ ReactDOM.render(<AbsoluteGrid items={sampleItems} onMove={onMoveDebounced} dragEnabled={true} zoom={zoom} responsive={true} verticalMargin={42} itemWidth={230} itemHeight={409}/>, document.getElementById('Demo')); }; var renderDebounced = _.debounce(render, 150); //Update the zoom value var onZoom = function(event){ zoom = parseFloat(event.target.value); renderDebounced(); }; ReactDOM.render(<input onChange={onZoom} type='range' min='0.3' max='1.5' step='0.1' defaultValue={zoom}/>, document.getElementById('Zoom')); ReactDOM.render(<input placeholder='Filter eg: calendar' onChange={onFilter} type='text'/>, document.getElementById('Filter')); ReactDOM.render(<button onClick={unMountTest}>Test Unmount</button>, document.getElementById('UnmountButton')); render(); }
app/components/Seat/ButtonJoinSeat.js
acebusters/ab-web
import React from 'react'; import PropTypes from 'prop-types'; import { ButtonIcon, ButtonStyle, ButtonText, ButtonWrapper, SeatWrapper, } from './styles'; const ButtonJoinSeat = ({ coords, onClickHandler }) => ( <SeatWrapper coords={coords}> <ButtonWrapper onClick={onClickHandler}> <ButtonStyle> <ButtonIcon className="fa fa-plus" aria-hidden="true" /> <ButtonText>Join</ButtonText> </ButtonStyle> </ButtonWrapper> </SeatWrapper> ); ButtonJoinSeat.propTypes = { coords: PropTypes.array, onClickHandler: PropTypes.func, }; export default ButtonJoinSeat;
js/views/login/LogoutView.js
n8e/memoirs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay'; import { hashHistory } from 'react-router'; import LogoutMutation from '../../mutations/LogoutMutation'; class LogoutView extends Component { componentDidMount() { const onSuccess = () => { hashHistory.push('/login'); }; Relay.Store.commitUpdate(new LogoutMutation({ viewer: this.props.viewer, }), { onSuccess }); } render() { return (<noscript />); } } LogoutView.propTypes = { viewer: PropTypes.shape({ userInfo: PropTypes.shape({ userName: PropTypes.string, }), }).isRequired, }; export default Relay.createContainer(LogoutView, { fragments: { viewer: () => Relay.QL` fragment on User { ${LogoutMutation.getFragment('viewer')} userInfo { userName } } `, }, });
definitions/npm/react-redux_v5.x.x/flow_v0.30.x-v0.52.x/test_Provider.js
hansonw/flow-typed
// @flow import React from 'react' import { Provider } from 'react-redux' // $ExpectError <Provider />; // missing store
fields/types/password/PasswordColumn.js
Tangcuyu/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; var PasswordColumn = React.createClass({ displayName: 'PasswordColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; return value ? '********' : ''; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = PasswordColumn;
web/app/admin/invites.js
bitemyapp/serials
// @flow import React from 'react' import {Link} from 'react-router' import {invitesAll, invitesAdd, invitesSend, invitesDelete, Invite} from '../model/invite' import {userApiURL} from '../model/user' import {reloadHandler} from '../data/load' import {makeUpdate} from '../data/update' import {toDateString} from '../helpers' import {sortBy, reverse} from 'lodash' import {Routes} from '../router' // should farm them out to other display components // should have model functions that do all the lifting // but it needs to reload too ... hmm ... type InvitesProps = { invites: Array<any> } export class Invites extends React.Component { props: InvitesProps; static load(params) { return {invites: invitesAll()} } addInvites(emails:Array<string>) { Promise.all(emails.map(e => invitesAdd(e))) .then(reloadHandler) } sendInvite(code:string) { invitesSend(code) .then(reloadHandler) } deleteInvite(code:string) { invitesDelete(code) .then(reloadHandler) } render():React.Element { var invites = sortBy(this.props.invites || [], i => i.created).reverse() return <div> <h2>Invites</h2> <InvitesList invites={invites} onSend={this.sendInvite.bind(this)} onDelete={this.deleteInvite.bind(this)} /> <BulkInvites onAdd={this.addInvites.bind(this)}/> </div> } } export class InvitesList extends React.Component { render():React.Element { return <table> <tr> <th>Email</th> <th>Code</th> <th>User</th> <th></th> <th>Sent</th> <th>Created</th> <th></th> </tr> {this.props.invites.map(this.renderRow.bind(this))} </table> } renderRow(invite:Invite):React.Element { var sent = " " if (invite.sent) { sent = toDateString(invite.sent) } return <tr> <td>{invite.email}</td> <td><Link to={Routes.signup} params={{code: invite.code}}>{invite.code}</Link></td> <td><UserCell invite={invite} onSend={this.props.onSend}/></td> <td><InvitesSend invite={invite} onSend={this.props.onSend}/></td> <td>{sent}</td> <td>{toDateString(invite.created)}</td> <td><a onClick={() => this.props.onDelete(invite.code)}> <span className="fa fa-trash"></span> </a></td> </tr> } } class UserCell extends React.Component { render():React.Element { var invite = this.props.invite if (invite.signup) { return <a href={userApiURL(invite.signup.userId)}>{toDateString(invite.userId)}</a> } return <span/> } } export class InvitesSend extends React.Component { render():React.Element { var invite = this.props.invite return <a onClick={this.props.onSend.bind(null, invite.code)}> <span className="fa fa-paper-plane"></span> </a> } } export class BulkInvites extends React.Component { props: { onAdd:(emails:Array<string>)=>void; }; constructor(props:any) { super(props) this.state = { text: "" } } onClickAdd() { var emails = this.state.text.split(/[,\s]+/) this.props.onAdd(emails) this.setState({text: ""}) } render():React.Element { var update = e => this.setState({text: e.target.value}) return <div> <div><textarea rows="4" value={this.state.text} onChange={update} placeholder="comma or whitespace separated emails"></textarea></div> <div><button onClick={this.onClickAdd.bind(this)}>Add Invites</button></div> </div> } }
react/features/desktop-picker/components/DesktopPickerPane.js
bgrozev/jitsi-meet
/* @flow */ import { Checkbox } from '@atlaskit/checkbox'; import Spinner from '@atlaskit/spinner'; import React, { Component } from 'react'; import { Platform } from '../../base/react'; import { translate } from '../../base/i18n'; import DesktopSourcePreview from './DesktopSourcePreview'; /** * The type of the React {@code Component} props of {@link DesktopPickerPane}. */ type Props = { /** * The handler to be invoked when a DesktopSourcePreview is clicked. */ onClick: Function, /** * The handler to be invoked when a DesktopSourcePreview is double clicked. */ onDoubleClick: Function, /** * The handler to be invoked if the users checks the audio screen sharing checkbox. */ onShareAudioChecked: Function, /** * The id of the DesktopCapturerSource that is currently selected. */ selectedSourceId: string, /** * An array of DesktopCapturerSources. */ sources: Array<Object>, /** * The source type of the DesktopCapturerSources to display. */ type: string, /** * Used to obtain translations. */ t: Function }; /** * React component for showing a grid of DesktopSourcePreviews. * * @extends Component */ class DesktopPickerPane extends Component<Props> { /** * Initializes a new DesktopPickerPane instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props: Props) { super(props); this._onShareAudioCheck = this._onShareAudioCheck.bind(this); } _onShareAudioCheck: (Object) => void; /** * Function to be called when the Checkbox is used. * * @param {boolean} checked - Checkbox status (checked or not). * @returns {void} */ _onShareAudioCheck({ target: { checked } }) { this.props.onShareAudioChecked(checked); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { onClick, onDoubleClick, selectedSourceId, sources, type, t } = this.props; const classNames = `desktop-picker-pane default-scrollbar source-type-${type}`; const previews = sources ? sources.map(source => ( <DesktopSourcePreview key = { source.id } onClick = { onClick } onDoubleClick = { onDoubleClick } selected = { source.id === selectedSourceId } source = { source } type = { type } />)) : ( <div className = 'desktop-picker-pane-spinner'> <Spinner isCompleting = { false } size = 'medium' /> </div> ); let checkBox; // Only display the share audio checkbox if we're on windows and on // desktop sharing tab. // App window and Mac OS screen sharing doesn't work with system audio. if (type === 'screen' && Platform.OS === 'windows') { checkBox = (<Checkbox label = { t('dialog.screenSharingAudio') } name = 'share-system-audio' onChange = { this._onShareAudioCheck } />); } return ( <div className = { classNames }> { previews } { checkBox } </div> ); } } export default translate(DesktopPickerPane);
app/static/scripts/layout/footer/main.js
joshleeb/Tobio-PreRelease
import React from 'react'; require('./styles.scss'); export default class Footer extends React.Component { constructor() { super(); } render() { return ( <footer id="footer"> <div className="content"> <p id="version">Tobio <small>PreRelease 0.2.0</small></p> </div> <div className="copyright"> <a href="http://hydrogen252.com" target="_blank">Hydrogen252 Ventures</a><br /> <small>Copyright 2016 <a href="http://joshleeb.com" target="_blank">Josh Leeb-du Toit</a></small> </div> </footer> ) } }
src/DayColumn.js
manishksmd/react-scheduler-smartdata
import PropTypes from 'prop-types'; import React from 'react'; import { findDOMNode } from 'react-dom'; import cn from 'classnames'; import Selection, { getBoundsForNode, isEvent } from './Selection'; import dates from './utils/dates'; import { isSelected } from './utils/selection'; import localizer from './localizer' import { notify } from './utils/helpers'; import { accessor, elementType, dateFormat } from './utils/propTypes'; import { accessor as get } from './utils/accessors'; import Img from './img/doctor.png'; import getStyledEvents, { positionFromDate, startsBefore } from './utils/dayViewLayout' import TimeColumn from './TimeColumn' import AppointmentBox from './AppointmentBox'; function snapToSlot(date, step){ var roundTo = 1000 * 60 * step; return new Date(Math.floor(date.getTime() / roundTo) * roundTo) } function startsAfter(date, max) { return dates.gt(dates.merge(max, date), max, 'minutes') } class DaySlot extends React.Component { constructor(props) { super(props); this.hoverDialogActions = this.hoverDialogActions.bind(this); } static propTypes = { events: PropTypes.array.isRequired, step: PropTypes.number.isRequired, min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, now: PropTypes.instanceOf(Date), rtl: PropTypes.bool, titleAccessor: accessor, // @Appointment field info declaration patientNameAccessor: accessor, clinicianImageAccessor: accessor, clinicianNameAccessor: accessor, appointmentTypeAccessor: accessor, appointmentTimeAccessor: accessor, appointmentAddressAccessor: accessor, coPayAccessor: accessor, soapNoteTitleAccessor: accessor, setProfileTitleAccessor: accessor, staffsAccessor: accessor, isRecurrenceAccessor: accessor, isRecurrenceEditAccessor: accessor, isEditAccessor: accessor, isDeleteAccessor: accessor, isCancelAccessor: accessor, isUnCancelAccessor: accessor, isApproveAccessor: accessor, cancellationReasonAccessor: accessor, isAppointmentRenderedAccessor: accessor, isVideoCallAccessor: accessor, isAppoinmentCancelledAccessor: accessor, practitionerNameAccessor: accessor, allDayAccessor: accessor.isRequired, startAccessor: accessor.isRequired, endAccessor: accessor.isRequired, selectRangeFormat: dateFormat, eventTimeRangeFormat: dateFormat, culture: PropTypes.string, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), eventOffset: PropTypes.number, onSelecting: PropTypes.func, onSelectSlot: PropTypes.func.isRequired, onSelectEvent: PropTypes.func.isRequired, className: PropTypes.string, dragThroughEvents: PropTypes.bool, eventPropGetter: PropTypes.func, dayWrapperComponent: elementType, eventComponent: elementType, eventWrapperComponent: elementType.isRequired, resource: PropTypes.string, }; static defaultProps = { dragThroughEvents: true }; state = { selecting: false }; componentDidMount() { this.props.selectable && this._selectable() } componentWillUnmount() { this._teardownSelectable(); } componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable(); if (!nextProps.selectable && this.props.selectable) this._teardownSelectable(); } render() { const { min, max, step, now, selectRangeFormat, culture, ...props } = this.props this._totalMin = dates.diff(min, max, 'minutes') let { selecting, startSlot, endSlot } = this.state let style = this._slotStyle(startSlot, endSlot) let selectDates = { start: this.state.startDate, end: this.state.endDate }; let lastNodeOfWeek = document.getElementsByClassName('rbc-day-slot'); let len = lastNodeOfWeek.length; // @Week add class to last column - for sat let lastelement = len < 1 ? '' : lastNodeOfWeek[len-1]; if(lastelement.classList !== undefined) { lastelement.classList.add('custom-class-sat') } // @Week add class to last column - for friday let secondLastElement = len < 2 ? '' : lastNodeOfWeek[len-2]; if(secondLastElement.classList !== undefined) { secondLastElement.classList.add('custom-class-sat') } return ( <TimeColumn {...props} className={cn( 'rbc-day-slot', dates.isToday(max) && 'rbc-today' )} now={now} min={min} max={max} step={step} > {this.renderEvents()} {selecting && <div className='rbc-slot-selection' style={style}> <span> { localizer.format(selectDates, selectRangeFormat, culture) } </span> </div> } </TimeColumn> ); } renderEvents = () => { let { events , min , max , culture , eventPropGetter , selected, eventTimeRangeFormat, eventComponent , eventWrapperComponent: EventWrapper , rtl: isRtl , step , startAccessor , endAccessor , titleAccessor , isRecurrenceAccessor , isAppointmentRenderedAccessor , isVideoCallAccessor , isAppoinmentCancelledAccessor } = this.props; let EventComponent = eventComponent let styledEvents = getStyledEvents({ events, startAccessor, endAccessor, min, totalMin: this._totalMin, step }) return styledEvents.map(({ event, style }, idx) => { let start = get(event, startAccessor) let end = get(event, endAccessor) let continuesPrior = startsBefore(start, min) let continuesAfter = startsAfter(end, max) let title = get(event, titleAccessor) // @Appointment associate appointment data with the fields , isRecurrence = get(event, isRecurrenceAccessor) let isAppointmentRendered = get(event, isAppointmentRenderedAccessor); let isVideoCall = get(event, isVideoCallAccessor); let isAppoinmentCancelled = get(event, isAppoinmentCancelledAccessor); let label = localizer.format({ start, end }, eventTimeRangeFormat, culture) let _isSelected = isSelected(event, selected) let viewClass = ''; let getEndHour = end.getHours(); let maxEndHourForHoverup = max.getHours(); if (getEndHour > (maxEndHourForHoverup - 6)) { viewClass = this.props.view === 'week' ? 'appointment_box dayslot hoverup' : 'appointment_box hoverup'; } else { viewClass = this.props.view === 'week' ? 'appointment_box dayslot' : 'appointment_box'; } let dayClass = this.props.view === 'day' ? 'colwrap' : ''; if (eventPropGetter) var { style: xStyle, className } = eventPropGetter(event, start, end, _isSelected) let { height, top, width, xOffset } = style return ( <EventWrapper event={event} key={'evt_' + idx}> <div style={{ ...xStyle, top: `${top}%`, height: `${height}%`, [isRtl ? 'right' : 'left']: `${Math.max(0, xOffset)}%`, width: `${width}%` }} // title={label + ': ' + title } //onClick={(e) => this._select(event, e)} className={cn(`rbc-event ${dayClass}`, className, { 'rbc-selected': _isSelected, 'rbc-event-continues-earlier': continuesPrior, 'rbc-event-continues-later': continuesAfter })} > {/* <div className="rbc-event-label">{label}</div> */} <div className='rbc-event-label rbc-event-content textoverflow'> {isRecurrence ? <i className="fa fa-repeat pr5" aria-hidden="true"></i> : ''} {isAppointmentRendered ? <i className="fa fa-check-circle-o pr5" aria-hidden="true"></i> : ''} {isVideoCall ? <i className="fa fa-video-camera pr5" aria-hidden="true"></i> : ''} {isAppoinmentCancelled ? <i className="fa fa-ban pr5" aria-hidden="true"></i> : ''} { EventComponent ? <EventComponent event={event} /> : title } {label} </div> <AppointmentBox {...this.props} event={event} popupClassName={viewClass} hoverDialogActions={this.hoverDialogActions} /> </div> </EventWrapper> ) }) }; _slotStyle = (startSlot, endSlot) => { let top = ((startSlot / this._totalMin) * 100); let bottom = ((endSlot / this._totalMin) * 100); return { top: top + '%', height: bottom - top + '%' } }; _selectable = () => { let node = findDOMNode(this); let selector = this._selector = new Selection(()=> findDOMNode(this)) let maybeSelect = (box) => { let onSelecting = this.props.onSelecting let current = this.state || {}; let state = selectionState(box); let { startDate: start, endDate: end } = state; if (onSelecting) { if ( (dates.eq(current.startDate, start, 'minutes') && dates.eq(current.endDate, end, 'minutes')) || onSelecting({ start, end }) === false ) return } this.setState(state) } let selectionState = ({ y }) => { let { step, min, max } = this.props; let { top, bottom } = getBoundsForNode(node) let mins = this._totalMin; let range = Math.abs(top - bottom) let current = (y - top) / range; current = snapToSlot(minToDate(mins * current, min), step) if (!this.state.selecting) this._initialDateSlot = current let initial = this._initialDateSlot; if (dates.eq(initial, current, 'minutes')) current = dates.add(current, step, 'minutes') let start = dates.max(min, dates.min(initial, current)) let end = dates.min(max, dates.max(initial, current)) return { selecting: true, startDate: start, endDate: end, startSlot: positionFromDate(start, min, this._totalMin), endSlot: positionFromDate(end, min, this._totalMin) } } selector.on('selecting', maybeSelect) selector.on('selectStart', maybeSelect) selector.on('mousedown', (box) => { if (this.props.selectable !== 'ignoreEvents') return return !isEvent(findDOMNode(this), box) }) selector .on('click', (box) => { if (!isEvent(findDOMNode(this), box)) this._selectSlot({ ...selectionState(box), action: 'click' }) this.setState({ selecting: false }) }) selector .on('select', () => { if (this.state.selecting) { this._selectSlot({ ...this.state, action: 'select' }) this.setState({ selecting: false }) } }) }; _teardownSelectable = () => { if (!this._selector) return this._selector.teardown(); this._selector = null; }; _selectSlot = ({ startDate, endDate, action }) => { let current = startDate , slots = []; while (dates.lte(current, endDate)) { slots.push(current) current = dates.add(current, this.props.step, 'minutes') } notify(this.props.onSelectSlot, { slots, start: startDate, end: endDate, resourceId: this.props.resource, action }) }; _select = (...args) => { notify(this.props.onSelectEvent, args) }; hoverDialogActions(event, e, action) { e.preventDefault(); event.action = action; this._select(event, e); } } function minToDate(min, date){ var dt = new Date(date) , totalMins = dates.diff(dates.startOf(date, 'day'), date, 'minutes'); dt = dates.hours(dt, 0); dt = dates.minutes(dt, totalMins + min); dt = dates.seconds(dt, 0) return dates.milliseconds(dt, 0) } export default DaySlot;
src/components/StreamItemView/index.js
Reditr-Software/reditr
import React from 'react' import moment from 'moment' import { AllHtmlEntities as Entities } from 'html-entities' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' import style from '../../utilities/Style' import reddit from '../../api/reddit' import CommentModel from '../../models/CommentModel' import StreamCommentView from '../StreamCommentView' import VoteView from '../VoteView' import { prettyNumber } from '../../utilities/Common' import MediaParserView from '../MediaParserView' class StreamItemView extends React.Component { static contextTypes = { setViewerState: PropTypes.func, router: PropTypes.object } static propTypes = { post: PropTypes.object, inColumn: PropTypes.bool, onHoverEnter: PropTypes.func, onHoverLeave: PropTypes.func } static defaultProps = { onHoverEnter() {}, onHoverLeave() {} } static style() { const streamTitle = { fontWeight: 'normal', color: '#333', textDecoration: 'none', fontSize: '15px' } const streamTitleLink = { ...streamTitle, '&:hover': { color: 'black', textDecoration: 'underline' } } return { streamTitle, streamTitleLink } } constructor(props) { super(props) // get the vote direction let voteDir = 0 switch (this.props.post.get('likes')) { case null: voteDir = 0 break case true: voteDir = 1 break case false: voteDir = -1 break } // set default this.state = { topComments: [], isLoading: true, showNSFW: false } if (this.props.postIds) { this.props.postIds[this.props.post.get('id')] = this } } componentDidMount() { this.loadComments() } onMouseEnter = e => { this.props.onHoverEnter(this.props.post, e.currentTarget) } onMouseLeave = e => { this.props.onHoverLeave() } loadComments() { let permalink = this.props.post.get('permalink') if (permalink) { // if permalink exists, proceed reddit.getPostFromPermalink(this.props.post.get('permalink'), null, (err, data) => { let comments = data.body[1].data.children let maxComments = Math.min(comments.length, 5) var first, second for (var i = 0; i < maxComments; i++) { var checking = comments[i] if (checking.data.body == '[removed]') continue if (!first) { first = checking } else if (!second) { second = checking } else { var newFirst = first.data.body.length < second.data.body.length ? first : second var rejected = newFirst == first ? second : first first = newFirst second = rejected.data.body.length < checking.data.body.length ? rejected : checking } } var topComments = [] if (first) topComments.push(first) if (second) topComments.push(second) this.setState({ isLoading: false, topComments: topComments, comments: comments }) }) } else { this.setState({ isLoading: false, topComments: [] }) } } enableNSFW() { this.setState({ showNSFW: true }) } didDisappear(post) { this.setState({ hidden: true, height: post.clientHeight }) } didAppear() { this.setState({ hidden: false }) } openInPostView = () => { if (this.props.inColumn) { this.context.router.history.push(this.props.post.get('permalink')) } } renderMedia = () => { const post = this.props.post let postMedia = false if (!this.props.inColumn) { if (post.get('over_18') && !this.state.showNSFW) { postMedia = ( <div onClick={this.enableNSFW.bind(this)} className="nsfw-btn"> Show NSFW Content </div> ) } else if (this.state.hidden) { postMedia = false } else { postMedia = <MediaParserView onClick={url => this.context.setViewerState(url)} url={post.get('url')} post={post} /> } } return postMedia } renderTopComments = () => { const post = this.props.post const topComments = this.state.topComments let commentsView = [] // if no comments, say no comments if (topComments.length == 0) { commentsView = <span className="no-comments">No comments!</span> } else { var commentCount = post.get('num_comments') topComments.forEach(comment => { commentCount-- let commentObj = new CommentModel(comment) commentsView.push(<StreamCommentView key={commentObj.get('id')} comment={commentObj} />) }) if (this.state.comments.length > 2) { commentCount = commentCount <= 0 ? '' : prettyNumber(commentCount) commentsView.push( <Link key="more" text={Entities.decode(post.get('title'))} to={post.get('permalink')} className="view-more-comments"> <div className="icon">{commentCount} More Comments</div> </Link> ) } } return commentsView } renderDetails = () => { const post = this.props.post if (this.props.inColumn) { const styles = { container: { clear: 'both', fontSize: '12px', display: 'flex', justifyContent: 'space-between', width: '100%', marginTop: '5px' } } return ( <div style={styles.container} className="mini-details"> <Link to={'/user/' + post.get('author')} className="stream-item-author"> {post.get('author')} </Link> <span> {moment .unix(post.get('created_utc')) .fromNow() .replace(/ ago/, '') .replace(/ day(s|)/, 'd') .replace(/ hour(s|)/, 'h') .replace(/ week(s|)/, 'w') .replace(/ (minute|min)(s|)/, 'm') } </span> </div> ) } else { return ( <div className="mini-details"> <Link to={'/user/' + post.get('author')} className="stream-item-author"> {post.get('author')} </Link> <span> posted in </span> <Link to={'/r/' + post.get('subreddit')} className="stream-item-subreddit"> {'/r/' + post.get('subreddit')} </Link> <span> {moment.unix(post.get('created_utc')).fromNow()}</span> </div> ) } } renderThumbnail = () => { const post = this.props.post if (this.props.inColumn && post.get('thumbnail') && post.get('domain').indexOf('self.') === -1) { const styles = { thumbnail: { float: 'left', width: '50px', height: '50px', borderRadius: '4px', border: '1px solid #fefefe', backgroundImage: `url(${post.get('thumbnail')})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', marginRight: '5px', marginBottom: '5px' } } return <div style={styles.thumbnail} /> } } renderTitle = () => { const post = this.props.post if (this.props.inColumn) { return <span className={this.props.classes.streamTitle}>{Entities.decode(post.get('title'))}</span> } else { return ( <a className={this.props.classes.streamTitleLink} href={post.get('url')} target="_blank"> {Entities.decode(post.get('title'))} </a> ) } } render() { const post = this.props.post // WARN: if it is a comment, ignore for now if (post.kind == 't1') { return false } let styles = { container: { minHeight: this.state.height || 'auto' }, voteContainer: { borderLeft: '1px solid #efefef' } } if (this.props.inColumn) { styles.container = { ...styles.container, cursor: 'pointer', margin: 0, borderRadius: 0, borderTop: 'none', borderLeft: 'none', borderRight: 'none', borderBottom: '1px solid #efefef', minHeight: '90px' } styles.voteContainer = { ...styles.voteContainer, width: '50px', fontSize: '12px' } styles.content = { width: 'calc(100% - 50px)', boxSizing: 'border-box' } } if (this.state.hidden) { return ( <div style={styles.container} onClick={this.openInPostView} className="stream-item-view hidden" data-postid={post.get('id')}> <div className="stream-item-top"> <div style={styles.voteContainer} className="stream-item-sidebar"> <VoteView item={this.props.post} /> </div> <div className="stream-item-content"> <a href={post.get('url')} target="_blank" className={this.props.classes.streamTitle}> {Entities.decode(post.get('title'))} </a> </div> </div> </div> ) } return ( <div style={styles.container} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} onClick={this.openInPostView} className="stream-item-view" data-postid={post.get('id')}> <div className="stream-item-top"> <div style={styles.voteContainer} className="stream-item-sidebar"> <VoteView item={this.props.post} /> </div> <div style={styles.content} className="stream-item-content"> {this.renderThumbnail()} {this.renderTitle()} <span className="stream-item-domain">({post.get('domain')})</span> {this.renderMedia()} {this.renderDetails()} </div> </div> {this.props.inColumn ? null : ( <div className="stream-item-comments">{this.state.isLoading ? <div className="loading">Loading...</div> : this.renderTopComments()}</div> )} </div> ) } } export default style(StreamItemView)
vj4/ui/components/scratchpad/ScratchpadRecordsContainer.js
vijos/vj4
import React from 'react'; import { connect } from 'react-redux'; import Tabs, { TabPane } from 'rc-tabs'; import TabContent from 'rc-tabs/lib/TabContent'; import ScrollableInkTabBar from 'rc-tabs/lib/ScrollableInkTabBar'; import i18n from 'vj/utils/i18n'; import request from 'vj/utils/request'; import Icon from 'vj/components/react/IconComponent'; import Panel from './PanelComponent'; import PanelButton from './PanelButtonComponent'; import ScratchpadRecordsTable from './ScratchpadRecordsTableContainer'; const mapDispatchToProps = dispatch => ({ loadSubmissions() { dispatch({ type: 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS', payload: request.get(Context.getSubmissionsUrl), }); }, handleClickClose() { dispatch({ type: 'SCRATCHPAD_UI_SET_VISIBILITY', payload: { uiElement: 'records', visibility: false, }, }); }, handleClickRefresh() { this.loadSubmissions(); }, }); @connect(null, mapDispatchToProps) export default class ScratchpadRecordsContainer extends React.PureComponent { componentDidMount() { this.props.loadSubmissions(); } render() { return ( <Panel title={( <span> <Icon name="flag" /> {' '} {i18n('Records')} </span> )} > <Tabs className="scratchpad__panel-tab flex-col flex-fill" activeKey="all" animation="slide-horizontal" renderTabBar={() => ( <ScrollableInkTabBar extraContent={( <span> <PanelButton data-tooltip={i18n('Refresh Records')} data-tooltip-pos="top right" onClick={() => this.props.handleClickRefresh()} > {i18n('Refresh')} </PanelButton> <PanelButton onClick={() => this.props.handleClickClose()} > <Icon name="close" /> </PanelButton> </span> )} /> )} renderTabContent={() => <TabContent />} > <TabPane tab={<span>{i18n('All')}</span>} key="all"> <ScratchpadRecordsTable /> </TabPane> </Tabs> </Panel> ); } }
packages/react-jsx-highstock/src/components/Scrollbar/Scrollbar.js
AlexMayants/react-jsx-highcharts
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hidden from 'react-jsx-highcharts/src/components/Hidden'; import getModifiedProps from 'react-jsx-highcharts/src/utils/getModifiedProps'; class Scrollbar extends Component { static propTypes = { update: PropTypes.func, // Provided by ChartProvider enabled: PropTypes.bool.isRequired }; static defaultProps = { enabled: true }; constructor (props) { super(props); this.updateScrollbar = this.updateScrollbar.bind(this); } componentDidMount () { const { children, ...rest } = this.props; this.updateScrollbar({ ...rest }); } componentDidUpdate (prevProps) { const modifiedProps = getModifiedProps(prevProps, this.props); if (modifiedProps !== false) { this.updateScrollbar(modifiedProps); } } componentWillUnmount () { this.updateScrollbar({ enabled: false }); } updateScrollbar (config) { this.props.update({ scrollbar: config }, true); } render () { const { children } = this.props; if (!children) return null; return ( <Hidden>{children}</Hidden> ); } } export default Scrollbar;
src/lib/reactors/Legend/PolylineSymbol.js
EsriJapan/photospot-finder
// Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; class PolylineSymbol extends React.Component { constructor (props) { super(props); } render () { return ( <div className="react-webmap-legend-row"> <div className="react-webmap-legend-cell react-webmap-legend-symbol"> <svg overflow="hidden" width="30" height="30"> <defs></defs> <path fill="none" fillOpacity="0" stroke={this.props.color} strokeOpacity={this.props.opacity} strokeWidth={this.props.width} strokeLinecap="butt" strokeLinejoin="miter" strokeMiterlimit="4" d="M-15 0L 15 0" strokeDasharray={this.props.dasharray} transform="matrix(1.00000000,0.00000000,0.00000000,1.00000000,15.00000000,15.00000000)"></path> </svg> </div> <div className="react-webmap-legend-cell react-webmap-legend-label"> {this.props.label} </div> </div> ); } } PolylineSymbol.propTypes = { color: React.PropTypes.string, opacity: React.PropTypes.string, width: React.PropTypes.string, dasharray: React.PropTypes.string, label: React.PropTypes.string }; PolylineSymbol.displayName = 'PolylineSymbol'; export default PolylineSymbol;
js/jqwidgets/jqwidgets-react/react_jqxmaskedinput.js
luissancheza/sice
/* jQWidgets v5.3.2 (2017-Sep) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxMaskedInput extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['disabled','height','mask','promptChar','readOnly','rtl','theme','textAlign','value','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxMaskedInput(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxMaskedInput('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxMaskedInput(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('disabled', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('disabled'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('height', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('height'); } }; mask(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('mask', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('mask'); } }; promptChar(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('promptChar', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('promptChar'); } }; readOnly(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('readOnly', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('readOnly'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('rtl', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('rtl'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('theme', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('theme'); } }; textAlign(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('textAlign', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('textAlign'); } }; value(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('value', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('value'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('width', arg) } else { return JQXLite(this.componentSelector).jqxMaskedInput('width'); } }; clear() { JQXLite(this.componentSelector).jqxMaskedInput('clear'); }; destroy() { JQXLite(this.componentSelector).jqxMaskedInput('destroy'); }; focus() { JQXLite(this.componentSelector).jqxMaskedInput('focus'); }; val(value) { if (value !== undefined) { JQXLite(this.componentSelector).jqxMaskedInput('val', value) } else { return JQXLite(this.componentSelector).jqxMaskedInput('val'); } }; render() { let id = 'jqxMaskedInput' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
src/app.js
Lorde-Y/happybuild
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import Root from 'container/root'; import './styles/app.less'; import { AppContainer } from 'react-hot-loader'; const render = (Component) => { ReactDOM.render( <Provider store={store}> <Component /> </Provider>, document.getElementById('app') ); }; render(Root); // ReactDOM.render( // <Canvas />, // document.getElementById('app') // ); // Hot Module Replacement API if (module.hot) { module.hot.accept('./container/root', () => { const NewApp = require('./container/root').default; render(NewApp) }); } // import Routes from './Routes.jsx'; // export default function Root(props) { // return ( // <Provider store={props.store}> // <Router history={props.history} routes={Routes} /> // </Provider> // ); // } // const store = ... // const history = ... // const Root = require('./Root.jsx').default; // const $root = document.getElementById('root'); // ReactDOM.render( // <AppContainer> // <Root store={store} history={history} /> // </AppContainer>, // $root // ); // if (module.hot) { // module.hot.accept('./Root.jsx', () => { // /* [Seems hacky] Running require tiggers hot reload */ // require('./components/Root.jsx').default; // ReactDOM.render( // <AppContainer> // <Root store={store} history={history} /> // </AppContainer>, // $root // ); // }); // } // // // // https://github.com/gaearon/react-hot-boilerplate/pull/61 // // import { AppContainer } from 'react-hot-loader'; // import { createStore } from 'redux'; // import { Provider } from 'react-redux'; // import App from './app'; // import appReducer from './reducer'; // const store = createStore(appReducer); // ReactDOM.render( // <AppContainer> // <Provider store={store}> // <App /> // </Provider> // </AppContainer>, // rootEl // ); // if (module.hot) { // module.hot.accept('./reducer', () => { // // redux store has a method replaceReducer // store.replaceReducer(appReducer); // }); // module.hot.accept('./app', () => { // ReactDOM.render( // <AppContainer> // <Provider store={store}> // <App /> // </Provider> // </AppContainer>, // rootEl // ); // }); // } // edit: if you’re using webpack 1, I believe you’ll need to re-require the module. (I’m using webpack2) // if (module.hot) { // module.hot.accept('./reducer', () => { // const nextStore = require('./reducer'); // store.replaceReducer(nextStore); // }); // }
app/javascript/flavours/glitch/features/compose/components/oekaki.js
Kirishima21/mastodon
import React from 'react'; import Button from '../../../components/button'; export default class CustomEmojiOekaki extends React.PureComponent { onClick(e) { e.preventDefault(); window.open('https://mamemomonga.github.io/mastodon-custom-emoji-oekaki/#kirishima.cloud'); } render () { return ( <div className='emoji-oekaki'> <Button text='☆絵文字でお絵かき☆' onClick={this.onClick} className='custom-emoji-oekaki' /> </div> ); } }
src/components/tools/ToolDescription.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; const ToolDescription = (props) => { const { name, description, screenshotUrl, url, className } = props; const { formatMessage } = props.intl; return ( <a href={url}> <div className={`tool-description ${className}`}> <h2><FormattedMessage {...name} /></h2> <p><FormattedMessage {...description} /></p> <img src={screenshotUrl} alt={formatMessage(name)} width="100%" /> </div> </a> ); }; ToolDescription.propTypes = { // from composition chain intl: PropTypes.object.isRequired, // from parent name: PropTypes.object.isRequired, // a msg to intl description: PropTypes.object.isRequired, // a msg to intl screenshotUrl: PropTypes.string.isRequired, className: PropTypes.string.isRequired, url: PropTypes.string.isRequired, }; export default injectIntl(ToolDescription);
client/scripts/components/user/revise/revise/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import {isEmpty} from 'lodash'; import {AppHeader} from '../../../app-header'; import {PIReviewStore} from '../../../../stores/pi-review-store'; import RevisionHeader from '../revision-header'; import QuestionnaireSection from '../questionnaire-section'; import FileSection from '../file-section'; import EntitySection from '../entity-section'; import DeclarationSection from '../declaration-section'; import SidePanel from '../side-panel'; import PIReviewActions from '../../../../actions/pi-review-actions'; import {DisclosureActions} from '../../../../actions/disclosure-actions'; export class Revise extends React.Component { constructor() { super(); const storeState = PIReviewStore.getState(); this.state = { disclosure: storeState.disclosure, applicationState: storeState.applicationState, files: storeState.files }; this.onChange = this.onChange.bind(this); this.onConfirm = this.onConfirm.bind(this); } componentDidMount() { PIReviewStore.listen(this.onChange); PIReviewActions.loadDisclosure(this.props.params.id); DisclosureActions.setCurrentDisclosureId(this.props.params.id); } componentWillUnmount() { PIReviewStore.unlisten(this.onChange); } onChange() { const storeState = PIReviewStore.getState(); this.setState({ disclosure: storeState.disclosure, applicationState: storeState.applicationState, files: storeState.files }); } onConfirm() { PIReviewActions.confirm(this.props.params.id); } render() { const {configState} = this.context; let questionnaireJsx; let entitiesJsx; let declarationsJsx; let submittedDate; let lastReviewDate; let disclosureType; let disclosureFilesJsx; if (this.state.disclosure) { lastReviewDate = this.state.disclosure.lastReviewDate; submittedDate = this.state.disclosure.submittedDate; disclosureType = this.state.disclosure.typeCd; const { questions, entities, declarations, id: disclosureId, configId } = this.state.disclosure; if (!isEmpty(questions)) { questionnaireJsx = ( <QuestionnaireSection questions={questions} /> ); } if (!isEmpty(entities)) { entitiesJsx = ( <EntitySection entitiesToReview={entities} disclosureId={parseInt(disclosureId)} /> ); } if (!isEmpty(declarations)) { declarationsJsx = ( <DeclarationSection declarationsToReview={declarations} configId={configId} necessaryEntities={entities} /> ); } if (this.state.files) { disclosureFilesJsx = ( <FileSection files={this.state.files} disclosureId={disclosureId} /> ); } } return ( <div className={'flexbox column'} style={{height: '100%'}}> <AppHeader className={`${styles.override} ${styles.header}`} moduleName={'Conflict Of Interest'} /> <div className={ `fill flexbox column ${styles.container} ${this.props.className}` } > <RevisionHeader disclosureType={disclosureType} submittedDate={submittedDate} returnedDate={lastReviewDate} /> <div className={'flexbox row fill'}> <span className={`fill ${styles.disclosure}`}> {questionnaireJsx} {entitiesJsx} {declarationsJsx} {disclosureFilesJsx} </span> <SidePanel certificationText={configState.config.general.certificationOptions.text} showingCertification={this.state.applicationState.showingCertification} submitEnabled={this.state.applicationState.canSubmit} onConfirm={this.onConfirm} /> </div> </div> </div> ); } } Revise.contextTypes = { configState: React.PropTypes.object };
samples/06.recomposing-ui/c.smart-display/src/MicrophoneIcon.js
billba/botchat
import React from 'react'; export default ({ className, size = 22 }) => ( <svg className={(className || '') + ''} height={size} viewBox="0 0 58 58" width={size}> <path d="M 44 28 C 43.448 28 43 28.447 43 29 L 43 35 C 43 42.72 36.72 49 29 49 C 21.28 49 15 42.72 15 35 L 15 29 C 15 28.447 14.552 28 14 28 C 13.448 28 13 28.447 13 29 L 13 35 C 13 43.485 19.644 50.429 28 50.949 L 28 56 L 23 56 C 22.448 56 22 56.447 22 57 C 22 57.553 22.448 58 23 58 L 35 58 C 35.552 58 36 57.553 36 57 C 36 56.447 35.552 56 35 56 L 30 56 L 30 50.949 C 38.356 50.429 45 43.484 45 35 L 45 29 C 45 28.447 44.552 28 44 28 Z" /> <path d="M 28.97 44.438 L 28.97 44.438 C 23.773 44.438 19.521 40.033 19.521 34.649 L 19.521 11.156 C 19.521 5.772 23.773 1.368 28.97 1.368 L 28.97 1.368 C 34.166 1.368 38.418 5.772 38.418 11.156 L 38.418 34.649 C 38.418 40.033 34.166 44.438 28.97 44.438 Z" /> <path d="M 29 46 C 35.065 46 40 41.065 40 35 L 40 11 C 40 4.935 35.065 0 29 0 C 22.935 0 18 4.935 18 11 L 18 35 C 18 41.065 22.935 46 29 46 Z M 20 11 C 20 6.037 24.038 2 29 2 C 33.962 2 38 6.037 38 11 L 38 35 C 38 39.963 33.962 44 29 44 C 24.038 44 20 39.963 20 35 L 20 11 Z" /> </svg> );
src/components/google_map.js
nfcortega89/airtime
import React, { Component } from 'react'; class GoogleMap extends Component { componentDidMount() { // create an embeded google map // this.refs.map is where map will be rendered to new google.maps.Map(this.refs.map, { zoom: 12, center: { lat: this.props.lat, lng: this.props.lon }, mapTypeId: 'satellite' }) } render() { // this.refs.map return <div ref="map" /> } } export default GoogleMap;
source/pages/users/show.js
simonewebdesign/react-router-page-js
import React from 'react'; export default class UserShowPage extends React.Component { render() { return <div>Showing user with id: { this.props.params.id }</div>; } }
client/trello/src/app/routes/login/Login.js
Madmous/Trello-Clone
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { push } from 'react-router-redux'; import { Link } from 'react-router'; import { LoginForm } from './components/index'; import './Login.css'; const propTypes = { isAuthenticatingSuccessful: PropTypes.bool.isRequired, isAuthenticated: PropTypes.bool.isRequired, loginActions: PropTypes.object.isRequired } export default class Login extends Component { componentWillMount() { const { isAuthenticated, dispatch } = this.props; if (isAuthenticated) { dispatch(push('/')); } } componentDidMount () { document.title = 'Login to Trello Clone'; } authenticate = (formInput) => { const { loginActions, location } = this.props; loginActions.authenticate(formInput, location); } render () { return ( <div className="Login"> <LoginForm onSubmit={ this.authenticate } /> <p>Don't have an account? <Link to={`/signup`}>Create a Trello Clone Account</Link></p> </div> ); } } Login.propTypes = propTypes;
example/example.js
AaronCCWong/react-remark
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import ReactRemark from 'react-remark'; class App extends Component { render () { const example = [ '# React Remark\n\n ***\n This is a react component that wraps [Remarkable](https://github.com/jonschlinkert/remarkable). ', 'Anything that is possible with Remarkable should be possible with this component.\n\n', 'Even embedding html into markdown works!\n\n Go to google with this link: <a href="https://www.google.com/">Google</a>\n\n', 'Check out the code for this [example](https://github.com/AaronCCWong/react-remark/tree/master/example/example.js).' ].join(''); return ( <div> <ReactRemark html source={example} /> </div> ); } }; ReactDOM.render(<App />, document.getElementById('app'));
test/NavbarSpec.js
roadmanfong/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Navbar from '../src/Navbar'; import Nav from '../src/Nav'; describe('Nav', function () { it('Should create nav element', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar /> ); let nav = React.findDOMNode(instance); assert.equal(nav.nodeName, 'NAV'); assert.ok(nav.className.match(/\bnavbar\b/)); assert.ok(nav.getAttribute('role'), 'navigation'); }); it('Should add fixedTop variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fixedTop /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-top')); }); it('Should add fixedBottom variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fixedBottom /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-bottom')); }); it('Should add staticTop variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar staticTop /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-static-top')); }); it('Should add inverse variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar inverse /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-inverse')); }); it('Should add fluid variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fluid /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'container-fluid')); }); it('Should override role attribute', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar role="banner"/> ); assert.ok(React.findDOMNode(instance).getAttribute('role'), 'banner'); }); it('Should override node class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar componentClass={'header'}/> ); assert.equal(React.findDOMNode(instance).nodeName, 'HEADER'); }); it('Should add header with brand', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand="Brand" /> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand'); assert.ok(brand); assert.equal(React.findDOMNode(brand).innerText, 'Brand'); }); it('Should add header with brand component', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand={<a>Brand</a>} /> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand'); assert.ok(brand); assert.equal(React.findDOMNode(brand).nodeName, 'A'); assert.equal(React.findDOMNode(brand).innerText, 'Brand'); }); it('Should pass navbar prop to navs', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand="Brand"> <Nav /> </Navbar> ); let nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.ok(nav.props.navbar); }); it('Should pass nav prop to ul', function () { let instance = ReactTestUtils.renderIntoDocument( <Nav /> ); let navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav')); assert.ok(navNode); assert.equal(navNode.nodeName, 'UL'); assert.equal(navNode.parentNode.nodeName, 'NAV'); instance.setProps({navbar: true}); navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav')); assert.ok(navNode); assert.equal(navNode.nodeName, 'UL'); assert.equal(navNode.parentNode.nodeName, 'DIV'); }); it('Should add header when toggleNavKey is 0', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={0}> <Nav eventKey={0} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); it('Should add header when toggleNavKey is 1', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={1}> <Nav eventKey={1} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); it('Should add header when toggleNavKey is string', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={'string'}> <Nav eventKey={'string'} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); });
src/panes/components/GeneralPane.js
trezy/eidetica
// Module imports import React from 'react' // Component imports import KBDContainer from './KBDContainer' import Pane from './Pane' import Switch from './Switch' // Component constants /* eslint-disable import/no-extraneous-dependencies */ const { app, BrowserWindow, globalShortcut, } = require('electron').remote /* eslint-enable */ class GeneralPane extends Pane { /***************************************************************************\ Private methods \***************************************************************************/ state = { altIsPressed: false, commandIsPressed: false, controlIsPressed: false, keyIsPressed: false, recordedShortcut: [], recordingShortcut: false, shiftIsPressed: false, autoUpdate: this.config.get('autoUpdate'), deleteAfterUpload: this.config.get('deleteAfterUpload'), filenameHandling: this.config.get('filenameHandling'), launchAtLogin: app.getLoginItemSettings().openAtLogin, shortcut: this.config.get('shortcut'), } /***************************************************************************\ Private methods \***************************************************************************/ _cancelRecording = () => { this.setState({ recordingShortcut: false }) BrowserWindow.getFocusedWindow().emit('shortcut-reset') } _handleKeydown = event => { const { recordedShortcut, recordingShortcut, } = this.state if (recordingShortcut) { const newState = { recordedShortcut: recordedShortcut.slice(0), recordingShortcut: true, } let addToShortcut let shouldCancel = false switch (event.key) { case '+': addToShortcut = 'Plus' newState.keyIsPressed = '+' newState.recordingShortcut = false break case 'Alt': addToShortcut = 'Alt' newState.altIsPressed = true break case 'Control': addToShortcut = 'Control' newState.controlIsPressed = true break case 'Escape': shouldCancel = true break case 'Meta': addToShortcut = 'Super' newState.commandIsPressed = true break case 'Shift': addToShortcut = 'Shift' newState.shiftIsPressed = true break default: if (event.code.indexOf('Key') !== -1) { addToShortcut = event.code.replace('Key', '') } else { addToShortcut = event.key } newState.keyIsPressed = addToShortcut newState.recordingShortcut = false } if (shouldCancel) { return this._cancelRecording() } if (recordedShortcut.indexOf(addToShortcut) === -1) { newState.recordedShortcut.push(addToShortcut) if (!newState.recordingShortcut) { this._updateShortcut(newState.recordedShortcut.join('+')) } this.setState(newState) } } return false } _handleKeyup = event => { const { recordedShortcut } = this.state if (this.state.recordingShortcut) { const newState = { recordedShortcut: recordedShortcut.slice(0) } let removeFromShortcut switch (event.key) { case '+': removeFromShortcut = 'Plus' newState.keyIsPressed = false break case 'Alt': removeFromShortcut = 'Alt' newState.altIsPressed = false break case 'Control': removeFromShortcut = 'Control' newState.controlIsPressed = false break case 'Meta': removeFromShortcut = 'Super' newState.commandIsPressed = false break case 'Shift': removeFromShortcut = 'Shift' newState.shiftIsPressed = false break default: removeFromShortcut = this.state.keyIsPressed newState.keyIsPressed = false } newState.recordedShortcut.splice(newState.recordedShortcut.indexOf(removeFromShortcut), 1) this.setState(newState) } } _startRecording = () => { globalShortcut.unregister(this.state.shortcut) this.setState({ altIsPressed: false, commandIsPressed: false, controlIsPressed: false, keyIsPressed: false, recordedShortcut: [], recordingShortcut: true, shiftIsPressed: false, }) } _toggleLaunchAtLogin = ({ target: { checked: shouldLaunchAtLogin } }) => { this.setState({ launchAtLogin: shouldLaunchAtLogin }) app.setLoginItemSettings({ openAtLogin: shouldLaunchAtLogin }) } _updateShortcut (shortcut) { this.setState({ shortcut }) this.config.set('shortcut', shortcut) BrowserWindow.getFocusedWindow().emit('shortcut-updated') } /***************************************************************************\ Public methods \***************************************************************************/ constructor (props) { super(props) window.addEventListener('keydown', this._handleKeydown) window.addEventListener('keyup', this._handleKeyup) } render () { const { autoUpdate, launchAtLogin, recordedShortcut, recordingShortcut, shortcut, } = this.state const keys = recordingShortcut ? recordedShortcut : shortcut.split('+') return ( <React.Fragment> <header> <h1>General Settings</h1> </header> <section className="setting"> <header>Keyboard Shortcut</header> <div className="control"> <KBDContainer editable keys={keys} onCancel={this._cancelRecording} onChange={this._startRecording} recording={recordingShortcut} /> </div> <div className="body"> <p>This is the description!</p> </div> </section> <section className="setting"> <header>Launch at Login</header> <div className="control"> <Switch checked={launchAtLogin} id="launchAtLogin" onChange={this._toggleLaunchAtLogin} /> </div> <div className="body"> <p>This is the description!</p> </div> </section> <section className="setting"> <header>Automatically Check for Updates</header> <div className="control"> <Switch checked={autoUpdate} id="autoUpdate" onChange={({ target: { checked } }) => this._updateSetting('autoUpdate', checked)} /> </div> <div className="body"> <p>This is the description!</p> </div> </section> </React.Fragment> ) } } export default GeneralPane
src/components/common/svg-icons/maps/directions-boat.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsBoat = (props) => ( <SvgIcon {...props}> <path d="M20 21c-1.39 0-2.78-.47-4-1.32-2.44 1.71-5.56 1.71-8 0C6.78 20.53 5.39 21 4 21H2v2h2c1.38 0 2.74-.35 4-.99 2.52 1.29 5.48 1.29 8 0 1.26.65 2.62.99 4 .99h2v-2h-2zM3.95 19H4c1.6 0 3.02-.88 4-2 .98 1.12 2.4 2 4 2s3.02-.88 4-2c.98 1.12 2.4 2 4 2h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V1H9v3H6c-1.1 0-2 .9-2 2v4.62l-1.29.42c-.26.08-.48.26-.6.5s-.15.52-.06.78L3.95 19zM6 6h12v3.97L12 8 6 9.97V6z"/> </SvgIcon> ); MapsDirectionsBoat = pure(MapsDirectionsBoat); MapsDirectionsBoat.displayName = 'MapsDirectionsBoat'; MapsDirectionsBoat.muiName = 'SvgIcon'; export default MapsDirectionsBoat;
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/FlowNone.js
mroch/flow
import React from 'react'; class MyComponent extends React.Component { static defaultProps: DefaultProps = {}; props: Props; state: State = {}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps: DefaultProps = {}; props: Props; state: State = {}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
frontend/src/pages/sys-admin/users/user-nav.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from '@reach/router'; import { siteRoot, gettext } from '../../../utils/constants'; const propTypes = { currentItem: PropTypes.string.isRequired }; class Nav extends React.Component { constructor(props) { super(props); this.navItems = [ {name: 'info', urlPart: '', text: gettext('Info')}, {name: 'owned-repos', urlPart: 'owned-libraries', text: gettext('Owned Libraries')}, {name: 'shared-repos', urlPart: 'shared-libraries', text: gettext('Shared Libraries')}, {name: 'links', urlPart: 'shared-links', text: gettext('Shared Links')}, {name: 'groups', urlPart: 'groups', text: gettext('Groups')} ]; } render() { const { currentItem, email, userName } = this.props; return ( <div> <div className="cur-view-path"> <h3 className="sf-heading"><Link to={`${siteRoot}sys/users/`}>{gettext('Users')}</Link> / {userName}</h3> </div> <ul className="nav border-bottom mx-4"> {this.navItems.map((item, index) => { return ( <li className="nav-item mr-2" key={index}> <Link to={`${siteRoot}sys/users/${encodeURIComponent(email)}/${item.urlPart}`} className={`nav-link ${currentItem == item.name ? ' active' : ''}`}>{item.text}</Link> </li> ); })} </ul> </div> ); } } Nav.propTypes = propTypes; export default Nav;
docs/app/Examples/modules/Popup/Variations/PopupExampleHideOnScroll.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Button, Popup } from 'semantic-ui-react' const PopupExampleHideOnScroll = () => ( <div> <Popup trigger={<Button icon>Click me</Button>} content='Hide the popup on any scroll event' on='click' hideOnScroll /> <Popup trigger={<Button icon>Hover me</Button>} content='Hide the popup on any scroll event' hideOnScroll /> </div> ) export default PopupExampleHideOnScroll
server/sonar-web/src/main/js/apps/overview/meta/MetaOrganizationKey.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { translate } from '../../../helpers/l10n'; const MetaOrganizationKey = ({ component }) => { return ( <div className="overview-meta-card"> <h4 className="overview-meta-header"> {translate('organization_key')} </h4> <input className="overview-key" type="text" value={component.organization} readOnly={true} onClick={e => e.target.select()} /> </div> ); }; export default MetaOrganizationKey;
packages/vx-demo/components/tiles/bargroup.js
Flaque/vx
import React from 'react'; import { BarGroup } from '@vx/shape'; import { Group } from '@vx/group'; import { AxisBottom } from '@vx/axis'; import { cityTemperature } from '@vx/mock-data'; import { scaleBand, scaleLinear, scaleOrdinal } from '@vx/scale'; import { timeParse, timeFormat } from 'd3-time-format'; import { extent, max } from 'd3-array'; const data = cityTemperature.slice(0, 8); const keys = Object.keys(data[0]).filter(d => d !== 'date'); const parseDate = timeParse("%Y%m%d"); const format = timeFormat("%b %d"); const formatDate = (date) => format(parseDate(date)); // accessors const x0 = d => d.date; const y = d => d.value; export default ({ width, height, events = false, margin = { top: 40 } }) => { if (width < 10) return null; // bounds const xMax = width; const yMax = height - margin.top - 100; // // scales const x0Scale = scaleBand({ rangeRound: [0, xMax], domain: data.map(x0), padding: 0.2, tickFormat: () => (val) => formatDate(val) }); const x1Scale = scaleBand({ rangeRound: [0, x0Scale.bandwidth()], domain: keys, padding: .1 }); const yScale = scaleLinear({ rangeRound: [yMax, 0], domain: [0, max(data, (d) => { return max(keys, (key) => d[key]) })], }); const zScale = scaleOrdinal({ domain: keys, range: ['#aeeef8', '#e5fd3d', '#9caff6'] }) return ( <svg width={width} height={height}> <rect x={0} y={0} width={width} height={height} fill={`#612efb`} rx={14} /> <BarGroup top={margin.top} data={data} keys={keys} height={yMax} x0={x0} x0Scale={x0Scale} x1Scale={x1Scale} yScale={yScale} zScale={zScale} rx={4} onClick={data => event => { if (!events) return; alert(`clicked: ${JSON.stringify(data)}`) }} /> <AxisBottom scale={x0Scale} top={yMax + margin.top} stroke='#e5fd3d' tickStroke='#e5fd3d' hideAxisLine tickLabelComponent={( <text fill='#e5fd3d' fontSize={11} textAnchor="middle" /> )} /> </svg> ); }
src/svg-icons/navigation/arrow-upward.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowUpward = (props) => ( <SvgIcon {...props}> <path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/> </SvgIcon> ); NavigationArrowUpward = pure(NavigationArrowUpward); NavigationArrowUpward.displayName = 'NavigationArrowUpward'; NavigationArrowUpward.muiName = 'SvgIcon'; export default NavigationArrowUpward;
project-templates/reactfiber/externals/react-fiber/fixtures/dom/src/components/fixtures/input-change-events/RangeKeyboardFixture.js
ItsAsbreuk/itsa-cli
import React from 'react'; import Fixture from '../../Fixture'; class RangeKeyboardFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { keydownCount: 0, changeCount: 0, }; } componentDidMount() { this.input.addEventListener('keydown', this.handleKeydown, false) } componentWillUnmount() { this.input.removeEventListener('keydown', this.handleKeydown, false) } handleChange = () => { this.setState(({ changeCount }) => { return { changeCount: changeCount + 1 } }) } handleKeydown = (e) => { // only interesting in arrow key events if (![37, 38, 39, 40].includes(e.keyCode)) return; this.setState(({ keydownCount }) => { return { keydownCount: keydownCount + 1 } }) } handleReset = () => { this.setState({ keydownCount: 0, changeCount: 0, }) } render() { const { keydownCount, changeCount } = this.state; const color = keydownCount === changeCount ? 'green' : 'red'; return ( <Fixture> <input type='range' ref={r => this.input = r} onChange={this.handleChange} /> {' '} <p style={{ color }}> <code>onKeyDown</code>{' calls: '}<strong>{keydownCount}</strong> {' vs '} <code>onChange</code>{' calls: '}<strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset counts</button> </Fixture> ) } } export default RangeKeyboardFixture;
examples/single-animation.js
ddcat1115/select
/* eslint no-console: 0 */ import React from 'react'; import Select, { Option } from 'rc-select'; import 'rc-select/assets/index.less'; import ReactDOM from 'react-dom'; function onChange(value) { console.log(`selected ${value}`); } const c1 = ( <div> <div style={{ height: 150 }}/> <h2>Single Select</h2> <div style={{ width: 300 }}> <Select allowClear placeholder="placeholder" defaultValue="lucy" style={{ width: 500 }} animation="slide-up" showSearch={false} onChange={onChange} > <Option value="jack"> <b style={{ color: 'red', }} > jack </b> </Option> <Option value="lucy">lucy</Option> <Option value="disabled" disabled>disabled</Option> <Option value="yiminghe">yiminghe</Option> </Select> </div> </div> ); ReactDOM.render(c1, document.getElementById('__react-content'));
server.js
mtomcal/starship-browser
import express from 'express'; import React from 'react'; import Router from 'react-router'; import ServerBootstrap from './views/ServerBootstrap.jsx'; import Routes from './views/Routes.jsx'; var { RouteHandler, // <-- not the usual RouteHandler! run } = require('react-router-async-props'); let app = express(); function server() { // LOAD static assets app.use('/static', express['static'](__dirname + '/static')); app.all('/*', function(req, res, next) { run(Routes, req.path, function (Handler, state, asyncProps) { var entry = React.renderToString(<Handler />); var html = React.renderToStaticMarkup(<ServerBootstrap asyncProps={asyncProps} bodyHTML={entry} />); res.send('<!DOCTYPE html>' + html); }); }); app.listen(3000); } module.exports = server;
src/entry.js
MatthewKosloski/lugar
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import createStore from './store'; import AppContainer from './containers/AppContainer'; let store = createStore(); let app = ( <Provider store={store}> <AppContainer/> </Provider> ); render(app, document.getElementById('app'));
src/components/routes/Resources/Resources.js
sievins/sarahs-footsteps
import React from 'react' import PropTypes from 'prop-types' import { join, map } from 'lodash' import { sliding } from 'utils/lists' import ResourcePair from './ResourcePair' Resources.propTypes = { resources: PropTypes.arrayOf(PropTypes.shape({ logo: PropTypes.string.isRequired, link: PropTypes.string.isRequired, description: PropTypes.string.isRequired, })).isRequired, } const createKey = resourcePair => join(map(resourcePair, 'link')) function Resources({ resources }) { return ( <div> { sliding(resources, 2).map(pair => ( <ResourcePair resources={pair} key={createKey(pair)} /> )) } </div> ) } export default Resources
__tests__/tests/components/GithubHtmlView.js
gitpoint/git-point
import React from 'react'; import { Text } from 'react-native'; import renderer from 'react-test-renderer'; import { GithubHtmlView } from 'components'; import { Icon } from 'react-native-elements'; describe('<GithubHtmlView />', () => { it('correctly renders <details/> tag in GithubHtmlView with correct icon', () => { const sourceHtml = ` <details> <summary>title</summary> <div>description</div> </details> `; const inst = renderer.create( <GithubHtmlView source={sourceHtml} onLinkPress={() => 0} /> ); expect(inst.root.findByType(Icon).props.name).toEqual('triangle-right'); }); it('if <summary/> tag contains a single text node, we shoud prettify it', () => { const sourceHtml = ` <details> <summary> make some space and line break here... </summary> <div>description</div> </details> `; const inst = renderer.create( <GithubHtmlView source={sourceHtml} onLinkPress={() => 0} /> ); expect( !!inst.root .findAllByType(Text) .find( e => e.props.children === 'make some space and line break here...' ) ).toBe(true); }); it('if there is no <summary/> tag, we should do fallback render which contains no icon', () => { const sourceHtml = ` <details> <div>no summary here!!</div> </details> `; const inst = renderer.create( <GithubHtmlView source={sourceHtml} onLinkPress={() => 0} /> ); expect(inst.root.findAllByType(Icon).length).toBe(0); }); it('if <summary/> contain nested tags, should still be rendered without exception', () => { const sourceHtml = ` <details> <summary> abcde <div>test</div> fg </summary> <div>no summary here!!</div> </details> `; const inst = renderer.create( <GithubHtmlView source={sourceHtml} onLinkPress={() => 0} /> ); expect(inst.root.findByType(Icon).props.name).toEqual('triangle-right'); }); });
src/routes/home_todelete/index.js
jackinf/skynda.me
/** * 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 from 'react'; import Home from './Home'; import fetch from '../../core/fetch'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,contentSnippet}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Home news={data.news} />, }; }, };
app/shared/resource-type-filter/ResourceTypeFilterContainer.js
fastmonkeys/respa-ui
import includes from 'lodash/includes'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import injectT from '../../i18n/injectT'; import ResourceTypeFilterButton from './ResourceTypeFilterButton'; class ResourceTypeFilterContainer extends Component { static propTypes = { selectedResourceTypes: PropTypes.arrayOf(PropTypes.string).isRequired, onSelectResourceType: PropTypes.func.isRequired, onUnselectResourceType: PropTypes.func.isRequired, resourceTypes: PropTypes.arrayOf(PropTypes.string).isRequired, t: PropTypes.func.isRequired, }; handleClick = (resourceType) => { const { selectedResourceTypes, onSelectResourceType, onUnselectResourceType, } = this.props; if (includes(selectedResourceTypes, resourceType)) { onUnselectResourceType(resourceType); } else { onSelectResourceType(resourceType); } } render() { const { t, selectedResourceTypes, resourceTypes } = this.props; return ( <div className="resource-type-filter-container"> <h6>{t('ResourceTypeFilter.title')}</h6> { resourceTypes.map(resourceType => ( <ResourceTypeFilterButton active={includes(selectedResourceTypes, resourceType)} key={`resource-type-${resourceType}`} onClick={this.handleClick} resourceType={resourceType} /> ))} </div> ); } } ResourceTypeFilterContainer = injectT(ResourceTypeFilterContainer); // eslint-disable-line export default ResourceTypeFilterContainer;
src/index.js
henyouqian/sale
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('root'));
frontend/src/components/showpicker/ShowPickerList.spec.js
tanzdervampire/website
// @flow import React from 'react'; import moment from 'moment'; import ShowPickerList from './ShowPickerList'; import CircularProgress from 'material-ui/CircularProgress'; const shows = [ { 'id': 1, 'day': '20.05.2017', 'time': '14:30', 'type': 'Matinée', 'location': 'Stuttgart', 'theater': 'Palladium', }, ]; it('renders without crashing', () => { const wrapper = mountWithContext( <ShowPickerList shows={shows} selectedShow={shows[0]} selectedDate={moment(shows[0].day, 'DD.MM.YYYY').toDate()} /> ); }); it('renders a throbber if no shows are given', () => { const wrapper = mountWithContext( <ShowPickerList shows={null} selectedShow={null} selectedDate={moment(shows[0].day, 'DD.MM.YYYY').toDate()} /> ); expect(wrapper.find(CircularProgress)).not.toBeEmpty(); }); it('displays a message if there are no shows for this day', () => { const wrapper = mountWithContext( <ShowPickerList shows={[]} selectedShow={null} selectedDate={moment(shows[0].day, 'DD.MM.YYYY').toDate()} /> ); expect(wrapper).toIncludeText('Für diesen Tag gibt es aktuell leider keine Informationen'); });
src/index.js
vladlen-g/ride-with-me
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Route, browserHistory, Redirect } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import configure from './store'; import App from './views/App/App.jsx'; import Home from './views/Home/Home.jsx'; import About from './views/About/About.jsx'; const store = configure(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( <Provider store={store}> <Router history={history}> <Route component={App} path="/"> <Route component={Home} path="home"/> <Route component={About} path="about" /> </Route> </Router> </Provider>, document.getElementById('root') );
src/components/Blog/Blog.react.js
uday96/chat.susi.ai
import './Blog.css'; import 'font-awesome/css/font-awesome.min.css'; import PropTypes from 'prop-types'; import htmlToText from 'html-to-text'; import $ from 'jquery'; import { Card, CardMedia, CardTitle, CardText, CardActions } from 'material-ui/Card'; import susi from '../../images/susi-logo.svg'; import dateFormat from 'dateformat'; import StaticAppBar from '../StaticAppBar/StaticAppBar.react'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import Next from 'material-ui/svg-icons/hardware/keyboard-arrow-right'; import Previous from 'material-ui/svg-icons/hardware/keyboard-arrow-left'; import React, { Component } from 'react'; import renderHTML from 'react-render-html'; import Loading from 'react-loading-animation'; import Footer from '../Footer/Footer.react'; import { ShareButtons, generateShareIcon } from 'react-share'; function arrDiff(a1, a2) { var a = [], diff = []; for (var f = 0; f < a1.length; f++) { a[a1[f]] = true; } for (var z = 0; z < a2.length; z++) { if (a[a2[z]]) { delete a[a2[z]]; } else { a[a2[z]] = true; } } for (var k in a) { diff.push(k); } return diff; }; class Blog extends Component { constructor(props) { super(props); this.state = { posts: [], postRendered: false, startPage: 0, nextDisplay: 'visible', prevDisplay: 'hidden', } } componentDidMount() { // Adding title tag to page document.title = 'Blog Posts about Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots - SUSI.AI'; // Scrolling to top of page when component loads $('html, body').animate({ scrollTop: 0 }, 'fast'); // Ajax call to convert the RSS feed to JSON format $.ajax({ url: 'https://api.rss2json.com/v1/api.json', method: 'GET', dataType: 'json', data: { 'rss_url': 'http://blog.fossasia.org/tag/susi-ai/feed/', 'api_key': 'qsmzjtyycc49whsfvf5ikzottxrbditq3burojhd', // put your api key here 'count': 50 } }).done(function (response) { if (response.status !== 'ok') { throw response.message; } this.setState({ posts: response.items, postRendered: true }); }.bind(this)); } scrollStep() { if (window.pageYOffset === 0) { clearInterval(this.state.intervalId); } window.scroll(0, window.pageYOffset - 1000); } // Function to scroll to top of page scrollToTop() { let intervalId = setInterval(this.scrollStep.bind(this), 16.66); this.setState({ intervalId: intervalId }); } // Function to navigate to previous page previousPage = () => { let current = this.state.startPage; if (current - 10 === 0) { this.setState({ startPage: current - 10, prevDisplay: 'hidden', nextDisplay: 'visible' }) } else { this.setState({ startPage: current - 10, prevDisplay: 'visible', nextDisplay: 'visible' }) } this.scrollToTop(); } // Function to navigate to next page nextPage = () => { let current = this.state.startPage; let size = this.state.posts.length; console.log(size) if (current + 10 === size - 10) { this.setState({ startPage: current + 10, nextDisplay: 'hidden', prevDisplay: 'visible' }) } else { this.setState({ startPage: current + 10, prevDisplay: 'visible', nextDisplay: 'visible' }) } this.scrollToTop(); } render() { const { FacebookShareButton, TwitterShareButton, } = ShareButtons; const FacebookIcon = generateShareIcon('facebook'); const TwitterIcon = generateShareIcon('twitter'); const nextStyle = { visibility: this.state.nextDisplay, marginLeft: '10px' } const prevStyle = { visibility: this.state.prevDisplay } const loadingStyle = { marginTop: '20px', position: 'relative', } const allCategories = ['FOSSASIA', 'GSoC', 'SUSI.AI', 'Tutorial', 'Android', 'API', 'App generator', 'CodeHeat', 'Community', 'Event', 'Event Management', 'loklak', 'Meilix', 'Open Event', 'Phimpme', 'Pocket Science Lab', 'yaydoc']; return ( <div> <StaticAppBar {...this.props} location={this.props.location} /> <div className='head_section'> <div className='container'> <div className="heading"> <h1>Blog</h1> <p>Latest Blog Posts on SUSI.AI</p> </div> </div> </div> <Loading style={loadingStyle} isLoading={!this.state.postRendered} /> {!this.state.postRendered && (<div><center>Fetching Blogs..</center></div>)} {this.state.postRendered && (<div> <div style={{ width: '100%' }}> { this.state.posts .slice(this.state.startPage, this.state.startPage + 10) .map((posts, i) => { let description = htmlToText.fromString(posts.description).split('…'); let content = posts.content; let category = []; posts.categories.forEach((cat) => { let k = 0; for (k = 0; k < allCategories.length; k++) { if (cat === allCategories[k]) { category.push(cat); } } }); var tags = arrDiff(category, posts.categories) let fCategory = category.map((cat) => <span key={cat} ><a className="tagname" href={'http://blog.fossasia.org/category/' + cat.replace(/\s+/g, '-').toLowerCase()} rel="noopener noreferrer">{cat}</a></span> ); let ftags = tags.map((tag) => <span key={tag} ><a className="tagname" href={'http://blog.fossasia.org/tag/' + tag.replace(/\s+/g, '-').toLowerCase()} rel="noopener noreferrer">{tag}</a></span> ); let htmlContent = content.replace(/<img.*?>/, ''); htmlContent = renderHTML(htmlContent); let image = susi let regExp = /\[(.*?)\]/; let imageUrl = regExp.exec(description[0]); if (imageUrl) { image = imageUrl[1] } let date = posts.pubDate.split(' '); let d = new Date(date[0]); return ( <div key={i} className="section_blog"> <Card style={{ width: '100%', padding: '0' }}> <CardMedia overlay={ <CardTitle className="noUnderline" subtitle={renderHTML('<a href="' + posts.link + '" >Published on ' + dateFormat(d, 'dddd, mmmm dS, yyyy') + '</a>')} /> }> <img className="featured_image" src={image} alt={posts.title} /> </CardMedia> <CardTitle className="noUnderline" title={posts.title} subtitle={renderHTML('by <a href="http://blog.fossasia.org/author/' + posts.author + '" >' + posts.author + '</a>')} /> <CardText style={{ fontSize: '16px' }}> {htmlContent} </CardText> <div className="social-btns"> <TwitterShareButton url={posts.guid} title={posts.title} via='asksusi' hashtags={posts.categories.slice(0, 4)} > <TwitterIcon size={32} round={true} /> </TwitterShareButton> <FacebookShareButton url={posts.link}> <FacebookIcon size={32} round={true} /> </FacebookShareButton> </div> <CardActions className="cardActions"> <span className="calendarContainer"> <i className="fa fa-calendar tagIcon"></i> {renderHTML('<a href="' + posts.link + '">' + dateFormat(d, 'mmmm dd, yyyy') + '</a>')} </span> <span className="authorsContainer"> <i className="fa fa-user tagIcon"></i> <a rel="noopener noreferrer" href={'http://blog.fossasia.org/author/' + posts.author} > {posts.author} </a></span> <span className='categoryContainer'> <i className="fa fa-folder-open-o tagIcon"></i> {fCategory} </span> <span className='tagsContainer'> <i className="fa fa-tags tagIcon"></i> {ftags} </span> </CardActions> </Card> </div> ) }) } </div> <div className="blog_navigation"> <FloatingActionButton style={prevStyle} backgroundColor={'#4285f4'} onTouchTap={this.previousPage}> <Previous /> </FloatingActionButton> <FloatingActionButton style={nextStyle} backgroundColor={'#4285f4'} onTouchTap={this.nextPage}> <Next /> </FloatingActionButton> </div> <div className="post_bottom"></div> <Footer /> </div>)} </div> ); } } Blog.propTypes = { history: PropTypes.object, location: PropTypes.object } export default Blog;
src/components/Chessboard/__tests__/Chessboard-test.js
bigamasta/chess-challenge
/** * Created by BigaMasta on 3/12/16. */ import React from 'react'; import ReactDOM from 'react-dom'; import expect from 'expect'; import alt from '../../../alt'; import Chessboard from '../Chessboard'; import Tile from '../../Tile/Tile'; import TestUtils from 'react-addons-test-utils'; import FigureStore from '../../../stores/FigureStore'; import TileStore from '../../../stores/TileStore'; describe('Chessboard', () => { let component; beforeEach(() => { alt.flush(); component = TestUtils.renderIntoDocument( <Chessboard playerColorPreference="black"/> ); }); /** * Must unmount the rendered component after each test. * Otherwise it will stay in the document for the next test. */ afterEach(() => { ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(component).parentNode); }); it('creates figures', () => { const figures = FigureStore.getState().figures; expect(figures.length > 0).toBe(true); }); it('creates 8x8 tiles', () => { const tiles = TileStore.getState().tiles; expect(tiles.length).toBe(64); }); it('can render', () => { const domComponent = TestUtils.findRenderedDOMComponentWithTag(component, 'table'); expect(domComponent).toExist(); }); it('renders 8x8 tiles', () => { const tileComponents = TestUtils.scryRenderedComponentsWithType(component, Tile); expect(tileComponents.length).toBe(64); }); });
app/views/Setup/Setup.js
lishengzxc/random
import styles from './Setup.scss'; import React from 'react'; import MessageBox from '../../views/MessageBox/MessageBox'; import clearTeamActionCreators from '../../actions/clearTeam-action-creators'; var Setup = React.createClass({ clear: function () { MessageBox.open('确认要清空所有数据吗ಥ_ಥ', function () { clearTeamActionCreators.emitClearTeam(); window.location.href = '#/'; }); }, render: function () { return ( <div className="in"> <button className={styles.button} onClick={this.clear}>清除数据</button> </div> ) } }); export default Setup;
actor-apps/app-web/src/app/components/ToolbarSection.react.js
vanloswang/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin } from 'react-intl'; import classnames from 'classnames'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import DialogStore from 'stores/DialogStore'; import ActivityStore from 'stores/ActivityStore'; //import AvatarItem from 'components/common/AvatarItem.react'; const getStateFromStores = () => { return { dialogInfo: DialogStore.getSelectedDialogInfo(), isActivityOpen: ActivityStore.isOpen() }; }; @ReactMixin.decorate(IntlMixin) class ToolbarSection extends React.Component { state = { dialogInfo: null, isActivityOpen: false }; constructor(props) { super(props); DialogStore.addSelectedChangeListener(this.onChange); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeSelectedChangeListener(this.onChange); ActivityStore.removeChangeListener(this.onChange); } onClick = () => { if (!this.state.isActivityOpen) { ActivityActionCreators.show(); } else { ActivityActionCreators.hide(); } }; onChange = () => { this.setState(getStateFromStores()); }; render() { const info = this.state.dialogInfo; const isActivityOpen = this.state.isActivityOpen; let infoButtonClassName = classnames('button button--icon', { 'button--active': isActivityOpen }); if (info != null) { return ( <header className="toolbar row"> <div className="toolbar__peer col-xs"> <span className="toolbar__peer__title">{info.name}</span> <span className="toolbar__peer__presence">{info.presence}</span> </div> <div className="toolbar__controls"> <div className="toolbar__controls__search pull-left hide"> <i className="material-icons">search</i> <input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/> </div> <div className="toolbar__controls__buttons pull-right"> <button className={infoButtonClassName} onClick={this.onClick}> <i className="material-icons">info</i> </button> <button className="button button--icon hide"> <i className="material-icons">more_vert</i> </button> </div> </div> </header> ); } else { return ( <header className="toolbar"/> ); } } } export default ToolbarSection;
examples/create-react-app-example/src/index.js
gvmani/socket.io
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
app/modules/header/index.js
donofkarma/react-starter
import React from 'react'; import Navigation from 'modules/navigation'; import { SiteHeader } from './style'; class Header extends React.Component { render() { return ( <SiteHeader className={this.props.className}> <h1>React Starter</h1> <Navigation /> </SiteHeader> ); } } export default Header;
src/components/Topbar.js
shockry/editest
import React, { Component } from 'react'; import '../css/Topbar.css'; import UploadButton from './UploadButton'; import DownloadButton from './DownloadButton'; import MainNavbar from './MainNavbar'; class Topbar extends Component { constructor(props) { super(props); this.setOriginalImage = this.setOriginalImage.bind(this); this.state = { originalImage: null }; } render() { return ( <div className="topbar"> <UploadButton canvas={this.props.canvas} imgElement={this.props.imgElement} setOriginalImage={this.setOriginalImage}/> <DownloadButton canvas={this.props.canvas}/> <MainNavbar canvas={this.props.canvas} originalImage={this.state.originalImage}/> </div> ); } setOriginalImage(img) { this.setState({originalImage: img}); } } export default Topbar;
_deprecated/src/components/App.js
paigekehoe/paigekehoe.github.io
import React from 'react'; import Interactive from 'react-interactive'; import { Switch, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; import PageNotFound from './PageNotFound'; import Breadcrumbs from './Breadcrumbs'; import Header from './Header'; import s from '../styles/app.style'; export default function App() { return ( <div style={s.root}> <Header /> <h1 style={s.title}>Paige Kehoe</h1> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route component={PageNotFound} /> </Switch> </div> ); }
client/components/dashboard/ReplyModal.js
creativcoder/rio
import { Modal, Button, Popover, OverlayTrigger, Tooltip } from 'react-bootstrap'; import React from 'react'; import Tweetbox from './Tweetbox'; class ReplyModal extends React.Component { constructor(props) { super(props); this.state = { showModal : false }; this.open = this.open.bind(this); this.close = this.close.bind(this); } open() { this.setState({ showModal: true }); } close() { this.setState({ showModal: false }); } render() { return ( <div> <i onClick={this.open} className="fa fa-reply" aria-hidden="true"></i> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>Reply to @{this.props.entities.alias}!</Modal.Title> </Modal.Header> <Modal.Body> <div> <Tweetbox entities={this.props.entities}/> </div> </Modal.Body> </Modal> </div> ); } } export default ReplyModal;
app/components/Badge.js
Nakan4u/pokemons-finder
import React, { Component } from 'react'; export default class Badge extends Component { makeBackground (type) { var obj = {}; switch (type) { case 'normal': obj.backgroundColor = 'aliceblue'; break; case 'fighting': obj.backgroundColor = 'bisque'; break; case 'flying': obj.backgroundColor = 'brown'; break; case 'poison': obj.backgroundColor = 'chartreuse'; break; case 'ground': obj.backgroundColor = 'darkgoldenrod'; break; case 'rock': obj.backgroundColor = 'darkgrey'; break; case 'bug': obj.backgroundColor = 'darkmagenta'; break; case 'ghost': obj.backgroundColor = 'darkseagreen'; break; case 'steel': obj.backgroundColor = 'dimgray'; break; case 'fire': obj.backgroundColor = 'gold'; break; case 'water': obj.backgroundColor = 'deepskyblue'; break; case 'grass': obj.backgroundColor = 'forestgreen'; break; case 'electric': obj.backgroundColor = 'khaki'; break; case 'psychic': obj.backgroundColor = 'lavender'; break; case 'ice': obj.backgroundColor = 'lightblue'; break; case 'dragon': obj.backgroundColor = 'lightgreen'; break; case 'dark': obj.backgroundColor = 'indigo'; break; case 'fairy': obj.backgroundColor = 'lightpink'; break; case 'unknown': obj.backgroundColor = 'silver'; break; case 'shadow': obj.backgroundColor = 'black'; break; default: obj.backgroundColor = 'grey'; } return obj; } } Badge.propTypes = { pokemon: React.PropTypes.object.isRequired, getPokemonsListByTypeHandler: React.PropTypes.func.isRequired };
src/interface/home/Page.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Trans } from '@lingui/macro'; import { Link, Route, Switch } from 'react-router-dom'; import lazyLoadComponent from 'common/lazyLoadComponent'; import retryingPromise from 'common/retryingPromise'; import NewsIcon from 'interface/icons/Megaphone'; import PremiumIcon from 'interface/icons/Premium'; import { ReactComponent as Logo } from 'interface/images/logo.svg'; import FingerprintFilledIcon from 'interface/icons/FingerprintFilled'; import HelpWantedIcon from 'interface/icons/Information'; import GitHubIcon from 'interface/icons/GitHubMarkLarge'; import DiscordIcon from 'interface/icons/DiscordTiny'; import { hasPremium } from 'interface/selectors/user'; import ErrorBoundary from 'interface/common/ErrorBoundary'; import Ad from 'interface/common/Ad'; import './Home.scss'; import ReportSelectionHeader from './ReportSelectionHeader'; import NotFound from './NotFound'; const News = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'News' */ 'interface/news').then(exports => exports.default))); const NewsPage = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'News' */ 'interface/news/Page').then(exports => exports.default))); const SpecListing = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'SpecListing' */ 'interface/SpecListing').then(exports => exports.default))); const Premium = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'Premium' */ 'interface/premium/Page').then(exports => exports.default))); const About = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'About' */ 'interface/about').then(exports => exports.default))); const HelpWanted = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'HelpWanted' */ 'interface/helpwanted').then(exports => exports.default))); const ContributorPage = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'ContributorPage' */ 'interface/contributor/Page').then(exports => exports.default))); class Home extends React.PureComponent { static propTypes = { location: PropTypes.shape({ pathname: PropTypes.string.isRequired, }).isRequired, premium: PropTypes.bool, }; static defaultProps = { premium: false, }; get pages() { return [ { icon: NewsIcon, name: <Trans>News</Trans>, url: 'news', }, { icon: FingerprintFilledIcon, name: <Trans>Specs</Trans>, url: 'specs', }, { icon: Logo, name: <Trans>About</Trans>, url: 'about', }, { icon: PremiumIcon, name: <Trans>Premium</Trans>, url: 'premium', }, { icon: HelpWantedIcon, name: <Trans>Help wanted</Trans>, url: 'help-wanted', }, { icon: GitHubIcon, name: <Trans>Source code</Trans>, url: 'https://github.com/WoWAnalyzer/WoWAnalyzer', }, { icon: DiscordIcon, name: <Trans>Discord</Trans>, url: 'https://wowanalyzer.com/discord', }, ]; } render() { const { location, premium } = this.props; const url = location.pathname === '/' ? 'news' : location.pathname.replace(/^\/|\/$/g, ''); return ( <div className="home-page"> <ReportSelectionHeader /> <main className="container"> {premium === false && ( <div style={{ marginTop: 40 }}> <Ad /> </div> )} <nav> <ul> {this.pages.map(page => { const Icon = page.icon; const isRelativeLink = !page.url.includes('://'); const content = ( <> <Icon className="icon" /> {page.name} </> ); return ( <li key={page.url} className={page.url === url ? 'active' : undefined}> {isRelativeLink ? ( <Link to={`/${page.url}`}>{content}</Link> ) : ( <a href={page.url}>{content}</a> )} </li> ); })} </ul> </nav> <ErrorBoundary> <Switch> <Route path="/" exact component={News} /> <Route path="/news" component={News} /> <Route path="/news/:articleId" render={({ match }) => ( <NewsPage articleId={decodeURI(match.params.articleId.replace(/\+/g, ' '))} /> )} /> <Route path="/specs" component={SpecListing} /> <Route path="/premium" component={Premium} /> <Route path="/about" component={About} /> <Route path="/help-wanted" component={HelpWanted} /> <Route path="/contributor/:id" render={({ match }) => ( <ContributorPage contributorId={decodeURI(match.params.id.replace(/\+/g, ' '))} /> )} /> <Route component={NotFound} /> </Switch> </ErrorBoundary> {premium === false && ( <div style={{ marginTop: 40 }}> <Ad /> </div> )} </main> </div> ); } } const mapStateToProps = state => ({ premium: hasPremium(state), }); export default connect( mapStateToProps )(Home);
app/components/Inputs/TextInput/TextInput.js
hbibkrim/neon-wallet
// @flow import React from 'react' import classNames from 'classnames' import { omit } from 'lodash-es' import ErrorIcon from '../../../assets/icons/errorRed.svg' import styles from './TextInput.scss' type Props = { className?: string, type: string, textInputClassName?: string, activeStyles?: string, placeholder: string, error?: string, id: string, renderBefore?: Function, renderAfter?: Function, onFocus?: Function, onBlur?: Function, label: string, shouldRenderErrorIcon?: boolean, } type State = { active: boolean, } export default class TextInput extends React.Component<Props, State> { static defaultProps = { type: 'text', shouldRenderErrorIcon: true, } state = { active: false, } render() { const passDownProps = omit( this.props, 'className', 'textInputClassName', 'activeStyles', 'renderBefore', 'renderAfter', 'shouldRenderErrorIcon', ) const { error, label, textInputClassName, activeStyles } = this.props const className = classNames(styles.textInput, this.props.className, { [activeStyles || styles.active]: this.state.active, [styles.error]: !!error, }) return ( <div className={styles.textInputContainer}> {label && <label className={styles.label}> {label} </label>} <div className={className}> {this.renderBefore()} <input {...passDownProps} className={classNames(styles.input, textInputClassName)} onFocus={this.handleFocus} onBlur={this.handleBlur} /> {error && this.props.shouldRenderErrorIcon && ( <ErrorIcon className={styles.errorIcon} /> )} {error && <div className={styles.errorMessage}>{error}</div>} {this.renderAfter()} </div> </div> ) } renderBefore = () => { if (!this.props.renderBefore) { return null } return ( <div className={styles.beforeInput}> {this.props.renderBefore({ active: this.state.active })} </div> ) } renderAfter = () => { if (!this.props.renderAfter) { return null } return ( <div className={styles.afterInput}> {this.props.renderAfter({ active: this.state.active })} </div> ) } handleFocus = (event: Object, ...args: Array<any>) => { this.setState({ active: true }) event.persist() return this.props.onFocus && this.props.onFocus(event, ...args) } handleBlur = (event: Object, ...args: Array<any>) => { this.setState({ active: false }) event.persist() return this.props.onBlur && this.props.onBlur(event, ...args) } }
src/components/topic/snapshots/foci/builder/FocusBuilderWizard.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import { FormattedMessage, injectIntl } from 'react-intl'; import BackLinkingControlBar from '../../../BackLinkingControlBar'; import FocusForm1TechniqueContainer from './FocusForm1TechniqueContainer'; import FocusForm2ConfigureContainer from './FocusForm2ConfigureContainer'; import FocusForm3DescribeContainer from './FocusForm3DescribeContainer'; import FocusForm4ConfirmContainer from './FocusForm4ConfirmContainer'; import { goToCreateFocusStep } from '../../../../../actions/topicActions'; const localMessages = { backToFociManager: { id: 'backToFociManager', defaultMessage: 'back to Subtopic Builder' }, step0Name: { id: 'focus.create.step0Name', defaultMessage: 'Pick a Technique' }, step1Name: { id: 'focus.create.step1Name', defaultMessage: 'Configure' }, step2Name: { id: 'focus.create.step2Name', defaultMessage: 'Describe' }, step3Name: { id: 'focus.create.step3Name', defaultMessage: 'Confirm' }, }; class FocusBuilderWizard extends React.Component { UNSAFE_componentWillMount = () => { const { startStep, goToStep } = this.props; goToStep(startStep || 0); } shouldComponentUpdate = (nextProps) => { const { currentStep } = this.props; return currentStep !== nextProps.currentStep; } componentWillUnmount = () => { const { handleUnmount } = this.props; handleUnmount(); } render() { const { topicId, currentStep, location, initialValues, onDone } = this.props; const steps = [ FocusForm1TechniqueContainer, FocusForm2ConfigureContainer, FocusForm3DescribeContainer, FocusForm4ConfirmContainer, ]; const CurrentStepComponent = steps[currentStep]; return ( <div className="focus-builder-wizard"> <BackLinkingControlBar message={localMessages.backToFociManager} linkTo={`/topics/${topicId}/snapshot/foci`}> <Stepper activeStep={currentStep}> <Step> <StepLabel><FormattedMessage {...localMessages.step0Name} /></StepLabel> </Step> <Step> <StepLabel><FormattedMessage {...localMessages.step1Name} /></StepLabel> </Step> <Step> <StepLabel><FormattedMessage {...localMessages.step2Name} /></StepLabel> </Step> <Step> <StepLabel><FormattedMessage {...localMessages.step3Name} /></StepLabel> </Step> </Stepper> </BackLinkingControlBar> <CurrentStepComponent topicId={topicId} location={location} initialValues={initialValues} onDone={onDone} /> </div> ); } } FocusBuilderWizard.propTypes = { // from parent topicId: PropTypes.number.isRequired, initialValues: PropTypes.object, startStep: PropTypes.number, location: PropTypes.object, onDone: PropTypes.func.isRequired, // from state currentStep: PropTypes.number.isRequired, // from dispatch goToStep: PropTypes.func.isRequired, handleUnmount: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ currentStep: state.topics.selected.focalSets.create.workflow.currentStep, }); const mapDispatchToProps = dispatch => ({ goToStep: (step) => { dispatch(goToCreateFocusStep(step)); }, handleUnmount: () => { dispatch(goToCreateFocusStep(0)); // reset for next time }, }); export default injectIntl( connect(mapStateToProps, mapDispatchToProps)( FocusBuilderWizard ) );
graphwalker-studio/src/main/js/components/sidemenu/editor-menu.js
KristianKarl/graphwalker-project
import React, { Component } from 'react'; import { connect } from "react-redux"; import { Button, ButtonGroup } from "@blueprintjs/core"; import { toggleProperties} from "../../redux/actions"; class EditorMenu extends Component { render() { return ( <ButtonGroup minimal={true} vertical={true} large={true}> <Button disabled={this.props.isMenuDisabled} className="sidemenu-button" icon="properties" onClick={ this.props.toggleProperties } /> </ButtonGroup> ); } } const mapStateToProps = ({ test: { models }}) => { return { isMenuDisabled: models.length === 0 } } export default connect(mapStateToProps, { toggleProperties })(EditorMenu);
app/components/TextInput/index.js
rahsheen/scalable-react-app
/** * * TextInput * */ import React from 'react'; import styles from './styles.css'; import classNames from 'classnames'; class TextInput extends React.Component { // eslint-disable-line react/prefer-stateless-function value() { return this.field.value; } render() { const { errorText } = this.props; const fieldError = errorText ? ( <div className={styles.errorMessage} > {errorText} </div> ) : null; return ( <div> <input className={classNames(styles.input, this.props.className, { [styles.inputError]: this.props.errorText })} placeholder={this.props.placeholder} ref={(f) => { this.field = f; }} type="text" /> {fieldError} </div> ); } } TextInput.propTypes = { errorText: React.PropTypes.string, placeholder: React.PropTypes.string, className: React.PropTypes.string, }; export default TextInput;
src/svg-icons/editor/format-indent-increase.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatIndentIncrease = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/> </SvgIcon> ); EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease); EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease'; EditorFormatIndentIncrease.muiName = 'SvgIcon'; export default EditorFormatIndentIncrease;
static/src/components/islands/IslandLog.js
hammerandchisel/airhornbot
// @flow // jscs:disable maximumLineLength import React from 'react'; type Props = { paused: boolean }; export default ({paused}: Props): React.Element => ( <svg className={`island log ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259" height="209"> <g fill="none" fill-rule="evenodd"> <path fill="#FFE6A7" d="M1.5012 81.2279v57.903l118.413 68.367 136.734-78.942v-57.903L1.5012 81.2279z"/> <path fill="#EDD194" d="M118.8135 76.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/> <path stroke="#5E4634" strokeWidth="3" d="M256.6494 70.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#C7E082" d="M1.5012 81.2279v20.403l118.413 68.37 136.734-78.945v-20.403L1.5012 81.2279z"/> <path fill="#B0CC64" d="M119.8134 76.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/> <path stroke="#5E4634" strokeWidth="3" d="M256.6494 73.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#B7D86F" d="M1.5012 81.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/> <path stroke="#5E4634" strokeWidth="3" d="M119.9151 149.5949L1.4991 81.2279l136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906m-5.0829-88.8003v3.249m-57.1155-44.385v3.249m161.3796-10.1622v3.249m-90.0216 34.4529v3.249m4.7883-6.4989v3.249M99.2985 42.3533v3.249" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#EBEBEB" d="M132.3141 38.8256h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/> <path stroke="#5E4634" strokeWidth="3" d="M132.3141 38.8256h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#EBEBEB" d="M191.0727 60.9152h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/> <path stroke="#5E4634" strokeWidth="3" d="M191.0727 60.9152h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#EDD194" d="M160.2915 81.4802l13.47-7.698c1.707-.978 3.933-.729 5.217.765.957 1.113 1.551 2.673 1.551 4.398 0 2.31-1.065 4.323-2.64 5.364l-13.533 8.703"/> <path stroke="#5E4634" strokeWidth="3" d="M160.2915 81.4802l13.47-7.698c1.707-.978 3.933-.729 5.217.765.957 1.113 1.551 2.673 1.551 4.398 0 2.31-1.065 4.323-2.64 5.364l-13.533 8.703" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#FFE6A7" d="M167.5194 87.2708c0 3.444-2.325 6.237-5.193 6.237-2.868 0-5.19-2.793-5.19-6.237s2.322-6.237 5.19-6.237c2.868 0 5.193 2.793 5.193 6.237"/> <path stroke="#5E4634" strokeWidth="3" d="M167.5194 87.2708c0 3.444-2.325 6.237-5.193 6.237-2.868 0-5.19-2.793-5.19-6.237s2.322-6.237 5.19-6.237c2.868 0 5.193 2.793 5.193 6.237z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#DCFAFF" d="M130.9788 89.6828c-13.386 7.728-33.633 8.568-45.225 1.875-11.592-6.693-10.14-18.384 3.246-26.112 13.386-7.728 33.633-8.568 45.225-1.875 11.592 6.693 10.14 18.384-3.246 26.112"/> <path stroke="#5E4634" strokeWidth="3" d="M130.9788 89.6828c-13.386 7.728-33.633 8.568-45.225 1.875-11.592-6.693-10.14-18.384 3.246-26.112 13.386-7.728 33.633-8.568 45.225-1.875 11.592 6.693 10.14 18.384-3.246 26.112z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#DCFAFF" d="M165.1434 50.429c-4.131 2.385-10.383 2.646-13.962.579-3.579-2.067-3.129-5.676 1.002-8.061 4.134-2.385 10.383-2.646 13.962-.579 3.579 2.067 3.129 5.676-1.002 8.061"/> <path stroke="#5E4634" strokeWidth="3" d="M165.1434 50.429c-4.131 2.385-10.383 2.646-13.962.579-3.579-2.067-3.129-5.676 1.002-8.061 4.134-2.385 10.383-2.646 13.962-.579 3.579 2.067 3.129 5.676-1.002 8.061z" strokeLinecap="round" strokeLinejoin="round"/> </g> </svg> );
src/components/NoMatch.js
uxlayouts/spidermonkey
import React from 'react' const NoMatch = ({ location }) => ( <div className="container-fluid padding-top-3 padding-bottom-3"> <h3>Sorry, we could not find: <code>{location.pathname}</code></h3> </div> ) export default NoMatch
projects/twitch-web/src/components/App.js
unindented/twitch-x
import React from 'react' import PropTypes from 'prop-types' import Root from 'twitch-ui/src/components/Root' import Navigation from 'twitch-ui/src/components/Navigation' import Main from 'twitch-ui/src/components/Main' export default function App (props) { const {children} = props return ( <Root> <Navigation /> <Main> {children} </Main> </Root> ) } App.propTypes = { children: PropTypes.node }
fields/types/textarea/TextareaField.js
helloworld3q3q/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'TextareaField', statics: { type: 'Textarea', }, renderField () { const { height, path, style, value } = this.props; const styles = { height: height, ...style, }; return ( <FormInput autoComplete="off" multiline name={this.getInputName(path)} onChange={this.valueChanged} ref="focusTarget" style={styles} value={value} /> ); }, });
src/LeftHalf.js
takng/REACT-STOCK
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; import { Button, Card, Row, Col } from 'react-materialize'; import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts'; //const d = [] export default ({ stocks, handleAdd, lows, fluctuate }) => { console.log(stocks.regularMarketChangePercent) if (stocks.regularMarketChangePercent >= 1) { return ( <div className="left-half"> <article> <div className = "stats" > <h1 className = "stats"> Stock Details</h1> </div> <div><br/></div> <table className ="bordered"> <tbody> <tr> <td>Name</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.longName}</td> </tr> <tr> <td>Symbol</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.symbol}</td> </tr> <tr> <td>Price</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPrice}</td> </tr> <tr> <td>Previous Close</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPreviousClose}</td> </tr> <tr> <td>Open</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketOpen}</td> </tr> <tr> <td>High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayHigh}</td> </tr> <tr> <td>Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayLow}</td> </tr> <tr> <td>52 Week High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekHigh}</td> </tr> <tr> <td>52 Week Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekLow}</td> </tr> <tr> <td>Percentage Change</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td className = "percentage">{stocks.regularMarketChangePercent}</td> </tr> <tr className= "last-tr"> <td>Volume</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketVolume}</td> </tr> </tbody> </table> <div><br/></div> <LineChart width={500} height={300} data={lows}> <Line type="monotone" dataKey="price" stroke="#026ed1" /> <CartesianGrid stroke="#ccc" /> <XAxis dataKey="Date" /> <Tooltip /> <YAxis /> </LineChart> <div className = "button"> <RaisedButton label="Add Stock" labelPosition="before" icon={<ContentAdd/>} onClick= {handleAdd} /> </div> </article> </div> ) } else if (stocks.regularMarketChangePercent < 0){ return ( <div className="left-half"> <article> <div className = "stats" > <h1 className = "stats"> Stock Details</h1> </div> <div><br/></div> <table className ="bordered"> <tbody> <tr> <td>Name</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.longName}</td> </tr> <tr> <td>Symbol</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.symbol}</td> </tr> <tr> <td>Price</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPrice}</td> </tr> <tr> <td>Previous Close</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPreviousClose}</td> </tr> <tr> <td>Open</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketOpen}</td> </tr> <tr> <td>High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayHigh}</td> </tr> <tr> <td>Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayLow}</td> </tr> <tr> <td>52 Week High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekHigh}</td> </tr> <tr> <td>52 Week Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekLow}</td> </tr> <tr> <td>Percent Change</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td className = "percent">{stocks.regularMarketChangePercent}</td> </tr> <tr className= "last-tr"> <td>Volume</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketVolume}</td> </tr> </tbody> </table> <div><br/></div> <LineChart width={500} height={300} data={lows}> <Line type="monotone" dataKey="price" stroke="#026ed1" /> <CartesianGrid stroke="#ccc" /> <XAxis dataKey="Date" /> <Tooltip /> <YAxis /> </LineChart> <div className = "button"> <RaisedButton label="Add Stock" labelPosition="before" icon={<ContentAdd/>} onClick= {handleAdd} /> </div> </article> </div> ) } else { return ( <div className="left-half"> <article> <div className = "stats" > <h1 className = "stats"> Stock Details</h1> </div> <div><br/></div> <table className ="bordered"> <tbody> <tr> <td>Name</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.longName}</td> </tr> <tr> <td>Symbol</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.symbol}</td> </tr> <tr> <td>Price</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPrice}</td> </tr> <tr> <td>Previous Close</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketPreviousClose}</td> </tr> <tr> <td>Open</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketOpen}</td> </tr> <tr> <td>High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayHigh}</td> </tr> <tr> <td>Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketDayLow}</td> </tr> <tr> <td>52 Week High</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekHigh}</td> </tr> <tr> <td>52 Week Low</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.fiftyTwoWeekLow}</td> </tr> <tr> <td>Percent Change</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketChangePercent}</td> </tr> <tr className= "last-tr"> <td>Volume</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>{stocks.regularMarketVolume}</td> </tr> </tbody> </table> <div><br/></div> <LineChart width={500} height={300} data={lows}> <Line type="monotone" dataKey="price" stroke="#026ed1" /> <CartesianGrid stroke="#ccc" /> <XAxis dataKey="Date" /> <Tooltip /> <YAxis /> </LineChart> <div className = "button"> <RaisedButton label="Add Stock" labelPosition="before" icon={<ContentAdd/>} onClick= {handleAdd} /> </div> </article> </div> ) } }
jenkins-design-language/src/js/components/material-ui/svg-icons/action/schedule.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSchedule = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); ActionSchedule.displayName = 'ActionSchedule'; ActionSchedule.muiName = 'SvgIcon'; export default ActionSchedule;
docs/app/Examples/elements/Image/States/ImageExampleDisabled.js
koenvg/Semantic-UI-React
import React from 'react' import { Image } from 'semantic-ui-react' const ImageExampleDisabled = () => ( <Image src='/assets/images/wireframe/image.png' size='medium' disabled /> ) export default ImageExampleDisabled
docs/app/Examples/views/Comment/Types/CommentExampleComment.js
clemensw/stardust
import React from 'react' import { Button, Comment, Form, Header } from 'semantic-ui-react' const CommentExampleComment = () => ( <Comment.Group> <Header as='h3' dividing>Comments</Header> <Comment> <Comment.Avatar src='http://semantic-ui.com/images/avatar/small/matt.jpg' /> <Comment.Content> <Comment.Author as='a'>Matt</Comment.Author> <Comment.Metadata> <div>Today at 5:42PM</div> </Comment.Metadata> <Comment.Text>How artistic!</Comment.Text> <Comment.Actions> <Comment.Action>Reply</Comment.Action> </Comment.Actions> </Comment.Content> </Comment> <Comment> <Comment.Avatar src='http://semantic-ui.com/images/avatar/small/elliot.jpg' /> <Comment.Content> <Comment.Author as='a'>Elliot Fu</Comment.Author> <Comment.Metadata> <div>Yesterday at 12:30AM</div> </Comment.Metadata> <Comment.Text> <p>This has been very useful for my research. Thanks as well!</p> </Comment.Text> <Comment.Actions> <Comment.Action>Reply</Comment.Action> </Comment.Actions> </Comment.Content> <Comment.Group> <Comment> <Comment.Avatar src='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> <Comment.Content> <Comment.Author as='a'>Jenny Hess</Comment.Author> <Comment.Metadata> <div>Just now</div> </Comment.Metadata> <Comment.Text> Elliot you are always so right :) </Comment.Text> <Comment.Actions> <Comment.Action>Reply</Comment.Action> </Comment.Actions> </Comment.Content> </Comment> </Comment.Group> </Comment> <Comment> <Comment.Avatar src='http://semantic-ui.com/images/avatar/small/joe.jpg' /> <Comment.Content> <Comment.Author as='a'>Joe Henderson</Comment.Author> <Comment.Metadata> <div>5 days ago</div> </Comment.Metadata> <Comment.Text> Dude, this is awesome. Thanks so much </Comment.Text> <Comment.Actions> <Comment.Action>Reply</Comment.Action> </Comment.Actions> </Comment.Content> </Comment> <Form reply onSubmit={e => e.preventDefault()}> <Form.TextArea /> <Button content='Add Reply' labelPosition='left' icon='edit' primary /> </Form> </Comment.Group> ) export default CommentExampleComment
examples/quick-start/components/user-form.js
davidkpiano/redux-simple-form
import React from 'react'; import { LocalForm, Form, actions, Control, Field, Errors } from 'react-redux-form'; import { connect } from 'react-redux'; import icepick from 'icepick'; window.i = icepick; const required = (val) => !!(val && val.length); function hasToBeTrue(value) { if (value === false || typeof value !== 'boolean') { return false; } return true; } // control class UserForm extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(user) { const { dispatch } = this.props; // Do whatever you like in here. // You can use actions such as: // dispatch(actions.submit('user', somePromise)); // etc. const somePromise = new Promise((resolve) => { /* eslint-disable no-console */ console.log(user); /* eslint-enable no-console */ setTimeout(() => { resolve(true); }, 1000); }); dispatch(actions.submit('user', somePromise)); } render() { return ( <Form model="user" onSubmit={this.handleSubmit}> <div> <label>First name:</label> <Control.text model="user.firstName" validators={{len: (val) => val.length > 8}} mapProps={{ className: ({fieldValue}) => fieldValue.focus ? 'focused' : '' }} /> <Errors model=".firstName" messages={{ len: 'len must be > 8' }} /> </div> <div> <label>Last name:</label> <Control model="user.lastName" validators={{required}}/> </div> <Field model="user.bag"> <label> <input type="radio" value="plastic" /> <span>Plastic</span> </label> <label> <input type="radio" value="paper" /> <span>Paper</span> </label> </Field> <Control.button model="user" disabled={{ valid: false }}> Finish registration! </Control.button> <input type="reset" value="Reset" title="reset"/> </Form> ); } } UserForm.propTypes = { dispatch: React.PropTypes.func.isRequired, user: React.PropTypes.shape({ firstName: React.PropTypes.string.isRequired, lastName: React.PropTypes.string.isRequired, }).isRequired, }; export default connect(s=>s)(UserForm);
src/client/spinner.js
eiriklv/hacker-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Loading... </div> ) } }
src/components/layouts/main-layout.js
mberneti/ReactAdmin
import React from 'react'; import Menu from './menu'; import Header from './header'; const mainLayout = props => { return ( <div id="wrapper"> {props.alert} <nav className="navbar navbar-default navbar-static-top" role="navigation"> <Header fullname={props.fullname} /> <Menu /> </nav> {props.children} </div> ); }; export default mainLayout;
extension/test/app/components/MainSection.spec.js
skortchmark9/reselect-tools
import { expect } from 'chai'; import sinon from 'sinon'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import MainSection from '../../../app/components/MainSection'; import style from '../../../app/components/MainSection.css'; import TodoItem from '../../../app/components/TodoItem'; import Footer from '../../../app/components/Footer'; import { SHOW_ALL, SHOW_COMPLETED } from '../../../app/constants/TodoFilters'; function setup(propOverrides) { const props = { todos: [{ text: 'Use Redux', completed: false, id: 0 }, { text: 'Run the tests', completed: true, id: 1 }], actions: { editTodo: sinon.spy(), deleteTodo: sinon.spy(), completeTodo: sinon.spy(), completeAll: sinon.spy(), clearCompleted: sinon.spy() }, ...propOverrides }; const renderer = TestUtils.createRenderer(); renderer.render(<MainSection {...props} />); const output = renderer.getRenderOutput(); return { props, output, renderer }; } describe('todoapp MainSection component', () => { it('should render correctly', () => { const { output } = setup(); expect(output.type).to.equal('section'); expect(output.props.className).to.equal(style.main); }); describe('toggle all input', () => { it('should render', () => { const { output } = setup(); const [toggle] = output.props.children; expect(toggle.type).to.equal('input'); expect(toggle.props.type).to.equal('checkbox'); expect(toggle.props.checked).to.equal(false); }); it('should be checked if all todos completed', () => { const { output } = setup({ todos: [{ text: 'Use Redux', completed: true, id: 0 }] }); const [toggle] = output.props.children; expect(toggle.props.checked).to.equal(true); }); it('should call completeAll on change', () => { const { output, props } = setup(); const [toggle] = output.props.children; toggle.props.onChange({}); expect(props.actions.completeAll.called).to.equal(true); }); }); describe('footer', () => { it('should render', () => { const { output } = setup(); const [,, footer] = output.props.children; expect(footer.type).to.equal(Footer); expect(footer.props.completedCount).to.equal(1); expect(footer.props.activeCount).to.equal(1); expect(footer.props.filter).to.equal(SHOW_ALL); }); it('onShow should set the filter', () => { const { output, renderer } = setup(); const [,, footer] = output.props.children; footer.props.onShow(SHOW_COMPLETED); const updated = renderer.getRenderOutput(); const [,, updatedFooter] = updated.props.children; expect(updatedFooter.props.filter).to.equal(SHOW_COMPLETED); }); it('onClearCompleted should call clearCompleted', () => { const { output, props } = setup(); const [,, footer] = output.props.children; footer.props.onClearCompleted(); expect(props.actions.clearCompleted.called).to.equal(true); }); it('onClearCompleted shouldnt call clearCompleted if no todos completed', () => { const { output, props } = setup({ todos: [{ text: 'Use Redux', completed: false, id: 0 }] }); const [,, footer] = output.props.children; footer.props.onClearCompleted(); expect(props.actions.clearCompleted.callCount).to.equal(0); }); }); describe('todo list', () => { it('should render', () => { const { output, props } = setup(); const [, list] = output.props.children; expect(list.type).to.equal('ul'); expect(list.props.children.length).to.equal(2); list.props.children.forEach((item, index) => { expect(item.type).to.equal(TodoItem); expect(item.props.todo).to.equal(props.todos[index]); }); }); it('should filter items', () => { const { output, renderer, props } = setup(); const [,, footer] = output.props.children; footer.props.onShow(SHOW_COMPLETED); const updated = renderer.getRenderOutput(); const [, updatedList] = updated.props.children; expect(updatedList.props.children.length).to.equal(1); expect(updatedList.props.children[0].props.todo).to.equal(props.todos[1]); }); }); });
plugins/Files/js/components/addfolderbutton.js
NebulousLabs/New-Sia-UI
import React from 'react' const AddFolderButton = ({ actions }) => { const handleClick = () => actions.showAddFolderDialog() return ( <div onClick={handleClick} className='addfolder-button'> <i className='fa fa-folder fa-2x' /> <span> New Folder </span> </div> ) } export default AddFolderButton
ios/versioned-react-native/ABI10_0_0/Libraries/Modal/Modal.js
jolicloud/exponent
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Modal * @flow */ 'use strict'; const I18nManager = require('I18nManager'); const Platform = require('Platform'); const PropTypes = require('react/lib/ReactPropTypes'); const React = require('React'); const StyleSheet = require('StyleSheet'); const UIManager = require('UIManager'); const View = require('View'); const deprecatedPropType = require('deprecatedPropType'); const requireNativeComponent = require('requireNativeComponent'); const RCTModalHostView = requireNativeComponent('RCTModalHostView', null); /** * The Modal component is a simple way to present content above an enclosing view. * * _Note: If you need more control over how to present modals over the rest of your app, * then consider using a top-level Navigator. Go [here](/react-native/docs/navigator-comparison.html) to compare navigation options._ * * ```javascript * import React, { Component } from 'react'; * import { Modal, Text, TouchableHighlight, View } from 'react-native'; * * class ModalExample extends Component { * * constructor(props) { * super(props); * this.state = {modalVisible: false}; * } * * setModalVisible(visible) { * this.setState({modalVisible: visible}); * } * * render() { * return ( * <View style={{marginTop: 22}}> * <Modal * animationType={"slide"} * transparent={false} * visible={this.state.modalVisible} * onRequestClose={() => {alert("Modal has been closed.")}} * > * <View style={{marginTop: 22}}> * <View> * <Text>Hello World!</Text> * * <TouchableHighlight onPress={() => { * this.setModalVisible(!this.state.modalVisible) * }}> * <Text>Hide Modal</Text> * </TouchableHighlight> * * </View> * </View> * </Modal> * * <TouchableHighlight onPress={() => { * this.setModalVisible(true) * }}> * <Text>Show Modal</Text> * </TouchableHighlight> * * </View> * ); * } * } * ``` */ class Modal extends React.Component { static propTypes = { /** * The `animationType` prop controls how the modal animates. * * - `slide` slides in from the bottom * - `fade` fades into view * - `none` appears without an animation */ animationType: PropTypes.oneOf(['none', 'slide', 'fade']), /** * The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background. */ transparent: PropTypes.bool, /** * The `visible` prop determines whether your modal is visible. */ visible: PropTypes.bool, /** * The `onRequestClose` prop allows passing a function that will be called once the modal has been dismissed. * * _On the Android platform, this is a required function._ */ onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func, /** * The `onShow` prop allows passing a function that will be called once the modal has been shown. */ onShow: PropTypes.func, animated: deprecatedPropType( PropTypes.bool, 'Use the `animationType` prop instead.' ), }; static defaultProps = { visible: true, }; render(): ?ReactElement<any> { if (this.props.visible === false) { return null; } const containerStyles = { backgroundColor: this.props.transparent ? 'transparent' : 'white', top: Platform.OS === 'android' && Platform.Version >= 19 ? UIManager.RCTModalHostView.Constants.StatusBarHeight : 0, }; let animationType = this.props.animationType; if (!animationType) { // manually setting default prop here to keep support for the deprecated 'animated' prop animationType = 'none'; if (this.props.animated) { animationType = 'slide'; } } return ( <RCTModalHostView animationType={animationType} transparent={this.props.transparent} onRequestClose={this.props.onRequestClose} onShow={this.props.onShow} style={styles.modal} onStartShouldSetResponder={this._shouldSetResponder} > <View style={[styles.container, containerStyles]}> {this.props.children} </View> </RCTModalHostView> ); } // We don't want any responder events bubbling out of the modal. _shouldSetResponder(): boolean { return true; } } const side = I18nManager.isRTL ? 'right' : 'left'; const styles = StyleSheet.create({ modal: { position: 'absolute', }, container: { position: 'absolute', [side] : 0, top: 0, } }); module.exports = Modal;
src/components/conversation/MessageGif/MessageGif.js
rlesniak/tind3r.com
// @flow import React, { Component } from 'react'; import { observable, action } from 'mobx'; import { observer } from 'mobx-react'; import cx from 'classnames'; import each from 'lodash/each'; import map from 'lodash/map'; import axios from 'axios'; import './MessageGif.scss'; const fetchGipy = query => axios.get(`http://api.giphy.com/v1/gifs/search?q=${encodeURI(query)}&api_key=dc6zaTOxFJmzC`); type PropsType = { onSelect: (body: string, data: Object) => void, onToggle: (state: boolean) => void, } @observer class MessageGif extends Component { componentDidMount() { if (this.inputRef) { this.inputRef.focus(); } document.addEventListener('mousedown', this.onMouseDown); } onMouseDown = (e: any) => { if (this.wrapperRef && !this.wrapperRef.contains(e.target)) { this.props.onToggle(false); } } props: PropsType; inputRef: ?any; wrapperRef: ?any; @observable text: string = ''; @observable gifs: Array<Object> = []; handleChange = (e: SyntheticInputEvent) => { this.text = e.target.value; } handleKeydown = async (e: SyntheticInputEvent) => { if (e.keyCode === 13) { const { data } = await fetchGipy(this.text); this.gifs = []; each(data.data, action((gif) => { this.gifs.push({ id: gif.id, url: gif.images.downsized.url, fixedHeight: gif.images.fixed_height, }); })); } } handleSelect = (gif: Object) => { const url = `${gif.fixedHeight.url}?width=${gif.fixedHeight.width}&height=${gif.fixedHeight.height}`; this.props.onSelect(url, { type: 'GIF', gif_id: gif.id, }); this.props.onToggle(false); } render() { return ( <div className={cx('message-gif')} ref={(ref) => { this.wrapperRef = ref; }} > <div className="message-gif__input"> <input ref={(ref) => { this.inputRef = ref; }} onChange={this.handleChange} onKeyDown={this.handleKeydown} placeholder="Search here" className="pt-input pt-intent-primary" /> </div> <div className="message-gif__list"> {map(this.gifs, gif => ( <div key={gif.id} className="message-gif__list-item" onClick={() => this.handleSelect(gif)}> <img alt="gif" src={gif.url} /> </div> ))} </div> </div> ); } } export default MessageGif;
imports/ui/home/components/committee_form.js
dououFullstack/atomic
import React from 'react'; import Modal from 'react-modal'; import { Field, reduxForm } from 'redux-form'; import ReactMarkdown from 'react-markdown'; class Form extends React.Component { constructor(props) { super(props); this.state = { readme: false, invitation: false, }; } readme() { this.setState({ readme: true, invitation: false, }); } invitation() { this.setState({ readme: false, invitation: true, }); } render() { const input = this.props.readme; const style = { overlay : { position : 'fixed', top : 0, left : 0, right : 0, bottom : 60, backgroundColor : 'rgba(255, 255, 255, 0.75)' }, content : { position : 'absolute', top : '10px', left : '10px', right : '10px', bottom : '10px', border : '1px solid #ccc', background : '#fff', overflow : 'auto', WebkitOverflowScrolling : 'touch', borderRadius : '4px', outline : 'none', padding : '20px' } } return ( <form className="new-form" onSubmit={this.props.handleSubmit}> <Modal isOpen={this.state.readme} style={style} > <div className="invitation-title">入会须知</div> <ReactMarkdown source={input} /> <button type="submit" onClick={()=> this.setState({readme: false, invitation:false})} className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 30, marginBottom: 10}}>我已阅读</button> </Modal> <Modal isOpen={this.state.invitation} style={style} > <div className="content"> <div className="invitation-title">《中国核电》杂志第三届理事会</div> <div className="invitation-title">邀 请 函 </div> <p> </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;目前,核电发展一直受到中国政府的高度重视。在国家“一带一路”发展战略的推动下,中国核电迎来了快速发展的机遇期,核电必将成为中国能源结构化发展的重要保障。</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;《中国核电》杂志(CN11-5660/TL)创刊于2008年1月,是国内唯一一本公开出版的核电类杂志。杂志由吴邦国同志题写刊名,中国核工业集团公司主管,中国原子能出版传媒有限公司主办。</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;杂志社每期都赠阅刊物给国务院有关部门及相关直属机构等,并送国际原子能机构等国际相关机构,以及国内外相关核电站和相关核电设备制造商等。杂志宗旨是宣传我国核电建设的方针政策;研讨我国核电建设的规划和如何加快我国核电发展等相关重大问题;分析讨论核电站的安全性、可靠性、经济性;介绍与我国核电工程建设有关的法规、标准;交流核电工作管理和建设经验;宣传我国核电自主研发、设计建造和设备国产化的最新进展;报道国内外核电建设和运行的最新动态和信息;跟踪国内外先进核电技术;加强与国际相关组织机构的信息与技术交流;普及核电知识等。</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;杂志由理事会、学术委员会、编辑委员会、杂志社等机构组成,作为理事会成员单位,可在杂志上优先发表论文,并可每期获赠一定数量的杂志;也可从本杂志获取相关咨询服务;成员单位在杂志上刊登广告可以享受一定的优惠;杂志作为我国核电行业宣传的平台,每年定期组织理事会成员单位的交流活动。为了把《中国核电》杂志办成国内外具有影响力的核心刊物,我们诚挚邀请我国从事核电产业的企事业单位、科研院所、大专院校共同关心和支持《中国核电》出版发行工作。</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;目前,《中国核电》杂志理事会已有成员71家,其中理事长单位1家,副理事长单位8家,常务理事单位9家,理事会单位53家。谨此,特邀请贵单位加入《中国核电》杂志理事会。</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;联系人:王 丹 电 话:010-88828694 E-mail:zghd2008@sina.com</p> <div style={{textAlign: 'right'}}>《中国核电》杂志理事会</div> <button type="submit" onClick={()=> this.setState({readme: false, invitation:false})} className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 30, marginBottom: 10}}>我已阅读</button> </div> </Modal> <div className="weui-cells__title">申请入会</div> <div className="weui-cells weui-cells_form"> <div className="weui-cell"> <div className="weui-cell__hd"> <label className="weui-label">单位名称</label> </div> <div className="weui-cell__bd"> <Field name="unit" component="input" type="text"/> </div> </div> <div className="weui-cell"> <div className="weui-cell__hd"> <label className="weui-label">入会级别</label> </div> <div className="weui-cell__bd"> <Field name="title" component="input" placeholder="副理事长 / 常务理事 / 理事" type="text"/> </div> </div> <div className="weui-cell"> <div className="weui-cell__hd"><label className="weui-label">联系人</label></div> <div className="weui-cell__bd"> <Field name="linkman" component="input" type="text"/> </div> </div> <div className="weui-cell"> <div className="weui-cell__hd"> <label className="weui-label">联系方式</label> </div> <div className="weui-cell__bd"> <Field name="address" component="input" type="text"/> </div> </div> </div> <div onClick={this.readme.bind(this)} style={{textAlign: 'center', width: '100%', marginTop: 10}}> <div className="inline field"> <div className="ui checkbox"> <input type="checkbox" checked name="example"/> <label>入会须知</label> </div> </div> </div> <div onClick={this.invitation.bind(this)} style={{textAlign: 'center', width: '100%', marginTop: 10}}> <div className="inline field"> <div className="ui checkbox"> <input type="checkbox" checked name="example"/> <label> 邀 请 函&nbsp;&nbsp; </label> </div> </div> </div> <button type="submit" className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 10, marginBottom: 25}}>提交申请</button> </form> ); } } export default reduxForm({ form: 'committeeNew' })(Form);
app/javascript/mastodon/features/compose/components/text_icon_button.js
increments/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class TextIconButton extends React.PureComponent { static propTypes = { label: PropTypes.string.isRequired, title: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func.isRequired, ariaControls: PropTypes.string, }; handleClick = (e) => { e.preventDefault(); this.props.onClick(); } render () { const { label, title, active, ariaControls } = this.props; return ( <button title={title} aria-label={title} className={`text-icon-button ${active ? 'active' : ''}`} aria-expanded={active} onClick={this.handleClick} aria-controls={ariaControls}> {label} </button> ); } }
assets/javascripts/kitten/components/embed/responsive-iframe-container/stories.js
KissKissBankBank/kitten
import React from 'react' import { ResponsiveIframeContainer } from './index' import { COLORS } from 'kitten' import { DocsPage } from 'storybook/docs-page' export default { title: 'Embed/ResponsiveIframeContainer', component: ResponsiveIframeContainer, parameters: { docs: { page: () => ( <DocsPage filepath={__filename} importString="ResponsiveIframeContainer" /> ), }, }, decorators: [ story => <div className="story-Container story-Grid">{story()}</div>, ], argTypes: { ratio: { name: 'ratio', control: 'number', }, children: { name: 'children', control: null, }, }, args: { ratio: 67.5, children: <iframe style={{ backgroundColor: COLORS.line1 }} />, }, } export const Default = args => <ResponsiveIframeContainer {...args} />
upgrade-guides/v0.12-v0.13/es5/src/components/Master.js
lore/lore
/** * This component serves as the root of your application, and should typically be the only * component subscribed to the store. * * It is also a good place to fetch the current user. Once you have configured 'models/currentUser' * to fetch the current user (by pointing it to the correct API endpoint) uncomment the commented * out code below in order to fetch the user, display a loading experience while they're being * fetched, and store the user in the applications context so that components can retrieve it * without having to pass it down through props or extract it from the Redux store directly. **/ import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import { connect } from 'lore-hook-connect'; import PayloadStates from '../constants/PayloadStates'; import RemoveLoadingScreen from './RemoveLoadingScreen'; import '../../assets/css/main.css'; export default connect(function(getState, props) { return { // user: getState('currentUser') }; }, { subscribe: true })( createReactClass({ displayName: 'Master', // propTypes: { // user: PropTypes.object.isRequired // }, // childContextTypes: { // user: PropTypes.object // }, // getChildContext() { // return { // user: this.props.user // }; // }, componentDidMount() { // If you want to play with the router through the browser's dev console then // uncomment out this line. React Router automatically provides 'router' // to any components that are "routes" (such as Master and Layout), so this // is a good location to attach it to the global lore object. // lore.router = this.props.router; }, render() { // const { user } = this.props; // if (user.state === PayloadStates.FETCHING) { // return null; // } return ( <div> <RemoveLoadingScreen/> {React.cloneElement(this.props.children)} </div> ); } }) );
src/parser/demonhunter/havoc/modules/spells/MetaBuffUptime.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; /* example report: https://www.warcraftlogs.com/reports/KGJgZPxanBX82LzV/#fight=4&source=20 * */ class MetaBuffUptime extends Analyzer { get buffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id) / this.owner.fightDuration; } get buffDuration() { return this.selectedCombatant.getBuffUptime(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id); } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(3)} icon={<SpellIcon id={SPELLS.METAMORPHOSIS_HAVOC_BUFF.id} />} value={`${formatPercentage(this.buffUptime)}%`} label="Metamorphosis Uptime" tooltip={`The Metamorphosis buff total uptime was ${formatDuration(this.buffDuration / 1000)}.`} /> ); } } export default MetaBuffUptime;
src/ReactPureLoggerComponent.js
D-Andreev/react-logger
import React from 'react'; import Logger from './logger/Logger'; export default class ReactPureLoggerComponent extends React.PureComponent { constructor(props, options) { super(props); this.logger = new Logger(options); this.displayName = props.displayName; } componentWillMount() { this.logger.log(this.displayName, 'componentWillMount'); } componentDidMount() { this.logger.log(this.displayName, 'componentDidMount'); } componentWillReceiveProps(nextProps) { this.logger.log(this.displayName, 'componentWillReceiveProps', {nextProps}); } shouldComponentUpdate(nextProps, nextState) { this.logger.log(this.displayName, 'shouldComponentUpdate', {nextProps, nextState}); return true; } componentWillUpdate(nextProps, nextState) { this.logger.log(this.displayName, 'componentWillUpdate', {nextProps, nextState}); } componentDidUpdate(prevProps, prevState) { this.logger.log(this.displayName, 'componentDidUpdate', {prevProps, prevState}); } componentWillUnmount() { this.logger.log(this.displayName, 'componentWillUnmount'); } }
src/AppBar/index.js
reactivers/react-material-design
/** * Created by Utku on 25/03/2017. */ import React from 'react'; import PropTypes from 'prop-types'; import '@material/toolbar/dist/mdc.toolbar.css'; import classNames from 'classnames'; export class AppBarTitle extends React.PureComponent { static propTypes = { iconAlignment: PropTypes.string, icon : PropTypes.node, title : PropTypes.string } render() { const {className,icon, iconAlignment, title,...rest} = this.props const style = Object.assign({ display: "flex", justifyContent: 'center', alignItems: 'center' }, this.props.style); return ( <span style={style} {...rest} className={className}> {icon && (!iconAlignment || iconAlignment !== "right") && icon} <span className="mdc-toolbar__title">{title}</span> {icon && iconAlignment && iconAlignment.toLowerCase() === "right" && icon} </span> ) } } export class AppBar extends React.PureComponent { static propTypes = { leftElements : PropTypes.node, rightElements : PropTypes.node, middleElements : PropTypes.node, barColor : PropTypes.string, fixed : PropTypes.bool } render() { const {className,fixed, style, barColor, leftElements, rightElements, middleElements,...otherProps} = this.props const classes = classNames("mdc-toolbar", {"mdc-toolbar--fixed": fixed},className); let barStyle = Object.assign({}, style, {backgroundColor: barColor}); return ( <header className={classes} style={barStyle} {...otherProps}> {leftElements && <section className="mdc-toolbar__section mdc-toolbar__section--align-start"> {leftElements} </section>} {middleElements && <section className="mdc-toolbar__section"> {middleElements} </section>} {rightElements && <section className="mdc-toolbar__section mdc-toolbar__section--align-end"> {rightElements} </section>} </header> ) } }
src/app/components/task/SingleChoiceTask.js
meedan/check-web
import React, { Component } from 'react'; import Box from '@material-ui/core/Box'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Button from '@material-ui/core/Button'; import { FormattedMessage } from 'react-intl'; import ParsedText from '../ParsedText'; import { FormattedGlobalMessage } from '../MappedMessage'; import { safelyParseJSON } from '../../helpers'; import { StyledSmallTextField } from '../../styles/js/shared'; class SingleChoiceTask extends Component { constructor(props) { super(props); this.state = { response: null, responseOther: null, taskAnswerDisabled: true, }; } handleSubmitResponse() { if (!this.state.taskAnswerDisabled) { const response = this.state.response ? this.state.response.trim() : this.props.response; this.props.onSubmit(response); this.setState({ taskAnswerDisabled: true }); } } canSubmit() { const response = this.state.response ? this.state.response.trim() : this.props.response; const can_submit = !!response; this.setState({ taskAnswerDisabled: !can_submit }); return can_submit; } handleCancelResponse() { this.setState({ response: null, responseOther: null, otherSelected: false, focus: false, }, this.canSubmit); if (this.props.onDismiss) { this.props.onDismiss(); } } handleSelectRadio(e) { this.setState({ focus: true, response: e.target.value, responseOther: '', otherSelected: false, taskAnswerDisabled: false, }); } handleSelectRadioOther() { // TODO Use React ref const input = document.querySelector('.task__option_other_text_input input'); if (input) { input.focus(); } this.setState({ focus: true, response: '', responseOther: '', otherSelected: true, taskAnswerDisabled: true, }); } handleEditOther(e) { const { value } = e.target; this.setState({ focus: true, response: value, responseOther: value, otherSelected: true, }, this.canSubmit); } handleKeyPress(e) { if (e.key === 'Enter' && !e.shiftKey) { if (this.canSubmit()) { this.setState({ taskAnswerDisabled: true }); this.handleSubmitResponse(); } e.preventDefault(); } } renderOptions(response, jsonoptions) { const { fieldset } = this.props; const options = safelyParseJSON(jsonoptions); const editable = !response || this.props.mode === 'edit_response'; const submitCallback = this.handleSubmitResponse.bind(this); const cancelCallback = this.handleCancelResponse.bind(this); const keyPressCallback = this.handleKeyPress.bind(this); const actionBtns = ( <div> <Button onClick={cancelCallback}> <FormattedMessage id="tasks.cancelEdit" defaultMessage="Cancel" /> </Button> <Button className="task__submit" color="primary" onClick={submitCallback} disabled={this.state.taskAnswerDisabled} > { fieldset === 'tasks' ? <FormattedMessage id="tasks.answer" defaultMessage="Answer Task" /> : <FormattedGlobalMessage messageKey="save" /> } </Button> </div> ); if (Array.isArray(options) && options.length > 0) { const otherIndex = options.findIndex(item => item.other); const other = otherIndex >= 0 ? options.splice(otherIndex, 1).pop() : null; const responseIndex = options.findIndex(item => item.label === response || item.label === this.state.response); let responseOther = ''; if (typeof this.state.responseOther !== 'undefined' && this.state.responseOther !== null) { ({ responseOther } = this.state); } else if (responseIndex < 0) { responseOther = response; } const responseOtherSelected = this.state.otherSelected || responseOther ? responseOther : 'none'; const responseSelected = this.state.response === null ? response : this.state.response; return ( <div className="task__options"> <FormGroup> <RadioGroup name="response" onChange={this.handleSelectRadio.bind(this)} value={responseSelected} > {options.map((item, index) => ( <FormControlLabel key={`task__options--radiobutton-${index.toString()}`} id={index.toString()} value={item.label} label={ <ParsedText text={item.label} /> } control={ <Radio disabled={!editable} /> } /> ))} </RadioGroup> <Box display="flex" justifyContent="flex-start" alignItems="center" className="task__options_other" > {other ? <RadioGroup name="task__option_other_radio" key="task__option_other_radio" className="task__option_other_radio" value={responseOtherSelected} onChange={this.handleSelectRadioOther.bind(this)} > <FormControlLabel value={responseOther} control={ <Radio disabled={!editable} /> } label={editable ? <StyledSmallTextField key="task__option_other_text_input" className="task__option_other_text_input" placeholder={other.label} value={responseOther} name="response" onKeyPress={keyPressCallback} onChange={this.handleEditOther.bind(this)} multiline /> : <ParsedText text={responseOther} /> } /> </RadioGroup> : null} </Box> {(this.state.focus && editable) || this.props.mode === 'edit_response' ? actionBtns : null} </FormGroup> </div> ); } return null; } render() { const { response, jsonoptions, } = this.props; return ( <div> {this.props.mode === 'respond' ? this.renderOptions(response, jsonoptions) : null} {this.props.mode === 'show_response' && response ? this.renderOptions(response, jsonoptions) : null} {this.props.mode === 'edit_response' ? this.renderOptions(response, jsonoptions) : null} </div> ); } } export default SingleChoiceTask;
src/components/LoginCard/__tests__/LoginCard-test.js
retaxJS/retax-seed
import chai, { expect } from 'chai'; import mockery from 'mockery'; import sinonChai from 'sinon-chai'; import dirtyChai from 'dirty-chai'; chai.use(dirtyChai); chai.use(sinonChai); import { shallow } from 'enzyme'; import React from 'react'; function noop() {} describe('LoginCard', () => { describe('Without DOM', () => { beforeEach(() => { mockery.enable({ warnOnReplace: false, warnOnUnregistered: false, useCleanCache: true, }); mockery.registerMock( 'decorators', require('helpers/test/decoratorsMock') ); mockery.registerMock( 'material-ui', require('helpers/test/materialUiMock') ); mockery.registerMock('components/WithLoading', require('helpers/test/componentsMock').WithLoading ); mockery.registerMock('components/LoginForm', require('helpers/test/componentsMock').LoginForm ); }); afterEach(() => { mockery.deregisterMock('pure-render-decorator'); mockery.deregisterMock('material-ui'); mockery.deregisterMock('components/WithLoading'); mockery.deregisterMock('components/LoginForm'); mockery.disable(); }); it('should exists', () => { const LoginCard = require('../LoginCard'); const wrapper = shallow( <LoginCard onLinkTouch={noop} links={[]} /> ); expect(wrapper).to.have.length(1); }); it('should render the LoginCard components', () => { const LoginCard = require('../LoginCard'); const wrapper = shallow( <LoginCard onLinkTouch={noop} links={[]} /> ); expect(wrapper.find('WithLoading')).to.have.length(1); expect(wrapper.find('LoginForm')).to.have.length(1); }); }); });
src/FormControls/Static.js
mcraiganthony/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import InputBase from '../InputBase'; import childrenValueValidation from '../utils/childrenValueInputValidation'; class Static extends InputBase { getValue() { const {children, value} = this.props; return children ? children : value; } renderInput() { return ( <p {...this.props} className={classNames(this.props.className, 'form-control-static')} ref="input" key="input"> {this.getValue()} </p> ); } } Static.propTypes = { value: childrenValueValidation, children: childrenValueValidation }; export default Static;
app/components/inputgroup/inputgroup.js
tidepool-org/blip
import PropTypes from 'prop-types'; import React from 'react'; import _ from 'lodash'; import cx from 'classnames'; import Select from 'react-select'; import DatePicker from '../datepicker'; // Input with label and validation error message class InputGroup extends React.Component { static propTypes = { name: PropTypes.string, label: PropTypes.node, items: PropTypes.array, text: PropTypes.node, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool, PropTypes.object // dates for datepicker input type are objects ]), error: PropTypes.string, type: PropTypes.string.isRequired, placeholder: PropTypes.string, rows: PropTypes.number, disabled: PropTypes.bool, multi: PropTypes.bool, autoFocus: PropTypes.bool, defaultChecked: PropTypes.bool, onChange: PropTypes.func }; DEFAULT_TEXTAREA_ROWS = 3; render() { var className = this.getClassName(); var label = this.renderLabel(); var input = this.renderInput(); var message = this.renderMessage(); return ( <div className={className}> <div> {label} {input} </div> {message} </div> ); } renderLabel = () => { var text = this.props.label; var htmlFor = this.props.name; if (this.props.type === 'checkbox' || this.props.type === 'radios') { // Label part of input return null; } if (text) { return ( <label className="input-group-label" htmlFor={htmlFor} ref="label">{text}</label> ); } return null; }; renderInput = () => { var type = this.props.type; if (type === 'textarea') { return this.renderTextArea(); } if (type === 'checkbox') { return this.renderCheckbox(); } if (type === 'radios') { return this.renderRadios(); } if (type === 'select') { return this.renderSelect(); } if (type === 'datepicker') { return this.renderDatePicker(); } if (type === 'explanation') { return this.renderExplanation(); } return ( <input type={type} className="input-group-control form-control" id={this.props.name} name={this.props.name} value={this.props.value} placeholder={this.props.placeholder} onChange={this.handleChange} disabled={this.props.disabled} autoFocus={!!this.props.autoFocus} ref="control"/> ); }; renderTextArea = () => { var rows = this.props.rows || this.DEFAULT_TEXTAREA_ROWS; return ( <textarea className="input-group-control form-control" id={this.props.name} name={this.props.name} value={this.props.value} placeholder={this.props.placeholder} rows={rows} onChange={this.handleChange} disabled={this.props.disabled} ref="control"></textarea> ); }; renderCheckbox = () => { return ( <label className="input-group-checkbox-label" htmlFor={this.props.name} ref="label"> <input type="checkbox" className="input-group-checkbox-control" id={this.props.name} name={this.props.name} checked={this.props.value} onChange={this.handleChange} disabled={this.props.disabled} defaultChecked={this.props.defaultChecked} ref="control"/> {' '} {this.props.label} </label> ); }; renderRadios = () => { var self = this; var radios = _.map(this.props.items, function(radio, index) { var id = self.props.name + index; var checked = (self.props.value === radio.value); return ( <label className="input-group-radio-label" htmlFor={id} key={id} ref={'label' + index}> <input type="radio" className="input-group-radio-control" id={id} name={self.props.name} value={radio.value} checked={checked} onChange={self.handleChange} disabled={self.props.disabled} ref={'control' + index}/> {' '} {radio.label} </label> ); }); return ( <div className="input-group-radios"> {radios} </div> ); }; renderSelect = () => { var isMultiSelect = this.props.multi || false; var classNames = cx({ 'input-group-control': true, 'form-control': true, 'Select': true, }); let valueArray = []; if (!_.isEmpty(this.props.value)) { // Select all provided values that have a corresponding option value valueArray = _.intersectionBy( this.props.items, _.map(this.props.value.split(','), value => ({ value })), 'value' ); } return ( <Select className={classNames} classNamePrefix="Select" name={this.props.name} id={this.props.name} isMulti={isMultiSelect} isClearable={isMultiSelect} closeMenuOnSelect={!isMultiSelect} placeholder={this.props.placeholder} value={valueArray} onChange={this.handleChange} isDisabled={this.props.disabled} options={this.props.items} /> ); }; renderDatePicker = () => { return ( <DatePicker name={this.props.name} value={this.props.value} disabled={this.props.disabled} onChange={this.handleChange} /> ); }; renderExplanation = () => { return <div className='input-group-explanation'> {this.props.text} </div>; }; renderMessage = () => { var error = this.props.error; if (error) { return ( <div className="input-group-message form-help-block" ref="message">{error}</div> ); } return null; }; getClassName = () => { var className = 'input-group form-group clearfix'; if (this.props.error) { className += ' input-group-error'; } return className; }; handleChange = (e) => { var target = (e !== null) ? e.target || e : {}; var attributes = { name: target.name || this.props.name, value: target.value || null, }; if (this.props.type === 'checkbox') { // "Normalize" checkbox change events to use `value` like other inputs attributes.value = target.checked; } if (this.props.type === 'select' && this.props.multi) { // Target comes in as an array of objects when using react-select's 'multi' attribute attributes.value = target; } var changeCallback = this.props.onChange; if (changeCallback) { changeCallback(attributes); } }; } module.exports = InputGroup;
packages/icons/src/md/action/Label.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLabel(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M34.27 11.69A4.015 4.015 0 0 0 31 10l-22 .02c-2.21 0-4 1.77-4 3.98v20c0 2.21 1.79 3.98 4 3.98L31 38c1.35 0 2.54-.67 3.27-1.69L43 24l-8.73-12.31z" /> </IconBase> ); } export default MdLabel;
src/workshops/presentation/attendee/AnttendeeView.js
GrayTurtle/rocket-workshop
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'react-icons-kit'; import { ic_keyboard_arrow_left } from 'react-icons-kit/md/ic_keyboard_arrow_left'; import { ic_keyboard_arrow_right } from 'react-icons-kit/md/ic_keyboard_arrow_right'; import { connect } from 'react-redux'; import { firebaseConnect, isLoaded, isEmpty } from 'react-redux-firebase'; import Step from '../step'; import '../assets/css/present.css'; import './assets/css/AnttendeeView.css'; class AttendeeView extends React.Component { constructor(props) { super(props); this.state = { workshop: null, activeStep: 0, status: 'WORKING', mode: 'PRESENT' }; } componentWillReceiveProps(nextProps) { if (!isEmpty(nextProps.workshop)) { const { match: { params: { organizerId, workshopId, attendeeId } } } = nextProps; const workshop = nextProps.workshop.organizers[organizerId].workshops[workshopId]; const attendee = workshop.attendee[attendeeId]; this.setState({ workshop, attendee, activeStep: attendee.step, status: attendee.status }); } } onClick = () => { const { activeStep, status, workshop } = this.state; const { firebase, match: { params: { organizerId, workshopId, attendeeId } } } = this.props; if (status === 'WORKING') { this.setState({ status: 'COMPLETE' }, () => { firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/status`, 'COMPLETE'); }); } else if (status === 'COMPLETE') { if (activeStep + 1 === workshop.steps.length) return; this.setState({ activeStep: activeStep + 1, status: activeStep + 1 > workshop.step ? 'ROCKET' : 'WORKING' }, () => { firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/step`, activeStep + 1); firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/status`, 'WORKING'); }); } } goBack = () => { const { activeStep } = this.state; this.setState({ activeStep: activeStep > 0 ? activeStep - 1 : 0, }); } goFoward = () => { const { activeStep, workshop: { steps } } = this.state; this.setState({ activeStep: activeStep < steps.length - 1 ? activeStep + 1 : activeStep, }); } render() { const { workshop, status, activeStep } = this.state; if (isEmpty(workshop)) return <div></div>; return ( <div className="presentation"> <div className="presentation-header">{workshop.title}</div> <div className="presentation-toolbar"> <div className="back" onClick={this.goBack}> <Icon size={18} icon={ic_keyboard_arrow_left} /> </div> <div className="current-step">{ activeStep + 1 } of { workshop.steps.length }</div> <div className="back" onClick={this.goFoward}> <Icon size={18} icon={ic_keyboard_arrow_right} /> </div> <div className={`action-attendee ${status.toLowerCase()}`} onClick={this.onClick}>{status === 'WORKING' ? 'Complete' : 'Next Step'}</div> </div> <Step step={workshop.steps[activeStep]} /> </div> ); } } const wrapped = firebaseConnect(({ match: { params }}) => ([ `/organizers/${params.organizerId}/workshops/${params.workshopId}` ]))(AttendeeView); export default connect( ({ firebase: { data }}) => ({ workshop: !isEmpty(data) && data }) )(wrapped);
src/chat/attachments/PhotoLibrary.js
elarasu/roverz-chat
import React from 'react'; import { StyleSheet, Text, TouchableOpacity, View, Modal, KeyboardAvoidingView, TextInput, Platform, Image, } from 'react-native'; import PropTypes from 'prop-types'; import { Icon } from 'react-native-elements'; import CameraRollPicker from 'react-native-camera-roll-picker'; import { isIphoneX } from 'react-native-iphone-x-helper'; import { Actions } from 'react-native-router-flux'; import NavBar, { NavButton, NavButtonText, NavTitle, } from 'react-native-nav'; import { AppColors } from '../../theme/'; import ImageUtil from './ImageUtil'; import t from '../../i18n'; const styles = StyleSheet.create({ preview: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', }, overlay: { position: 'absolute', padding: 16, right: 0, left: 0, alignItems: 'center', }, captureButton: { padding: 15, backgroundColor: 'white', borderRadius: 40, }, messageContainer: { flex: 1, flexDirection: 'row', marginBottom: (Platform.OS === 'ios') ? 16 : 0, }, textInput: { backgroundColor: '#F5F5F5', borderRadius: 3, padding: 5, marginRight: 8, height: 40, flex: 1, fontSize: 16, fontFamily: 'OpenSans-Regular', }, sendButton: { height: 40, width: 40, }, buttonsSpace: { width: 30, }, }); export default class PhotoLibrary extends React.Component { constructor(props) { super(props); this._images = []; const groupId = this.props.groupId; this.state = { groupId, modalPreviewVisible: false, imageData: {}, imageMessage: '', }; this.selectImages = this.selectImages.bind(this); } setImages(images) { this._images = images; } getImages() { return this._images; } setPreviewModalVisible(visible = false) { this.setState({ modalPreviewVisible: visible }); } selectImages(images) { this.setImages(images); } selectPictureForPreview = (data) => { this.setState({ imageData: data, previewImageUri: data.path, modalPreviewVisible: true, }); const images = this.getImages().map(image => ({ image: image.uri, })); this.props.onSend(images); this.setImages([]); this.setPreviewModalVisible(true); } sendImageMessages() { const images = this.getImages().map(image => ({ image: image.uri, })); if (images && images.length > 0) { if (images.length === 1) { const data = { path: images[0].image }; this.selectPictureForPreview(data); } else { for (let i = 0; i < images.length; i += 1) { const data = { path: images[i].image }; const _progressCallback = this.props.progressCallback; new ImageUtil().uploadImage(data, this.state.groupId, true, this.state.imageMessage, (fuFileName, fuPercent, fuMsg) => { // console.log(fuFileName, ':', fuPercent, ':', fuMsg); const fileNameCount = fuFileName; const percentage = Math.round(Number(parseFloat(fuPercent).toFixed(2) * 100)); if (_progressCallback) { _progressCallback(fileNameCount, fuMsg, percentage, images.length, i); } }); } this.props.onSend(images); this.setImages([]); Actions.pop(); } } } sendLibraryImage() { const _progressCallback = this.props.progressCallback; new ImageUtil().uploadImage(this.state.imageData, this.state.groupId, true, this.state.imageMessage, (fuFileName, fuPercent, fuMsg) => { // console.log(fuFileName, ':', fuPercent, ':', fuMsg); const percentage = Math.round(Number(parseFloat(fuPercent).toFixed(2) * 100)); if (_progressCallback) { _progressCallback(fuFileName, fuMsg, percentage, 1, 0); } }); this.setState({ imageData: {}, imageMessage: '', }); Actions.pop(); } renderNavBar() { return ( <NavBar style={{ statusBar: { backgroundColor: '#FFF', }, navBar: { backgroundColor: '#FFF', marginTop: isIphoneX() ? 25 : null, }, }} > <NavButton onPress={() => { this.setState({ imageData: {} }); Actions.pop({ duration: 0 }); }} > <NavButtonText style={{ color: '#000', }} > {t('lbl_nav_cancel')} </NavButtonText> </NavButton> <NavTitle style={{ color: '#000', }} > {t('lbl_nav_camera_roll')} </NavTitle> <NavButton onPress={() => { this.sendImageMessages(); }} > <NavButtonText style={{ color: '#000', }} > {t('lbl_nav_send')} </NavButtonText> </NavButton> </NavBar> ); } renderPreview() { return ( <Modal animationType={'none'} transparent={false} visible={this.state.modalPreviewVisible} onRequestClose={() => { this.setPreviewModalVisible(false); }} > <Image style={styles.preview} source={{ uri: this.state.previewImageUri }} /> <KeyboardAvoidingView behavior={(Platform.OS === 'ios') ? 'padding' : 'height'} style={[styles.overlay, { bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)', flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }]} > <View style={styles.messageContainer} > <TextInput placeholder={t('ph_image_caption')} style={[styles.textInput]} onChangeText={(text) => { this.setState({ imageMessage: text }); }} value={this.state.imageMessage} underlineColorAndroid={'transparent'} /> <TouchableOpacity style={[styles.sendButton]} onPress={() => { this.setPreviewModalVisible(false); this.sendLibraryImage(); }} > <Icon name="send" size={34} color={AppColors.brand().third} /> </TouchableOpacity> </View> </KeyboardAvoidingView> <TouchableOpacity style={[styles.captureButton, { position: 'absolute', top: isIphoneX() ? 40 : 20, left: 20, }]} onPress={() => { this.setPreviewModalVisible(false); this.setState({ imageData: {} }); }} > <Icon name="arrow-back" size={20} color="#000" width={20} /> </TouchableOpacity> </Modal> ); } render() { return ( <View style={{ flex: 1, }} > {this.renderPreview()} {this.renderNavBar()} <CameraRollPicker maximum={10} assetType={'All'} pageSize={2} imagesPerRow={3} callback={this.selectImages} selected={[]} selectedMarker={ <View style={{ height: '100%', backgroundColor: 'rgba(0,0,0,0.3)', width: '100%', position: 'absolute', justifyContent: 'center', alignItems: 'center', zIndex: 200, }} > <Icon name="done" type="MaterialIcons" size={45} color={'#fff'} /> </View> } /> </View> ); } } PhotoLibrary.defaultProps = { onSend: () => {}, containerStyle: {}, textStyle: {}, groupId: null, progressCallback: () => {}, }; PhotoLibrary.propTypes = { onSend: React.PropTypes.func, containerStyle: View.propTypes.style, textStyle: Text.propTypes.style, groupId: PropTypes.string, progressCallback: PropTypes.func, };
src/Affix.js
chilts/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import AffixMixin from './AffixMixin'; const Affix = React.createClass({ mixins: [AffixMixin], render() { let holderStyle = { top: this.state.affixPositionTop, // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; return ( <div {...this.props} className={classNames(this.props.className, this.state.affixClass)} style={holderStyle}> {this.props.children} </div> ); } }); export default Affix;
resources/js/components/editor.js
ncbrown1/go-playground
import React from 'react'; import { connect } from 'react-redux'; import CodeMirror from 'react-codemirror'; import * as actions from '../actions'; class Editor extends React.Component { constructor(props){ super(props); } shouldComponentUpdate(nextProps, newState) { return nextProps.forceEditorRender; } render() { let options = { autofocus: true, indentUnit: 4, keymap: 'sublime', lineNumbers: true, mode: 'go', theme: 'monokai', value: this.props.code }; return <div id="go-editor"> <CodeMirror value={this.props.code} onChange={this.props.updateCode} options={options} /> </div>; } } // Maps state from store to props const mapStateToProps = (state, ownProps) => { return { code: state.code, // this.props.code forceEditorRender: state.forceEditorRender }; }; // Maps actions to props const mapDispatchToProps = (dispatch) => { return { // this.props.updateCode updateCode: code => dispatch(actions.updateCode(code)) }; }; // Use connect to put them together export default connect(mapStateToProps, mapDispatchToProps)(Editor);
src/explore/LoadableStartExploringPage.js
ipfs/webui
import React from 'react' import Loadable from '@loadable/component' import ComponentLoader from '../loader/ComponentLoader.js' const LoadableStartExploringPage = Loadable(() => import('./StartExploringContainer'), { fallback: <ComponentLoader/> } ) export default LoadableStartExploringPage
app/javascript/mastodon/components/avatar.js
summoners-riftodon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class Avatar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, size: PropTypes.number.isRequired, style: PropTypes.object, inline: PropTypes.bool, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { account, size, animate, inline } = this.props; const { hovering } = this.state; const src = account.get('avatar'); const staticSrc = account.get('avatar_static'); let className = 'account__avatar'; if (inline) { className = className + ' account__avatar-inline'; } const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } return ( <div className={className} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} /> ); } }
test/datepicker_test.js
mitchrosu/react-datepicker
import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-addons-test-utils' import { mount } from 'enzyme' import defer from 'lodash/defer' import DatePicker from '../src/datepicker.jsx' import Day from '../src/day' import TetherComponent from '../src/tether_component.jsx' import moment from 'moment' describe('DatePicker', () => { it('should show the calendar when focusing on the date input', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) expect(datePicker.refs.calendar).to.exist }) it('should show the calendar when clicking on the date input', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.click(ReactDOM.findDOMNode(dateInput)) expect(datePicker.refs.calendar).to.exist }) it('should not set open state when it is disabled and gets clicked', function () { var datePicker = TestUtils.renderIntoDocument( <DatePicker disabled/> ) var dateInput = datePicker.refs.input TestUtils.Simulate.click(ReactDOM.findDOMNode(dateInput)) expect(datePicker.state.open).to.be.false }) it('should render the calendar into a specified node', () => { var node = document.createElement('div') document.body.appendChild(node) var datePicker = TestUtils.renderIntoDocument( <DatePicker renderCalendarTo={node} /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.click(ReactDOM.findDOMNode(dateInput)) expect(datePicker.refs.calendar).to.exist var calendarNode = ReactDOM.findDOMNode(datePicker.refs.calendar) expect(node.contains(calendarNode)).to.be.true document.body.removeChild(node) }) it('should keep the calendar shown when blurring the date input', (done) => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input var focusSpy = sinon.spy(dateInput, 'focus') TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) TestUtils.Simulate.blur(ReactDOM.findDOMNode(dateInput)) defer(() => { expect(datePicker.refs.calendar).to.exist assert(focusSpy.calledOnce, 'should refocus the date input') done() }) }) it('should not re-focus the date input when focusing the year dropdown', (done) => { const onBlurSpy = sinon.spy() const datePicker = mount( <DatePicker showMonthDropdown showYearDropdown dropdownMode="select" onBlur={onBlurSpy}/> ) const dateInput = datePicker.ref('input') const focusSpy = sinon.spy(dateInput.get(0), 'focus') dateInput.simulate('focus') const yearSelect = datePicker.ref('calendar').find('.react-datepicker__year-select') dateInput.simulate('blur') yearSelect.simulate('focus') defer(() => { assert(focusSpy.called === false, 'should not refocus the date input') assert(onBlurSpy.called === false, 'should not call DatePicker onBlur') done() }) }) it('should keep the calendar shown when clicking the calendar', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) TestUtils.Simulate.click(ReactDOM.findDOMNode(datePicker.refs.calendar)) expect(datePicker.refs.calendar).to.exist }) it('should hide the calendar when clicking a day on the calendar', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) var day = TestUtils.scryRenderedComponentsWithType(datePicker.refs.calendar, Day)[0] TestUtils.Simulate.click(ReactDOM.findDOMNode(day)) expect(datePicker.refs.calendar).to.not.exist }) it('should hide the calendar when the pressing enter in the date input', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) TestUtils.Simulate.keyDown(ReactDOM.findDOMNode(dateInput), { key: 'Enter' }) expect(datePicker.refs.calendar).to.not.exist }) it('should hide the calendar when the pressing escape in the date input', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) TestUtils.Simulate.keyDown(ReactDOM.findDOMNode(dateInput), { key: 'Escape' }) expect(datePicker.refs.calendar).to.not.exist }) it('should hide the calendar when tabbing from the date input', () => { var onBlurSpy = sinon.spy() var datePicker = TestUtils.renderIntoDocument( <DatePicker onBlur={onBlurSpy} /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) TestUtils.Simulate.keyDown(ReactDOM.findDOMNode(dateInput), { key: 'Tab' }) TestUtils.Simulate.blur(ReactDOM.findDOMNode(dateInput)) expect(datePicker.refs.calendar).to.not.exist assert(onBlurSpy.calledOnce, 'should call onBlur') }) it('should not apply the react-datepicker-ignore-onclickoutside class to the date input when closed', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input expect(ReactDOM.findDOMNode(dateInput).className).to.not.contain('react-datepicker-ignore-onclickoutside') }) it('should apply the react-datepicker-ignore-onclickoutside class to date input when open', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) var dateInput = datePicker.refs.input TestUtils.Simulate.focus(ReactDOM.findDOMNode(dateInput)) expect(ReactDOM.findDOMNode(dateInput).className).to.contain('react-datepicker-ignore-onclickoutside') }) it('should allow clearing the date when isClearable is true', () => { var cleared = false function handleChange (d) { if (d === null) { cleared = true } } var datePicker = TestUtils.renderIntoDocument( <DatePicker selected={moment('2015-12-15')} isClearable onChange={handleChange} /> ) var clearButton = TestUtils.findRenderedDOMComponentWithClass(datePicker, 'react-datepicker__close-icon') TestUtils.Simulate.click(clearButton) expect(cleared).to.be.true }) it('should save time from the selected date', () => { const selected = moment('2015-12-20 10:11:12') let date var datePicker = TestUtils.renderIntoDocument( <DatePicker inline selected={selected} onChange={(d) => { date = d }} /> ) var dayButton = TestUtils.scryRenderedDOMComponentsWithClass(datePicker, 'react-datepicker__day')[0] TestUtils.Simulate.click(dayButton) expect(date.hours()).to.equal(10) expect(date.minutes()).to.equal(11) expect(date.seconds()).to.equal(12) }) it('should mount and unmount properly', done => { var TestComponent = React.createClass({ displayName: 'TestComponent', getInitialState () { return { mounted: true } }, render () { return this.state.mounted ? <DatePicker /> : null } }) var element = TestUtils.renderIntoDocument(<TestComponent />) element.setState({ mounted: false }, done) }) it('should render calendar inside TetherComponent when inline prop is not set', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker /> ) expect(function () { TestUtils.findRenderedComponentWithType(datePicker, TetherComponent) }).to.not.throw() }) it('should render calendar directly without TetherComponent when inline prop is set', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker inline /> ) expect(function () { TestUtils.findRenderedComponentWithType(datePicker, TetherComponent) }).to.throw() expect(datePicker.refs.calendar).to.exist }) it('should ignore disable prop when inline prop is set', () => { var datePicker = TestUtils.renderIntoDocument( <DatePicker inline disabled /> ) expect(datePicker.refs.calendar).to.exist }) function getOnInputKeyDownStuff () { var m = moment() var copyM = moment(m) var testFormat = 'YYYY-MM-DD' var callback = sinon.spy() var datePicker = TestUtils.renderIntoDocument( <DatePicker selected={m} onChange={callback}/> ) var dateInput = datePicker.refs.input var nodeInput = ReactDOM.findDOMNode(dateInput) TestUtils.Simulate.focus(nodeInput) return { m, copyM, testFormat, callback, datePicker, dateInput, nodeInput } } it('should handle onInputKeyDown ArrowLeft', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'ArrowLeft', keyCode: 37, which: 37}) data.copyM.subtract(1, 'days') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown ArrowRight', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'ArrowRight', keyCode: 39, which: 39}) data.copyM.add(1, 'days') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown ArrowUp', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'ArrowUp', keyCode: 38, which: 38}) data.copyM.subtract(1, 'weeks') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown ArrowDown', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'ArrowDown', keyCode: 40, which: 40}) data.copyM.add(1, 'weeks') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown PageUp', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'PageUp', keyCode: 33, which: 33}) data.copyM.subtract(1, 'months') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown PageDown', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'PageDown', keyCode: 34, which: 34}) data.copyM.add(1, 'months') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown Home', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'Home', keyCode: 36, which: 36}) data.copyM.subtract(1, 'years') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should handle onInputKeyDown End', () => { var data = getOnInputKeyDownStuff() TestUtils.Simulate.keyDown(data.nodeInput, {key: 'End', keyCode: 35, which: 35}) data.copyM.add(1, 'years') expect(data.callback.calledOnce).to.be.true var result = data.callback.args[0][0] expect(result.format(data.testFormat)).to.equal(data.copyM.format(data.testFormat)) }) it('should autofocus the input given the autoFocus prop', () => { var div = document.createElement('div') document.body.appendChild(div) ReactDOM.render(<DatePicker autoFocus />, div) expect(div.querySelector('input')).to.equal(document.activeElement) }) it('should autofocus the input when calling the setFocus method', () => { var div = document.createElement('div') document.body.appendChild(div) var datePicker = ReactDOM.render(<DatePicker />, div) datePicker.setFocus() expect(div.querySelector('input')).to.equal(document.activeElement) }) it('should correctly clear date with empty input string', () => { var cleared = false function handleChange (d) { // Internally DateInput calls it's onChange prop with null // when the input value is an empty string if (d === null) { cleared = true } } var datePicker = TestUtils.renderIntoDocument( <DatePicker selected={moment('2016-11-22')} onChange={handleChange} /> ) var input = ReactDOM.findDOMNode(datePicker.refs.input) input.value = '' TestUtils.Simulate.change(input) expect(cleared).to.be.true }) })
src/components/icons/NoAnswerMobileIcon.js
austinknight/ui-components
import React from 'react'; const NoAnswerMobileIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24" fill="currentColor"> {props.title && <title>{props.title}</title>} <path d="M15.5,1 L7.5,1 C6.12,1 5,2.12 5,3.5 L5,20.5 C5,21.88 6.12,23 7.5,23 L15.5,23 C16.88,23 18,21.88 18,20.5 L18,3.5 C18,2.12 16.88,1 15.5,1 Z M11.5,22 C10.67,22 10,21.33 10,20.5 C10,19.67 10.67,19 11.5,19 C12.33,19 13,19.67 13,20.5 C13,21.33 12.33,22 11.5,22 Z M16,18 L7,18 L7,4 L16,4 L16,18 Z M15,13.013 L12.487,10.5 L15,7.987 L14.013,7 L11.5,9.513 L8.987,7 L8,7.987 L10.513,10.5 L8,13.013 L8.987,14 L11.5,11.487 L14.013,14 L15,13.013 Z" id="path-1"></path> </svg> ); export default NoAnswerMobileIcon;
test/PanelSpec.js
chilts/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Panel from '../src/Panel'; import Table from '../src/Table'; describe('Panel', function () { it('Should have class and body', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel>Panel content</Panel> ); assert.ok(React.findDOMNode(instance).className.match(/\bpanel\b/)); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-body')); }); it('Should have bootstrap style class', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel bsStyle="default">Panel content</Panel> ); assert.ok(React.findDOMNode(instance).className.match(/\bpanel-default\b/)); }); it('Should honour additional classes passed in, adding not overriding', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel className="bob"/> ); assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/)); assert.ok(React.findDOMNode(instance).className.match(/\bpanel\b/)); }); it('Should have unwrapped header', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel header="Heading">Panel content</Panel> ); let header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading')); assert.equal(header.innerHTML, 'Heading'); }); it('Should have custom component header', function () { let header = <h3>Heading</h3>; let instance = ReactTestUtils.renderIntoDocument( <Panel header={header}>Panel content</Panel> ); header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading')); assert.equal(header.firstChild.nodeName, 'H3'); assert.ok(header.firstChild.className.match(/\bpanel-title\b/)); assert.equal(header.firstChild.innerHTML, 'Heading'); }); it('Should have custom component header with anchor', function () { let header = <h3>Heading</h3>; let instance = ReactTestUtils.renderIntoDocument( <Panel header={header} collapsible={true}>Panel content</Panel> ); header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading')); assert.equal(header.firstChild.nodeName, 'H3'); assert.ok(header.firstChild.className.match(/\bpanel-title\b/)); assert.equal(header.firstChild.firstChild.nodeName, 'A'); assert.equal(header.firstChild.firstChild.innerHTML, 'Heading'); }); it('Should have custom component header with custom class', function () { let header = <h3 className="custom-class">Heading</h3>; let instance = ReactTestUtils.renderIntoDocument( <Panel header={header}>Panel content</Panel> ); header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading')); assert.equal(header.firstChild.nodeName, 'H3'); assert.ok(header.firstChild.className.match(/\bpanel-title\b/)); assert.ok(header.firstChild.className.match(/\bcustom-class\b/)); assert.equal(header.firstChild.innerHTML, 'Heading'); }); it('Should have footer', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel footer="Footer">Panel content</Panel> ); let footer = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-footer')); assert.equal(footer.innerText, 'Footer'); }); it('Should have collapse classes', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} expanded={true}>Panel content</Panel> ); assert.ok(React.findDOMNode(instance).querySelector('.panel-collapse.collapse.in')); }); it('Should pass through dom properties', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={false} id="testid">Panel content</Panel> ); assert.equal(React.findDOMNode(instance).id, 'testid'); }); it('Should pass id to panel-collapse', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} id="testid" header="Heading">Panel content</Panel> ); assert.notOk(React.findDOMNode(instance).id); let collapse = React.findDOMNode(instance).querySelector('.panel-collapse'); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.equal(collapse.id, 'testid'); assert.equal(anchor.getAttribute('href'), '#testid'); }); it('Should be open', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} expanded={true} header="Heading">Panel content</Panel> ); let collapse = React.findDOMNode(instance).querySelector('.panel-collapse'); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.ok(collapse.className.match(/\bin\b/)); assert.notOk(anchor.className.match(/\bcollapsed\b/)); }); it('Should be closed', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} expanded={false} header="Heading">Panel content</Panel> ); let collapse = React.findDOMNode(instance).querySelector('.panel-collapse'); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.notOk(collapse.className.match(/\bin\b/)); assert.ok(anchor.className.match(/\bcollapsed\b/)); }); it('Should call onSelect handler', function (done) { function handleSelect (e, key) { assert.equal(key, '1'); done(); } let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} onSelect={handleSelect} header="Click me" eventKey='1'>Panel content</Panel> ); let title = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-title'); ReactTestUtils.Simulate.click(React.findDOMNode(title).firstChild); }); it('Should toggle when uncontrolled', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} defaultExpanded={false} header="Click me">Panel content</Panel> ); assert.notOk(instance.state.expanded); ReactTestUtils.Simulate.click( React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-title')).firstChild ); assert.ok(instance.state.expanded); }); it('Should not wrap panel-filling tables in a panel body', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel> Panel content <Table fill /> More panel content </Panel> ); let children = React.findDOMNode(instance).children; assert.equal(children.length, 3); assert.equal(children[0].nodeName, 'DIV'); assert.ok(children[0].className.match(/\bpanel-body\b/)); assert.equal(children[1].nodeName, 'TABLE'); assert.notOk(children[1].className.match(/\bpanel-body\b/)); assert.equal(children[2].nodeName, 'DIV'); assert.ok(children[2].className.match(/\bpanel-body\b/)); }); it('Should not wrap single panel-fill table in a panel body', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel> <Table fill /> </Panel> ); let children = React.findDOMNode(instance).children; assert.equal(children.length, 1); assert.equal(children[0].nodeName, 'TABLE'); assert.notOk(children[0].className.match(/\bpanel-body\b/)); }); describe('Web Accessibility', function(){ it('Should be aria-expanded=true', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} expanded={true} header="Heading">Panel content</Panel> ); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.equal(anchor.getAttribute('aria-expanded'), 'true'); }); it('Should be aria-expanded=false', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel collapsible={true} expanded={false} header="Heading">Panel content</Panel> ); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.equal(anchor.getAttribute('aria-expanded'), 'false'); }); it('Should add aria-controls with id', function () { let instance = ReactTestUtils.renderIntoDocument( <Panel id='panel-1' collapsible expanded header="Heading">Panel content</Panel> ); let collapse = React.findDOMNode(instance).querySelector('.panel-collapse'); let anchor = React.findDOMNode(instance).querySelector('.panel-title a'); assert.equal(collapse.getAttribute('id'), 'panel-1'); assert.equal(anchor.getAttribute('aria-controls'), 'panel-1'); }); }); });
src/lib/gui/components/ServerViewHeaderToggle/ServerViewHeaderToggle.js
xclix/chan
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; const ServerViewHeaderToggle = ({ toggled, serverId, onSwitchButtonClick }) => { const toggleClassNames = classnames({ 'server-view-header-toggle': true, 'server-view-header-toggle--up': toggled }); return ( <button className={toggleClassNames} onClick={() => onSwitchButtonClick(serverId, toggled)} > <svg className="server-view-header-toggle-icon" width="60px" height="60px" > <title>icons_power/on@3x</title> <desc>Created with Sketch.</desc> <defs /> <g id="Page-1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd" opacity="0.75" > <path className="server-view-header-toggle__icon" transform="translate(4, 4)" d="M26.0503929,17 C25.3931535,17 24.8637106,17.5364493 24.8637106,18.1941509 L24.8637106,23.6945939 C24.8637106,24.3559698 25.3968048,24.8887448 26.0503929, 24.8887448 C26.7039809,24.8887448 27.2370751,24.3522955 27.2370751,23.6945939 L27.2370751,18.1941509 C27.2370751,17.5364493 26.7076322,17 26.0503929,17 M18.0357237,27.6738723 C17.7728279,24.8262816 18.9814181,22.2469155 20.9859983 ,20.608173 C21.7673829,19.968843 22.9358084,20.5163152 22.9358084,21.5267506 C22.9358084,21.897856 22.7605446,22.2395669 22.4757409,22.4710485 C21.0553735, 23.6358049 20.2009623,25.4729602 20.4090881,27.5011797 C20.6792866,30.143009 22.7824526,32.2814577 25.4041075,32.5754026 C28.8254036,32.9612052 31.7318987, 30.2642612 31.7318987,26.8985927 C31.7318987,25.1128778 30.9103495,23.5145527 29.6286962,22.4673742 C29.3438924,22.2358926 29.1722799,21.8941817 29.1722799, 21.5267506 C29.1722799,20.5273382 30.3224489,19.9614943 31.0965308,20.5861271 C32.9294984,22.0742229 34.1052632,24.3486212 34.1052632,26.8985927 C34.1052632, 31.5612929 30.169093,35.3201494 25.4625287,34.9784017 C21.5702111,34.7028284 18.3972054,31.5833387 18.0357237,27.6738723" id="Fill-1" fill="#83878E" /> <circle stroke="#83878E" id="Oval" strokeWidth="2" cx="28" cy="28" r="26" transform="translate(2, 2)" /> </g> </svg> </button> ); }; ServerViewHeaderToggle.propTypes = { toggled: PropTypes.bool.isRequired, serverId: PropTypes.string.isRequired, onSwitchButtonClick: PropTypes.func.isRequired }; export default ServerViewHeaderToggle;