path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
docs/app/Examples/collections/Form/States/FormExampleError.js
koenvg/Semantic-UI-React
import React from 'react' import { Button, Form, Input, Message } from 'semantic-ui-react' const FormExampleError = () => ( <Form error> <Form.Input label='Email' placeholder='joe@schmoe.com' /> <Message error header='Action Forbidden' content='You can only sign up for an account once with a given e-mail address.' /> <Button>Submit</Button> </Form> ) export default FormExampleError
l2_es6/node_modules/eslint-config-airbnb/test/test-react-order.js
kobkrit/learn-react-native
import test from 'tape'; import { CLIEngine } from 'eslint'; import eslintrc from '../'; import reactRules from '../rules/react'; import reactA11yRules from '../rules/react-a11y'; const cli = new CLIEngine({ useEslintrc: false, baseConfig: eslintrc, rules: { // It is okay to import devDependencies in tests. 'import/no-extraneous-dependencies': [2, { devDependencies: true }], }, }); function lint(text) { // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext const linter = cli.executeOnText(text); return linter.results[0]; } function wrapComponent(body) { return ` import React from 'react'; export default class MyComponent extends React.Component { /* eslint no-empty-function: 0 */ ${body} } `; } test('validate react prop order', (t) => { t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { t.plan(2); t.deepEqual(reactRules.plugins, ['react']); t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); }); t.test('passes a good component', (t) => { t.plan(3); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; } `)); t.notOk(result.warningCount, 'no warnings'); t.notOk(result.errorCount, 'no errors'); t.deepEquals(result.messages, [], 'no messages in results'); }); t.test('order: when random method is first', t => { t.plan(2); const result = lint(wrapComponent(` someMethod() {} componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', t => { t.plan(2); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); });
packages/expo-dev-menu/vendored/react-native-gesture-handler/src/touchables/TouchableOpacity.js
exponentjs/exponent
import { Animated, Easing, StyleSheet, View } from 'react-native'; import GenericTouchable, { TOUCHABLE_STATE } from './GenericTouchable'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; /** * TouchableOpacity bases on timing animation which has been used in RN's core */ export default class TouchableOpacity extends Component { static defaultProps = { ...GenericTouchable.defaultProps, activeOpacity: 0.2, }; static propTypes = { ...GenericTouchable.publicPropTypes, style: PropTypes.any, activeOpacity: PropTypes.number, }; // opacity is 1 one by default but could be overwritten getChildStyleOpacityWithDefault = () => { const childStyle = StyleSheet.flatten(this.props.style) || {}; return childStyle.opacity == null ? 1 : childStyle.opacity; }; opacity = new Animated.Value(this.getChildStyleOpacityWithDefault()); setOpacityTo = (value, duration) => { Animated.timing(this.opacity, { toValue: value, duration: duration, easing: Easing.inOut(Easing.quad), useNativeDriver: true, }).start(); }; onStateChange = (from, to) => { if (to === TOUCHABLE_STATE.BEGAN) { this.setOpacityTo(this.props.activeOpacity, 0); } else if ( to === TOUCHABLE_STATE.UNDETERMINED || to === TOUCHABLE_STATE.MOVED_OUTSIDE ) { this.setOpacityTo(this.getChildStyleOpacityWithDefault(), 150); } }; render() { const { style = {}, ...rest } = this.props; return ( <GenericTouchable {...rest} style={[ style, { opacity: this.opacity, }, ]} onStateChange={this.onStateChange}> {this.props.children ? this.props.children : <View />} </GenericTouchable> ); } }
src/svg-icons/action/trending-flat.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingFlat = (props) => ( <SvgIcon {...props}> <path d="M22 12l-4-4v3H3v2h15v3z"/> </SvgIcon> ); ActionTrendingFlat = pure(ActionTrendingFlat); ActionTrendingFlat.displayName = 'ActionTrendingFlat'; ActionTrendingFlat.muiName = 'SvgIcon'; export default ActionTrendingFlat;
src/Typography/Typography.js
gutenye/react-mc
// @flow import React from 'react' import cx from 'classnames' import type { PropsC } from '../types' class Typography extends React.Component { props: PropsC static defaultProps = { component: 'div', } render() { const { component: Component, className, ...rest } = this.props const rootClassName = cx('mdc-typography', className) return <Component className={rootClassName} {...rest} /> } } export default Typography
node_modules/react-bootstrap/es/FormControlStatic.js
Chen-Hailin/iTCM.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'p' }; var FormControlStatic = function (_React$Component) { _inherits(FormControlStatic, _React$Component); function FormControlStatic() { _classCallCheck(this, FormControlStatic); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormControlStatic.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return FormControlStatic; }(React.Component); FormControlStatic.propTypes = propTypes; FormControlStatic.defaultProps = defaultProps; export default bsClass('form-control-static', FormControlStatic);
src/client/components/forms/parts/achievement.js
bookbrainz/bookbrainz-site
/* * Copyright (C) 2016 Max Prettyjohns * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU 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 DragAndDropImage from '../../input/drag-and-drop-image'; import PropTypes from 'prop-types'; import React from 'react'; class Achievement extends React.Component { constructor(props) { super(props); this.state = { achievement: props.achievement, unlocked: props.unlocked }; } render() { let imgElement; if (this.state.unlocked) { imgElement = ( <DragAndDropImage achievementId={this.state.achievement.id} achievementName={this.state.achievement.name} height="100px" src={this.state.achievement.badgeUrl} style={{zIndex: 2}} /> ); } else { imgElement = ( <img alt={this.state.achievement.name} height="100px" src={this.state.achievement.badgeUrl} style={{zIndex: 2}} /> ); } return ( <div className="row well"> <div className="col-sm-2"> {imgElement} </div> <div className="col-sm-8"> <div className="h2"> {this.state.achievement.name} </div> <p>{this.state.achievement.description}</p> </div> </div> ); } } Achievement.displayName = 'achievement'; Achievement.propTypes = { achievement: PropTypes.shape({ badgeUrl: PropTypes.string, description: PropTypes.string, name: PropTypes.string }).isRequired, unlocked: PropTypes.bool }; Achievement.defaultProps = { unlocked: false }; export default Achievement;
old/cppcon-2017-web-service/example/client/strawpoll/src/App.js
Voultapher/Presentations
import React from 'react'; import PropTypes from 'prop-types'; import Fingerprint2 from 'fingerprintjs2'; import { flatbuffers } from './flatbuffers'; import { Strawpoll } from './strawpoll_generated.js'; import './App.css'; function printWrap(val) { console.log("val: ", val); return val; } function uOr(val, fn) { return val === undefined ? undefined : fn(val); } function ResultDescription(props) { return ( <div style={{ marginBottom: 4, overflow: 'hidden' }} className={'ResultDescription'} > {props.text} </div> ); } ResultDescription.propTypes = { text: PropTypes.string.isRequired }; const barColorsA = [ // eslint-disable-line no-unused-vars '#4b3947', '#e3c17d', '#f9f2e5', '#9e8e85' ]; const barColorsB = [ // eslint-disable-line no-unused-vars '#9eb4db', '#756a92', '#494165', '#2e205c', '#22144f' ]; const barColorsC = [ // eslint-disable-line no-unused-vars '#ffd0b0', '#ffa996', '#e6857c', '#d1626d', '#b54b63' ]; function ResultBar(props) { return ( <div className={'ResultBar'} style={{ position: 'relative' }}> <div style={{ width: `${props.width.toFixed(2)}%`, height: '100%', backgroundColor: props.barColor }} /> <div style={{ position: 'absolute', top: '0.35em', right: '0.5em' }}> {props.percent.toFixed(0)}% ({props.votes} votes) </div> </div> ); } ResultBar.propTypes = { width: PropTypes.number.isRequired, barColor: PropTypes.string.isRequired, percent: PropTypes.number.isRequired, votes: PropTypes.number.isRequired }; function BarChart(props) { // FIXME talk about shalow copy and sorting as weird for a c++ user const options = props.options.slice().sort((a, b) => (b.votes - a.votes)); const total = options.reduce((sum, an) => (sum + an.votes), 0); return ( <div className={'BarChart'}> {options.map((an, i) => { const width = (an.votes / total) * 100; return ( <div key={an.text} style={{ paddingBottom: '1em' }}> <ResultDescription text={an.text} /> <ResultBar width={width} barColor={props.barColors[i % props.barColors.length]} percent={width} votes={an.votes} /> </div> ); })} Total Votes: <span style={{ fontWeight: 600 }}>{total}</span> </div> ); } BarChart.propTypes = { options: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired, votes: PropTypes.number.isRequired })).isRequired, barColors: PropTypes.arrayOf(PropTypes.string).isRequired }; BarChart.defaultProps = { barColors: barColorsB }; function Vote(props) { return ( <ul className="Vote"> {props.options.map((option, i) => ( <li key={option.text}> <button onClick={() => { props.handleVote(i) }}> {option.text} </button> </li> ))} </ul> ); } Vote.propTypes = { options: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired })).isRequired, handleVote: PropTypes.func.isRequired }; class StrawPoll extends React.Component { constructor(props) { super(props); this.state = { hasVoted: false, title: '', options: [] }; } componentDidMount() { this.setupWebSocketCommunication(); } shouldComponentUpdate(nextProps, nextState) { return nextState.options.length > 0 && nextState.options[0].text !== undefined; } setupWebSocketCommunication() { this.socket = new WebSocket(this.props.apiUrl); this.socket.binaryType = 'arraybuffer'; this.socket.addEventListener('open', this.fetchPoll); this.socket.addEventListener('message', this.handleServerResponse); this.socket.addEventListener('close', this.handleDisconnect); } fetchPoll = (event) => { new Fingerprint2().get((result, components) => { const builder = new flatbuffers.Builder(1024); const fingerprint = builder.createString(result); Strawpoll.Request.startRequest(builder); Strawpoll.Request.addType(builder, Strawpoll.RequestType.Poll); Strawpoll.Request.addFingerprint(builder, fingerprint); builder.finish(Strawpoll.Request.endRequest(builder)); this.socket.send(builder.asUint8Array()); }); } fetchResult = (id) => { const builder = new flatbuffers.Builder(1024); Strawpoll.Request.startRequest(builder); Strawpoll.Request.addType(builder, Strawpoll.RequestType.Result); Strawpoll.Request.addVote(builder, builder.createLong(id)); builder.finish(Strawpoll.Request.endRequest(builder)); this.socket.send(builder.asUint8Array()); } handleServerResponse = (event) => { //console.log("Server sent: ", event); const buf = new flatbuffers.ByteBuffer(new Uint8Array(event.data)); const response = Strawpoll.Response.getRootAsResponse(buf); //console.log("Response Type: ", response.type()); switch(response.type()) { case Strawpoll.ResponseType.Poll: this.updatePoll(response.poll()); break; case Strawpoll.ResponseType.Result: this.updateResult(response.result()); break; case Strawpoll.ResponseType.Error: console.error("Error: ", response.error()); break; default: console.error("Invalid response type: ", response.type()); }; } updatePoll = (poll) => { //console.log("updatePoll called ", this.state); this.setState((prevState) => ({ title: poll.title(), options: Array.apply(null, { length: poll.optionsLength() }) .map((v, i) => ({ text: poll.options(i), votes: uOr(prevState.options[i], (op) => (op.votes)) })) })); } updateResult = (result) => { //console.log("updateResult called ", this.state); this.setState((prevState) => ({ hasVoted: true, options: Array.apply(null, { length: result.votesLength() }) .map((v, i) => ({ text: uOr(prevState.options[i], (op) => (op.text)), votes: result.votes(i).toFloat64() })) })); } handleDisconnect = (event) => { console.error("WebSocket closed"); } handleVote = (id) => { this.fetchResult(id); } render() { return ( <div> <h1>{this.state.title}</h1> {this.state.hasVoted ? <BarChart options={this.state.options} barColors={barColorsC} /> : <Vote options={this.state.options} handleVote={this.handleVote}/> } </div> ); } }; function PresentationUrl(props) { return ( <div style={{ textAlign: 'right', fontWeight: 600 }}> <span style={{ fontSize: '1.3em' }}>Go Vote at: </span> <span style={{ fontSize: '2em', color: '#b54b63' }}>var.bz</span> </div> ); } StrawPoll.propTypes = { apiUrl: PropTypes.string.isRequired }; class App extends React.Component { render() { return ( <div className="App"> <StrawPoll apiUrl={'ws://165.227.29.121:3003'} /> {/*<StrawPoll apiUrl={'ws://localhost:3003'} />*/} <PresentationUrl /> </div> ); } }; export default App;
src/svg-icons/navigation/arrow-back.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowBack = (props) => ( <SvgIcon {...props}> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/> </SvgIcon> ); NavigationArrowBack = pure(NavigationArrowBack); NavigationArrowBack.displayName = 'NavigationArrowBack'; NavigationArrowBack.muiName = 'SvgIcon'; export default NavigationArrowBack;
mobile/src/components/alarm.js
sradevski/homeAutomate
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, Picker } from 'react-native'; import { connect } from 'react-redux'; import Icon from 'react-native-vector-icons/Ionicons'; import Button from 'react-native-button'; import _ from 'lodash'; import SliderWithLabel from './sliderWithLabel'; import ClickableLabel from './sectionClickableLabel'; import {makeServerCall, generateRequestBody} from '../shared/utils'; import {toggleAlarm, setAlarmTime, updateAlarmState} from '../state/actions/alarm'; import {showNotification, changeConnectionStatus} from '../state/actions/appState'; const Item = Picker.Item; const mapStateToProps = (state) => ({ alarm: state.alarm, }); const mapDispatchToProps = (dispatch) => ({ toggleAlarm: () => { dispatch(toggleAlarm()); }, setAlarmTime: (time) => { dispatch(setAlarmTime(time)); }, updateAlarmState: (newState) => { dispatch(updateAlarmState(newState)); }, showNetworkStatus: (message) => { dispatch(changeConnectionStatus(message)); }, showNotification: (message) => { dispatch(showNotification(message)); } }); class Alarm extends Component { sendToServer(requestBody){ this.props.showNetworkStatus('Fetching...'); makeServerCall('alarm', requestBody) .then((data) => { this.props.updateAlarmState(data); this.props.showNetworkStatus('Fetched alarm data'); }) .catch((err) => { this.props.showNotification(`Oops, something didn't work`); this.props.showNetworkStatus('Fetching failed.'); }); } toggleAlarm() { const {isOn, timeData} = this.props.alarm; let args = [timeData.hour, timeData.minute]; if (isOn) { args = ['r']; } this.props.toggleAlarm(); this.sendToServer(generateRequestBody('alarmToggle', args)); } pickerChanged(key, value) { const {isOn, timeData} = this.props.alarm; const newTimeData = Object.assign({}, timeData); newTimeData[key] = value; this.props.setAlarmTime(newTimeData); if (isOn){ this.sendToServer(generateRequestBody('alarmToggle', [newTimeData.hour, newTimeData.minute])); } } render() { const {isOn, timeData} = this.props.alarm; const labelColor = isOn ? 'green' : 'red'; return ( <View {...this.props}> <ClickableLabel containerStyle = {{paddingRight: 30}} iconName= 'md-alarm' iconSize= {32} color = {labelColor} backgroundColor = 'skyblue' onPress = {() => this.toggleAlarm()}> Alarm </ClickableLabel> {_.keys(timeData).map((key, index) => <Picker key = {key} style={[styles.picker, pickerColor]} itemStyle = {pickerItemColor} selectedValue = {timeData[key]} onValueChange={(val, index) => { this.pickerChanged(key, val); }} mode='dropdown'> {alarmData[key].map((val, index) => <Item key={val} label={val} value={val} /> )} </Picker> )} </View> ); } } const alarmData = { hour: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '0'], minute: ['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'], }; const pickerColor = Platform.OS === 'android' ? { color: 'white' } : {}, pickerItemColor = Platform.OS === 'android' ? {} : { color: 'white' }; const styles = StyleSheet.create({ picker: { width: 90 }, }); export default connect(mapStateToProps, mapDispatchToProps)(Alarm);
imports/ui/pages/Collection/pages/Collection/components/Content.js
ShinyLeee/meteor-album-app
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import moment from 'moment'; import ConnectedJustified from '/imports/ui/components/JustifiedLayout'; import PhotoSwipeHolder from './PhotoSwipeHolder'; import { Header, Title, SubTitle } from '../styles'; const getDuration = (images) => { let duration; const imgLen = images.length; if (imgLen === 0) { duration = '暂无相片'; } else if (imgLen === 1) { duration = moment(images[0].shootAt).format('YYYY年MM月DD日'); } else if (imgLen > 1) { const start = moment(images[imgLen - 1].shootAt).format('YYYY年MM月DD日'); const end = moment(images[0].shootAt).format('YYYY年MM月DD日'); duration = `${start} - ${end}`; } return duration; }; export default class CollectionContent extends Component { static propTypes = { isEditing: PropTypes.bool.isRequired, images: PropTypes.array.isRequired, match: PropTypes.object.isRequired, } render() { const { images, isEditing, match } = this.props; const { cname } = match.params; return ( <div> <Header> <Title>{cname}</Title> <SubTitle>{getDuration(images)}</SubTitle> </Header> { images.length > 0 && ( <ConnectedJustified isEditing={isEditing} images={images} /> ) } <PhotoSwipeHolder /> </div> ); } }
index.android.js
rjvani/agent
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class agent extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('agent', () => agent);
docs/app/Examples/views/Card/Types/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const Types = () => ( <ExampleSection title='Types'> <ComponentExample title='Card' description='A card displays site content in a manner similar to a playing card.' examplePath='views/Card/Types/CardExampleIndividualCard' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='views/Card/Types/CardExampleIndividualCardProps' /> <ComponentExample title='Cards' description='A group of cards.' examplePath='views/Card/Types/CardExampleGroups' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='views/Card/Types/CardExampleGroupProps' /> </ExampleSection> ) export default Types
app/containers/Teachers/Teachers.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Loadable from 'react-loadable'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; // import TeacherScreen from '../../components/Teachers'; import { getBoundariesEntities, getTeachers, getLanguages, showAddTeacherPopup, showTeacherLoading, } from '../../actions'; import { checkPermissions, getEntitiesPath } from '../../utils'; import { Loading } from '../../components/common'; const TeacherScreen = Loadable({ loader: () => { return import('../../components/Teachers/ShowTeachers'); }, loading: Loading, }); class GetTeachers extends Component { constructor(props) { super(props); this.getEntities = this.getEntities.bind(this); } componentDidMount() { const { institution } = this.props; this.props.getLanguages(); this.props.showTeacherLoading(); if (isEmpty(institution)) { const entities = this.getEntities(); this.props.getBoundariesEntities(entities); } if (!isEmpty(institution)) { this.props.getTeachers(institution.id); } } componentWillReceiveProps(nextProps) { if (nextProps.institution !== this.props.institution) { if (!isEmpty(nextProps.institution)) { this.props.getTeachers(nextProps.institution.id); } } } getEntities() { const { params, parentId } = this.props; const { blockNodeId, districtNodeId, clusterNodeId } = params; return [parentId, districtNodeId, blockNodeId, clusterNodeId].map((id, i) => { return { depth: i, uniqueId: id }; }); } render() { return <TeacherScreen {...this.props} />; } } const mapStateToProps = (state, ownProps) => { const { blockNodeId, districtNodeId, clusterNodeId, institutionNodeId } = ownProps.params; const district = get(state.boundaries.boundaryDetails, districtNodeId, {}); const block = get(state.boundaries.boundaryDetails, blockNodeId, {}); const cluster = get(state.boundaries.boundaryDetails, clusterNodeId, {}); const institution = get(state.boundaries.boundaryDetails, institutionNodeId, {}); const { isAdmin } = state.profile; const hasPermissions = checkPermissions( isAdmin, state.userPermissions, [district.id, block.id, cluster.id], institution.id, ); const pathname = get(ownProps, ['location', 'pathname'], ''); const paths = getEntitiesPath(pathname, [ districtNodeId, blockNodeId, clusterNodeId, institutionNodeId, ]); return { district, block, cluster, institution, teacherIds: Object.keys(state.teachers.teachers), isLoading: state.appstate.loadingBoundary, teacherLoading: state.teachers.loading, hasPermissions, paths, parentId: state.profile.parentNodeId, }; }; GetTeachers.propTypes = { teacherIds: PropTypes.array, params: PropTypes.object, institution: PropTypes.object, getBoundariesEntities: PropTypes.func, getTeachers: PropTypes.func, getLanguages: PropTypes.func, primary: PropTypes.bool, showTeacherLoading: PropTypes.func, parentId: PropTypes.string, }; const Teachers = connect(mapStateToProps, { getBoundariesEntities, getTeachers, getLanguages, showAddTeacherPopup, showTeacherLoading, })(GetTeachers); export { Teachers };
src/svg-icons/action/eject.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionEject = (props) => ( <SvgIcon {...props}> <path d="M5 17h14v2H5zm7-12L5.33 15h13.34z"/> </SvgIcon> ); ActionEject = pure(ActionEject); ActionEject.displayName = 'ActionEject'; ActionEject.muiName = 'SvgIcon'; export default ActionEject;
src/server/render/redux.js
PepijnSenders/ronvandekerkhof.nl
import { match, RouterContext } from 'react-router'; import { Map, fromJS } from 'immutable'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { Provider } from 'react-redux'; import Helmet from 'react-helmet'; import { StyleSheetServer } from 'aphrodite'; import { default as createMemoryHistory } from 'history/lib/createMemoryHistory'; import { createHistory } from '<common/utilities>/history'; import { configureStore } from '<common/store>'; import { renderRequest, renderFailed } from '<common/actions>'; import { createContext } from '<server/context>'; import createRoutes from '<common/routes>'; import HttpError from '<server/http>/errors/HttpError'; import { send, sendError, redirect } from '<server/http>/response'; import Meta from '<common/components>/Meta'; import preRenderMiddleware from '<common/middlewares>/preRenderMiddleware'; export default function redux(req, res) { const routes = createRoutes(); const history = createHistory(routes, createMemoryHistory); const store = configureStore(fromJS({}), history); const context = createContext(store, createRoutes(), req); store.dispatch(renderRequest(req.url)); renderer(context, req.url) .then(({ status, body }) => { if (status >= 200 && status < 300) { res.status(status) .send(body); } else { res.redirect(status, body); } }) .catch((err) => { const status = 500; store.dispatch(renderFailed(req.url, status, err.message)); res.status(status) .send(err.message); }); } export function renderer(context = new Map(), location) { return resolveMatch({ routes: context.get('routes'), location, }).then(({ redirectLocation, renderProps }) => { if (redirectLocation) { return Promise.resolve(redirect(redirectLocation)); } if (renderProps) { return renderHTML(renderProps, context); } return Promise.reject(); }).catch((err) => { if (err) { sendError(err); return Promise.resolve(sendError(err)); } const httpError = HttpError.createFromStatus(404); return Promise.resolve( sendError(httpError) ); }); } function renderHTML(renderProps, context, req) { const store = context.get('store'); return preRenderMiddleware( store.dispatch, renderProps.components, renderProps.params, context.get('req') ).then(() => { const header = renderHeader(context.get('helmetConfig')); const renderFunction = context.get('renderIndex'); const initialState = store.getState(); const radiumConfig = context.get('radiumConfig'); const { css, html } = renderComponent(store, renderProps, radiumConfig); return renderFunction(header, initialState, html, css); }).then((compiled) => send(200, compiled)); } function renderHeader(config) { renderToString( // Needs to be here for helmet to know what to rewind <Meta config={config} /> ); return Helmet.rewind(); } function resolveMatch({ routes, location }) { return new Promise((resolve, reject) => { match({ routes, location, }, (err, redirectLocation, renderProps) => { if (err) { reject(err); } else { resolve({ redirectLocation, renderProps, }); } }); }); } function renderComponent(store, renderProps) { return StyleSheetServer.renderStatic(() => renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ) ); }
src/svg-icons/device/widgets.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceWidgets = (props) => ( <SvgIcon {...props}> <path d="M13 13v8h8v-8h-8zM3 21h8v-8H3v8zM3 3v8h8V3H3zm13.66-1.31L11 7.34 16.66 13l5.66-5.66-5.66-5.65z"/> </SvgIcon> ); DeviceWidgets = pure(DeviceWidgets); DeviceWidgets.displayName = 'DeviceWidgets'; DeviceWidgets.muiName = 'SvgIcon'; export default DeviceWidgets;
jenkins-design-language/src/js/components/material-ui/svg-icons/hardware/laptop-mac.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareLaptopMac = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/> </SvgIcon> ); HardwareLaptopMac.displayName = 'HardwareLaptopMac'; HardwareLaptopMac.muiName = 'SvgIcon'; export default HardwareLaptopMac;
src/svg-icons/maps/directions-bike.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsBike = (props) => ( <SvgIcon {...props}> <path d="M15.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5zm5.8-10l2.4-2.4.8.8c1.3 1.3 3 2.1 5.1 2.1V9c-1.5 0-2.7-.6-3.6-1.5l-1.9-1.9c-.5-.4-1-.6-1.6-.6s-1.1.2-1.4.6L7.8 8.4c-.4.4-.6.9-.6 1.4 0 .6.2 1.1.6 1.4L11 14v5h2v-6.2l-2.2-2.3zM19 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5z"/> </SvgIcon> ); MapsDirectionsBike = pure(MapsDirectionsBike); MapsDirectionsBike.displayName = 'MapsDirectionsBike'; MapsDirectionsBike.muiName = 'SvgIcon'; export default MapsDirectionsBike;
src/containers/Accounts/SignUp/InputDetails.js
westoncolemanl/tabbr-web
import React from 'react' import TextField from 'material-ui/TextField' import Button from 'material-ui/Button' import Card, { CardActions, CardContent } from 'material-ui/Card' import Typography from 'material-ui/Typography' import * as EmailValidator from 'email-validator' import { PasswordInput, CardLogoHeader } from 'components' export default ({ email, firstName, lastName, password, confirmPassword, onChangeEmail, onChangeFirstName, onChangeLastName, onChangePassword, onChangeConfirmPassword, onSubmit, setState, errorPassword, errorConfirmPassword }) => <Card raised > <CardLogoHeader /> <CardContent> <Typography variant={'headline'} gutterBottom > {'Create account'} </Typography> <TextField label={'Email address'} fullWidth value={email} margin={'normal'} onChange={(e) => onChangeEmail(e.target.value)} /> <TextField label={'First name'} fullWidth value={firstName} margin={'normal'} onChange={(e) => onChangeFirstName(e.target.value)} /> <TextField label={'Last name'} fullWidth value={lastName} margin={'normal'} onChange={(e) => onChangeLastName(e.target.value)} /> <div className={'mt3'} /> <PasswordInput label={'New password'} value={password} onChange={(e) => onChangePassword(e)} helperText={errorPassword} error={Boolean(errorPassword)} onBlur={() => { if (password.length === 0) { setState({ errorPassword: false }) } else if (password.length > 0 && password.length < 6) { setState({ errorPassword: 'Password is less than 6 characters' }) } else if (password !== confirmPassword && confirmPassword.length >= 6) { setState({ errorPassword: 'Passwords do not match' }) } else if (password === confirmPassword && password.length >= 6 && confirmPassword.length >= 6) { setState({ errorPassword: false, errorConfirmPassword: false }) } else { setState({ errorPassword: false }) } }} /> <div className={'mt3'} /> <PasswordInput label={'Confirm new password'} value={confirmPassword} onChange={(e) => onChangeConfirmPassword(e)} helperText={errorConfirmPassword} error={Boolean(errorConfirmPassword)} onBlur={() => { if (confirmPassword.length === 0) { setState({ errorConfirmPassword: false }) } else if (confirmPassword.length > 0 && confirmPassword.length < 6) { setState({ errorConfirmPassword: 'Confirmed password is less than 6 characters' }) } else if (password !== confirmPassword && password.length >= 6) { setState({ errorConfirmPassword: 'Passwords do not match' }) } else if (password === confirmPassword && password.length >= 6 && confirmPassword.length >= 6) { setState({ errorPassword: false, errorConfirmPassword: false }) } else { setState({ errorConfirmPassword: false }) } }} /> </CardContent> <CardActions className={'flex flex-row justify-end'} > <Button children={'NEXT'} color={'primary'} variant={'raised'} disabled={ email.length === 0 || !EmailValidator.validate(email) || firstName.length === 0 || lastName.length === 0 || password.length < 6 || password !== confirmPassword } onClick={onSubmit} /> </CardActions> </Card>
setup/src/universal/features/routing/containers/LoginRedirectContainer.js
ch-apptitude/goomi
/** * * LoginRedirect * */ import React, { Component } from 'react'; import RedirectBox from 'features/routing/components/RedirectBox'; import messages from './messages'; class LoginRedirect extends Component { body = messages.LoginRedirectBody; buttons = [ { linkTo: '/login', message: messages.LoginRedirectLogin, }, { linkTo: '/register', message: messages.LoginRedirectRegister, }, ]; render() { return <RedirectBox body={this.body} buttons={this.buttons} />; } } export default LoginRedirect;
src/scenes/home/header/logo/logo.js
alexspence/operationcode_frontend
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import logo from 'images/logos/small-white-logo.png'; import styles from './logo.css'; class Logo extends Component { render() { return ( <div className={styles.logo} > <Link to="/"><img src={logo} alt="" /></Link> </div> ); } } export default Logo;
docs/src/examples/modules/Dropdown/Usage/DropdownExampleUpwardSelection.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const options = [ { key: 1, text: 'One', value: 1 }, { key: 2, text: 'Two', value: 2 }, { key: 3, text: 'Three', value: 3 }, ] const DropdownExampleUpwardSelection = () => ( <Dropdown upward search selection options={options} placeholder='Choose an option' /> ) export default DropdownExampleUpwardSelection
src/js/components/routes/Home.react.js
teamUndefined/creativity
import React from 'react'; import { Paper, RaisedButton, CircularProgress } from 'material-ui'; var Home = React.createClass({ getInitialState() { return { search: false } }, componentDidMount() { this.props.socket.on("lobby_found", function(lobbyPath) { window.location = lobbyPath; }); this.props.socket.on("lobby_not_found", function() { notie.alert(3, 'Sorry, We didn\'t fund any rooms!', 3); this.setState({ search: false }); }); }, findRoom() { this.props.socket.emit("server_join_lobby"); this.setState({ search: true }); }, render() { return ( <div className="mdl-grid home"> <div className="mdl-cell mdl-cell--1-col mdl-cell--0-col-phone"></div> <Paper zDepth={1} className="content-container mdl-cell mdl-cell--10-col mdl-cell--12-col-phone"> <div className="mdl-grid"> <div className="mdl-cell mdl-cell--6-col mdl-cell--12-col-phone p-xl text-center"> <a href="/@/createLobby"> <RaisedButton label="Create Room" primary={true} /> </a> </div> <div className="mdl-cell mdl-cell--6-col mdl-cell--12-col-phone p-xl text-center"> <RaisedButton label="Join Room" secondary={true} onClick={this.findRoom} /> { this.state.search ? (<CircularProgress mode="indeterminate" size={0.5} />) : null} </div> </div> </Paper> </div> ); } }); export default Home;
docs/pages/home.js
woshisbb43/coinMessageWechat
import React from 'react'; import FontAwesome from 'react-fontawesome'; import './home.less'; //import { Button } from 'react-weui'; const Home = () => ( <div className="App__preview background--canvas flex-center"> <div className="App__preview--none"> <FontAwesome name="weixin" size="4x" /> <p>Hello, React-WeUI</p> </div> </div> ); export default Home;
example/v9.x.x/razzle-ssr/src/Home.js
i18next/react-i18next
import React, { Component } from 'react'; import { withNamespaces, Trans } from 'react-i18next'; import logo from './react.svg'; import './Home.css'; class Home extends Component { render() { const { t } = this.props; return ( <div className="Home"> <div className="Home-header"> <img src={logo} className="Home-logo" alt="logo" /> <h2>{t('message.welcome')}</h2> </div> <div className="Home-intro"> <Trans i18nKey="guideline"> To get started, edit <code>src/App.js</code> or <code>src/Home.js</code> and save to reload. </Trans> </div> <ul className="Home-resources"> <li> <a href="https://github.com/jaredpalmer/razzle">Docs</a> </li> <li> <a href="https://github.com/jaredpalmer/razzle/issues">Issues</a> </li> <li> <a href="https://palmer.chat">Community Slack</a> </li> </ul> </div> ); } } export default withNamespaces('translations')(Home);
src/components/TableBody/TableCell.js
cantonjs/re-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TableContext from './TableContext'; export default class TableCell extends Component { static propTypes = { children: PropTypes.node, renderCell: PropTypes.func, store: PropTypes.object, }; _handleClick = () => { const { store } = this.props; if (store && store.record) { this.tableContext.toggleSelectedKey(store.record.key); } }; _renderChildren(children, other) { return ( <td {...other} onClick={this._handleClick}> {children} </td> ); } _render = (tableContext) => { this.tableContext = tableContext; const { renderCell, store, children, ...other } = this.props; if (!renderCell) return this._renderChildren(children, other); return renderCell( store, (render) => render ? ( this._renderChildren(render(), other) ) : ( <td style={{ padding: 0 }} /> ) // (render) => (render ? this._renderChildren(render(), other) : null) ); }; render() { return <TableContext.Consumer>{this._render}</TableContext.Consumer>; } }
test/integration/getserversideprops/pages/something.js
flybayer/next.js
import React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' export async function getServerSideProps({ params, query, resolvedUrl }) { return { props: { resolvedUrl: resolvedUrl, world: 'world', query: query || {}, params: params || {}, time: new Date().getTime(), random: Math.random(), }, } } export default ({ world, time, params, random, query, appProps, resolvedUrl, }) => { const router = useRouter() return ( <> <p>hello: {world}</p> <span>time: {time}</span> <div id="random">{random}</div> <div id="params">{JSON.stringify(params)}</div> <div id="initial-query">{JSON.stringify(query)}</div> <div id="query">{JSON.stringify(router.query)}</div> <div id="app-query">{JSON.stringify(appProps.query)}</div> <div id="app-url">{appProps.url}</div> <div id="resolved-url">{resolvedUrl}</div> <div id="as-path">{router.asPath}</div> <Link href="/"> <a id="home">to home</a> </Link> <br /> <Link href="/another"> <a id="another">to another</a> </Link> </> ) }
client/components/MenuItem/index.js
JohannesAnd/SKWebsite
import React from 'react'; import { Item, Link } from './elements'; export default function MenuItem({ className, children, href, current }) { return ( <Item className={className} role={'presentation'}> <Link href={href} current={current}> {children} </Link> </Item> ); }
src/app/components/Article.js
Yording/app-fullstack-yording
import React, { Component } from 'react'; class Article extends Component { constructor(props){ super(props) } render() { return ( <div className="row"> <div className="col s12"> <div className="card grey lighten-4"> <div className="card-content"> <span className="card-title"><a href={this.props.url}>{this.props.title}</a></span> <p>{this.props.description}</p> <h6 className="right-align grey-text text-darken-1"><b><i>Anónimo</i></b></h6> </div> <div className="card-action"> <a className="btn-floating waves-effect waves-light green"><i className="fa fa-pencil"></i></a> <a className="btn-floating waves-effect waves-light red" onClick={this.props.deleteArticle}><i className="fa fa-times"></i></a> </div> </div> </div> </div> ); } } export default Article;
node_modules/react-router/es/Route.js
Oritechnology/pubApp
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import React from 'react'; import PropTypes from 'prop-types'; import matchPath from './matchPath'; /** * The public API for matching a single path and rendering. */ var Route = function (_React$Component) { _inherits(Route, _React$Component); function Route() { var _temp, _this, _ret; _classCallCheck(this, Route); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { match: _this.computeMatch(_this.props, _this.context.router) }, _temp), _possibleConstructorReturn(_this, _ret); } Route.prototype.getChildContext = function getChildContext() { return { router: _extends({}, this.context.router, { route: { location: this.props.location || this.context.router.route.location, match: this.state.match } }) }; }; Route.prototype.computeMatch = function computeMatch(_ref, _ref2) { var computedMatch = _ref.computedMatch, location = _ref.location, path = _ref.path, strict = _ref.strict, exact = _ref.exact; var route = _ref2.route; if (computedMatch) return computedMatch; // <Switch> already computed the match for us var pathname = (location || route.location).pathname; return path ? matchPath(pathname, { path: path, strict: strict, exact: exact }) : route.match; }; Route.prototype.componentWillMount = function componentWillMount() { var _props = this.props, component = _props.component, render = _props.render, children = _props.children; warning(!(component && render), 'You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored'); warning(!(component && children), 'You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored'); warning(!(render && children), 'You should not use <Route render> and <Route children> in the same route; <Route children> will be ignored'); }; Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) { warning(!(nextProps.location && !this.props.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'); warning(!(!nextProps.location && this.props.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.'); this.setState({ match: this.computeMatch(nextProps, nextContext.router) }); }; Route.prototype.render = function render() { var match = this.state.match; var _props2 = this.props, children = _props2.children, component = _props2.component, render = _props2.render; var _context$router = this.context.router, history = _context$router.history, route = _context$router.route, staticContext = _context$router.staticContext; var location = this.props.location || route.location; var props = { match: match, location: location, history: history, staticContext: staticContext }; return component ? // component prop gets first priority, only called if there's a match match ? React.createElement(component, props) : null : render ? // render prop is next, only called if there's a match match ? render(props) : null : children ? // children come last, always called typeof children === 'function' ? children(props) : !Array.isArray(children) || children.length ? // Preact defaults to empty children array React.Children.only(children) : null : null; }; return Route; }(React.Component); Route.propTypes = { computedMatch: PropTypes.object, // private, from <Switch> path: PropTypes.string, exact: PropTypes.bool, strict: PropTypes.bool, component: PropTypes.func, render: PropTypes.func, children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]), location: PropTypes.object }; Route.contextTypes = { router: PropTypes.shape({ history: PropTypes.object.isRequired, route: PropTypes.object.isRequired, staticContext: PropTypes.object }) }; Route.childContextTypes = { router: PropTypes.object.isRequired }; export default Route;
examples/with-atlaskit/components/CheckboxComponent.js
flybayer/next.js
import React from 'react' import { Checkbox } from '@atlaskit/checkbox' export default function CheckboxComponent() { return ( <React.Fragment> <Checkbox value="Basic checkbox" label="Basic checkbox" onChange={() => {}} name="checkbox-basic" testId="cb-basic" /> <Checkbox isDisabled label="Disabled" value="Disabled" name="checkbox-disabled" testId="cb-disabled" /> <Checkbox isInvalid label="Invalid" value="Invalid" name="checkbox-invalid" testId="cb-invalid" /> </React.Fragment> ) }
src/Affix.js
collinwu/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import AffixMixin from './AffixMixin'; import domUtils from './utils/domUtils'; const Affix = React.createClass({ statics: { domUtils }, mixins: [AffixMixin], render() { let holderStyle = {top: this.state.affixPositionTop}; return ( <div {...this.props} className={classNames(this.props.className, this.state.affixClass)} style={holderStyle}> {this.props.children} </div> ); } }); export default Affix;
src/parser/shared/modules/resources/mana/ManaUsageChart.js
anom0ly/WoWAnalyzer
import { Trans } from '@lingui/macro'; import Analyzer from 'parser/core/Analyzer'; import ManaValues from 'parser/shared/modules/ManaValues'; import HealingDone from 'parser/shared/modules/throughput/HealingDone'; import Panel from 'parser/ui/Panel'; import React from 'react'; import ManaUsageChartComponent from './ManaUsageChartComponent'; /** * @property {ManaValues} manaValues * @property {HealingDone} healingDone */ class ManaUsageChart extends Analyzer { static dependencies = { manaValues: ManaValues, healingDone: HealingDone, }; statistic() { const reportCode = this.owner.report.code; const actorId = this.owner.playerId; const start = this.owner.fight.start_time; const end = this.owner.fight.end_time; const offset = this.owner.fight.offset_time; return ( <Panel title={<Trans id="shared.manaUsageChart.statistic.title">Mana usage</Trans>} explanation={ <Trans id="shared.manaUsageChart.statistic.explanation"> This shows you your mana usage in correlation with your throughput. Big spikes in mana usage without increases in throughput may indicate poor mana usage. The scale for both mana lines is 0-100% where 100% is aligned with the max HPS throughput. </Trans> } position={110} > <ManaUsageChartComponent reportCode={reportCode} actorId={actorId} start={start} end={end} offset={offset} manaUpdates={this.manaValues.manaUpdates} healingBySecond={this.healingDone.bySecond} /> </Panel> ); } } export default ManaUsageChart;
client/components/routes/home.js
aintnorest/ubiquitous-spoon
import React from 'react'; import warmahordes from '../../images/warmahordes.png'; import chess from '../../images/chess.png'; import { setGame, setUserName, signIn } from '../../actions/app'; import { connect } from 'react-redux'; import InputField from '../inputField'; import { bindActionCreators } from 'redux'; function Home(props) { let ld = Object.keys(props.loading); console.log('home props: ',props); return ( <div className='body'> { (props.game !== null) ? ( (props.signedIn) ? null : ( <div> <h1>Sign In</h1> <div className='signin-input-wrap'> <InputField type='text' placeholder='' error={props.errorMessage} value={props.userName} change={props.setUserName} id='username' label='Username'/> </div> <button disabled={!props.serverConnected} className="signin-btn" onClick={props.signIn}>Sign In</button> </div> ) ) : ( <div> <h1>Select Game</h1> <ul className="btnless-list"> <li> <div className="card-image"> <img src={chess} alt='chess'/> <span className="card-title">Chess</span> </div> <div className="card-content"> Chess is a two-player strategy board game played on a checkered gameboard with an eight-by-eight grid. </div> <div className="card-action"> <a onClick={() => props.setGame('chess')}>Select Game</a> <a href="https://en.wikipedia.org/wiki/Chess">Read More</a> </div> </li> <li> <div className="card-image"> <img src={warmahordes} alt='warmahordes'/> <span className="card-title">WarmaHordes</span> </div> <div className="card-content"> Warmachine and Hordes are tabletop skirmish sized war games produced by Privateer Press &reg; </div> <div className="card-action"> <a onClick={() => props.setGame('warmachine')}>Select Game</a> <a href="http://privateerpress.com/">Read More</a> </div> </li> </ul> </div> ) } <div className="about-faq-wrap"> <h2>About</h2> <section> The goal is make a more modern and web based alternative to http://www.vassalengine.org/ . As of right now the two primary contributers use vassal for warmachine / hordes and feature development will probably be geared towards that game. </section> <h3>FAQ</h3> <ul> <li>What the name?</li> Didn't want to waste time trying to name it, ubiquitous-spoon was githubs random pick. <li>What games are supported?</li> At first warmachine / hordes but development is being done with an eye towards modularity and support other tabletop games. <li>Is it open source and can I help?</li> Yes please! <a href="https://github.com/aintnorest/ubiquitous-spoon">Ubiquitous Spoon</a> </ul> </div> {(ld.length > 0) ? ( <div className="signin-dialog-bg"> <div className="signin-dialog-box"> <div data-loader="circle" /> { ld.map(function(k,n) { return (<div key={n} className="signin-dialog-txt">{k+" "+props.loading[k]+"%"}</div>); }) } </div> </div> ) : null } </div> ); } export default connect( (state) => state.app, (dispatch) => bindActionCreators({setGame, setUserName, signIn}, dispatch) )(Home);
src/app/createDevToolsWindow.js
eordano/sherlock
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import DevTools from './DevToolsWindow' export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ) // reload in case it's reusing the same window with the old content win.location.reload() // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>') win.document.body.style.margin = '0' ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ) }, 10) }
src/svg-icons/file/cloud-off.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudOff = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4c-1.48 0-2.85.43-4.01 1.17l1.46 1.46C10.21 6.23 11.08 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3 0 1.13-.64 2.11-1.56 2.62l1.45 1.45C23.16 18.16 24 16.68 24 15c0-2.64-2.05-4.78-4.65-4.96zM3 5.27l2.75 2.74C2.56 8.15 0 10.77 0 14c0 3.31 2.69 6 6 6h11.73l2 2L21 20.73 4.27 4 3 5.27zM7.73 10l8 8H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h1.73z"/> </SvgIcon> ); FileCloudOff = pure(FileCloudOff); FileCloudOff.displayName = 'FileCloudOff'; FileCloudOff.muiName = 'SvgIcon'; export default FileCloudOff;
src/components/loading/VerticalTable.js
GovReady/GovReady-Agent-Client
import React from 'react'; import { PropTypes as PT } from 'prop-types'; const VerticalTable = ({text = false, colCount = 4, rowCount = 3 }) => { return ( <div className="widget loading-shim"> <div> <div className="text"> <h3><span className="loading-shim-block-small" /></h3> </div> {text && ( <h5><span className="loading-shim-block-large" /></h5> )} <div className='table-responsive'> <table className='table'> <thead> <tr> {[...Array(colCount)].map((un,i) => ( <th key={i.toString()}><span className="loading-shim-block-small" /></th> ))} </tr> </thead> <tbody> {[...Array(rowCount)].map((un,i) => ( <tr key={i.toString()}> {[...Array(colCount)].map((und,j) => ( <td key={j.toString()}><span className="loading-shim-block-small" /></td> ))} </tr> ))} </tbody> </table> </div> </div> </div> ) } export default VerticalTable;
demo/src/App.js
bringking/react-web-animation
import React, { Component } from 'react'; import { Link, Route, Switch } from 'react-router-dom'; import Basic from './basic'; import BasicGroup from './basic_group'; import BasicSequence from './basic_sequence'; import ParallaxStarfield from './parallax_starfield'; import SpinningDots from './spinning_dots'; import AnimateCss from './animate_css'; import Scrolling from './scrolling'; import SvgGroup from './svg_group'; import Welcome from './welcome'; export default class App extends Component { constructor(props) { super(props); this.state = { menuOpen: false, }; this.onMenuClick = this.onMenuClick.bind(this); this.closeMenu = this.closeMenu.bind(this); } onMenuClick() { this.setState({ menuOpen: !this.state.menuOpen }); } getListItemStyle() { return { width: '100%', padding: '6px', }; } closeMenu() { this.setState({ menuOpen: false }); } render() { return ( <div style={{ display: 'flex' }}> <div className={`menu ${this.state.menuOpen ? 'active' : ''}`}> <button className={`menu-button ${this.state.menuOpen ? 'active' : ''}`} onClick={this.onMenuClick} > Menu </button> <ul style={{ listStyle: 'none', margin: 0, padding: '12px' }}> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/">Home</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/basic">Basic</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/basic-group">Basic Group</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/basic-sequence">Basic Sequence</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/parallax-starfield">Parallax Starfield</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/spinning-dots">Spinning Dots</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/animate-css">AnimateCSS</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/scrolling">Scrolling</Link> </li> <li style={this.getListItemStyle()} onClick={this.closeMenu}> <Link to="/svg-group">SVG Group</Link> </li> </ul> </div> <div className="example-display"> <Switch> <Route path="/basic" component={Basic} /> <Route path="/basic-group" component={BasicGroup} /> <Route path="/basic-sequence" component={BasicSequence} /> <Route path="/parallax-starfield" component={ParallaxStarfield} /> <Route path="/spinning-dots" component={SpinningDots} /> <Route path="/animate-css" component={AnimateCss} /> <Route path="/scrolling" component={Scrolling} /> <Route path="/svg-group" component={SvgGroup} /> <Route component={Welcome} /> </Switch> </div> </div> ); } }
app/components/Thought/index.js
brainsandspace/ship
/** * * Thought * */ import React from 'react'; import styled from 'styled-components'; const Wrapper = styled.span` color: gainsboro; .floating { color: #444; font-weight: 550; font-size:5rem; font-family: 'ah natural'; } `; function Thought({ children }) { return ( <Wrapper> <span className="floating"> {children} </span> </Wrapper> ); } Thought.propTypes = { }; export default Thought;
src/svg-icons/action/donut-large.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDonutLarge = (props) => ( <SvgIcon {...props}> <path d="M11 5.08V2c-5 .5-9 4.81-9 10s4 9.5 9 10v-3.08c-3-.48-6-3.4-6-6.92s3-6.44 6-6.92zM18.97 11H22c-.47-5-4-8.53-9-9v3.08C16 5.51 18.54 8 18.97 11zM13 18.92V22c5-.47 8.53-4 9-9h-3.03c-.43 3-2.97 5.49-5.97 5.92z"/> </SvgIcon> ); ActionDonutLarge = pure(ActionDonutLarge); ActionDonutLarge.displayName = 'ActionDonutLarge'; ActionDonutLarge.muiName = 'SvgIcon'; export default ActionDonutLarge;
examples/query-params/app.js
iest/react-router
import React from 'react'; import { Router, Route, Link } from 'react-router'; var User = React.createClass({ render() { var { query } = this.props.location; var age = query && query.showAge ? '33' : ''; var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> {age} </div> ); } }); var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/bob">Bob</Link></li> <li><Link to="/user/bob" query={{showAge: true}}>Bob With Query Params</Link></li> <li><Link to="/user/sally">Sally</Link></li> </ul> {this.props.children} </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User} /> </Route> </Router> ), document.getElementById('example'));
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DefaultParameters.js
tharakawj/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(id = 0) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, { id: id + 4, name: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-default-parameters"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
react-src/catalog/components/voyages/layouts/CatalogVoyageDetailsModalCards.js
gabzon/experiensa
import React from 'react' import { Button, Header, Image, Modal, Icon, Grid } from 'semantic-ui-react' export default class CatalogVoyageDetailsModalCards extends React.Component { state = { modalOpen: false } handleOpen = (e) => this.setState({ modalOpen: true, }) handleClose = (e) => this.setState({ modalOpen: false, }) constructor(){ super() } render() { let voyage = this.props.voyage let price = () =>{ let value = "" if(voyage.price){ value = "<b>Price</b>: "+ voyage.price+" " if(voyage.currency) value += voyage.currency value += "<br/>" } return value } let duration = () =>{ return (voyage.duration?"<b>Duration</b>: " + voyage.duration+"<br/>":"") } let country = () =>{ return (voyage.country?"<b>Country</b>: " + voyage.country+"<br/>":"") } let location = () =>{ return (voyage.location?"<b>Location</b>: " + voyage.location+"<br/>":"") } let theme = () =>{ return (voyage.theme?"<b>Theme</b>: " + voyage.theme+"<br/>":"") } let voyageImage = () => { let image = voyage.cover_image let imageSrc if(!image.feature_image && image.gallery.length < 1){ imageSrc = sage_vars.stylesheet_directory_uri + '/assets/images/travel-no-image.jpg' }else{ if(image.feature_image){ imageSrc = image.feature_image }else{ imageSrc = image.gallery[0] } } return imageSrc } let itinerary_title = () => { let title = '' if(voyage.itinerary && voyage.itinerary !== "") title = "Itinerary" return title } return ( <Modal trigger={<Button id="modal-card-details" onClick={this.handleOpen} className="ui green button catalog-button" type="submit" name="select" style={{"width": "100%","height": "100%"}}><Icon name='eye' />Details</Button>} open={this.state.modalOpen} onClose={this.handleClose} > <Modal.Header> <h2>{voyage.title}</h2> </Modal.Header> <Modal.Content> <Grid stackable columns={2}> <Grid.Column width={6}> <div dangerouslySetInnerHTML={{__html: price()}}/> <div dangerouslySetInnerHTML={{__html: duration()}}/> <div dangerouslySetInnerHTML={{__html: country()}}/> <div dangerouslySetInnerHTML={{__html: location()}}/> <div dangerouslySetInnerHTML={{__html: theme()}}/> <br/> <p dangerouslySetInnerHTML={{__html: voyage.excerpt}}></p> </Grid.Column> <Grid.Column width={10}> <Image src={voyageImage()}/> </Grid.Column> </Grid> </Modal.Content> <Modal.Content> <h3>{itinerary_title()}</h3> <Modal.Description dangerouslySetInnerHTML={{__html: voyage.itinerary}}> </Modal.Description> </Modal.Content> <Modal.Actions> <Button color="black" onClick={this.handleClose}>Close</Button> <a className="ui positive right labeled icon button"> Contact us <Icon name='checkmark' /> </a> </Modal.Actions> </Modal> ); } }
src/components/Navbar/Navbar.js
baruinho/cashier
import React from 'react'; import { Link } from 'react-router-dom'; import { Navbar , Nav, NavItem, MenuItem, NavDropdown } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; export default ({ accounts = []}) => ( <Navbar inverse collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to="/">Cashier</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <LinkContainer to="/about"> <NavItem eventKey={1}>About</NavItem> </LinkContainer> <NavDropdown eventKey={3} title="Accounts" id="basic-nav-dropdown"> <LinkContainer to="/accounts"> <MenuItem eventKey={3.1}>Manage accounts</MenuItem> </LinkContainer> <MenuItem divider /> <MenuItem eventKey={3.2}>Another action</MenuItem> </NavDropdown> </Nav> <Nav pullRight> <NavItem eventKey={1} href="#">Link Right</NavItem> <NavItem eventKey={2} href="#">Link Right</NavItem> </Nav> </Navbar.Collapse> </Navbar> );
node_modules/react-router/es6/RouteContext.js
jotamaggi/react-calendar-app
import warning from './routerWarning'; import React from 'react'; var object = React.PropTypes.object; /** * The RouteContext mixin provides a convenient way for route * components to set the route in context. This is needed for * routes that render elements that want to use the Lifecycle * mixin to prevent transitions. */ var RouteContext = { propTypes: { route: object.isRequired }, childContextTypes: { route: object.isRequired }, getChildContext: function getChildContext() { return { route: this.props.route }; }, componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin') : void 0; } }; export default RouteContext;
src/components/recording/AudioRecordingStream.js
streamr-app/streamr-web
import React from 'react' import cx from 'classnames' import { BinaryClient } from '../../vendor/binary' import Recorder from 'react-recorder' const FFT_SIZE = 64 const NUM_FFT_BARS = 32 export default class AudioRecordingStream extends React.Component { constructor (props) { super(props) this.state = { fft: new Uint8Array(FFT_SIZE) } } componentDidMount () { this.visualizerFrame = requestAnimationFrame(() => this.redrawVisualizer()) } componentWillReceiveProps (nextProps) { if (nextProps.recordingStarted && !this.streamSetup) { this.client = new BinaryClient(process.env.RECORDING_SERVICE_URL) this.client.on('open', () => { this.stream = this.client.createStream({ streamId: this.props.streamId, authToken: this.props.authToken, sampleRate: this.sampleRate }) this.props.onAudioReady() this.setState({ recording: true }) this.recording = true }) this.client.on('error', () => { this.props.onWebsocketFailure() }) this.streamSetup = true } if (nextProps.recordingStopped) { this.client && this.client.close() clearTimeout(this.visualizerTimeout) this.setState({ fft: new Uint8Array(NUM_FFT_BARS) }) } } componentWillUnmount () { this.stream && this.stream.end() this.client && this.client.close() this.audioStream && this.audioStream.getTracks()[0].stop() clearTimeout(this.visualizerTimeout) cancelAnimationFrame(this.visualizerFrame) } gotStream (stream) { this.audioStream = stream this.audioContext = new AudioContext() this.sampleRate = this.audioContext.sampleRate const audioInput = this.audioContext.createMediaStreamSource(stream) const bufferSize = 2048 const recorder = this.audioContext.createScriptProcessor(bufferSize, 1, 1) recorder.onaudioprocess = (event) => { this.analysisProcess(event) this.recorderProcess(event) } this.analyzer = this.audioContext.createAnalyser() this.analyzer.smoothingTimeConstant = 0.2 this.analyzer.fftSize = FFT_SIZE audioInput.connect(recorder) audioInput.connect(this.analyzer) recorder.connect(this.audioContext.destination) } onStop (blob) { console.log(blob) } recorderProcess (event) { if (!this.recording || this.props.recordingStopped) return null var left = event.inputBuffer.getChannelData(0) this.stream.write(this.float32to16(left)) } analysisProcess (event) { const data = new Uint8Array(NUM_FFT_BARS) this.analyzer.getByteFrequencyData(data) this.fft = data } float32to16 (buffer) { var l = buffer.length const buf = new Int16Array(l) while (l--) { buf[l] = Math.min(1, buffer[l]) * 0x7FFF } return buf.buffer } redrawVisualizer () { this.setState({ fft: this.fft }, () => { this.visualizerTimeout = setTimeout(() => { this.visualizerFrame = requestAnimationFrame(() => this.redrawVisualizer()) }, 10) }) } render () { const fft = Array.from(this.state.fft || []) return ( <div className='recorder'> <div className={cx('visualizer', { recording: this.state.recording && !this.props.recordingStopped })}> {fft.map((bar, i) => ( <div className='bar' key={i} style={{ height: `${bar / 255 * 100}%` }} /> ))} </div> <Recorder onStop={this.onStop} gotStream={(stream) => this.gotStream(stream)} onMissingAPIs={this.props.onMissingAPIs} onError={this.onError} /> </div> ) } } /* global AudioContext, Int16Array, requestAnimationFrame, cancelAnimationFrame */
modules/Link.js
9618211/react-router
import React from 'react'; var { object, string, func } = React.PropTypes; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * <Link> components are used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route name="showPost" path="/posts/:postID" handler={Post}/> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along query string parameters * using the `query` prop. * * <Link to="/posts/123" query={{ show:true }}/> */ export var Link = React.createClass({ contextTypes: { router: object }, propTypes: { activeStyle: object, activeClassName: string, to: string.isRequired, query: object, state: object, onClick: func }, getDefaultProps() { return { className: '', activeClassName: 'active', style: {} }; }, handleClick(event) { var allowTransition = true; var clickResult; if (this.props.onClick) clickResult = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (clickResult === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) this.context.router.transitionTo(this.props.to, this.props.query, this.props.state); }, render() { var { router } = this.context; var { to, query } = this.props; var props = Object.assign({}, this.props, { href: router.makeHref(to, query), onClick: this.handleClick }); // ignore if rendered outside of the context of a router, simplifies unit testing if (router && router.isActive(to, query)) { if (props.activeClassName) props.className += props.className !== '' ? ` ${props.activeClassName}` : props.activeClassName; if (props.activeStyle) props.style = Object.assign({}, props.style, props.activeStyle); } return React.createElement('a', props); } }); export default Link;
app/javascript/mastodon/components/status.js
sylph-sin-tyaku/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import AvatarOverlay from './avatar_overlay'; import AvatarComposite from './avatar_composite'; import RelativeTimestamp from './relative_timestamp'; import DisplayName from './display_name'; import StatusContent from './status_content'; import StatusActionBar from './status_action_bar'; import AttachmentList from './attachment_list'; import Card from '../features/status/components/card'; import { injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { MediaGallery, Video, Audio } from '../features/ui/util/async-components'; import { HotKeys } from 'react-hotkeys'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import { displayMedia } from '../initial_state'; // We use the component (and not the container) since we do not want // to use the progress bar to show download progress import Bundle from '../features/ui/components/bundle'; export const textForScreenReader = (intl, status, rebloggedByText = false) => { const displayName = status.getIn(['account', 'display_name']); const values = [ displayName.length === 0 ? status.getIn(['account', 'acct']).split('@')[0] : displayName, status.get('spoiler_text') && status.get('hidden') ? status.get('spoiler_text') : status.get('search_index').slice(status.get('spoiler_text').length), intl.formatDate(status.get('created_at'), { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }), status.getIn(['account', 'acct']), ]; if (rebloggedByText) { values.push(rebloggedByText); } return values.join(', '); }; export const defaultMediaVisibility = (status) => { if (!status) { return undefined; } if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { status = status.get('reblog'); } return (displayMedia !== 'hide_all' && !status.get('sensitive') || displayMedia === 'show_all'); }; export default @injectIntl class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, account: ImmutablePropTypes.map, otherAccounts: ImmutablePropTypes.list, onClick: PropTypes.func, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onPin: PropTypes.func, onOpenMedia: PropTypes.func, onOpenVideo: PropTypes.func, onBlock: PropTypes.func, onEmbed: PropTypes.func, onHeightChange: PropTypes.func, onToggleHidden: PropTypes.func, muted: PropTypes.bool, hidden: PropTypes.bool, unread: PropTypes.bool, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, showThread: PropTypes.bool, getScrollPosition: PropTypes.func, updateScrollBottom: PropTypes.func, cacheMediaWidth: PropTypes.func, cachedMediaWidth: PropTypes.number, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'account', 'muted', 'hidden', ]; state = { showMedia: defaultMediaVisibility(this.props.status), statusId: undefined, }; // Track height changes we know about to compensate scrolling componentDidMount () { this.didShowCard = !this.props.muted && !this.props.hidden && this.props.status && this.props.status.get('card'); } getSnapshotBeforeUpdate () { if (this.props.getScrollPosition) { return this.props.getScrollPosition(); } else { return null; } } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.status && nextProps.status.get('id') !== prevState.statusId) { return { showMedia: defaultMediaVisibility(nextProps.status), statusId: nextProps.status.get('id'), }; } else { return null; } } // Compensate height changes componentDidUpdate (prevProps, prevState, snapshot) { const doShowCard = !this.props.muted && !this.props.hidden && this.props.status && this.props.status.get('card'); if (doShowCard && !this.didShowCard) { this.didShowCard = true; if (snapshot !== null && this.props.updateScrollBottom) { if (this.node && this.node.offsetTop < snapshot.top) { this.props.updateScrollBottom(snapshot.height - snapshot.top); } } } } componentWillUnmount() { if (this.node && this.props.getScrollPosition) { const position = this.props.getScrollPosition(); if (position !== null && this.node.offsetTop < position.top) { requestAnimationFrame(() => { this.props.updateScrollBottom(position.height - position.top); }); } } } handleToggleMediaVisibility = () => { this.setState({ showMedia: !this.state.showMedia }); } handleClick = () => { if (this.props.onClick) { this.props.onClick(); return; } if (!this.context.router) { return; } const { status } = this.props; this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`); } handleExpandClick = (e) => { if (this.props.onClick) { this.props.onClick(); return; } if (e.button === 0) { if (!this.context.router) { return; } const { status } = this.props; this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`); } } handleAccountClick = (e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { const id = e.currentTarget.getAttribute('data-id'); e.preventDefault(); this.context.router.history.push(`/accounts/${id}`); } } handleExpandedToggle = () => { this.props.onToggleHidden(this._properStatus()); }; renderLoadingMediaGallery () { return <div className='media-gallery' style={{ height: '110px' }} />; } renderLoadingVideoPlayer () { return <div className='video-player' style={{ height: '110px' }} />; } renderLoadingAudioPlayer () { return <div className='audio-player' style={{ height: '110px' }} />; } handleOpenVideo = (media, startTime) => { this.props.onOpenVideo(media, startTime); } handleHotkeyReply = e => { e.preventDefault(); this.props.onReply(this._properStatus(), this.context.router.history); } handleHotkeyFavourite = () => { this.props.onFavourite(this._properStatus()); } handleHotkeyBoost = e => { this.props.onReblog(this._properStatus(), e); } handleHotkeyMention = e => { e.preventDefault(); this.props.onMention(this._properStatus().get('account'), this.context.router.history); } handleHotkeyOpen = () => { this.context.router.history.push(`/statuses/${this._properStatus().get('id')}`); } handleHotkeyOpenProfile = () => { this.context.router.history.push(`/accounts/${this._properStatus().getIn(['account', 'id'])}`); } handleHotkeyMoveUp = e => { this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyMoveDown = e => { this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyToggleHidden = () => { this.props.onToggleHidden(this._properStatus()); } handleHotkeyToggleSensitive = () => { this.handleToggleMediaVisibility(); } _properStatus () { const { status } = this.props; if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { return status.get('reblog'); } else { return status; } } handleRef = c => { this.node = c; } render () { let media = null; let statusAvatar, prepend, rebloggedByText; const { intl, hidden, featured, otherAccounts, unread, showThread } = this.props; let { status, account, ...other } = this.props; if (status === null) { return null; } const handlers = this.props.muted ? {} : { reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, open: this.handleHotkeyOpen, openProfile: this.handleHotkeyOpenProfile, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleHotkeyToggleHidden, toggleSensitive: this.handleHotkeyToggleSensitive, }; if (hidden) { return ( <HotKeys handlers={handlers}> <div ref={this.handleRef} className={classNames('status__wrapper', { focusable: !this.props.muted })} tabIndex='0'> {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])} {status.get('content')} </div> </HotKeys> ); } if (status.get('filtered') || status.getIn(['reblog', 'filtered'])) { const minHandlers = this.props.muted ? {} : { moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, }; return ( <HotKeys handlers={minHandlers}> <div className='status__wrapper status__wrapper--filtered focusable' tabIndex='0' ref={this.handleRef}> <FormattedMessage id='status.filtered' defaultMessage='Filtered' /> </div> </HotKeys> ); } if (featured) { prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><Icon id='thumb-tack' className='status__prepend-icon' fixedWidth /></div> <FormattedMessage id='status.pinned' defaultMessage='Pinned toot' /> </div> ); } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { const display_name_html = { __html: status.getIn(['account', 'display_name_html']) }; prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><Icon id='retweet' className='status__prepend-icon' fixedWidth /></div> <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} /> </div> ); rebloggedByText = intl.formatMessage({ id: 'status.reblogged_by', defaultMessage: '{name} boosted' }, { name: status.getIn(['account', 'acct']) }); account = status.get('account'); status = status.get('reblog'); } if (status.get('media_attachments').size > 0) { if (this.props.muted) { media = ( <AttachmentList compact media={status.get('media_attachments')} /> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'audio') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Audio} loading={this.renderLoadingAudioPlayer} > {Component => ( <Component src={attachment.get('url')} alt={attachment.get('description')} duration={attachment.getIn(['meta', 'original', 'duration'], 0)} peaks={[0]} height={70} /> )} </Bundle> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={attachment.get('preview_url')} blurhash={attachment.get('blurhash')} src={attachment.get('url')} alt={attachment.get('description')} width={this.props.cachedMediaWidth} height={110} inline sensitive={status.get('sensitive')} onOpenVideo={this.handleOpenVideo} cacheWidth={this.props.cacheMediaWidth} visible={this.state.showMedia} onToggleVisibility={this.handleToggleMediaVisibility} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}> {Component => ( <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} cacheWidth={this.props.cacheMediaWidth} defaultWidth={this.props.cachedMediaWidth} visible={this.state.showMedia} onToggleVisibility={this.handleToggleMediaVisibility} /> )} </Bundle> ); } } else if (status.get('spoiler_text').length === 0 && status.get('card')) { media = ( <Card onOpenMedia={this.props.onOpenMedia} card={status.get('card')} compact cacheWidth={this.props.cacheMediaWidth} defaultWidth={this.props.cachedMediaWidth} /> ); } if (otherAccounts && otherAccounts.size > 0) { statusAvatar = <AvatarComposite accounts={otherAccounts} size={48} />; } else if (account === undefined || account === null) { statusAvatar = <Avatar account={status.get('account')} size={48} />; } else { statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />; } return ( <HotKeys handlers={handlers}> <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { 'status__wrapper-reply': !!status.get('in_reply_to_id'), read: unread === false, focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null} aria-label={textForScreenReader(intl, status, rebloggedByText)} ref={this.handleRef}> {prepend} <div className={classNames('status', `status-${status.get('visibility')}`, { 'status-reply': !!status.get('in_reply_to_id'), muted: this.props.muted, read: unread === false })} data-id={status.get('id')}> <div className='status__expand' onClick={this.handleExpandClick} role='presentation' /> <div className='status__info'> <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a> <a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name'> <div className='status__avatar'> {statusAvatar} </div> <DisplayName account={status.get('account')} others={otherAccounts} /> </a> </div> <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} collapsable /> {media} {showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) && ( <button className='status__content__read-more-button' onClick={this.handleClick}> <FormattedMessage id='status.show_thread' defaultMessage='Show thread' /> </button> )} <StatusActionBar status={status} account={account} {...other} /> </div> </div> </HotKeys> ); } }
src/svg-icons/image/filter-frames.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterFrames = (props) => ( <SvgIcon {...props}> <path d="M20 4h-4l-4-4-4 4H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H4V6h4.52l3.52-3.5L15.52 6H20v14zM18 8H6v10h12"/> </SvgIcon> ); ImageFilterFrames = pure(ImageFilterFrames); ImageFilterFrames.displayName = 'ImageFilterFrames'; export default ImageFilterFrames;
src/svg-icons/image/rotate-right.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageRotateRight = (props) => ( <SvgIcon {...props}> <path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"/> </SvgIcon> ); ImageRotateRight = pure(ImageRotateRight); ImageRotateRight.displayName = 'ImageRotateRight'; ImageRotateRight.muiName = 'SvgIcon'; export default ImageRotateRight;
Code/V1/src/src/Intro.js
neurotechuoft/MindType
import React, { Component } from 'react'; class Intro extends React.Component { render(){ return ( <div> <center> <p className="heading">What is MindType?</p> </center> <p className="text">MindType is a mind-controlled keyboard that lets you type letters, words, numbers and characters using your brain activity! </p> <center><p className="heading">How Does It Work?</p></center> <p className="text">Let's start with a thought experiment.</p> <p className="text">Imagine you have a bag of balls, which are all <span className="blueText">blue</span> except for one <span className="redText">red</span> ball.</p> <p className="text"><span className="redText">You want the red ball.</span></p> <p className="text">Now suppose I start randomly removing the balls. One by one, you see blue ball after blue ball removed from the bag until suddenly, after patiently waiting, you see the red ball emerge.</p> <p className="text">Because you knew what you were looking for but you didn't know when you'll see it exactly, the moment you saw the red ball finally removed, it triggered a neurological reaction detectable by measuring your brain activity.</p> <p className="text">This is known as the P300 oddball paradigm and it's the foundation for the keyboard's functionality.</p> <p className="text">The keyboard relies on the P300 mechanism by randomly flashing rows and columns of letters, symbols and numbers. When you see a row with the letter you want, but you don't know when it's going to happen exactly, it triggers the P300 reaction in your brain - and the same happens when a row with the letter is randomly flashed. Your EEG headset detects the specific change in your brain's electrical activity associated with the P300. When both a row and a column with a particular item of interest (such as the letter 'p') triggers this response, our code will type the letter on the screen. </p> <p className="text"> Now you know how it works. Let's practice using the keyboard!</p> <center> <button className="continueButton" onClick={this.props.introHandler}>Continue</button> </center> </div> ) } } export default Intro;
app/components/main/Footer.js
MarcinJarecki/React-js-Sticky-Notes
import React from 'react'; import {aFontFooter} from '../../styles'; var Footer = React.createClass({ render: function() { return ( <footer> <div className="container"> <div className="row-fluid"> <div className="span4"> <p>&copy;2016 &nbsp; <a style={aFontFooter} href="https://github.com/MarcinJarecki/">Marcin Jarecki</a> </p> </div> </div> </div> </footer> ); } }); module.exports = Footer;
docs/src/components/code.js
balloob/nuclear-js
import React from 'react' import { PrismCode } from 'react-prism' export default React.createClass({ render() { var languageClass = 'language-' + this.props.lang return ( <div className="highlighted-code"> <pre className={languageClass}> <PrismCode className={languageClass} async={false}> {this.props.children} </PrismCode> </pre> </div> ) } })
react-app/src/App.js
danieluy/www.danielsosa.uy
import React, { Component } from 'react'; import './App.css'; import NotificationsTray from './notifications-tray/NotificationsTray'; class App extends Component { constructor() { super(); this.state = { window_height: window.innerHeight, window_width: window.innerWidth, notification: null } } setStatusBarThemeColor(color_hex) { const metas = document.getElementsByTagName('meta'); for (let i = 0; i < metas.length; i++) { if (metas[i].name === 'theme-color' || metas[i].name === 'msapplication-navbutton-color' || metas[i].name === 'apple-mobile-web-app-status-bar-style') metas[i].content = color_hex || '#000000'; } } componentDidMount() { window.addEventListener('resize', () => { this.setState({ window_height: window.innerHeight, window_width: window.innerWidth }) }); } createNotifitacion(notif) { this.setState({ notification: notif }, () => { this.setState({ notification: null }) }) } render() { const children_with_props = React.cloneElement(this.props.children, { setStatusBarThemeColor: this.setStatusBarThemeColor, window_height: this.state.window_height, window_width: this.state.window_width, notify: this.createNotifitacion.bind(this) }) return ( <div> {children_with_props} <NotificationsTray notification={this.state.notification} /> </div> ); } } export default App;
src/react/LogMonitorButton.js
jackielii/redux-devtools
import React from 'react'; import brighten from '../utils/brighten'; const styles = { base: { cursor: 'pointer', fontWeight: 'bold', borderRadius: 3, padding: 4, marginLeft: 3, marginRight: 3, marginTop: 5, marginBottom: 5, flexGrow: 1, display: 'inline-block', fontSize: '0.8em', color: 'white', textDecoration: 'none' } }; export default class LogMonitorButton extends React.Component { constructor(props) { super(props); this.state = { hovered: false, active: false }; } handleMouseEnter() { this.setState({ hovered: true }); } handleMouseLeave() { this.setState({ hovered: false }); } handleMouseDown() { this.setState({ active: true }); } handleMouseUp() { this.setState({ active: false }); } onClick() { if (!this.props.enabled) { return; } if (this.props.onClick) { this.props.onClick(); } } render() { let style = { ...styles.base, backgroundColor: this.props.theme.base02 }; if (this.props.enabled && this.state.hovered) { style = { ...style, backgroundColor: brighten(this.props.theme.base02, 0.2) }; } if (!this.props.enabled) { style = { ...style, opacity: 0.2, cursor: 'text', backgroundColor: 'transparent' }; } return ( <a onMouseEnter={::this.handleMouseEnter} onMouseLeave={::this.handleMouseLeave} onMouseDown={::this.handleMouseDown} onMouseUp={::this.handleMouseUp} style={style} onClick={::this.onClick}> {this.props.children} </a> ); } }
ui/js/components/description.js
FujiHaruka/shakyo-programming
import React from 'react' import classnames from 'classnames' const DesctiptionSection = React.createClass({ render () { return ( <section className='section'> <h2 className={classnames('section-title', 'app-theme-dark-color')}>■ 遊び方</h2> <div className='description-section-body'> <ul> <li> 写経するボタンで開始です。 </li> <li> 入力モードを「半角入力」にしてください。 </li> <li> コメント、行頭の空白、改行は写経の文字に含まれません。 </li> <li> たくさん写経して徳を積みましょう。 </li> </ul> </div> </section> ) } }) export default DesctiptionSection
react-flux-mui/js/material-ui/src/svg-icons/action/cached.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCached = (props) => ( <SvgIcon {...props}> <path d="M19 8l-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.43 20 12 20c4.42 0 8-3.58 8-8h3l-4-4zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.57 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4H6z"/> </SvgIcon> ); ActionCached = pure(ActionCached); ActionCached.displayName = 'ActionCached'; ActionCached.muiName = 'SvgIcon'; export default ActionCached;
app/javascript/mastodon/components/column_header.js
pfm-eyesightjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { FormattedMessage, injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ show: { id: 'column_header.show_settings', defaultMessage: 'Show settings' }, hide: { id: 'column_header.hide_settings', defaultMessage: 'Hide settings' }, moveLeft: { id: 'column_header.moveLeft_settings', defaultMessage: 'Move column to the left' }, moveRight: { id: 'column_header.moveRight_settings', defaultMessage: 'Move column to the right' }, }); @injectIntl export default class ColumnHeader extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, title: PropTypes.node.isRequired, icon: PropTypes.string.isRequired, active: PropTypes.bool, multiColumn: PropTypes.bool, focusable: PropTypes.bool, showBackButton: PropTypes.bool, children: PropTypes.node, pinned: PropTypes.bool, onPin: PropTypes.func, onMove: PropTypes.func, onClick: PropTypes.func, }; static defaultProps = { focusable: true, } state = { collapsed: true, animating: false, }; handleToggleClick = (e) => { e.stopPropagation(); this.setState({ collapsed: !this.state.collapsed, animating: true }); } handleTitleClick = () => { this.props.onClick(); } handleMoveLeft = () => { this.props.onMove(-1); } handleMoveRight = () => { this.props.onMove(1); } handleBackClick = () => { if (window.history && window.history.length === 1) this.context.router.history.push('/'); else this.context.router.history.goBack(); } handleTransitionEnd = () => { this.setState({ animating: false }); } render () { const { title, icon, active, children, pinned, onPin, multiColumn, focusable, showBackButton, intl: { formatMessage } } = this.props; const { collapsed, animating } = this.state; const wrapperClassName = classNames('column-header__wrapper', { 'active': active, }); const buttonClassName = classNames('column-header', { 'active': active, }); const collapsibleClassName = classNames('column-header__collapsible', { 'collapsed': collapsed, 'animating': animating, }); const collapsibleButtonClassName = classNames('column-header__button', { 'active': !collapsed, }); let extraContent, pinButton, moveButtons, backButton, collapseButton; if (children) { extraContent = ( <div key='extra-content' className='column-header__collapsible__extra'> {children} </div> ); } if (multiColumn && pinned) { pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={onPin}><i className='fa fa fa-times' /> <FormattedMessage id='column_header.unpin' defaultMessage='Unpin' /></button>; moveButtons = ( <div key='move-buttons' className='column-header__setting-arrows'> <button title={formatMessage(messages.moveLeft)} aria-label={formatMessage(messages.moveLeft)} className='text-btn column-header__setting-btn' onClick={this.handleMoveLeft}><i className='fa fa-chevron-left' /></button> <button title={formatMessage(messages.moveRight)} aria-label={formatMessage(messages.moveRight)} className='text-btn column-header__setting-btn' onClick={this.handleMoveRight}><i className='fa fa-chevron-right' /></button> </div> ); } else if (multiColumn) { pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={onPin}><i className='fa fa fa-plus' /> <FormattedMessage id='column_header.pin' defaultMessage='Pin' /></button>; } if (!pinned && (multiColumn || showBackButton)) { backButton = ( <button onClick={this.handleBackClick} className='column-header__back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); } const collapsedContent = [ extraContent, ]; if (multiColumn) { collapsedContent.push(moveButtons); collapsedContent.push(pinButton); } if (children || multiColumn) { collapseButton = <button className={collapsibleButtonClassName} aria-label={formatMessage(collapsed ? messages.show : messages.hide)} aria-pressed={collapsed ? 'false' : 'true'} onClick={this.handleToggleClick}><i className='fa fa-sliders' /></button>; } return ( <div className={wrapperClassName}> <h1 tabIndex={focusable && '0'} role='button' className={buttonClassName} aria-label={title} onClick={this.handleTitleClick}> <i className={`fa fa-fw fa-${icon} column-header__icon`} /> {title} <div className='column-header__buttons'> {backButton} {collapseButton} </div> </h1> <div className={collapsibleClassName} tabIndex={collapsed && -1} onTransitionEnd={this.handleTransitionEnd}> <div className='column-header__collapsible-inner'> {(!collapsed || animating) && collapsedContent} </div> </div> </div> ); } }
docs/src/index.js
Trioxis/immutable-react-form
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import s from './style.css'; import ExampleOne from './examples/one'; import ExampleOneIndexCode from '!raw-loader!./examples/one/index.js'; import ExampleOneFormCode from '!raw-loader!./examples/one/Form.js'; import ExampleOneTextFieldCode from '!raw-loader!./examples/one/TextField.js'; import ExampleOneValidationCode from '!raw-loader!./examples/one/validation.js'; import writeUpOverview from './writeUp/overview.md'; import writeUpExampleOverview from './writeUp/exampleOneOverview.md'; import writeUpExampleIndex from './writeUp/exampleOneIndex.md'; import writeUpExampleForm from './writeUp/exampleOneForm.md'; import writeUpExampleCustomFieldComponents from './writeUp/exampleCustomFieldComponents.md'; import writeUpValidation from './writeUp/validation.md'; injectTapEventPlugin(); function Docs(props){ return <MuiThemeProvider> <div className={s.page}> <WriteUp className={s.topWriteUp} content={writeUpOverview}/> <SideBySide left={<WriteUp content={writeUpExampleOverview}/>} right={<ExampleOne />} /> <SideBySide left={<WriteUp content={writeUpExampleIndex}/>} right={<pre>{ExampleOneIndexCode}</pre>} code /> <SideBySide left={<WriteUp content={writeUpExampleForm}/>} right={<pre>{ExampleOneFormCode}</pre>} code /> <SideBySide left={<WriteUp content={writeUpExampleCustomFieldComponents}/>} right={<pre>{ExampleOneTextFieldCode}</pre>} code /> <SideBySide left={<WriteUp content={writeUpValidation}/>} right={<pre>{ExampleOneValidationCode}</pre>} code /> </div> </MuiThemeProvider> } ReactDOM.render( <Docs />, document.getElementById('root') ); function SideBySide(props){ return <div className={s.sbsWrapper}> <div className={s.sbsColumn}> {props.left} </div> <div className={`${s.sbsColumn} ${!props.code || s.codeWrapper}`}> {props.right} </div> </div> } function Code(props){ return <div className={s.codeWrapper}> <pre>{props.children}</pre> </div> } function WriteUp(props){ return <div className={s.writeUp+' '+props.className} dangerouslySetInnerHTML={{__html:props.content}} /> }
src/App.js
TonyChol/tinyurl-react
// Vendor import React, { Component } from 'react'; import './App.css'; // Components import Header from './components/Header' import Footer from './components/Footer' // Containers import URlFormWrapper from './containers/UrlFormWrapper' class App extends Component { render() { return ( <div className="App" onSubmitCapture={this.onSubmitCapturing}> <Header/> <URlFormWrapper></URlFormWrapper> <Footer/> </div> ); } } export default App;
src/index.js
clhenrick/nyc-crash-mapper
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import { Provider } from 'react-redux'; import { calculateResponsiveState } from 'redux-responsive'; import { syncHistoryWithStore } from 'react-router-redux'; import debounce from 'lodash/debounce'; import makeStore from './store'; import { makeDefaultState } from './constants/api'; import AppConnected from './containers/AppConnected'; import '../scss/main.scss'; const state = makeDefaultState(); const store = makeStore(state); const history = syncHistoryWithStore(hashHistory, store); // fire redux-responsive on window resize event window.addEventListener('resize', debounce(() => store.dispatch(calculateResponsiveState(window)), 250)); render( <Provider store={store}> <Router history={history}> <Route path="/" component={AppConnected}> <IndexRoute component={AppConnected} /> </Route> <Route path="*" component={AppConnected} /> </Router> </Provider>, document.getElementById('root') );
src/svg-icons/image/brightness-7.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness7 = (props) => ( <SvgIcon {...props}> <path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/> </SvgIcon> ); ImageBrightness7 = pure(ImageBrightness7); ImageBrightness7.displayName = 'ImageBrightness7'; ImageBrightness7.muiName = 'SvgIcon'; export default ImageBrightness7;
app/index.js
animalphase/bramble
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from './containers/Root'; import { configureStore, history } from './store/configureStore'; // import './app.global.css'; import './app.global.scss'; const store = configureStore(); const listenToPresses = e => { console.log(e); store.dispatch({ type: 'HOTKEY', key: e.key, withMeta: e.metaKey, withShift: e.shiftKey, withCtrl: e.ctrlKey }); // e.stopPropagation(); // TODO: USE ELECTRON ACCELERATORS }; document.addEventListener('keydown', listenToPresses); document.addEventListener('mousedown', event => { store.dispatch({ type: 'MOUSE_DOWN', data: { target: event.target, button: event.button, mouseX: event.clientX, mouseY: event.clientY } }); }); document.addEventListener('click', event => { store.dispatch({ type: 'MOUSE_CLICK', data: { target: event.target, button: event.button, mouseX: event.clientX, mouseY: event.clientY } }); }); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('./containers/Root', () => { const NextRoot = require('./containers/Root'); // eslint-disable-line global-require render( <AppContainer> <NextRoot store={store} history={history} /> </AppContainer>, document.getElementById('root') ); }); }
web-app/src/components/SignUpAfterOnBoarding/index.js
oSoc17/code9000
import React, { Component } from 'react'; import SignUp from '../SignUp'; import Header from '../Header'; import classNames from '../../utils/classNames'; import './SignUpAfterOnBoarding.css'; import bertVerkijkerIcon from '../../theme/icons/bert_verkijker.svg'; class SignUpAfterOnBoarding extends Component { constructor(...props) { super(...props); this.state = { showContent: false, }; } componentDidMount() { setTimeout(() => { this.setState({ showContent: true }); }, 2500); } render() { const { showContent } = this.state; return ( <div> <div className={classNames('SignUpAfterOnBoarding__Content', showContent && 'SignUpAfterOnBoarding__Content--visible')}> <SignUp /> </div> <div className={classNames('App', 'SignUpAfterOnBoarding__Overlay', showContent && 'SignUpAfterOnBoarding__Overlay--hidden')}> <div className="SignUpAfterOnBoarding__Header"> <Header /> </div> <div className="SignUpAfterOnBoarding__Text"> Awesome!<br /> Let&apos;s get you signed up! </div> <img src={bertVerkijkerIcon} className="SignUpAfterOnBoarding__Bert" alt="Bert with a verkijker" /> </div> </div> ); } } export default SignUpAfterOnBoarding;
docs/getting-started-chart/components/Aggregates.js
reimagined/resolve
import React from 'react' const Aggregates = ({ selected, onClick }) => ( <g className="box-inner" data-selected={selected} onClick={onClick}> <path className="box" d="M140 89H400V122H140V89Z" /> <path className="caption" d="M227.339 111L228.408 107.92H232.953L234.016 111H235.879L231.692 99.3636H229.663L225.476 111H227.339ZM228.919 106.443L230.635 101.477H230.726L232.442 106.443H228.919ZM240.942 114.455C243.163 114.455 244.879 113.438 244.879 111.193V102.273H243.214V103.688H243.089C242.788 103.148 242.186 102.159 240.561 102.159C238.453 102.159 236.902 103.824 236.902 106.602C236.902 109.386 238.487 110.869 240.55 110.869C242.152 110.869 242.771 109.966 243.078 109.409H243.186V111.125C243.186 112.494 242.249 113.085 240.959 113.085C239.544 113.085 238.993 112.375 238.692 111.875L237.232 112.477C237.692 113.545 238.857 114.455 240.942 114.455ZM240.925 109.46C239.408 109.46 238.618 108.295 238.618 106.58C238.618 104.903 239.391 103.602 240.925 103.602C242.408 103.602 243.203 104.812 243.203 106.58C243.203 108.381 242.391 109.46 240.925 109.46ZM250.817 114.455C253.038 114.455 254.754 113.438 254.754 111.193V102.273H253.089V103.688H252.964C252.663 103.148 252.061 102.159 250.436 102.159C248.328 102.159 246.777 103.824 246.777 106.602C246.777 109.386 248.362 110.869 250.425 110.869C252.027 110.869 252.646 109.966 252.953 109.409H253.061V111.125C253.061 112.494 252.124 113.085 250.834 113.085C249.419 113.085 248.868 112.375 248.567 111.875L247.107 112.477C247.567 113.545 248.732 114.455 250.817 114.455ZM250.8 109.46C249.283 109.46 248.493 108.295 248.493 106.58C248.493 104.903 249.266 103.602 250.8 103.602C252.283 103.602 253.078 104.812 253.078 106.58C253.078 108.381 252.266 109.46 250.8 109.46ZM257.033 111H258.732V105.67C258.732 104.528 259.612 103.705 260.817 103.705C261.169 103.705 261.567 103.767 261.703 103.807V102.182C261.533 102.159 261.197 102.142 260.982 102.142C259.959 102.142 259.084 102.722 258.766 103.659H258.675V102.273H257.033V111ZM266.622 111.176C268.526 111.176 269.872 110.239 270.259 108.818L268.651 108.528C268.344 109.352 267.605 109.773 266.639 109.773C265.185 109.773 264.207 108.83 264.162 107.148H270.366V106.545C270.366 103.392 268.48 102.159 266.503 102.159C264.071 102.159 262.469 104.011 262.469 106.693C262.469 109.403 264.048 111.176 266.622 111.176ZM264.168 105.875C264.236 104.636 265.134 103.562 266.514 103.562C267.832 103.562 268.696 104.54 268.702 105.875H264.168ZM275.911 114.455C278.132 114.455 279.848 113.438 279.848 111.193V102.273H278.183V103.688H278.058C277.757 103.148 277.155 102.159 275.53 102.159C273.422 102.159 271.871 103.824 271.871 106.602C271.871 109.386 273.456 110.869 275.518 110.869C277.121 110.869 277.74 109.966 278.047 109.409H278.155V111.125C278.155 112.494 277.217 113.085 275.928 113.085C274.513 113.085 273.962 112.375 273.661 111.875L272.2 112.477C272.661 113.545 273.825 114.455 275.911 114.455ZM275.893 109.46C274.376 109.46 273.587 108.295 273.587 106.58C273.587 104.903 274.359 103.602 275.893 103.602C277.376 103.602 278.172 104.812 278.172 106.58C278.172 108.381 277.359 109.46 275.893 109.46ZM284.666 111.193C286.109 111.193 286.922 110.46 287.246 109.807H287.314V111H288.973V105.205C288.973 102.665 286.973 102.159 285.587 102.159C284.007 102.159 282.553 102.795 281.984 104.386L283.581 104.75C283.831 104.131 284.467 103.534 285.609 103.534C286.706 103.534 287.268 104.108 287.268 105.097V105.136C287.268 105.756 286.632 105.744 285.064 105.926C283.411 106.119 281.717 106.551 281.717 108.534C281.717 110.25 283.007 111.193 284.666 111.193ZM285.036 109.83C284.075 109.83 283.382 109.398 283.382 108.557C283.382 107.648 284.189 107.324 285.172 107.193C285.723 107.119 287.03 106.972 287.274 106.727V107.852C287.274 108.886 286.45 109.83 285.036 109.83ZM295.31 102.273H293.52V100.182H291.821V102.273H290.543V103.636H291.821V108.79C291.815 110.375 293.026 111.142 294.366 111.114C294.906 111.108 295.27 111.006 295.469 110.932L295.162 109.528C295.048 109.551 294.838 109.602 294.565 109.602C294.014 109.602 293.52 109.42 293.52 108.438V103.636H295.31V102.273ZM300.857 111.176C302.76 111.176 304.107 110.239 304.493 108.818L302.885 108.528C302.578 109.352 301.839 109.773 300.874 109.773C299.419 109.773 298.442 108.83 298.396 107.148H304.601V106.545C304.601 103.392 302.714 102.159 300.737 102.159C298.305 102.159 296.703 104.011 296.703 106.693C296.703 109.403 298.283 111.176 300.857 111.176ZM298.402 105.875C298.47 104.636 299.368 103.562 300.749 103.562C302.067 103.562 302.93 104.54 302.936 105.875H298.402ZM313.026 104.403C312.673 103.045 311.611 102.159 309.724 102.159C307.753 102.159 306.355 103.199 306.355 104.744C306.355 105.983 307.105 106.807 308.741 107.17L310.219 107.494C311.06 107.682 311.452 108.057 311.452 108.602C311.452 109.278 310.73 109.807 309.616 109.807C308.599 109.807 307.946 109.369 307.741 108.511L306.099 108.761C306.384 110.307 307.668 111.176 309.628 111.176C311.736 111.176 313.196 110.057 313.196 108.477C313.196 107.244 312.412 106.483 310.81 106.114L309.423 105.795C308.463 105.568 308.048 105.244 308.054 104.653C308.048 103.983 308.776 103.506 309.741 103.506C310.798 103.506 311.287 104.091 311.486 104.676L313.026 104.403Z" /> </g> ) export default Aggregates
app/javascript/mastodon/features/notifications/components/notification.js
d6rkaiz/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import { injectIntl, FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { HotKeys } from 'react-hotkeys'; import Icon from 'mastodon/components/icon'; const notificationForScreenReader = (intl, message, timestamp) => { const output = [message]; output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' })); return output.join(', '); }; export default @injectIntl class Notification extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { notification: ImmutablePropTypes.map.isRequired, hidden: PropTypes.bool, onMoveUp: PropTypes.func.isRequired, onMoveDown: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onFavourite: PropTypes.func.isRequired, onReblog: PropTypes.func.isRequired, onToggleHidden: PropTypes.func.isRequired, status: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, getScrollPosition: PropTypes.func, updateScrollBottom: PropTypes.func, cacheMediaWidth: PropTypes.func, cachedMediaWidth: PropTypes.number, }; handleMoveUp = () => { const { notification, onMoveUp } = this.props; onMoveUp(notification.get('id')); } handleMoveDown = () => { const { notification, onMoveDown } = this.props; onMoveDown(notification.get('id')); } handleOpen = () => { const { notification } = this.props; if (notification.get('status')) { this.context.router.history.push(`/statuses/${notification.get('status')}`); } else { this.handleOpenProfile(); } } handleOpenProfile = () => { const { notification } = this.props; this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`); } handleMention = e => { e.preventDefault(); const { notification, onMention } = this.props; onMention(notification.get('account'), this.context.router.history); } handleHotkeyFavourite = () => { const { status } = this.props; if (status) this.props.onFavourite(status); } handleHotkeyBoost = e => { const { status } = this.props; if (status) this.props.onReblog(status, e); } handleHotkeyToggleHidden = () => { const { status } = this.props; if (status) this.props.onToggleHidden(status); } getHandlers () { return { reply: this.handleMention, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleMention, open: this.handleOpen, openProfile: this.handleOpenProfile, moveUp: this.handleMoveUp, moveDown: this.handleMoveDown, toggleHidden: this.handleHotkeyToggleHidden, }; } renderFollow (notification, account, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-follow focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow', defaultMessage: '{name} followed you' }, { name: account.get('acct') }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='user-plus' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </span> </div> <AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} /> </div> </HotKeys> ); } renderMention (notification) { return ( <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} onMoveDown={this.handleMoveDown} onMoveUp={this.handleMoveUp} contextType='notifications' getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> ); } renderFavourite (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-favourite focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.favourite', defaultMessage: '{name} favourited your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='star' className='star-icon' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } renderReblog (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-reblog focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.reblog', defaultMessage: '{name} boosted your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='retweet' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } renderPoll (notification) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-poll focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.poll', defaultMessage: 'A poll you have voted in has ended' }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='tasks' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.poll' defaultMessage='A poll you have voted in has ended' /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayNameHtml = { __html: account.get('display_name_html') }; const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>; switch(notification.get('type')) { case 'follow': return this.renderFollow(notification, account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); case 'poll': return this.renderPoll(notification); } return null; } }
reflux-app/components/Toolbox.js
Orientsoft/borgnix-web-ide
import React from 'react' import ToolboxStore from '../stores/ToolboxStore' import Nav from './toolbox/Nav' import Project from './toolbox/Project' import Library from './toolbox/Library' import ProjectActions from '../actions/ProjectActions' class Toolbox extends React.Component { constructor(props) { super(props) this.state = { activeTool: '' } } componentDidMount() { this.unsubscribe = ToolboxStore.listen(function(state) { this.setState(state) }.bind(this)) } componentWillUnmount() { if (_.isFunction(this.unsubscribe)) this.unsubscribe() } render() { let panel; if (this.state.activeTool == 'Library') panel = <Library /> else if (this.state.activeTool == 'Project') panel = <Project /> else panel = <div /> return ( <div className='row'> <div className='col-xs-2'> <Nav /> </div> <div className='col-xs-10'> {panel} </div> </div> ) } } Toolbox.propTypes = { } Toolbox.defaultProps = { } export default Toolbox
actor-apps/app-web/src/app/components/Deactivated.react.js
KitoHo/actor-platform
import React from 'react'; class Deactivated extends React.Component { render() { return ( <div className="deactivated row center-xs middle-xs"> <div className="deactivated__window"> <h2>Tab deactivated</h2> <p> Oops, you have opened another tab with Actor, so we had to deactivate this one to prevent some dangerous things happening. </p> </div> </div> ); } } export default Deactivated;
admin/client/App/shared/Kbd.js
ratecity/keystone
import React from 'react'; import { css } from 'glamor'; import theme from '../../theme'; import { darken, lighten } from '../../utils/color'; function Kbd ({ className, ...props }) { props.className = css(classes.kbd); return <kbd {...props} />; }; const classes = { kbd: { backgroundColor: theme.color.body, borderRadius: 3, border: `1px solid #ccc`, borderBottomColor: darken('#ccc', 4), borderTopColor: lighten('#ccc', 4), boxShadow: `0 1px 1px rgba(0, 0, 0, 0.12), 0 2px 0 0 rgba(255, 255, 255, 0.7) inset`, display: 'inline-block', fontFamily: 'Consolas, "Liberation Mono", Courier, monospace', fontSize: '0.85em', fontWeight: 700, lineHeight: 'inherit', padding: '1px 4px', whiteSpace: 'nowrap', // little hack to tweak "visual-middle" alignment position: 'relative', top: -1, }, }; module.exports = Kbd;
app/containers/tutorial/sixth.js
DeividasK/tgoals
import React from 'react' import SimpleList from 'components/lists/simple' import { updateStep, updateHeading, updateActions } from '../../actions/TutorialActions' import { FormattedMessage, defineMessages, injectIntl } from 'react-intl' const content = defineMessages({ title: { id: 'app.tutorial.step6.title', defaultMessage: 'Deadlines', } }) class TutorialStep6 extends React.Component { constructor (props) { super(props) this.state = { filters: [ function(item) { return item.primary === false } ], formItem: { type: 'date', value: 'deadline' } } } componentWillMount () { updateStep(6) updateHeading(this.props.intl.formatMessage(content.title), "calendar") updateActions(6) } render () { return ( <div> <p><FormattedMessage id='app.tutorial.step6.introduction' defaultMessage="Set a date when you plan to achieve your goal." /></p> <SimpleList items={ this.props.goals } filters={ this.state.filters } formItem={ this.state.formItem } /> </div> ) } } export default injectIntl(TutorialStep6)
docs/app/Examples/elements/Label/Content/LabelExampleLinkDetail.js
ben174/Semantic-UI-React
import React from 'react' import { Icon, Label } from 'semantic-ui-react' const LabelExampleLinkDetail = () => ( <Label> <Icon name='mail' /> 23 <Label.Detail>View Mail</Label.Detail> </Label> ) export default LabelExampleLinkDetail
src/svg-icons/editor/highlight.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorHighlight = (props) => ( <SvgIcon {...props}> <path d="M6 14l3 3v5h6v-5l3-3V9H6zm5-12h2v3h-2zM3.5 5.875L4.914 4.46l2.12 2.122L5.62 7.997zm13.46.71l2.123-2.12 1.414 1.414L18.375 8z"/> </SvgIcon> ); EditorHighlight = pure(EditorHighlight); EditorHighlight.displayName = 'EditorHighlight'; EditorHighlight.muiName = 'SvgIcon'; export default EditorHighlight;
client/components/ui/validated-date-input.js
jankeromnes/kresus
import React from 'react'; import PropTypes from 'prop-types'; import DatePicker from './date-picker'; // A validated date input is form group for a date picker, with a special hint // next to the date picker showing whether the date is valid or not. class ValidatedDateInput extends React.Component { constructor(props) { super(props); this.state = { valid: false }; this.refInput = node => { this.input = node; }; this.handleSelect = this.handleSelect.bind(this); } clear() { this.input.clear(); this.handleSelect(null); } handleSelect(date) { let hasDate = !!date; this.setState({ valid: hasDate }, () => { this.props.onChange(hasDate ? date : null); }); } render() { let iconClass = this.state.valid ? 'fa-check' : 'fa-times'; iconClass = `fa ${iconClass} form-control-feedback`; return ( <div className="form-group has-feedback"> <label className="control-label" htmlFor={ this.props.inputID } > { this.props.label } </label> <DatePicker id={ this.props.inputID } required={ true } onSelect={ this.handleSelect } ref={ this.refInput } /> <span className={ iconClass } aria-hidden="true" /> </div> ); } } ValidatedDateInput.propTypes = { // Callback receiving the validated date input. onChange: PropTypes.func.isRequired, // CSS id for the date picker. inputID: PropTypes.string.isRequired, // Description of the date picker (shown to the user). label: PropTypes.string.isRequired }; export default ValidatedDateInput;
app/private/indexerApp/imports/ui/components/PublicNavigation.js
ericvrp/GameCollie
import React from 'react'; import { LinkContainer } from 'react-router-bootstrap'; import { Nav, NavItem } from 'react-bootstrap'; const PublicNavigation = () => ( <Nav pullRight> <LinkContainer to="signup"> <NavItem eventKey={ 1 } href="/signup">Sign Up</NavItem> </LinkContainer> <LinkContainer to="login"> <NavItem eventKey={ 2 } href="/login">Log In</NavItem> </LinkContainer> </Nav> ); export default PublicNavigation;
src/common/StatusLabel/ActiveStatusLabel.js
Syncano/syncano-dashboard
import React from 'react'; import { FontIcon } from 'material-ui'; import { colors as Colors } from 'material-ui/styles'; const StatusLabel = ({ style }) => ( <FontIcon style={style} className="synicon-check" color={Colors.green500} /> ); export default StatusLabel;
src/index.js
FreeCodeCampGuam/fccg-website
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
docs/src/examples/elements/Button/Variations/ButtonExampleVerticallyAttachedGroup.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Segment } from 'semantic-ui-react' const ButtonExampleVerticallyAttachedGroup = () => ( <div> <Button.Group attached='top'> <Button>One</Button> <Button>Two</Button> </Button.Group> <Segment attached> <img src='/images/wireframe/paragraph.png' /> </Segment> <Button.Group attached='bottom'> <Button>One</Button> <Button>Two</Button> </Button.Group> </div> ) export default ButtonExampleVerticallyAttachedGroup
actor-apps/app-web/src/app/index.js
WangCrystal/actor-platform
import polyfills from 'utils/polyfills'; // eslint-disable-line import RouterContainer from 'utils/RouterContainer'; import crosstab from 'crosstab'; import React from 'react'; import Router from 'react-router'; import Raven from 'utils/Raven'; // eslint-disable-line import isMobile from 'utils/IsMobile'; import ReactMixin from 'react-mixin'; import Intl from 'intl'; // eslint-disable-line import LocaleData from 'intl/locale-data/jsonp/en-US'; // eslint-disable-line import { IntlMixin } from 'react-intl'; import injectTapEventPlugin from 'react-tap-event-plugin'; import LoginStore from 'stores/LoginStore'; import PreferencesStore from 'stores/PreferencesStore'; import LoginActionCreators from 'actions/LoginActionCreators'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import Deactivated from 'components/Deactivated.react'; import Login from 'components/Login.react'; import Main from 'components/Main.react'; import JoinGroup from 'components/JoinGroup.react'; import Install from 'components/Install.react'; //import AppCache from 'utils/AppCache'; // eslint-disable-line import Pace from 'pace'; Pace.start({ ajax: false, restartOnRequestAfter: false, restartOnPushState: false }); const DefaultRoute = Router.DefaultRoute; const Route = Router.Route; const RouteHandler = Router.RouteHandler; const ActorInitEvent = 'concurrentActorInit'; if (crosstab.supported) { crosstab.on(ActorInitEvent, (msg) => { if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') { window.location.assign('#/deactivated'); window.location.reload(); } }); } // Check for mobile device, and force users to install native apps. if (isMobile() && window.location.hash !== '#/install') { window.location.assign('#/install'); document.body.classList.add('overflow'); } else if (window.location.hash === '#/install') { window.location.assign('/'); } @ReactMixin.decorate(IntlMixin) class App extends React.Component { render() { return <RouteHandler/>; } } // Internationalisation let intlData; PreferencesStore.addChangeListener(() => { intlData = PreferencesStore.languageData; }); PreferencesActionCreators.load(); const initReact = () => { if (window.location.hash !== '#/deactivated') { if (crosstab.supported) { crosstab.broadcast(ActorInitEvent, {}); } if (location.pathname === '/app/index.html') { window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']); } else { window.messenger = new window.actor.ActorApp(); } } const routes = ( <Route handler={App} name="app" path="/"> <Route handler={Main} name="main" path="/im/:id"/> <Route handler={JoinGroup} name="join" path="/join/:token"/> <Route handler={Login} name="login" path="/auth"/> <Route handler={Deactivated} name="deactivated" path="/deactivated"/> <Route handler={Install} name="install" path="/install"/> <DefaultRoute handler={Main}/> </Route> ); const router = Router.create(routes, Router.HashLocation); RouterContainer.set(router); router.run((Root) => { injectTapEventPlugin(); React.render(<Root {...intlData}/>, document.getElementById('actor-web-app')); }); if (window.location.hash !== '#/deactivated') { if (LoginStore.isLoggedIn()) { LoginActionCreators.setLoggedIn(router, {redirect: false}); } } }; window.jsAppLoaded = () => { setTimeout(initReact, 0); };
src/Thumbnail.js
xsistens/react-bootstrap
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const Thumbnail = React.createClass({ mixins: [BootstrapMixin], propTypes: { alt: React.PropTypes.string, href: React.PropTypes.string, src: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'thumbnail' }; }, render() { let classes = this.getBsClassSet(); if(this.props.href) { return ( <SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </SafeAnchor> ); } else { if(this.props.children) { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> <div className="caption"> {this.props.children} </div> </div> ); } else { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </div> ); } } } }); export default Thumbnail;
src/CircularMeter.js
ayonghosh/circle-chart-demo
/* React component to render an animated circular meter. Simply pass in the value, title and CSS color code to the component, e.g., CircularMeter val={ 58 } title={ "Progress" } color={ "#000" } Tested on Firefox and Chrome. Implemented using SVG with CSS transition: https://www.smashingmagazine.com/2015/07/designing-simple-pie-charts-with-css Text animation uses JavaScript. */ import React from 'react'; import styles from './css/chart.less'; const FPS = 60; // requestAnimationFrame frames per second const CircularMeter = React.createClass({ initialState() { return { textProgress: 0, // The current animated text value tick: 0, // The current tick of the animation clock val: 0 // The value of the meter } }, getInitialState() { return this.initialState(); }, animate() { const textPercentProgress = Math.min(Math.round(this.textAnimSpeedFactor * this.state.tick), this.props.val); this.setState({ textProgress: textPercentProgress, tick: this.state.tick + 1, val: this.props.val }); this.startAnim(); }, startAnim() { this.ticker = requestAnimationFrame(this.animate); }, stopAnim() { cancelAnimationFrame(this.ticker); this.setState({ textProgress: this.props.val }); }, componentWillReceiveProps(nextProps) { if (nextProps.val !== this.props.val) { this.setState(this.initialState()); this.startAnim(); } }, componentDidMount() { this.textAnimSpeedFactor = this.props.val / FPS; this.startAnim(); }, render () { return ( <div class="circular-chart"> <svg viewBox="0 0 40 40"> <circle r="20" cx="20" cy="20" stroke={ this.props.color } fill="none" /> <circle r="16" cx="20" cy="20" class="pie" strokeDasharray={ this.state.val + ' 100' } stroke={ this.props.color } onTransitionEnd={ this.stopAnim }/> <circle r="14" cx="20" cy="20" class="inset" /> </svg> <div class="counter">{ Math.round(this.state.textProgress) + '%'}</div> <div class="title">{ this.props.title }</div> </div> ) } }); CircularMeter.propTypes = { val: React.PropTypes.number, title: React.PropTypes.string, color: React.PropTypes.string }; CircularMeter.defaultProps = { val: 0, title: '', color: 'blue' }; export default CircularMeter;
docs/src/examples/elements/Loader/States/LoaderExampleDisabled.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Loader, Image, Segment } from 'semantic-ui-react' const LoaderExampleDisabled = () => ( <Segment> <Loader disabled /> <Image src='/images/wireframe/short-paragraph.png' /> </Segment> ) export default LoaderExampleDisabled
src/components/button/BaseButton.js
edgemesh/emui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Paper } from '../../'; import { colors } from '../../utils/colors'; const KEYCODE = { ENTER: 13, SPACE: 32, TAB: 9 } export const BaseButton = (ComposedComponent, ref) => { return class extends Component { static displayName = 'BaseButton'; static propTypes = { // Configuration style: PropTypes.object, disabledStyle: PropTypes.object, disabled: PropTypes.bool, fullWidth: PropTypes.bool, hoverColor: PropTypes.string, // Events onClick: PropTypes.func, onBlur: PropTypes.func, onFocus: PropTypes.func }; tabPressed = false; // Events _onClick(e) { let { onClick } = this.props; if(this.tabPressed){ this.refs.composed.refs.ripple.endCenterRipple(); this.tabPressed = false; } if( onClick ) onClick(e); } _onFocus(e) { let { onFocus } = this.props; if( onFocus ) onFocus(e); } _onBlur(e) { let { onBlur } = this.props; if(this.tabPressed){ this.refs.composed.refs.ripple.endCenterRipple(); this.tabPressed = false; } if( onBlur ) onBlur(e); } _onKeyDown(e) { if (e.keyCode == KEYCODE.ENTER){ this._onClick(e); } } _onKeyUp(e) { if (e.keyCode == KEYCODE.SPACE){ this._onClick(e); } if (e.keyCode == KEYCODE.TAB){ this.tabPressed = true; this.refs.composed.refs.ripple.startCenterRipple(); } } // Render render() { let { style, disabled, fullWidth, hoverColor, disabledStyle } = this.props; let onClick = !disabled ? this._onClick.bind(this) : ()=>{}, onFocus = !disabled ? this._onFocus.bind(this) : ()=>{}, onBlur = !disabled ? this._onBlur.bind(this) : ()=>{}, onKeyDown = !disabled ? this._onKeyDown.bind(this) : ()=>{}, onKeyUp = !disabled ? this._onKeyUp.bind(this) : ()=>{}; let buttonStyles = [ fullWidth && styles.fullWidth, styles.button, !disabled && style, disabled && styles.disabled, disabled && styles.disabledStyle ]; let buttonProps = Object.assign({}, this.props, { disabled, onClick, onFocus, onBlur, onKeyUp, onKeyDown, buttonStyles }); return ( <ComposedComponent ref="composed" {...buttonProps}/> ); } } } export default BaseButton; const styles = { button: { backgroundColor: colors.grey300, padding: 10, border: 0, cursor: 'pointer', color: colors.grey700 }, disabled: { backgroundColor: colors.grey400, cursor: 'initial', color: colors.grey500 }, fullWidth: { width: '100%' } }
components/StoryPage.js
githubhaohao/DevNews
import React, { Component } from 'react'; import { Dimensions, Image, PixelRatio, StyleSheet, Text, View, TouchableOpacity, Platform, Share, } from 'react-native'; import GlobalStyle from './GlobalStyle.js'; import ParallaxScrollView from 'react-native-parallax-scroll-view'; import CommonItem from './CommonItem.js'; const PARALLAX_HEADER_HEIGHT = GlobalStyle.windowWidth * 4 / 3; const STICKY_HEADER_HEIGHT = 76; const GIT_HUB_URL = 'https://github.com/githubhaohao'; class StoryPage extends Component { constructor(props) { super(props); this.story = this.props.news; this.state = { }; } getParallaxRenderConfig() { let config = {}; let title = this.story.results.休息视频 ? this.story.results.休息视频[0].desc : 'Gank.io GithubHaohao'; let imgSrc = (typeof this.story.results.福利[0].url !== 'undefined') ? {uri:this.story.results.福利[0].url} : require('../images/logo.jpg'); config.renderBackground = () => ( <View key='background'> <Image source={imgSrc} style={{width:GlobalStyle.windowWidth,height:PARALLAX_HEADER_HEIGHT}}/> <View style={{ position: 'absolute', top: 0, width: GlobalStyle.windowWidth, backgroundColor: 'rgba(0,0,0,.4)', height: PARALLAX_HEADER_HEIGHT }}/> </View> ); config.renderForeground = () => ( <View key="parallax-header" style={styles.parallaxHeader}> <Text style={ styles.sectionSpeakerText }> {`${this.story.date}期`} </Text> <Text style={ styles.sectionTitleText }> {title} </Text> </View> ); config.renderStickyHeader = () => ( <View key="sticky-header" style={styles.stickySection}> <Text style={styles.stickySectionText}>{`${this.story.date}期`}</Text> </View> ); config.renderFixedHeader = () => ( <View key='fixed-header' style={styles.fixedSection}> <TouchableOpacity activeOpacity={0.5} onPress={() => this.props.navigator.pop()} style={styles.backWrapper} > <View style={styles.backIcon}></View> </TouchableOpacity> <TouchableOpacity activeOpacity={0.5} style={{alignItems:'center',justifyContent:'center'}} onPress={() => {this.shareMessage(title)}} > <Image source={require('../images/ic_share.png')} style={{width:24,height:24,marginRight:8,tintColor:'white'}}/> </TouchableOpacity> </View> ); return config; } render() { let renderConfig = this.getParallaxRenderConfig(); return ( <ParallaxScrollView contentBackgroundColor='#efefef' backgroundColor={GlobalStyle.themeColor} headerBackgroundColor="#333" stickyHeaderHeight={ STICKY_HEADER_HEIGHT } parallaxHeaderHeight={ PARALLAX_HEADER_HEIGHT } backgroundSpeed={10} {...renderConfig} > {this.getChildViews(this.story)} </ParallaxScrollView> ); } shareMessage(title) { Share.share({ title:'Developer News', message:title, }).then(result => {}) .catch((error) => {this.toast.show(error.toString())}); } getChildViews(newsData){ console.log(newsData); let views = []; for(let i = 0;i<newsData.category.length;i++){ views.push(<View key={i} style={styles.childView}> <Text style={styles.childTitle}>{newsData.category[i]}</Text> {this.getItems(newsData,newsData.category[i])} </View>) } return views; } getItems(newsData,category){ let child = []; let data = newsData.results[category]; for(let i = 0;i<data.length;i++){ let item = data[i]; //console.log('[item]',item);item._id child.push( <TouchableOpacity activeOpacity={0.3} onPress={() => { this.props.navigator.push({ name:'detail', url:item.url, title:item.desc, id:item._id, }); }} style={styles.itemView} key={i}> <Text style={styles.itemTitle}><Text style={{fontSize:14,color:'red'}}>&hearts;</Text> {item.desc} ( {item.who} )</Text> </TouchableOpacity>); } return child; } } const styles = StyleSheet.create({ container: { flex: 1, }, childView:{ backgroundColor:'white', margin:8, padding:15, borderRadius:3, flex:1, }, childTitle:{ fontSize:18, color:'orange', }, itemView:{ marginTop:10, }, itemTitle:{ fontSize:14, marginLeft:15, color:GlobalStyle.themeColor, }, parallaxHeader: { alignItems: 'center', flex: 1, flexDirection: 'column', paddingTop: GlobalStyle.windowWidth, }, sectionSpeakerText: { color: 'white', fontSize: 24, paddingVertical: 5, }, sectionTitleText: { color: 'white', fontSize: 16, marginLeft: 10, marginRight: 10, }, stickySection: { height: STICKY_HEADER_HEIGHT, justifyContent: 'center', paddingTop: 20, alignItems: 'center', }, stickySectionText: { color: 'white', fontSize: 20, margin: 10, }, fixedSection: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, paddingTop: 20, flexDirection: 'row', alignItems: 'center', justifyContent:'space-between', }, backIcon: { width: 14, height: 14, marginLeft: 12, borderLeftWidth: 2.5, borderBottomWidth: 2.5, transform: [{rotate: '45deg'}], borderColor:'white', }, backWrapper: { flexDirection: 'row', alignItems: 'center', height:66, }, }); export default StoryPage;
app/scripts/components/metric-selector-item.js
hustbill/autorender-js
import React from 'react'; import classNames from 'classnames'; import { connect } from 'react-redux'; import { hoverMetric, pinMetric, unpinMetric } from '../actions/app-actions'; import { selectedMetricTypeSelector } from '../selectors/node-metric'; const messageToUser = 'Alert! Please check containers network'; class MetricSelectorItem extends React.Component { constructor(props, context) { super(props, context); this.onMouseOver = this.onMouseOver.bind(this); this.onMouseClick = this.onMouseClick.bind(this); // this.onMouseLeave = this.onMouseLeave.bind(this); } onMouseOver() { const metricType = this.props.metric.get('label'); this.props.hoverMetric(metricType); } onMouseClick() { const metricType = this.props.metric.get('label'); const pinnedMetricType = this.props.pinnedMetricType; if (metricType !== pinnedMetricType) { this.props.pinMetric(metricType); } else { this.props.unpinMetric(); } } onMouseLeave() { this.props.unpinMetric(); } render() { const { metric, selectedMetricType, pinnedMetricType } = this.props; const type = metric.get('label'); const isAlerted = (Math.floor(Math.random() * 4) + 1) === 2; const isPinned = (type === pinnedMetricType); const isSelected = (type === selectedMetricType); const className = classNames('metric-selector-action', { 'metric-selector-action-selected': isSelected }); return ( <div key={type} className={className} onMouseOver={this.onMouseOver} onMouseLeave={this.onMouseLeave} onClick={this.onMouseClick}> {type === 'CPU' ? 'Latency' : 'BandWidth'} {isPinned && <span className="fa fa-thumb-tack" />} {isAlerted && isPinned && <textarea style={{ width: 360, height: 30, backgroundColor: 'red', borderColor: 'darkred'}} value={messageToUser} name="data" />} <br /> </div> ); } } function mapStateToProps(state) { return { selectedMetricType: selectedMetricTypeSelector(state), pinnedMetricType: state.get('pinnedMetricType'), }; } export default connect( mapStateToProps, { hoverMetric, pinMetric, unpinMetric } )(MetricSelectorItem);
client/src/components/dashboard/Profile/Preferences/Mentorship.js
FCC-Alumni/alumni-network
import { connectScreenSize } from 'react-screen-size'; import { isEqual } from 'lodash'; import { mapScreenSizeToProps } from '../../../Navbar'; import MessageBox from '../../common/MessageBox'; import propTypes from 'prop-types'; import React from 'react'; import Ribbon from './common/RibbonHeader'; import SliderToggle from './common/SliderToggle'; import { TransitionContainer } from '../../../../styles/style-utils'; class Mentorship extends React.Component { shouldComponentUpdate(nextProps) { return !isEqual(this.props, nextProps); } render() { const { error, handleInputChange, isMentee, isMentor, mentorshipSkills, saveSection, screen: { isMobile, isTablet }, showMentorship, showPopUp, toggle, toggleMentorship, } = this.props; return ( <div> <Ribbon content="Mentorship Program" id="mentorshipPopUp" onClick={() => toggle('showMentorship')} saveSection={saveSection} showPopUp={showPopUp} showSave={showMentorship} /> <TransitionContainer isExpanded={showMentorship}> <MessageBox header="Would you like to be a mentor?" message="The main goal of this community is to bring together programmers of varying degrees of skill, and connect them with one another to form meaningful mentor/mentee relationships. If you are interested in becoming a mentor, please toggle the switch and provide a short description of the core competencies you feel comortable mentoring others in. Your profile will be searchable based on all the criteria provided here for prospective mentees who can contact you via private chat, or your email if you provide it. We encourage all members to be proactive and creative in building these relationships!" type="info" /> <SliderToggle defaultOn={isMentor ? true : false} id="mentorship" label="I would like to be a mentor." saveStateToParent={toggleMentorship} /> <SliderToggle defaultOn={isMentee ? true : false} id="menteeship" label="I would like to be mentored." saveStateToParent={toggleMentorship} /> <div className="ui form"> <TransitionContainer className={`ui ${isMobile ? 'fluid' : isTablet ? 'eight wide' : 'six wide'} field`} isExpanded={isMentor || isMentee}> <label>{'Mentorship Bio'}</label> <textarea name="mentorshipSkills" onChange={handleInputChange} placeholder="Please provide a short description of the skills you feel comfortable providing mentorship for and / or the areas you are looking for mentorship in." rows="3" style={{ marginBottom: 8 }} value={mentorshipSkills} /> { error && <div className="ui red basic label" style={{ marginTop: 10 }}> {error} </div> } </TransitionContainer> </div> </TransitionContainer> </div> ); } } Mentorship.propTypes = { error: propTypes.string, handleInputChange: propTypes.func.isRequired, isMentor: propTypes.bool.isRequired, isMobile: propTypes.bool, isTablet: propTypes.bool, mentorshipSkills: propTypes.string.isRequired, saveSection: propTypes.func.isRequired, showMentorship: propTypes.bool.isRequired, showPopUp: propTypes.bool.isRequired, toggle: propTypes.func.isRequired, toggleMentorship: propTypes.func.isRequired, } Mentorship.defaultProps = { error: '' } export default connectScreenSize(mapScreenSizeToProps)(Mentorship);
src/svg-icons/image/brightness-2.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness2 = (props) => ( <SvgIcon {...props}> <path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/> </SvgIcon> ); ImageBrightness2 = pure(ImageBrightness2); ImageBrightness2.displayName = 'ImageBrightness2'; ImageBrightness2.muiName = 'SvgIcon'; export default ImageBrightness2;
src/svg-icons/maps/directions.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirections = (props) => ( <SvgIcon {...props}> <path d="M21.71 11.29l-9-9c-.39-.39-1.02-.39-1.41 0l-9 9c-.39.39-.39 1.02 0 1.41l9 9c.39.39 1.02.39 1.41 0l9-9c.39-.38.39-1.01 0-1.41zM14 14.5V12h-4v3H8v-4c0-.55.45-1 1-1h5V7.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); MapsDirections = pure(MapsDirections); MapsDirections.displayName = 'MapsDirections'; MapsDirections.muiName = 'SvgIcon'; export default MapsDirections;
app/javascript/mastodon/components/status.js
ashfurrow/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import AvatarOverlay from './avatar_overlay'; import AvatarComposite from './avatar_composite'; import RelativeTimestamp from './relative_timestamp'; import DisplayName from './display_name'; import StatusContent from './status_content'; import StatusActionBar from './status_action_bar'; import AttachmentList from './attachment_list'; import Card from '../features/status/components/card'; import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { MediaGallery, Video, Audio } from '../features/ui/util/async-components'; import { HotKeys } from 'react-hotkeys'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import { displayMedia } from '../initial_state'; import PictureInPicturePlaceholder from 'mastodon/components/picture_in_picture_placeholder'; // We use the component (and not the container) since we do not want // to use the progress bar to show download progress import Bundle from '../features/ui/components/bundle'; export const textForScreenReader = (intl, status, rebloggedByText = false) => { const displayName = status.getIn(['account', 'display_name']); const values = [ displayName.length === 0 ? status.getIn(['account', 'acct']).split('@')[0] : displayName, status.get('spoiler_text') && status.get('hidden') ? status.get('spoiler_text') : status.get('search_index').slice(status.get('spoiler_text').length), intl.formatDate(status.get('created_at'), { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }), status.getIn(['account', 'acct']), ]; if (rebloggedByText) { values.push(rebloggedByText); } return values.join(', '); }; export const defaultMediaVisibility = (status) => { if (!status) { return undefined; } if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { status = status.get('reblog'); } return (displayMedia !== 'hide_all' && !status.get('sensitive') || displayMedia === 'show_all'); }; const messages = defineMessages({ public_short: { id: 'privacy.public.short', defaultMessage: 'Public' }, unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' }, private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' }, direct_short: { id: 'privacy.direct.short', defaultMessage: 'Mentioned people only' }, edited: { id: 'status.edited', defaultMessage: 'Edited {date}' }, }); export default @injectIntl class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, account: ImmutablePropTypes.map, otherAccounts: ImmutablePropTypes.list, onClick: PropTypes.func, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onPin: PropTypes.func, onOpenMedia: PropTypes.func, onOpenVideo: PropTypes.func, onBlock: PropTypes.func, onEmbed: PropTypes.func, onHeightChange: PropTypes.func, onToggleHidden: PropTypes.func, onToggleCollapsed: PropTypes.func, muted: PropTypes.bool, hidden: PropTypes.bool, unread: PropTypes.bool, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, showThread: PropTypes.bool, getScrollPosition: PropTypes.func, updateScrollBottom: PropTypes.func, cacheMediaWidth: PropTypes.func, cachedMediaWidth: PropTypes.number, scrollKey: PropTypes.string, deployPictureInPicture: PropTypes.func, pictureInPicture: ImmutablePropTypes.contains({ inUse: PropTypes.bool, available: PropTypes.bool, }), }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'account', 'muted', 'hidden', 'unread', 'pictureInPicture', ]; state = { showMedia: defaultMediaVisibility(this.props.status), statusId: undefined, }; static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.status && nextProps.status.get('id') !== prevState.statusId) { return { showMedia: defaultMediaVisibility(nextProps.status), statusId: nextProps.status.get('id'), }; } else { return null; } } handleToggleMediaVisibility = () => { this.setState({ showMedia: !this.state.showMedia }); } handleClick = e => { if (e && (e.button !== 0 || e.ctrlKey || e.metaKey)) { return; } if (e) { e.preventDefault(); } this.handleHotkeyOpen(); } handlePrependAccountClick = e => { this.handleAccountClick(e, false); } handleAccountClick = (e, proper = true) => { if (e && (e.button !== 0 || e.ctrlKey || e.metaKey)) { return; } if (e) { e.preventDefault(); } this._openProfile(proper); } handleExpandedToggle = () => { this.props.onToggleHidden(this._properStatus()); } handleCollapsedToggle = isCollapsed => { this.props.onToggleCollapsed(this._properStatus(), isCollapsed); } renderLoadingMediaGallery () { return <div className='media-gallery' style={{ height: '110px' }} />; } renderLoadingVideoPlayer () { return <div className='video-player' style={{ height: '110px' }} />; } renderLoadingAudioPlayer () { return <div className='audio-player' style={{ height: '110px' }} />; } handleOpenVideo = (options) => { const status = this._properStatus(); this.props.onOpenVideo(status.get('id'), status.getIn(['media_attachments', 0]), options); } handleOpenMedia = (media, index) => { this.props.onOpenMedia(this._properStatus().get('id'), media, index); } handleHotkeyOpenMedia = e => { const { onOpenMedia, onOpenVideo } = this.props; const status = this._properStatus(); e.preventDefault(); if (status.get('media_attachments').size > 0) { if (status.getIn(['media_attachments', 0, 'type']) === 'video') { onOpenVideo(status.get('id'), status.getIn(['media_attachments', 0]), { startTime: 0 }); } else { onOpenMedia(status.get('id'), status.get('media_attachments'), 0); } } } handleDeployPictureInPicture = (type, mediaProps) => { const { deployPictureInPicture } = this.props; const status = this._properStatus(); deployPictureInPicture(status, type, mediaProps); } handleHotkeyReply = e => { e.preventDefault(); this.props.onReply(this._properStatus(), this.context.router.history); } handleHotkeyFavourite = () => { this.props.onFavourite(this._properStatus()); } handleHotkeyBoost = e => { this.props.onReblog(this._properStatus(), e); } handleHotkeyMention = e => { e.preventDefault(); this.props.onMention(this._properStatus().get('account'), this.context.router.history); } handleHotkeyOpen = () => { if (this.props.onClick) { this.props.onClick(); return; } const { router } = this.context; const status = this._properStatus(); if (!router) { return; } router.history.push(`/@${status.getIn(['account', 'acct'])}/${status.get('id')}`); } handleHotkeyOpenProfile = () => { this._openProfile(); } _openProfile = (proper = true) => { const { router } = this.context; const status = proper ? this._properStatus() : this.props.status; if (!router) { return; } router.history.push(`/@${status.getIn(['account', 'acct'])}`); } handleHotkeyMoveUp = e => { this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyMoveDown = e => { this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyToggleHidden = () => { this.props.onToggleHidden(this._properStatus()); } handleHotkeyToggleSensitive = () => { this.handleToggleMediaVisibility(); } _properStatus () { const { status } = this.props; if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { return status.get('reblog'); } else { return status; } } handleRef = c => { this.node = c; } render () { let media = null; let statusAvatar, prepend, rebloggedByText; const { intl, hidden, featured, otherAccounts, unread, showThread, scrollKey, pictureInPicture } = this.props; let { status, account, ...other } = this.props; if (status === null) { return null; } const handlers = this.props.muted ? {} : { reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, open: this.handleHotkeyOpen, openProfile: this.handleHotkeyOpenProfile, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleHotkeyToggleHidden, toggleSensitive: this.handleHotkeyToggleSensitive, openMedia: this.handleHotkeyOpenMedia, }; if (hidden) { return ( <HotKeys handlers={handlers}> <div ref={this.handleRef} className={classNames('status__wrapper', { focusable: !this.props.muted })} tabIndex='0'> <span>{status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}</span> <span>{status.get('content')}</span> </div> </HotKeys> ); } if (status.get('filtered') || status.getIn(['reblog', 'filtered'])) { const minHandlers = this.props.muted ? {} : { moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, }; return ( <HotKeys handlers={minHandlers}> <div className='status__wrapper status__wrapper--filtered focusable' tabIndex='0' ref={this.handleRef}> <FormattedMessage id='status.filtered' defaultMessage='Filtered' /> </div> </HotKeys> ); } if (featured) { prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><Icon id='thumb-tack' className='status__prepend-icon' fixedWidth /></div> <FormattedMessage id='status.pinned' defaultMessage='Pinned post' /> </div> ); } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { const display_name_html = { __html: status.getIn(['account', 'display_name_html']) }; prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><Icon id='retweet' className='status__prepend-icon' fixedWidth /></div> <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handlePrependAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} /> </div> ); rebloggedByText = intl.formatMessage({ id: 'status.reblogged_by', defaultMessage: '{name} boosted' }, { name: status.getIn(['account', 'acct']) }); account = status.get('account'); status = status.get('reblog'); } if (pictureInPicture.get('inUse')) { media = <PictureInPicturePlaceholder width={this.props.cachedMediaWidth} />; } else if (status.get('media_attachments').size > 0) { if (this.props.muted) { media = ( <AttachmentList compact media={status.get('media_attachments')} /> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'audio') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Audio} loading={this.renderLoadingAudioPlayer} > {Component => ( <Component src={attachment.get('url')} alt={attachment.get('description')} poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])} backgroundColor={attachment.getIn(['meta', 'colors', 'background'])} foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])} accentColor={attachment.getIn(['meta', 'colors', 'accent'])} duration={attachment.getIn(['meta', 'original', 'duration'], 0)} width={this.props.cachedMediaWidth} height={110} cacheWidth={this.props.cacheMediaWidth} deployPictureInPicture={pictureInPicture.get('available') ? this.handleDeployPictureInPicture : undefined} /> )} </Bundle> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={attachment.get('preview_url')} frameRate={attachment.getIn(['meta', 'original', 'frame_rate'])} blurhash={attachment.get('blurhash')} src={attachment.get('url')} alt={attachment.get('description')} width={this.props.cachedMediaWidth} height={110} inline sensitive={status.get('sensitive')} onOpenVideo={this.handleOpenVideo} cacheWidth={this.props.cacheMediaWidth} deployPictureInPicture={pictureInPicture.get('available') ? this.handleDeployPictureInPicture : undefined} visible={this.state.showMedia} onToggleVisibility={this.handleToggleMediaVisibility} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}> {Component => ( <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.handleOpenMedia} cacheWidth={this.props.cacheMediaWidth} defaultWidth={this.props.cachedMediaWidth} visible={this.state.showMedia} onToggleVisibility={this.handleToggleMediaVisibility} /> )} </Bundle> ); } } else if (status.get('spoiler_text').length === 0 && status.get('card')) { media = ( <Card onOpenMedia={this.handleOpenMedia} card={status.get('card')} compact cacheWidth={this.props.cacheMediaWidth} defaultWidth={this.props.cachedMediaWidth} sensitive={status.get('sensitive')} /> ); } if (otherAccounts && otherAccounts.size > 0) { statusAvatar = <AvatarComposite accounts={otherAccounts} size={48} />; } else if (account === undefined || account === null) { statusAvatar = <Avatar account={status.get('account')} size={48} />; } else { statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />; } const visibilityIconInfo = { 'public': { icon: 'globe', text: intl.formatMessage(messages.public_short) }, 'unlisted': { icon: 'unlock', text: intl.formatMessage(messages.unlisted_short) }, 'private': { icon: 'lock', text: intl.formatMessage(messages.private_short) }, 'direct': { icon: 'envelope', text: intl.formatMessage(messages.direct_short) }, }; const visibilityIcon = visibilityIconInfo[status.get('visibility')]; return ( <HotKeys handlers={handlers}> <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { 'status__wrapper-reply': !!status.get('in_reply_to_id'), unread, focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null} aria-label={textForScreenReader(intl, status, rebloggedByText)} ref={this.handleRef}> {prepend} <div className={classNames('status', `status-${status.get('visibility')}`, { 'status-reply': !!status.get('in_reply_to_id'), muted: this.props.muted })} data-id={status.get('id')}> <div className='status__expand' onClick={this.handleClick} role='presentation' /> <div className='status__info'> <a onClick={this.handleClick} href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'> <span className='status__visibility-icon'><Icon id={visibilityIcon.icon} title={visibilityIcon.text} /></span> <RelativeTimestamp timestamp={status.get('created_at')} />{status.get('edited_at') && <abbr title={intl.formatMessage(messages.edited, { date: intl.formatDate(status.get('edited_at'), { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) })}> *</abbr>} </a> <a onClick={this.handleAccountClick} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name' target='_blank' rel='noopener noreferrer'> <div className='status__avatar'> {statusAvatar} </div> <DisplayName account={status.get('account')} others={otherAccounts} /> </a> </div> <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} showThread={showThread} onExpandedToggle={this.handleExpandedToggle} collapsable onCollapsedToggle={this.handleCollapsedToggle} /> {media} <StatusActionBar scrollKey={scrollKey} status={status} account={account} {...other} /> </div> </div> </HotKeys> ); } }
frontend/src/Movie/Details/Credits/MovieCreditPosterConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { selectImportListSchema, setImportListFieldValue, setImportListValue } from 'Store/Actions/settingsActions'; import createMovieCreditListSelector from 'Store/Selectors/createMovieCreditListSelector'; function createMapStateToProps() { return createMovieCreditListSelector(); } const mapDispatchToProps = { selectImportListSchema, setImportListFieldValue, setImportListValue }; class MovieCreditPosterConnector extends Component { // // Listeners onImportListSelect = () => { this.props.selectImportListSchema({ implementation: 'TMDbPersonImport', presetName: undefined }); this.props.setImportListFieldValue({ name: 'personId', value: this.props.tmdbId.toString() }); this.props.setImportListValue({ name: 'name', value: `${this.props.personName} - ${this.props.tmdbId}` }); } // // Render render() { const { tmdbId, component: ItemComponent, personName } = this.props; return ( <ItemComponent {...this.props} tmdbId={tmdbId} personName={personName} onImportListSelect={this.onImportListSelect} /> ); } } MovieCreditPosterConnector.propTypes = { tmdbId: PropTypes.number.isRequired, personName: PropTypes.string.isRequired, component: PropTypes.elementType.isRequired, selectImportListSchema: PropTypes.func.isRequired, setImportListFieldValue: PropTypes.func.isRequired, setImportListValue: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(MovieCreditPosterConnector);
examples/gatsby/src/withRoot.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { MuiThemeProvider } from 'material-ui/styles'; import CssBaseline from 'material-ui/CssBaseline'; import getPageContext from './getPageContext'; function withRoot(Component) { class WithRoot extends React.Component { constructor(props, context) { super(props, context); this.pageContext = this.props.pageContext || getPageContext(); } componentDidMount() { // Remove the server-side injected CSS. const jssStyles = document.querySelector('#server-side-jss'); if (jssStyles && jssStyles.parentNode) { jssStyles.parentNode.removeChild(jssStyles); } } pageContext = null; render() { // MuiThemeProvider makes the theme available down the React tree thanks to React context. return ( <MuiThemeProvider theme={this.pageContext.theme} sheetsManager={this.pageContext.sheetsManager} > {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */} <CssBaseline /> <Component {...this.props} /> </MuiThemeProvider> ); } } WithRoot.propTypes = { pageContext: PropTypes.object, }; return WithRoot; } export default withRoot;
popup-study/screens/PostScreen.js
Morhaus/popupstudy
import React from 'react'; import { KeyboardAvoidingView, ScrollView, StyleSheet, Text, View, Button, ActivityIndicator, } from 'react-native'; import { NavigationBar } from '@expo/ex-navigation'; import { graphql, gql } from 'react-apollo'; import { GiftedChat } from 'react-native-gifted-chat'; import { connect } from 'react-redux'; import Router from '../navigation/Router'; import PostCard from '../components/PostCard'; import TagsList from '../components/TagsList'; import Chat from '../components/Chat'; import ChatList from '../components/ChatList'; class PostScreen extends React.Component { static route = { navigationBar: {}, }; render() { const { loading, userId } = this.props; if (this.props.data.loading) { return <ActivityIndicator />; } return ( <View style={styles.container}> <PostCard post={this.props.data.post} /> <View style={styles.description}> <Text>{this.props.data.post.description}</Text> </View> {this.props.data.post.author.id === userId ? <View style={styles.chatList}> <ChatList postId={this.props.data.post.id} /> </View> : <View style={styles.chat}> <Chat userId={userId} postId={this.props.data.post.id} /> </View>} </View> ); } } const styles = StyleSheet.create({ backButton: { flexDirection: 'row', }, container: { flex: 1, }, chatList: { flex: 1, }, chat: { flex: 1, backgroundColor: 'white', }, description: { padding: 20, paddingTop: 0, backgroundColor: '#fff', borderBottomWidth: 0.5, borderBottomColor: '#b2b2b2', }, }); const PostQuery = gql` query PostQuery($id: ID!) { post: Post(id: $id) { id title description author { id } tags { id name isCourse } } } `; export default connect(state => ({ userId: state.app.userId }))( graphql(PostQuery, { options: ({ id }) => ({ variables: { id } }), })(PostScreen) );
frontend/src/WorkflowList.js
aclowes/yawn
import React from 'react'; import {Alert, Table} from 'react-bootstrap'; import {Link} from 'react-router'; import API from "./API"; export default class WorkflowList extends React.Component { constructor(props) { super(props); this.state = {workflows: null}; } componentDidMount() { document.title = `YAWN - Workflows`; API.get('/api/names/', (payload, error) => { this.setState({workflows: payload, error}); }) } renderRows() { if (this.state.workflows === null) { return ( <tr> <td colSpan="4">Loading...</td> </tr> ) } else { return this.state.workflows.map((workflow) => ( <tr key={workflow.id}> <td><Link to={`/workflows/${workflow.current_version_id}`}>{workflow.name}</Link></td> <td>{workflow.schedule_active ? 'True' : 'False'}</td> <td>{workflow.schedule || '(none)'}</td> <td>{workflow.task_count}</td> </tr> )) } } render() { return ( <div> <h3>Workflows</h3> {this.state.error && <Alert bsStyle="danger">{this.state.error}</Alert>} <Table striped bordered condensed hover> <thead> <tr> <th>Name</th> <th>Schedule Active</th> <th>Schedule</th> <th>Tasks</th> </tr> </thead> <tbody> {this.renderRows()} </tbody> </Table> </div> ); } }
src/svg-icons/device/battery-50.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
src/components/TabWrapper/Tab.js
GetAmbassador/react-ions
import React from 'react' import PropTypes from 'prop-types' import style from './style.scss' import classNames from 'classnames/bind' class Tab extends React.Component { constructor(props) { super(props) } static defaultProps = { } static propTypes = { /** * Whether the tab is active. Set by the tab wrapper component. */ active: PropTypes.bool, /** * Whether the tab is disabled. */ disabled: PropTypes.bool, /** * The tab count. */ count: PropTypes.number, /** * Optional styles to add to the tab header. */ optClass: PropTypes.string, /** * Optional styles to add to the tab content. */ optTabContentClass: PropTypes.string, /** * The tab title. */ title: PropTypes.string.isRequired, /** * Optional title prefix renders in front of the title. */ titlePrefix: PropTypes.node, /** * Optional title suffix renders after the title */ titleSuffix: PropTypes.node } formatCount = () => { // Add thousands separator (',') return this.props.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') } handleClick = event => { if (this.props.onClick && !this.props.disabled) { this.props.onClick(event, this) } } render() { const cx = classNames.bind(style) const tabActiveClass = (this.props.active) ? 'active' : null const tabDisabledClass = (this.props.disabled) ? 'disabled' : null const tabClasses = cx(style.tab, this.props.optClass, tabActiveClass, tabDisabledClass) return ( <div className={tabClasses} onClick={this.handleClick} aria-selected={this.props.active}> {this.props.titlePrefix} {this.props.title} {this.props.count ? <span className={style.count}>({this.formatCount()})</span> : null} {this.props.titleSuffix} </div> ) } } export default Tab
src/components/Register/RegisterForm.js
TalentedEurope/te-app
import React from 'react'; import { ActivityIndicator, KeyboardAvoidingView, StyleSheet, Text, TouchableOpacity, } from 'react-native'; import { CheckBox } from 'react-native-elements'; import I18n from '../../i18n/i18n'; import AuthenticationApi from '../../api/AuthenticationApi'; import COMMON_STYLES from '../../styles/common'; import { sortInstitutions, submit } from './utils'; import { UserTypeSelector } from './UserTypeSelector'; import { TextInputForm } from './TextInputForm'; import InstitutionSelector from './InstitutionSelector'; export default class RegisterForm extends React.Component { state = { errorMessage: '', warningTranslationKey: '', loading: false, selectionIndex: 'none', name: '', surname: '', email: '', password: '', passwordConfirm: '', institutions: [], institutionSelected: {}, inviteInstitution: false, institutionName: '', institutioEmail: '', termsChecked: false, }; componentWillMount() { this.authenticationApi = new AuthenticationApi(); const { state } = this.props.navigation; if (state.params && state.params.requiredRegister) { this.setState({ warningTranslationKey: 'reg-profile.to_see_more_details' }); } this.authenticationApi.getInstitutions().then((response) => { this.setState({ institutions: sortInstitutions(response), }); }); } onSelectUserType(newType) { if (this.state.loading) { return; } this.setState({ selectionIndex: newType, }); } onSelectInstitution(institutionSelected) { this.setState({ institutionSelected, inviteInstitution: false, institutionName: '', institutionEmail: '', }); } onSaveInstitution(institutionName, institutionEmail) { this.setState({ institutionSelected: {}, inviteInstitution: true, institutionName, institutionEmail, }); } onClickTerms() { if (this.state.loading) { return; } this.setState({ termsChecked: !this.state.termsChecked, }); } submit = submit.bind(this); render() { return ( <KeyboardAvoidingView behavior="padding" style={styles.formBox}> {!!this.state.errorMessage && <Text style={styles.error}>{this.state.errorMessage}</Text>} {!!this.state.warningTranslationKey && ( <Text style={styles.warning}>{I18n.t(this.state.warningTranslationKey)}</Text> )} <UserTypeSelector selectionIndex={this.state.selectionIndex} onSelect={this.onSelectUserType.bind(this)} /> {['validator', 'institution'].includes(this.state.selectionIndex) && ( <TextInputForm icon={this.state.selectionIndex === 'institution' ? 'university' : 'user-o'} value={this.state.name} placeholder={I18n.t('reg-profile.name')} onChangeText={name => this.setState({ name })} onSubmitEditing={() => { if (this.state.selectionIndex === 'validator') { this.surnameInput.focus(); } else { this.emailInput.focus(); } }} editable={!this.state.loading} /> )} {this.state.selectionIndex === 'validator' && ( <TextInputForm icon="user-o" value={this.state.surname} placeholder={I18n.t('reg-profile.surname')} onChangeText={surname => this.setState({ surname })} onSubmitEditing={() => this.emailInput.focus()} editable={!this.state.loading} refFn={(input) => { this.surnameInput = input; }} /> )} <TextInputForm icon="user-o" value={this.state.email} placeholder={I18n.t('reg-profile.email')} onChangeText={email => this.setState({ email })} onSubmitEditing={() => this.passwordInput.focus()} keyboardType="email-address" editable={!this.state.loading} refFn={(input) => { this.emailInput = input; }} /> <TextInputForm icon="lock" value={this.state.password} placeholder={I18n.t('reg-profile.password')} onChangeText={password => this.setState({ password })} onSubmitEditing={() => this.confirmPasswordInput.focus()} secureTextEntry={true} editable={!this.state.loading} refFn={(input) => { this.passwordInput = input; }} /> <TextInputForm icon="lock" value={this.state.passwordConfirm} placeholder={I18n.t('reg-profile.confirm_password')} returnKeyType="go" onChangeText={passwordConfirm => this.setState({ passwordConfirm })} secureTextEntry={true} editable={!this.state.loading} refFn={(input) => { this.confirmPasswordInput = input; }} /> {this.state.selectionIndex === 'validator' && ( <InstitutionSelector institutions={this.state.institutions} institutionSelected={this.state.institutionSelected} inviteInstitution={this.state.inviteInstitution} institutionName={this.state.institutionName} institutionEmail={this.state.institutionEmail} loading={this.state.loading} onSelect={this.onSelectInstitution.bind(this)} onSave={this.onSaveInstitution.bind(this)} /> )} <CheckBox title={I18n.t('reg-profile.terms_of_use')} style={styles.checkBox} textStyle={styles.checkBoxText} checked={this.state.termsChecked} checkedColor={COMMON_STYLES.YELLOW} onPress={() => this.onClickTerms()} /> <TouchableOpacity activeOpacity={0.8} style={ this.state.loading ? [styles.submitButtonContainer, styles.disabledButton] : styles.submitButtonContainer } onPress={() => this.submit()} > {this.state.loading === true && ( <ActivityIndicator style={styles.buttonSpinner} color={COMMON_STYLES.BLACK} /> )} <Text style={styles.submitButtonText}>{I18n.t('global.register_btn').toUpperCase()}</Text> </TouchableOpacity> </KeyboardAvoidingView> ); } } const styles = StyleSheet.create({ error: { backgroundColor: COMMON_STYLES.RED, color: COMMON_STYLES.WHITE, textAlign: 'center', padding: 10, fontSize: 14, marginBottom: 15, }, warning: { backgroundColor: COMMON_STYLES.WARNING_BG, color: COMMON_STYLES.WARNING_TEXT, textAlign: 'center', padding: 10, fontSize: 14, marginBottom: 15, }, formBox: { margin: 20, marginTop: 0, padding: 15, paddingTop: 5, width: '100%', flexDirection: 'column', alignItems: 'center', }, checkBox: { flex: 1, padding: 10, backgroundColor: 'transparent', marginBottom: 10, }, checkBoxText: { color: COMMON_STYLES.WHITE, }, submitButtonContainer: { backgroundColor: COMMON_STYLES.YELLOW, paddingVertical: 12, width: '100%', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, submitButtonText: { textAlign: 'center', color: COMMON_STYLES.BROWN, }, disabledButton: { backgroundColor: COMMON_STYLES.GRAY, }, buttonSpinner: { paddingRight: 10, }, });
ui/kirk/src/index.js
socx/Kirk
import React from 'react'; import { render } from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; import 'bootstrap/dist/css/bootstrap.css'; import './index.css'; import App from './App'; import { Provider } from 'react-redux' import { ConnectedRouter } from 'react-router-redux' import store, { history} from './store' render( <Provider store={store}> <ConnectedRouter history={history}> <div> <App history={history} /> </div> </ConnectedRouter> </Provider>, document.querySelector('#root') ); registerServiceWorker();
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/AutoComplete/Page.js
pbogdan/react-flux-mui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import autoCompleteReadmeText from './README'; import autoCompleteCode from '!raw!material-ui/AutoComplete/AutoComplete'; import AutoCompleteExampleSimple from './ExampleSimple'; import autoCompleteExampleSimpleCode from '!raw!./ExampleSimple'; import AutoCompleteExampleDataSources from './ExampleDataSources'; import autoCompleteExampleDataSourcesCode from '!raw!./ExampleDataSources'; import AutoCompleteExampleFilters from './ExampleFilters'; import autoCompleteExampleFiltersCode from '!raw!./ExampleFilters'; import AutoCompleteExampleControlled from './ExampleControlled'; import autoCompleteExampleControlledCode from '!raw!./ExampleControlled'; const AutoCompletesPage = () => ( <div> <Title render={(previousTitle) => `Auto Complete - ${previousTitle}`} /> <MarkdownElement text={autoCompleteReadmeText} /> <CodeExample code={autoCompleteExampleSimpleCode} title="Simple example" > <AutoCompleteExampleSimple /> </CodeExample> <CodeExample code={autoCompleteExampleDataSourcesCode} title="Data sources" > <AutoCompleteExampleDataSources /> </CodeExample> <CodeExample code={autoCompleteExampleFiltersCode} title="Filters" > <AutoCompleteExampleFilters /> </CodeExample> <CodeExample code={autoCompleteExampleControlledCode} title="Controlled example" > <AutoCompleteExampleControlled /> </CodeExample> <PropTypeDescription code={autoCompleteCode} /> </div> ); export default AutoCompletesPage;
src/v0/demo/listview/index1.js
huanganqi/wsapp
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ListView, } from 'react-native'; class wsapp extends Component { constructor(props) { super(props); var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2','row 1', 'row 2', ]), }; } render() { return ( <ListView dataSource={this.state.dataSource} renderRow={(rowData) => <Text style={{ backgroundColor: 'red', color: 'white', }}>{rowData}</Text>} /> ); } } export default wsapp
frontend/src/components/siteComponents/HomepageMessage/index.js
webrecorder/webrecorder
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import TempUserTimer from 'components/TempUserTimer'; function HomepageMessage(props) { const { auth, showModal } = props; const user = auth.get('user'); const username = user.get('username'); const showModalCB = () => showModal(true); const recCount = user.get('num_recordings'); return ( <div className="row wr-hp-message"> <div className="col-md-6 col-md-offset-3"> <div className="panel panel-info"> <div className="panel-heading"> You have a <b><Link to={`/${username}/temp/manage`}>Temporary Collection</Link></b> with {recCount} recording{recCount === 1 ? '' : 's'}, expiring in <b><TempUserTimer ttl={user.get('ttl')} accessed={auth.get('accessed')} /></b> </div> <div className="panel-body"> <div className="top-buffer-md"> <ul> <li> <Link to="/_register"><strong>Sign Up</strong></Link> or <button className="button-link" onClick={showModalCB} type="button">Login</button> to keep your collection and give it a permanent address. </li> <li> Continue capturing by entering another URL below and clicking <b>Start</b> </li> </ul> </div> </div> </div> </div> </div> ); } HomepageMessage.propTypes = { auth: PropTypes.object, showModal: PropTypes.func }; export default HomepageMessage;