path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/components/YoutubeNotice/index.js
zillding/hangouts
/** * * YoutubeNotice * */ import React from 'react'; import styles from './styles.css'; const YoutubeNotice = () => ( <p className={styles.youtubeNotice}> * Use above control buttons to make sure actions are sync across all users in the room. </p> ); export default YoutubeNotice;
src/components/render-clip/render-clip-2d.js
raulsebastianmihaila/crizmas-components
import React from 'react'; import propTypes from 'prop-types'; import {getFitContentValue, getStickyValue} from '../../utils.js'; const {createElement} = React; const fitContentValue = getFitContentValue(); const stickyValue = getStickyValue(); export default class RenderClip2D extends React.Component { constructor() { super(); this.containerRef = React.createRef(); this.onScroll = (e) => { if (e.target === this.containerRef.current) { this.props.controller.onScroll(); } }; this.syncHeightAfterRender = () => { if (!this.props.controller.verticalRenderClipController.renderedItemsCount || !this.props.controller.horizontalRenderClipController.renderedItemsCount) { return; } const {mustReapplyLastOperationForSizeSync: mustReapplyVerticalLastOperationForSizeSync, lastOperationForSizeSync: verticalLastOperationForSizeSync} = this.props.controller.verticalRenderClipController.onRender(); const {mustReapplyLastOperationForSizeSync: mustReapplyHorizontalLastOperationForSizeSync, lastOperationForSizeSync: horizontalLastOperationForSizeSync} = this.props.controller.horizontalRenderClipController.onRender(); if (mustReapplyVerticalLastOperationForSizeSync) { verticalLastOperationForSizeSync(); } if (mustReapplyHorizontalLastOperationForSizeSync) { horizontalLastOperationForSizeSync(); } }; this.onWindowResize = () => { this.props.controller.refresh(); }; } componentDidMount() { this.props.controller.setDomContainer(this.containerRef.current); window.addEventListener('resize', this.onWindowResize); } componentDidUpdate(prevProps) { if (this.props.controller !== prevProps.controller) { this.props.controller.setDomContainer(this.containerRef.current); } this.syncHeightAfterRender(); } componentWillUnmount() { this.props.controller.setDomContainer(null); window.removeEventListener('resize', this.onWindowResize); } render() { const { controller: {verticalRenderClipController, horizontalRenderClipController}, renderRow, renderCell, preventTabFocus } = this.props; return createElement( 'div', { ref: this.containerRef, tabIndex: preventTabFocus ? -1 : 0, style: { position: 'relative', width: '100%', height: '100%', overflow: 'auto', whiteSpace: 'nowrap' }, onScroll: this.onScroll }, !!verticalRenderClipController.renderedItemsCount && !!horizontalRenderClipController.renderedItemsCount && createElement( 'div', { style: { position: stickyValue, top: verticalRenderClipController.isScrollVirtualized ? 0 : 'unset', left: horizontalRenderClipController.isScrollVirtualized ? 0 : 'unset', height: verticalRenderClipController.isScrollVirtualized ? '100%' : horizontalRenderClipController.isScrollVirtualized ? fitContentValue : 'unset', width: horizontalRenderClipController.isScrollVirtualized ? '100%' : verticalRenderClipController.isScrollVirtualized ? fitContentValue : 'unset', overflowY: verticalRenderClipController.isScrollVirtualized ? 'hidden' : 'unset', overflowX: horizontalRenderClipController.isScrollVirtualized ? 'hidden' : 'unset' } }, createElement( 'div', { style: { transform: `translateY(${ verticalRenderClipController.trimmedStartNegativeSize}px) translateX(${ horizontalRenderClipController.trimmedStartNegativeSize}px)` } }, Array.from( {length: verticalRenderClipController.renderedItemsCount}, (v, index) => { const rowIndex = verticalRenderClipController.renderedItemsStartIndex + index; return renderRow({ index: rowIndex, itemHeight: verticalRenderClipController.getRealItemSize(rowIndex), renderCells: () => Array.from( {length: horizontalRenderClipController.renderedItemsCount}, (v, index) => { const cellIndex = horizontalRenderClipController.renderedItemsStartIndex + index; return renderCell({ index: cellIndex, itemWidth: horizontalRenderClipController.getRealItemSize(cellIndex), itemHeight: verticalRenderClipController.getRealItemSize(rowIndex), rowIndex }); }) }); }))), !!verticalRenderClipController.renderedItemsCount && verticalRenderClipController.isScrollVirtualized && createElement( 'div', { style: { position: 'absolute', left: 0, top: 0, zIndex: -1, width: '100%', height: verticalRenderClipController.virtualTotalItemsSize } }), !!horizontalRenderClipController.renderedItemsCount && horizontalRenderClipController.isScrollVirtualized && createElement( 'div', { style: { position: 'absolute', left: 0, top: 0, zIndex: -1, height: '100%', width: horizontalRenderClipController.virtualTotalItemsSize } })); } } RenderClip2D.propTypes = { controller: propTypes.object.isRequired, renderRow: propTypes.func.isRequired, renderCell: propTypes.func.isRequired, preventTabFocus: propTypes.bool };
src/server.js
prgits/react-product
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, changeOrigin: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, {target: targetUrl}); }); app.use('/ws', (req, res) => { proxy.web(req, res, {target: targetUrl + '/ws'}); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, client); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
react-router-tutorial/lessons/04-nested-routes/index.js
zerotung/practices-and-notes
import React from 'react' import { render } from 'react-dom' import { Router, Route, hashHistory } from 'react-router' import App from './modules/App' import About from './modules/About' import Repos from './modules/Repos' render(( <Router history={hashHistory}> <Route path="/" component={App}/> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Router> ), document.getElementById('app'))
src/widgets/History/components/CustomizedAxisTick.js
rocket-internet-berlin/RocketDashboard
import React from 'react'; import constants from '../../../config/constants'; const CustomizedAxisTick = props => { const { x, y, stroke, payload } = props; // eslint-disable-line return ( <g transform={`translate(${x},${y})`}> <text x={0} y={0} dy={16} textAnchor="end" fill={constants.chartColor.tickColor} transform="rotate(-35)"> {payload.value} </text> </g> ); }; export default CustomizedAxisTick;
src/components/Forms/NewOffer.js
andresmechali/shareify
import React from 'react'; import PropTypes from 'prop-types'; import axios from 'axios'; import { withApollo } from 'react-apollo'; import CREATE_ITEM from '../../utils/queries/CREATE_ITEM'; import classNames from 'classnames'; import validateInput from '../../utils/formValidation'; import Input from '../../components/Inputs/Input'; import Cropper from 'react-cropper'; import 'cropperjs/dist/cropper.css'; import dataUriToBlob from '../../utils/dataUriToBlob'; import ItemPreview from '../Preview/ItemPreview'; import PlacesSearchBox from '../../components/Maps/PlacesSearchBox'; import UploadImage from "./UploadImage"; import FlashMessageList from "../FlashMessages/FlashMessageList"; import IMG_PATH from "../../utils/IMG_PATH"; class NewOffer extends React.Component { constructor(props) { super(props); this.state = { name: "", location: props.auth.user.lastLocation? props.auth.user.lastLocation : "", latitude: props.auth.user.lastLatitude? props.auth.user.lastLatitude : 55.6760968, longitude: props.auth.user.lastLongitude? props.auth.user.lastLongitude : 12.568337199999974, description: "", isLoading: false, errors: {}, focus: "", flashMessage: "", validLocation: true, image: false, filename: false, }; this.onChange = this.onChange.bind(this); this.onFocus = this.onFocus.bind(this); this.onBlur = this.onBlur.bind(this); this.onSubmit = this.onSubmit.bind(this); this.onGeoLocate = this.onGeoLocate.bind(this); } onChange(e) { if (e.target.name === 'location') { this.setState({ validLocation: false, }) } this.setState({ errors: {...this.state.errors, [e.target.name]: ""}, [e.target.name]: e.target.value, }) } onFocus(e) { this.setState({ focus: e.target.name }) } onBlur(e) { this.setState({ focus: "" }) } toggleRemember() { this.setState({ remember: !this.state.remember }) } setImage(img) { if (typeof img === "object") { let reader = new FileReader(); reader.readAsDataURL(img[0]); reader.onloadend = () => { this.setState({image: reader.result}); }; } else { this.setState({image: null}); } } onGeoLocate() { navigator.geolocation.getCurrentPosition((location) => { const coords = location.coords; axios.get("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + coords.latitude + "," + coords.longitude + "&key=AIzaSyA8zfwWQ-K9UXLe64adjv_dn8ELzk6yLdA") .then((res) => { this.setState({ location: res.data.results[1].formatted_address, latitude: coords.latitude, longitude: coords.longitude, }); }) .catch((error) => { console.log(error) }) }) } isValid() { let { errors, isValid} = validateInput({ name: this.state.name, location: this.state.location, latitude: String(this.state.latitude), longitude: String(this.state.longitude), description: this.state.description, }); if (!this.state.validLocation) { isValid = false; errors['location'] = 'Invalid location'; } if (!this.state.image) { isValid = false; errors['image'] = 'Missing image' } if (!isValid) { this.setState({ errors }); } return isValid; } onSubmit(e) { e.preventDefault(); this.props.deleteFlashMessage(); if (this.isValid()) { this.setState({ isLoading: true, }); const blobImage = dataUriToBlob(this.refs.cropper.getCroppedCanvas().toDataURL()); let fd = new FormData(); fd.append("image", blobImage); axios.post(IMG_PATH + '/upload/photo', fd, { headers: { 'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*', } } ) .then(res => { this.props.client.mutate({ mutation: CREATE_ITEM, variables: { name: this.state.name, location: this.state.location, latitude: this.state.latitude, longitude: this.state.longitude, description: this.state.description, userId: this.props.auth.user._id, picturePath: res.data.filename,//'item-no-image.jpeg', created: new Date().toISOString(), active: true, views: [], viewCount: 0, type: "offer", activated: [], deleted: [], reviews: [], transactions: [], requests: [], } }) .then(({data}) => { this.setState({isLoading: false}); if (localStorage.getItem('token')) { localStorage.setItem('token', data.createItem.token); this.props.setCurrentUser(data.createItem.token); } else if (sessionStorage.getItem('token')) { sessionStorage.setItem('token', data.createItem.token); this.props.setCurrentUser(data.createItem.token); } this.props.push('/profile/main'); }) .catch((error) => { this.props.addFlashMessage({ type: 'error', text: error.message }); this.setState({flashMessage: 'error', isLoading: false}) }); }) .catch(err => { console.log(err); }); } } render() { return ( <div className="row"> <div className="col-xl-8 order-xl-2 col-lg-8 order-lg-2 col-md-12 order-md-1 col-sm-12 col-xs-12"> <div className="ui-block"> <div className="ui-block-title"> <h5 className="bold">Offer something you are not using</h5> </div> <div className="ui-block-content"> <form onSubmit={this.onSubmit}> <div className="row"> <div className="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <Input name='name' label= 'What do you want to offer?' type='text' errors={this.state.errors} focus={this.state.focus} value={this.state.name} onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} autoFocus={true} placeholder="What do you want to offer?" /> </div> <div className="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div className={classNames("form-group label-floating", {"has-error": this.state.errors['location']} )} > <div className={classNames("input-group", {"no-geolocation": !navigator.geolocation} )}> <PlacesSearchBox googleMapURL= 'https://maps.googleapis.com/maps/api/js?key=AIzaSyA8zfwWQ-K9UXLe64adjv_dn8ELzk6yLdA&libraries=geometry,drawing,places' loadingElement= {<input type="text" name="location" className="form-control taller-input" placeholder="Where do you have it?" />} containerElement= '<div style={{ height: `400px` }} />' name='location' label= 'Where do you have it?' ref='searchBox' type='text' errors={this.state.errors} focus={this.state.focus} value={this.state.location} onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} setState={this.setState.bind(this)} validLocation={this.state.validLocation} latitude={this.state.latitude} longitude={this.state.longitude} /> {navigator.geolocation ? <span className="input-group-btn"> <button onClick={this.onGeoLocate} className="btn btn-secondary get-location" type="button">Get</button> </span> : "" } </div> </div> </div> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div className={classNames("form-group label-floating", {"has-error": this.state.errors['description']} )} > <label className="control-label">Description</label> <textarea name="description" className="form-control" value={this.state.description} onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} /> </div> <UploadImage setImage={this.setImage.bind(this)} addFlashMessage={this.props.addFlashMessage} deleteFlashMessage={this.props.deleteFlashMessage} flashMessages={this.props.flashMessages} missing={!!this.state.errors.image} /> {this.props.flashMessages ? <FlashMessageList messages={this.props.flashMessages} deleteFlashMessage={this.props.deleteFlashMessage} /> : "" } {this.state.image ? <section> <Cropper src={this.state.image} style={{height:"300px", width: "100%"}} ref='cropper' aspectRatio={1} guides={false} /> </section> : '' } </div> </div> </form> </div> </div> </div> <ItemPreview name={this.state.name} description={this.state.description} location={this.state.location} latitude={Number(this.state.latitude)} longitude={Number(this.state.longitude)} radiusOfSearch={20} onSubmit={this.onSubmit} buttonMessage="Offer" /> </div> ) } } NewOffer.propTypes = { auth: PropTypes.object.isRequired, push: PropTypes.func.isRequired, addFlashMessage: PropTypes.func.isRequired, deleteFlashMessage: PropTypes.func.isRequired, setCurrentUser: PropTypes.func.isRequired, flashMessages: PropTypes.array.isRequired, }; NewOffer = withApollo(NewOffer); export default NewOffer;
scripts/routes.js
stylecoder/flux-react-router-example
'use strict'; import React from 'react'; import { Route } from 'react-router'; import App from './App'; import RepoPage from './pages/RepoPage'; import UserPage from './pages/UserPage'; export default ( <Route name='explore' path='/' handler={App}> <Route name='repo' path='/:login/:name' handler={RepoPage} /> <Route name='user' path='/:login' handler={UserPage} /> </Route> );
front_end/front_end_app/src/client/components/editable.react.js
carlodicelico/horizon
import './editable.styl'; import Component from '../components/component.react'; import React from 'react'; import Textarea from 'react-textarea-autosize'; import classnames from 'classnames'; import immutable from 'immutable'; import {msg} from '../intl/store'; const State = immutable.Record({ isEditing: false, value: '' }); const initialState = new State; export default class Editable extends Component { static propTypes = { className: React.PropTypes.string, disabled: React.PropTypes.bool, editButtons: React.PropTypes.func, id: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]).isRequired, isRequired: React.PropTypes.bool, maxRows: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]), name: React.PropTypes.string.isRequired, onSave: React.PropTypes.func.isRequired, onState: React.PropTypes.func.isRequired, rows: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]), showEditButtons: React.PropTypes.bool, showViewButtons: React.PropTypes.bool, state: React.PropTypes.instanceOf(State), text: React.PropTypes.string.isRequired, type: React.PropTypes.string, viewButtons: React.PropTypes.func } static defaultProps = { isRequired: true, showEditButtons: false, showViewButtons: false, editButtons: (onSaveClick, onCancelClick, disabled) => <div className="btn-group"> <button disabled={disabled} onClick={onSaveClick}>Save</button> <button disabled={disabled} onClick={onCancelClick}>Cancel</button> </div>, viewButtons: (onEditClick, disabled) => <div className="btn-group"> <button disabled={disabled} onClick={onEditClick}>Edit</button> </div> } constructor(props) { super(props); this.cancelEdit = ::this.cancelEdit; this.enableEdit = ::this.enableEdit; this.onInputChange = ::this.onInputChange; this.onInputFocus = ::this.onInputFocus; this.onInputKeyDown = ::this.onInputKeyDown; this.onViewClick = ::this.onViewClick; this.saveEdit = ::this.saveEdit; } onInputChange(e) { this.setState(state => state.set('value', e.target.value)); } onInputFocus(e) { this.moveCaretToEnd(e.target); } moveCaretToEnd(field) { const isSelectable = /text|password|search|tel|url/.test(field.type); if (!isSelectable) return; const length = field.value.length; field.selectionStart = length; field.selectionEnd = length; } onInputKeyDown(e) { switch (e.key) { case 'Enter': this.onKeyEnter(); break; case 'Escape': this.onKeyEscape(); break; } } onKeyEnter() { if (this.props.type === 'textarea') return; this.saveEdit(); } saveEdit() { if (!this.isDirty()) { this.disableEdit(); return; } const value = this.props.state.value.trim(); if (!value && this.props.isRequired) return; this.props .onSave(this.props.id, this.props.name, value) .then(() => { this.disableEdit(); }); } isDirty() { return this.props.state.value !== this.props.text; } onKeyEscape() { this.cancelEdit(); } cancelEdit() { if (!this.isDirty()) { this.disableEdit(); return; } if (!confirm(msg('components.editable.cancelEdit'))) // eslint-disable-line no-alert return; this.disableEdit(); } disableEdit() { this.setState(state => null); } onViewClick(e) { this.enableEdit(); } enableEdit() { this.setState(state => state.merge({ isEditing: true, value: this.props.text })); } setState(callback) { this.props.onState( this.props.id, this.props.name, callback(this.props.state || initialState) ); } render() { const { className, disabled, editButtons, maxRows, rows, showEditButtons, showViewButtons, state, text, type, viewButtons } = this.props; const isEditing = state && state.isEditing; if (!isEditing) return ( <div className={classnames('editable view', className)}> <span onClick={this.onViewClick}>{text}</span> {showViewButtons && viewButtons(this.enableEdit, disabled)} </div> ); const fieldProps = { autoFocus: true, disabled: disabled, onChange: this.onInputChange, onFocus: this.onInputFocus, onKeyDown: this.onInputKeyDown, value: state.value }; const field = type === 'textarea' ? <Textarea {...fieldProps} maxRows={maxRows} rows={rows} /> : <input {...fieldProps} type={type || 'text'} />; return ( <div className={classnames('editable edit', className)}> {field} {(showEditButtons || type === 'textarea') && editButtons(this.saveEdit, this.cancelEdit, disabled)} </div> ); } }
src/entypo/Typing.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Typing'; let EntypoTyping = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M16,4H4C2.899,4,2,4.9,2,6v7c0,1.1,0.899,2,2,2h4l4,3v-3h4c1.1,0,2-0.9,2-2V6C18,4.9,17.1,4,16,4z M6,10.6c-0.607,0-1.1-0.492-1.1-1.1c0-0.608,0.492-1.1,1.1-1.1s1.1,0.492,1.1,1.1C7.1,10.107,6.607,10.6,6,10.6z M10,10.6c-0.607,0-1.1-0.492-1.1-1.1c0-0.608,0.492-1.1,1.1-1.1s1.1,0.492,1.1,1.1C11.1,10.107,10.607,10.6,10,10.6z M14,10.6c-0.607,0-1.1-0.492-1.1-1.1c0-0.608,0.492-1.1,1.1-1.1s1.1,0.492,1.1,1.1C15.1,10.107,14.607,10.6,14,10.6z"/> </EntypoIcon> ); export default EntypoTyping;
modules/Home/Logo.js
cloudytimemachine/frontend
import React from 'react' const Logo = ({props}) => { return ( <div className="logo"> <img className="img-responsive" src="images/ctm_logo.png" alt="Cloudy Time Machine Logo" /> </div> ) } export default Logo;
src/components/PeerInfoTitle/PeerInfoTitle.js
dialogs/dialog-web-components
/* * Copyright 2019 dialog LLC <info@dlg.im> * @flow strict */ import React from 'react'; import Icon from '../Icon/Icon'; import classNames from 'classnames'; import Markdown from '../Markdown/Markdown'; import decorators from './decorators'; import styles from './PeerInfoTitle.css'; export type PeerInfoTitleProps = { title: string, inline: boolean, userName?: ?string, className?: string, titleClassName?: string, userNameClassName?: string, verifiedIconClassName?: string, onTitleClick?: ?(event: SyntheticMouseEvent<>) => mixed, onUserNameClick?: ?(event: SyntheticMouseEvent<>) => mixed, addSpacebars: boolean, emojiSize?: number, isVerified?: ?boolean, isFluid: boolean, }; export function PeerInfoTitle({ title, inline, userName, className, titleClassName, userNameClassName, verifiedIconClassName, onTitleClick, onUserNameClick, addSpacebars, emojiSize, isVerified, isFluid, }: PeerInfoTitleProps) { const spacebars = addSpacebars ? '\u00A0\u00A0' : null; return ( <span className={classNames( styles.container, { [styles.fluid]: isFluid }, className, )} > <span className={classNames(styles.title, titleClassName)} style={onTitleClick ? { cursor: 'pointer' } : undefined} onClick={onTitleClick} title={title} > <Markdown inline={inline} emojiSize={emojiSize} decorators={decorators} text={title} /> {spacebars} </span> {userName ? ( <span className={classNames(styles.userName, userNameClassName)} style={onUserNameClick ? { cursor: 'pointer' } : undefined} onClick={onUserNameClick} title={`@${userName}`} > {`@${userName}`} {spacebars} </span> ) : null} {isVerified ? ( <Icon glyph="verified" size={16} className={classNames(styles.verifiedIcon, verifiedIconClassName)} /> ) : null} </span> ); } PeerInfoTitle.defaultProps = { addSpacebars: false, inline: true, isFluid: false, };
src/index.js
marcosfede/random-quote-machine
import React from 'react' import ReactDOM from 'react-dom' import App from './App' import './index.css' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); ReactDOM.render( <MuiThemeProvider> <App /> </MuiThemeProvider>, document.getElementById('root') )
src/js/components/button/button.js
working-minds/realizejs
import React, { Component } from 'react'; import PropTypes from '../../prop_types'; import i18n from '../../i18n/i18n'; import { autobind, mixin } from '../../utils/decorators'; import Icon from '../icon/icon'; import CssClassMixin from '../../mixins/css_class_mixin'; import RequestHandlerMixin from '../../mixins/request_handler_mixin'; import InputText from "../input/input_text"; // TODO (PJ): Separar em dois componentes os concerns de href e actionURL. @mixin(CssClassMixin, RequestHandlerMixin) export default class Button extends Component { static propTypes = { name: PropTypes.localizedString, type: PropTypes.string, icon: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), buttonStyle: PropTypes.oneOf(['danger', 'primary', 'warning', 'cancel']), disabled: PropTypes.bool, href: PropTypes.string, onClick: PropTypes.func, actionUrl: PropTypes.string, actionData: PropTypes.object, isLoading: PropTypes.bool, disableWith: PropTypes.localizedString, confirmsWith: PropTypes.string, target: PropTypes.string, method: PropTypes.string, hidden: PropTypes.bool, element: PropTypes.component, }; static defaultProps = { themeClassKey: 'button', name: '', disabled: false, isLoading: false, icon: null, href: null, onClick: null, actionUrl: null, actionData: {}, disableWith: 'loading', confirmsWith: null, element: 'button', method: 'POST', hidden: false, buttonStyle: 'primary', }; static ommitedProps = [ 'onComplete', 'onSuccess', 'onRequest', 'buttonStyle', 'confirmsWith', 'disableWith', 'actionData', 'actionUrl', 'isLoading', 'themeClassKey', 'clearTheme', 'element', 'imgSrc', 'iconAlign', ]; constructor(props) { super(props); this.state = { themeClassKey: this.getButtonThemeClassKey() + this.getStyleThemeClassKey(), }; } getButtonThemeClassKey() { const { themeClassKey, name } = this.props; return (!name || name.length === 0) ? `${themeClassKey} button.iconOnly` : themeClassKey; } getStyleThemeClassKey() { const { buttonStyle } = this.props; return (buttonStyle) ? ` button.${buttonStyle}` : ''; } getClassName() { return (this.props.disabled) ? `${this.className()}button btn-flat disable-action-button` : this.className(); } getHref() { return (this.props.disabled) ? '#!' : this.props.href; } getIconClassName() { return (!this.props.name || this.props.name.length === 0) ? '' : 'right'; } @autobind handleClick(event) { const { onClick, actionUrl, actionData, method, confirmsWith } = this.props; if (confirmsWith && !confirm(i18n.t(confirmsWith))) return; if (typeof onClick === 'function') { onClick(event); } else if (actionUrl) { this.performRequest(actionUrl, actionData, method); } } prepareProps() { return _.omit(this.propsWithoutCSS(), Button.ommitedProps); } renderIcon() { const { icon } = this.props; const iconProps = (typeof icon === 'string') ? { type: icon } : icon; if (!icon) return <span />; return ( <Icon className={this.getIconClassName()} {...iconProps} /> ); } renderLoadingIndicator() { return ( <span>{i18n.t(this.props.disableWith)}</span> ); } renderContent() { return ( <span> <span>{i18n.t(this.props.name)}</span> {this.renderIcon()} </span> ); } render() { const { hidden, disabled, isLoading } = this.props; const ButtonElement = this.props.element; const buttonContent = (isLoading) ? this.renderLoadingIndicator() : this.renderContent(); if (hidden) return <span />; return ( <ButtonElement {...this.prepareProps()} className={this.getClassName()} disabled={disabled || isLoading} href={this.getHref()} onClick={this.handleClick} > {buttonContent} </ButtonElement> ); } }
app/containers/HomePage1/index.js
dedywahyudi/lilly-contentful
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; // import RichTextEditor from 'react-rte'; import { Link } from 'react-router'; // import { Checkbox, Grid, Modal, Icon } from 'semantic-ui-react'; import ReactModal from 'react-modal'; import Sortable from 'react-sortablejs'; // import { makeSelectPage, makeSelectRepos, makeSelectLoading, makeSelectError } from './selectors'; // import { changeSearch, loadStudioRepos, changeMainNav } from '../App/actions'; // import { makeSelectSearch } from '../App/selectors'; // import { loadRepos } from './actions'; const FontAwesome = require('react-fontawesome'); // const Select = require('react-select'); class HomePage1 extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function // static propTypes = { // // onChange: PropTypes.func, // }; constructor(props) { super(props); this.state = { showModal: false, // valueTextEditor: RichTextEditor.createEmptyValue(), checked: false, list: [ // { value: 'learn Sortable' }, // { value: 'use gn-sortable' }, // { value: 'Enjoy' }, // { value: 'Collapsible Section' }, { value: 'Summary (Basic Content)' }, { value: 'Overview (Basic Content)', selected: false }, { value: 'Key Related (Link List)', selected: false }, { value: 'Contact Information (Data Table)', selected: false }, ], }; this.handleOpenModal = this.handleOpenModal.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this); this.onChange = this.onChange.bind(this); // this.handleKeyPress = this.handleKeyPress.bind(this); // this.handleSubmit = this.handleSubmit.bind(this); } componentWillMount() { // this.props.onSubmitForm(); // this.props.onLoadStudio(); } componentDidMount() { // this.props.onChangeSearcDefault(''); } onChange() { this.setState({ checked: !this.state.checked }); // console.log(`this.state.checked: ` + this.state.checked); if (this.state.checked === false) { this.context.router.push('/collapsible-section'); } } handleOpenModal() { this.setState({ showModal: true }); } handleCloseModal() { this.setState({ showModal: false }); } render() { return ( <div id="sub-page"> <Helmet title="Lilly Contentful" meta={[ { name: 'description', content: 'Lilly Contentful' }, ]} /> <div className="wrapper sub-page"> <div id="two-cols"> <div id="left-col"> <div className="contentful-box border-grey"> <div className="cf-form-field"> <label className="cf-text-dimmed">Contain one or more content sections within a collapsible section?</label> <div className="cf-form-horizontal"> <div className="cf-form-option"> <input type="checkbox" id="option-d" defaultChecked={this.state.checked} onChange={this.onChange} /> <label htmlFor="option-d">Yes</label> </div> </div> </div> <div className="cf-form-field"> <ReactModal isOpen={this.state.showModal} contentLabel="Minimal Modal Example" style={{ overlay: { backgroundColor: 'rgba(0, 0, 0, 0.8)', }, content: { border: '0', borderRadius: '4px', bottom: 'auto', minHeight: '200px', left: '50%', padding: '20px', position: 'fixed', right: 'auto', top: '50%', transform: 'translate(-50%,-50%)', minWidth: '400px', width: '50%', maxWidth: '400px', backgroundColor: '#DB2828', }, }} > <div className="modal-content"> <div className="modal-message"> Are you sure you want to delete Overview section from this page? <br /> This cannot be undone </div> <div className="cf-form-field ovHidden"> <div className="fRight"> <button className="cf-btn-secondary" onClick={this.handleCloseModal}>No</button> <Link to="/homepage1"> <button className="cf-btn-primary success">Yes</button> </Link> </div> </div> </div> </ReactModal> <ReactModal isOpen={this.state.showModalCollapsible} contentLabel="Minimal Modal Example" style={{ overlay: { backgroundColor: 'rgba(0, 0, 0, 0.8)', }, content: { border: '0', borderRadius: '4px', bottom: 'auto', minHeight: '200px', left: '50%', padding: '20px', position: 'fixed', right: 'auto', top: '50%', transform: 'translate(-50%,-50%)', minWidth: '400px', width: '50%', maxWidth: '400px', backgroundColor: '#DB2828', }, }} > <div className="modal-content"> <div className="modal-message"> <p>Are you sure you want to remove Collapsible section from this page?</p> <p className="smaller">The content within the collapsible section will NOT be deleted</p> </div> <div className="cf-form-field ovHidden"> <div className="fRight"> <button className="cf-btn-secondary" onClick={this.handleCloseModalCollapsible}>No</button> <Link to="/collapsible-section"> <button className="cf-btn-primary success">Yes</button> </Link> </div> </div> </div> </ReactModal> <div className="cf-form-field"> <Sortable tag="ul" // Defaults to "div" id="sortable-section" // items={this.state.list} // onChange={(items) => { // this.setState({ items }); // console.log(`this.state.list: ` + JSON.stringify(this.state.list)); // }} options={{ animation: 150, // handle: '.drag', // group: { // name: 'shared', // pull: true, // put: true, // }, }} > { this.state.list.map((item, index) => { return ( <li key={index}> <div className="collapsible-item"> <div className="collapsible-left"> <button href="#" className="drag"><FontAwesome name="ellipsis-v" /></button> <label htmlFor="option-d">{item.value}</label> </div> <div className="collapsible-right"> <Link to="/edit-section"> <button>Edit</button> </Link> <button onClick={this.handleOpenModal}>Delete</button> </div> </div> </li> ) }) } </Sortable> </div> </div> {/* <div className="cf-form-field"> <div className="collapsible-item"> <div className="collapsible-left"> <button href="#" className="drag"><FontAwesome name="ellipsis-v" /></button> <label>Overview (Basic Content)</label> </div> <div className="collapsible-right"> <Link to="/edit-section"> <button>Edit</button> </Link> <button onClick={this.handleOpenModal}>Delete</button> </div> </div> <div className="collapsible-item"> <div className="collapsible-left"> <button href="#" className="drag"><FontAwesome name="ellipsis-v" /></button> <label>Key Related (Link List)</label> </div> <div className="collapsible-right"> <Link to="/edit-section"> <button>Edit</button> </Link> <button onClick={this.handleOpenModal}>Delete</button> </div> </div> <div className="collapsible-item"> <div className="collapsible-left"> <button href="#" className="drag"><FontAwesome name="ellipsis-v" /></button> <label>Contact Information (Data Table)</label> </div> <div className="collapsible-right"> <Link to="/edit-section"> <button>Edit</button> </Link> <button onClick={this.handleOpenModal}>Delete</button> </div> </div> <div className="collapsible-item"> <div className="collapsible-left"> <button href="#" className="drag"><FontAwesome name="ellipsis-v" /></button> <label>Summary (Basic Content)</label> </div> <div className="collapsible-right"> <Link to="/edit-section"> <button>Edit</button> </Link> <button onClick={this.handleOpenModal}>Delete</button> </div> </div> </div> */} <div className="cf-form-field"> <label className="cf-text-dimmed">Add New Content Section</label> <Link to="/basic-content"> <button className="cf-btn-primary">Basic Content</button> </Link> <Link to="/data-table"> <button className="cf-btn-primary">Data Table</button> </Link> <Link to="/link-list"> <button className="cf-btn-primary">Link List</button> </Link> <Link to="/video"> <button className="cf-btn-primary">Video</button> </Link> <Link to="/team-member"> <button className="cf-btn-primary">Team Member</button> </Link> <Link to="/local-content"> <button className="cf-btn-primary">Local Content</button> </Link> </div> </div> </div> </div> </div> </div> ); } } HomePage1.contextTypes = { router: PropTypes.object.isRequired, }; // Wrap the component to inject dispatch and state into it export default HomePage1;
frontend/react-stack/react/aluraflix/src/index.js
wesleyegberto/courses-projects
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import './index.css'; import Home from './pages/Home'; import Pagina404 from './pages/Pagina404'; import CadastroVideo from './pages/CadastroVideo'; import CadastroCategoria from './pages/CadastroCategoria'; ReactDOM.render( // <React.StrictMode> // <App /> // </React.StrictMode>, <BrowserRouter> <Switch> <Route path="/" component={Home} exact /> <Route path="/nova-categoria" component={CadastroCategoria} exact /> <Route path="/novo-video" component={CadastroVideo} exact /> <Route component={Pagina404} /> </Switch> </BrowserRouter>, document.getElementById('root') );
client/src/components/Explorer/ExplorerPanel.js
mikedingjan/wagtail
import PropTypes from 'prop-types'; import React from 'react'; import FocusTrap from 'focus-trap-react'; import { STRINGS, MAX_EXPLORER_PAGES } from '../../config/wagtailConfig'; import Button from '../Button/Button'; import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'; import Transition, { PUSH, POP } from '../Transition/Transition'; import ExplorerHeader from './ExplorerHeader'; import ExplorerItem from './ExplorerItem'; import PageCount from './PageCount'; /** * The main panel of the page explorer menu, with heading, * menu items, and special states. */ class ExplorerPanel extends React.Component { constructor(props) { super(props); this.state = { transition: PUSH, paused: false, }; this.onItemClick = this.onItemClick.bind(this); this.onHeaderClick = this.onHeaderClick.bind(this); this.clickOutside = this.clickOutside.bind(this); } componentWillReceiveProps(newProps) { const { path } = this.props; const isPush = newProps.path.length > path.length; this.setState({ transition: isPush ? PUSH : POP, }); } componentDidMount() { document.querySelector('[data-explorer-menu-item]').classList.add('submenu-active'); document.body.classList.add('explorer-open'); document.addEventListener('mousedown', this.clickOutside); document.addEventListener('touchend', this.clickOutside); } componentWillUnmount() { document.querySelector('[data-explorer-menu-item]').classList.remove('submenu-active'); document.body.classList.remove('explorer-open'); document.removeEventListener('mousedown', this.clickOutside); document.removeEventListener('touchend', this.clickOutside); } clickOutside(e) { const { onClose } = this.props; const explorer = document.querySelector('[data-explorer-menu]'); const toggle = document.querySelector('[data-explorer-menu-item]'); const isInside = explorer.contains(e.target) || toggle.contains(e.target); if (!isInside) { onClose(); } if (toggle.contains(e.target)) { this.setState({ paused: true, }); } } onItemClick(id, e) { const { pushPage } = this.props; e.preventDefault(); e.stopPropagation(); pushPage(id); } onHeaderClick(e) { const { path, popPage } = this.props; const hasBack = path.length > 1; if (hasBack) { e.preventDefault(); e.stopPropagation(); popPage(); } } renderChildren() { const { page, nodes } = this.props; let children; if (!page.isFetching && !page.children.items) { children = ( <div key="empty" className="c-explorer__placeholder"> {STRINGS.NO_RESULTS} </div> ); } else { children = ( <div key="children"> {page.children.items.map((id) => ( <ExplorerItem key={id} item={nodes[id]} onClick={this.onItemClick.bind(null, id)} /> ))} </div> ); } return ( <div className="c-explorer__drawer"> {children} {page.isFetching ? ( <div key="fetching" className="c-explorer__placeholder"> <LoadingSpinner /> </div> ) : null} {page.isError ? ( <div key="error" className="c-explorer__placeholder"> {STRINGS.SERVER_ERROR} </div> ) : null} </div> ); } render() { const { page, onClose, path } = this.props; const { transition, paused } = this.state; return ( <FocusTrap tag="div" role="dialog" className="explorer" paused={paused || !page || page.isFetching} focusTrapOptions={{ initialFocus: '.c-explorer__header', onDeactivate: onClose, }} > <Button className="c-explorer__close u-hidden" onClick={onClose}> {STRINGS.CLOSE_EXPLORER} </Button> <Transition name={transition} className="c-explorer" component="nav" label={STRINGS.PAGE_EXPLORER}> <div key={path.length} className="c-transition-group"> <ExplorerHeader depth={path.length} page={page} onClick={this.onHeaderClick} /> {this.renderChildren()} {page.isError || page.children.items && page.children.count > MAX_EXPLORER_PAGES ? ( <PageCount page={page} /> ) : null} </div> </Transition> </FocusTrap> ); } } ExplorerPanel.propTypes = { nodes: PropTypes.object.isRequired, path: PropTypes.array.isRequired, page: PropTypes.shape({ isFetching: PropTypes.bool, children: PropTypes.shape({ count: PropTypes.number, items: PropTypes.array, }), }).isRequired, onClose: PropTypes.func.isRequired, popPage: PropTypes.func.isRequired, pushPage: PropTypes.func.isRequired, }; export default ExplorerPanel;
examples/cra-ts-kitchen-sink/src/stories/docgen-tests/jsdoc/jsdoc.js
storybooks/react-storybook
/* eslint-disable react/no-unused-prop-types */ /* eslint-disable react/require-default-props */ import React from 'react'; import PropTypes from 'prop-types'; export const JsDocProps = () => <div>JSDoc with PropTypes!</div>; JsDocProps.propTypes = { /** * should not be visible since it's ignored. * @ignore */ case0: PropTypes.string, /** * simple description. */ case1: PropTypes.string, /** * multi * lines * description */ case2: PropTypes.string, /** * *description* **with** `formatting` */ case3: PropTypes.string, /** * simple description and dummy JSDoc tag. * @param event */ case4: PropTypes.string, /** * @param event */ case5: PropTypes.string, /** * simple description with a @. */ case6: PropTypes.string, case7: PropTypes.func, /** * func with a simple description. */ case8: PropTypes.func, /** * @param event */ case9: PropTypes.func, /** * param with name * @param event */ case10: PropTypes.func, /** * param with name & type * @param {SyntheticEvent} event */ case11: PropTypes.func, /** * param with name, type & description * @param {SyntheticEvent} event - React's original event */ case12: PropTypes.func, /** * param with type * @param {SyntheticEvent} */ case13: PropTypes.func, /** * param with type & description * @param {SyntheticEvent} - React's original event */ case14: PropTypes.func, /** * param with name & description * @param event - React's original event */ case15: PropTypes.func, /** * autofix event- * @param event- React's original event */ case16: PropTypes.func, /** * autofix event. * @param event. * @returns {string} */ case17: PropTypes.func, /** * with an empty param. * @param */ case18: PropTypes.func, /** * with multiple empty params. * @param * @param * @param */ case19: PropTypes.func, /** * with arg alias. * @arg event */ case20: PropTypes.func, /** * with argument alias. * @argument event */ case21: PropTypes.func, /** * with multiple params. * @param {SyntheticEvent} event * @param {string} stringValue * @param {number} numberValue */ case22: PropTypes.func, /** * with an empty returns * @returns */ case23: PropTypes.func, /** * with a returns with a type * @returns {SyntheticEvent} */ case24: PropTypes.func, /** * with a returns with a type & description * @returns {SyntheticEvent} - React's original event */ case25: PropTypes.func, /** * single param and a returns * @param {string} stringValue * @returns {SyntheticEvent} - React's original event */ case26: PropTypes.func, /** * multiple params and a returns * @param {string} stringValue * @param {number} numberValue * @returns {SyntheticEvent} - React's original event */ case27: PropTypes.func, /** * multiple returns * @returns {SyntheticEvent} - React's original event * @returns {string} - Second returns */ case28: PropTypes.func, /** * param with unsupported JSDoc tags * @param {SyntheticEvent} event - React's original event * @type {number} * @version 2 */ case29: PropTypes.func, /** * param record type * @param {{a: number, b: string}} myType */ case30: PropTypes.func, /** * param array type * @param {string[]} myType */ case31: PropTypes.func, /** * param union type * @param {(number|boolean)} myType */ case32: PropTypes.func, /** * param any type * @param {*} myType */ case33: PropTypes.func, /** * param repeatable type * @param {...number} myType */ case34: PropTypes.func, /** * optional param * @param {number} [myType] */ case35: PropTypes.func, /** * optional param * @param {number} [myType] */ case36: PropTypes.func, /** * dot in param name * @param {number} my.type */ case37: PropTypes.func, /** * returns record type * @returns {{a: number, b: string}} */ case38: PropTypes.func, /** * returns array type * @returns {string[]} */ case39: PropTypes.func, /** * returns union type * @returns {(number|boolean)} */ case40: PropTypes.func, /** * returns any type * @returns {*} */ case41: PropTypes.func, /** * returns primitive * @returns {string} */ case42: PropTypes.func, /** * returns void * @returns {void} */ case43: PropTypes.func, }; export const FailingJsDocProps = () => <div>Failing JSDoc Props!</div>; FailingJsDocProps.propTypes = { /** * autofix event. * @param event. */ case: PropTypes.func, };
containers/animalScene.js
marxsk/zobro
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import AnimalScene from '../components/animalScene'; import {setLastAnimal, setReaderLevel} from '../actions' const mapStateToProps = (state) => { return { configuration: state.configuration, } } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ setLastAnimal, setReaderLevel, }, dispatch); } class MainMenu extends React.Component { constructor(props) { super(props); } render() { return ( <AnimalScene animal={this.props.animal} bg={this.props.bg} navigator={this.props.navigator} {...this.props.configuration} setLastAnimal={this.props.setLastAnimal} setReaderLevel={this.props.setReaderLevel} /> ); } } export default connect(mapStateToProps, mapDispatchToProps)(MainMenu)
frontend/src/containers/BackupDetails/subpage/StatsContent.js
XiaocongDong/mongodb-backup-manager
import React, { Component } from 'react'; import BackupStats from 'components/BackupStats'; export default class StatsContent extends Component { render() { return ( <div className="stats-content"> <BackupStats backupConfig={ this.props.backupConfig }/> </div> ) } }
docs/src/GettingStartedPage.js
victorzhang17/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; import Anchor from './Anchor'; export default class Page extends React.Component { render() { return ( <div> <NavMain activePage="getting-started" /> <PageHeader title="Getting started" subTitle="An overview of React-Bootstrap and how to install and use." /> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <h2 className="page-header"><Anchor id="setup">Setup</Anchor></h2> <p className="lead">You can import the lib as AMD modules, CommonJS modules, or as a global JS script.</p> <p>First add the Bootstrap CSS to your project; check <a href="http://getbootstrap.com/getting-started/" name="Bootstrap Docs">here</a> if you have not already done that. Note that:</p> <ul> <li>Because many folks use custom Bootstrap themes, we do not directly depend on Bootstrap. It is up to you to to determine how you get and link to the Bootstrap CSS and fonts.</li> <li>React-Bootstrap doesn't depend on a very precise version of Bootstrap. Just pull the latest and, in case of trouble, take hints on the version used by this documentation page. Then, have Bootstrap in your dependencies and ensure your build can read your Less/Sass/SCSS entry point.</li> </ul> <p>Then:</p> <h3><Anchor id="commonjs">CommonJS</Anchor></h3> <div className="highlight"> <CodeExample codeText={ `$ npm install react $ npm install react-bootstrap` } /> <br /> <CodeExample mode="javascript" codeText={ `var Alert = require('react-bootstrap/lib/Alert'); // or var Alert = require('react-bootstrap').Alert;` } /> </div> <h3><Anchor id="es6">ES6</Anchor></h3> <div className="highlight"> <CodeExample codeText={ `$ npm install react $ npm install react-bootstrap` } /> <br /> <CodeExample mode="javascript" codeText={ `import Button from 'react-bootstrap/lib/Button'; // or import { Button } from 'react-bootstrap';` } /> </div> <h3><Anchor id="amd">AMD</Anchor></h3> <div className="highlight"> <CodeExample codeText={ `$ bower install react $ bower install react-bootstrap` } /> <br /> <CodeExample mode="javascript" codeText={ `define(['react-bootstrap'], function(ReactBootstrap) { var Alert = ReactBootstrap.Alert; ... });` } /> </div> <h3 className="page-header"><Anchor id="browser-globals">Browser globals</Anchor></h3> <p>The bower repo contains <code>react-bootstrap.js</code> and <code>react-bootstrap.min.js</code> with all components exported in the <code>window.ReactBootstrap</code> object.</p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react.js"></script> <script src="path/to/react-bootstrap-bower/react-bootstrap.min.js"></script> <script> var Alert = ReactBootstrap.Alert; </script>` } /> </div> </div> <div className="bs-docs-section"> <h2 className="page-header"><Anchor id="browser-support">Browser support</Anchor></h2> <p>We aim to support all browsers supported by both <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">React</a> and <a href="http://getbootstrap.com/getting-started/#support">Bootstrap</a>.</p> <p>Unfortunately, due to the lack of resources and the will of dedicating the efforts to modern browsers and getting closer to Bootstrap's features, we will not be testing <code>react-bootstrap</code> against IE8 anymore. <br/>We will however continue supporting IE8 as long as people submit PRs addressing compatibility issues with it.</p> <p>React requires <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">polyfills for non-ES5 capable browsers.</a></p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<!--[if lt IE 9]> <script> (function(){ var ef = function(){}; window.console = window.console || {log:ef,warn:ef,error:ef,dir:ef}; }()); </script> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` } /> </div> </div> </div> </div> </div> <PageFooter /> </div> ); } shouldComponentUpdate() { return false; } }
_reference_dup-src-ignore/index.js
Ankiewicz/veteran-mentor
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import PlayerReducer from './reducers/player'; import Scoreboard from './containers/Scoreboard'; const store = createStore( PlayerReducer, window.devToolsExtension && window.devToolsExtension() ); render( <Provider store={store}> <Scoreboard /> </Provider>, document.getElementById('root') );
docs/src/PaginationPage.js
jsbranco/react-materialize
import React from 'react'; import Row from '../../src/Row'; import Col from '../../src/Col'; import ReactPlayground from './ReactPlayground'; import PropTable from './PropTable'; import store from './store'; import Samples from './Samples'; import pagination from '../../examples/Pagination'; class PaginationPage extends React.Component { componentDidMount() { store.emit('component', 'Pagination'); } render() { return ( <Row> <Col m={9} s={12} l={10}> <p className='caption'> Add pagination links to help split up your long content into shorter, easier to understand blocks. You just have to provide the items and onSelect attribute, when clicked, the onSelect function will be called with the page number. Otherwise you can customize the page button with PaginationButton component. </p> <Col s={12}> <ReactPlayground code={ Samples.pagination }> {pagination} </ReactPlayground> </Col> <Col s={12}> <PropTable component='Pagination'/> <PropTable component='PaginationButton'/> </Col> </Col> </Row> ); } } export default PaginationPage;
src/components/Label/Label.js
ggrumbley/ghg-react
import React from 'react'; import PropTypes from 'prop-types'; /** Label with required field display, htmlFor, and block styling */ const Label = ({ htmlFor, label, required }) => { return ( <label style={{display: 'block'}} htmlFor={htmlFor}> { label } { required && <span style={{color: 'red'}}> *</span> } </label> ); } Label.propTypes = { /** HTML ID for associated input */ htmlFor: PropTypes.string.isRequired, /** Label text */ label: PropTypes.string.isRequired, /** Display asterisk after label if true */ required: PropTypes.bool }; export default Label;
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/FormComponents/CheckboxOrRadioGroup.js
lakmali/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'; const CheckboxOrRadioGroup = (props) => ( <div> <label className="form-label">{props.title}</label> <div className="checkbox-group"> {props.options.map(option => { return ( <label key={option} className="form-label capitalize"> <input className="form-checkbox" name={props.setName} onChange={props.controlFunc} value={option} checked={props.selectedOptions.indexOf(option) > -1} type={props.type} /> {option} </label> ); })} </div> </div> ); CheckboxOrRadioGroup.propTypes = { title: React.PropTypes.string.isRequired, type: React.PropTypes.oneOf(['checkbox', 'radio']).isRequired, setName: React.PropTypes.string.isRequired, options: React.PropTypes.array.isRequired, selectedOptions: React.PropTypes.array, controlFunc: React.PropTypes.func.isRequired }; export default CheckboxOrRadioGroup;
src/components/docker/original/DockerOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DockerOriginal.svg' /** DockerOriginal */ function DockerOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'DockerOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DockerOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DockerOriginal
LogFileReader/log-viewer-fe/app/containers/NavBar/index.js
luungoc2005/LogFileReader
import React from 'react'; import { Menu } from 'semantic-ui-react'; import { HOME_ITEM } from './constants'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectActiveItem } from './selectors'; import { changeActiveItem } from './actions' class NavBar extends React.PureComponent { static propTypes = { changeActiveItem: React.PropTypes.func, activeItem: React.PropTypes.string, }; render() { const { activeItem } = this.props return ( <div> <Menu pointing secondary> <Menu.Item name={HOME_ITEM} active={activeItem === HOME_ITEM} onClick={this.props.changeActiveItem} /> </Menu> </div> ); } } const mapStateToProps = createSelector( makeSelectActiveItem(), (activeItem) => ({ activeItem }) ); function mapDispatchToProps(dispatch) { return { dispatch, changeActiveItem: (e, {name}) => dispatch(changeActiveItem(name)) }; } export default connect(mapStateToProps, mapDispatchToProps)(NavBar);
src/browser/components/fxbml.js
chad099/react-native-boilerplate
// @flow // Higher order component for Facebook XFBML. // Examples // https://gist.github.com/steida/04a39dfa1043e1451044ba8370743b0c // https://gist.github.com/steida/b19a1858e38007651a616ae44244ca52 import React from 'react'; const xfbml = (WrappedComponent: any) => class Wrapper extends React.Component { el: Element; isMounted: boolean; parseXfbmlAsap() { if (window.FB) { window.FB.XFBML.parse(this.el); return; } const fbAsyncInit = window.fbAsyncInit; // Aspect Oriented Programming ftw. window.fbAsyncInit = () => { fbAsyncInit(); if (!this.isMounted) return; window.FB.XFBML.parse(this.el); }; } componentDidMount() { this.isMounted = true; this.parseXfbmlAsap(); } componentWillUnmount() { this.isMounted = false; } onWrappedComponentRef(el: Element) { this.el = el; } render() { return ( <WrappedComponent {...this.props} ref={el => this.onWrappedComponentRef(el)} /> ); } }; export default xfbml;
lab-nodejs/lab-nodejs-react-ux/src/components/Comp2/index.js
rojarsmith/Lab
import React from 'react'; import { Link } from "react-router-dom"; const Comp2 = () => { return ( <div>Comp2 <div style={{ width: '50vw', height: '2160px', border: '2px #cccccc dashed' }}></div> Comp2 END </div> ) }; export default Comp2;
src/components/Header/Header.js
ademuk/flyguy-flux
import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return <Navigation/>; } } export default Header;
src/components/need/BookingAgent/ResidentInspect.js
lethecoa/work-order-pc
import React from 'react'; import {Form, DatePicker, Input, Radio, Checkbox} from 'antd'; import moment from 'moment'; import {config, fun} from '../../../common'; import CarryMaterial from '../../formItme/CarryMaterial/CarryMaterial'; import styles from './ResidentInspect.less'; const RadioGroup = Radio.Group; const RangePicker = DatePicker.RangePicker; const CheckboxGroup = Checkbox.Group; const materialOptions = [ { label: '临床血液检验:a.白细胞 b.红细胞 c.血小板 d.血红蛋白', value: 1 }, { label: '临床尿液检查:a.红细胞 b.白细胞 c.上皮细胞', value: 2 }, { label: '肝功能', value: 3 }, { label: '肾功能', value: 4 }, { label: '血脂', value: 5 }, { label: '心电图', value: 6 }, { label: 'B超', value: 7 }, ]; function ResidentInspect( props ) { const FormItem = Form.Item; const { getFieldDecorator } = props.form; return ( <div className={styles.need}> <div className={styles.title}>需求说明</div> <div className={styles.form}> <FormItem label="预约体检项目" {...config.formItemLayout}> {getFieldDecorator( 'examineItem', { initialValue: props.examineItem ? fun.strToIntArr( props.examineItem ) : [], rules: [ { required: true, message: '请至少选择其中一项!' }, ], } )( <CheckboxGroup options={materialOptions} disabled={props.disabled}/> )} </FormItem> <FormItem label="所需携带材料" {...config.formItemLayout}> {getFieldDecorator( 'carryMaterial', { initialValue: props.carryMaterial ? fun.strToIntArr( props.carryMaterial ) : [ 1 ], rules: [ { required: true, message: '请至少选择其中一项!' }, ], } )( <CarryMaterial disabled={props.disabled}/> )} </FormItem> <FormItem {...config.formItemLayout} label="体检注意事项"> {getFieldDecorator( 'announcements', { initialValue: props.announcements ? parseInt( props.announcements ) : 0 } )( <RadioGroup disabled={props.disabled}> <Radio value={1}>空腹:晚上10点后不摄入食物</Radio> <Radio value={0}>无</Radio> </RadioGroup> )} </FormItem> <FormItem label="体检地点" {...config.formItemLayout}> {getFieldDecorator( 'examineSite', { initialValue: props.examineSite, rules: [ { required: true, message: '必须填写体检地点!' }, ], } )( <Input placeholder="请输入您希望的体检地点" disabled={props.disabled}/> )} </FormItem> <FormItem label="预约体检时间" {...config.formItemLayout} help="时间需精确到小时(日期选择里可以切换时间显示,默认使用当前的时间)"> {getFieldDecorator( 'allowDate', { initialValue: props.examineDateStart ? [ moment( new Date( parseInt( props.examineDateStart ) ), 'YYYY-MM-DD HH:mm' ), moment( new Date( parseInt( props.examineDateEnd ) ), 'YYYY-MM-DD HH:mm' ) ] : [], rules: [ { required: true, type: 'array', message: '请选择一个预约体检时间段,精确到小时!' }, ], } )( <RangePicker size="small" showTime format="YYYY-MM-DD HH:mm" disabled={props.disabled} disabledDate={( current ) => current && current.valueOf() < Date.now()} /> )} </FormItem> <FormItem {...config.formItemLayout} label="体检是否免费"> {getFieldDecorator( 'isFree', { initialValue: props.isFree ? parseInt( props.isFree ) : 0 } )( <RadioGroup disabled={props.disabled}> <Radio value={1}>是</Radio> <Radio value={0}>否</Radio> </RadioGroup> )} </FormItem> <FormItem {...config.formItemLayout} label="其他要求"> {getFieldDecorator( 'otherRequirements', { initialValue: props.otherRequirements } )( <Input type="textarea" rows={4} placeholder="请在此输入您的其它要求" disabled={props.disabled}/> )} </FormItem> </div> </div> ); } export default Form.create()( ResidentInspect );
website/src/pages/404.js
frontyard/keystone
import React, { Component } from 'react'; import Container from '../../components/Container'; import { compose } from 'glamor'; import Link from 'gatsby-link'; import Header from '../../components/Header'; import theme from '../../theme'; import Footer from './components/home/Footer'; const Body = () => ( <div className={compose(styles.content)}> <h1 className={compose(styles.heading)}>Whoops! Nothing to see here.</h1> <p className={compose(styles.subHeading)}> Something should have been here, but apparently it's not. No worries, here are a couple of helpful links that will get you on your way! </p> <div className={compose(styles.buttons)}> <Link to="/getting-started" className={compose( styles.button, styles.buttonPrimary )}> Get started </Link> <a href="http://demo.keystonejs.com/" className={compose( styles.button, styles.buttonSecondary )} target="_blank"> Documentation </a> </div> </div> ); export default class extends Component { render () { return ( <div> <div className={compose(styles.wrapper)}> <Container> <Header /> <Body /> </Container> </div> <Footer /> </div> ); } } const styles = { wrapper: { background: 'linear-gradient(145deg, #00c1da, #003bca)', color: 'white', padding: '2rem 0 4em', position: 'relative', width: '100vw', height: '100vh', overflow: 'hidden' }, content: { padding: '8em 0 0', textAlign: 'center', margin: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '80%', [theme.breakpoint.mediumDown]: { width: '100%', padding: '4rem 0rem 0', }, }, heading: { color: 'white', fontSize: '3rem', [theme.breakpoint.mediumDown]: { fontSize: '2.5rem', }, }, subHeading: { fontSize: '1.25rem', opacity: 0.8, }, buttons: { display: 'inline-flex', marginTop: '1.25rem', alignItems: 'center', }, button: { background: 'white', color: theme.color.blue, textDecoration: 'none', fontSize: '1.25rem', padding: '1rem 2rem', borderRadius: 6, transition: 'transform linear 120ms', ':hover': { transform: 'scale(1.025)', }, ':active': { opacity: 0.8, }, }, buttonPrimary: { textTransform: 'uppercase', fontWeight: '500', }, buttonSecondary: { display: 'flex', background: 'none', color: 'white', fontSize: '1.25rem', border: '2px solid rgba(255,255,255,0.4)', marginLeft: '1rem', }, };
src/components/topic/summary/StoryTotalsSummaryContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import MenuItem from '@material-ui/core/MenuItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ActionMenu from '../../common/ActionMenu'; import withFilteredAsyncData from '../FilteredAsyncDataContainer'; import withSummary from '../../common/hocs/SummarizedVizualization'; import { fetchTopicStoryCounts } from '../../../actions/topicActions'; import BubbleRowChart from '../../vis/BubbleRowChart'; import { DownloadButton } from '../../common/IconButton'; import { topicDownloadFilename } from '../../util/topicUtil'; import { getBrandDarkColor } from '../../../styles/colors'; import messages from '../../../resources/messages'; import { downloadSvg } from '../../util/svg'; const BUBBLE_CHART_DOM_ID = 'bubble-chart-story-total'; const localMessages = { title: { id: 'topic.summary.storyTotals.title', defaultMessage: 'Filtered Story Count' }, descriptionIntro: { id: 'topic.summary.storyTotals.help.title', defaultMessage: '<p>Any filters you choose to apply will focus in on a smaller set of the stories within this topic. Here you can see how many stories you are looking at, from the total stories within the topic.</p>', }, description: { id: 'topic.summary.storyTotals.help.into', defaultMessage: '<p>This bubble chart shows you how many stories from this Topic are included in the filters you have selected. The "filtered" bubble is the number of stories included in your filters. The "Total" bubble is the total stories within this topic.</p>', }, filteredLabel: { id: 'topic.summary.storyTotals.filtered', defaultMessage: 'Filtered' }, totalLabel: { id: 'topic.summary.storyTotals.total', defaultMessage: 'Total' }, }; const StoryTotalsSummaryContainer = (props) => { const { counts, topicName, filters } = props; const { formatMessage, formatNumber } = props.intl; let content = null; if (counts !== null) { const data = [ // format the data for the bubble chart help { value: counts.count, fill: getBrandDarkColor(), aboveText: formatMessage(localMessages.filteredLabel), aboveTextColor: 'rgb(255,255,255)', rolloverText: `${formatMessage(localMessages.filteredLabel)}: ${formatNumber(counts.count)} stories`, }, { value: counts.total, aboveText: formatMessage(localMessages.totalLabel), rolloverText: `${formatMessage(localMessages.totalLabel)}: ${formatNumber(counts.total)} stories`, }, ]; content = ( <BubbleRowChart data={data} domId={BUBBLE_CHART_DOM_ID} /> ); } return ( <> {content} <div className="actions"> <ActionMenu actionTextMsg={messages.downloadOptions}> <MenuItem className="action-icon-menu-item" onClick={() => downloadSvg(`${topicDownloadFilename(topicName, filters)}-filtered-story-count`, BUBBLE_CHART_DOM_ID)} > <ListItemText><FormattedMessage {...messages.downloadSVG} /></ListItemText> <ListItemIcon><DownloadButton /></ListItemIcon> </MenuItem> </ActionMenu> </div> </> ); }; StoryTotalsSummaryContainer.propTypes = { // from compositional chain intl: PropTypes.object.isRequired, // from parent topicId: PropTypes.number.isRequired, topicName: PropTypes.string.isRequired, filters: PropTypes.object.isRequired, // from state counts: PropTypes.object, fetchStatus: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ fetchStatus: state.topics.selected.summary.storyTotals.fetchStatus, counts: state.topics.selected.summary.storyTotals.counts, filters: state.topics.selected.filters, }); const fetchAsyncData = (dispatch, props) => dispatch(fetchTopicStoryCounts(props.topicId, props.filters)); export default injectIntl( connect(mapStateToProps)( withSummary(localMessages.title, localMessages.descriptionIntro, localMessages.description)( withFilteredAsyncData(fetchAsyncData)( StoryTotalsSummaryContainer ) ) ) );
ReactNative/appB - Copy/App.js
tahashahid/cloud-computing-2017
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ /*import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; export default class App extends Component<Props> { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit App.js </Text> <Text style={styles.instructions}> {instructions} </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, }, }); */ import React, { Component } from 'react'; import { Text, Image, View, StyleSheet } from 'react-native'; export default class HelloWorldApp extends Component { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' }; return ( <View style={{alignItems: 'center'}}> <Text style={styles.red}>just red</Text> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> <Text> Hello world! <Text>Taha!</Text> <Image source={pic} style={{width: 193, height: 110}}/> </Text> </View> ); } } class Greeting extends Component { render() { return ( <Text>Hello {this.props.name}!</Text> ); } } const styles = StyleSheet.create({ bigblue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: { color: 'red', }, });
src/svg-icons/action/flip-to-back.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFlipToBack = (props) => ( <SvgIcon {...props}> <path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); ActionFlipToBack = pure(ActionFlipToBack); ActionFlipToBack.displayName = 'ActionFlipToBack'; ActionFlipToBack.muiName = 'SvgIcon'; export default ActionFlipToBack;
packages/reactor-kitchensink/src/examples/PivotGrid/RangeEditorPlugin/RangeEditorPlugin.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Container, PivotGrid, Toolbar, Button } from '@extjs/reactor/modern'; import SaleModel from '../SaleModel'; import { generateData } from '../generateSaleData'; Ext.require(['Ext.pivot.plugin.RangeEditor']); export default class RangeEditorPlugin extends Component { store = Ext.create('Ext.data.Store', { model: SaleModel, data: generateData() }) collapseAll = () => { this.refs.pivotgrid.collapseAll(); } expandAll = () => { this.refs.pivotgrid.expandAll(); } render() { return ( <Container layout="fit" padding={10}> <PivotGrid shadow ref="pivotgrid" plugins={[{ type: 'pivotrangeeditor' }]} matrix={{ type: 'local', store: this.store, // Configure the aggregate dimensions. Multiple dimensions are supported. aggregate: [{ dataIndex: 'value', header: 'Total', aggregator: 'sum', width: 120 }], // Configure the left axis dimensions that will be used to generate the grid rows leftAxis: [{ dataIndex: 'company', header: 'Company', width: 120 }, { dataIndex: 'country', header: 'Country', direction: 'DESC', width: 150 }], /** * Configure the top axis dimensions that will be used to generate * the columns. * * When columns are generated the aggregate dimensions are also used. * If multiple aggregation dimensions are defined then each top axis * result will have in the end a column header with children columns * for each aggregate dimension defined. */ topAxis: [{ dataIndex: 'year', header: 'Year' }, { dataIndex: 'month', header: 'Month', labelRenderer: value => Ext.Date.monthNames[value] }] }} /> <Toolbar docked="top" ui="app-transparent-toolbar" padding="5 8" shadow={false} defaults={{ margin: '0 10 0 0', shadow: true, ui: 'action' }} > <Button text="Expand All" handler={this.expandAll}/> <Button text="Collapse All" handler={this.collapseAll}/> <div style={{fontSize: '12px', fontWeight: 'normal', marginLeft: '10px'}}>Double click an amount to edit.</div> </Toolbar> </Container> ) } }
src/components/icons/CautionFilledIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const CautionFilledIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M0 0h24v24H0z" fill="none" /> <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" /> </svg> ); export default CautionFilledIcon;
frontend/app_v2/src/components/GridListToggle/GridListTogglePresentation.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // FPCC import useIcon from 'common/useIcon' function GridListTogglePresentation({ accentColor, isGridView, setIsGridView }) { return ( <div className="ml-6 bg-gray-100 p-0.5 rounded-lg flex items-center"> <button type="button" onClick={() => setIsGridView(false)} className={`${ !isGridView ? `bg-white shadow-sm text-${accentColor}` : 'hover:bg-white hover:shadow-sm text-gray-400' } p-1.5 rounded-lg focus:outline-none focus:ring-2 focus:ring-inset focus:ring-${accentColor}`} > {useIcon('HamburgerMenu', 'fill-current h-5 w-5')} <span className="sr-only">Use list view</span> </button> <button type="button" onClick={() => setIsGridView(true)} className={`${ isGridView ? `bg-white shadow-sm text-${accentColor}` : 'hover:bg-white hover:shadow-sm text-gray-400' } ml-0.5 p-1.5 rounded-lg focus:outline-none focus:ring-2 focus:ring-inset focus:ring-${accentColor}`} > {useIcon('Grid', 'fill-current h-5 w-5')} <span className="sr-only">Use grid view</span> </button> </div> ) } // PROPTYPES const { bool, func, string } = PropTypes GridListTogglePresentation.propTypes = { isGridView: bool, setIsGridView: func, accentColor: string, } GridListTogglePresentation.defaultProps = { accentColor: 'primary', } export default GridListTogglePresentation
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js
glitch-soc/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { changeComposeSensitivity } from 'mastodon/actions/compose'; import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'; const messages = defineMessages({ marked: { id: 'compose_form.sensitive.marked', defaultMessage: '{count, plural, one {Media is marked as sensitive} other {Media is marked as sensitive}}', }, unmarked: { id: 'compose_form.sensitive.unmarked', defaultMessage: '{count, plural, one {Media is not marked as sensitive} other {Media is not marked as sensitive}}', }, }); const mapStateToProps = state => ({ active: state.getIn(['compose', 'sensitive']), disabled: state.getIn(['compose', 'spoiler']), mediaCount: state.getIn(['compose', 'media_attachments']).size, }); const mapDispatchToProps = dispatch => ({ onClick () { dispatch(changeComposeSensitivity()); }, }); class SensitiveButton extends React.PureComponent { static propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, mediaCount: PropTypes.number, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { active, disabled, mediaCount, onClick, intl } = this.props; return ( <div className='compose-form__sensitive-button'> <label className={classNames('icon-button', { active })} title={intl.formatMessage(active ? messages.marked : messages.unmarked, { count: mediaCount })}> <input name='mark-sensitive' type='checkbox' checked={active} onChange={onClick} disabled={disabled} /> <span className={classNames('checkbox', { active })} /> <FormattedMessage id='compose_form.sensitive.hide' defaultMessage='{count, plural, one {Mark media as sensitive} other {Mark media as sensitive}}' values={{ count: mediaCount }} /> </label> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
src/app/core/atoms/icon/icons/star-half.js
blowsys/reservo
import React from 'react'; const StarHalf = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><path d="M12,17.27 L5.82,21 L7.46,13.97 L2,9.24 L9.19,8.63 L12,2 L14.81,8.63 L22,9.24 L16.54,13.97 L18.18,21 L12,17.27 Z M12,7.12519767 L12,7.12519767 L12,14.9339482 L15.1554708,16.8384638 L14.3180455,13.2487686 L17.1076664,10.8321191 L13.4391982,10.520886 L12,7.12519767 Z"/></g></g></svg>; export default StarHalf;
packages/react/src/components/forms/InputSlider/index.js
massgov/mayflower
/** * InputSlider module. * @module @massds/mayflower-react/InputSlider * @requires module:@massds/mayflower-assets/scss/01-atoms/01-atoms/helper-text */ import React from 'react'; import PropTypes from 'prop-types'; import Input from 'MayflowerReactForms/Input'; import CompoundSlider from 'MayflowerReactForms/CompoundSlider'; const InputSlider = (props) => { const { axis, max, min, step, ticks, onChange, onUpdate, domain, skipped, displayValueFormat, ...inputProps } = props; const sliderProps = { axis, max, min, step, defaultValue: props.defaultValue, onChange, onUpdate, domain, skipped, displayValueFormat }; const { id, disabled } = inputProps; sliderProps.id = id; sliderProps.ticks = new Map(ticks); sliderProps.disabled = disabled; return( <Input {...inputProps}> <CompoundSlider {...sliderProps} /> </Input> ); }; InputSlider.propTypes = { /** Whether the label should be hidden or not */ hiddenLabel: PropTypes.bool, /** The label text for the input field */ labelText: PropTypes.string.isRequired, /** The unique ID for the input field */ id: PropTypes.string.isRequired, /** Custom change function */ onChange: PropTypes.func, /** Custom change function */ onUpdate: PropTypes.func, /** Default input text value */ defaultValue: PropTypes.string, /** Max value for the field. */ max: PropTypes.number.isRequired, /** Min value for the field. */ min: PropTypes.number.isRequired, /** This controls how much sliding the handle increments/decrements the value of the slider. */ step: PropTypes.number, /** An array where each entry is an array of [key,value] pairs. The key (number inclusively between min and max) and value (label to display at the key) are used for displaying tick marks. */ ticks: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** The direction for the slider, where x is horizontal and y is vertical. */ axis: PropTypes.oneOf(['x', 'y']), /** Disables the slider if true. */ disabled: PropTypes.bool, /** Whether input is required or not */ required: PropTypes.bool, /** The range of numbers, inclusively, for the slider to fall between. First number is the min and second number is the max. */ domain: PropTypes.arrayOf(PropTypes.number), /** Whether to skip the slider with keyboard interaction and hide the slider on screen readers. */ skipped: PropTypes.bool, /** Display the value of the slider based. If null, don't display. If equals percentage, format the value in percentage. */ displayValueFormat: PropTypes.oneOf(['percentage', 'value', null]) }; InputSlider.defaultProps = { defaultValue: 0, disabled: false }; export default InputSlider;
app/javascript/mastodon/features/generic_not_found/index.js
rutan/mastodon
import React from 'react'; import Column from '../ui/components/column'; import MissingIndicator from '../../components/missing_indicator'; const GenericNotFound = () => ( <Column> <MissingIndicator /> </Column> ); export default GenericNotFound;
frontend/src/components/editor/attachments/list.js
1905410/Misago
// jshint ignore:start import React from 'react'; import Attachment from './attachment'; export default function(props) { return ( <ul className="list-unstyled editor-attachments-list"> {props.attachments.map((item) => { return ( <Attachment item={item} key={item.id || item.key} {...props} /> ); })} </ul> ); };
modules/IndexRoute.js
hgezim/react-router
import React from 'react' import invariant from 'invariant' import warning from 'warning' import { createRouteFromReactElement } from './RouteUtils' import { component, components, falsy } from './PropTypes' const { bool, func } = React.PropTypes /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ const 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/components/Search/AdvancedSearch.js
terryli1643/thinkmore
import React from 'react' import PropTypes from 'prop-types' import ReactDOM from 'react-dom' import styles from './Search.less' import { DatePicker, Input, Select, Button, Icon } from 'antd' import moment from 'moment'; const { RangePicker } = DatePicker; const dateFormat = 'YYYY/MM/DD'; class AdvancedSearch extends React.Component { state = { clearVisible: false, selectValue: (this.props.select && this.props.selectProps) ? this.props.selectProps.defaultValue : '', }; handleSearch = () => { const data = { keyword: ReactDOM.findDOMNode(this.refs.searchInput).value, }; if (this.props.select) { data.field = this.state.selectValue } if (this.props.onSearch) this.props.onSearch(data) }; handleInputChange = e => { this.setState({ ...this.state, clearVisible: e.target.value !== '', }) }; handeleSelectChange = value => { this.setState({ ...this.state, selectValue: value, }) }; handleClearInput = () => { ReactDOM.findDOMNode(this.refs.searchInput).value = ''; this.setState({ clearVisible: false, }); this.handleSearch() }; render () { const { size, select, selectOptions, selectProps, style, keyword } = this.props; const { clearVisible } = this.state; return ( <div> <Input.Group compact size={size} className={styles.search} style={style}> {select && <Select ref="searchSelect" onChange={this.handeleSelectChange} size={size} {...selectProps}> {selectOptions && selectOptions.map((item, key) => <Select.Option value={item.value} key={key}>{item.name || item.value}</Select.Option>)} </Select>} <RangePicker defaultValue={[moment(), moment()]} format={dateFormat} /> <Input ref="searchInput" size={size} style={{ width: '50%' }} onChange={this.handleInputChange} onPressEnter={this.handleSearch} placeholder="支持以姓名,手机,订单号,快递单号查询"/> <Button size={size} type="primary" icon="search" onClick={this.handleSearch}>搜索</Button> {clearVisible && <Icon type="cross" onClick={this.handleClearInput} />} </Input.Group> </div> ) } } AdvancedSearch.propTypes = { size: PropTypes.string, select: PropTypes.bool, selectProps: PropTypes.object, onSearch: PropTypes.func, selectOptions: PropTypes.array, style: PropTypes.object, keyword: PropTypes.string, }; export default AdvancedSearch
assets/javascript/components/editActivity/activityLink.js
colinjeanne/learning-site
import { activityLinkPropType } from './../propTypes'; import React from 'react'; const activityLink = props => { return ( <section className="activityLink"> <span>{props.activityLink.title}</span> <span> (<a href={props.activityLink.uri}>{props.activityLink.uri}</a>) </span> <button onClick={() => props.onDelete(props.activityLink.uri)}> Delete </button> </section> ); }; activityLink.propTypes = { activityLink: activityLinkPropType.isRequired, onDelete: React.PropTypes.func.isRequired }; export default activityLink;
src/interface/statistics/components/RadarChart/SvgWrappingText.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { select } from 'd3-selection'; class SvgWrappingText extends React.PureComponent { static propTypes = { children: PropTypes.string.isRequired, width: PropTypes.number.isRequired, }; elem = null; constructor() { super(); this.elem = React.createRef(); } componentDidMount() { this.wrap(this.elem.current, this.props.width); } // Wrap SVG text so long lines are condensed // Taken from http://bl.ocks.org/mbostock/7555321. Cleaned it up a little to meet our coding style. wrap(elem, width) { const text = select(elem); const words = text.text().split(/\s+/); let line = []; let lineNumber = 0; const lineHeight = 1.4; // ems const y = text.attr('y'); const x = text.attr('x'); const dy = parseFloat(text.attr('dy')); let tspan = text.text(null).append('tspan').attr('x', x).attr('y', y).attr('dy', dy + 'em'); // noinspection JSAssignmentUsedAsCondition words.forEach(word => { line.push(word); tspan.text(line.join(' ')); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(' ')); line = [word]; lineNumber += 1; tspan = text.append('tspan').attr('x', x).attr('y', y).attr('dy', lineNumber * lineHeight + dy + 'em').text(word); } }); } render() { return ( <text {...this.props} ref={this.elem} /> ); } } export default SvgWrappingText;
src/client/app/home.react.js
srhmgn/markdowner
import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; class Home extends Component { render() { return ( <DocumentTitle title="Home"> <div> <h1>Home</h1> </div> </DocumentTitle> ); } } export default Home;
client/src/js/component/AdminAuthHandler.js
lologarithm/fastbible
import React from 'react'; const {div, span, h1} = React.DOM; import component from 'component'; import {routeNames} from 'constants'; import {RouteHandler, Router} from './router-jsx'; import LeftNav from './LeftNav'; export default component({ displayName: 'LoginView', mixins: [Router.State, Router.Navigation], componentWillMount() { console.log(this.isLoggedIn()); this.redirectToLogin(); }, componentWillUpdate() { this.redirectToLogin(); }, redirectToLogin() { if (!this.isLoggedIn()) { this.transitionTo(routeNames.login); } }, render() { return div({className: 'fb-auth-content'}, LeftNav(), div({className: 'fb-content'}, RouteHandler() ) ); } });
example/examples/DraggableMarkers.js
palexs/react-native-maps
import React from 'react'; import { StyleSheet, View, Dimensions, } from 'react-native'; import MapView from 'react-native-maps'; import PriceMarker from './PriceMarker'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; function log(eventName, e) { console.log(eventName, e.nativeEvent); } class MarkerTypes extends React.Component { constructor(props) { super(props); this.state = { a: { latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }, b: { latitude: LATITUDE - SPACE, longitude: LONGITUDE - SPACE, }, }; } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={{ latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }} > <MapView.Marker coordinate={this.state.a} onSelect={(e) => log('onSelect', e)} onDrag={(e) => log('onDrag', e)} onDragStart={(e) => log('onDragStart', e)} onDragEnd={(e) => log('onDragEnd', e)} onPress={(e) => log('onPress', e)} draggable > <PriceMarker amount={99} /> </MapView.Marker> <MapView.Marker coordinate={this.state.b} onSelect={(e) => log('onSelect', e)} onDrag={(e) => log('onDrag', e)} onDragStart={(e) => log('onDragStart', e)} onDragEnd={(e) => log('onDragEnd', e)} onPress={(e) => log('onPress', e)} draggable /> </MapView> </View> ); } } MarkerTypes.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, }); module.exports = MarkerTypes;
templates/react/components/foo/Create.js
api-platform/generate-crud
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import Form from './Form'; import { create, reset } from '../../actions/{{{lc}}}/create'; class Create extends Component { static propTypes = { error: PropTypes.string, loading: PropTypes.bool.isRequired, created: PropTypes.object, create: PropTypes.func.isRequired, reset: PropTypes.func.isRequired }; componentWillUnmount() { this.props.reset(); } render() { if (this.props.created) return ( <Redirect to={`edit/${encodeURIComponent(this.props.created['@id'])}`} /> ); return ( <div> <h1>New {{{title}}}</h1> {this.props.loading && ( <div className="alert alert-info" role="status"> Loading... </div> )} {this.props.error && ( <div className="alert alert-danger" role="alert"> <span className="fa fa-exclamation-triangle" aria-hidden="true" />{' '} {this.props.error} </div> )} <Form onSubmit={this.props.create} values={this.props.item} /> <Link to="." className="btn btn-primary"> Back to list </Link> </div> ); } } const mapStateToProps = state => { const { created, error, loading } = state.{{{lc}}}.create; return { created, error, loading }; }; const mapDispatchToProps = dispatch => ({ create: values => dispatch(create(values)), reset: () => dispatch(reset()) }); export default connect(mapStateToProps, mapDispatchToProps)(Create);
main.js
lublank/blank-react
/** * main.js入口文件,把App和redux建立联系,Provider是react-redux的组件, * 用于将store和视图绑定在一起,Store就是那个唯一的State树。当Store发生变化时, * 整个App就会做出相应的变化,这里的会传进Provider的props.children里。 */ import React from 'react'; import {createStore} from 'redux'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import App from './App.jsx'; import todoReducer from './reducers/reducers'; import './dist/todo.less'; /** * 创建store, 传入两个参数, * 参数1: reducer 用来修改state, * 参数2(可选): [], 默认的state值,如果不传, 则为undefined */ let store = createStore(todoReducer); /** * 通过 store.getState() 可以获取当前store的状态(state) * @type {Element} */ let rootElement = document.getElementById('app'); ReactDOM.render( <Provider store={store}> <App /> </Provider>, rootElement );
icandevit/src/components/Nav.js
yeli-buonya/icandevit.io
import React from 'react'; import logo from '../header.svg'; import { Link } from 'react-router-dom'; import { Collapse, Col, Row, Grid, Jumbotron, Media, MenuItem, NavDropdown, Navbar, NavbarToggler, NavbarBrand, PageHeader, Image, Nav, NavItem, NavLink } from 'react-bootstrap'; class Navigation extends React.Component { render() { return ( <Navbar collapseOnSelect fixedTop> <Navbar.Header> <Navbar.Brand> <Link activeClass='active' to='/'>icandevit.io</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> <NavItem style={{ textAlign: 'center' }}> <Link activeClass='active' to='/'>Home</Link> </NavItem> <NavItem style={{ textAlign: 'center' }}> <Link activeClass='active' to='/about'>About</Link> </NavItem> <NavItem style={{ textAlign: 'center' }}> <Link activeClass='active' to='/github'>Github</Link> </NavItem> </Nav> </Navbar.Collapse> </Navbar> ); } } /*class Navigation extends React.Component { render() { return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <a className="navbar-brand">icandevit.io</a> </div> <div className="collapse navbar-collapse" id="myNavbar"> <ul className="nav navbar-nav navbar-right"> <li><Link to='/'>Home</Link></li> <li><Link to='/about'>About</Link></li> <li><Link to='/contact'>Contact</Link></li> </ul> </div> </div> </nav> ) } }*/ export default Navigation;
app/assets/scripts/components/workshop-fold.js
openaq/openaq.github.io
'use strict'; import React from 'react'; var WorkshopFold = React.createClass({ displayName: 'WorkshopFold', render: function () { return ( <section className='workshop-fold'> <div className='inner'> <header className='workshop-fold__header'> <h1 className='workshop-fold__title'>Hold a Workshop</h1> <div className='prose prose--responsive'> <p>Interested in convening various members of your community around open air quality data? We can help!</p> <p> <a href='mailto:info@openaq.org' className='workshop-go-button'> <span>Contact Us</span> </a> </p> </div> </header> <figure className='workshop-fold__media'> <img src='/assets/graphics/content/view--community-workshops/workshop-fold-media.jpg' alt='Cover image' width='830' height='830' /> </figure> </div> </section> ); } }); module.exports = WorkshopFold;
components/toolbar/index.js
react-material-design/react-material-design
import '@material/toolbar/dist/mdc.toolbar.css'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import classNames from 'classnames'; import { MDCToolbar } from '@material/toolbar'; import ToolbarRow from './toolbarRow'; class Toolbar extends Component { static propTypes = { children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element), ]), darkTheme: PropTypes.bool, fixed: PropTypes.bool, } constructor(props) { super(props); this.mainRoot = React.createRef(); } componentDidMount() { this.toolbar = new MDCToolbar(this.mainRoot.current); } render() { const { children, darkTheme, fixed, ...rest } = this.props; return ( <header ref={this.mainRoot} className={classNames('mdc-toolbar', { 'mdc-toolbar--theme-dark': darkTheme }, { 'mdc-toolbar--fixed': fixed })}> <ToolbarRow {...rest} /> {children} </header> ); } } export default Toolbar;
actor-apps/app-web/src/app/components/dialog/messages/MessageItem.react.js
liruqi/actor-platform-v0.9
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import classnames from 'classnames'; import VisibilitySensor from 'react-visibility-sensor'; import DialogActionCreators from 'actions/DialogActionCreators'; import { MessageContentTypes } from 'constants/ActorAppConstants'; import AvatarItem from 'components/common/AvatarItem.react'; import Text from './Text.react'; import Image from './Image.react'; import Document from './Document.react'; import State from './State.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class MessageItem extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired, message: React.PropTypes.object.isRequired, isNewDay: React.PropTypes.bool, isSameSender: React.PropTypes.bool, onVisibilityChange: React.PropTypes.func }; constructor(props) { super(props); //this.state = { // isActionsShown: false //}; } onClick = () => { const { message } = this.props; DialogActionCreators.selectDialogPeerUser(message.sender.peer.id); }; onVisibilityChange = (isVisible) => { const { message } = this.props; this.props.onVisibilityChange(message, isVisible); }; onDelete = () => { const { peer, message } = this.props; DialogActionCreators.deleteMessages(peer, [message.rid]); }; //showActions = () => { // this.setState({isActionsShown: true}); // document.addEventListener('click', this.hideActions, false); //}; //hideActions = () => { // this.setState({isActionsShown: false}); // document.removeEventListener('click', this.hideActions, false); //}; render() { const { message, isSameSender, onVisibilityChange } = this.props; let header = null, messageContent = null, visibilitySensor = null, leftBlock = null; const messageClassName = classnames('message row', { 'message--same-sender': isSameSender }); //let actionsDropdownClassName = classnames({ // 'dropdown': true, // 'dropdown--small': true, // 'dropdown--opened': this.state.isActionsShown //}); if (isSameSender) { leftBlock = ( <div className="message__info text-right"> <time className="message__timestamp">{message.date}</time> <State message={message}/> </div> ); } else { leftBlock = ( <div className="message__info message__info--avatar"> <a onClick={this.onClick}> <AvatarItem image={message.sender.avatar} placeholder={message.sender.placeholder} title={message.sender.title}/> </a> </div> ); header = ( <header className="message__header"> <h3 className="message__sender"> <a onClick={this.onClick}>{message.sender.title}</a> </h3> <time className="message__timestamp">{message.date}</time> <State message={message}/> </header> ); } switch (message.content.content) { case MessageContentTypes.SERVICE: messageContent = <div className="message__content message__content--service">{message.content.text}</div>; break; case MessageContentTypes.TEXT: messageContent = ( <Text content={message.content} className="message__content message__content--text"/> ); break; case MessageContentTypes.PHOTO: messageContent = ( <Image content={message.content} className="message__content message__content--photo" loadedClassName="message__content--photo--loaded"/> ); break; case MessageContentTypes.DOCUMENT: messageContent = ( <Document content={message.content} className="message__content message__content--document"/> ); break; default: return null; } if (onVisibilityChange) { visibilitySensor = <VisibilitySensor onChange={this.onVisibilityChange}/>; } return ( <li className={messageClassName}> {leftBlock} <div className="message__body col-xs"> {header} {messageContent} {visibilitySensor} </div> {/* <div className="message__actions"> <i className="material-icons" onClick={this.onDelete}>close</i> </div> <div className="message__actions hide"> <div className={actionsDropdownClassName}> <span className="dropdown__button" onClick={this.showActions}> <i className="material-icons">arrow_drop_down</i> </span> <ul className="dropdown__menu dropdown__menu--right"> <li className="dropdown__menu__item"> <i className="icon material-icons">reply</i> Reply </li> <li className="dropdown__menu__item hide"> <i className="icon material-icons">forward</i> Forward </li> <li className="dropdown__menu__item" onClick={this.onDelete}> <i className="icon material-icons">close</i> Delete </li> </ul> </div> </div> */} </li> ); } } export default MessageItem;
app/client/src/components/ActionSettingsContainer/ActionSettingsContainer.js
uprisecampaigns/uprise-app
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { graphql, compose } from 'react-apollo'; import camelCase from 'camelcase'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import { Step, Stepper, StepButton, StepContent, } from 'material-ui/Stepper'; import ActivitiesQuery from 'schemas/queries/ActivitiesQuery.graphql'; import formWrapper from 'lib/formWrapper'; import { validateString, validateState, validateZipcode, } from 'lib/validateComponentForms'; import ActionProfile from 'components/ActionProfile'; import ActionSettingsForm from 'components/ActionSettingsForm'; import ActionProfileForm from 'components/ActionProfileForm'; import ShiftScheduler from 'components/ShiftScheduler'; import s from 'styles/Organize.scss'; const WrappedActionSettingsForm = formWrapper(ActionSettingsForm); const WrappedActionProfileForm = formWrapper(ActionProfileForm); class ActionSettingsContainer extends Component { static propTypes = { submit: PropTypes.func.isRequired, type: PropTypes.string.isRequired, campaign: PropTypes.object.isRequired, activities: PropTypes.arrayOf(PropTypes.object).isRequired, graphqlLoading: PropTypes.bool.isRequired, // eslint-disable-next-line react/no-unused-prop-types action: PropTypes.object, } static defaultProps = { action: { title: '', internalTitle: '', virtual: false, locationName: '', streetAddress: '', streetAddress2: '', city: '', state: '', zipcode: '', locationNotes: '', description: '', shifts: [], activities: [], tags: [], }, } constructor(props) { super(props); const ongoing = (typeof props.action === 'object' && typeof props.action.ongoing === 'boolean') ? props.action.ongoing : (props.type === 'role'); this.state = { stepIndex: 0, formData: { ...ActionSettingsContainer.defaultProps.action, ongoing, }, }; } componentWillMount() { this.handleActionProps(this.props); } componentWillReceiveProps(nextProps) { this.handleActionProps(nextProps); } settingsSubmit = async (data) => { const formData = { ...this.state.formData, ...data }; if (formData.ongoing) { this.setState({ formData, stepIndex: 1 }); } else { this.setState({ formData }); this.shiftScheduler.formSubmit(); } return { success: true, message: false, }; } defaultErrorText = { titleErrorText: null, internalTitleErrorText: null, locationNameErrorText: null, locationNotesErrorText: null, streetAddressErrorText: null, cityErrorText: null, stateErrorText: null, zipcodeErrorText: null, dateErrorText: null, } handleActionProps = (nextProps) => { if (nextProps.action && !nextProps.graphqlLoading) { // Just camel-casing property keys and checking for null const action = Object.assign(...Object.keys(nextProps.action).map((k) => { if (nextProps.action[k] !== null) { return { [camelCase(k)]: nextProps.action[k] }; } return undefined; })); Object.keys(action).forEach((k) => { if (!Object.keys(ActionSettingsContainer.defaultProps.action).includes(camelCase(k))) { delete action[k]; } }); this.setState(prevState => ({ formData: { ...prevState.formData, ...action }, })); } } shiftSubmit = (data) => { const formData = { ...this.state.formData, ...data }; this.setState({ formData, stepIndex: 1 }); } profileSubmit = async (data) => { const formData = { ...this.state.formData, ...data }; this.setState({ formData, stepIndex: 2 }); return { success: true, message: false, }; } handlePrev = () => { if (this.state.stepIndex > 0) { this.setState(prevState => ({ ...prevState, stepIndex: prevState.stepIndex - 1, })); } } toggleOngoing = (ongoing) => { this.setState(prevState => ({ formData: { ...prevState.formData, ongoing }, })); } handleNext = () => { const { formData, stepIndex } = this.state; if (stepIndex === 0) { this.actionSettingsForm.wrappedInstance.formSubmit(); } else if (stepIndex === 1) { this.actionProfileForm.wrappedInstance.formSubmit(); } else if (stepIndex === 2) { const submitData = { ...formData, activities: formData.activities.map(a => a.id), }; this.props.submit(submitData); } }; renderStepActions = (step) => { const { stepIndex } = this.state; return ( <div> <RaisedButton label={stepIndex === 2 ? 'Finish' : 'Next'} disableTouchRipple disableFocusRipple primary onClick={this.handleNext} /> {step > 0 && ( <FlatButton label="Back" disabled={stepIndex === 0} disableTouchRipple disableFocusRipple onClick={this.handlePrev} /> )} </div> ); } render() { const { defaultErrorText, renderStepActions, shiftSubmit, profileSubmit, settingsSubmit, } = this; const { formData, stepIndex } = this.state; const { campaign, activities, graphqlLoading } = this.props; if (graphqlLoading) { return null; } const activityDetails = formData.activities.map((activity) => { const activityMatch = activities.find(a => a.id === activity.id); if (activityMatch) { return { id: activity.id, title: activityMatch.title, description: activityMatch.description, long_description: activityMatch.long_description, }; } return undefined; }); const settingsValidators = [ (component) => { validateString(component, 'title', 'titleErrorText', 'Opportunity Name is Required'); }, (component) => { validateState(component); }, (component) => { validateZipcode(component); }, ]; return ( <div className={s.stepperOuterContainer}> <div className={s.stepperContainer}> <Stepper activeStep={stepIndex} orientation="vertical" className={s.stepper} > <Step> <StepButton onClick={() => this.setState({ stepIndex: 0 })}> Basic Info </StepButton> <StepContent> {renderStepActions(0)} </StepContent> </Step> <Step> <StepButton onClick={() => this.setState({ stepIndex: 1 })}> Details </StepButton> <StepContent> {renderStepActions(1)} </StepContent> </Step> <Step> <StepButton onClick={() => this.setState({ stepIndex: 2 })}> Preview </StepButton> <StepContent> {renderStepActions(2)} </StepContent> </Step> </Stepper> </div> <div className={s.stepperContentContainer}> { stepIndex === 0 && <div> <WrappedActionSettingsForm initialState={formData} initialErrors={defaultErrorText} validators={settingsValidators} submit={settingsSubmit} ref={(form) => { this.actionSettingsForm = form; }} /> { !formData.ongoing && ( <ShiftScheduler data={formData} submit={shiftSubmit} ref={(scheduler) => { this.shiftScheduler = scheduler; }} /> )} </div> } { stepIndex === 1 && <div> <WrappedActionProfileForm initialState={formData} initialErrors={defaultErrorText} validators={[]} submit={profileSubmit} ref={(form) => { this.actionProfileForm = form; }} /> </div> } { stepIndex === 2 && <ActionProfile signup={() => {}} cancelSignup={() => {}} action={{ ...formData, campaign, activities: activityDetails, }} saving={false} /> } </div> </div> ); } } export default compose(graphql(ActivitiesQuery, { props: ({ data }) => ({ activities: !data.loading && data.activities ? data.activities : [], graphqlLoading: data.loading, }), }))(ActionSettingsContainer);
examples/forms-bootstrap/src/components/forms-destroy-wizard-generic/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import config from './config'; export default createReactClass({ displayName: 'Hook', propTypes: { model: PropTypes.object.isRequired }, render: function() { const { model } = this.props; return ( <div key={model.id}> {lore.forms.tweet.destroy(model, config)} </div> ); } });
src/SField.js
thr-consulting/controls
// @flow import React from 'react'; import type {ChildrenArray} from 'react'; import {connectToMessageContainer} from 'react-input-message'; import {Form} from 'semantic-ui-react'; type Props = { for: string, messages: Object, children?: ChildrenArray<*>, }; /** * A SemanticUI field with error markings. * @class * @property {string} for - The React Formal Form.Field name. * @property {Component[]} children - React children elements. * @property {string} className - Additional class names applied to the field div. * @property {Object[]} messages - Error messages from React Formal form. */ function SField(props: Props) { return ( <Form.Field error={!!props.messages[props.for]} > {props.children} </Form.Field> ); } export default connectToMessageContainer.default(SField);
client/modules/App/components/DevTools.js
caleb272/ProjectAccent
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
static/src/index.js
tmc/parsesearch
import React from 'react'; import SearchApp from './SearchApp'; React.render(<SearchApp className={ClassName} />, document.getElementById('root'));
src/controls/InputError.js
amvmdev/amvm-ui
import React from 'react'; const styles = { 'position': 'absolute', 'bottom': '-28px', 'top': 'auto', 'zIndex': '1000' } function displaySingleMessage(error) { return (<li className="parsley-required" key={error}>{error}</li>); }; const InputError = ({error}) => { if (error && typeof (error) === "string") { // this is single error message return (<ul className="parsley-error-list filled" style={styles}>{displaySingleMessage(error)}</ul>) } else if (error && error.length > 0) { // this is array of messages return (<ul className="parsley-error-list filled" style={styles}>{error.map(displaySingleMessage)}</ul>); } return null; }; InputError.propTypes = { error: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.array ]) } export default InputError;
Electron-vanillaJS-HTML/app.js
arishuynhvan/SPi-Reader
'use strict'; /** An example */ import React from 'react'; import {render} from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Main from './src/Main'; // Our custom react component import style from './css/main.scss'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); // Render the main app react component into the app div. // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render render(<Main />, document.getElementById('app'));
app/routes.js
LeagueDevelopers/lol-skins-viewer
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import TabbedContainer from 'containers/TabbedContainer'; import App from 'containers/App'; import Skins from 'containers/Skins'; import Settings from 'containers/Settings'; import ReleaseNotes from 'containers/ReleaseNotes'; export default ( <Route path="/" component={App}> <IndexRoute component={Skins} /> <Route path="settings" component={TabbedContainer}> <IndexRoute name="Settings" component={Settings} /> <Route name="Release Notes" path="releasenotes" component={ReleaseNotes} /> </Route> </Route> );
docs/src/app/components/pages/components/Menu/Page.js
ArcanisCz/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import menuReadmeText from './README'; import MenuExampleSimple from './ExampleSimple'; import menuExampleSimpleCode from '!raw!./ExampleSimple'; import MenuExampleDisable from './ExampleDisable'; import menuExampleDisableCode from '!raw!./ExampleDisable'; import MenuExampleIcons from './ExampleIcons'; import menuExampleIconsCode from '!raw!./ExampleIcons'; import MenuExampleSecondary from './ExampleSecondary'; import menuExampleSecondaryCode from '!raw!./ExampleSecondary'; import MenuExampleNested from './ExampleNested'; import menuExampleNestedCode from '!raw!./ExampleNested'; import menuCode from '!raw!material-ui/Menu/Menu'; import menuItemCode from '!raw!material-ui/MenuItem/MenuItem'; const descriptions = { simple: 'Two simple examples. The menu widths adjusts to accommodate the content in keyline increments.', disabled: 'The `disabled` property disables a `MenuItem`. ' + '`Menu` supports a more compact vertical spacing using the `desktop` property. ' + 'The [Divider](/#/components/divider) can be used to separate `MenuItems`.', icons: '`MenuItem` supports icons through the `leftIcon` and `rightIcon` properties.', secondary: '`MenuItem` supports a `secondaryText` property.', nested: 'Cascading menus can be configured using the `menuItems` property of the `MenuItem` component.', }; const MenuPage = () => ( <div> <Title render={(previousTitle) => `Menu - ${previousTitle}`} /> <MarkdownElement text={menuReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={menuExampleSimpleCode} > <MenuExampleSimple /> </CodeExample> <CodeExample title="Disabled items" description={descriptions.disabled} code={menuExampleDisableCode} > <MenuExampleDisable /> </CodeExample> <CodeExample title="Icons" description={descriptions.icons} code={menuExampleIconsCode} > <MenuExampleIcons /> </CodeExample> <CodeExample title="Secondary text" description={descriptions.secondary} code={menuExampleSecondaryCode} > <MenuExampleSecondary /> </CodeExample> <CodeExample title="Nested menus" description={descriptions.nested} code={menuExampleNestedCode} > <MenuExampleNested /> </CodeExample> <PropTypeDescription header="### Menu Properties" code={menuCode} /> <PropTypeDescription header="### MenuItem Properties" code={menuItemCode} /> </div> ); export default MenuPage;
app/javascript/mastodon/features/follow_requests/index.js
MitarashiDango/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountAuthorizeContainer from './containers/account_authorize_container'; import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts'; import ScrollableList from '../../components/scrollable_list'; import { me } from '../../initial_state'; const messages = defineMessages({ heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'follow_requests', 'items']), isLoading: state.getIn(['user_lists', 'follow_requests', 'isLoading'], true), hasMore: !!state.getIn(['user_lists', 'follow_requests', 'next']), locked: !!state.getIn(['accounts', me, 'locked']), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class FollowRequests extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, hasMore: PropTypes.bool, isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list, locked: PropTypes.bool, domain: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFollowRequests()); } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowRequests()); }, 300, { leading: true }); render () { const { intl, accountIds, hasMore, multiColumn, locked, domain, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.follow_requests' defaultMessage="You don't have any follow requests yet. When you receive one, it will show up here." />; const unlockedPrependMessage = locked ? null : ( <div className='follow_requests-unlocked_explanation'> <FormattedMessage id='follow_requests.unlocked_explanation' defaultMessage='Even though your account is not locked, the {domain} staff thought you might want to review follow requests from these accounts manually.' values={{ domain: domain }} /> </div> ); return ( <Column bindToDocument={!multiColumn} icon='user-plus' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='follow_requests' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} emptyMessage={emptyMessage} bindToDocument={!multiColumn} prepend={unlockedPrependMessage} > {accountIds.map(id => <AccountAuthorizeContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
src/components/basicComponent/CheckboxTag/CheckboxTag.js
SmiletoSUN/react-redux-demo
/***************************************************************** * 青岛雨人软件有限公司©2016版权所有 * * 本软件之所有(包括但不限于)源代码、设计图、效果图、动画、日志、 * 脚本、数据库、文档均为青岛雨人软件或其附属子公司所有。任何组织 * 或者个人,未经青岛雨人软件书面授权,不得复制、使用、修改、分发、 * 公布本软件的任何部分。青岛雨人软件有限公司保留对任何违反本声明 * 的组织和个人采取法律手段维护合法权益的权利。 *****************************************************************/ import React from 'react'; import classNames from 'classnames'; import check from './check.png'; import Checkbox from 'rc-checkbox'; import './CheckboxTag.scss'; export default class CheckboxTag extends React.Component { static propTypes = { checked: React.PropTypes.bool, defaultChecked: React.PropTypes.bool, } static defaultProps = { prefixCls: 'icrm-checkoutTag', defaultChecked: false, } constructor(props) { super(props); let checked = false; if ('checked' in props) { checked = props.checked; } else { checked = props.defaultChecked; } this.state = { checked, }; this.handleChange = this.handleChange.bind(this); } handleChange = (e) => { this.setState({ checked: e.target.checked }); } render() { const { checked, children, className, color, disabled, onChange, prefixCls, style, ...others } = this.props; const checkIcon = checked ? <img src={check} alt="" /> : ''; const wrapperClassString = classNames({ [`${prefixCls}-wrapper`]: true, [`${prefixCls}-has-color`]: !!color, [`${prefixCls}-wrapper-checked`]: checked, [`${prefixCls}-wrapper-disabled`]: disabled, [className]: !!className, }); return ( <label className={wrapperClassString} style={color ? Object.assign({}, style, { backgroundColor: color }) : style} > <Checkbox onChange={e => this.handleChange(e)} {...this.props} /> {children ? <span> {children} {checkIcon} </span> : null } </label> ); } }
src/svg-icons/image/wb-sunny.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageWbSunny = (props) => ( <SvgIcon {...props}> <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> </SvgIcon> ); ImageWbSunny = pure(ImageWbSunny); ImageWbSunny.displayName = 'ImageWbSunny'; ImageWbSunny.muiName = 'SvgIcon'; export default ImageWbSunny;
src/components/pages/yunbook/EditView.js
yiweimatou/yishenghoutai
import React from 'react' import { Field } from 'redux-form' import { RaisedButton,MenuItem,Tabs,Tab} from 'material-ui' import TextField from '../../ReduxForm/TextField' import SelectField from '../../ReduxForm/SelectField' import AreaSelect3 from '../../AreaSelect3' import EditLblView from './EditLblView' const styles = { form:{ display:'flex', flexFlow:'column wrap', alignItems:'center' }, item:{ width:'100%' }, margin:{ marginLeft:20 }, selectDiv:{ display:'flex', justifyContent:'space-between', width:'100%' }, submit:{ display:'flex', width:'100%', flexFlow:'row wrap', marginTop:30 } } class EditView extends React.Component{ onClick(){ document.querySelector('#_submit').click() } render(){ const { submitting, invalid, handleSubmit, areaSelectProps, handleChange, changeLbl, yunbook } = this.props return ( <div> <Tabs> <Tab label="云板书基础信息编辑"> <form style = { styles.form } onSubmit={handleSubmit} > <Field name = 'title' type = 'text' hintText = '云板书名称' floatingLabelText = '云板书名称' component = {TextField} style = { styles.item } /> <Field name = 'status' type = 'text' hintText = '云板书状态' floatingLabelText = '云板书状态' component = {SelectField} style = { styles.item } > <MenuItem primaryText = '仅自己可见' value = { 1 } /> <MenuItem primaryText = '所有人可见' value={2}/> </Field> <AreaSelect3 {...areaSelectProps} handleChange={ handleChange } /> <Field name = 'descript' hintText = '云板书简介' floatingLabelText = '云板书简介' component = { TextField } multiLine = { true } rows = { 2 } style = { styles.item } /> <button type='submit' id = '_submit' hidden/> </form> </Tab> <Tab label="标注编辑"> <EditLblView changeLbl = { changeLbl } yunbook = { yunbook } /> </Tab> </Tabs> <div style = { styles.submit } > <RaisedButton label = '保存编辑' primary = { true } disabled = { submitting || invalid } onClick = { this.onClick } /> </div> </div> ) } } EditView.propTypes ={ handleSubmit:React.PropTypes.func.isRequired, submitting:React.PropTypes.bool.isRequired, invalid:React.PropTypes.bool.isRequired, areaSelectProps:React.PropTypes.object, handleChange:React.PropTypes.func.isRequired, yunbook:React.PropTypes.object, changeLbl:React.PropTypes.func.isRequired } export default EditView
src/svg-icons/av/surround-sound.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSurroundSound = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM7.76 16.24l-1.41 1.41C4.78 16.1 4 14.05 4 12c0-2.05.78-4.1 2.34-5.66l1.41 1.41C6.59 8.93 6 10.46 6 12s.59 3.07 1.76 4.24zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm5.66 1.66l-1.41-1.41C17.41 15.07 18 13.54 18 12s-.59-3.07-1.76-4.24l1.41-1.41C19.22 7.9 20 9.95 20 12c0 2.05-.78 4.1-2.34 5.66zM12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); AvSurroundSound = pure(AvSurroundSound); AvSurroundSound.displayName = 'AvSurroundSound'; export default AvSurroundSound;
node_modules/react-paginate/react_components/BreakView.js
wiflsnmo/react_study2
'use strict'; import React from 'react'; const BreakView = (props) => { const label = props.breakLabel; const className = props.breakClassName || 'break'; return ( <li className={className}> {label} </li> ); } export default BreakView;
packages/material-ui-icons/src/LocalPharmacy.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let LocalPharmacy = props => <SvgIcon {...props}> <path d="M21 5h-2.64l1.14-3.14L17.15 1l-1.46 4H3v2l2 6-2 6v2h18v-2l-2-6 2-6V5zm-5 9h-3v3h-2v-3H8v-2h3V9h2v3h3v2z" /> </SvgIcon>; LocalPharmacy = pure(LocalPharmacy); LocalPharmacy.muiName = 'SvgIcon'; export default LocalPharmacy;
src/components/Section/MoreOverlay.js
ndlib/beehive
import React from 'react' import createReactClass from 'create-react-class' const MoreOverlay = createReactClass({ style: function () { return { position: 'absolute', bottom: '0', left: '0', zIndex: '2', height: '60px', lineHeight: '60px', width: '100%', textAlign: 'center', background: 'linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,1) 55%,rgba(0,0,0,1) 100%)', } }, render: function () { return (<div style={this.style()}>MORE</div>) }, }) export default MoreOverlay
client/index.js
vibhas77/Student-Wallet
/** * Client entry point */ import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import App from './App'; import { configureStore } from './store'; // Initialize store const store = configureStore(window.__INITIAL_STATE__); const mountApp = document.getElementById('root'); render( <AppContainer> <App store={store} /> </AppContainer>, mountApp ); // For hot reloading of react components if (module.hot) { module.hot.accept('./App', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const NextApp = require('./App').default; // eslint-disable-line global-require render( <AppContainer> <NextApp store={store} /> </AppContainer>, mountApp ); }); }
src/components/portal/Single/_base.js
chaoticbackup/chaoticbackup.github.io
import React from 'react'; import { observable } from "mobx"; import { observer, inject } from 'mobx-react'; import { Link } from 'react-router-dom'; import API from '../../SpreadsheetData'; import { RarityIcon, Ability } from '../../Snippets'; import s from '../../../styles/app.style'; // own "name" display function function Name(props) { const name = props.name.split(","); return (<> <span>{name[0]}</span> { name.length > 1 && <span className="bigger"><br />{name[1].trim()}</span> } </>); } function Artist(props) { const artists = []; props.artist.split(/(?=, )/).forEach((artist, i) => { artists.push(<Link key={i} to={`/portal/Search/?${artist.replace(", ", "")}`}>{artist}</Link>); }); return (<div className="artist">{artists}</div>); } @inject((stores, props, context) => props) @observer export default class Single extends React.Component { @observable fullscreen = false; expand = (e) => { this.fullscreen = true; } close = (e) => { this.fullscreen = false; } render() { const { card } = this.props; return (<> <div className={"modal" + (this.fullscreen?"":" hidden")}> <span className="close" onClick={this.close}>&times;</span> <img className="modal-content" src={API.cardFullart(card)} /> </div> {API.hasFullart(card) && ( <div className="entry_splash"> {/*<span className="arrow">&#8681;</span>*/} <img onClick={this.expand} src={API.cardFullart(card)} /> </div> )} <div className="entry_body"> <div className="title"> <Name name={card.gsx$name} /> <hr /> </div> <div className="column"> {card.gsx$artist && (<> <div> <strong>Artist(s):</strong> <Artist artist={card.gsx$artist} /> </div> <hr /> </>)} {card.gsx$set && (<> <div> <strong>Set: </strong> {`${API.sets[card.gsx$set]} (${card.gsx$set})`} </div> <hr /> </>)} {card.gsx$rarity && (<> <div> <strong>Rarity: </strong> <RarityIcon set={card.gsx$set} rarity={card.gsx$rarity} iconOnly />&nbsp; {card.gsx$rarity} </div> <hr /> </>)} {card.gsx$id && (<> <div> <strong>Card ID: </strong> {card.gsx$id} </div> <hr /> </>)} {this.props.col0 && (<> {this.props.col0} </>)} {card.gsx$ability && (<> <hr /> <div> <strong>Ability:</strong> <Ability ability={card.gsx$ability} /> </div> </>)} {card.gsx$flavortext && (<> <hr /> <div> <strong>Card Flavor:</strong><br /> {card.gsx$flavortext} </div> </>)} {this.props.col1 && (<> <hr /> this.props.col1 </>)} </div> <div className="column"> {this.props.col2} </div> </div> </>); } }
src/client/spinner.js
kukhckr/hacker-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Loading... </div> ) } }
src/routes.js
djfm/ps-translations-interface-mockup
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Router from 'react-routing/src/Router'; import fetch from './core/fetch'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; import Translations from './components/Translations'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/translations', async ({ query }) => <Translations query={query}/>); on('/', async () => <Translations query={{ }}/>); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const response = await fetch(`/api/content?path=${state.path}`); const content = await response.json(); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/applications/my-education-benefits/config/form.js
department-of-veterans-affairs/vets-website
import React from 'react'; import { createSelector } from 'reselect'; // Example of an imported schema: // import fullSchema from '../22-1990-schema.json'; // eslint-disable-next-line no-unused-vars import commonDefinitions from 'vets-json-schema/dist/definitions.json'; import preSubmitInfo from 'platform/forms/preSubmitInfo'; import FormFooter from 'platform/forms/components/FormFooter'; import fullNameUI from 'platform/forms-system/src/js/definitions/fullName'; import emailUI from 'platform/forms-system/src/js/definitions/email'; import phoneUI from 'platform/forms-system/src/js/definitions/phone'; import currentOrPastDateUI from 'platform/forms-system/src/js/definitions/currentOrPastDate'; import dateUI from 'platform/forms-system/src/js/definitions/date'; import * as address from 'platform/forms-system/src/js/definitions/address'; import { VA_FORM_IDS } from 'platform/forms/constants'; import environment from 'platform/utilities/environment'; import bankAccountUI from 'platform/forms/definitions/bankAccount'; import * as ENVIRONMENTS from 'site/constants/environments'; import * as BUCKETS from 'site/constants/buckets'; import fullSchema from '../22-1990-schema.json'; // In a real app this would not be imported directly; instead the schema you // imported above would import and use these common definitions: import GetFormHelp from '../components/GetFormHelp'; import manifest from '../manifest.json'; import IntroductionPage from '../containers/IntroductionPage'; import ConfirmationPage from '../containers/ConfirmationPage'; import toursOfDutyUI from '../definitions/toursOfDuty'; import CustomReviewDOBField from '../components/CustomReviewDOBField'; import ServicePeriodAccordionView from '../components/ServicePeriodAccordionView'; import EmailViewField from '../components/EmailViewField'; import PhoneViewField from '../components/PhoneViewField'; import AccordionField from '../components/AccordionField'; import BenefitGivenUpReviewField from '../components/BenefitGivenUpReviewField'; import YesNoReviewField from '../components/YesNoReviewField'; import PhoneReviewField from '../components/PhoneReviewField'; import DateReviewField from '../components/DateReviewField'; import EmailReviewField from '../components/EmailReviewField'; import { chapter30Label, chapter1606Label, unsureDescription, post911GiBillNote, prefillTransformer, } from '../helpers'; import MailingAddressViewField from '../components/MailingAddressViewField'; import LearnMoreAboutMilitaryBaseTooltip from '../components/LearnMoreAboutMilitaryBaseTooltip'; import { isValidPhone, validatePhone, validateEmail, validateEffectiveDate, } from '../utils/validation'; import { createSubmissionForm } from '../utils/form-submit-transform'; import { directDepositDescription } from '../../edu-benefits/1990/helpers'; import { ELIGIBILITY } from '../actions'; const { fullName, // ssn, date, dateRange, usaPhone, email, toursOfDuty, } = commonDefinitions; // Define all the fields in the form to aid reuse const formFields = { fullName: 'fullName', userFullName: 'userFullName', dateOfBirth: 'dateOfBirth', ssn: 'ssn', toursOfDuty: 'toursOfDuty', serviceHistoryIncorrect: 'serviceHistoryIncorrect', viewNoDirectDeposit: 'view:noDirectDeposit', viewStopWarning: 'view:stopWarning', bankAccount: 'bankAccount', accountType: 'accountType', accountNumber: 'accountNumber', routingNumber: 'routingNumber', address: 'address', email: 'email', viewPhoneNumbers: 'view:phoneNumbers', phoneNumber: 'phoneNumber', mobilePhoneNumber: 'mobilePhoneNumber', viewBenefitSelection: 'view:benefitSelection', benefitRelinquished: 'benefitRelinquished', benefitEffectiveDate: 'benefitEffectiveDate', incorrectServiceHistoryExplanation: 'incorrectServiceHistoryExplanation', contactMethod: 'contactMethod', receiveTextMessages: 'receiveTextMessages', hasDoDLoanPaymentPeriod: 'hasDoDLoanPaymentPeriod', activeDutyKicker: 'activeDutyKicker', selectedReserveKicker: 'selectedReserveKicker', federallySponsoredAcademy: 'federallySponsoredAcademy', seniorRotcCommission: 'seniorRotcCommission', loanPayment: 'loanPayment', additionalConsiderationsNote: 'additionalConsiderationsNote', }; // Define all the form pages to help ensure uniqueness across all form chapters const formPages = { applicantInformation: 'applicantInformation', contactInformation: { contactInformation: 'contactInformation', mailingAddress: 'mailingAddress', preferredContactMethod: 'preferredContactMethod', }, serviceHistory: 'serviceHistory', benefitSelection: 'benefitSelection', additionalConsiderations: { activeDutyKicker: { name: 'active-duty-kicker', order: 1, title: 'Do you qualify for an active duty kicker, sometimes called a College Fund?', additionalInfo: { triggerText: 'What is an active duty kicker?', info: 'Kickers, sometimes referred to as College Funds, are additional amounts of money that increase an individual’s basic monthly benefit. Each Department of Defense service branch (and not VA) determines who receives the kicker payments and the amount received. Kickers are included in monthly GI Bill payments from VA.', }, }, reserveKicker: { name: 'reserve-kicker', order: 1, title: 'Do you qualify for a reserve kicker, sometimes called a College Fund?', additionalInfo: { triggerText: 'What is a reserve kicker?', info: 'Kickers, sometimes referred to as College Funds, are additional amounts of money that increase an individual’s basic monthly benefit. Each Department of Defense service branch (and not VA) determines who receives the kicker payments and the amount received. Kickers are included in monthly GI Bill payments from VA.', }, }, militaryAcademy: { name: 'academy-commission', order: 2, title: 'Did you graduate and receive a commission from the United States Military Academy, Naval Academy, Air Force Academy, or Coast Guard Academy?', }, seniorRotc: { name: 'rotc-commission', order: 3, title: 'Were you commissioned as a result of Senior ROTC?', additionalInfo: { triggerText: 'What is Senior ROTC?', info: 'The Senior Reserve Officer Training Corps (SROTC)—more commonly referred to as the Reserve Officer Training Corps (ROTC)—is an officer training and scholarship program for postsecondary students authorized under Chapter 103 of Title 10 of the United States Code.', }, }, loanPayment: { name: 'loan-payment', order: 4, title: 'Do you have a period of service that the Department of Defense counts towards an education loan payment?', additionalInfo: { triggerText: 'What does this mean?', info: "This is a Loan Repayment Program, which is a special incentive that certain military branches offer to qualified applicants. Under a Loan Repayment Program, the branch of service will repay part of an applicant's qualifying student loans.", }, }, }, directDeposit: 'directDeposit', }; const contactMethods = ['Email', 'Home Phone', 'Mobile Phone', 'Mail']; const benefits = [ ELIGIBILITY.CHAPTER30, ELIGIBILITY.CHAPTER1606, 'CannotRelinquish', ]; function isOnlyWhitespace(str) { return str && !str.trim().length; } function startPhoneEditValidation({ phone }) { if (!phone) { return true; } return validatePhone(phone); } function titleCase(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); } function phoneUISchema(category) { return { 'ui:options': { hideLabelText: true, showFieldLabel: false, startInEdit: formData => startPhoneEditValidation(formData), viewComponent: PhoneViewField, }, 'ui:objectViewField': PhoneReviewField, phone: { ...phoneUI(`${titleCase(category)} phone number`), 'ui:validations': [validatePhone], }, isInternational: { 'ui:title': `This ${category} phone number is international`, 'ui:reviewField': YesNoReviewField, 'ui:options': { hideIf: formData => { if (category === 'mobile') { if (!formData['view:phoneNumbers'].mobilePhoneNumber.phone) { return true; } } else if (!formData['view:phoneNumbers'].phoneNumber.phone) { return true; } return false; }, }, }, }; } function phoneSchema() { return { type: 'object', properties: { phone: { ...usaPhone, pattern: '^\\d[-]?\\d(?:[0-9-]*\\d)?$', }, isInternational: { type: 'boolean', }, }, }; } function additionalConsiderationsQuestionTitleText(benefitSelection, order) { const isUnsure = !benefitSelection || benefitSelection === 'CannotRelinquish'; const pageNumber = isUnsure ? order - 1 : order; const totalPages = isUnsure ? 3 : 4; return `Question ${pageNumber} of ${totalPages}`; } function additionalConsiderationsQuestionTitle(benefitSelection, order) { const titleText = additionalConsiderationsQuestionTitleText( benefitSelection, order, ); return ( <> <h3 className="meb-additional-considerations-title meb-form-page-only"> {titleText} </h3> <h4 className="form-review-panel-page-header vads-u-font-size--h5 meb-review-page-only"> {titleText} </h4> <p className="meb-review-page-only"> If you’d like to update your answer to {titleText}, edit your answer to to the question below. </p> </> ); } function AdditionalConsiderationTemplate(page, formField) { const { title, additionalInfo } = page; const additionalInfoViewName = `view:${page.name}AdditionalInfo`; let additionalInfoView; if (additionalInfo) { additionalInfoView = { [additionalInfoViewName]: { 'ui:description': ( <va-additional-info trigger={additionalInfo.triggerText}> <p>{additionalInfo.info}</p> </va-additional-info> ), }, }; } return { path: page.name, title: data => { return additionalConsiderationsQuestionTitleText( data[formFields.viewBenefitSelection][formFields.benefitRelinquished], page.order, ); }, uiSchema: { 'ui:description': data => { return additionalConsiderationsQuestionTitle( data.formData[formFields.viewBenefitSelection][ formFields.benefitRelinquished ], page.order, ); }, [formFields[formField]]: { 'ui:title': title, 'ui:widget': 'radio', }, [formFields[formField]]: { 'ui:title': title, 'ui:widget': 'radio', }, ...additionalInfoView, }, schema: { type: 'object', required: [formField], properties: { [formFields[formField]]: { type: 'string', enum: ['Yes', 'No'], }, [additionalInfoViewName]: { type: 'object', properties: {}, }, }, }, }; } function givingUpBenefitSelected(formData) { return ['Chapter30', 'Chapter1606'].includes( formData[formFields.viewBenefitSelection][formFields.benefitRelinquished], ); } function notGivingUpBenefitSelected(formData) { return !givingUpBenefitSelected(formData); } function transform(metaData, form) { const submission = createSubmissionForm(form.data, form.formId); return JSON.stringify(submission); } const checkImageSrc = (() => { const bucket = environment.isProduction() ? BUCKETS[ENVIRONMENTS.VAGOVPROD] : BUCKETS[ENVIRONMENTS.VAGOVSTAGING]; return `${bucket}/img/check-sample.png`; })(); const formConfig = { rootUrl: manifest.rootUrl, urlPrefix: '/', submitUrl: `${environment.API_URL}/meb_api/v0/submit_claim`, transformForSubmit: transform, trackingPrefix: 'my-education-benefits-', introduction: IntroductionPage, confirmation: ConfirmationPage, formId: VA_FORM_IDS.FORM_22_1990EZ, saveInProgress: { messages: { inProgress: 'Your my education benefits application (22-1990) is in progress.', expired: 'Your saved my education benefits application (22-1990) has expired. If you want to apply for my education benefits, please start a new application.', saved: 'Your my education benefits application has been saved.', }, }, version: 0, prefillEnabled: true, prefillTransformer, savedFormMessages: { notFound: 'Please start over to apply for my education benefits.', noAuth: 'Please sign in again to continue your application for my education benefits.', }, title: 'Apply for VA education benefits', subTitle: 'Equal to VA Form 22-1990 (Application for VA Education Benefits)', defaultDefinitions: { fullName, // ssn, date, dateRange, usaPhone, }, footerContent: FormFooter, getHelp: GetFormHelp, preSubmitInfo, chapters: { applicantInformationChapter: { title: 'Your information', pages: { [formPages.applicantInformation]: { title: 'Your information', path: 'applicant-information/personal-information', subTitle: 'Your information', instructions: 'This is the personal information we have on file for you.', uiSchema: { 'view:subHeadings': { 'ui:description': ( <> <h3>Review your personal information</h3> <p> This is the personal information we have on file for you. If you notice any errors, please correct them now. Any updates you make will change the information for your education benefits only. </p> <p> <strong>Note:</strong> If you want to update your personal information for other VA benefits, you can do that from your profile. </p> <p> <a href="/profile/personal-information"> Go to your profile </a> </p> </> ), }, formId: { 'ui:title': 'Form ID', 'ui:disabled': true, 'ui:options': { hideOnReview: true, }, }, claimantId: { 'ui:title': 'Claimant ID', 'ui:disabled': true, 'ui:options': { hideOnReview: true, }, }, 'view:userFullName': { 'ui:description': ( <p className="meb-review-page-only"> If you’d like to update your personal information, please edit the form fields below. </p> ), [formFields.userFullName]: { ...fullNameUI, first: { ...fullNameUI.first, 'ui:title': 'Your first name', 'ui:validations': [ (errors, field) => { if (isOnlyWhitespace(field)) { errors.addError('Please enter a first name'); } }, ], }, last: { ...fullNameUI.last, 'ui:title': 'Your last name', 'ui:validations': [ (errors, field) => { if (isOnlyWhitespace(field)) { errors.addError('Please enter a last name'); } }, ], }, middle: { ...fullNameUI.middle, 'ui:title': 'Your middle name', }, }, }, [formFields.dateOfBirth]: { ...currentOrPastDateUI('Your date of birth'), 'ui:reviewField': CustomReviewDOBField, }, }, schema: { type: 'object', required: [formFields.dateOfBirth], properties: { formId: { type: 'string', }, claimantId: { type: 'integer', }, 'view:subHeadings': { type: 'object', properties: {}, }, 'view:userFullName': { required: [formFields.userFullName], type: 'object', properties: { [formFields.userFullName]: { ...fullName, properties: { ...fullName.properties, middle: { ...fullName.properties.middle, maxLength: 30, }, }, }, }, }, [formFields.dateOfBirth]: date, }, }, }, }, }, contactInformationChapter: { title: 'Contact information', pages: { [formPages.contactInformation.contactInformation]: { title: 'Phone numbers and email address', path: 'contact-information/email-phone', uiSchema: { 'view:subHeadings': { 'ui:description': ( <> <h3>Review your phone numbers and email address</h3> <div className="meb-list-label"> <strong>We’ll use this information to:</strong> </div> <ul> <li> Contact you if we have questions about your application </li> <li>Tell you important information about your benefits</li> </ul> <p> This is the contact information we have on file for you. If you notice any errors, please correct them now. Any updates you make will change the information for your education benefits only. </p> <p> <strong>Note:</strong> If you want to update your contact information for other VA benefits, you can do that from your profile. </p> <p> <a href="/profile/personal-information"> Go to your profile </a> </p> </> ), }, [formFields.viewPhoneNumbers]: { 'ui:description': ( <> <h4 className="form-review-panel-page-header vads-u-font-size--h5 meb-review-page-only"> Phone numbers and email addresses </h4> <p className="meb-review-page-only"> If you’d like to update your phone numbers and email address, please edit the form fields below. </p> </> ), [formFields.mobilePhoneNumber]: phoneUISchema('mobile'), [formFields.phoneNumber]: phoneUISchema('home'), }, [formFields.email]: { 'ui:options': { hideLabelText: true, showFieldLabel: false, viewComponent: EmailViewField, }, email: { ...emailUI('Email address'), 'ui:validations': [validateEmail], 'ui:reviewField': EmailReviewField, }, confirmEmail: { ...emailUI('Confirm email address'), 'ui:options': { ...emailUI()['ui:options'], hideOnReview: true, }, }, 'ui:validations': [ (errors, field) => { if (field.email !== field.confirmEmail) { errors.confirmEmail.addError( 'Sorry, your emails must match', ); } }, ], }, }, schema: { type: 'object', properties: { 'view:subHeadings': { type: 'object', properties: {}, }, [formFields.viewPhoneNumbers]: { type: 'object', properties: { [formFields.mobilePhoneNumber]: phoneSchema(), [formFields.phoneNumber]: phoneSchema(), }, }, [formFields.email]: { type: 'object', required: [formFields.email, 'confirmEmail'], properties: { email, confirmEmail: email, }, }, }, }, }, [formPages.contactInformation.mailingAddress]: { title: 'Mailing address', path: 'contact-information/mailing-address', uiSchema: { 'view:subHeadings': { 'ui:description': ( <> <h3>Review your mailing address</h3> <p> We’ll send any important information about your application to this address. </p> <p> This is the mailing address we have on file for you. If you notice any errors, please correct them now. Any updates you make will change the information for your education benefits only. </p> <p> <strong>Note:</strong> If you want to update your personal information for other VA benefits, you can do that from your profile. </p> <p> <a href="/profile/personal-information"> Go to your profile </a> </p> </> ), }, 'view:mailingAddress': { 'ui:description': ( <> <h4 className="form-review-panel-page-header vads-u-font-size--h5 meb-review-page-only"> Mailing address </h4> <p className="meb-review-page-only"> If you’d like to update your mailing address, please edit the form fields below. </p> </> ), livesOnMilitaryBase: { 'ui:title': ( <span id="LiveOnMilitaryBaseTooltip"> I live on a United States military base outside of the country </span> ), 'ui:reviewField': YesNoReviewField, }, livesOnMilitaryBaseInfo: { 'ui:description': LearnMoreAboutMilitaryBaseTooltip(), }, [formFields.address]: { ...address.uiSchema(''), street: { 'ui:title': 'Street address', 'ui:errorMessages': { required: 'Please enter your full street address', }, 'ui:validations': [ (errors, field) => { if (isOnlyWhitespace(field)) { errors.addError( 'Please enter your full street address', ); } }, ], }, city: { 'ui:title': 'City', 'ui:errorMessages': { required: 'Please enter a valid city', }, 'ui:validations': [ (errors, field) => { if (isOnlyWhitespace(field)) { errors.addError('Please enter a valid city'); } }, ], }, state: { 'ui:title': 'State/Province/Region', 'ui:errorMessages': { required: 'State is required', }, }, postalCode: { 'ui:title': 'Postal Code (5-digit)', 'ui:errorMessages': { required: 'Zip code must be 5 digits', }, }, }, 'ui:options': { hideLabelText: true, showFieldLabel: false, viewComponent: MailingAddressViewField, }, }, }, schema: { type: 'object', properties: { 'view:subHeadings': { type: 'object', properties: {}, }, 'view:mailingAddress': { type: 'object', properties: { livesOnMilitaryBase: { type: 'boolean', }, livesOnMilitaryBaseInfo: { type: 'object', properties: {}, }, [formFields.address]: { ...address.schema(fullSchema, true), }, }, }, }, }, }, [formPages.contactInformation.preferredContactMethod]: { title: 'Contact preferences', path: 'contact-information/contact-preferences', uiSchema: { 'view:contactMethodIntro': { 'ui:description': ( <> <h3 className="meb-form-page-only"> Choose your contact method for follow-up questions </h3> </> ), }, [formFields.contactMethod]: { 'ui:title': 'How should we contact you if we have questions about your application?', 'ui:widget': 'radio', 'ui:errorMessages': { required: 'Please select at least one way we can contact you.', }, 'ui:options': { updateSchema: (() => { const filterContactMethods = createSelector( form => form['view:phoneNumbers'].mobilePhoneNumber.phone, form => form['view:phoneNumbers'].phoneNumber.phone, (mobilePhoneNumber, homePhoneNumber) => { const invalidContactMethods = []; if (!mobilePhoneNumber) { invalidContactMethods.push('Mobile Phone'); } if (!homePhoneNumber) { invalidContactMethods.push('Home Phone'); } return { enum: contactMethods.filter( method => !invalidContactMethods.includes(method), ), }; }, ); return form => filterContactMethods(form); })(), }, }, 'view:receiveTextMessages': { 'ui:description': ( <> <div className="meb-form-page-only"> <h3>Choose how you want to get notifications</h3> <p> We recommend that you opt in to text message notifications about your benefits. These include notifications that prompt you to verify your enrollment so you’ll receive your education payments. This is an easy way to verify your monthly enrollment. </p> </div> </> ), [formFields.receiveTextMessages]: { 'ui:title': 'Would you like to receive text message notifications on your education benefits?', 'ui:widget': 'radio', 'ui:validations': [ (errors, field, formData) => { const isYes = field.slice(0, 4).includes('Yes'); const phoneExist = !!formData['view:phoneNumbers'] .mobilePhoneNumber.phone; const { isInternational } = formData[ 'view:phoneNumbers' ].mobilePhoneNumber; if (isYes) { if (!phoneExist) { errors.addError( "You can't select that response because we don't have a mobile phone number on file for you.", ); } else if (isInternational) { errors.addError( "You can't select that response because you have an international mobile phone number", ); } } }, ], 'ui:options': { widgetProps: { Yes: { 'data-info': 'yes' }, No: { 'data-info': 'no' }, }, selectedProps: { Yes: { 'aria-describedby': 'yes' }, No: { 'aria-describedby': 'no' }, }, }, }, }, 'view:textMessagesAlert': { 'ui:description': ( <va-alert status="info"> <> If you choose to get text message notifications from VA’s GI Bill program, message and data rates may apply. Students will receive an average of two messages per month. At this time, we can only send text messages to U.S. mobile phone numbers. Text STOP to opt out or HELP for help.{' '} <a href="https://benefits.va.gov/gibill/isaksonroe/verification_of_enrollment.asp" rel="noopener noreferrer" target="_blank" > View Terms and Conditions and Privacy Policy. </a> </> </va-alert> ), 'ui:options': { hideIf: formData => !isValidPhone( formData[formFields.viewPhoneNumbers][ formFields.mobilePhoneNumber ].phone, ) || formData[formFields.viewPhoneNumbers][ formFields.mobilePhoneNumber ].isInternational, }, }, 'view:noMobilePhoneAlert': { 'ui:description': ( <va-alert status="warning"> <> You can’t choose to get text message notifications because we don’t have a mobile phone number on file for you. </> </va-alert> ), 'ui:options': { hideIf: formData => isValidPhone( formData[formFields.viewPhoneNumbers][ formFields.mobilePhoneNumber ].phone, ) || formData[formFields.viewPhoneNumbers][ formFields.mobilePhoneNumber ].isInternational, }, }, 'view:internationalTextMessageAlert': { 'ui:description': ( <va-alert status="warning"> <> You can’t choose to get text notifications because you have an international mobile phone number. At this time, we can send text messages about your education benefits to U.S. mobile phone numbers. </> </va-alert> ), 'ui:options': { hideIf: formData => !formData[formFields.viewPhoneNumbers][ formFields.mobilePhoneNumber ].isInternational, }, }, }, schema: { type: 'object', properties: { 'view:contactMethodIntro': { type: 'object', properties: {}, }, [formFields.contactMethod]: { type: 'string', enum: contactMethods, }, 'view:receiveTextMessages': { type: 'object', required: [formFields.receiveTextMessages], properties: { [formFields.receiveTextMessages]: { type: 'string', enum: [ 'Yes, send me text message notifications', 'No, just send me email notifications', ], }, }, }, 'view:textMessagesAlert': { type: 'object', properties: {}, }, 'view:noMobilePhoneAlert': { type: 'object', properties: {}, }, 'view:internationalTextMessageAlert': { type: 'object', properties: {}, }, }, required: [formFields.contactMethod], }, }, }, }, serviceHistoryChapter: { title: 'Service history', pages: { [formPages.serviceHistory]: { path: 'service-history', title: 'Service history', uiSchema: { 'view:subHeading': { 'ui:description': <h3>Review your service history</h3>, }, [formFields.toursOfDuty]: { ...toursOfDutyUI, 'ui:field': AccordionField, 'ui:title': 'Service history', 'ui:options': { ...toursOfDutyUI['ui:options'], keepInPageOnReview: true, reviewTitle: <></>, setEditState: () => { return true; }, showSave: false, viewField: ServicePeriodAccordionView, viewComponent: ServicePeriodAccordionView, viewOnlyMode: true, }, items: { ...toursOfDutyUI.items, 'ui:objectViewField': ServicePeriodAccordionView, }, }, 'view:serviceHistory': { 'ui:description': ( <div className="meb-review-page-only"> <p> If you’d like to update information related to your service history, edit the form fields below. </p> </div> ), [formFields.serviceHistoryIncorrect]: { 'ui:title': 'This information is incorrect and/or incomplete', 'ui:reviewField': YesNoReviewField, }, }, [formFields.incorrectServiceHistoryExplanation]: { 'ui:title': 'Please explain what is incorrect and/or incomplete about your service history (250 character limit)', 'ui:options': { expandUnder: 'view:serviceHistory', hideIf: formData => !formData['view:serviceHistory'][ formFields.serviceHistoryIncorrect ], }, 'ui:widget': 'textarea', }, }, schema: { type: 'object', properties: { 'view:subHeading': { type: 'object', properties: {}, }, [formFields.toursOfDuty]: { ...toursOfDuty, title: '', // Hack to prevent console warning }, 'view:serviceHistory': { type: 'object', properties: { [formFields.serviceHistoryIncorrect]: { type: 'boolean', }, }, }, [formFields.incorrectServiceHistoryExplanation]: { type: 'string', maxLength: 250, }, }, }, }, }, }, benefitSelection: { title: 'Benefit selection', pages: { [formPages.benefitSelection]: { path: 'benefit-selection', title: 'Benefit selection', subTitle: "You're applying for the Post-9/11 GI Bill®", depends: formData => formData.eligibility?.length, uiSchema: { 'view:post911Notice': { 'ui:description': ( <> {post911GiBillNote} <h3>Give up one other benefit</h3> <p> Because you are applying for the Post-9/11 GI Bill, you have to give up one other benefit you may be eligible for. </p> <p> <strong> You cannot change your decision after you submit this application. </strong> </p> <va-additional-info trigger="Why do I have to give up a benefit?"> <p> The law says if you are eligible for both the Post-9/11 GI Bill and another education benefit based on the same period of active duty, you must give one up. One qualifying period of active duty can only be used for one VA education benefit. </p> </va-additional-info> </> ), }, [formFields.viewBenefitSelection]: { 'ui:description': ( <div className="meb-review-page-only"> <p> If you’d like to update which benefit you’ll give up, please edit your answers to the questions below. </p> {post911GiBillNote} </div> ), [formFields.benefitRelinquished]: { 'ui:title': 'Which benefit will you give up?', 'ui:reviewField': BenefitGivenUpReviewField, 'ui:widget': 'radio', 'ui:options': { labels: { Chapter30: chapter30Label, Chapter1606: chapter1606Label, CannotRelinquish: "I'm not sure", }, widgetProps: { Chapter30: { 'data-info': 'Chapter30' }, Chapter1606: { 'data-info': 'Chapter1606' }, CannotRelinquish: { 'data-info': 'CannotRelinquish' }, }, selectedProps: { Chapter30: { 'aria-describedby': 'Chapter30' }, Chapter1606: { 'aria-describedby': 'Chapter1606', }, CannotRelinquish: { 'aria-describedby': 'CannotRelinquish', }, }, updateSchema: (() => { const filterEligibility = createSelector( state => state.eligibility, eligibility => { if (!eligibility || !eligibility.length) { return benefits; } return { enum: benefits.filter( benefit => eligibility.includes(benefit) || benefit === 'CannotRelinquish', ), }; }, ); return (form, state) => filterEligibility(form, state); })(), }, 'ui:errorMessages': { required: 'Please select an answer.', }, }, }, 'view:activeDutyNotice': { 'ui:description': ( <div className="meb-alert meb-alert--mini meb-alert--warning"> <i aria-hidden="true" role="img" /> <p className="meb-alert_body"> <span className="sr-only">Alert:</span> If you give up the Montgomery GI Bill Active Duty, you’ll get Post-9/11 GI Bill benefits only for the number of months you had left under the Montgomery GI Bill Active Duty. </p> </div> ), 'ui:options': { expandUnder: [formFields.viewBenefitSelection], hideIf: formData => formData[formFields.viewBenefitSelection][ formFields.benefitRelinquished ] !== 'Chapter30', }, }, [formFields.benefitEffectiveDate]: { ...dateUI('Effective date'), 'ui:options': { hideIf: notGivingUpBenefitSelected, expandUnder: [formFields.viewBenefitSelection], }, 'ui:required': givingUpBenefitSelected, 'ui:reviewField': DateReviewField, 'ui:validations': [validateEffectiveDate], }, 'view:effectiveDateNotes': { 'ui:description': ( <ul> <li> You can select a date up to one year in the past. We may be able to pay you benefits for education or training taken during this time. </li> <li> We can’t pay for education or training taken more than one year before the date of your application for benefits. </li> <li> If you are currently using another benefit, select the date you would like to start using the Post-9/11 GI Bill. </li> </ul> ), 'ui:options': { hideIf: notGivingUpBenefitSelected, expandUnder: [formFields.viewBenefitSelection], }, }, 'view:unsureNote': { 'ui:description': unsureDescription, 'ui:options': { hideIf: formData => formData[formFields.viewBenefitSelection][ formFields.benefitRelinquished ] !== 'CannotRelinquish', expandUnder: [formFields.viewBenefitSelection], }, }, }, schema: { type: 'object', properties: { 'view:post911Notice': { type: 'object', properties: {}, }, [formFields.viewBenefitSelection]: { type: 'object', required: [formFields.benefitRelinquished], properties: { [formFields.benefitRelinquished]: { type: 'string', enum: benefits, }, }, }, 'view:activeDutyNotice': { type: 'object', properties: {}, }, [formFields.benefitEffectiveDate]: date, 'view:effectiveDateNotes': { type: 'object', properties: {}, }, 'view:unsureNote': { type: 'object', properties: {}, }, }, }, }, }, }, additionalConsiderationsChapter: { title: 'Additional considerations', pages: { [formPages.additionalConsiderations.activeDutyKicker.name]: { ...AdditionalConsiderationTemplate( formPages.additionalConsiderations.activeDutyKicker, formFields.activeDutyKicker, ), depends: formData => formData[formFields.viewBenefitSelection][ formFields.benefitRelinquished ] === 'Chapter30', }, [formPages.additionalConsiderations.reserveKicker.name]: { ...AdditionalConsiderationTemplate( formPages.additionalConsiderations.reserveKicker, formFields.selectedReserveKicker, ), depends: formData => formData[formFields.viewBenefitSelection][ formFields.benefitRelinquished ] === 'Chapter1606', }, [formPages.additionalConsiderations.militaryAcademy.name]: { ...AdditionalConsiderationTemplate( formPages.additionalConsiderations.militaryAcademy, formFields.federallySponsoredAcademy, ), }, [formPages.additionalConsiderations.seniorRotc.name]: { ...AdditionalConsiderationTemplate( formPages.additionalConsiderations.seniorRotc, formFields.seniorRotcCommission, ), }, [formPages.additionalConsiderations.loanPayment.name]: { ...AdditionalConsiderationTemplate( formPages.additionalConsiderations.loanPayment, formFields.loanPayment, ), }, }, }, bankAccountInfoChapter: { title: 'Direct deposit', pages: { [formPages.directDeposit]: { path: 'direct-deposit', uiSchema: { 'ui:description': directDepositDescription, bankAccount: { ...bankAccountUI, 'ui:order': ['accountType', 'accountNumber', 'routingNumber'], }, 'view:learnMore': { 'ui:description': ( <> <img key="check-image-src" style={{ marginTop: '1rem' }} src={checkImageSrc} alt="Example of a check showing where the account and routing numbers are" /> <p key="learn-more-title">Where can I find these numbers?</p> <p key="learn-more-description"> The bank routing number is the first 9 digits on the bottom left corner of a printed check. Your account number is the second set of numbers on the bottom of a printed check, just to the right of the bank routing number. </p> <va-additional-info key="learn-more-btn" trigger="Learn More"> <p key="btn-copy"> If you don’t have a printed check, you can sign in to your online banking institution for this information </p> </va-additional-info> </> ), }, }, schema: { type: 'object', properties: { bankAccount: { type: 'object', properties: { accountType: { type: 'string', enum: ['checking', 'savings'], }, routingNumber: { type: 'string', pattern: '^\\d{9}$', }, accountNumber: { type: 'string', }, }, }, 'view:learnMore': { type: 'object', properties: {}, }, }, }, }, }, }, }, }; export default formConfig;
src/components/Unit/SvgUnit.js
wfp/ui
import React from 'react'; import { InvalidSvg } from './InvalidUnit'; const SvgUnit = (value, props) => { const { style, ...other } = props; if (value) return ( <text className={props.className} {...other}> <tspan style={style}>{value.before} </tspan> <tspan style={style}>{value.value}</tspan> <tspan style={style}> {' '} {value.output ? value.output.default.after + '' : ''} {value.after} </tspan> </text> ); else return <InvalidSvg className={props.className} />; }; export default SvgUnit;
src/renderer/main.js
p4sh4/electron-react-sample-app
/* eslint-disable */ import React from 'react'; import ReactDOM from 'react-dom'; import Main from './components/Main'; ReactDOM.render(<Main />, document.getElementById('app'));
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
rubengrill/react-router
import React from 'react' class Assignments extends React.Component { render() { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ) } } export default Assignments
src/components/Artboard.js
weaintplastic/react-sketchapp
/* @flow */ import React from 'react'; import PropTypes from 'prop-types'; import StyleSheet from '../stylesheet'; import ViewStylePropTypes from './ViewStylePropTypes'; const propTypes = { // TODO(lmr): do some nice warning stuff like RN does style: PropTypes.shape({ ...ViewStylePropTypes, }), name: PropTypes.string, children: PropTypes.node, }; class Artboard extends React.Component { static defaultProps = { name: 'Artboard', }; render() { return ( <artboard style={StyleSheet.flatten(this.props.style)} name={this.props.name} > {this.props.children} </artboard> ); } } Artboard.propTypes = propTypes; module.exports = Artboard;
docs/src/app/components/pages/components/Stepper/VerticalNonLinearStepper.js
frnk94/material-ui
import React from 'react'; import { Step, Stepper, StepButton, StepContent, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; /** * A basic vertical non-linear implementation */ class VerticalNonLinear extends React.Component { state = { stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; renderStepActions(step) { return ( <div style={{margin: '12px 0'}}> <RaisedButton label="Next" disableTouchRipple={true} disableFocusRipple={true} primary={true} onTouchTap={this.handleNext} style={{marginRight: 12}} /> {step > 0 && ( <FlatButton label="Back" disableTouchRipple={true} disableFocusRipple={true} onTouchTap={this.handlePrev} /> )} </div> ); } render() { const {stepIndex} = this.state; return ( <div style={{maxWidth: 380, maxHeight: 400, margin: 'auto'}}> <Stepper activeStep={stepIndex} linear={false} orientation="vertical" > <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 0})}> Select campaign settings </StepButton> <StepContent> <p> For each ad campaign that you create, you can control how much you're willing to spend on clicks and conversions, which networks and geographical locations you want your ads to show on, and more. </p> {this.renderStepActions(0)} </StepContent> </Step> <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 1})}> Create an ad group </StepButton> <StepContent> <p>An ad group contains one or more ads which target a shared set of keywords.</p> {this.renderStepActions(1)} </StepContent> </Step> <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 2})}> Create an ad </StepButton> <StepContent> <p> Try out different ad text to see what brings in the most customers, and learn how to enhance your ads using features like ad extensions. If you run into any problems with your ads, find out how to tell if they're running and how to resolve approval issues. </p> {this.renderStepActions(2)} </StepContent> </Step> </Stepper> </div> ); } } export default VerticalNonLinear;
src/client/components/NavWidget/NavWidget.js
vidaaudrey/trippian
import log from '../../log' import React from 'react' import { Link } from 'react-router' import { SearchBoxWidget, LocaleMenuWidget } from '../index' import { FormattedMessage } from 'react-intl' import { UserMenuWidget } from '../index' import { NavWidget as appConfig } from '../../config/appConfig' function renderSearchForm() { return ( <SearchBoxWidget className="navbar-form navbar-left" role="search" /> ) } const NavWidget = ({ currentPath, user, history }) => { const { isAuthed, isTrippian } = user log.info('----logo', appConfig) return ( <nav className="navbar navbar-default" role="navigation"> <div className="navbar-header"> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span className="sr-only">{appConfig.srToggleText} </span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link className="navbar-brand" to="/"> <img src={appConfig.logo} alt="Trippian"/> </Link> </div> <div className="collapse navbar-collapse navbar-ex1-collapse"> <LocaleMenuWidget className="nav navbar-nav navbar-right list-inline"/> <ul className="nav navbar-nav navbar-right"> {!isTrippian && <li> <Link to='become-a-trippian' className="btn btn-bordered"> <FormattedMessage id="NavWidget.becomeATrippianButtonText" description="becomeATrippianButtonText" defaultMessage={appConfig.becomeATrippianButtonText}/> </Link> </li>} {isAuthed && <UserMenuWidget {...user}/>} {!isAuthed && <li><Link to="login"> <FormattedMessage id="NavWidget.loginButtonText" description="loginButtonText" defaultMessage={appConfig.loginButtonText}/> </Link></li>} </ul> </div> </nav> ) } NavWidget.displayName = 'NavWidget' export default NavWidget //<li>{currentPath !== '/' && <SearchBoxWidget history={history} className="navbar-form navbar-left" role="search" /> }</li> // import React, { // Component // } // from 'react' // import { // Link // } // from 'react-router' // import { // SearchBoxWidget, LocaleMenuWidget // } // from '../index' // import { // FormattedMessage // } // from 'react-intl' // import store from '../../redux/store' // import { // connect // } // from 'react-redux' // import { // UserMenuWidget // } // from '../index' // function renderSearchForm() { // return ( // <SearchBoxWidget className="navbar-form navbar-left" role="search" /> // ) // } // function mapStateToProps(state) { // return { // user: state.appState.get('user') // } // } // @ // connect(mapStateToProps) // export default class NavWidget extends Component { // constructor(props) { // super(props) // this.state = {} // } // render() { // const { // isAuthed, isTrippian // } = this.props.user // // currentPath, username = '', displayName = '', isUserAdmin = false, history // return ( // <nav className="navbar navbar-default" role="navigation"> // <div className="navbar-header"> // <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> // <span className="sr-only">Toggle navigation</span> // <span className="icon-bar"></span> // <span className="icon-bar"></span> // <span className="icon-bar"></span> // </button> // <Link className="navbar-brand" to="/"> // <img src="https://s3-us-west-1.amazonaws.com/trippian/logo-trans-white.png" alt="Trippian"/> // </Link> // </div> // <div className="collapse navbar-collapse navbar-ex1-collapse"> // <LocaleMenuWidget className="nav navbar-nav navbar-right list-inline"/> // <ul className="nav navbar-nav navbar-right"> // {!isTrippian || !isAuthed && <li> // <Link to='become-a-trippian' className="btn btn-bordered"> // <FormattedMessage // id="app-pages.become-a-trippian" // description="become a trippian page title" // defaultMessage="Become a Trippian"/> // </Link> // </li>} // {isAuthed && <UserMenuWidget />} // {!isAuthed && <li><Link to="login">Login </Link></li>} // </ul> // </div> // </nav> // ) // } // } // NavWidget.displayName = 'NavWidget' // //<li>{currentPath !== '/' && <SearchBoxWidget history={history} className="navbar-form navbar-left" role="search" /> }</li>
fixtures/react_native_windows_e2e_app/src/Films.js
callstack-io/haul
import React from 'react'; import { Text, FlatList } from 'react-native'; import { Query } from 'react-apollo'; import gql from 'graphql-tag'; export default function Films() { return ( <Query query={gql` { allFilms { title } } `} > {({ loading, error, data }) => { if (loading) return <Text>Loading...</Text>; if (error) return <Text>Error</Text>; return ( <FlatList testID="films" data={data.allFilms} keyExtractor={(item) => item.title} renderItem={({ item }) => ( <Text>{item.title}</Text> )} /> ); }} </Query> ); }
app/components/ErrorLine.js
zoo1/fil
import React from 'react'; export default class ErrorLine extends React.Component { render() { let block = "console__error-line", error = this.props.error; return ( <div className={block}> <pre className={block + "__description"}> {error} </pre> </div> ); } }
src/ButtonToolbar.js
glenjamin/react-bootstrap
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { createBootstrapComponent } from './ThemeProvider'; class ButtonToolbar extends React.Component { static propTypes = { /** * @default 'btn-toolbar' */ bsPrefix: PropTypes.string, /** * The ARIA role describing the button toolbar. Generally the default * "toolbar" role is correct. An `aria-label` or `aria-labelledby` * prop is also recommended. */ role: PropTypes.string, }; static defaultProps = { role: 'toolbar', }; render() { const { bsPrefix, className, ...props } = this.props; return <div {...props} className={classNames(className, bsPrefix)} />; } } export default createBootstrapComponent(ButtonToolbar, 'btn-toolbar');
dashboard-ui/app/components/drawer/cloudEvent.js
CloudBoost/cloudboost
/* eslint-disable no-undef */ import React from 'react'; import { Card, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; class CloudEvent extends React.Component { constructor () { super(); this.state = { }; } copyToClipboard = (element) => () => { var $temp = $('<input>'); $('body').append($temp); $temp.val($(element).text()).select(); document.execCommand('copy'); $temp.remove(); } handleExpandChange = (expanded) => { this.setState({ expanded: expanded }); }; handleToggle = (event, toggle) => { this.setState({ expanded: toggle }); }; handleExpand = () => { this.setState({ expanded: true }); }; handleReduce = () => { this.setState({ expanded: false }); }; render () { return ( <div> <div className='method'> <a id='CloudEvent-track' name='CloudObject-constructor' className='section-anchor' /> <Card style={{ marginBottom: 16 }} onExpandChange={this.handleExpandChange}> <CardHeader title='Track an Event' actAsExpander showExpandableButton style={{ backgroundColor: '#f4f4f4', padding: '10px 16px' }} /> <CardMedia> <div className='method-example' id='api-summary-example'> <span className='pull-right flag fa fa-clipboard' title='Copy..' onClick={this.copyToClipboard('#pre_track')} /> <pre id='pre_track'> <span className='code-red'>{`var`}</span>{` eventObj = `}<span className='code-red'>{`new`}</span>{` CB.CloudEvent.track("`}<span className='code-yellow'>{`Signup`}</span>{`",{` }<span className='code-yellow'>{` username: thisObj.username, email: thisObj.email`}</span>{`},{ success: `}<span className='code-red'>{`function`}</span>{`(eventObj) { //Gets Event Object }, error: `}<span className='code-red'>{`function`}</span>{`(err) { //error in geting Event Object }});` } </pre> </div>{/* method-example */} </CardMedia> <CardTitle title='CloudEvent( name, data, [type], [callback] )' expandable subtitle='Track Down an Event' /> <CardText expandable> <div className='method-description'> <div className='method-list'> <h6>Argument</h6> <dl className='argument-list'> <dt>name</dt> <dd className>string <span>The name of the event you want to track.</span></dd> <div className='clearfix' /> <dt>data</dt> <dd className> Object <span>The information you want to send to the event.</span></dd> <div className='clearfix' /> <dt>type</dt> <dd className> [optional]Object <span /></dd> <div className='clearfix' /> <dt>type</dt> <dd className> [optional]callback <span>The callback actions you want to perform.</span></dd> <div className='clearfix' /> </dl> <h6>Returns</h6> <p>Void</p> </div> </div> </CardText> </Card> </div> </div> ); } } export default CloudEvent;
public/js/11D.js
ritchieanesco/frontendmastersreact
/* Setting application state */ import React from 'react' // type annotataions for data const {string} = React.PropTypes const ShowCard = React.createClass({ propTypes: { poster: string, title: string, year: string, description: string }, render () { // destructuring - e6 feature const { poster, title, year, description } = this.props return ( <div className='show-card'> <img src={`/public/img/posters/${poster}`} /> <div> <h3>{title}</h3> <h4>({year})</h4> <p>{description}</p> </div> </div> ) } }) export default ShowCard
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js
Havi4/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ContactStore from 'stores/ContactStore'; import ContactActionCreators from 'actions/ContactActionCreators'; import AddContactStore from 'stores/AddContactStore'; import AddContactActionCreators from 'actions/AddContactActionCreators'; import ContactsSectionItem from './ContactsSectionItem.react'; import AddContactModal from 'components/modals/AddContact.react.js'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { isAddContactModalOpen: AddContactStore.isModalOpen(), contacts: ContactStore.getContacts() }; }; class ContactsSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { ContactActionCreators.hideContactList(); ContactStore.removeChangeListener(this.onChange); AddContactStore.removeChangeListener(this.onChange); } constructor(props) { super(props); this.state = getStateFromStores(); ContactActionCreators.showContactList(); ContactStore.addChangeListener(this.onChange); AddContactStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } onChange = () => { this.setState(getStateFromStores()); }; openAddContactModal = () => { AddContactActionCreators.openModal(); }; render() { let contacts = this.state.contacts; let contactList = _.map(contacts, (contact, i) => { return ( <ContactsSectionItem contact={contact} key={i}/> ); }); let addContactModal; if (this.state.isAddContactModalOpen) { addContactModal = <AddContactModal/>; } return ( <section className="sidebar__contacts"> <ul className="sidebar__list sidebar__list--contacts"> {contactList} </ul> <footer> <RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/> {addContactModal} </footer> </section> ); } } export default ContactsSection;
client/src/containers/about/About.js
Edvinas01/chat-rooms
import React from 'react'; const About = () => { return ( <div> <h1>About</h1> <p> Chat Rooms is a simple ReactJS chat application which uses JWTs to authenticate. This application is based on awesome ReactJS starter project which you can find <a href="https://github.com/cloudmu/react-redux-starter-kit" target="_blank">here</a>. </p> <p> Find out more on <a href="https://github.com/Edvinas01/chat-rooms" target="_blank">GitHub</a>. </p> </div> ); }; export default About;
node_modules/react-native/local-cli/templates/HelloNavigation/views/MainNavigator.js
gunaangs/Feedonymous
'use strict'; /** * This is an example React Native app demonstrates ListViews, text input and * navigation between a few screens. * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { StackNavigator } from 'react-navigation'; import HomeScreenTabNavigator from './HomeScreenTabNavigator'; import ChatScreen from './chat/ChatScreen'; /** * Top-level navigator. Renders the application UI. */ const MainNavigator = StackNavigator({ Home: { screen: HomeScreenTabNavigator, }, Chat: { screen: ChatScreen, }, }); export default MainNavigator;
src/client/pages/me.react.js
jaegerpicker/GLDice
import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import Logout from '../auth/logout.react'; import React from 'react'; import immutable from 'immutable'; import requireAuth from '../auth/requireauth.react'; import {msg} from '../intl/store'; @requireAuth class Me extends Component { static propTypes = { viewer: React.PropTypes.instanceOf(immutable.Record).isRequired }; render() { const {viewer: {email}} = this.props; return ( <DocumentTitle title={msg('me.title')}> <div className="me-page"> <p> {msg('me.welcome', {email})} </p> <Logout /> </div> </DocumentTitle> ); } } export default Me;
src/client/pages/Layout.js
callmeJozo/MKRN
import React from 'react'; import { Link } from 'react-router'; import { Button, Icon, Menu, Dropdown, message, notification } from 'antd'; import AuthStore from "../stores/auth"; import UserStore from "../stores/user"; const DropdownButton = Dropdown.Button; AuthStore.init(); class Layout extends React.Component { constructor(props) { super(props); this.state = { login: false, user: AuthStore.getUser() } } componentDidMount() { AuthStore.addChangeListener(this.loginStateChange.bind(this)); } componentWillUnmount() { AuthStore.removeChangeListener(this.loginStateChange.bind(this)); } loginStateChange(user) { if (!user) { this.props.history.replace({ pathname: 'login' }) } this.setState({ user: user }) if (user && user.inviteMsgs.length) { this.notification(); } } singout() { AuthStore.signOut((err, res) => { if (!err) { message.success('退出成功!', 3); this.props.history.replace({ pathname: 'login' }) } }); } acceptInvite(notificationKey, inviteMsg) { UserStore.acceptInvite(inviteMsg._id, inviteMsg.project._id, (err, res) => { message.success('加入成功!', 2); this.props.history.replace({ pathname: `project/${res.data.projectUrl}/apis`, }) notification.close(notificationKey); }); } rejectInvite(notificationKey, inviteMsg) { UserStore.rejectInvite(inviteMsg._id, (err, res) => { message.success('操作成功!', 2); notification.close(notificationKey); }); } notification() { let inviteMsg = this.state.user.inviteMsgs[0]; if (typeof inviteMsg != 'object') return; let description = ( <div> <span>{inviteMsg.invitor.username}</span> <span>邀请您加入</span> <span>{inviteMsg.project.name}</span> </div> ); let key = `open${Date.now()}`; let sureClick = () => { this.acceptInvite(key, inviteMsg); } let cacelClick = () => { this.rejectInvite(key, inviteMsg); notification.close(key); } let btn = ( <div> <Button type="ghost" size="small" onClick={cacelClick}>不再提醒</Button> <Button type="primary" size="small" onClick={sureClick} style={{marginLeft: '10px'}} >我要加入</Button> </div> ) notification.open({ message: '项目邀请', description, key, btn, duration: null }) } render() { let isLoginPage = (() => { if (this.props.routes.length >= 1) { return this.props.routes[1].path == 'login'; } })(); const userMenu = ( <Menu> <Menu.Item key="2" > <span onClick={this.singout.bind(this)}>退出</span> </Menu.Item> </Menu> ); let user = this.state.user || {}; return ( <div className="wrap"> {!isLoginPage ? <div className="navbar-wrap"> <div className="navbar main-wrap"> <ul className="nav-left"> <li><Link to="/" activeClassName={"active"}>我的项目</Link></li> </ul> <div className="nav-right ttr"> <div className="authed"> <DropdownButton overlay={userMenu} type="ghost"> <Link to={`u/${user._id}`}>{user.username}</Link> </DropdownButton> <Link to="addproject"> <Button type="primary" shape="circle" title="添加项目"> <Icon type="plus-circle-o" size="small"/> </Button> </Link> </div> </div> </div> </div> : ''} <div className="content"> {this.props.children} </div> </div> ); } } export default Layout;
js/components/inputgroup/error.js
ChiragHindocha/stay_fit
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, Text, Body, Left, Right, IconNB, Item, Input } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; const { popRoute, } = actions; class Error extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Error Input</Title> </Body> <Right /> </Header> <Content padder> <Item error> <Input placeholder="Textbox with Error Input" /> <IconNB name="ios-close-circle" /> </Item> </Content> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Error);
app/containers/LanguageProvider/index.js
dvm4078/dvm-blog
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: PropTypes.string, messages: PropTypes.object, children: PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
source/components/Tour.react.js
BeethovensWerkstatt/VideApp
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import TourSteps from '../tour/tourSteps.js'; import {eohub} from './../_modules/eo-hub'; import Popper from 'popper.js'; //Tours //var Drop = require('tether-drop'); let TourException = (count) => { console.log('emitting a tour exception with count ' + count) } class Tour extends React.Component { componentDidMount() { //console.log('INFO: componentDidMount'); if(typeof this.props.tour === 'string' && this.props.tour !== '') { let renders = false; let iteration = 0; do { let func = () => { this.renderTour(iteration) } try { if(iteration === 0) { this.renderTour(iteration); } else { //console.log('[DEBUG] Trying to render tour for ' + (iteration + 1) + ' times now.') window.setTimeout(func,iteration * 100); } renders = true; } catch(err) { /*if(err.type !== 'TourException') { throw err; }*/ //console.log('[ERROR] Tour error uncaught') iteration++; } } while (!renders); } } componentWillReceiveProps(nextProps) { //console.log('Tour.componentWillReceiveProps'); if(this.props.tour === '' && nextProps.tour !== '') { this.forceUpdate(); this.initializeTour(nextProps.tour); } if(typeof nextProps.fullState.tour === 'string' && nextProps.fullState.tour !== '') { //this.forceUpdate(); /*console.log(' ') console.log(' forced update ') console.log(' ')*/ } if(typeof this.props.tour === 'string' && this.props.tour !== '' && typeof nextProps.tour === 'string' && nextProps.tour === '') { try { document.querySelector('#tourPopper').remove(); } catch(err) { console.log('[ERROR] Unable to find #tourPopper: ' + err) } } } render() { if(this.props.tour === '') { return null; } if(typeof this.props.tour !== 'string') { return null; } let tourClass = 'currentTourStep ' + this.props.tour; /*console.log('[DEBUG] rendering ' + tourClass);*/ return ( <div className="tourBackground"> <div id="tourPopper" className="popper"> <div className="closeTourButton" onClick={e => { //e.preventDefault(); document.querySelector('#tourPopper').remove(); this.props.closeTour(); }}> <i className="fa fa-times" aria-hidden="true"></i> </div> <div className='popper__arrow'></div> <div className="tourContent">TourContent</div> </div> </div> ) } componentDidUpdate(prevProps,prevState) { //console.log('[DEBUG] componentDidUpdate') if(typeof this.props.tour === 'string' && this.props.tour !== ''/* && !this.props.nolog*/) { let renders = false; let iteration = 1; do { let func = () => { this.renderTour(iteration) } try { if(iteration === 0) { this.renderTour(iteration); } else { /*console.log('[DEBUG] Trying to render tour for ' + (iteration + 1) + ' times now.')*/ window.setTimeout(func,iteration * 100); } renders = true; } catch(err) { /*if(err.type !== 'TourException') { mam throw err; }*/ iteration++; } } while (!renders); } } shouldComponentUpdate(nextProps, nextState) { /*console.log('----------- nextProps.tour: ' + nextProps.tour);*/ if(typeof nextProps.tour === 'string' && nextProps.tour !== ''/* && !nextProps.nolog*/) { return true; } else { return false; } } initializeTour(firstStep) { /*console.log('\n \n \n INITIALIZING EVERYTHING \n \n \n \n')*/ let handler = (event) => { this.handleTourEvent(event) } let app = document.querySelector('body'); this.tourHandlers = []; this.tourHandlers.push(app.addEventListener('click',handler,true)); this.tourHandlers.push(app.addEventListener('change',handler,true)); this.tourHandlers.push(app.addEventListener('mousedown',handler,true)); } handleTourEvent(event) { /*console.log('\n \n handleTourEvent ' + event.type + ' ' + this.props.tour + '') console.log(event) console.log('\n ')*/ let currentStepId = this.props.tour; let tourObj = TourSteps[currentStepId]; if(typeof tourObj === 'undefined') { console.log('\n [DEBUG] Unable to get tour item "' + stepId + '"') return false; } let isOk = false; let nextStep; let tourEnd = false; let allowedSelectors = []; //always allow to switch language tourObj.allowedTargets.push({selector:'.languageSwitch'}); //always allow to close tour tourObj.allowedTargets.push({selector:'.closeTourButton'}); //always allow to open links contained in the tour itself tourObj.allowedTargets.push({selector:'.tourContent a'}); for(let i=0;i<tourObj.allowedTargets.length;i++) { let elem = event.target.closest(tourObj.allowedTargets[i].selector); if(elem !== null) { isOk = true; allowedSelectors.push(tourObj.allowedTargets[i]); if(typeof tourObj.allowedTargets[i].state !== 'undefined') { nextStep = tourObj.allowedTargets[i].state; } if(typeof tourObj.allowedTargets[i].tourEnd !== 'undefined') { tourEnd = tourObj.allowedTargets[i].tourEnd; } } } /*console.log(' Values are isOk:' + isOk + ' | nextStep:' + nextStep + ' | stepId: ' + currentStepId + ' | ' + allowedSelectors.length + ' allowedSelectors'); console.log(allowedSelectors)*/ /* * this is a fix for the view menu, which doesn't change values without this fix */ let changeIsOk = false; if(event.type === 'change') { /*console.log('\n CHANGE EVENT:') console.log(event) console.log(isOk) console.log('\ngoing out\n\n')*/ let selectIsAllowed = (allowedSelectors.length > 0) ? allowedSelectors[0].hasOwnProperty('selectBox') : false; let targetIsSelect = event.target.classList.contains('viewSelect'); let selectionIsAllowed = false; if(allowedSelectors.length > 0 && allowedSelectors[0].hasOwnProperty('selectBox')) { for(let n=0; n<allowedSelectors[0].selectBox.allowedValues.length;n++) { let allowedValue = allowedSelectors[0].selectBox.allowedValues[n]; if(event.value === allowedValue.value) { selectionIsAllowed = true; } } } //console.log('\n\nVALUES: selectIsAllowed: ' + selectIsAllowed + ', targetIsSelect: ' + targetIsSelect + ', selectionIsAllowed: ' + selectionIsAllowed); if(selectIsAllowed && targetIsSelect && selectionIsAllowed) { //console.log('\n\nWILL ALLOW CHANGE') changeIsOk = true; } } /* * /fix end */ if(tourObj.restrictsAction && !isOk && changeIsOk) { event.stopPropagation(); event.preventDefault(); /*console.log(' matching case 1') console.log(event.target);*/ } else if(currentStepId === 'tool011' && nextStep === 'tool012' && isOk) { /*console.log('\n\n----------------------\n\n I should have been able to move on!\n\n----------------------\n\n'); */ window.setTimeout(() => {this.props.loadTourStep(nextStep);},500); } else if(event.type === 'click' || event.type === 'change') { //only resolve event when it's a click /*console.log(' matching case 2')*/ //kill the existing Drop //drop.destroy(); //remove listener if(tourEnd) { /*console.log(' matching case 2.1')*/ this.props.closeTour(); } else if(typeof nextStep !== 'undefined') { /*console.log(' matching case 2.2 (loading ' + nextStep + ')')*/ this.props.loadTourStep(nextStep); } else { /*console.log('matching case 2.3 (just passing on)') console.log(event)*/ } //Special Treatment for Select Boxes if(allowedSelectors.length > 0 && event.type === 'click' && allowedSelectors[0].hasOwnProperty('selectBox')) { /*console.log(' matching case 2 – select box handling')*/ document.VideApp = {}; document.VideApp.openTour = (value) => { let target; for(let n=0; n<allowedSelectors[0].selectBox.allowedValues.length;n++) { let allowedValue = allowedSelectors[0].selectBox.allowedValues[n]; if(value === allowedValue.value) { target = allowedValue.state; } } /*console.log(' TOUR: resolving function to load tour')*/ if(typeof target !== 'undefined') { /*console.log('DING DONG')*/ this.props.loadTourStep(target); return true; } else { /*console.log('DONG DONG')*/ this.props.loadTourStep(currentStepId); return true; //return false; } } //appElem.setAttribute('data-nextTourStep','tool004'); } } else { //other event types aren't resolved //console.log('passing event on without further action') /*console.log(' matching case 3 (passing event of type ' + event.type + ' on)')*/ } } renderTour(delayCount = 0) { /*console.log('\n-------renderTour---------')*/ let stepId = this.props.tour; let tourObj = TourSteps[stepId]; if(typeof tourObj === 'undefined') { console.log('[DEBUG] Unable to get tour item "' + stepId + '"') return false; } //object seems fine, continue //add "restrictive" class to background to suppress all user events let bg = document.querySelector('.tourBackground'); if(tourObj.restrictsAction && bg !== null) { bg.classList.add('restrictive'); } else if(bg) { bg.classList.remove('restrictive'); } let targetElem = document.querySelector(tourObj.attachTo); if(targetElem === null) { console.log('[DEBUG] Unable to find anchors for tour "' + stepId + '", with an attachTo of "' + tourObj.attachTo + '"'); //todo: revert tour return false; //throw new TourException(delayCount); } //let reference = document.querySelector('.editionPreview'); let popper = document.querySelector('#tourPopper'); let popperContent = popper.querySelector('.tourContent'); //render content into popper ReactDOM.render(tourObj.content[this.props.language],popperContent); let container = document.querySelector('.views'); let anotherPopper = new Popper( targetElem, popper, { // popper options here placement: tourObj.attachWhere, flip: { behavior: ['left','right','bottom','top'] }/*, preventOverflow: { boundariesElement: container, }*/ } ); /*let drop = new Drop({ target: targetElem, //classes: 'tourDrop', //classPrefix: 'tourDrop', //todo: fix classes!!! content: div, /\*position: 'bottom left',*\/ openOn: 'always', constrainToWindow: true, classes: 'drop-theme-arrows tourDrop', beforeClose: () => { /\*console.log('the drop is supposed to close now… (but I try to prevent that)'); return false;*\/ }, tetherOptions: { attachment: attachment, targetAttachment: targetAttachment, constraints: [ { to: 'window', pin: true, attachment: 'both' } ] } }); this.Drop = drop; //window.drop = drop; drop.on('close',(e) => { this.Drop = null; })*/ return true; } }; Tour.propTypes = { tour: PropTypes.string.isRequired, language: PropTypes.string.isRequired, closeTour: PropTypes.func.isRequired, loadTourStep: PropTypes.func.isRequired, nolog: PropTypes.bool.isRequired, fullState: PropTypes.object.isRequired }; export default Tour;
redux-form/example-fieldArrays/jsx/FieldArraysForm.js
Muzietto/react-playground
import React from 'react' import { Field, FieldArray, reduxForm } from 'redux-form' import validate from './validate' const renderField = ({ input, label, type, meta: { touched, error } }) => ( <div> <label>{label}</label> <div> <input {...input} type={type} placeholder={label} /> {touched && error && <span>{error}</span>} </div> </div> ) const renderHobbies = ({ fields, meta: { error } }) => ( <ul> <li> <button type="button" onClick={() => fields.push()}> Add Hobby </button> </li> {fields.map((hobby, index) => ( <li key={index}> <button type="button" title="Remove Hobby" onClick={() => fields.remove(index)} >Remove Hobby</button> <Field name={hobby} type="text" component={renderField} label={`Hobby #${index + 1}`} /> </li> ))} {error && <li className="error">{error}</li>} </ul> ) const renderMembers = ({ fields, meta: { error, submitFailed } }) => ( <ul> <li> <button type="button" onClick={() => fields.push({})}> Add Member </button> {submitFailed && error && <span>{error}</span>} </li> {fields.map((member, index) => ( <li key={index}> <button type="button" title="Remove Member" onClick={() => fields.remove(index)} >Remove Member</button> <h4>Member #{index + 1}</h4> <Field name={`${member}.firstName`} type="text" component={renderField} label="First Name" /> <Field name={`${member}.lastName`} type="text" component={renderField} label="Last Name" /> <FieldArray name={`${member}.hobbies`} component={renderHobbies} /> </li> ))} </ul> ) const FieldArraysForm = props => { const { handleSubmit, pristine, reset, submitting } = props return ( <form onSubmit={handleSubmit}> {/*<Field name="clubName" type="text" title="irrelevant stuff" component={renderField} label="Club Name" />*/} <FieldArray name="members" component={renderMembers} /> <div> <button type="submit" disabled={submitting}> Submit </button> <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button> </div> </form> ) } export default reduxForm({ form: 'fieldArrays', // a unique identifier for this form validate })(FieldArraysForm)
src/Parser/Core/Modules/NetherlightCrucibleTraits/SecureInTheLight.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import HealingDone from 'Parser/Core/Modules/HealingDone'; /** * Secure in the Light * Your harmful spells and abilities have the chance to deal 135000 additional damage and grant you Holy Bulwark, absorbing up to 135000 damage over 8 sec. */ class SecureInTheLight extends Analyzer { static dependencies = { combatants: Combatants, healingDone: HealingDone, }; damage = 0; on_initialized() { this.traitLevel = this.combatants.selected.traitsBySpellId[SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id]; this.active = this.traitLevel > 0; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SECURE_IN_THE_LIGHT_DAMAGE.id) { return; } this.damage += (event.amount || 0) + (event.absorbed || 0) + (event.overkill || 0); } subStatistic() { const healing = this.healingDone.byAbility(SPELLS.HOLY_BULWARK.id).effective; return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id}> <SpellIcon id={SPELLS.SECURE_IN_THE_LIGHT_TRAIT.id} noLink /> Secure in the Light </SpellLink> </div> <div className="flex-sub text-right"> <dfn data-tip={`${this.traitLevel} ${this.traitLevel > 1 ? `traits` : `trait`}`}> {formatPercentage(this.owner.getPercentageOfTotalHealingDone(healing))} % healing<br /> {formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damage))} % damage </dfn> </div> </div> ); } } export default SecureInTheLight;
app/javascript/mastodon/features/ui/index.js
SerCom-KC/mastodon
import classNames from 'classnames'; import React from 'react'; import { HotKeys } from 'react-hotkeys'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import NotificationsContainer from './containers/notifications_container'; import LoadingBarContainer from './containers/loading_bar_container'; import TabsBar from './components/tabs_bar'; import ModalContainer from './containers/modal_container'; import { isMobile } from '../../is_mobile'; import { debounce } from 'lodash'; import { uploadCompose, resetCompose } from '../../actions/compose'; import { expandHomeTimeline } from '../../actions/timelines'; import { expandNotifications } from '../../actions/notifications'; import { fetchFilters } from '../../actions/filters'; import { clearHeight } from '../../actions/height_cache'; import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers'; import UploadArea from './components/upload_area'; import ColumnsAreaContainer from './containers/columns_area_container'; import { Compose, Status, GettingStarted, KeyboardShortcuts, PublicTimeline, CommunityTimeline, AccountTimeline, AccountGallery, HomeTimeline, Followers, Following, Reblogs, Favourites, DirectTimeline, HashtagTimeline, Notifications, FollowRequests, GenericNotFound, FavouritedStatuses, ListTimeline, Blocks, DomainBlocks, Mutes, PinnedStatuses, Lists, } from './util/async-components'; import { me } from '../../initial_state'; import { previewState } from './components/media_modal'; // Dummy import, to make sure that <Status /> ends up in the application bundle. // Without this it ends up in ~8 very commonly used bundles. import '../../components/status'; const messages = defineMessages({ beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' }, }); const mapStateToProps = state => ({ isComposing: state.getIn(['compose', 'is_composing']), hasComposingText: state.getIn(['compose', 'text']).trim().length !== 0, hasMediaAttachments: state.getIn(['compose', 'media_attachments']).size > 0, dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null, }); const keyMap = { help: '?', new: 'n', search: 's', forceNew: 'option+n', focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'], reply: 'r', favourite: 'f', boost: 'b', mention: 'm', open: ['enter', 'o'], openProfile: 'p', moveDown: ['down', 'j'], moveUp: ['up', 'k'], back: 'backspace', goToHome: 'g h', goToNotifications: 'g n', goToLocal: 'g l', goToFederated: 'g t', goToDirect: 'g d', goToStart: 'g s', goToFavourites: 'g f', goToPinned: 'g p', goToProfile: 'g u', goToBlocked: 'g b', goToMuted: 'g m', goToRequests: 'g r', toggleHidden: 'x', }; class SwitchingColumnsArea extends React.PureComponent { static propTypes = { children: PropTypes.node, location: PropTypes.object, onLayoutChange: PropTypes.func.isRequired, }; state = { mobile: isMobile(window.innerWidth), }; componentWillMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentDidUpdate (prevProps) { if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) { this.node.handleChildrenContentChange(); } } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } shouldUpdateScroll (_, { location }) { return location.state !== previewState; } handleResize = debounce(() => { // The cached heights are no longer accurate, invalidate this.props.onLayoutChange(); this.setState({ mobile: isMobile(window.innerWidth) }); }, 500, { trailing: true, }); setRef = c => { this.node = c.getWrappedInstance().getWrappedInstance(); } render () { const { children } = this.props; const { mobile } = this.state; const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />; return ( <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}> <WrappedSwitch> {redirect} <WrappedRoute path='/getting-started' component={GettingStarted} content={children} /> <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} /> <WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} /> <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} /> <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} /> <WrappedRoute path='/statuses/new' component={Compose} content={children} /> <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} /> <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} /> <WrappedRoute component={GenericNotFound} content={children} /> </WrappedSwitch> </ColumnsAreaContainer> ); } } export default @connect(mapStateToProps) @injectIntl @withRouter class UI extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { dispatch: PropTypes.func.isRequired, children: PropTypes.node, isComposing: PropTypes.bool, hasComposingText: PropTypes.bool, hasMediaAttachments: PropTypes.bool, location: PropTypes.object, intl: PropTypes.object.isRequired, dropdownMenuIsOpen: PropTypes.bool, }; state = { draggingOver: false, }; handleBeforeUnload = (e) => { const { intl, isComposing, hasComposingText, hasMediaAttachments } = this.props; if (isComposing && (hasComposingText || hasMediaAttachments)) { // Setting returnValue to any string causes confirmation dialog. // Many browsers no longer display this text to users, // but we set user-friendly message for other browsers, e.g. Edge. e.returnValue = intl.formatMessage(messages.beforeUnload); } } handleLayoutChange = () => { // The cached heights are no longer accurate, invalidate this.props.dispatch(clearHeight()); } handleDragEnter = (e) => { e.preventDefault(); if (!this.dragTargets) { this.dragTargets = []; } if (this.dragTargets.indexOf(e.target) === -1) { this.dragTargets.push(e.target); } if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) { this.setState({ draggingOver: true }); } } handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); try { e.dataTransfer.dropEffect = 'copy'; } catch (err) { } return false; } handleDrop = (e) => { e.preventDefault(); this.setState({ draggingOver: false }); if (e.dataTransfer && e.dataTransfer.files.length === 1) { this.props.dispatch(uploadCompose(e.dataTransfer.files)); } } handleDragLeave = (e) => { e.preventDefault(); e.stopPropagation(); this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el)); if (this.dragTargets.length > 0) { return; } this.setState({ draggingOver: false }); } closeUploadModal = () => { this.setState({ draggingOver: false }); } handleServiceWorkerPostMessage = ({ data }) => { if (data.type === 'navigate') { this.context.router.history.push(data.path); } else { console.warn('Unknown message type:', data.type); } } componentWillMount () { window.addEventListener('beforeunload', this.handleBeforeUnload, false); document.addEventListener('dragenter', this.handleDragEnter, false); document.addEventListener('dragover', this.handleDragOver, false); document.addEventListener('drop', this.handleDrop, false); document.addEventListener('dragleave', this.handleDragLeave, false); document.addEventListener('dragend', this.handleDragEnd, false); if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage); } this.props.dispatch(expandHomeTimeline()); this.props.dispatch(expandNotifications()); setTimeout(() => this.props.dispatch(fetchFilters()), 500); } componentDidMount () { this.hotkeys.__mousetrap__.stopCallback = (e, element) => { return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName); }; } componentWillUnmount () { window.removeEventListener('beforeunload', this.handleBeforeUnload); document.removeEventListener('dragenter', this.handleDragEnter); document.removeEventListener('dragover', this.handleDragOver); document.removeEventListener('drop', this.handleDrop); document.removeEventListener('dragleave', this.handleDragLeave); document.removeEventListener('dragend', this.handleDragEnd); } setRef = c => { this.node = c; } handleHotkeyNew = e => { e.preventDefault(); const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea'); if (element) { element.focus(); } } handleHotkeySearch = e => { e.preventDefault(); const element = this.node.querySelector('.search__input'); if (element) { element.focus(); } } handleHotkeyForceNew = e => { this.handleHotkeyNew(e); this.props.dispatch(resetCompose()); } handleHotkeyFocusColumn = e => { const index = (e.key * 1) + 1; // First child is drawer, skip that const column = this.node.querySelector(`.column:nth-child(${index})`); if (column) { const status = column.querySelector('.focusable'); if (status) { status.focus(); } } } handleHotkeyBack = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } setHotkeysRef = c => { this.hotkeys = c; } handleHotkeyToggleHelp = () => { if (this.props.location.pathname === '/keyboard-shortcuts') { this.context.router.history.goBack(); } else { this.context.router.history.push('/keyboard-shortcuts'); } } handleHotkeyGoToHome = () => { this.context.router.history.push('/timelines/home'); } handleHotkeyGoToNotifications = () => { this.context.router.history.push('/notifications'); } handleHotkeyGoToLocal = () => { this.context.router.history.push('/timelines/public/local'); } handleHotkeyGoToFederated = () => { this.context.router.history.push('/timelines/public'); } handleHotkeyGoToDirect = () => { this.context.router.history.push('/timelines/direct'); } handleHotkeyGoToStart = () => { this.context.router.history.push('/getting-started'); } handleHotkeyGoToFavourites = () => { this.context.router.history.push('/favourites'); } handleHotkeyGoToPinned = () => { this.context.router.history.push('/pinned'); } handleHotkeyGoToProfile = () => { this.context.router.history.push(`/accounts/${me}`); } handleHotkeyGoToBlocked = () => { this.context.router.history.push('/blocks'); } handleHotkeyGoToMuted = () => { this.context.router.history.push('/mutes'); } handleHotkeyGoToRequests = () => { this.context.router.history.push('/follow_requests'); } render () { const { draggingOver } = this.state; const { children, isComposing, location, dropdownMenuIsOpen } = this.props; const handlers = { help: this.handleHotkeyToggleHelp, new: this.handleHotkeyNew, search: this.handleHotkeySearch, forceNew: this.handleHotkeyForceNew, focusColumn: this.handleHotkeyFocusColumn, back: this.handleHotkeyBack, goToHome: this.handleHotkeyGoToHome, goToNotifications: this.handleHotkeyGoToNotifications, goToLocal: this.handleHotkeyGoToLocal, goToFederated: this.handleHotkeyGoToFederated, goToDirect: this.handleHotkeyGoToDirect, goToStart: this.handleHotkeyGoToStart, goToFavourites: this.handleHotkeyGoToFavourites, goToPinned: this.handleHotkeyGoToPinned, goToProfile: this.handleHotkeyGoToProfile, goToBlocked: this.handleHotkeyGoToBlocked, goToMuted: this.handleHotkeyGoToMuted, goToRequests: this.handleHotkeyGoToRequests, }; return ( <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}> <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}> <TabsBar /> <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}> {children} </SwitchingColumnsArea> <NotificationsContainer /> <LoadingBarContainer className='loading-bar' /> <ModalContainer /> <UploadArea active={draggingOver} onClose={this.closeUploadModal} /> </div> </HotKeys> ); } }
react/Autosuggest/Autosuggest.demo.js
seek-oss/seek-style-guide
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Autosuggest from './Autosuggest'; import styles from '../TextField/TextField.less'; import classnames from 'classnames'; import fieldMessageOptions from '../FieldMessage/FieldMessage.demoFragment'; import fieldLabelOptions from '../FieldLabel/FieldLabel.demoFragment'; class AutosuggestContainer extends Component { static propTypes = { component: PropTypes.func.isRequired, componentProps: PropTypes.object.isRequired }; constructor() { super(); this.state = { inputValue: '' }; } handleChange = (_, { newValue }) => { this.setState({ inputValue: newValue }); }; handleFocus = event => { console.log('Focused, event: ', event); }; handleClear = () => { this.setState({ inputValue: '' }); }; render() { const { component: DemoComponent, componentProps } = this.props; const { inputValue } = this.state; return ( <div style={{ width: '300px' }}> <DemoComponent {...componentProps} type="search" value={inputValue} onChange={this.handleChange} onFocus={this.handleFocus} onClear={this.handleClear} /> </div> ); } } export default { route: '/autosuggest', title: 'Autosuggest', category: 'Form', component: Autosuggest, container: AutosuggestContainer, initialProps: { id: 'jobTitles', label: 'Job Titles', type: 'search', value: '...', onChange: () => {}, autosuggestProps: { suggestions: [ 'Developer', 'Product manager', 'Iteration manager', 'Designer' ], onSuggestionsFetchRequested: () => {}, onSuggestionsClearRequested: () => {}, renderSuggestion: suggestion => <div>{suggestion}</div>, getSuggestionValue: suggestion => suggestion }, message: false, onClear: () => {} }, options: [ { label: 'States', type: 'checklist', states: [ { label: 'Focus', transformProps: ({ className, ...props }) => ({ ...props, className: classnames(className, styles.rootFocus) }) }, { label: 'Grouped', transformProps: ({ autosuggestProps, ...props }) => ({ ...props, autosuggestProps: { ...autosuggestProps, multiSection: true, suggestions: [ { title: 'RECENT TITLES', suggestions: [ 'Developer', 'Product manager', 'Iteration manager', 'Designer' ] } ], renderSectionTitle: section => <div>{section.title}</div>, getSectionSuggestions: section => section.suggestions } }) }, { label: 'Show mobile backdrop', transformProps: ({ ...props }) => ({ ...props, showMobileBackdrop: true }) } ] }, ...fieldMessageOptions, ...fieldLabelOptions ] };