path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/routes/Todo/containers/AddTodo.js
YannickBochatay/JSYG-starterkit
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' import { FormattedMessage } from "react-intl" class AddTodo extends React.Component { constructor(props) { super(props) this.onSubmit = this.onSubmit.bind(this) } onSubmit(e) { e.preventDefault() let {input} = this.refs if (!input.value.trim()) return this.props.dispatch( addTodo(input.value) ) input.value = '' } render() { return ( <form onSubmit={ this.onSubmit }> <input type="text" id="addTodo" ref="input"/> <br/> <button type="submit"> <FormattedMessage id="Submit"/> </button> </form> ) } } export default connect()(AddTodo)
src/components/OfficialRankGraph.js
giladgreen/pokerStats
import React, { Component } from 'react'; import {connect} from 'react-redux'; import {cloneDeep} from 'lodash'; import {getBackgroundColorByPlayerName, geTextColorByPlayerName} from '../colorsHelper'; import {bindActionCreators} from 'redux'; import {LineChart,ReferenceLine, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts'; class OfficialRankGraph extends Component { constructor(props){ super(props); this.toggleButton=this.toggleButton.bind(this); let {rankedPlayers} =this.props; const ids = rankedPlayers.map(item=>item.playerObject.id); const names = {}; rankedPlayers.forEach((item)=>{ names[item.playerObject.id]= item.playerObject.displayName; } ); this.state = { allIds:ids, ids:ids, names:names } } toggleButton(id){ const newState = cloneDeep(this.state); let {ids,allIds} = newState; console.log('toggleButton ',id); console.log('before ids ',ids); if (ids.includes(id)){ console.log('removing ',id); ids = ids.filter(x=>x!==id); }else{ console.log('adding ',id); console.log('allIds ',allIds); ids = allIds.filter(x =>{ return (x===id || ids.includes(x)); }); } console.log('after ids ',ids); newState.ids= ids; this.setState(newState); } render() { let {width,height,games,rankedPlayers,loggedInPlayerId} =this.props; const {names, ids, allIds} = this.state; const prevData = {}; const data = games.map(game => { const item = {name:game.name}; const {players} = game; ids.forEach(id=>{ const player = players.find(p=>p.id===id); if (player){ let dif = player.exit - player.enter; if (prevData.hasOwnProperty(id)){ dif += prevData[id]; } prevData[id] = dif; item[names[id]] = dif; } else{ if (prevData.hasOwnProperty(id)){ item[names[id]] = prevData[id]; } } }); return item; }) const bc = {name:' '}; ids.forEach(id=>{bc[names[id]] = 0}); data.unshift(bc) const strokes={}; const textColors={}; let positive_index = 0; let non_positive_index = 1; rankedPlayers.forEach((item)=>{ const id = item.playerObject.id; if ( !ids.includes(id)){ strokes[id]= 'pressed'; textColors[id]= 'black'; return; } let color =getBackgroundColorByPlayerName(id);// 'black'; let textColor = geTextColorByPlayerName(id);// 'black'; if (id ===loggedInPlayerId){ color='blue'; textColor = 'white'; } strokes[id]= color ; textColors[id]= textColor; } ); const lines =ids.map(id=>(<Line className="graphLine" strokeWidth={(id ===loggedInPlayerId ? 4 :2)} type="monotone" key={id} dataKey={names[id]} stroke={strokes[id]} th />)); const buttons = allIds.map(id=> { const style={ backgroundColor:strokes[id], color:textColors[id], marginLeft:"10px" } if (strokes[id]==='pressed'){ style.backgroundColor='#e5e5e5'; style['-webkit-box-shadow']= 'inset 0px 0px 5px #c1c1c1'; style['-moz-box-shadow']= 'inset 0px 0px 5px #c1c1c1'; style['box-shadow']= 'inset 0px 0px 5px #c1c1c1'; } return (<button style={style} onClick={()=>{this.toggleButton(id)}}>{names[id]} </button>); }); //toggleButton(id) const graph = ( <div className="row"> <div className="rankedPlayersGraph" width={width}> <LineChart className="rankedPlayersGraphLineChart" width={width} height={height} data={data} > <XAxis dataKey="name"/> <YAxis/> <CartesianGrid strokeDasharray="2 20"/> <Tooltip/> <ReferenceLine y={0} label="Zero" stroke="black"/> {lines} </LineChart> </div> <div className="buttons" width={width}> Filter {buttons} </div> </div> ); return graph; } } function mapStateToProps(state){ return {pokerStats:state.pokerStats}; } function mapDispatchToProps(dispatch){ return bindActionCreators({},dispatch); } export default connect(mapStateToProps,mapDispatchToProps)(OfficialRankGraph);
ignite/Examples/Containers/ignite-ir-boilerplate/GridExample.js
jpklein/TwistedMind
import React from 'react' import { View, Text, ListView } from 'react-native' import { connect } from 'react-redux' // For empty lists // import AlertMessage from '../Components/AlertMessage' // Styles import styles from './Styles/GridExampleStyle' class GridExample extends React.Component { constructor (props) { super(props) // If you need scroll to bottom, consider http://bit.ly/2bMQ2BZ /* *********************************************************** * STEP 1 * This is an array of objects with the properties you desire * Usually this should come from Redux mapStateToProps *************************************************************/ const dataObjects = [ {title: 'First Title', description: 'First Description'}, {title: 'Second Title', description: 'Second Description'}, {title: 'Third Title', description: 'Third Description'}, {title: 'Fourth Title', description: 'Fourth Description'}, {title: 'Fifth Title', description: 'Fifth Description'}, {title: 'Sixth Title', description: 'Sixth Description'}, {title: 'Seventh Title', description: 'Seventh Description'} ] /* *********************************************************** * STEP 2 * Teach datasource how to detect if rows are different * Make this function fast! Perhaps something like: * (r1, r2) => r1.id !== r2.id} *************************************************************/ const rowHasChanged = (r1, r2) => r1 !== r2 // DataSource configured const ds = new ListView.DataSource({rowHasChanged}) // Datasource is always in state this.state = { dataSource: ds.cloneWithRows(dataObjects) } } /* *********************************************************** * STEP 3 * `_renderRow` function -How each cell/row should be rendered * It's our best practice to place a single component here: * * e.g. return <MyCustomCell title={rowData.title} description={rowData.description} /> *************************************************************/ _renderRow (rowData) { return ( <View style={styles.row}> <Text style={styles.boldLabel}>{rowData.title}</Text> <Text style={styles.label}>{rowData.description}</Text> </View> ) } /* *********************************************************** * STEP 4 * If your datasource is driven by Redux, you'll need to * reset it when new data arrives. * DO NOT! place `cloneWithRows` inside of render, since render * is called very often, and should remain fast! Just replace * state's datasource on newProps. * * e.g. componentWillReceiveProps (newProps) { if (newProps.someData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(newProps.someData) }) } } *************************************************************/ // Used for friendly AlertMessage // returns true if the dataSource is empty _noRowData () { return this.state.dataSource.getRowCount() === 0 } // Render a footer. _renderFooter = () => { return ( <Text> - Footer - </Text> ) } render () { return ( <View style={styles.container}> <ListView contentContainerStyle={styles.listContent} dataSource={this.state.dataSource} renderRow={this._renderRow} renderFooter={this._renderFooter} enableEmptySections pageSize={15} /> </View> ) } } const mapStateToProps = (state) => { return { // ...redux state to props here } } const mapDispatchToProps = (dispatch) => { return { } } export default connect(mapStateToProps, mapDispatchToProps)(GridExample)
ui/js/components/SectionMultiEdit.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FormFieldAdd from './FormFieldAdd'; import Button from './Button'; import SectionFields from './SectionFields'; import SectionItem from './SectionItem'; export default class SectionMultiEdit extends Component { constructor() { super(); this._onAddItem = this._onAddItem.bind(this); this._onChangeItem = this._onChangeItem.bind(this); this.state = { nextId: 1 }; } _onAddItem() { const { formState, property } = this.props; const { nextId } = this.state; const section = formState.object; const items = (section[property] ? section[property].slice(0) : []); items.push({ id: nextId }); formState.set(property, items); this.setState({ nextId: nextId + 1 }); } _onChangeItem(item, index) { const { formState, property } = this.props; const items = (formState.object[property] || []).slice(0); items[index] = item; formState.change(property)(items); } render() { const { formState, ItemEdit, label, property } = this.props; const section = formState.object; const items = (section[property] || []).map((item, index) => ( <SectionItem key={item._id || item.id} formState={formState} index={index} property={property} label={label}> <ItemEdit item={item} index={index} onChange={nextItem => this._onChangeItem(nextItem, index)} /> </SectionItem> )); return ( <fieldset className="form__fields"> <SectionFields formState={formState} /> {items} <div className="form-item-add"> <FormFieldAdd> <Button label={`Add ${label}`} secondary={true} onClick={this._onAddItem} /> </FormFieldAdd> </div> </fieldset> ); } } SectionMultiEdit.propTypes = { formState: PropTypes.object.isRequired, ItemEdit: PropTypes.func.isRequired, label: PropTypes.string.isRequired, property: PropTypes.string.isRequired, };
imports/ui/components/SessionList.js
hanstest/hxgny
import React from 'react' import DataList from '../components/DataList' import { insertSession, updateSession, removeSession } from '../../api/data/methods' class SessionList extends React.Component { state = { key: (new Date()).getTime(), } refresh = () => { this.setState({ key: (new Date()).getTime() }) } render() { return ( <DataList key={this.state.key} dataType='上课时间' items={this.props.items} refresh={this.refresh} insertItem={insertSession} updateItem={updateSession} removeItem={removeSession} /> ) } } SessionList.propTypes = { items: React.PropTypes.array, } export default SessionList
front-end (deprecated)/src/components/Shared/Footer.js
iankhor/medrefer
import React from 'react' const Footer = (props) => { return ( <div className="generic-center"> <h1>This is from Footer</h1> </div> ) } export default Footer
src/utils/ValidComponentChildren.js
thealjey/react-bootstrap
import React from 'react'; /** * Maps children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { let index = 0; return React.Children.map(children, function(child) { if (React.isValidElement(child)) { let lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { let index = 0; return React.Children.forEach(children, function(child) { if (React.isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { let count = 0; React.Children.forEach(children, function(child) { if (React.isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { let hasValid = false; React.Children.forEach(children, function(child) { if (!hasValid && React.isValidElement(child)) { hasValid = true; } }); return hasValid; } function find(children, finder) { let child; forEachValidComponents(children, (c, idx)=> { if (!child && finder(c, idx, children)) { child = c; } }); return child; } export default { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, find, hasValidComponent };
components/MessageForm.js
caesai/sushka-chat
import React from 'react'; // import io from 'socket.io-client'; import { connect } from 'react-redux'; import * as actions from '../actions/actions'; import store from '../store/store'; import * as styles from './scss/MessageForm.scss'; // const socket = io(); export default class MessageForm extends React.Component { // let emojiActive = false; render() { let buttn; let input; let uploader; let emojiCont; let {avatar} = this.props; return( <div className='message_form'> <img src={avatar} className={styles.avatar} alt=""/> <div className={styles.formBlock}> <form encType="multipart/form-data" action="/" method="post" onSubmit={e => { e.preventDefault(); if (!input.innerHTML.trim()) { return } // socket.emit('chat message', { // 'avatar': avatar, // 'msg' : input.innerHTML // }); store.dispatch(actions.addMessage(input.innerHTML)); input.innerHTML = ''; } } > <div className={styles.textInput}> <div className={styles.messageTextarea} ref={node => { input = node }} placeholder="Написать сообщение" contentEditable="true" onKeyDown={(e) => { if(e.keyCode === 13) { document.execCommand('formatBlock', false, 'p'); input.innerHTML.replace(/(<([^>]+)>)/ig,""); if (e.shiftKey) { e.stopPropagation(); } else if (input.innerText.trim() !== "") { buttn.click(); } return false; } }}></div> <input className={styles.uploader} type="file" name="uploads" ref={(node) => uploader = node} onChange={(e) => { var files = e.target.files; // store.dispatch(actions.loadFile(files)); store.dispatch(actions.fetchFile(files)).then(() => console.log(store.getState()) ) }} /> <i className={'fa fa-picture-o ' + styles.fileTrigger} aria-hidden="true" onClick={()=>{ uploader.click(); }}> </i> <i className={'fa fa-smile-o ' + styles.emojiTrigger} aria-hidden="true" data-active="false" onClick={(e)=> { let emojiActive = e.currentTarget.dataset.active; emojiCont.classList.toggle(styles.active, !emojiActive); e.currentTarget.dataset.active = !emojiActive; }}> </i> <div className={styles.emojiContainer} ref={(node) => emojiCont = node} > </div> </div> <p> <button className={styles.submitBtn} type="submit" ref={node => { buttn = node }}> Отправить </button> </p> </form> </div> </div> ); } }; // const mapStateToProps = function(store) { // return { // avatar: store.UserInfo.avatar // }; // }; // // MessageForm = connect(mapStateToProps,state => ({ // info: state.info // }))(MessageForm); // export default MessageForm;
src/components/Results.js
my-contributions/my-contributions.github.io
import './Results.scss'; import React from 'react'; import PropTypes from 'prop-types'; import GitHub from '../api/GitHub'; import Author from './Author'; import PullRequests from './PullRequests'; import Issues from './Issues'; export default class Results extends React.PureComponent { render() { return ( <div className="results"> <Author github={this.props.github}/> <div className="contributions pl-md-4 px-sm-2"> <PullRequests github={this.props.github}/> <Issues github={this.props.github}/> </div> </div> ); } } Results.propTypes = { github: PropTypes.instanceOf(GitHub).isRequired, };
src/js/components/icons/base/Scorecard.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-scorecard`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'scorecard'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M9,18 L9,12 M12,18 L12,13 M15,18 L15,10 M17,3 L21,3 L21,23 L3,23 L3,3 L7,3 M7,1 L17,1 L17,5 L7,5 L7,1 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Scorecard'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
node_modules/react-scripts/template/src/index.js
CodeShareRepeat/ReactBookStore
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
breezy_rails/lib/install/templates/web/application.js
jho406/Breezy
import React from 'react'; import { combineReducers, createStore, applyMiddleware, compose } from 'redux'; import reduceReducers from 'reduce-reducers'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; import { ApplicationBase, fragmentMiddleware } from '@jho406/breezy'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; import { applicationRootReducer, applicationPagesReducer } from './reducer'; import { buildVisitAndRemote } from './application_visit'; // Mapping between your props template to Component, you must add to this // to register any new page level component you create. If you are using the // scaffold, it will auto append the identifers for you. // // e.g {'posts/new': PostNew} const identifierToComponentMapping = { }; if (typeof window !== "undefined") { document.addEventListener("DOMContentLoaded", function () { const appEl = document.getElementById("app"); const location = window.location; if (appEl) { render( <Application appEl={appEl} // The base url prefixed to all calls made by the `visit` // and `remote` thunks. baseUrl={location.origin} // The global var BREEZY_INITIAL_PAGE_STATE is set by your erb // template, e.g., index.html.erb initialPage={window.BREEZY_INITIAL_PAGE_STATE} // The initial path of the page, e.g., /foobar path={location.pathname + location.search + location.hash} buildVisitAndRemote={buildVisitAndRemote} />, appEl ); } }); } export default class Application extends ApplicationBase { mapping() { return identifierToComponentMapping; } visitAndRemote(navRef, store) { return buildVisitAndRemote(navRef, store); } buildStore(initialState, { breezy: breezyReducer, pages: pagesReducer }) { // Create the store // See `./reducer.js` for an explaination of the two included reducers const composeEnhancers = (this.hasWindow && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose; const reducer = this.wrapWithPersistReducer( reduceReducers( combineReducers({ breezy: breezyReducer, pages: reduceReducers(pagesReducer, applicationPagesReducer), }), applicationRootReducer ) ); const store = createStore( reducer, initialState, composeEnhancers(applyMiddleware(thunk, fragmentMiddleware)) ); if (this.hasWindow) { // Persist the store using Redux-Persist persistStore(store); } return store; } wrapWithPersistReducer(reducers) { // Redux Persist settings // The key is set to the stringified JS asset path to remove the need for // migrations when hydrating. if (!this.hasWindow) { return reducers; } const prefix = "breezy"; const persistKey = prefix + this.props.initialPage.assets .filter((asset) => asset.endsWith(".js")) .join(","); const persistConfig = { key: persistKey, storage, }; // Remove older storage items that were used by previous JS assets if (this.hasWindow) { const storedKeys = Object.keys(localStorage); storedKeys.forEach((key) => { if (key.startsWith(`persist:${prefix}`) && key !== persistKey) { localStorage.removeItem(key); } }); } return persistReducer(persistConfig, reducers); } }
features/apimgt/org.wso2.carbon.apimgt.admin.feature/src/main/resources/admin/source/src/app/components/Base/Loading/Loading.js
dewmini/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react' import PropTypes from 'prop-types' import {Spin, Row, Col} from 'antd' const LoadingAnimation = (props) => { return ( <Row type="flex" justify="center" align="middle"> <Col span={24} style={{textAlign: "center"}}> <Spin spinning={true} size="large"/> </Col> </Row> ); }; LoadingAnimation.propTypes = { message: PropTypes.string }; LoadingAnimation.defaultProps = { message: "Loading . . ." }; export default LoadingAnimation
components/time_picker/ClockHours.js
KerenChandran/react-toolbox
import React from 'react'; import utils from '../utils/utils'; import Face from './ClockFace'; import Hand from './ClockHand'; const outerNumbers = [0, ...utils.range(13, 24)]; const innerNumbers = [12, ...utils.range(1, 12)]; const innerSpacing = 1.7; const step = 360 / 12; class Hours extends React.Component { static propTypes = { center: React.PropTypes.object, format: React.PropTypes.oneOf(['24hr', 'ampm']), onChange: React.PropTypes.func, onHandMoved: React.PropTypes.func, radius: React.PropTypes.number, selected: React.PropTypes.number, spacing: React.PropTypes.number }; state = { inner: this.props.format === '24hr' && this.props.selected > 0 && this.props.selected <= 12 }; handleHandMove = (degrees, radius) => { const currentInner = radius < this.props.radius - this.props.spacing * innerSpacing; if (this.props.format === '24hr' && this.state.inner !== currentInner) { this.setState({inner: currentInner}, () => { this.props.onChange(this.valueFromDegrees(degrees)); }); } else { this.props.onChange(this.valueFromDegrees(degrees)); } }; handleMouseDown = (event) => { this.refs.hand.mouseStart(event); }; handleTouchStart = (event) => { this.refs.hand.touchStart(event); }; valueFromDegrees (degrees) { if (this.props.format === 'ampm' || this.props.format === '24hr' && this.state.inner) { return innerNumbers[degrees / step]; } else { return outerNumbers[degrees / step]; } } renderInnerFace (innerRadius) { if (this.props.format === '24hr') { return ( <Face onTouchStart={this.handleTouchStart} onMouseDown={this.handleMouseDown} numbers={innerNumbers} spacing={this.props.spacing} radius={innerRadius} active={this.props.selected} /> ); } } render () { const { format, selected, radius, spacing, center, onHandMoved } = this.props; const is24hr = format === '24hr'; return ( <div> <Face onTouchStart={this.handleTouchStart} onMouseDown={this.handleMouseDown} numbers={is24hr ? outerNumbers : innerNumbers} spacing={spacing} radius={radius} twoDigits={is24hr} active={is24hr ? selected : (selected % 12 || 12)} /> {this.renderInnerFace(radius - spacing * innerSpacing)} <Hand ref='hand' angle={selected * step} length={(this.state.inner ? radius - spacing * innerSpacing : radius) - spacing} onMove={this.handleHandMove} onMoved={onHandMoved} origin={center} step={step} /> </div> ); } } export default Hours;
fields/types/localfile/LocalFileField.js
matthieugayon/keystone
import Field from '../Field'; import React from 'react'; import ReactDOM from 'react-dom'; import { Button, FormField, FormInput, FormNote } from 'elemental'; module.exports = Field.create({ shouldCollapse () { return this.props.collapse && !this.hasExisting(); }, fileFieldNode () { return ReactDOM.findDOMNode(this.refs.fileField); }, changeFile () { this.fileFieldNode().click(); }, getFileSource () { if (this.hasLocal()) { return this.state.localSource; } else if (this.hasExisting()) { return this.props.value.url; } else { return null; } }, getFileURL () { if (!this.hasLocal() && this.hasExisting()) { return this.props.value.url; } }, undoRemove () { this.fileFieldNode().value = ''; this.setState({ removeExisting: false, localSource: null, origin: false, action: null, }); }, fileChanged (event) { // eslint-disable-line no-unused-vars this.setState({ origin: 'local', }); }, removeFile (e) { var state = { localSource: null, origin: false, }; if (this.hasLocal()) { this.fileFieldNode().value = ''; } else if (this.hasExisting()) { state.removeExisting = true; if (this.props.autoCleanup) { if (e.altKey) { state.action = 'reset'; } else { state.action = 'delete'; } } else { if (e.altKey) { state.action = 'delete'; } else { state.action = 'reset'; } } } this.setState(state); }, hasLocal () { return this.state.origin === 'local'; }, hasFile () { return this.hasExisting() || this.hasLocal(); }, hasExisting () { return this.props.value && !!this.props.value.filename; }, getFilename () { if (this.hasLocal()) { return this.fileFieldNode().value.split('\\').pop(); } else { return this.props.value.filename; } }, renderFileDetails (add) { var values = null; if (this.hasFile() && !this.state.removeExisting) { values = ( <div className="file-values"> <FormInput noedit>{this.getFilename()}</FormInput> </div> ); } return ( <div key={this.props.path + '_details'} className="file-details"> {values} {add} </div> ); }, renderAlert () { if (this.hasLocal()) { return ( <div className="file-values upload-queued"> <FormInput noedit>File selected - save to upload</FormInput> </div> ); } else if (this.state.origin === 'cloudinary') { return ( <div className="file-values select-queued"> <FormInput noedit>File selected from Cloudinary</FormInput> </div> ); } else if (this.state.removeExisting) { return ( <div className="file-values delete-queued"> <FormInput noedit>File {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</FormInput> </div> ); } else { return null; } }, renderClearButton () { if (this.state.removeExisting) { return ( <Button type="link" onClick={this.undoRemove}> Undo Remove </Button> ); } else { var clearText; if (this.hasLocal()) { clearText = 'Cancel Upload'; } else { clearText = (this.props.autoCleanup ? 'Delete File' : 'Remove File'); } return ( <Button type="link-cancel" onClick={this.removeFile}> {clearText} </Button> ); } }, renderFileField () { if (!this.shouldRenderField()) return null; return <input ref="fileField" type="file" name={this.props.paths.upload} className="field-upload" onChange={this.fileChanged} tabIndex="-1" />; }, renderFileAction () { if (!this.shouldRenderField()) return null; return <input type="hidden" name={this.props.paths.action} className="field-action" value={this.state.action} />; }, renderFileToolbar () { return ( <div key={this.props.path + '_toolbar'} className="file-toolbar"> <div className="u-float-left"> <Button onClick={this.changeFile}> {this.hasFile() ? 'Change' : 'Upload'} File </Button> {this.hasFile() && this.renderClearButton()} </div> </div> ); }, renderNote () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { var container = []; var body = []; var hasFile = this.hasFile(); if (this.shouldRenderField()) { if (hasFile) { container.push(this.renderFileDetails(this.renderAlert())); } body.push(this.renderFileToolbar()); } else { if (hasFile) { container.push(this.renderFileDetails()); } else { container.push(<FormInput noedit>no file</FormInput>); } } return ( <FormField label={this.props.label} className="field-type-localfile" htmlFor={this.props.path}> {this.renderFileField()} {this.renderFileAction()} <div className="file-container">{container}</div> {body} {this.renderNote()} </FormField> ); }, });
client/views/edit_seq.js
visipedia/annotation_tools
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap'; import {KEYS} from '../utils.js'; /** * Edit a sequence of images. Unlike task_seq.js, this will load and save data to the server each time, * rather than saving state. */ export class EditSequence extends React.Component { constructor(props) { super(props); this.state = { imageIndex : -1, fetchingData : true }; this.prevImage = this.prevImage.bind(this); this.nextImage = this.nextImage.bind(this); this.finish = this.finish.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); } componentDidMount(){ document.addEventListener("keydown", this.handleKeyDown); if(this.props.imageIds.length > 0){ let nextImageId = this.props.imageIds[0]; // Get the data for the next image. this.getImageData(nextImageId, (imageData)=>{ // Render the next image this.setState(function(prevState, props){ return { imageIndex : 0, image : imageData.image, annotations : imageData.annotations, fetchingData : false } }); }, ()=>{ alert("Failed to load image data"); }); } this.setState({ fetchingData : true }); } componentWillUnmount(){ document.removeEventListener("keydown", this.handleKeyDown); } handleKeyDown(e){ switch(e.keyCode){ case KEYS.SPACE: this.nextImage(); break; case KEYS.LEFT_ARROW: this.prevImage(); break; case KEYS.RIGHT_ARROW: this.nextImage(); break } } getImageData(imageId, onSuccess, onFail){ let endpoint = "/edit_image/" + imageId; $.ajax({ url : endpoint, method : 'GET' }).done(function(data){ onSuccess(data); }).fail(function(jqXHR, textStatus, errorThrown ){ console.log(textStatus); onFail(); }); } prevImage(){ if(this.state.fetchingData){ return; } if(this.state.imageIndex == 0){ return; } else{ // Get the next image id let nextImageId = this.props.imageIds[this.state.imageIndex - 1]; // Save the annotations from the current image this.taskViewRef.performSave(()=>{ // Get the data for the next image. this.getImageData(nextImageId, (imageData)=>{ // Render the next image this.setState(function(prevState, props){ return { imageIndex : prevState.imageIndex - 1, image : imageData.image, annotations : imageData.annotations, fetchingData : false } }); }, ()=>{ alert("Failed to load image data"); }); }, ()=>{ alert("Failed to save image data"); }); this.setState({ fetchingData : true }); } } nextImage(){ if(this.state.fetchingData){ return; } if(this.state.imageIndex == this.props.imageIds.length - 1){ return; } else{ // Get the next image id let nextImageId = this.props.imageIds[this.state.imageIndex + 1]; // Save the annotations from the current image this.taskViewRef.performSave(()=>{ // Get the data for the next image. this.getImageData(nextImageId, (imageData)=>{ // Render the next image this.setState(function(prevState, props){ return { imageIndex : prevState.imageIndex + 1, image : imageData.image, annotations : imageData.annotations, fetchingData : false } }); }, ()=>{ alert("Failed to load image data"); }); }, ()=>{ alert("Failed to save image data"); }); this.setState({ fetchingData : true }); } } finish(){ this.props.onFinish(); } render() { if(this.state.fetchingData){ return ( <div> Loading Image </div> ); } // feedback for the user let current_image = this.state.imageIndex + 1; let num_images = this.props.imageIds.length; // Determine which buttons we should render var buttons = [] if(this.state.imageIndex > 0){ buttons.push( (<button key="prevButton" type="button" className="btn btn-outline-secondary" onClick={this.prevImage}>Prev</button>) ); } if(this.state.imageIndex < num_images - 1){ buttons.push( (<button key="nextButton" type="button" className="btn btn-outline-secondary" onClick={this.nextImage}>Next</button>) ); } if(this.state.imageIndex == num_images - 1){ buttons.push( (<button key="finishButton" type="button" className="btn btn-outline-success" onClick={this.finish}>Finish</button>) ); } return ( <div> <div className="row"> <div className="col"> <this.props.taskView ref={ e => { this.taskViewRef = e; }} image={this.state.image} annotations={this.state.annotations} categories={this.props.categories} key={this.state.imageIndex} /> </div> </div> <nav className="navbar fixed-bottom navbar-light bg-light"> <div className="ml-auto"> <div className="btn-group" role="group"> {buttons} </div> <span> Image {current_image} / {num_images} </span> </div> <div className="ml-auto"> </div> </nav> </div> ) } } EditSequence.defaultProps = { imageIds : [], // Array of image ids onFinish : null, // a function to call when the image sequence is finished. categories : null // Categories array, };
src/documentation/Favicons/FaviconGenerator.js
wfp/ui
/* eslint-disable jsx-a11y/label-has-associated-control */ /* eslint-disable no-console */ import React, { Component } from 'react'; import Button from '../../components/Button'; import TextInput from '../../components/TextInput'; import { Module, ModuleBody } from '../../components/Module'; import ReduxFormWrapper from '../../components/ReduxFormWrapper'; import { Form, Field } from 'react-final-form'; import { Package } from './favicon/favicon.js'; import centerjs from './favicon/center'; import colors from '../../globals/data/colors.js'; const canvas = { width: 128, height: 128, }; class FaviconCanvas extends React.Component { componentDidMount() { this.updateCanvas(); } componentDidUpdate() { this.updateCanvas(); } updateCanvas() { const context = this.refs.canvas.getContext('2d'); context.clearRect(0, 0, 300, 300); var mainColor = colors.main.hex; const name = this.props.name && this.props.name.length >= 1 ? this.props.name : '–'; centerjs({ canvas: this.refs.canvas, width: canvas.width, height: canvas.height, shape: 'square', fontColor: '#ffffff', backgroundColor: mainColor, text: name.toUpperCase(), fontFamily: 'Open Sans', fontWeight: 'bold', fontSize: 15 + (120 * 1) / name.length, }); } download = () => { const canvas = document.getElementById('canvas'); const dataurl = Package.generate(canvas); //const dataurl = ico.generate([16, 32, 48]); this.props.updateUrl(dataurl); }; render() { return <canvas id="canvas" ref="canvas" width={128} height={128} />; } } const onSubmit = async (values) => { window.alert(JSON.stringify(values, 0, 2)); }; export default class FaviconGenerator extends Component { constructor(props) { super(props); this.child = React.createRef(); this.state = { dataurl: {} }; } onClick = () => { this.child.current.download(); }; updateUrl = (dataurl) => { this.setState({ dataurl: dataurl, }); }; render() { const buttonElements = Object.keys(this.state.dataurl).map((file, i) => ( <React.Fragment> <Button download={`wfp-favicon-${file}.${file.substring(0, 3)}`} kind="secondary" small href={this.state.dataurl[file]}> {file} </Button>{' '} </React.Fragment> )); return ( <div> <Form onSubmit={onSubmit} initialValues={{ name: 'WFP', }} render={({ handleSubmit, form, submitting, pristine, values }) => ( <form onSubmit={handleSubmit}> <Module light className="some-class" style={{ padding: '1em 0' }}> <ModuleBody> <div style={{ display: 'flex', justifyContent: 'space-between', }}> <div className="wfp--form-long"> <Field name="name" component={ReduxFormWrapper} inputComponent={TextInput} type="text" labelText="Acronym" helperText="Abbreviation of the applications name, like: WSS, WFP, INFO" placeholder="WFP" /> <div className="wfp--form-item"> <Button onClick={this.onClick}>Generate files</Button> </div> <div style={{ marginBottom: '1rem' }}> {Object.keys(this.state.dataurl).length > 0 && ( <React.Fragment> <h4>Download</h4> {buttonElements} </React.Fragment> )} </div> </div> <div> <label className="wfp--label">Preview</label> <br /> <FaviconCanvas updateUrl={this.updateUrl} {...values} ref={this.child} /> </div> </div> </ModuleBody> </Module> </form> )} /> </div> ); } }
src/app/common/UserInterface/components/Text.js
toxzilla/app
import React from 'react'; import shallowCompare from 'react-addons-shallow-compare'; export default class Text extends React.Component { static displayName = 'Text' static propTypes = { l10n: React.PropTypes.object.isRequired, id: React.PropTypes.string, className: React.PropTypes.string, onTranslate: React.PropTypes.func } shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } render () { const { id, className, l10n } = this.props; return ( <span id={id} className={className} data-l10n-id={l10n ? l10n.id : null} data-l10n-args={l10n.args ? JSON.stringify(l10n.args) : null} data-l10n-with={l10n.bundle ? l10n.bundle : null}> {this.props.children ? this.props.children : String.fromCharCode(160) } </span> ); } }
app/javascript/mastodon/features/getting_started/index.js
rekif/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, invitesEnabled, version } from '../../initial_state'; import { fetchFollowRequests } from '../../actions/accounts'; import { List as ImmutableList } from 'immutable'; import { Link } from 'react-router-dom'; import NavigationBar from '../compose/components/navigation_bar'; const messages = defineMessages({ home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' }, community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' }, personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' }, security: { id: 'navigation_bar.security', defaultMessage: 'Security' }, menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, }); const mapStateToProps = state => ({ myAccount: state.getIn(['accounts', me]), unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size, }); const mapDispatchToProps = dispatch => ({ fetchFollowRequests: () => dispatch(fetchFollowRequests()), }); const badgeDisplay = (number, limit) => { if (number === 0) { return undefined; } else if (limit && number >= limit) { return `${limit}+`; } else { return number; } }; export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class GettingStarted extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, myAccount: ImmutablePropTypes.map.isRequired, columns: ImmutablePropTypes.list, multiColumn: PropTypes.bool, fetchFollowRequests: PropTypes.func.isRequired, unreadFollowRequests: PropTypes.number, unreadNotifications: PropTypes.number, }; componentDidMount () { const { myAccount, fetchFollowRequests } = this.props; if (myAccount.get('locked')) { fetchFollowRequests(); } } render () { const { intl, myAccount, multiColumn, unreadFollowRequests } = this.props; const navItems = []; let i = 1; let height = (multiColumn) ? 0 : 60; if (multiColumn) { navItems.push( <ColumnSubheading key={i++} text={intl.formatMessage(messages.discover)} />, <ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />, <ColumnLink key={i++} icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />, <ColumnSubheading key={i++} text={intl.formatMessage(messages.personal)} /> ); height += 34*2 + 48*2; } navItems.push( <ColumnLink key={i++} icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />, <ColumnLink key={i++} icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />, <ColumnLink key={i++} icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' /> ); height += 48*3; if (myAccount.get('locked')) { navItems.push(<ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />); height += 48; } if (!multiColumn) { navItems.push( <ColumnSubheading key={i++} text={intl.formatMessage(messages.settings_subheading)} />, <ColumnLink key={i++} icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />, ); height += 34 + 48; } return ( <Column label={intl.formatMessage(messages.menu)}> {multiColumn && <div className='column-header__wrapper'> <h1 className='column-header'> <button> <i className='fa fa-bars fa-fw column-header__icon' /> <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' /> </button> </h1> </div>} <div className='getting-started'> <div className='getting-started__wrapper' style={{ height }}> {!multiColumn && <NavigationBar account={myAccount} />} {navItems} </div> {!multiColumn && <div className='flex-spacer' />} <div className='getting-started__footer'> <ul> <li><a href='https://bridge.joinmastodon.org/' target='_blank'><FormattedMessage id='getting_started.find_friends' defaultMessage='Find friends from Twitter' /></a> · </li> {invitesEnabled && <li><a href='/invites' target='_blank'><FormattedMessage id='getting_started.invite' defaultMessage='Invite people' /></a> · </li>} {multiColumn && <li><Link to='/keyboard-shortcuts'><FormattedMessage id='navigation_bar.keyboard_shortcuts' defaultMessage='Hotkeys' /></Link> · </li>} <li><a href='/auth/edit'><FormattedMessage id='getting_started.security' defaultMessage='Security' /></a> · </li> <li><a href='/about/more' target='_blank'><FormattedMessage id='navigation_bar.info' defaultMessage='About this instance' /></a> · </li> <li><a href='https://joinmastodon.org/apps' target='_blank'><FormattedMessage id='navigation_bar.apps' defaultMessage='Mobile apps' /></a> · </li> <li><a href='/terms' target='_blank'><FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /></a> · </li> <li><a href='/settings/applications' target='_blank'><FormattedMessage id='getting_started.developers' defaultMessage='Developers' /></a> · </li> <li><a href='https://docs.joinmastodon.org' target='_blank'><FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' /></a> · </li> <li><a href='/auth/sign_out' data-method='delete'><FormattedMessage id='navigation_bar.logout' defaultMessage='Logout' /></a></li> </ul> <p> <FormattedMessage id='getting_started.open_source_notice' defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.' values={{ github: <span><a href='https://github.com/tootsuite/mastodon' rel='noopener' target='_blank'>tootsuite/mastodon</a> (v{version})</span> }} /> </p> </div> </div> </Column> ); } }
src/modules/RenderHtmlLayout.js
janoist1/universal-react-redux-starter-kit
import React from 'react' import server from 'react-dom/server' /** * Render the HTML layout * * @param head * @param body & scripts * @param resolverPayload * @returns {string} */ export function renderHtmlLayout(head, body, resolverPayload = {}) { return '<!DOCTYPE html>' + (0, server.renderToStaticMarkup)(React.createElement( 'html', head.htmlAttributes.toComponent(), React.createElement( 'head', null, head.title.toComponent(), head.meta.toComponent(), head.base.toComponent(), head.link.toComponent(), head.script.toComponent(), head.style.toComponent(), React.createElement( 'script', { dangerouslySetInnerHTML: {__html: `__REACT_RESOLVER_PAYLOAD__=${JSON.stringify(resolverPayload)}`} } ) ), React.createElement( 'body', null, body ) )); }
components/publication/datasets.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import {sortBy, deburr} from 'lodash' import LoadingIcon from 'react-icons/lib/fa/refresh' import Box from '../box' import Link from '../link' import Button from '../button' class Datasets extends React.Component { static propTypes = { published: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, remoteUrl: PropTypes.string.isRequired })).isRequired, notPublished: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired, title: PropTypes.string.isRequired })).isRequired, publishedByOthers: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, remoteUrl: PropTypes.string.isRequired })).isRequired, publishDatasets: PropTypes.func.isRequired } state = { toPublish: [], publishing: false, almostPublished: [] } toggleSelect = dataset => () => { this.setState(state => { const without = state.toPublish.filter(d => d !== dataset._id) if (without.length !== state.toPublish.length) { return { toPublish: without } } return { toPublish: [ ...state.toPublish, dataset._id ] } }) } toggleSelectAll = () => { const {notPublished} = this.props this.setState(state => { if (state.toPublish.length === notPublished.length) { return { toPublish: [] } } return { toPublish: notPublished.map(dataset => dataset._id) } }) } publishDatasets = async () => { const {publishDatasets, notPublished} = this.props const {toPublish} = this.state this.setState({ publishing: true }) await publishDatasets(toPublish) const almostPublished = toPublish.map(id => notPublished.find(d => d._id === id)).filter(d => d) this.setState(state => ({ publishing: false, toPublish: [], almostPublished: [ ...state.almostPublished, ...almostPublished ] })) } render() { const {published, notPublished, publishedByOthers} = this.props const {publishing, toPublish, almostPublished} = this.state const allSelected = toPublish.length === notPublished.length const sortedPublished = sortBy(published, ({title}) => deburr(title)) const sortedNotPublished = sortBy(notPublished, ({title}) => deburr(title)) const sortedPublishedByOthers = sortBy(publishedByOthers, ({title}) => deburr(title)) return ( <div> <Box color='blue' padded={false} title={ <div className='title'> <div> Données en attente de publication </div> <div>{sortedNotPublished.length}</div> </div> } > {sortedNotPublished.length > 0 ? ( <> {sortedNotPublished.map(dataset => ( <div key={dataset._id} className='row' onClick={publishing ? null : this.toggleSelect(dataset)}> <div> <Link href={`/dataset?did=${dataset._id}`} as={`/datasets/${dataset._id}`}> <a> {dataset.title} </a> </Link> </div> <div> <input type='checkbox' checked={toPublish.includes(dataset._id)} disabled={publishing} onChange={() => {/* handled by div onClick handler */}} /> </div> </div> ))} <div className='row'> <div> <Button disabled={!toPublish.length || publishing} onClick={this.publishDatasets}> {publishing ? ( <> <LoadingIcon style={{verticalAlign: -2}} /> Publication… </> ) : 'Publier les données sélectionnées'} </Button> </div> <div> <Button color='white' disabled={publishing} onClick={this.toggleSelectAll}> {allSelected ? 'Tout désélectionner' : 'Tout sélectionner'} </Button> </div> </div> </> ) : ( <div className='row'> <i>Aucun jeu de données en attente de publication.</i> </div> )} </Box> {almostPublished.length > 0 && ( <Box color='yellow' padded={false} title={ <div className='title blue'> <div> Données en cours de publication </div> <div> {almostPublished.length} </div> </div> } > {almostPublished.map(dataset => ( <div key={dataset._id} className='row'> <div> <Link href={`/dataset?did=${dataset._id}`} as={`/datasets/${dataset._id}`}> <a> {dataset.title} </a> </Link> </div> <div> <i>En cours de publication…</i> </div> </div> ))} </Box> )} <Box color='green' padded={false} title={ <div className='title blue'> <div> Données publiées </div> <div>{sortedPublished.length}</div> </div> } > {sortedPublished.length > 0 ? sortedPublished.map(dataset => ( <div key={dataset._id} className='row'> <div> <Link href={`/dataset?did=${dataset._id}`} as={`/datasets/${dataset._id}`}> <a> {dataset.title} </a> </Link> </div> <div> <a href={dataset.remoteUrl}> Fiche data.gouv.fr </a> </div> </div> )) : ( <div className='row'> <i>Aucun jeu de données publié.</i> </div> )} </Box> <Box padded={false} title={ <div className='title'> <div> Données publiées par une autre organisation </div> <div>{sortedPublishedByOthers.length}</div> </div> } > {sortedPublishedByOthers.length > 0 ? sortedPublishedByOthers.map(dataset => ( <div key={dataset._id} className='row'> <div> <Link href={`/dataset?did=${dataset._id}`} as={`/datasets/${dataset._id}`}> <a> {dataset.title} </a> </Link> </div> <div> <a href={dataset.remoteUrl}> Fiche data.gouv.fr </a> </div> </div> )) : ( <div className='row'> <i>Aucun jeu de données publié par une autre organization.</i> </div> )} </Box> <style jsx>{` @import 'colors'; .title { display: flex; align-items: center; div:last-child { margin-left: auto; padding: 0 0.5em 0 1em; font-weight: 600; } small { display: block; margin-top: 0.2em; font-size: 0.9em; color: $grey; } &.blue small { color: lighten($blue, 35%); } } .row { display: flex; align-items: center; justify-content: space-between; padding: 0.8em 1em; border-bottom: 1px solid $whitesmoke; &:hover { background-color: $whitesmoke; } &:last-child { border-bottom: 0 none; } } i { color: $grey; } `}</style> </div> ) } } export default Datasets
src/CommentForm.js
JiLiZART/react-tutorial
'use strict'; import React from 'react'; export default React.createClass({ displayName: 'CommentForm', onSubmitHandler(e) { e.preventDefault(); this.handleSubmit(); return; }, handleSubmit() { var author = React.findDOMNode(this.refs.author).value.trim(); var text = React.findDOMNode(this.refs.text).value.trim(); if (!text || !author) { return; } this.props.onCommentSubmit({author: author, text: text}); React.findDOMNode(this.refs.author).value = ''; React.findDOMNode(this.refs.text).value = ''; }, render() { return ( <form className="form commentForm" onSubmit={this.onSubmitHandler}> <div className="form-group"> <input type="text" className="form-control" required placeholder="Your name" ref="author" /> </div> <textarea type="text" className="form-control" placeholder="Say something..." ref="text" ></textarea> <div className="form-group"> <input type="submit" className="btn btn-primary" value="Post" /> </div> </form> ); } });
src/components/header_page.js
kaloudiyi/VotePlexClient
// src/components/Header.js import React, { Component } from 'react'; import { Nav, Navbar, NavItem } from 'react-bootstrap'; import PropTypes from 'prop-types'; import history from '../history'; class HeaderPage extends Component { createPoll() { history.replace('/polladd'); } login() { this.props.auth.login(); } logout() { this.props.auth.logout(); } render() { const { isAuthenticated } = this.props.auth; return ( <Navbar fluid> <Navbar.Header> <Navbar.Brand> VotePlex Polls </Navbar.Brand> </Navbar.Header> { !isAuthenticated() && ( <Nav> <NavItem onClick={() => this.login()}> Login </NavItem> </Nav> ) } { isAuthenticated() && ( <Nav> <NavItem onClick={() => this.logout()}> Logout </NavItem> <NavItem onClick={() => this.createPoll()}> Create a Poll </NavItem> </Nav> ) } </Navbar> ); } } HeaderPage.propTypes = { auth: PropTypes.object.isRequired }; export default HeaderPage;
src/stories/Welcome.js
raavanan/jukebox
import React from 'react'; const styles = { main: { margin: 15, maxWidth: 600, lineHeight: 1.4, fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif', }, logo: { width: 200, }, link: { color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: 2, }, code: { fontSize: 15, fontWeight: 600, padding: "2px 5px", border: "1px solid #eae9e9", borderRadius: 4, backgroundColor: '#f3f2f2', color: '#3a3a3a', }, codeBlock: { backgroundColor: '#f3f2f2', padding: '1px 10px', margin: '10px 0', } }; const codeBlock = ` // Add this code to "src/stories/index.js" import '../index.css'; import App from '../App'; storiesOf('App', module) .add('default view', () => ( &lt;App /&gt; )) `; export default class Welcome extends React.Component { showApp(e) { e.preventDefault(); if(this.props.showApp) this.props.showApp(); } render() { return ( <div style={styles.main}> <h1>Welcome to STORYBOOK</h1> <p> This is a UI component dev environment for your app. </p> <p> We've added some basic stories inside the <code style={styles.code}>src/stories</code> directory. <br/> A story is a single state of one or more UI components. You can have as many stories as you want. <br/> (Basically a story is like a visual test case.) </p> <p> See these sample <a style={styles.link} href='#' onClick={this.showApp.bind(this)}>stories</a> for a component called <code style={styles.code}>Button</code>. </p> <p> Just like that, you can add your own components as stories. <br /> Here's how to add your <code style={styles.code}>App</code> component as a story. <div style={styles.codeBlock} dangerouslySetInnerHTML={{__html: `<pre>${codeBlock}</pre>`}} /> </p> <p> Usually we create stories with smaller UI components in the app.<br /> Have a look at the <a style={styles.link} href="https://getstorybook.io/docs/basics/writing-stories" target="_blank">Writing Stories</a> section in our documentation. </p> </div> ); } }
src/components/omnibar/Omnibar.js
ello/webapp
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import Editor from '../editor/Editor' import { ChevronIcon } from '../assets/Icons' import { css, hover, media, modifier } from '../../styles/jss' import * as s from '../../styles/jso' const omnibarStyle = css( s.relative, s.displayNone, s.pt30, s.bgcWhite, s.mxAuto, { maxWidth: 1440 }, modifier('.isActive', s.block), media(s.minBreak2, s.pt0), ) const revealButton = css( s.absolute, { top: 15, right: 10, width: 20 }, s.overflowHidden, s.fontSize14, s.nowrap, s.transitionWidth, hover({ width: 100 }), media(s.minBreak2, { top: -20, right: 20 }), media(s.minBreak4, { right: 40 }), ) export const Omnibar = ({ classList, isActive, isFullScreen, onClickCloseOmnibar }) => { if (!isActive) { return <div className={classNames(`Omnibar ${omnibarStyle}`, { isActive }, classList)} /> } return ( <div className={classNames(`Omnibar ${omnibarStyle}`, { isActive, isFullScreen }, classList)} > <Editor shouldPersist /> <button className={revealButton} onClick={onClickCloseOmnibar}> <ChevronIcon /> Navigation </button> </div> ) } Omnibar.propTypes = { classList: PropTypes.string, isActive: PropTypes.bool.isRequired, isFullScreen: PropTypes.bool, onClickCloseOmnibar: PropTypes.func.isRequired, } Omnibar.defaultProps = { classList: null, isFullScreen: false, } export default Omnibar
src/components/EventHeader/EventHeader.js
filipsuk/eventigoApp
/* @flow */ import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; import EventTags from '../EventTags'; import EventDate from '../EventDate'; import LinearGradient from 'react-native-linear-gradient'; import { fontSizes } from '../../styles'; import type { Event } from '../../types/model'; type Props = { event: Event }; const EventHeader = ({ event }: Props) => { return ( <LinearGradient colors={['transparent', 'rgba(0, 0, 0, 0.9)']}> <View style={styles.container}> <EventDate event={event} style={styles.date} /> <Text style={styles.title} numberOfLines={3} ellipsizeMode="tail"> {event.name} </Text> <EventTags tags={event.tags} numberOfLines={1} /> </View> </LinearGradient> ); }; const textShadow = { textShadowColor: '#000000', textShadowRadius: 4, textShadowOffset: { width: 0, height: 0 }, shadowOpacity: 0.5 }; const styles = StyleSheet.create({ container: { paddingHorizontal: 10, paddingBottom: 7, paddingTop: 70, backgroundColor: 'transparent' }, title: { color: '#FFFFFF', fontSize: fontSizes.h2, fontWeight: '300', ...textShadow }, date: { color: '#FFFFFF', fontSize: fontSizes.small, fontWeight: '300', ...textShadow } }); export default EventHeader;
src/components/icons/WindIcon.js
maximgatilin/weathernow
import React from 'react'; export default function WindIcon() { return ( <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 194.71 125.2"><title>wind</title><path d="M749,698.65h0c0-.25,0-0.5,0-0.75a36.25,36.25,0,1,0-72.51,0s0,0,0,.07a29.59,29.59,0,0,0,1.39,59.16H749A29.24,29.24,0,1,0,749,698.65Z" transform="translate(-648.27 -661.65)" fill="#42bfec"/><path d="M825.35,726.68H766.8a5,5,0,0,1,0-10h58.55a7.59,7.59,0,0,0,0-15.19h-7.44a5,5,0,1,1,0-10h7.44A17.64,17.64,0,0,1,825.35,726.68Z" transform="translate(-648.27 -661.65)" fill="#ade0f3"/><path d="M806.27,786.85a22.52,22.52,0,0,1-22.49-22.49,15.37,15.37,0,1,1,30.75,0v2.59a5,5,0,1,1-10,0v-2.59a5.33,5.33,0,1,0-10.66,0,12.44,12.44,0,0,0,24.89,0v-5.14a17,17,0,0,0-17-17H722.81a5,5,0,1,1,0-10H801.7a27.09,27.09,0,0,1,27.06,27.05v5.14A22.52,22.52,0,0,1,806.27,786.85Z" transform="translate(-648.27 -661.65)" fill="#ade0f3"/></svg> ) }
demo/src/index.js
FunctionFoundry/react-table-for-bootstrap
/** * Copyright (c) 2015, Peter W Moresi * */ import React from 'react'; import MyApp from './components/MyApp.js' React.render( <div className="container main"> <h1>Crayola Colors</h1> <MyApp /> </div>, document.body );
node_modules/react-icons/md/cake.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdCake = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m30 15c2.7 0 5 2.3 5 5v2.6c0 1.8-1.5 3.3-3.3 3.3-0.8 0-1.6-0.4-2.2-1l-3.6-3.6-3.6 3.6c-1.3 1.3-3.4 1.3-4.6 0l-3.6-3.6-3.6 3.6c-0.6 0.6-1.4 1-2.2 1-1.8 0-3.3-1.5-3.3-3.3v-2.6c0-2.7 2.3-5 5-5h8.4v-3.4h3.2v3.4h8.4z m-2.3 11.6c1.1 1.1 2.5 1.8 4 1.8 1.3 0 2.4-0.4 3.3-1.1v7.7c0 0.9-0.7 1.6-1.6 1.6h-26.8c-0.9 0-1.6-0.7-1.6-1.6v-7.7c0.9 0.7 2 1.1 3.3 1.1 1.5 0 3-0.7 4-1.8l1.8-1.8 1.8 1.8c2.2 2.2 6 2.2 8.2 0l1.8-1.8z m-7.7-16.6c-1.8 0-3.4-1.6-3.4-3.4 0-0.6 0.3-1.2 0.6-1.7l2.8-4.9 2.8 4.9c0.3 0.5 0.6 1.1 0.6 1.7 0 1.8-1.5 3.4-3.4 3.4z"/></g> </Icon> ) export default MdCake
app/components/ProblemExamples/index.js
zmora-agh/zmora-ui
/** * * ProblemExamples * */ import React from 'react'; import Paper from 'material-ui/Paper'; import Grid from 'material-ui/Grid'; import Typography from 'material-ui/Typography'; import Divider from 'material-ui/Divider'; import { FormattedMessage } from 'react-intl'; import { examplesPropType } from './constants'; import messages from './messages'; const DataElement = (props) => ( <Grid item xs={props.xs}> <Typography type="title" component="h2" gutterBottom>{props.desc}</Typography> <Paper style={{ padding: '8px 16px' }}> <pre>{ props.children }</pre> </Paper> </Grid> ); DataElement.propTypes = { xs: React.PropTypes.number.isRequired, desc: React.PropTypes.node.isRequired, children: React.PropTypes.node.isRequired, }; const createExample = (props) => ([ <Grid container style={{ padding: 24 }}> <DataElement xs={6} desc={<FormattedMessage {...messages.input} />}> {props.input} </DataElement> <DataElement xs={6} desc={<FormattedMessage {...messages.result} />}> {props.result} </DataElement> <DataElement xs={12} desc={<FormattedMessage {...messages.explanation} />}> {props.explanation} </DataElement> </Grid>, <Divider />, ]); function ProblemExamples(props) { return ( <div style={{ overflow: 'hidden' }}> {props.examples.map(createExample)} </div> ); } ProblemExamples.propTypes = { examples: examplesPropType, }; export default ProblemExamples;
imports/ui/pages/teams/NewTeam.js
KyneSilverhide/team-manager
import React from 'react'; import TeamEditor from '../../components/teams/TeamEditor.js'; const NewTeam = () => ( <div className="NewTeam"> <h4 className="page-header">Ajout d'une nouvelle équipe</h4> <TeamEditor /> </div> ); export default NewTeam;
src/client/components/devtools/index.js
kevinhikaruevans/uojs2
import React, { Component } from 'react'; import DevtoolsMap from 'component/devtools-map' import DevtoolsCursore from 'component/devtools-cursore' import style from './style' class Devtools extends Component { static displayName = '[component] devtools'; state = { x : localStorage.getItem('devtools-x') === 'true', y : localStorage.getItem('devtools-y') === 'true', sidebar : false, tool : null }; onClickChangePosition = (axis, value) => (e) => { e.preventDefault(); this.setState({ [axis] : value }, () => { localStorage.setItem(`devtools-${axis}`, value); }) }; onClickSidebar = (e) => { e.preventDefault(); this.setState({ sidebar : !this.state.sidebar }) }; onClickSelectTool = (tool) => (e) => { e.preventDefault(); if(this.state.tool === tool) { this.setState({ tool : null }) } else { this.setState({ tool }) } }; get elPositionTop() { if(!this.state.sidebar && !this.state.y) { return( <svg className={`${style['devtools__position']} ${style['devtools__position_top']}`} onClick={this.onClickChangePosition('y', true)} viewBox="0 0 512 512"> <path d="m495 236l-233-233c-4-4-11-4-15 0l-233 233c-4 4-4 11 0 15l73 74c4 4 11 4 15 0l90-81l0 257c0 6 5 11 11 11l106 0c6 0 11-5 11-11l0-257l87 81c4 4 10 4 14 0l74-74c2-2 3-4 3-7c0-3-1-6-3-8z m-81 66l-97-91c-3-3-8-3-12-2c-4 2-6 6-6 10l0 272l-86 0l0-271c0-5-2-8-6-10c-4-2-8-1-12 2l-100 91l-59-59l218-218l218 218z" /> </svg> ) } } get elPositionRight() { if(!this.state.sidebar && !this.state.x) { return( <svg className={`${style['devtools__position']} ${style['devtools__position_right']}`} onClick={this.onClickChangePosition('x', true)} viewBox="0 0 512 512"> <path d="m509 248l-233-233c-4-4-11-4-15 0l-74 74c-4 4-4 11 0 15l82 88l-258 0c0 0 0 0 0 0c-3 0-6 1-8 3c-2 2-3 5-3 8l0 107c0 6 5 11 11 11l257 0l-81 87c-4 4-4 11 0 15l74 74c2 2 5 3 7 3c3 0 6-1 8-3l233-233c4-5 4-11 0-16z m-241 226l-58-59l91-98c3-3 3-7 2-11c-2-4-6-6-10-6l-272 0l0-87l273 1l0 0c4 0 8-3 10-7c1-4 1-8-2-11l-92-99l58-59l218 218z" /> </svg> ) } } get elPositionBottom() { if(!this.state.sidebar && this.state.y) { return( <svg className={`${style['devtools__position']} ${style['devtools__position_bottom']}`} onClick={this.onClickChangePosition('y', false)} viewBox="0 0 512 512"> <path d="m497 261l-74-74c-4-4-11-4-15 0l-87 81l0-257c0-6-5-11-11-11l-107 0c-6 0-10 5-10 11l0 258l-89-82c-4-4-11-4-15 0l-74 74c-4 4-4 11 0 15l233 233c2 2 5 3 8 3c3 0 6-1 8-3l233-233c4-4 4-11 0-15z m-241 225l-218-218l59-59l99 92c3 3 8 3 12 2c3-2 6-6 6-10l0-272l85 0l0 271c0 5 3 9 7 10c4 2 8 1 11-2l98-90l59 58z" /> </svg> ) } } get elPositionLeft() { if(!this.state.sidebar && this.state.x) { return( <svg className={`${style['devtools__position']} ${style['devtools__position_left']}`} onClick={this.onClickChangePosition('x', false)} viewBox="0 0 512 512"> <path d="m509 195c-2-2-4-3-7-3l-260 0l83-88c4-4 4-11 0-15l-74-74c-4-4-11-4-15 0l-233 233c-4 5-4 11 0 16l233 233c2 2 5 3 7 3c3 0 6-1 8-3l74-74c4-4 4-11 0-15l-82-87l258 0c6 0 11-5 11-11l0-107c0-3-1-5-3-8z m-19 105l-271 0c-4 0-8 2-10 6c-2 4-1 9 2 12l91 97l-59 59l-218-218l218-218l59 59l-92 99c-3 3-4 7-2 11c2 4 6 7 10 7l273 0z" /> </svg> ) } } elSidebarItem = (label, code) => { return <li className={style['devtools__sidebar-item']} onClick={this.onClickSelectTool(code)} data-active={this.state.tool === code}>{label}</li> }; get elSidebar() { if(this.state.sidebar) { return( <ul className={style['devtools__sidebar']}> {this.elSidebarItem('Cursore corrector', 'cursore')} {this.elSidebarItem('Map', 'map')} </ul> ) } } get elTool() { switch(this.state.tool) { case 'map': return <DevtoolsMap />; break; case 'cursore': return <DevtoolsCursore />; break; } } get elToolContainer() { if(this.state.sidebar && this.state.tool) { return <div className={style['devtools__tool']} data-x={this.state.x}>{this.elTool}</div> } } render() { return( <div className={style['devtools']} data-x={this.state.x} data-y={this.state.y}> {this.elSidebar} <div className={style['devtools__toggle']} data-status={this.state.sidebar}> <svg className={style['devtools__button']} onClick={this.onClickSidebar} viewBox="0 0 512 512"> <path d="m501 299l-43 0c-1-22-6-43-13-62l39-18c6-2 8-8 6-14-3-5-9-8-14-5l-40 17c-3-6-6-12-10-18-1-1-2-3-3-4-19-27-44-50-73-65 12-13 21-28 27-45 22-2 39-20 39-42 0-24-19-43-43-43-23 0-42 19-42 43 0 17 10 31 24 38-6 15-15 28-26 39-23-8-47-13-73-13-26 0-50 5-73 13-11-11-20-24-26-39 14-7 24-21 24-38 0-24-19-43-42-43-24 0-43 19-43 43 0 22 17 40 39 42 6 17 15 32 27 45-29 15-54 38-73 65-1 1-2 3-3 4-4 6-7 12-10 18l-40-17c-5-3-11 0-14 5-2 6 0 12 6 14l39 18c-7 19-12 40-13 62l-43 0c-6 0-11 4-11 10 0 6 5 11 11 11l43 0c1 24 6 47 15 68l-38 19c-5 3-8 9-5 15 2 3 6 6 10 6 1 0 3-1 4-2l39-18c35 62 101 104 177 104 76 0 142-42 177-104l39 18c1 1 3 2 4 2 4 0 8-3 10-6 3-6 0-12-5-15l-38-19c9-21 14-44 15-68l43 0c6 0 11-5 11-11 0-6-5-10-11-10z m-128-278c12 0 22 10 22 22 0 11-10 21-22 21-11 0-21-10-21-21 0-12 10-22 21-22z m-256 22c0-12 10-22 22-22 11 0 21 10 21 22 0 11-10 21-21 21-12 0-22-10-22-21z m139 85c55 0 105 25 138 64l-276 0c33-39 83-64 138-64z m-181 181c0-35 10-68 27-96l143 0 0 277c-95-5-170-84-170-181z m192 181l0-277 143 0c17 28 27 61 27 96 0 97-75 176-170 181z" /> </svg> {this.elPositionTop} {this.elPositionRight} {this.elPositionBottom} {this.elPositionLeft} </div> {this.elToolContainer} </div> ) } } export { Devtools as default, style };
es/components/sidebar/panel.js
cvdlab/react-planner
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; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; import * as SharedStyle from '../../shared-style'; import { FaAngleDown, FaAngleUp } from 'react-icons/fa'; var STYLE = { borderTop: '1px solid #222', borderBottom: '1px solid #48494E', userSelect: 'none' }; var STYLE_TITLE = { fontSize: '11px', color: SharedStyle.PRIMARY_COLOR.text_alt, padding: '5px 15px 8px 15px', backgroundColor: SharedStyle.PRIMARY_COLOR.alt, textShadow: '-1px -1px 2px rgba(0, 0, 0, 1)', boxShadow: 'inset 0px -3px 19px 0px rgba(0,0,0,0.5)', margin: '0px', cursor: 'pointer' }; var STYLE_CONTENT = { fontSize: '11px', color: SharedStyle.PRIMARY_COLOR.text_alt, border: '1px solid #222', padding: '0px', backgroundColor: SharedStyle.PRIMARY_COLOR.alt, textShadow: '-1px -1px 2px rgba(0, 0, 0, 1)' }; var STYLE_ARROW = { float: 'right' }; var Panel = function (_Component) { _inherits(Panel, _Component); function Panel(props, context) { _classCallCheck(this, Panel); var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props, context)); _this.state = { opened: props.hasOwnProperty('opened') ? props.opened : false, hover: false }; return _this; } _createClass(Panel, [{ key: 'toggleOpen', value: function toggleOpen() { this.setState({ opened: !this.state.opened }); } }, { key: 'toggleHover', value: function toggleHover() { this.setState({ hover: !this.state.hover }); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, name = _props.name, headComponents = _props.headComponents, children = _props.children; var _state = this.state, opened = _state.opened, hover = _state.hover; return React.createElement( 'div', { style: STYLE }, React.createElement( 'h3', { style: _extends({}, STYLE_TITLE, { color: hover ? SharedStyle.SECONDARY_COLOR.main : SharedStyle.PRIMARY_COLOR.text_alt }), onMouseEnter: function onMouseEnter() { return _this2.toggleHover(); }, onMouseLeave: function onMouseLeave() { return _this2.toggleHover(); }, onClick: function onClick() { return _this2.toggleOpen(); } }, name, headComponents, opened ? React.createElement(FaAngleUp, { style: STYLE_ARROW }) : React.createElement(FaAngleDown, { style: STYLE_ARROW }) ), React.createElement( 'div', { style: _extends({}, STYLE_CONTENT, { display: opened ? 'block' : 'none' }) }, children ) ); } }]); return Panel; }(Component); export default Panel; Panel.propTypes = { name: PropTypes.string.isRequired, headComponents: PropTypes.array, opened: PropTypes.bool };
src/views/main/routes.js
zanph/board
import React from 'react' import {Route, IndexRoute} from 'react-router' import Main from './Main' import Container from './Container' import CommentBox from 'components/CommentBox/CommentBox' import Landing from 'components/Landing/Landing' export const makeMainRoutes = () => { return ( <Route path="/" component={Main}> <IndexRoute component={Landing} /> <Route path=":boardID" component={Container} /> </Route> ) } export default makeMainRoutes
webpack/scenes/Subscriptions/components/SubscriptionsTable/components/Dialogs/DeleteDialog.js
mccun934/katello
import React from 'react'; import PropTypes from 'prop-types'; import { MessageDialog } from 'patternfly-react'; import { sprintf, translate as __ } from 'foremanReact/common/I18n'; const DeleteDialog = ({ show, selectedRows, onDeleteSubscriptions, onSubscriptionDeleteModalClose, }) => ( <MessageDialog show={show} title={__('Confirm Deletion')} secondaryContent={ // eslint-disable-next-line react/no-danger <p dangerouslySetInnerHTML={{ __html: sprintf( __(`Are you sure you want to delete %(entitlementCount)s subscription(s)? This action will remove the subscription(s) and refresh your manifest. All systems using these subscription(s) will lose them and also may lose access to updates and Errata.`), { entitlementCount: `<b>${selectedRows.length}</b>`, }, ), }} /> } primaryActionButtonContent={__('Delete')} primaryAction={() => onDeleteSubscriptions(selectedRows)} primaryActionButtonBsStyle="danger" secondaryActionButtonContent={__('Cancel')} secondaryAction={onSubscriptionDeleteModalClose} onHide={onSubscriptionDeleteModalClose} accessibleName="deleteConfirmationDialog" accessibleDescription="deleteConfirmationDialogContent" />); DeleteDialog.propTypes = { show: PropTypes.bool.isRequired, selectedRows: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ])).isRequired, onDeleteSubscriptions: PropTypes.func.isRequired, onSubscriptionDeleteModalClose: PropTypes.func.isRequired, }; export default DeleteDialog;
front/app/js/components/controls/containers/Module.js
nudoru/React-Starter-3
import React from 'react'; import PropTypes from 'prop-types'; import { css } from 'emotion'; import { metrics, modularScale, colorList } from '../../../theme/Theme'; import { Container } from './Container'; import { joinClasses } from '../../../utils/componentUtils'; const containerComponentStyle = css` width: 100%; min-height: 100%; display: flex; flex: 1; flex-direction: column; `; export const ModuleContainer = ({className, children}) => <div className={joinClasses(containerComponentStyle, className)}>{children}</div>; const moduleComponentStyle = props => css` display: flex; flex-direction: column; width: 100%; flex: ${props.full ? '1' : '0 1 auto'}; `; const contentContainerStyle = css` padding-top: ${modularScale.ms4}; padding-bottom: ${modularScale.ms4}; `; const flexContentContainerStyle = props => css` display: flex; flex-direction: column; align-items: ${props.middle ? 'center' : 'flex-start'}; justify-content: ${props.center ? 'center' : 'flex-start'}; flex: ${props.full ? 1 : 0}; `; export class Module extends React.PureComponent { static propTypes = { middle: PropTypes.bool, center: PropTypes.bool, full : PropTypes.bool }; static defaultProps = {}; _hasFlexProps = _ => { return this.props.middle || this.props.center || this.props.full; }; render () { const {className, children} = this.props; return ( <article className={joinClasses(moduleComponentStyle(this.props), className)}> <Container className={joinClasses(contentContainerStyle, (this._hasFlexProps()) ? flexContentContainerStyle(this.props) : null)}> {children} </Container> </article> ); } } const titleStyle = css` color: ${colorList.grey10}; font-size: ${modularScale.ms3}; margin-bottom: ${modularScale.ms5}; text-align: center; `; export const ModuleTitle = props => <h1 className={titleStyle}>{props.children}</h1>; const subTitleStyle = css` color: ${colorList.grey8}; line-height: 1.25rem; font-size: ${modularScale.ms0}; margin-top: -${modularScale.ms4}; margin-bottom: ${modularScale.ms5}; text-align: center; `; export const ModuleSubTitle = props => <h2 className={subTitleStyle}>{props.children}</h2>;
src/components/appbar.js
Rabbit884/reactapp
import React from 'react'; import AppBar from 'material-ui/AppBar'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import LinearProgress from 'material-ui/LinearProgress'; import { cyanA200 } from 'material-ui/styles/colors' import { Link } from 'react-router'; const titleName = [ { title: 'Home', link: '/' }, { title: 'Table', link: '/table' }, { title: 'Card', link: '/card' } ]; export default class AppBar_ extends React.Component { constructor (props) { super(props) this.state = { open: false } } handleTouchTap = () => {this.setState({open: !this.state.open})} closeDrawer = (x) => { this.setState({open: false}) this.props.setDisplay(x) } render() { const menuItems = titleName.map((item, i) => { return ( <MenuItem key={i} onTouchTap={this.closeDrawer.bind(this, i)} containerElement={<Link to={item.link} />} primaryText={item.title} /> ) }) return ( <div> <AppBar title={titleName[this.props.home.display].title} iconClassNameRight="muidocs-icon-navigation-expand-more" onLeftIconButtonTouchTap={this.handleTouchTap} /> <LinearProgress style={this.props.progress} mode="indeterminate" color={cyanA200} /> <Drawer open={this.state.open}> { menuItems } </Drawer> { this.props.children } </div> ) } }
pootle/static/js/admin/components/SearchBox.js
pavels/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import _ from 'underscore'; const SearchBox = React.createClass({ propTypes: { onSearch: React.PropTypes.func.isRequired, placeholder: React.PropTypes.string, searchQuery: React.PropTypes.string, }, /* Lifecycle */ getInitialState() { return { // XXX: review, prop should be explicitly named `initialSearchQuery` searchQuery: this.props.searchQuery, }; }, componentWillMount() { this.handleSearchDebounced = _.debounce(() => { this.props.onSearch.apply(this, [this.state.searchQuery]); }, 300); }, componentDidMount() { this.refs.input.focus(); }, componentWillReceiveProps(nextProps) { if (nextProps.searchQuery !== this.state.searchQuery) { this.setState({ searchQuery: nextProps.searchQuery }); } }, /* Handlers */ handleKeyUp(e) { const key = e.nativeEvent.keyCode; if (key === 27) { this.refs.input.blur(); } }, handleChange() { this.setState({ searchQuery: this.refs.input.value }); this.handleSearchDebounced(); }, /* Layout */ render() { return ( <input type="text" ref="input" value={this.state.searchQuery} onChange={this.handleChange} onKeyUp={this.handleKeyUp} {...this.props} /> ); }, }); export default SearchBox;
src/svg-icons/action/offline-pin.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOfflinePin = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z"/> </SvgIcon> ); ActionOfflinePin = pure(ActionOfflinePin); ActionOfflinePin.displayName = 'ActionOfflinePin'; ActionOfflinePin.muiName = 'SvgIcon'; export default ActionOfflinePin;
app/javascript/mastodon/features/list_editor/components/account.js
yi0713/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import { removeFromListEditor, addToListEditor } from '../../../actions/lists'; const messages = defineMessages({ remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId, added }) => ({ account: getAccount(state, accountId), added: typeof added === 'undefined' ? state.getIn(['listEditor', 'accounts', 'items']).includes(accountId) : added, }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { accountId }) => ({ onRemove: () => dispatch(removeFromListEditor(accountId)), onAdd: () => dispatch(addToListEditor(accountId)), }); export default @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl class Account extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onRemove: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, added: PropTypes.bool, }; static defaultProps = { added: false, }; render () { const { account, intl, onRemove, onAdd, added } = this.props; let button; if (added) { button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />; } else { button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />; } return ( <div className='account'> <div className='account__wrapper'> <div className='account__display-name'> <div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div> <DisplayName account={account} /> </div> <div className='account__relationship'> {button} </div> </div> </div> ); } }
src/components/FBLoginView.js
dbyilmaz/jobs
import React, { Component } from 'react'; import { StyleSheet,Text,View } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome' import { Button, SocialIcon } from 'react-native-elements'; class FBLoginView extends Component { static contextTypes = { isLoggedIn: React.PropTypes.bool, login: React.PropTypes.func, logout: React.PropTypes.func, props: React.PropTypes.object }; constructor(props) { super(props); } render(){ return ( <Button title="Logout" icon={{ name: 'loop' }} backgroundColor="crimson" buttonStyle={{ marginTop:10 }} onPress= { () => { this.context.logout() } }/> ) } } export default FBLoginView;
server/soman/frontend/app/components/sensors/EventHistory.js
bilgorajskim/soman
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; const styles = { radioButton: { marginTop: 16, }, }; /** * Dialog content can be scrollable. */ export default class EventHistory extends React.Component { handleClose = () => { this.props.onClose() }; render() { const actions = [ <FlatButton label="Zamknij" primary={true} keyboardFocused={true} onTouchTap={this.handleClose} /> ]; return ( <div> <Dialog title="Historia zdarzeń" actions={actions} modal={false} open={true} onRequestClose={this.handleClose} autoScrollBodyContent={true} > <Table> <TableHeader> <TableRow> <TableHeaderColumn>Data</TableHeaderColumn> <TableHeaderColumn>Zdarzenie</TableHeaderColumn> </TableRow> </TableHeader> <TableBody> {this.props.events.map(event => { let eventText = '' return <TableRow> <TableRowColumn>{moment(event.date).format('DD.MM.YYYY mm:ss')}</TableRowColumn> <TableRowColumn>{eventText}</TableRowColumn> </TableRow>; })} </TableBody> </Table> </Dialog> </div> ); } }
src/layouts/layout-4-5.js
nuruddeensalihu/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} {components[1]} {components[2]} </div> <div className="horizontal"> {components[3]} </div> </div> );
admin/client/App/screens/Item/components/RelatedItemsList.js
helloworld3q3q/keystone
import React from 'react'; import { Link } from 'react-router'; import { Columns } from 'FieldTypes'; import { Alert, Spinner } from 'elemental'; const RelatedItemsList = React.createClass({ propTypes: { list: React.PropTypes.object.isRequired, refList: React.PropTypes.object.isRequired, relatedItemId: React.PropTypes.string.isRequired, relationship: React.PropTypes.object.isRequired, }, getInitialState () { return { columns: this.getColumns(), err: null, items: null, }; }, componentDidMount () { this.loadItems(); }, getColumns () { const { relationship, refList } = this.props; const columns = refList.expandColumns(refList.defaultColumns); return columns.filter(i => i.path !== relationship.refPath); }, loadItems () { const { refList, relatedItemId, relationship } = this.props; if (!refList.fields[relationship.refPath]) { const err = ( <Alert type="danger"> <strong>Error:</strong> Related List <strong>{refList.label}</strong> has no field <strong>{relationship.refPath}</strong> </Alert> ); return this.setState({ err }); } refList.loadItems({ columns: this.state.columns, filters: [{ field: refList.fields[relationship.refPath], value: { value: relatedItemId }, }], }, (err, items) => { // TODO: indicate pagination & link to main list view this.setState({ items }); }); }, renderItems () { return this.state.items.results.length ? ( <div className="ItemList-wrapper"> <table cellPadding="0" cellSpacing="0" className="Table ItemList"> {this.renderTableCols()} {this.renderTableHeaders()} <tbody> {this.state.items.results.map(this.renderTableRow)} </tbody> </table> </div> ) : ( <h4 className="Relationship__noresults">No related {this.props.refList.plural}</h4> ); }, renderTableCols () { const cols = this.state.columns.map((col) => <col width={col.width} key={col.path} />); return <colgroup>{cols}</colgroup>; }, renderTableHeaders () { const cells = this.state.columns.map((col) => { return <th key={col.path}>{col.label}</th>; }); return <thead><tr>{cells}</tr></thead>; }, renderTableRow (item) { const cells = this.state.columns.map((col, i) => { const ColumnType = Columns[col.type] || Columns.__unrecognised__; const linkTo = !i ? `${Keystone.adminPath}/${this.props.refList.path}/${item.id}` : undefined; return <ColumnType key={col.path} list={this.props.refList} col={col} data={item} linkTo={linkTo} />; }); return <tr key={'i' + item.id}>{cells}</tr>; }, render () { if (this.state.err) { return <div className="Relationship">{this.state.err}</div>; } const listHref = `${Keystone.adminPath}/${this.props.refList.path}`; return ( <div className="Relationship"> <h3 className="Relationship__link"><Link to={listHref}>{this.props.refList.label}</Link></h3> {this.state.items ? this.renderItems() : <Spinner size="sm" />} </div> ); }, }); module.exports = RelatedItemsList;
src/client/home/components/Nav/Nav.js
noahamar/smlscrn
import React from 'react'; import classNames from 'classnames/bind'; import styles from './Nav.styl'; import FilterOptions from '../FilterOptions/FilterOptions'; import MenuButton from '../MenuButton/MenuButton'; const cx = classNames.bind(styles); export default class Nav extends React.Component { constructor(props) { super(); } handleChangeSortBy(event) { this.props.changeFilterSortBy(event.target.value); this.props.fetchItems(); } handleChangeGenre(event) { this.props.changeFilterGenre(event.target.value); this.props.fetchItems(); } // fetch() { // this.props.fetchItems(this.props.selectedSortBy, this.props.selectedGenre); // } render() { return ( <div className={cx('Nav')}> <div className={cx('Nav__menu-button')}> <MenuButton onClick={this.props.toggleMenu}/> </div> <div className={cx('Nav__filter')}> <div className={cx('Nav__filter-sort-by')}> <FilterOptions options={this.props.sortByOptions} selected={this.props.selectedSortBy} onChange={this.handleChangeSortBy.bind(this)} /> </div> <div className={cx('Nav__filter-in')}>in</div> <div className={cx('Nav__filter-genres')}> <FilterOptions options={this.props.genreOptions} selected={this.props.selectedGenre} onChange={this.handleChangeGenre.bind(this)} /> </div> </div> <div className={cx('Nav__loading', {'Nav__loading--show': this.props.isFetching})}></div> </div> ); } }
src/utils/childUtils.js
xmityaz/material-ui
import React from 'react'; import createFragment from 'react-addons-create-fragment'; export function createChildFragment(fragments) { const newFragments = {}; let validChildrenCount = 0; let firstKey; // Only create non-empty key fragments for (const key in fragments) { const currentChild = fragments[key]; if (currentChild) { if (validChildrenCount === 0) firstKey = key; newFragments[key] = currentChild; validChildrenCount++; } } if (validChildrenCount === 0) return undefined; if (validChildrenCount === 1) return newFragments[firstKey]; return createFragment(newFragments); } export function extendChildren(children, extendedProps, extendedChildren) { return React.isValidElement(children) ? React.Children.map(children, (child) => { const newProps = typeof (extendedProps) === 'function' ? extendedProps(child) : extendedProps; const newChildren = typeof (extendedChildren) === 'function' ? extendedChildren(child) : extendedChildren ? extendedChildren : child.props.children; return React.cloneElement(child, newProps, newChildren); }) : children; }
src/encoded/static/components/static-pages/placeholders/HiGlassEmbeddedInstance.js
4dn-dcic/fourfront
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import _ from 'underscore'; import { console, object, ajax } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { BasicUserContentBody, ExpandableStaticHeader } from './../components/BasicUserContentBody'; import { HiGlassLoadingIndicator } from './../../item-pages/components/HiGlass/HiGlassPlainContainer'; export class HiGlassEmbeddedInstance extends React.PureComponent { static defaultProps = { "headerElement": "h3", "headerClassName": "tab-section-title mb-0" }; static propTypes = { "uuid": PropTypes.string.isRequired, "headerElement": PropTypes.string, "headerClassName": PropTypes.string, }; constructor(props) { super(props); this.state = { 'loading': false, 'higlassItem': null }; } componentDidMount() { const { higlassItem } = this.state; const { uuid } = this.props; if (!higlassItem && uuid && typeof uuid === 'string' && uuid.length > 0) { this.setState({ 'loading': true }, () => { // Use the @id to get the item, then remove the loading message ajax.load('/higlass-view-configs/' + uuid, (r) => { this.setState({ 'higlassItem': r, 'loading': false }); }); }); } } render() { const { headerElement = 'h3', headerClassName = "tab-section-title mb-0" } = this.props; const { higlassItem, loading } = this.state; // If HiGlass item is loaded, then display viewer if (higlassItem) { const { title: propTitle, options: { collapsible: isCollapsible = false, default_open = true } = {} } = higlassItem; const headerProps = { className: headerClassName }; const title = (propTitle && !isCollapsible) ? React.createElement(headerElement, headerProps, propTitle) : null; return ( <React.Fragment> {title} {title ? (<hr className="tab-section-title-horiz-divider mb-2"></hr>) : null} { isCollapsible ? <ExpandableStaticHeader context={higlassItem} defaultOpen={default_open} title={propTitle} href={null} titleElement={headerElement} titleTip={higlassItem.description} titleClassName="mb-0" /> : <BasicUserContentBody context={higlassItem} href={null} /> } </React.Fragment> ); } // If we're loading, show a loading screen if (loading) { return <div className="text-center mb-3 mt-3"><HiGlassLoadingIndicator title="Loading" /></div>; } return null; } }
packages/material-ui-icons/src/Tablet.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M21 4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 1.99-.9 1.99-2L23 6c0-1.1-.9-2-2-2zm-2 14H5V6h14v12z" /></g> , 'Tablet');
packages/storyboard-extension-chrome/src/components/015-toolbar.js
guigrpa/storyboard
import React from 'react'; import * as ReactRedux from 'react-redux'; import { Icon, isDark, hintShow } from 'giu'; import Login from './010-login'; import Settings from './016-settings'; import * as actions from '../actions/actions'; const mapStateToProps = (state) => ({ wsState: state.cx.wsState, }); const mapDispatchToProps = { expandAllStories: actions.expandAllStories, collapseAllStories: actions.collapseAllStories, clearLogs: actions.clearLogs, quickFind: actions.quickFind, }; class Toolbar extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, // From Redux.connect wsState: React.PropTypes.string.isRequired, expandAllStories: React.PropTypes.func.isRequired, collapseAllStories: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fSettingsShown: false, }; } // ----------------------------------------------------- render() { const { colors } = this.props; return ( <div id="sbToolbar"> {this.renderSettings()} <div style={style.outer(colors)}> <div style={style.left}> <Icon id="sbBtnShowSettings" icon="cog" size="lg" title="Show settings..." onClick={this.toggleSettings} style={style.icon(colors)} /> <Icon icon="chevron-circle-down" size="lg" title="Expand all stories" onClick={this.props.expandAllStories} style={style.icon(colors)} /> <Icon icon="chevron-circle-right" size="lg" title="Collapse all stories" onClick={this.props.collapseAllStories} style={style.icon(colors)} /> <Icon icon="remove" size="lg" title="Clear logs" onClick={this.props.clearLogs} style={style.icon(colors)} /> <Icon icon="info-circle" size="lg" title="Show hints" onClick={this.showHints} style={style.icon(colors)} /> {' '} <input id="quickFind" type="search" results={0} placeholder="Quick find..." onChange={this.onChangeQuickFind} style={style.quickFind(colors)} /> {this.renderWsStatus()} </div> <div style={style.spacer} /> <Login colors={colors} /> </div> <div style={style.placeholder} /> </div> ); } renderSettings() { if (!this.state.fSettingsShown) return null; return ( <Settings onClose={this.toggleSettings} colors={this.props.colors} /> ); } renderWsStatus() { const fConnected = this.props.wsState === 'CONNECTED'; const icon = fConnected ? 'chain' : 'chain-broken'; const title = fConnected ? 'Connection with the server is UP' : 'Connection with the server is DOWN'; return ( <Icon id="sbWsStatusIcon" icon={icon} size="lg" title={title} style={style.wsStatus(fConnected)} /> ); } // ----------------------------------------------------- toggleSettings = () => { this.setState({ fSettingsShown: !this.state.fSettingsShown }); } showHints = () => { hintShow('main', true); } onChangeQuickFind = (ev) => { this.props.quickFind(ev.target.value); } } // ----------------------------------------------------- const style = { outer: (colors) => { const rulerColor = isDark(colors.colorUiBg) ? '#ccc' : '#555'; return { position: 'fixed', top: 0, left: 0, height: 30, width: '100%', backgroundColor: colors.colorUiBg, borderBottom: `1px solid ${rulerColor}`, display: 'flex', flexDirection: 'row', whiteSpace: 'nowrap', zIndex: 10, }; }, icon: (colors) => ({ cursor: 'pointer', color: colors.colorUiFg, marginRight: 10, }), wsStatus: (fConnected) => ({ marginRight: 5, marginLeft: 10, color: fConnected ? 'green' : 'red', cursor: 'default', }), placeholder: { height: 30 }, left: { padding: '4px 4px 4px 8px' }, right: { padding: '4px 8px 4px 4px' }, spacer: { flex: '1 1 0px' }, quickFind: (colors) => ({ backgroundColor: 'transparent', color: colors.colorUiFg, borderWidth: 1, }), }; // ----------------------------------------------------- const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps); export default connect(Toolbar); export { Toolbar as _Toolbar };
internals/templates/appContainer.js
54vanya/ru-for-you-front
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
local-cli/templates/HelloWorld/index.ios.js
peterp/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
src/containers/search_bar.js
jstowers/ReduxWeatherApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; // import fetchWeather payload import { fetchWeather} from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' } // Sec. 5, Lec. 53 // bind the context of onInputChange() // this = instance of SearchBar // overriding local method // this.onInputChange = this.onInputChange.bind(this); // this.onFormSubmit = this.onFormSubmit.bind(this); } // all DOM event handlers come along with an event object onInputChange = (e) => { this.setState({ term: e.target.value }); } onFormSubmit = (e) => { // prevents page from re-rendering automatically e.preventDefault(); // we need to go and fetch weather data!! this.props.fetchWeather(this.state.term); // clear out search input and re-render this.setState({ term:'' }); } render() { return ( <form onSubmit= { this.onFormSubmit } className="input-group"> <input placeholder="Get five-day forecasts for your favorite cities" className="form-control" value= { this.state.term } onChange= { this.onInputChange } /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit </button> </span> </form> ); } } // ---------------------- mapDispatchToProps() ----------------------------- // // Egghead.io => http://bit.ly/2npPYwk // It allows us to inject certain properties into the wrapped component // that can then dispatch actions. // Use mapDispatchToProps and dispatch to hook up action creator fetchWeather // to our search_bar container: function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } // Connect to action creator -- injects Redux-related props into the component // Passing 'null' for first argument because this container not concerned with state. export default connect(null, mapDispatchToProps)(SearchBar);
src/components/data/DataExplorer.js
dherault/Oso
import React from 'react'; import definitions from '../../models/'; import { Link } from 'react-router'; export default class DataExplorer extends React.Component { render() { const links = Object.keys(definitions).map(model => { const x = definitions[model].pluralName; return <li key={x}> <Link to={'/data/explore/' + x}>{ x }</Link> </li>; }); return <div> <h2>Data Explorer</h2> { this.props.children || <ul> { links } </ul> } </div>; } }
node_modules/react-native/Libraries/Components/WebView/WebView.ios.js
TrungSpy/React-Native-SampleProject
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var PropTypes = require('prop-types'); var ReactNative = require('ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ViewPropTypes = require('ViewPropTypes'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...ViewPropTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * A function that is invoked when the webview calls `window.postMessage`. * Setting this property will inject a `postMessage` global into your * webview, but will still call pre-existing values of `postMessage`. * * `window.postMessage` accepts one argument, `data`, which will be * available on the event object, `event.nativeEvent.data`. `data` * must be a string. */ onMessage: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: ViewPropTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to enable third party cookies in the `WebView`. Used on * Android Lollipop and above only as third party cookies are enabled by * default on Android Kitkat and below and on iOS. The default value is `true`. * @platform android */ thirdPartyCookiesEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, /** * Function that accepts a string that will be passed to the WebView and * executed immediately as JavaScript. */ injectJavaScript: PropTypes.func, /** * Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin. * * Possible values for `mixedContentMode` are: * * - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin. * - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure. * - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content. * @platform android */ mixedContentMode: PropTypes.oneOf([ 'never', 'always', 'compatibility' ]), }; static defaultProps = { scalesPageToFit: true, }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } const messagingEnabled = typeof this.props.onMessage === 'function'; var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} messagingEnabled={messagingEnabled} onMessage={this._onMessage} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * Posts a message to the web view, which will emit a `message` event. * Accepts one argument, `data`, which must be a string. * * In your webview, you'll need to something like the following. * * ```js * document.addEventListener('message', e => { document.title = e.data; }); * ``` */ postMessage = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.postMessage, [String(data)] ); }; /** * Injects a javascript string into the referenced WebView. Deliberately does not * return a response because using eval() to return a response breaks this method * on pages with a Content Security Policy that disallows eval(). If you need that * functionality, look into postMessage/onMessage. */ injectJavaScript = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.injectJavaScript, [data] ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; _onMessage = (event: Event) => { var {onMessage} = this.props; onMessage && onMessage(event); } } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, onMessage: true, messagingEnabled: PropTypes.bool, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
packages/arwes/src/Content/Content.js
romelperez/prhone-ui
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; export default function Content(props) { const { theme, classes, className, children, ...etc } = props; const cls = cx(classes.root, className); return ( <div className={cls} {...etc}> {children} </div> ); } Content.propTypes = { theme: PropTypes.any.isRequired, classes: PropTypes.any.isRequired };
client/LogoBar/Name.js
PicDrop/PicDrop
import React from 'react'; class Name extends React.Component { render() { return ( <div className="box"> <h2>PicDrop</h2> </div> ); } } export default Name;
src/scenes/User/components/Overview/components/TimelineGroup/index.js
antoinechalifour/Reddix
import React from 'react' import styled from 'styled-components' import TimelineItem from '../TimelineItem' import { BOX_SHADOW_2 } from 'Util/constants' const Container = styled.div` display: flex; flex-direction: row; ` const Posts = styled.div` flex: 1; padding: 24px 16px; ` const Timeline = styled.div` position: relative; padding: 24px 8px; display: flex; flex-direction: column; align-items: center; ` const Date = styled.div` padding: 8px; background: rgba(255, 255, 255, .9); box-shadow: ${BOX_SHADOW_2}; position: relative; z-index: 1; border-radius: 4px; ` const Line = styled.div` position: absolute; width: 4px; background: ${props => props.theme.colors.primaryDark}; top: 0; bottom: 0; left: 50%; transform: translate(-50%); ` const TimelineGroup = ({ username, date, posts }) => { return ( <Container> <Timeline> <Date>{date}</Date> <Line /> </Timeline> <Posts> {posts.map(post => ( <TimelineItem key={post.created_utc} {...post} username={username} /> ))} </Posts> </Container> ) } export default TimelineGroup
tests/unit/development/TestReactComponentRequired.react.js
plotly/dash
import React from 'react'; // A react component with all of the available proptypes to run tests over /** * This is a description of the component. * It's multiple lines long. */ class ReactComponent extends Component { render() { return ''; } } ReactComponent.propTypes = { children: React.PropTypes.node, id: React.PropTypes.string.isRequired, }; export default ReactComponent;
docs/src/Anchor.js
xiaoking/react-bootstrap
import React from 'react'; const Anchor = React.createClass({ propTypes: { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }, render() { return ( <a id={this.props.id} href={'#' + this.props.id} className="anchor"> <span className="anchor-icon">#</span> {this.props.children} </a> ); } }); export default Anchor;
src/modules/PlaylistUploadButton/component.js
svmn/ace-fnd
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import CircularProgress from 'material-ui/CircularProgress'; import FontIcon from 'material-ui/FontIcon'; import { fullWhite } from 'material-ui/styles/colors'; export default function PlaylistUploadButton(props) { const { uploadProgress, upload } = props; const spinner = !uploadProgress ? null : ( <CircularProgress color={fullWhite} mode='determinate' value={uploadProgress} style={{ position: 'absolute', left: 0 }} /> ); return ( <div className='playlist-upload-button'> <FloatingActionButton mini> {spinner} <FontIcon className='material-icons'>playlist_add</FontIcon> </FloatingActionButton> <input type='file' onChange={e => upload(e.target.files[0])} /> </div> ); } PlaylistUploadButton.propTypes = { uploadProgress: PropTypes.number, upload: PropTypes.func.isRequired };
packages/reactor-rest-example/src/index.js
sencha/extjs-reactor
import 'babel-polyfill'; import React from 'react'; import App from './App'; import { launch } from '@extjs/reactor'; launch(<App/>);
modules/IndexRoute.js
yongxu/react-router
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './PropTypes'; var { bool, func } = React.PropTypes; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element); } else { warning( false, 'An <IndexRoute> does not make sense at the root of your route config' ); } } }, propTypes: { path: falsy, ignoreScrollBehavior: bool, component, components, getComponents: func }, render() { invariant( false, '<IndexRoute> elements are for router configuration only and should not be rendered' ); } }); export default IndexRoute;
src/client/lib/validation.js
dfogas/my-mindmap
/* Simple serial "one by one" sync/async promises based validation. */ import Promise from 'bluebird'; import React from 'react'; import validator from 'validator'; export class ValidationError extends Error { constructor(message: string, prop: string) { super(); this.message = message; this.prop = prop; } } export function focusInvalidField(component) { return (error) => { if (error instanceof ValidationError) { if (!error.prop) return; const node = React.findDOMNode(component); if (!node) return; const el = node.querySelector(`[name=${error.prop}]`); if (!el) return; el.focus(); return; } throw error; }; } export default class Validation { constructor(object: Object) { this._object = object; this._prop = null; this._validator = validator; this.promise = Promise.resolve(); } custom(callback: Function, {required} = {}) { const prop = this._prop; const value = this._object[prop]; const object = this._object; this.promise = this.promise.then(() => { if (required && !this._isEmptyString(value)) return; callback(value, prop, object); }); return this; } _isEmptyString(value) { return !this._validator.toString(value).trim(); } prop(prop: string) { this._prop = prop; return this; } required(getRequiredMessage?) { return this.custom((value, prop) => { const msg = getRequiredMessage ? getRequiredMessage(prop, value) : this.getRequiredMessage(prop, value); throw new ValidationError(msg, prop); }, {required: true}); } getRequiredMessage(prop, value) { return `Please fill out '${prop}' field.`; } email() { return this.custom((value, prop) => { if (this._validator.isEmail(value)) return; throw new ValidationError( this.getEmailMessage(prop, value), prop ); }); } getEmailMessage() { return `Email address is not valid.`; } simplePassword() { return this.custom((value, prop) => { const minLength = 5; if (value.length >= minLength) return; throw new ValidationError( this.getSimplePasswordMessage(minLength), prop ); }); } getSimplePasswordMessage(minLength) { return `Password must contain at least ${minLength} characters.`; } }
src/components/Footer/Footer.js
IanChuckYin/IanChuckYin.github.io
import React, { Component } from 'react'; import styles from './Footer.module.scss'; import { connect } from 'react-redux'; import SplitContainer from '../SplitContainer/SplitContainer'; import WithTypeAnimation from '../../hoc/WithTypeAnimation/WithTypeAnimation'; const TYPE_ANIMATION_OPTIONS = { speed: 40, type: 'scroll' } class Footer extends Component { state = { name: 'IAN CHUCK-YIN', location: { text: 'Mississauga Ontario', icon: 'fas fa-building' }, email: { text: 'ichuckyin.uwaterloo.ca', icon: 'fas fa-envelope' }, phone: { text: '647-470-9115', icon: 'fas fa-phone' }, } /** * The desktop version of the Footer */ _renderDesktopVersion() { const { name, location, email, phone } = this.state; const leftSide = ( <WithTypeAnimation className={styles.Left} text={name} speed={TYPE_ANIMATION_OPTIONS.speed} type={TYPE_ANIMATION_OPTIONS.type} /> ); const rightSide = [location, email, phone].map((item, index) => { return ( <div className={styles.Right} key={index}> <i className={item.icon} /> <WithTypeAnimation key={index} text={item.text} speed={TYPE_ANIMATION_OPTIONS.speed} type={TYPE_ANIMATION_OPTIONS.type} /> </div> ) }); return ( <div className={styles.Footer}> <SplitContainer split='50' left={leftSide} right={rightSide} middle={true} polar={true} /> <span className={styles.credits}>Image credits to: <a href="http://www.freepik.com">freepik</a></span> </div> ); } /** * The mobile version of the Footer */ _renderMobileVersion() { const { name, location, email, phone } = this.state; const nameContent = ( <WithTypeAnimation className={styles.Top} text={name} speed={TYPE_ANIMATION_OPTIONS.speed} type={TYPE_ANIMATION_OPTIONS.type} /> ); const contactContent = [location, email, phone].map((item, index) => { return ( <div className={styles.Bottom} key={index}> <i className={item.icon} /> <WithTypeAnimation key={index} text={item.text} speed={TYPE_ANIMATION_OPTIONS.speed} type={TYPE_ANIMATION_OPTIONS.type} /> </div> ) }); return ( <div className={styles.Footer}> {nameContent} {contactContent} <span className={styles.credits}>Image credits to: <a href="http://www.freepik.com">freepik</a></span> </div> ); } render() { const { isMobile } = this.props; return (isMobile ? <div className={styles.Mobile}>{this._renderMobileVersion()}</div> : <div className={styles.Desktop}>{this._renderDesktopVersion()}</div> ); } } const mapStateToProps = state => { return { isMobile: state.isMobile }; }; export default connect(mapStateToProps, null)(Footer);
node_modules/react-icons/fa/beer.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const FaBeer = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m14.8 20v-8.6h-5.7v5.7q0 1.2 0.8 2.1t2 0.8h2.9z m22.8 10v4.3h-25.7v-4.3l2.9-4.3h-2.9q-3.5 0-6-2.5t-2.5-6.1v-7.1l-1.5-1.4 0.7-2.9h10.8l0.7-2.8h21.4l0.7 4.2-1.4 0.8v17.8z"/></g> </Icon> ) export default FaBeer
packages/lore-hook-react/src/index.js
lore/lore
/* global document */ import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; export default { dependencies: ['redux', 'router'], defaults: { react: { /** * ID of DOM Element the application will be mounted to */ domElementId: 'root', /** * Generate the root component that will be mounted to the DOM */ getRootComponent: function(lore) { const store = lore.store; const routes = lore.router.routes; const history = lore.router.history; return ( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider> ); }, /** * Mount the root component to the DOM */ mount: function(Root, lore) { const config = lore.config.react; ReactDOM.render(Root, document.getElementById(config.domElementId)); } } }, load: function(lore) { // no-op } };
reactjs-redux/src/index.js
hawkup/github-stars
import { AppContainer } from 'react-hot-loader'; import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import store from './store'; import Root from './Root'; const history = syncHistoryWithStore(browserHistory, store); const rootEl = document.getElementById('root'); ReactDOM.render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, rootEl ); if (module.hot) { module.hot.accept('./Root', () => { // eslint-disable-next-line no-shadow, global-require const Root = require('./Root').default; ReactDOM.render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, rootEl ); }); }
src/svg-icons/action/eject.js
IsenrichO/mui-with-arrows
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/svg-icons/hardware/computer.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareComputer = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"/> </SvgIcon> ); HardwareComputer = pure(HardwareComputer); HardwareComputer.displayName = 'HardwareComputer'; HardwareComputer.muiName = 'SvgIcon'; export default HardwareComputer;
react/apidocs/apidocs.js
bdaroz/the-blue-alliance
import React from 'react' import ReactDOM from 'react-dom' import ApiDocsFrame from './ApiDocsFrame' const swaggerUrl = document.getElementById('swagger_url').innerHTML ReactDOM.render( <ApiDocsFrame url={swaggerUrl} />, document.getElementById('content') )
docs/resume/_next/static/webpack/static/development/pages/index.js.2d4113408dcb5b18c464.hot-update.js
davidpham5/resume
webpackHotUpdate("static/development/pages/index.js",{ /***/ "./pages/index.js": /*!************************!*\ !*** ./pages/index.js ***! \************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _components_Education__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/Education */ "./components/Education.js"); /* harmony import */ var _components_Hero__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/Hero */ "./components/Hero.js"); /* harmony import */ var _components_Organizations__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../components/Organizations */ "./components/Organizations.js"); /* harmony import */ var _components_Skills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/Skills */ "./components/Skills.js"); /* harmony import */ var _components_Work_Experience_WorkExp__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../components/Work-Experience/WorkExp */ "./components/Work-Experience/WorkExp.js"); /* harmony import */ var _components_WorkFlow__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../components/WorkFlow */ "./components/WorkFlow.js"); var _jsxFileName = "/Users/davidpham/Projects/personal/resume/pages/index.js"; var __jsx = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement; // import React from 'react'; // import Welcome from '../components/Welcome'; // function Home() { // return ( // <div> // <Welcome /> // </div> // ) // } // export default Home var Resume = function Resume() { return __jsx("div", { __source: { fileName: _jsxFileName, lineNumber: 24 }, __self: this }, __jsx(_components_Hero__WEBPACK_IMPORTED_MODULE_2__["default"], { className: "flex mb-5", __source: { fileName: _jsxFileName, lineNumber: 25 }, __self: this }), __jsx("div", { className: "flex mb-4 container md:p-12 justify-center m-auto", __source: { fileName: _jsxFileName, lineNumber: 26 }, __self: this }, __jsx("div", { className: "w-2/3 ", __source: { fileName: _jsxFileName, lineNumber: 27 }, __self: this }, __jsx(_components_Work_Experience_WorkExp__WEBPACK_IMPORTED_MODULE_5__["default"], { __source: { fileName: _jsxFileName, lineNumber: 28 }, __self: this }), __jsx(_components_WorkFlow__WEBPACK_IMPORTED_MODULE_6__["default"], { __source: { fileName: _jsxFileName, lineNumber: 29 }, __self: this })), __jsx("div", { className: "w-1/3", __source: { fileName: _jsxFileName, lineNumber: 31 }, __self: this }, __jsx(_components_Education__WEBPACK_IMPORTED_MODULE_1__["default"], { __source: { fileName: _jsxFileName, lineNumber: 32 }, __self: this }), __jsx(_components_Skills__WEBPACK_IMPORTED_MODULE_4__["default"], { __source: { fileName: _jsxFileName, lineNumber: 33 }, __self: this }), __jsx(_components_Organizations__WEBPACK_IMPORTED_MODULE_3__["default"], { __source: { fileName: _jsxFileName, lineNumber: 34 }, __self: this })))); }; /* harmony default export */ __webpack_exports__["default"] = (Resume); /***/ }) }) //# sourceMappingURL=index.js.2d4113408dcb5b18c464.hot-update.js.map
client/components/basic/burger/BurgerIcon.js
Sing-Li/Rocket.Chat
import { css } from '@rocket.chat/css-in-js'; import { Box } from '@rocket.chat/fuselage'; import React from 'react'; import { useIsReducedMotionPreferred } from '../../../hooks/useIsReducedMotionPreferred'; const Wrapper = ({ children }) => <Box is='span' display='inline-flex' flexDirection='column' alignItems='center' justifyContent='space-between' size='x24' paddingBlock='x4' paddingInline='x2' verticalAlign='middle' children={children} />; const Line = ({ animated, moved }) => <Box is='span' width='x20' height='x2' backgroundColor='currentColor' className={[ animated && css` will-change: transform; transition: transform 0.2s ease-out; `, moved && css` &:nth-child(1), &:nth-child(3) { transform-origin: 50%, 50%, 0; } &:nth-child(1) { transform: translate(-25%, 3px) rotate(-45deg) scale(0.5, 1); } [dir=rtl] &:nth-child(1) { transform: translate(25%, 3px) rotate(45deg) scale(0.5, 1); } &:nth-child(3) { transform: translate(-25%, -3px) rotate(45deg) scale(0.5, 1); } [dir=rtl] &:nth-child(3) { transform: translate(25%, -3px) rotate(-45deg) scale(0.5, 1); } `, ]} aria-hidden='true' />; function BurgerIcon({ children, open }) { const isReducedMotionPreferred = useIsReducedMotionPreferred(); return <Wrapper> <Line animated={!isReducedMotionPreferred} moved={open} /> <Line animated={!isReducedMotionPreferred} moved={open} /> <Line animated={!isReducedMotionPreferred} moved={open} /> {children} </Wrapper>; } export default BurgerIcon;
src/Select.js
range-me/react-select
import React from 'react'; import ReactDOM from 'react-dom'; import Input from 'react-input-autosize'; import classNames from 'classnames'; import stripDiacritics from './utils/stripDiacritics'; import Async from './Async'; import Option from './Option'; import Value from './Value'; function stringifyValue (value) { if (typeof value === 'object') { return JSON.stringify(value); } else { return value; } } const stringOrNode = React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]); const Select = React.createClass({ displayName: 'Select', propTypes: { addLabelText: React.PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input allowCreate: React.PropTypes.bool, // whether to allow creation of new entries autoBlur: React.PropTypes.bool, autofocus: React.PropTypes.bool, // autofocus the component on mount backspaceRemoves: React.PropTypes.bool, // whether backspace removes an item if there is no text input className: React.PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearValueText: stringOrNode, // title for the "clear" control clearable: React.PropTypes.bool, // should it be possible to reset value delimiter: React.PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: React.PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: React.PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: React.PropTypes.func, // method to filter a single option (option, filterString) filterOptions: React.PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: React.PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering inputProps: React.PropTypes.object, // custom attributes for the Input isLoading: React.PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) labelKey: React.PropTypes.string, // path of the label value in option objects matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: React.PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: React.PropTypes.object, // optional style to apply to the menu container menuStyle: React.PropTypes.object, // optional style to apply to the menu multi: React.PropTypes.bool, // multi-value input name: React.PropTypes.string, // generates a hidden <input /> tag with this field name for html forms newOptionCreator: React.PropTypes.func, // factory to create new options when allowCreate set noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: React.PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: React.PropTypes.bool, // whether input is cleared on blur onChange: React.PropTypes.func, // onChange handler: function (newValue) {} onClose: React.PropTypes.func, // fires when the menu is closed onFocus: React.PropTypes.func, // onFocus handler: function (event) {} onInputChange: React.PropTypes.func, // onInputChange handler: function (inputValue) {} onMenuScrollToBottom: React.PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: React.PropTypes.func, // fires when the menu is opened onValueClick: React.PropTypes.func, // onClick handler for value labels: function (value, event) {} optionComponent: React.PropTypes.func, // option component to render in dropdown optionRenderer: React.PropTypes.func, // optionRenderer: function (option) {} options: React.PropTypes.array, // array of options placeholder: stringOrNode, // field placeholder, displayed when there's no value required: React.PropTypes.bool, // applies HTML5 required attribute when needed scrollMenuIntoView: React.PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: React.PropTypes.bool, // whether to enable searching feature or not simpleValue: React.PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: React.PropTypes.object, // optional style to apply to the control tabIndex: React.PropTypes.string, // optional tab index of the control value: React.PropTypes.any, // initial field value valueComponent: React.PropTypes.func, // value component to render valueKey: React.PropTypes.string, // path of the label value in option objects valueRenderer: React.PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: React.PropTypes.object, // optional style to apply to the component wrapper }, statics: { Async }, getDefaultProps () { return { addLabelText: 'Add "{label}"?', allowCreate: false, backspaceRemoves: true, clearable: true, clearAllText: 'Clear all', clearValueText: 'Clear value', delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: true, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, multi: false, noResultsText: 'No results found', onBlurResetsInput: true, optionComponent: Option, placeholder: 'Select...', required: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, valueComponent: Value, valueKey: 'value', }; }, getInitialState () { return { inputValue: '', isFocused: false, isLoading: false, isOpen: false, isPseudoFocused: false, required: this.props.required && this.handleRequired(this.props.value, this.props.multi) }; }, componentDidMount () { if (this.props.autofocus) { this.focus(); } }, componentWillUpdate (nextProps, nextState) { if (nextState.isOpen !== this.state.isOpen) { const handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose; handler && handler(); } }, componentDidUpdate (prevProps, prevState) { // focus to the selected option if (this.refs.menu && this.refs.focused && this.state.isOpen && !this.hasScrolledToOption) { let focusedOptionNode = ReactDOM.findDOMNode(this.refs.focused); let menuNode = ReactDOM.findDOMNode(this.refs.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (prevState.inputValue !== this.state.inputValue && this.props.onInputChange) { this.props.onInputChange(this.state.inputValue); } if (this._scrollToFocusedOptionOnUpdate && this.refs.focused && this.refs.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = ReactDOM.findDOMNode(this.refs.focused); var menuDOM = ReactDOM.findDOMNode(this.refs.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = (focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight); } } if (this.props.scrollMenuIntoView && this.refs.menuContainer) { var menuContainerRect = this.refs.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollTo(0, window.scrollY + menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state } }, focus () { if (!this.refs.input) return; this.refs.input.focus(); }, blurInput() { if (!this.refs.input) return; this.refs.input.blur(); }, handleTouchMove (event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart (event) { // Set a flag that the view is not being dragged this.dragging = false; }, handleTouchEnd (event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if(this.dragging) return; // Fire the mouse events this.handleMouseDown(event); }, handleTouchEndClearValue (event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if(this.dragging) return; // Clear the value this.clearValue(event); }, handleMouseDown (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen, }); } if (this.state.isFocused) { // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false, }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, handleMouseDownOnMenu (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); }, closeMenu () { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '', }); this.hasScrolledToOption = false; }, handleInputFocus (event) { var isOpen = this.state.isOpen || this._openAfterFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur (event) { if (this.refs.menu && document.activeElement.isEqualNode(this.refs.menu)) { return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false, }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = ''; } this.setState(onBlurredState); }, handleInputChange (event) { this.setState({ isOpen: true, isPseudoFocused: false, inputValue: event.target.value, }); }, handleKeyDown (event) { if (this.props.disabled) return; switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen) { return; } this.selectFocusedOption(); return; case 13: // enter if (!this.state.isOpen) return; event.stopPropagation(); this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; // case 188: // , // if (this.props.allowCreate && this.props.multi) { // event.preventDefault(); // event.stopPropagation(); // this.selectFocusedOption(); // } else { // return; // } // break; default: return; } event.preventDefault(); }, handleValueClick (option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll (event) { if (!this.props.onMenuScrollToBottom) return; let { target } = event; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, handleRequired (value, multi) { if (!value) return true; return (multi ? value.length === 0 : Object.keys(value).length === 0); }, getOptionLabel (op) { return op[this.props.labelKey]; }, getValueArray () { let value = this.props.value; if (this.props.multi) { if (typeof value === 'string') value = value.split(this.props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(this.expandValue).filter(i => i); } var expandedValue = this.expandValue(value); return expandedValue ? [expandedValue] : []; }, expandValue (value) { if (typeof value !== 'string' && typeof value !== 'number') return value; let { options, valueKey } = this.props; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue (value) { if (this.props.autoBlur){ this.blurInput(); } if (!this.props.onChange) return; if (this.props.required) { const required = this.handleRequired(value, this.props.multi); this.setState({ required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(i => i[this.props.valueKey]).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue (value) { this.hasScrolledToOption = false; if (this.props.multi) { this.addValue(value); this.setState({ inputValue: '', }); } else { this.setValue(value); this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused, }); } }, addValue (value) { var valueArray = this.getValueArray(); this.setValue(valueArray.concat(value)); }, popValue () { var valueArray = this.getValueArray(); if (!valueArray.length) return; if (valueArray[valueArray.length-1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue (value) { var valueArray = this.getValueArray(); this.setValue(valueArray.filter(i => i !== value)); this.focus(); }, clearValue (event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(null); this.setState({ isOpen: false, inputValue: '', }, this.focus); }, focusOption (option) { this.setState({ focusedOption: option }); }, focusNextOption () { this.focusAdjacentOption('next'); }, focusPreviousOption () { this.focusAdjacentOption('previous'); }, focusAdjacentOption (dir) { var options = this._visibleOptions.filter(i => !i.disabled); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1] }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i]) { focusedIndex = i; break; } } var focusedOption = options[0]; if (dir === 'next' && focusedIndex > -1 && focusedIndex < options.length - 1) { focusedOption = options[focusedIndex + 1]; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedOption = options[focusedIndex - 1]; } else { focusedOption = options[options.length - 1]; } } this.setState({ focusedOption: focusedOption }); }, selectFocusedOption () { // if (this.props.allowCreate && !this.state.focusedOption) { // return this.selectValue(this.state.inputValue); // } if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading () { if (!this.props.isLoading) return; return ( <span className="Select-loading-zone" aria-hidden="true"> <span className="Select-loading" /> </span> ); }, renderValue (valueArray, isOpen) { let renderLabel = this.props.valueRenderer || this.getOptionLabel; let ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? <div className="Select-placeholder">{this.props.placeholder}</div> : null; } let onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map((value, i) => { return ( <ValueComponent disabled={this.props.disabled || value.clearableValue === false} key={`value-${i}-${value[this.props.valueKey]}`} onClick={onClick} onRemove={this.removeValue} value={value} > {renderLabel(value)} </ValueComponent> ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return ( <ValueComponent disabled={this.props.disabled} onClick={onClick} value={valueArray[0]} > {renderLabel(valueArray[0])} </ValueComponent> ); } }, renderInput (valueArray) { var className = classNames('Select-input', this.props.inputProps.className); if (this.props.disabled || !this.props.searchable) { return ( <div {...this.props.inputProps} className={className} tabIndex={this.props.tabIndex || 0} onBlur={this.handleInputBlur} onFocus={this.handleInputFocus} ref="input" style={{ border: 0, width: 1, display:'inline-block' }}/> ); } return ( <Input {...this.props.inputProps} className={className} tabIndex={this.props.tabIndex} onBlur={this.handleInputBlur} onChange={this.handleInputChange} onFocus={this.handleInputFocus} minWidth="5" ref="input" required={this.state.required} value={this.state.inputValue} /> ); }, renderClear () { if (!this.props.clearable || !this.props.value || (this.props.multi && !this.props.value.length) || this.props.disabled || this.props.isLoading) return; return ( <span className="Select-clear-zone" title={this.props.multi ? this.props.clearAllText : this.props.clearValueText} aria-label={this.props.multi ? this.props.clearAllText : this.props.clearValueText} onMouseDown={this.clearValue} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEndClearValue}> <span className="Select-clear" dangerouslySetInnerHTML={{ __html: '&times;' }} /> </span> ); }, renderArrow () { return ( <span className="Select-arrow-zone" onMouseDown={this.handleMouseDownOnArrow}> <span className="Select-arrow" onMouseDown={this.handleMouseDownOnArrow} /> </span> ); }, filterOptions (excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (typeof this.props.filterOptions === 'function') { return this.props.filterOptions.call(this, options, filterValue, excludeOptions); } else if (this.props.filterOptions) { if (this.props.ignoreAccents) { filterValue = stripDiacritics(filterValue); } if (this.props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (excludeOptions) excludeOptions = excludeOptions.map(i => i[this.props.valueKey]); return options.filter(option => { if (excludeOptions && excludeOptions.indexOf(option[this.props.valueKey]) > -1) return false; if (this.props.filterOption) return this.props.filterOption.call(this, option, filterValue); if (!filterValue) return true; var valueTest = String(option[this.props.valueKey]); var labelTest = String(option[this.props.labelKey]); if (this.props.ignoreAccents) { if (this.props.matchProp !== 'label') valueTest = stripDiacritics(valueTest); if (this.props.matchProp !== 'value') labelTest = stripDiacritics(labelTest); } if (this.props.ignoreCase) { if (this.props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (this.props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return this.props.matchPos === 'start' ? ( (this.props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue) || (this.props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue) ) : ( (this.props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0) || (this.props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0) ); }); } else { return options; } }, renderMenu (options, valueArray, focusedOption) { if (options && options.length) { let Option = this.props.optionComponent; let renderLabel = this.props.optionRenderer || this.getOptionLabel; return options.map((option, i) => { let isSelected = valueArray && valueArray.indexOf(option) > -1; let isFocused = option === focusedOption; let optionRef = isFocused ? 'focused' : null; let optionClass = classNames({ 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled, }); return ( <Option className={optionClass} isDisabled={option.disabled} isFocused={isFocused} key={`option-${i}-${option[this.props.valueKey]}`} onSelect={this.selectValue} onFocus={this.focusOption} option={option} isSelected={isSelected} ref={optionRef} > {renderLabel(option)} </Option> ); }); } else if (this.props.noResultsText) { return ( <div className="Select-noresults"> {this.props.noResultsText} </div> ); } else { return null; } }, renderHiddenField (valueArray) { if (!this.props.name) return; let value = valueArray.map(i => stringifyValue(i[this.props.valueKey])).join(this.props.delimiter); return <input type="hidden" ref="value" name={this.props.name} value={value} disabled={this.props.disabled} />; }, getFocusableOption (selectedOption) { var options = this._visibleOptions; if (!options.length) return; let focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && options.indexOf(focusedOption) > -1) return focusedOption; for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return options[i]; } }, render () { let valueArray = this.getValueArray(); let options = this._visibleOptions = this.filterOptions(this.props.multi ? valueArray : null); let isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; let focusedOption = this._focusedOption = this.getFocusableOption(valueArray[0]); let className = classNames('Select', this.props.className, { 'Select--multi': this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length, }); return ( <div ref="wrapper" className={className} style={this.props.wrapperStyle}> {this.renderHiddenField(valueArray)} <div ref="control" className="Select-control" style={this.props.style} onKeyDown={this.handleKeyDown} onMouseDown={this.handleMouseDown} onTouchEnd={this.handleTouchEnd} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove}> {this.renderValue(valueArray, isOpen)} {this.renderInput(valueArray)} {this.renderLoading()} {this.renderClear()} {this.renderArrow()} </div> {isOpen ? ( <div ref="menuContainer" className="Select-menu-outer" style={this.props.menuContainerStyle}> <div ref="menu" className="Select-menu" style={this.props.menuStyle} onScroll={this.handleMenuScroll} onMouseDown={this.handleMouseDownOnMenu}> {this.renderMenu(options, !this.props.multi ? valueArray : null, focusedOption)} </div> </div> ) : null} </div> ); } }); export default Select;
src/svg-icons/toggle/star-border.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStarBorder = (props) => ( <SvgIcon {...props}> <path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/> </SvgIcon> ); ToggleStarBorder = pure(ToggleStarBorder); ToggleStarBorder.displayName = 'ToggleStarBorder'; ToggleStarBorder.muiName = 'SvgIcon'; export default ToggleStarBorder;
packages/docsite/src/html.js
r24y/tf-hcl
import React from 'react' import Helmet from 'react-helmet' let stylesStr if (process.env.NODE_ENV === 'production') { try { stylesStr = require('!raw-loader!../public/styles.css') } catch (e) { console.log(e) } } export default class HTML extends React.Component { render() { const head = Helmet.rewind() let css if (process.env.NODE_ENV === 'production') { css = ( <style id="gatsby-inlined-css" dangerouslySetInnerHTML={{ __html: stylesStr }} /> ) } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {this.props.headComponents} {css} <link href="/img/apple-touch-icon.png" rel="apple-touch-icon" sizes="180x180" /> <link href="/img/favicon.ico" rel="icon" type="image/x-icon" /> </head> <body> <div id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ) } }
examples/shopping-cart/index.js
mjw56/redux
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import logger from 'redux-logger' import thunk from 'redux-thunk' import reducer from './reducers' import { getAllProducts } from './actions' import App from './containers/App' const middleware = process.env.NODE_ENV === 'production' ? [ thunk ] : [ thunk, logger() ] const store = createStore( reducer, applyMiddleware(...middleware) ) store.dispatch(getAllProducts()) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/docs/examples/TextInputStyledComponents/ExampleError.js
wsherman67/UBA
import React from 'react'; import TextInputStyledComponents from 'ps-react/TextInputStyledComponents'; /** Required TextBox with error */ export default class ExampleError extends React.Component { render() { return ( <TextInputStyledComponents htmlId="example-optional" label="First Name" name="firstname" onChange={() => {}} required error="First name is required." /> ) } }
src/modules/editor/components/popovers/addTooltip/AddTooltipMenu/AddVimeoButton/AddVimeoButton.js
CtrHellenicStudies/Commentary
import React from 'react'; import autoBind from 'react-autobind'; import { connect } from 'react-redux'; // redux import editorActions from '../../../../../actions'; // components import AddTooltipMenuItemButton from '../../AddTooltipMenuItemButton'; // icons import { FaVimeo } from "react-icons/fa"; class AddVimeoButton extends React.Component { constructor(props) { super(props); autoBind(this); } handleAddVimeo() { } render() { return ( <AddTooltipMenuItemButton className="AddTooltipMenuItemButtonDisabled" onClick={this.handleAddVimeo} > <FaVimeo /> <span>Vimeo</span> </AddTooltipMenuItemButton> ); } } const mapStateToProps = state => ({ ...state.editor, }); const mapDispatchToProps = dispatch => ({ setEditorState: (editorState) => { dispatch(editorActions.setEditorState(editorState)); }, }); export default connect( mapStateToProps, mapDispatchToProps, )(AddVimeoButton);
grunt/config-grunt/node_modules/grunt-browser-sync/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
perrineb/2015-lpdw-html5css3
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
malax/src/modules/main/index.js
cseale/nasa-space-jockey
import React from 'react'; import Navbar from '../navbar'; import Button from './button'; import satelitebutton from './satelitebutton.svg' import vrbutton from './vrbutton.svg' import telescopebutton from './telescope.svg' import {Link} from 'react-router-dom' class Main extends React.Component { render() { return ( <div> <Navbar /> <div className="Main"> <Link to="/augmented"> <Button text="Augmented Reality" src={telescopebutton}></Button> </Link> <Link to="/cesium"> <Button text="Virtual Reality" src={vrbutton}></Button> </Link> </div> </div> ) } } export default Main;
app/app.js
dcarneiro/my-react-boilerplate
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved, import/extensions */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import injectTapEventPlugin from 'react-tap-event-plugin'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import jwtDecode from 'jwt-decode'; import { jwtTokenKey } from 'utils/jwtToken'; import LanguageProvider from './containers/LanguageProvider'; import configureStore from './store'; import { setAuthorizationToken } from './utils/request'; import { setCurrentUser } from './containers/App/actions'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import 'sanitize.css/sanitize.css'; import './global-styles'; // Material UI // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; if (localStorage.getItem(jwtTokenKey())) { try { const currentUser = jwtDecode(localStorage.getItem(jwtTokenKey())).sub; setAuthorizationToken(localStorage.getItem(jwtTokenKey())); store.dispatch(setCurrentUser(currentUser)); } catch (error) { localStorage.removeItem(jwtTokenKey()); } } const render = (translatedMessages) => { ReactDOM.render( <MuiThemeProvider muiTheme={getMuiTheme()}> <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider> </MuiThemeProvider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
src/routes/Builder/components/EquipToCharSelect.js
DaveSpringer/bmg-rap-sheets
import React from 'react' import './style/EquipToCharSelect.scss' import EquipmentItem from '../../../components/EquipmentItem/EquipmentItem' import Character from './Character' class EquipToCharSelect extends React.Component { constructor (props) { super(props) this.handleCharacterSelect = this.handleCharacterSelect.bind(this) } handleCharacterSelect (event) { console.log('Selected character key ' + event + ' for equipment ' + this.props.equipment.name) this.props.assignEquipment(this.props.equipment, event) } render () { return ( <div className='equip-to-char-select'> <h2>Select Character for Equipment</h2> <div> <EquipmentItem equipment={this.props.equipment} /> </div> <div> {this.props.validEquipChars.map(character => <Character key={character.key} character={character} selectCharacter={this.handleCharacterSelect} /> )} </div> <div className='clear-left' /> </div> ) } } EquipToCharSelect.propTypes = { validEquipChars : React.PropTypes.array.isRequired, equipment : React.PropTypes.object.isRequired, assignEquipment : React.PropTypes.func.isRequired } export default EquipToCharSelect
docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js
kasra-co/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import FontIcon from 'material-ui/FontIcon'; const styles = { button: { margin: 12, }, exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const RaisedButtonExampleComplex = () => ( <div> <RaisedButton label="Choose an Image" labelPosition="before" style={styles.button} > <input type="file" style={styles.exampleImageInput} /> </RaisedButton> <RaisedButton label="Label before" labelPosition="before" primary={true} icon={<ActionAndroid />} style={styles.button} /> <RaisedButton label="Github Link" href="https://github.com/callemall/material-ui" secondary={true} style={styles.button} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default RaisedButtonExampleComplex;
app/containers/LocaleToggle/index.js
KraigWalker/frontendfriday
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { selectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
client/src/components/instructor/InstructorList.js
yegor-sytnyk/contoso-express
import React from 'react'; import InstructorRow from './InstructorRow'; const InstructorList = ({instructors, selectedInstructorId, onSelectClick, onSaveClick, onDetailsClick, onDeleteClick}) => { return ( <table className="table"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Hire Date</th> <th>Office</th> <th>Courses</th> <th></th> </tr> </thead> <tbody> {instructors.map(instructor => <InstructorRow key={instructor.id} instructor={instructor} selectedInstructorId={selectedInstructorId} onSelectClick={() => onSelectClick(instructor.id)} onSaveClick={() => onSaveClick(instructor.id)} onDetailsClick={() => onDetailsClick(instructor.id)} onDeleteClick={() => onDeleteClick(instructor.id)} /> )} </tbody> </table> ); }; InstructorList.propTypes = { instructors: React.PropTypes.array.isRequired, selectedInstructorId: React.PropTypes.number.isRequired, onSaveClick: React.PropTypes.func.isRequired, onSelectClick: React.PropTypes.func.isRequired, onDetailsClick: React.PropTypes.func.isRequired, onDeleteClick: React.PropTypes.func.isRequired }; export default InstructorList;
admin/client/App/shared/FlashMessages.js
alobodig/keystone
/** * Render a few flash messages, e.g. errors, success messages, warnings,... * * Use like this: * <FlashMessages * messages={{ * error: [{ * title: 'There is a network problem', * detail: 'Please try again later...', * }], * }} * /> * * Instead of error, it can also be hilight, info, success or warning */ import React from 'react'; import _ from 'lodash'; import FlashMessage from './FlashMessage'; var FlashMessages = React.createClass({ displayName: 'FlashMessages', propTypes: { messages: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.shape({ error: React.PropTypes.array, hilight: React.PropTypes.array, info: React.PropTypes.array, success: React.PropTypes.array, warning: React.PropTypes.array, }), ]), }, // Render messages by their type renderMessages (messages, type) { if (!messages || !messages.length) return null; return messages.map((message, i) => { return <FlashMessage message={message} type={type} key={`i${i}`} />; }); }, // Render the individual messages based on their type renderTypes (types) { return Object.keys(types).map(type => this.renderMessages(types[type], type)); }, render () { if (!this.props.messages) return null; return ( <div className="flash-messages"> {_.isPlainObject(this.props.messages) && this.renderTypes(this.props.messages)} </div> ); }, }); module.exports = FlashMessages;
index.ios.js
yomi-network/app
/** * 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 yomi 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.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake 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('yomi', () => yomi);
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-bricks-blockquote.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, ColorSchemaMixin, ContentMixin, Tools} from '../common/common.js'; import Environment from '../environment/environment.js'; import Footer from './blockquote-footer.js' import './blockquote.less'; export const Blockquote = React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, ColorSchemaMixin, ContentMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Bricks.Blockquote', classNames: { main: 'uu5-bricks-blockquote', bg: 'uu5-bricks-blockquote-bg', right: 'blockquote-reverse' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { background: React.PropTypes.bool, alignment: React.PropTypes.oneOf([ 'left', 'right' ]), footer: React.PropTypes.any, footerAlignment: React.PropTypes.oneOf([ 'left', 'right' ]) }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { background: false, alignment: 'left', footer: null, footerAlignment: null }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _buildMainAttrs: function () { var mainAttrs = this.buildMainAttrs(); this.props.background && (mainAttrs.className += ' ' + this.getClassName().bg); this.props.alignment === 'right' && (mainAttrs.className += ' ' + this.getClassName().right); return mainAttrs; }, _getFooterAlignment: function () { return this.props.footerAlignment || this.props.alignment; }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return ( <blockquote {...this._buildMainAttrs()}> {this.getChildren()} {this.props.footer && <Footer content={this.props.footer} alignment={this._getFooterAlignment()} />} {this.getDisabledCover()} </blockquote> ); } //@@viewOff:render }); var createColoredBlockquote = function (colorSchema, background) { return React.createClass({ render: function () { return ( <Blockquote {...this.props} colorSchema={colorSchema} background={background}> {this.props.children && React.Children.toArray(this.props.children)} </Blockquote> ); } }); }; Environment.colorSchema.forEach(function (colorSchema) { var colorSchemaCapitalize = Tools.getCamelCase(colorSchema); Blockquote[colorSchema] = createColoredBlockquote(colorSchema); Blockquote['bg' + colorSchemaCapitalize] = createColoredBlockquote(colorSchema, true); }); export default Blockquote;
src/Badge.js
blue68/react-bootstrap
import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; import classNames from 'classnames'; const Badge = React.createClass({ propTypes: { pullRight: React.PropTypes.bool }, getDefaultProps() { return { pullRight: false }; }, hasContent() { return ValidComponentChildren.hasValidComponent(this.props.children) || (React.Children.count(this.props.children) > 1) || (typeof this.props.children === 'string') || (typeof this.props.children === 'number'); }, render() { let classes = { 'pull-right': this.props.pullRight, 'badge': this.hasContent() }; return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Badge;
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_04/finished/src/index.js
yevheniyc/C
import C from './constants' import React from 'react' import { render } from 'react-dom' import routes from './routes' import sampleData from './initialState' import storeFactory from './store' import { Provider } from 'react-redux' import { addError } from './actions' const initialState = (localStorage["redux-store"]) ? JSON.parse(localStorage["redux-store"]) : sampleData const saveState = () => localStorage["redux-store"] = JSON.stringify(store.getState()) const handleError = error => { store.dispatch( addError(error.message) ) } const store = storeFactory(initialState) store.subscribe(saveState) window.React = React window.store = store window.addEventListener("error", handleError) render( <Provider store={store}> {routes} </Provider>, document.getElementById('react-container') )
src/components/ChatApp/MessageSection/DialogSection.js
isuruAb/chat.susi.ai
import Dialog from 'material-ui/Dialog'; import React, { Component } from 'react'; import Login from '../../Auth/Login/Login.react'; import SignUp from '../../Auth/SignUp/SignUp.react'; import ForgotPassword from '../../Auth/ForgotPassword/ForgotPassword.react'; import PropTypes from 'prop-types'; import Close from 'material-ui/svg-icons/navigation/close'; export default class DialogSection extends Component { render() { const closingStyle = { position: 'absolute', zIndex: 1200, fill: '#444', width: '26px', height: '26px', right: '10px', top: '10px', cursor: 'pointer' } const customThemeBodyStyle = { padding: 0, textAlign: 'center', backgroundColor: '#f9f9f9' } return ( <div> {/* Login */} <Dialog className='dialogStyle' modal={false} open={this.props.openLogin} autoScrollBodyContent={true} bodyStyle={this.props.bodyStyle} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.props.onRequestClose()}> <Login {...this.props} handleForgotPassword={this.props.onForgotPassword()} handleSignUp={this.props.handleSignUp} /> <Close style={closingStyle} onTouchTap={this.props.onRequestClose()} /> </Dialog> {/* SignUp */} <Dialog className='dialogStyle' modal={false} open={this.props.openSignUp} autoScrollBodyContent={true} bodyStyle={this.props.bodyStyle} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.props.onRequestClose()}> <SignUp {...this.props} onRequestClose={this.props.onRequestClose()} onLoginSignUp={this.props.onLoginSignUp()} /> <Close style={closingStyle} onTouchTap={this.props.onRequestClose()} /> </Dialog> {/* Forgot Password */} <Dialog className='dialogStyle' modal={false} open={this.props.openForgotPassword} autoScrollBodyContent={true} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.props.onRequestClose()}> <ForgotPassword {...this.props} onLoginSignUp={this.props.onLoginSignUp()} showForgotPassword={this.showForgotPassword} /> <Close style={closingStyle} onTouchTap={this.props.onRequestClose()} /> </Dialog> {/* ThemeChanger */} <Dialog actions={this.props.customSettingsDone} modal={false} open={this.props.openThemeChanger} autoScrollBodyContent={true} bodyStyle={customThemeBodyStyle} contentStyle={{ width: '35%', minWidth: '300px' }} onRequestClose={this.props.onRequestClose()}> <div className='settingsComponents'> {this.props.ThemeChangerComponents} </div> <Close style={closingStyle} onTouchTap={this.props.onRequestClose()} /> </Dialog> <Dialog className='dialogStyle' contentStyle={{ width: '45%', minWidth: '300px'}} title="Welcome to SUSI Web Chat" open={this.props.tour} > <iframe width="100%" height="315" src="https://www.youtube.com/embed/9T3iMoAUKYA" gesture="media" allow="encrypted-media" > </iframe> <Close style={closingStyle} onTouchTap={this.props.onRequestCloseTour()} /> </Dialog> </div> ); } } DialogSection.propTypes = { openLogin: PropTypes.bool, openSignUp: PropTypes.bool, openForgotPassword: PropTypes.bool, openHardwareChange: PropTypes.bool, openThemeChanger: PropTypes.bool, tour: PropTypes.bool, onLoginSignUp: PropTypes.func, handleSignUp: PropTypes.func, ServerChangeActions: PropTypes.array, HardwareActions: PropTypes.array, customSettingsDone: PropTypes.object, ThemeChangerComponents: PropTypes.array, actions: PropTypes.object, bodyStyle: PropTypes.object, onRequestClose: PropTypes.func, onRequestCloseTour: PropTypes.func, onSaveThemeSettings: PropTypes.func, onForgotPassword: PropTypes.func, onSignedUp: PropTypes.func };
lib/circlePacking/circlePacking.js
team-parsnips/ReD3
import React from 'react'; import * as d3 from 'd3'; class CirclePacking extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { var height, width, svg, margin, diameter, g, color, pack; height = +this.props.height; width = +this.props.width; svg = d3.select(".circle-packing") .attr('height', height) .attr('width', width); margin = 20; diameter = +svg.attr("width"); g = svg.append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")"); color = d3.scaleLinear() .domain([-1, 5]) .range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"]) .interpolate(d3.interpolateHcl); pack = d3.pack() .size([diameter - margin, diameter - margin]) .padding(2); function genCirclePacking(root) { var focus, nodes, view, circle, text, node; root = d3.hierarchy(root) .sum(function(d) { return d.size; }) .sort(function(a, b) { return b.value - a.value; }); focus = root; nodes = pack(root).descendants(); circle = g.selectAll("circle") .data(nodes) .enter().append("circle") .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) .style("fill", function(d) { return d.children ? color(d.depth) : 'white'; }) .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); }); text = g.selectAll("text") .data(nodes) .enter().append("text") .attr("class", "label") .style('font', '11px "Helvetica Neue", Helvetica, Arial, sans-serif') .style('text-anchor', 'middle') .style('text-shadow', '0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff') .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) .style("display", function(d) { return d.parent === root ? "inline" : "none"; }) .text(function(d) { return d.data.name; }); node = g.selectAll("circle, text"); g.selectAll("circle") .style('cursor', 'pointer') .on('mouseover', function(d) { var nodeSelection = d3.select(this) .style('stroke', '#000') .style('stroke-width', '1.5px') }) .on('mouseout', function(d) { var nodeSelection = d3.select(this) .style('stroke', '#000') .style('stroke-width', '0px') }); svg.style("background", color(-1)) .on("click", function() { zoom(root); }); zoomTo([root.x, root.y, root.r * 2 + margin]); function zoom(d) { var focus0 = focus; focus = d; var transition = d3.transition() .duration(d3.event.altKey ? 7500 : 750) .tween("zoom", function(d) { var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]); return function(t) { zoomTo(i(t)); }; }); transition.selectAll("text") .filter(function(d) { return d.parent === focus || this.style.display === "inline"; }) .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) .on("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) .on("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); } function zoomTo(v) { var k = diameter / v[2]; view = v; node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; }); circle.attr("r", function(d) { return d.r * k; }); } } genCirclePacking(this.props.data); } render() { return ( <div> <svg className='circle-packing'> </svg> </div> ); } } export default CirclePacking;
docs-ui/components/scoreCard.stories.js
beeftornado/sentry
import React from 'react'; import styled from '@emotion/styled'; import {t} from 'app/locale'; import ScoreCard from 'app/components/scoreCard'; import space from 'app/styles/space'; export default { title: 'UI/ScoreCard', }; export const Default = () => ( <Wrapper> <ScoreCard title={t('First Score')} help={t('First score is used to ...')} score="94.1%" trend="+13.5%" trendStyle="good" /> <ScoreCard title={t('Velocity Score')} help={t('Velocity score is used to ...')} score="16" trend="-2 releases / 2 wks" trendStyle="bad" /> <ScoreCard title={t('Other Score')} help={t('Other score is used to ...')} score="0.95" trend="+0.2" /> <ScoreCard title={t('Minimal')} /> </Wrapper> ); Default.story = {name: 'default'}; const Wrapper = styled('div')` display: grid; grid-gap: ${space(1)}; grid-template-columns: repeat(4, minmax(0, 1fr)); `;
src/routes/not-found/index.js
tonimoeckel/lap-counter-react
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import NotFound from './NotFound'; const title = 'Page Not Found'; function action() { return { chunks: ['not-found'], title, component: ( <Layout> <NotFound title={title} /> </Layout> ), status: 404, }; } export default action;
src/components/StationSelector.js
gj262/noaa-coops-viewer
import PropTypes from 'prop-types' import React from 'react' import Select from 'react-select' import './StationSelector.scss' export default class StationSelector extends React.Component { static propTypes = { stations: PropTypes.array.isRequired, selectedStationID: PropTypes.string, selectStationID: PropTypes.func.isRequired } render () { var options = this.makeStationOptions() return ( <div className='text-left col-xs-offset-3 col-xs-6 col-lg-offset-4 col-lg-4 '> <Select value={options.find( option => option.value === this.props.selectedStationID )} clearable={false} options={options} onChange={this.selectStationID} /> </div> ) } makeStationOptions () { return this.props.stations.map(station => { return { value: station.ID, label: `${station.name} ${station.state} (${station.ID})` } }) } selectStationID = option => { this.props.selectStationID(option.value) } }
client/components/Menu/MenuMobile.js
Art404/platform404
import React from 'react' import {Link} from 'react-router' import Squad from './Squad' class MenuMobile extends React.Component { static displayName = 'MenuMobile'; static propTypes = { 'params': React.PropTypes.object, 'squad': React.PropTypes.array, 'main': React.PropTypes.object, 'actions': React.PropTypes.object }; render() { const {main, squad, actions} = this.props return ( <section className="MenuMobile"> <div className="MenuMobile-links"> {Object.keys(main.pages).map((p, i) => { if (p === 'home') return null return ( <Link to={`/${main.pages[p].url}`} className="MenuMobile-link" key={i} onClick={actions.toggleSidebar.bind(this, false)}> <span className={`MenuMobile-icn ${main.pages[p].url}`} /> {p} </Link> ) })} </div> <Squad mobile={true} squad={squad} actions={actions} /> </section> ) } } export default MenuMobile
fields/types/boolean/BooleanColumn.js
davibe/keystone
import React from 'react'; import classnames from 'classnames'; import Checkbox from '../../../admin/src/components/Checkbox'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; var BooleanColumn = React.createClass({ displayName: 'BooleanColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <Checkbox readonly checked={this.props.data.fields[this.props.col.path]} /> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = BooleanColumn;
envkey-react/src/components/forms/app/app_form.js
envkey/envkey-app
import React from 'react' import {RadioGroup, Radio} from 'react-radio-group' import moment from 'moment' import AppImporter from './app_importer' import { SubscriptionWallContainer } from 'containers' export default class AppForm extends React.Component { constructor(props) { super(props) this.state = { importOption: "noImport", importValid: false } } componentDidMount(){ if(this.refs.name)this.refs.name.focus() } _onSubmit(e){ e.preventDefault() this.props.onSubmit({ willImport: this.state.importOption == "import", toImport: this._willImport() ? this.refs.appImporter.toImport() : undefined, params: {name: this.refs.name.value} }) } _onImportOptionChange(val){ this.setState({importOption: val}) } _willImport(){ return this.props.renderImporter && this.state.importOption == "import" } _showSubscriptionWall(){ return this.props.numApps && this.props.currentOrg && this.props.numApps >= this.props.currentOrg.maxApps } render(){ if (this._showSubscriptionWall()){ return <SubscriptionWallContainer type="app" max={this.props.currentOrg.maxApps} /> } return ( <form ref="form" className="object-form new-form app-form" onSubmit={this._onSubmit.bind(this)}> <fieldset> <input type="text" className="app-name" disabled={this.props.isSubmitting} ref="name" placeholder="App Name" required /> </fieldset> {this._renderImportOpts()} {this._renderImporter()} <fieldset>{this._renderSubmit()}</fieldset> </form> ) } _renderImportOpts(){ return <fieldset className="radio-opts import-opts"> <RadioGroup selectedValue={this.state.importOption} onChange={::this._onImportOptionChange}> <label className={this.state.importOption == "noImport" ? "selected" : ""}> <Radio disabled={this.props.isSubmitting} value="noImport" /> <strong>Start from scratch</strong> </label> <label className={this.state.importOption == "import" ? "selected" : ""}> <Radio disabled={this.props.isSubmitting} value="import" /><strong>Import config</strong> </label> </RadioGroup> </fieldset> } _renderImporter(){ if(this._willImport()){ return <AppImporter ref="appImporter" environments={this.props.environments} embeddedInAppForm={true} onChange={importValid => this.setState({importValid})}/> } } _renderSubmit(){ if(this.props.isSubmitting){ return <button disabled={true}> Creating App... </button> } else { if (!this.props.renderImporter && this.state.importOption == "import"){ return <button>Next</button> } else { const disabled = this.state.importOption == "import" && !this.state.importValid return <button disabled={disabled}>Create App</button> } } } }
examples/universal/server/server.js
drewschrauf/redux
/* eslint-disable no-console, no-use-before-define */ import path from 'path'; import Express from 'express'; import qs from 'qs'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; import { fetchCounter } from '../common/api/counter'; const app = new Express(); const port = 3000; // Use this middleware to server up static files built into dist app.use(require('serve-static')(path.join(__dirname, '../dist'))); // This is fired every time the server side receives a request app.use(handleRender); function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query); const counter = parseInt(params.counter, 10) || apiResult || 0; // Compile an initial state const initialState = { counter }; // Create a new Redux store instance const store = configureStore(initialState); // Render the component to a string const html = React.renderToString( <Provider store={store}> { () => <App/> } </Provider>); // Grab the initial state from our Redux store const finalState = store.getState(); // Send the rendered page back to the client res.send(renderFullPage(html, finalState)); }); } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; </script> <script src="/bundle.js"></script> </body> </html> `; } app.listen(port, (error) => { if (error) { console.error(error); } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`); } });
examples/relay-treasurehunt/js/components/App.js
dmfrancisco/relay
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import CheckHidingSpotForTreasureMutation from '../mutations/CheckHidingSpotForTreasureMutation'; import React from 'react'; import Relay from 'react-relay'; class App extends React.Component { _getHidingSpotStyle(hidingSpot) { var color; if (this.props.relay.hasOptimisticUpdate(hidingSpot)) { color = 'lightGrey'; } else if (hidingSpot.hasBeenChecked) { if (hidingSpot.hasTreasure) { color = 'green'; } else { color = 'red'; } } else { color = 'black'; } return { backgroundColor: color, cursor: this._isGameOver() ? null : 'pointer', display: 'inline-block', height: 100, marginRight: 10, width: 100, }; } _handleHidingSpotClick(hidingSpot) { if (this._isGameOver()) { return; } Relay.Store.update( new CheckHidingSpotForTreasureMutation({ game: this.props.game, hidingSpot, }) ); } _hasFoundTreasure() { return ( this.props.game.hidingSpots.edges.some(edge => edge.node.hasTreasure) ); } _isGameOver() { return !this.props.game.turnsRemaining || this._hasFoundTreasure(); } renderGameBoard() { return this.props.game.hidingSpots.edges.map(edge => { return ( <div key={edge.node.id} onClick={this._handleHidingSpotClick.bind(this, edge.node)} style={this._getHidingSpotStyle(edge.node)} /> ); }); } render() { var headerText; if (this.props.relay.getPendingTransactions(this.props.game)) { headerText = '\u2026'; } else if (this._hasFoundTreasure()) { headerText = 'You win!'; } else if (this._isGameOver()) { headerText = 'Game over!'; } else { headerText = 'Find the treasure!'; } return ( <div> <h1>{headerText}</h1> {this.renderGameBoard()} <p>Turns remaining: {this.props.game.turnsRemaining}</p> </div> ); } } export default Relay.createContainer(App, { fragments: { game: () => Relay.QL` fragment on Game { turnsRemaining, hidingSpots(first: 9) { edges { node { hasBeenChecked, hasTreasure, id, ${CheckHidingSpotForTreasureMutation.getFragment('hidingSpot')}, } } }, ${CheckHidingSpotForTreasureMutation.getFragment('game')}, } `, }, });