path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/redux/root.js
andreipreda/coconut
import React from 'react'; import { Provider } from 'react-redux'; import store from './store'; import { AppRouter } from './router'; export const Root = () => ( <Provider store={store}> <AppRouter /> </Provider> );
src/higherOrders/Sort.js
Lobos/react-ui
import React from 'react' import PropTypes from '../utils/proptypes' import { isEmpty } from '../utils/objects' import PureRender from '../mixins/PureRender' const defaultSort = (key, asc) => (a, b) => { let x = a[key] let y = b[key] if (asc === 0) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)) } else { return ((x > y) ? -1 : ((x < y) ? 1 : 0)) } } export default function (Component) { class Sort extends React.Component { constructor (props) { super(props) this.state = {} this.handleSort = this.handleSort.bind(this) } handleSort (key, asc, fn) { this.setState({ key, asc, fn }) this.props.onSort && this.props.onSort(key, asc) } sort (data, { key, asc, fn }) { if (!Array.isArray(data)) return data return data.sort(typeof fn === 'function' ? fn : defaultSort(key, asc)) } render () { const state = this.state const { data, ...props } = this.props let sortData = isEmpty(state) ? data : this.sort(data, state) return ( <Component {...props} onSort={this.handleSort} sortStatus={{ key: state.key, asc: state.asc }} data={sortData} /> ) } } Sort.propTypes = { data: PropTypes.array_element_string, onSort: PropTypes.func } return PureRender()(Sort) }
frontend/src/components/editor/index.js
1905410/Misago
// jshint ignore:start import React from 'react'; import Code from './actions/code'; import Emphasis from './actions/emphasis'; import Hr from './actions/hr'; import Image from './actions/image'; import Link from './actions/link'; import Striketrough from './actions/striketrough'; import Strong from './actions/strong'; import Quote from './actions/quote'; import AttachmentsEditor from './attachments'; import Upload from './attachments/upload-button/'; import MarkupPreview from './markup-preview'; import * as textUtils from './textUtils'; import Button from 'misago/components/button'; import misago from 'misago'; import ajax from 'misago/services/ajax'; import modal from 'misago/services/modal'; import snackbar from 'misago/services/snackbar'; export default class extends React.Component { constructor(props) { super(props); this.state = { isPreviewLoading: false }; } onPreviewClick = () => { if (this.state.isPreviewLoading) { return; } this.setState({ isPreviewLoading: true }); ajax.post(misago.get('PARSE_MARKUP_API'), {post: this.props.value}).then((data) => { modal.show( <MarkupPreview markup={data.parsed} /> ); this.setState({ isPreviewLoading: false }); }, (rejection) => { if (rejection.status === 400) { snackbar.error(rejection.detail); } else { snackbar.apiError(rejection); } this.setState({ isPreviewLoading: false }); }); }; replaceSelection = (operation) => { operation(textUtils.getSelectionText(), this._replaceSelection); }; _replaceSelection = (newValue) => { this.props.onChange({ target: { value: textUtils.replace(newValue) } }); }; render() { return ( <div className="editor-border"> <textarea className="form-control" defaultValue={this.props.value} disabled={this.props.loading} id="editor-textarea" onChange={this.props.onChange} rows="9" ></textarea> <div className="editor-footer"> <Strong className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Emphasis className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Striketrough className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Hr className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Link className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Image className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Quote className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Code className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Upload className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} /> <Button className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} onClick={this.onPreviewClick} type="button" > {gettext("Preview")} </Button> <Button className="btn-primary btn-sm pull-right" loading={this.props.loading} > {this.props.submitLabel || gettext("Post")} </Button> <button className="btn btn-default btn-sm pull-right" disabled={this.props.loading} onClick={this.props.onCancel} type="button" > {gettext("Cancel")} </button> <Protect canProtect={this.props.canProtect} disabled={this.props.loading} onProtect={this.props.onProtect} onUnprotect={this.props.onUnprotect} protect={this.props.protect} /> </div> <AttachmentsEditor attachments={this.props.attachments} onAttachmentsChange={this.props.onAttachmentsChange} placeholder={this.props.placeholder} replaceSelection={this.replaceSelection} /> </div> ); } } export function Protect(props) { if (props.canProtect) { return ( <button className="btn btn-icon btn-default btn-sm pull-right" disabled={props.disabled} onClick={props.protect ? props.onUnprotect : props.onProtect} title={props.protect ? gettext('Protected') : gettext('Protect')} type="button" > <span className="material-icon"> {props.protect ? 'lock' : 'lock_outline'} </span> </button> ); } else { return null; } }
server/server.js
tranphong001/BIGVN
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } app.use('/static', Express.static('./static')); app.use('/fonts', Express.static('./fonts')); app.use('/images', Express.static('./client/images')); app.use('/photo', Express.static('./public')); app.use('/banner', Express.static('../adminBig/banner')); app.use('/blog', Express.static('./blog')); // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; import helmet from 'helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import news from './routes/news.routes'; import users from './routes/user.routes'; import categories from './routes/category.routes'; import cities from './routes/city.routes'; import districts from './routes/district.routes'; import wards from './routes/ward.routes'; import banners from './routes/banner.routes'; import topics from './routes/topic.routes'; import settings from './routes/setting.routes'; import keywords from './routes/keyword.routes'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } }); app.use(helmet.xssFilter()); app.use(helmet.frameguard({ action: 'deny' })); app.use(helmet.noSniff()); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '30mb' })); app.use(bodyParser.urlencoded({ limit: '30mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist/client'))); app.use('/api', [banners, settings, topics, cities, districts, wards, categories, users, keywords, news]); // Render Initial HTML {/*<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">*/} {/*<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">*/} {/*<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">*/} {/*<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">*/} {/*<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">*/} const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link rel="stylesheet" href="/static/font-awesome.min.css"> <link rel="stylesheet" href="/static/bootstrap.min.css"> <link rel="stylesheet" href="/static/bootstrap-theme.min.css"> <link rel="stylesheet" href="/static/materialIcons/materialIcons.css"> </head> <body> <div id="root"><div>${html}</div></div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app const server = app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
client/channel/helpers/clickableItem.js
iiet/iiet-chat
import React from 'react'; import { css } from '@rocket.chat/css-in-js'; export function clickableItem(WrappedComponent) { const clickable = css` cursor: pointer; border-bottom: 2px solid #F2F3F5 !important; &:hover, &:focus { background: #F7F8FA; } `; return (props) => <WrappedComponent className={clickable} tabIndex={0} {...props}/>; }
src/index.js
ndemianc/react_app
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import Board from './components/board'; import { observe } from './components/game'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); const rootElement = document.querySelector('.container'); observe(rookPosition => ReactDOM.render( <Board rookPosition={rookPosition} /> , rootElement ) );
node_modules/semantic-ui-react/dist/es/collections/Table/TableFooter.js
jessicaappelbaum/cljs-update
import React from 'react'; import { META } from '../../lib'; import TableHeader from './TableHeader'; /** * A table can have a footer. */ function TableFooter(props) { return React.createElement(TableHeader, props); } TableFooter.handledProps = ['as']; TableFooter._meta = { name: 'TableFooter', type: META.TYPES.COLLECTION, parent: 'Table' }; TableFooter.defaultProps = { as: 'tfoot' }; export default TableFooter;
docs/src/app/components/pages/components/DropDownMenu/ExampleLabeled.js
ruifortes/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default class DropDownMenuLabeledExample extends React.Component { constructor(props) { super(props); this.state = {value: 2}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} label="5 am - 12 pm" primaryText="Morning" /> <MenuItem value={2} label="12 pm - 5 pm" primaryText="Afternoon" /> <MenuItem value={3} label="5 pm - 9 pm" primaryText="Evening" /> <MenuItem value={4} label="9 pm - 5 am" primaryText="Night" /> </DropDownMenu> ); } }
www/src/layouts/index.js
tsuyoshiwada/react-drip-form
import React from 'react'; /* eslint-disable import/no-extraneous-dependencies */ import 'prismjs'; import 'prismjs/components/prism-bash'; import 'prismjs/components/prism-javascript'; import 'prismjs/components/prism-typescript'; import 'prismjs/components/prism-jsx'; import 'prismjs/components/prism-css'; import 'prismjs/components/prism-json'; import 'prismjs/components/prism-markdown'; import 'prismjs/themes/prism.css'; /* eslint-enable import/no-extraneous-dependencies */ import 'normalize.css'; import '../css/style.css'; export default ({ children }) => ( <div> {children()} </div> );
components/common/icons.js
DarcyChan/darcychan.com
/* Icon Component. A common component to render an SVG icon. */ import React from 'react'; import ArrowRight from 'assets/arrow-right.svg'; import Close from 'assets/close.svg'; import Logo from 'assets/logo.svg'; import Menu from 'assets/menu.svg'; import Photo from 'assets/photo.svg'; export default class Icon extends React.Component { render() { const { glyph, ...props } = this.props; return ( <svg {...props}> <use xlinkHref={`#${glyph.id}`} /> </svg> ); } } export const Glyph = { ArrowRight: ArrowRight, Close: Close, Logo: Logo, Menu: Menu, Photo: Photo };
src/ColumnMarkers.js
ornl-sava/vis-react-components
import React from 'react' import PropTypes from 'prop-types' import { setEase } from './util/d3' import SVGComponent from './SVGComponent' // NOTE: Fills top margin with rect column markers // Requires a top margin greater than 5px, xScale, and the data // Expects 2D data like heatmap class ColumnMarkers extends React.Component { render () { let { className, data, onClick, xScale, xAccessor, colorScale, chartWidth, margin } = this.props let y = -margin.top let height = (margin.top - 2 > 5) ? margin.top - 2 : 5 return ( <g className={className}> {data[0].bins.map((d, i) => { // Get width of column let width = (i + 1 < data[0].bins.length) ? xScale(data[0].bins[i + 1][xAccessor.key]) : chartWidth width -= xScale(d[xAccessor.key]) // Get total value for column let total = 0 for (let j = 0; j < data.length; j++) { total += data[j].bins[i][xAccessor.key] } return ( <SVGComponent Component='rect' key={i} data={d} index={i} x={xScale(d[xAccessor.key])} y={y} fill={colorScale(total)} width={width} height={height} onClick={onClick} onUpdate={{ func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('x', props.x) .attr('y', props.y) .attr('width', props.width) .attr('height', props.height) .attr('fill', props.fill) return transition } }} /> ) })} </g> ) } } ColumnMarkers.defaultProps = { data: [], xAccessor: { key: 'key', value: 'value' }, onClick: () => {}, className: 'columnMarker', margin: { top: 0, right: 0, bottom: 0, left: 0 }, chartWidth: 0 } ColumnMarkers.propTypes = { data: PropTypes.array, colorScale: PropTypes.any, xScale: PropTypes.any, xAccessor: PropTypes.any, onClick: PropTypes.func, className: PropTypes.string, margin: PropTypes.object, chartWidth: PropTypes.number } export default ColumnMarkers
client/src/javascript/components/sidebar/DiskUsage.js
jfurrow/flood
import {FormattedMessage} from 'react-intl'; import React from 'react'; import EventTypes from '../../constants/EventTypes'; import DiskUsageStore from '../../stores/DiskUsageStore'; import Size from '../general/Size'; import Tooltip from '../general/Tooltip'; import connectStores from '../../util/connectStores'; import ProgressBar from '../general/ProgressBar'; import SettingsStore from '../../stores/SettingsStore'; const DiskUsageTooltipItem = ({label, value}) => { return ( <li className="diskusage__details-list__item"> <label className="diskusage__details-list__label">{label}</label> <Size className="diskuage__size-used" value={value} /> </li> ); }; class DiskUsage extends React.Component { getDisks() { const {disks, mountPoints} = this.props; const diskMap = disks.reduce((disksByTarget, disk) => { disksByTarget[disk.target] = disk; return disksByTarget; }, {}); return mountPoints .filter(target => target in diskMap) .map(target => diskMap[target]) .map(d => { return ( <li key={d.target} className="sidebar-filter__item sidebar__diskusage"> <Tooltip content={ <ul className="diskusage__details-list"> <DiskUsageTooltipItem value={d.used} label={<FormattedMessage id="status.diskusage.used" defaultMessage="Used" />} /> <DiskUsageTooltipItem value={d.avail} label={<FormattedMessage id="status.diskusage.free" defaultMessage="Free" />} /> <DiskUsageTooltipItem value={d.size} label={<FormattedMessage id="status.diskusage.total" defaultMessage="Total" />} /> </ul> } position="top" wrapperClassName="diskusage__item"> <div className="diskusage__text-row"> {d.target} <span>{Math.round((100 * d.used) / d.size)}%</span> </div> <ProgressBar percent={(100 * d.used) / d.size} /> </Tooltip> </li> ); }); } render() { const disks = this.getDisks(); if (disks.length === 0) { return null; } return ( <ul className="sidebar-filter sidebar__item"> <li className="sidebar-filter__item sidebar-filter__item--heading"> <FormattedMessage id="status.diskusage.title" defaultMessage="Disk Usage" /> </li> {disks} </ul> ); } } export default connectStores(DiskUsage, () => [ { store: DiskUsageStore, event: EventTypes.DISK_USAGE_CHANGE, getValue: ({store}) => ({ disks: store.getDiskUsage(), }), }, { store: SettingsStore, event: EventTypes.SETTINGS_CHANGE, getValue: ({store}) => { return { mountPoints: store.getFloodSettings('mountPoints'), }; }, }, ]);
src/index.js
kfergin/dragging-boxes-example
import React, { Component } from 'react'; import { render } from 'react-dom'; import { TransitionMotion, spring } from 'react-motion'; import uuid from 'uuid'; import classNames from 'classnames'; import './styles/main.scss'; class Box extends Component { constructor(props) { super(props); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); } handleMouseDown(e) { this.props.handleMouseDown(e, this.props.id); } handleTouchStart(e) { e.preventDefault(); this.props.handleTouchStart(e, this.props.id); } render() { const {opacity, left, top, id} = this.props; return ( <div className="box" style={{ opacity: opacity, left: `${left}px`, top: `${top}px` }} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart} /> ); } } class Container extends Component { constructor(props) { super(props); // Determine if we're responding to touch or click events this.touchDebounce = undefined; this.handleGlobalTouch = this.handleGlobalTouch.bind(this); this.handleGlobalMouseover = this.handleGlobalMouseover.bind(this); // Notify when Shift is pressed. CSS purposes. this.handleKeyUpDown = this.handleKeyUpDown.bind(this); // Adding, moving, and removing boxes this.addBox = this.addBox.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); this.selectBox = this.selectBox.bind(this); this.removeBox = this.removeBox.bind(this); this.handleMove = this.handleMove.bind(this); this.handleRelease = this.handleRelease.bind(this); // Initial state const id = uuid(), left = 0, top = 0; this.state = { touchBased: 'ontouchstart' in window, boxes: { byID: {[id]: {id, left, top}}, allIDs: [id] }, selectedBox: null, lastSelect: 0, removing: false }; } // would want to remove these listeners if component were part of larger app componentDidMount() { document.addEventListener('touchstart', this.handleGlobalTouch); document.addEventListener('mouseover', this.handleGlobalMouseover); document.querySelector('html').addEventListener('keydown', this.handleKeyUpDown); document.querySelector('html').addEventListener('keyup', this.handleKeyUpDown); } handleGlobalTouch() { clearTimeout(this.touchDebounce); if (!this.state.touchBased) this.setState({touchBased: true}); this.touchDebounce = setTimeout(() => { this.touchDebounce = undefined; }, 500) } handleGlobalMouseover() { if (this.touchDebounce === undefined && this.state.touchBased) this.setState({touchBased: false}); } handleKeyUpDown(e) { if (e.which === 16) { this.setState(prevState => ({ ...prevState, removing: !prevState.removing })); } } addBox(e) { if (this.state.selectedBox) return; const id = uuid(), left = 0, top = 0; this.setState(prevState => ({ ...prevState, boxes: { byID: { ...prevState.boxes.byID, [id]: {id, left, top} }, allIDs: [...prevState.boxes.allIDs, id] } })); } selectBox(e, id, now) { let {clientX, clientY} = e; if (e.type === 'touchstart') { ({clientX, clientY} = e.changedTouches[0]); } this.setState(prevState => { // Possible to "select" a box as it's transition out. // Potential problem bc it's out of state but kept in TransitionMotion const box = prevState.boxes.byID[id], selectedBox = !box ? null : { id, diffX: clientX - box.left, diffY: clientY - box.top }; return { ...prevState, lastSelect: now, selectedBox }; }); } removeBox(id) { this.setState(prevState => { const {[id]: toRemove, ...rest} = prevState.boxes.byID; return { ...prevState, selectedBox: null, boxes: { byID: rest, allIDs: prevState.boxes.allIDs.filter(aid => aid !== id) } }; }); } handleMouseDown(e, id) { if (this.state.touchBased) return; const now = Date.now(); if (e.shiftKey) { this.removeBox(id); } else { this.selectBox(e, id, now); } } handleTouchStart(e, id) { const now = Date.now(); if (now - this.state.lastSelect > 250) { this.selectBox(e, id, now); } else { this.removeBox(id); } } handleMove(e) { if (!this.state.selectedBox) return; let {clientX, clientY} = e; if (e.type === 'touchmove') { e.preventDefault(); ({clientX, clientY} = e.changedTouches[0]); } this.setState(prevState => { const {id, diffX, diffY} = prevState.selectedBox; return { ...prevState, boxes: { ...prevState.boxes, byID: { ...prevState.boxes.byID, [id]: { id, left: clientX - diffX, top: clientY - diffY } } } }; }); } handleRelease(e) { this.setState(prevState => ({ ...prevState, selectedBox: null })); } render() { const containerClasses = classNames({ "container": true, "grabbing": this.state.selectedBox, "removing": this.state.removing }); return ( <div className={containerClasses} onMouseMove={this.handleMove} onTouchMove={this.handleMove} onMouseUp={this.handleRelease} onTouchEnd={this.handleRelease} > <div className="instructions"> <h4>Drag some boxes!</h4> <ul> <li>Add boxes by {this.state.touchBased ? 'tapping' : 'hovering over'} the top-left area of the screen</li> <li>To remove, {this.state.touchBased ? 'double-tap' : 'hold shift and click on'} a box.</li> </ul> </div> <div className="new-box-area" onMouseEnter={this.addBox} onTouchStart={this.addBox} /> <TransitionMotion willEnter={() => ({opacity: 0, left: 0, top: 0})} willLeave={(lv) => ({...lv.styles, opacity: spring(0)})} styles={this.state.boxes.allIDs.map((id) => ({ key: id, style: { opacity: spring(1), left: spring(this.state.boxes.byID[id].left), top: spring(this.state.boxes.byID[id].top) } }))} > {instances => ( <div className="boxes"> {instances.map(inst => ( <Box key={inst.key} {...{...inst.style, id: inst.key}} handleMouseDown={this.handleMouseDown} handleTouchStart={this.handleTouchStart} /> ))} </div> )} </TransitionMotion> </div> ); } } render( <Container/>, document.getElementById('dragEl') );
node_modules/react-bootstrap/es/PaginationButton.js
darklilium/Factigis_2
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: elementType, className: React.PropTypes.string, eventKey: React.PropTypes.any, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, active: React.PropTypes.bool, onClick: React.PropTypes.func }; var defaultProps = { componentClass: SafeAnchor, active: false, disabled: false }; var PaginationButton = function (_React$Component) { _inherits(PaginationButton, _React$Component); function PaginationButton(props, context) { _classCallCheck(this, PaginationButton); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, active = _props2.active, disabled = _props2.disabled, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === SafeAnchor) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return React.createElement( 'li', { className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(Component, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return PaginationButton; }(React.Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; export default PaginationButton;
src/SparklinesLine.js
konsumer/react-sparklines
import React from 'react'; export default class SparklinesLine extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style } = this.props; const linePoints = points .map((p) => [p.x, p.y]) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: color || style.fill || 'slategray' }; return ( <g> <polyline points={fillPoints.join(' ')} style={fillStyle} /> <polyline points={linePoints.join(' ')} style={lineStyle} /> </g> ) } }
examples/universal/client/index.js
ggerrietts/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
scripts/stores/GetBookStore.js
nverdhan/satticentre
import React from 'react'; import { register } from '../AppDispatcher'; import { createStore, mergeIntoBag, isInBag } from '../utils/StoreUtils'; import selectn from 'selectn'; var _book = {} var _bookUsers = [] var _bookStatus = 'NA' // NA, OWN, WISH, LEND, RENT var _showLoading = true; const GetBookStore = createStore({ get(){ return _book; }, getBookUsers(){ return _bookUsers }, getStatus(){ return _bookStatus; }, getLoadingStatus(){ return _showLoading; }, updateBook(book){ _book = book; }, updateBookUsers(users){ _bookUsers = users; }, updateStatus(status){ _bookStatus = status; }, updateShowLoading(bool){ _showLoading = bool; } }); GetBookStore.dispathToken = register(action=>{ const responseData = selectn('response.data', action); switch(action.type){ case 'FETCH_GET_BOOK_INFO_FROM_API': GetBookStore.updateShowLoading(true); break; case 'FETCH_GET_BOOK_INFO_FROM_API_SUCCESS': if(responseData){ var book = selectn('book', responseData); var users = selectn('users', responseData); GetBookStore.updateBook(book); GetBookStore.updateBookUsers(users); GetBookStore.updateShowLoading(false); } break; } GetBookStore.emitChange(); }); export default GetBookStore;
snippets/camunda-tasklist-examples/camunda-react-app/src/components/forms/myprocess/approveDataTask.js
camunda/camunda-consulting
import React from 'react' import { connect } from 'react-redux' import { Field, reduxForm } from 'redux-form' import { Form, Button } from 'semantic-ui-react' import { InputField, CheckboxField, TextAreaField } from 'react-semantic-redux-form' import * as Validation from '../../../constants/ValidationOptions' let SimpleForm = props => { const { handleSubmit } = props return ( <Form onSubmit={handleSubmit}> <legend>Approve Form</legend> <Field name='lastName' component={InputField} label='Last Name' placeholder='Last Name' validate={[ Validation.required, Validation.maxLength15, Validation.minLength2 ]}/> <Field name='items' component={TextAreaField} label='Items'/> <Form.Group> <Field name='approved' component={CheckboxField} label='Approve'/> </Form.Group> <Form.Field control={Button} primary type='submit'>Complete</Form.Field> </Form> ) } SimpleForm = reduxForm({ form: 'simpleForm', enableReinitialize: true })(SimpleForm) SimpleForm = connect( state => ({ initialValues: state.entities.taskVariables ? state.entities.taskVariables.variables : {} }) )(SimpleForm) export default SimpleForm
pages/api/table-cell.js
AndriusBil/material-ui
// @flow import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './table-cell.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
src/svg-icons/image/blur-linear.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBlurLinear = (props) => ( <SvgIcon {...props}> <path d="M5 17.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM9 13c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zM3 21h18v-2H3v2zM5 9.5c.83 0 1.5-.67 1.5-1.5S5.83 6.5 5 6.5 3.5 7.17 3.5 8 4.17 9.5 5 9.5zm0 4c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM9 17c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8-.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM3 3v2h18V3H3zm14 5.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm0 4c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM13 9c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1z"/> </SvgIcon> ); ImageBlurLinear = pure(ImageBlurLinear); ImageBlurLinear.displayName = 'ImageBlurLinear'; ImageBlurLinear.muiName = 'SvgIcon'; export default ImageBlurLinear;
node_modules/react-bootstrap/es/Tooltip.js
ivanhristov92/bookingCalendar
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
app/LoginScene.js
dalmago/thatThing
import React, { Component } from 'react'; import { Text, View, Button, TextInput, Picker, ActivityIndicator, Alert, } from 'react-native' export class LoginScene extends Component { constructor(props){ super(props); this.state = {pickerValue: 'dw', loading: false, text: '', text2: ''}; } render() { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "rgb(74,144,226)", }}> <View style={{ flex: 1, justifyContent: "flex-end", alignItems: "center", }}> <Picker style={{ width: 200, }} selectedValue={this.state && this.state.pickerValue} onValueChange={(value) => {this.setState({pickerValue: value});}}> <Picker.Item label={'Telit Device Wise'} value={'dw'} /> <Picker.Item label={'AWS IoT'} value={'aws'} /> <Picker.Item label={'Cisco Jasper'} value={'jas'} /> </Picker> <Text>{'\n'}</Text> </View> <View style={{ flex: 1, justifyContent: "space-around", alignItems: "center", }}> <TextInput style={{ height: 50, width: 300, borderWidth: 4, borderColor: "rgba(0,0,0,0.5)", textAlign: "center", fontSize: 19, }} keyboardType = {"email-address"} returnKeyType = {"next"} autoCapitalize = {"none"} placeholder= {"Login"} autoCorrect = {false} autoFocus = {true} placeholderTextColor={"rgb(103,103,103)"} onChangeText={(text) => {this.setState({text})}} onSubmitEditing={() => {this.refs.pass.focus();}} value={(this.state && this.state.text) || ''} /> <TextInput style={{ height: 50, width: 300, borderWidth: 4, borderColor: "rgba(0,0,0,0.5)", textAlign: "center", fontSize: 28, }} ref = {"pass"} autoCapitalize = {"none"} secureTextEntry = {true} returnKeyType = {"done"} returnKeyLabel = {"Login"} placeholder={"Password"} placeholderTextColor={"rgb(103,103,103)"} onChangeText={(text) => {this.setState({text2: text})}} onSubmitEditing={() => {this.login()}} value={(this.state && this.state.text2) || ''} /> </View> <View style={{ flex: 1, justifyContent: "flex-start", alignItems: "center", }}> <Text>{'\n'}</Text> {(this.state.loading)? <ActivityIndicator style={{ alignItems: 'center', justifyContent: 'center', }} animating={this.state.loading} size={"large"} color={'black'} /> : <Button onPress={() => {this.login()}} title="Login" color="rgb(0,0,0)" />} </View> </View> ); } login(){ this.setState({loading: true}); var portal = this.state.pickerValue; switch(portal){ case 'dw': this.login_dw(); break; default: Alert.alert('Portal ainda não implementado'); this.setState({loading: false}); } } login_dw(){ var login = this.state.text; var pass = this.state.text2; var server = "https://api.devicewise.com/api"; js = { "auth" : { "command" : "api.authenticate", "params" : { "username": login, "password": pass } } } fetch(server, { method: 'POST', body: JSON.stringify(js) }).then((res) => res.json()).then((res) => { if (__DEV__ === true) // if in development console.log('login_dw: ', res); if (res.success === false){ this.setState({loading: false, text:'', text2: ''}); Alert.alert('Login falhou!', 'Usuário ou senha inválido'); } else if (res.auth.success === true){ js_org = { "auth":{"sessionId": res.auth.params.sessionId}, "1": { "command": "session.org.switch", "params" : { "key" : "UNIVERSIDADEFEDERALDESANTAMARIA" } } } fetch(server, {method: 'POST', body: JSON.stringify(js_org)}).then((res2) => res2.json()).then((res2) => { if (res2[1].success === true){ if (__DEV__ === true) console.log('login_dw org: ', res2); this.props.navigator.resetTo({ sceneIndex: 1, sessionId: res.auth.params.sessionId, portal: 'dw' }); } }).catch((err) => { if (__DEV__ === true) console.log('login_dw org err: ', err); }); } else{ Alert.alert('Erro desconhecido'); this.setState({loading: false, text:'', text2: ''}); } }).catch((err) => { if (__DEV__ === true) // if in development console.log('login_dw err: ', err); Alert.alert('Login falhou!', 'Verifique sua conexão com a internet'); this.setState({loading: false}); }); } }
docs/src/app/components/pages/components/Dialog/Page.js
tan-jerene/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 dialogReadmeText from './README'; import DialogExampleSimple from './ExampleSimple'; import dialogExampleSimpleCode from '!raw!./ExampleSimple'; import DialogExampleModal from './ExampleModal'; import dialogExampleModalCode from '!raw!./ExampleModal'; import DialogExampleCustomWidth from './ExampleCustomWidth'; import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth'; import DialogExampleDialogDatePicker from './ExampleDialogDatePicker'; import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker'; import DialogExampleScrollable from './ExampleScrollable'; import DialogExampleScrollableCode from '!raw!./ExampleScrollable'; import DialogExampleAlert from './ExampleAlert'; import DialogExampleAlertCode from '!raw!./ExampleAlert'; import dialogCode from '!raw!material-ui/Dialog/Dialog'; const DialogPage = () => ( <div> <Title render={(previousTitle) => `Dialog - ${previousTitle}`} /> <MarkdownElement text={dialogReadmeText} /> <CodeExample title="Simple dialog" code={dialogExampleSimpleCode} > <DialogExampleSimple /> </CodeExample> <CodeExample title="Modal dialog" code={dialogExampleModalCode} > <DialogExampleModal /> </CodeExample> <CodeExample title="Styled dialog" code={dialogExampleCustomWidthCode} > <DialogExampleCustomWidth /> </CodeExample> <CodeExample title="Nested dialogs" code={dialogExampleDialogDatePickerCode} > <DialogExampleDialogDatePicker /> </CodeExample> <CodeExample title="Scrollable dialog" code={DialogExampleScrollableCode} > <DialogExampleScrollable /> </CodeExample> <CodeExample title="Alert dialog" code={DialogExampleAlertCode} > <DialogExampleAlert /> </CodeExample> <PropTypeDescription code={dialogCode} /> </div> ); export default DialogPage;
packages/reactor-tests/src/tests/props/SimplePropUpdate.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Button } from '@extjs/ext-react'; export default class SimplePropUpdate extends Component { state = { count: 0 }; increment = () => this.setState({ count: this.state.count + 1 }); render() { return ( <Button itemId="button" text={`Count: ${this.state.count}`} handler={this.increment}/> ) } }
src/pages/index.js
BeardedYeti/react-blog
import React from 'react' import Link from 'gatsby-link' import Helmet from 'react-helmet' // import '../css/index.css'; export default function Index({ data }) { const { edges: posts } = data.allMarkdownRemark; return ( <div className="blog-posts"> {posts .filter(post => post.node.frontmatter.title.length > 0) .map(({ node: post }) => { return ( <div className="blog-post-preview" key={post.id}> <h1> <Link to={post.frontmatter.path}>{post.frontmatter.title}</Link> </h1> <h2>{post.frontmatter.date}</h2> <p>{post.excerpt}</p> </div> ); })} </div> ); } export const pageQuery = graphql` query IndexQuery { allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) { edges { node { excerpt(pruneLength: 250) id frontmatter { title date(formatString: "MMMM DD, YYYY") path } } } } } `;
customView/node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
TheKingOfNorway/React-Native
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
client/scripts/controllers/season2Ctrl.js
IHarryIJumper/trials-fusion-stats-cptsparkles
import React from 'react'; import { render } from 'react-dom'; import { SeasonTwoPageComponent } from '../components/seasonsPages/season2Component.jsx'; export const renderSeason2Page = render(<SeasonTwoPageComponent />, document.getElementById('season2-page-target'));
app/addons/replication/components/source.js
popojargo/couchdb-fauxton
// Licensed 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 PropTypes from 'prop-types'; import React from 'react'; import Constants from '../constants'; import Components from '../../components/react-components'; import ReactSelect from 'react-select'; import RemoteExample from './remoteexample'; const { StyledSelect } = Components; const RemoteSourceInput = ({onChange, value}) => <div className="replication__section"> <div className="replication__input-label">Database URL:</div> <div className=""> <input type="text" className="replication__remote-connection-url" placeholder="https://" value={value} onChange={(e) => onChange(e.target.value)} /> <RemoteExample /> </div> </div>; RemoteSourceInput.propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; const LocalSourceInput = ({value, onChange, databases}) => { const options = databases.map(db => ({value: db, label: db})); return ( <div className="replication__section"> <div className="replication__input-label"> Source Name: </div> <div className="replication__input-react-select"> <ReactSelect name="source-name" value={value} placeholder="Database name" options={options} clearable={false} onChange={({value}) => onChange(value)} /> </div> </div> ); }; LocalSourceInput.propTypes = { value: PropTypes.string.isRequired, databases: PropTypes.array.isRequired, onChange: PropTypes.func.isRequired }; const ReplicationSourceRow = ({replicationSource, databases, localSource, remoteSource, onChangeRemote, onChangeLocal}) => { if (replicationSource === Constants.REPLICATION_SOURCE.LOCAL) { return <LocalSourceInput value={localSource} databases={databases} onChange={onChangeLocal} />; } return <RemoteSourceInput value={remoteSource} onChange={onChangeRemote} />; }; ReplicationSourceRow.propTypes = { replicationSource: PropTypes.string.isRequired, databases: PropTypes.array.isRequired, localSource: PropTypes.string.isRequired, remoteSource: PropTypes.string.isRequired, onChangeRemote: PropTypes.func.isRequired, onChangeLocal: PropTypes.func.isRequired }; const replicationSourceSelectOptions = () => { return [ { value: '', label: 'Select source' }, { value: Constants.REPLICATION_SOURCE.LOCAL, label: 'Local database' }, { value: Constants.REPLICATION_SOURCE.REMOTE, label: 'Remote database' } ].map((option) => { return ( <option value={option.value} key={option.value}>{option.label}</option> ); }); }; export const ReplicationSourceSelect = ({onChange, value}) => { return ( <div className="replication__section"> <div className="replication__input-label"> Replication Source: </div> <div className="replication__input-select"> <StyledSelect selectContent={replicationSourceSelectOptions()} selectChange={(e) => onChange(e.target.value)} selectId="replication-source" selectValue={value} /> </div> </div> ); }; ReplicationSourceSelect.propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; export class ReplicationSource extends React.Component { getReplicationSourceRow () { const { replicationSource, localSource, onLocalSourceChange, onRemoteSourceChange, remoteSource, databases } = this.props; if (!replicationSource) { return null; } return <ReplicationSourceRow replicationSource={replicationSource} databases={databases} localSource={localSource} remoteSource={remoteSource} onChangeLocal={onLocalSourceChange} onChangeRemote={onRemoteSourceChange} />; } render () { const {replicationSource, onSourceSelect} = this.props; return ( <div> <ReplicationSourceSelect onChange={onSourceSelect} value={replicationSource} /> {this.getReplicationSourceRow()} </div> ); } } ReplicationSource.propTypes = { replicationSource: PropTypes.string.isRequired, localSource: PropTypes.string.isRequired, remoteSource: PropTypes.string.isRequired, databases: PropTypes.array.isRequired, onLocalSourceChange: PropTypes.func.isRequired, onRemoteSourceChange: PropTypes.func.isRequired };
src/parser/deathknight/blood/modules/talents/Bloodworms.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import { formatThousands } from 'common/format'; //Worms last 15 sec. But sometimes lag and such makes them expire a little bit early. const WORMLIFESPAN = 14900; class Bloodworms extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; totalSummons=0; totalHealing=0; totalDamage=0; poppedEarly=0; wormID=0; bloodworm = []; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.BLOODWORMS_TALENT.id); } poppedWorms(bloodworm) { return bloodworm.filter(e => e.killedTime - e.summonedTime <= WORMLIFESPAN).length; } on_byPlayer_summon(event) { if (event.ability.guid !== SPELLS.BLOODWORM.id) { return; } this.bloodworm.push({ uniqueID: event.targetInstance, summonedTime: event.timestamp, }); this.totalSummons+= 1; this.wormID = event.targetID; } on_byPlayerPet_damage(event) { if (event.sourceID !== this.wormID) { return; } this.totalDamage += event.amount + (event.absorbed || 0); } on_byPlayerPet_instakill(event) { if (event.ability.guid !== SPELLS.BLOODWORM_DEATH.id) { return; } let index = -1; this.bloodworm.forEach((e, i) => { if (e.uniqueID === event.targetInstance) { index = i; } }); if (index === -1) { return; } this.bloodworm[index].killedTime = event.timestamp; } on_toPlayer_heal(event) { if (event.ability.guid !== SPELLS.BLOODWORM_DEATH.id) { return; } this.totalHealing+= (event.amount || 0) + (event.absorbed || 0); } statistic() { return ( <TalentStatisticBox talent={SPELLS.BLOODWORMS_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(6)} value={this.owner.formatItemHealingDone(this.totalHealing)} label="Bloodworm Stats" tooltip={( <> <strong>Damage:</strong> {formatThousands(this.totalDamage)} / {this.owner.formatItemDamageDone(this.totalDamage)}<br /> <strong>Number of worms summoned:</strong> {this.totalSummons}<br /> <strong>Number of worms popped early:</strong> {this.poppedWorms(this.bloodworm)} </> )} /> ); } } export default Bloodworms;
packages/material-ui-icons/src/PermContactCalendar.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let PermContactCalendar = props => <SvgIcon {...props}> <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H6v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1z" /> </SvgIcon>; PermContactCalendar = pure(PermContactCalendar); PermContactCalendar.muiName = 'SvgIcon'; export default PermContactCalendar;
src/js/components/Split.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../utils/CSSClassnames'; import { smallSize } from '../utils/Responsive'; const CLASS_ROOT = CSSClassnames.SPLIT; export default class Split extends Component { constructor(props, context) { super(props, context); this._onResize = this._onResize.bind(this); this._layout = this._layout.bind(this); this.state = { responsive: undefined }; } componentDidMount () { window.addEventListener('resize', this._onResize); this._layout(); } componentWillReceiveProps (nextProps) { // If we change the number of visible children, trigger a resize event // so things like Table header can adjust. This will go away once // CSS supports per element media queries. // The 500ms delay is loosely tied to the CSS animation duration. // We want any animations to finish before triggering the resize. // TODO: consider using an animation end event instead of a timer. if (this._nonNullChildCount(nextProps) !== this._nonNullChildCount(this.props)) { clearTimeout(this._resizeTimer); this._resizeTimer = setTimeout(function () { var event = document.createEvent('HTMLEvents'); event.initEvent('resize', true, false); window.dispatchEvent(event); }, 500); } this.setState({ relayout: true }); } componentDidUpdate () { if (this.state.relayout) { this.setState({ relayout: false }); this._layout(); } } componentWillUnmount () { window.removeEventListener('resize', this._onResize); } // Support function for componentWillReceiveProps() _nonNullChildCount (props) { let result = 0; React.Children.forEach(props.children, function (child) { if (child) result += 1; }); return result; } _onResize () { // debounce clearTimeout(this._resizeTimer); this._resizeTimer = setTimeout(this._layout, 50); } _setResponsive (responsive) { if (this.state.responsive !== responsive) { this.setState({responsive: responsive}); if (this.props.onResponsive) { this.props.onResponsive(responsive); } } } _layout () { const splitElement = this.splitRef; if (splitElement) { if (splitElement.offsetWidth <= smallSize() && this.props.showOnResponsive === 'priority') { this._setResponsive('single'); } else { this._setResponsive('multiple'); } } } render () { const { children, className, fixed, flex, priority, separator, ...props } = this.props; delete props.onResponsive; delete props.showOnResponsive; const { responsive } = this.state; const classes = classnames( CLASS_ROOT, className ); const boxedChildren = !Array.isArray(children) ? children : children.map((child, index) => { if (!child) { // skip the empty children but keep original index // this avoid the right element to remount return undefined; } const lastChild = (index === children.length - 1); let hidden; let childFlex = true; // When we only have room to show one child, hide the appropriate one if ('single' === responsive && (('left' === priority && index > 0) || ('right' === priority && index === 0 && children.length > 1))) { hidden = true; } else if (children.length > 1 && ((flex === 'right' && index === 0) || (flex === 'left' && lastChild))) { childFlex = false; } else { childFlex = true; } const classes = classnames( `${CLASS_ROOT}__column`, { [`${CLASS_ROOT}__column--fixed`]: fixed, [`${CLASS_ROOT}__column--hidden`]: hidden, [`${CLASS_ROOT}__column--flex`]: childFlex, [`${CLASS_ROOT}__column--separator`]: (separator && ! lastChild) } ); // Don't use a Box here because we don't want to constrain the child // in a flexbox container. return ( <div key={index} className={classes}> {child} </div> ); }); return ( <div ref={ref => this.splitRef = ref} {...props} className={classes}> {boxedChildren} </div> ); } } Split.propTypes = { children: PropTypes.arrayOf(PropTypes.node).isRequired, fixed: PropTypes.bool, flex: PropTypes.oneOf(['left', 'right', 'both']), onResponsive: PropTypes.func, priority: PropTypes.oneOf(['left', 'right']), separator: PropTypes.bool, showOnResponsive: PropTypes.oneOf(['priority', 'both']) }; Split.defaultProps = { fixed: true, flex: 'both', priority: 'right', showOnResponsive: 'priority' };
components/Header/NavIcon.js
owennicol/yaiza
// React import React from 'react' import classNames from 'classnames' const NavIcon = (props) => { const menuClasses = classNames({ cross: true, open: props.menuIsOpen }) return ( <div className="toggle" id="navMenuToggleButton"> <a href="#" className={menuClasses}><span></span></a> </div> ); }; export default NavIcon;
src/svg-icons/action/restore.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRestore = (props) => ( <SvgIcon {...props}> <path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/> </SvgIcon> ); ActionRestore = pure(ActionRestore); ActionRestore.displayName = 'ActionRestore'; ActionRestore.muiName = 'SvgIcon'; export default ActionRestore;
src/App.js
karlpatrickespiritu/todo-react-flux
import React, { Component } from 'react'; // import logo from './logo.svg'; import './App.css'; import Todos from './components/Todos/Todos' import TodoForm from './components/Todos/TodoForm/TodoForm' class App extends Component { render() { return ( <div className="App"> <div className="row"> <div className="col-md-6 col-md-offset-3"> <TodoForm/> <hr/> <Todos/> </div> </div> </div> ); } } export default App;
src/Parser/Warrior/Fury/Modules/Features/RampageCancelled.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import { formatPercentage } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; const RAMPAGE_HITS_PER_CAST = 5; class RampageCancelled extends Analyzer { // Rampage is in fact 5 separate spells cast in this sequence rampage = [SPELLS.RAMPAGE_1.id, SPELLS.RAMPAGE_2.id, SPELLS.RAMPAGE_3.id, SPELLS.RAMPAGE_4.id, SPELLS.RAMPAGE_5.id] counter = {} on_initialized() { for (let i = 0; i < this.rampage.length; i++) { this.counter[this.rampage[i]] = 0; } } on_byPlayer_damage(event) { if (!this.rampage.includes(event.ability.guid)) { return; } this.counter[event.ability.guid]++; } get suggestionThresholdsFrothingBerserker() { return { isGreaterThan: { minor: 0, average: 0.02, major: 0.05, }, style: 'percentage', }; } suggestions(when) { const { isGreaterThan: { minor, average, major, }, } = this.suggestionThresholdsFrothingBerserker; const max = Object.values(this.counter).reduce((max, current) => current > max ? current : max, 0); const wasted = Object.keys(this.counter).reduce((acc, current) => acc + max - this.counter[current], 0); when(wasted / (max * RAMPAGE_HITS_PER_CAST)).isGreaterThan(minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your <SpellLink id={SPELLS.RAMPAGE.id} /> cast are being cancelled prematurely. Be sure to be facing the target within melee distance to avoid this.</Wrapper>) .icon(SPELLS.RAMPAGE.icon) .actual(`${formatPercentage(actual)}% (${wasted} out of ${max * RAMPAGE_HITS_PER_CAST}) of your Rampage hits were cancelled.`) .recommended(`0% is recommended`) .regular(average).major(major); }); } } export default RampageCancelled;
client/src/app/admin/panel/dashboard/admin-panel-my-account.js
ivandiazwm/opensupports
import React from 'react'; import {connect} from 'react-redux'; import _ from 'lodash'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import SessionActions from 'actions/session-actions'; import StaffEditor from 'app/admin/panel/staff/staff-editor'; import Header from 'core-components/header'; class AdminPanelMyAccount extends React.Component { render() { return ( <div className="admin-panel-view-staff"> <Header title={i18n('MY_ACCOUNT')} description={i18n('MY_ACCOUNT_DESCRIPTION')} /> <StaffEditor {...this.getEditorProps()}/> </div> ); } getEditorProps() { return { myAccount: true, staffId: this.props.userId * 1, name: this.props.userName, email: this.props.userEmail, profilePic: this.props.userProfilePic, level: this.props.userLevel * 1, departments: this.props.userDepartments, sendEmailOnNewTicket: this.props.userSendEmailOnNewTicket, onChange: () => this.props.dispatch(SessionActions.getUserData(null, null, true)) }; } } export default connect((store) => store.session)(AdminPanelMyAccount);
src/svg-icons/content/archive.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentArchive = (props) => ( <SvgIcon {...props}> <path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zM12 17.5L6.5 12H10v-2h4v2h3.5L12 17.5zM5.12 5l.81-1h12l.94 1H5.12z"/> </SvgIcon> ); ContentArchive = pure(ContentArchive); ContentArchive.displayName = 'ContentArchive'; ContentArchive.muiName = 'SvgIcon'; export default ContentArchive;
node_modules/native-base/src/basic/H2.js
odapplications/WebView-with-Lower-Tab-Menu
import React, { Component } from 'react'; import { Text } from 'react-native'; import { connectStyle } from '@shoutem/theme'; import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames'; class H2 extends Component { render() { return ( <Text ref={c => this._root = c} {...this.props} /> ); } } const childrenType = function (props, propName, component) { let error; const prop = props[propName]; React.Children.forEach(prop, (child) => { if (typeof child !== 'string') { error = new Error(`${component} should have only string`); } }); return error; }; H2.propTypes = { ...Text.propTypes, children: childrenType, style: React.PropTypes.object, }; const StyledH2 = connectStyle('NativeBase.H2', {}, mapPropsToStyleNames)(H2); export { StyledH2 as H2, };
components/SpaceTypeIcon/SpaceTypeIcon.story.js
NGMarmaduke/bloom
import React from 'react'; import { storiesOf } from '@storybook/react'; import SpaceTypeIcon from './SpaceTypeIcon'; import icons from './icons'; const story = storiesOf('SpaceTypeIcon', module); Object.keys(icons).forEach((icon) => { story.add(icon, () => ( <div> {icon}: <SpaceTypeIcon name={ icon } /> </div> )); });
app/containers/App.js
robogroves/bps
// @flow import React, { Component } from 'react'; export default class App extends Component { props: { children: HTMLElement }; render() { return ( <div> {this.props.children} </div> ); } }
src/entypo/Brush.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Brush'; let EntypoBrush = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M2.763,13.563c-1.515,1.488-0.235,3.016-2.247,5.279c-0.908,1.023,3.738,0.711,6.039-1.551c0.977-0.961,0.701-2.359-0.346-3.389C5.162,12.874,3.739,12.602,2.763,13.563z M19.539,0.659C18.763-0.105,10.16,6.788,7.6,9.305c-1.271,1.25-1.695,1.92-2.084,2.42c-0.17,0.219,0.055,0.285,0.154,0.336c0.504,0.258,0.856,0.496,1.311,0.943c0.456,0.447,0.699,0.793,0.959,1.289c0.053,0.098,0.121,0.318,0.342,0.152c0.51-0.383,1.191-0.801,2.462-2.049C13.305,9.88,20.317,1.422,19.539,0.659z"/> </EntypoIcon> ); export default EntypoBrush;
www/src/pages/components/modal.js
glenjamin/react-bootstrap
import { graphql } from 'gatsby'; import React from 'react'; import { css } from 'astroturf'; import ComponentApi from '../../components/ComponentApi'; import LinkedHeading from '../../components/LinkedHeading'; import ReactPlayground from '../../components/ReactPlayground'; import ModalStatic from '../../examples/Modal/Static'; import ModalBasic from '../../examples/Modal/Basic'; import ModalDefaultSizing from '../../examples/Modal/DefaultSizing'; import ModalCustomSizing from '../../examples/Modal/CustomSizing'; import ModalVerticallyCentered from '../../examples/Modal/VerticallyCentered'; import ModalGrid from '../../examples/Modal/Grid'; import withLayout from '../../withLayout'; const styles = css` /* has to be fully global because of modal portals */ :global(.modal-90w) { width: 90%; max-width: none !important; } `; export default withLayout(function ModalSection({ data }) { return ( <> <LinkedHeading h="1" id="modals"> Modals </LinkedHeading> <p className="lead"> Add dialogs to your site for lightboxes, user notifications, or completely custom content. </p> <LinkedHeading h="2" id="modals-overview"> Overview </LinkedHeading> <ul> <li> Modals are positioned over everything else in the document and remove scroll from the <code>{'<body>'}</code> so that modal content scrolls instead. </li> <li> Modals are <em>unmounted</em> when closed. </li> <li> Bootstrap only supports <strong>one</strong> modal window at a time. Nested modals aren’t supported, but if you really need them the underlying <code>react-overlays</code> can support them if you're willing. </li> <li> Modal's "trap" focus in them, ensuring the keyboard navigation cycles through the modal, and not the rest of the page. </li> <li> Unlike vanilla Bootstrap, <code>autoFocus</code> works in Modals because React handles the implementation. </li> </ul> <LinkedHeading h="2" id="modals-examples"> Examples </LinkedHeading> <LinkedHeading h="3" id="modals-static"> Static Markup </LinkedHeading> <p> Below is a <em>static</em> modal dialog (without the positioning) to demostrate the look and feel of the Modal. </p> <ReactPlayground codeText={ModalStatic} /> <LinkedHeading h="3" id="modals-live"> Live demo </LinkedHeading> <p> A modal with header, body, and set of actions in the footer. Use{' '} <code>{'<Modal/>'}</code> in combination with other components to show or hide your Modal. The <code>{'<Modal/>'}</code> Component comes with a few convenient "sub components": <code>{'<Modal.Header/>'}</code>,{' '} <code>{'<Modal.Title/>'}</code>, <code>{'<Modal.Body/>'}</code>, and{' '} <code>{'<Modal.Footer/>'}</code>, which you can use to build the Modal content. </p> <ReactPlayground codeText={ModalBasic} /> <div className="bs-callout bs-callout-info"> <div className="h4">Additional Import Options</div> <p> The Modal Header, Title, Body, and Footer components are available as static properties the <code>{'<Modal/>'}</code> component, but you can also, import them directly from the <code>/lib</code> directory like:{' '} <code>require("react-bootstrap/lib/ModalHeader")</code>. </p> </div> <LinkedHeading h="3" id="modal-vertically-centered"> Vertically centered </LinkedHeading> <p> You can vertically center a modal by passing the "verticallyCenter" prop. </p> <ReactPlayground codeText={ModalVerticallyCentered} /> <LinkedHeading h="3" id="modal-grid"> Using the grid </LinkedHeading> <p> You can use grid layouts within a model using regular grid components inside the modal content. </p> <ReactPlayground codeText={ModalGrid} /> <LinkedHeading h="2" id="modal-default-sizing"> Optional Sizes </LinkedHeading> <p> You can specify a bootstrap large or small modal by using the "size" prop. </p> <ReactPlayground codeText={ModalDefaultSizing} /> <LinkedHeading h="3" id="modal-custom-sizing"> Sizing modals using custom CSS </LinkedHeading> <p> You can apply custom css to the modal dialog div using the "dialogClassName" prop. Example is using a custom css class with width set to 90%. </p> <ReactPlayground codeText={ModalCustomSizing} exampleClassName={styles.custom} /> <LinkedHeading h="2" id="modals-props"> API </LinkedHeading> <ComponentApi metadata={data.Modal} /> <ComponentApi metadata={data.ModalDialog} /> <ComponentApi metadata={data.ModalHeader} /> <ComponentApi metadata={data.ModalTitle} /> <ComponentApi metadata={data.ModalBody} /> <ComponentApi metadata={data.ModalFooter} /> </> ); }); export const query = graphql` query ModalQuery { Modal: componentMetadata(displayName: { eq: "Modal" }) { ...ComponentApi_metadata } ModalDialog: componentMetadata(displayName: { eq: "ModalDialog" }) { ...ComponentApi_metadata } ModalHeader: componentMetadata(displayName: { eq: "ModalHeader" }) { ...ComponentApi_metadata } ModalTitle: componentMetadata(displayName: { eq: "ModalTitle" }) { ...ComponentApi_metadata } ModalBody: componentMetadata(displayName: { eq: "ModalBody" }) { ...ComponentApi_metadata } ModalFooter: componentMetadata(displayName: { eq: "ModalFooter" }) { ...ComponentApi_metadata } } `;
src/entypo/DotSingle.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--DotSingle'; let EntypoDotSingle = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M7.8,10c0,1.215,0.986,2.2,2.201,2.2S12.2,11.214,12.2,10c0-1.215-0.984-2.199-2.199-2.199S7.8,8.785,7.8,10z"/> </EntypoIcon> ); export default EntypoDotSingle;
genie-web/src/main/resources/static/scripts/components/Error.js
irontable/genie
import T from 'prop-types'; import React from 'react'; const Error = props => ( <div className="col-md-10 result-panel-msg"> <div><h4>{props.error.error}</h4></div> <code> <div>{props.error.status}</div> <div>{props.error.exception}</div> <div>{props.error.message}</div> </code> </div> ); Error.propTypes = { error: T.object }; export default Error;
src/packages/@ncigdc/components/Explore/SummaryPage/SummaryPage.relay.js
NCI-GDC/portal-ui
import React from 'react'; import { graphql } from 'react-relay'; import { BaseQuery } from '@ncigdc/modern_components/Query'; import { compose, setDisplayName } from 'recompose'; const EnhancedSummaryPageQuery = (Component) => compose( setDisplayName('SummaryPageQuery'), )( (props) => ( <BaseQuery Component={Component} parentProps={props} query={graphql` query SummaryPage_relayQuery($filters: FiltersArgument) { viewer { explore { cases { aggregations(filters: $filters){ summary__experimental_strategies__experimental_strategy{ buckets{ doc_count key } } diagnoses__age_at_diagnosis{ histogram { buckets { doc_count key } } } demographic__vital_status { buckets{ doc_count key } } demographic__race { buckets{ doc_count key } } demographic__gender { buckets{ doc_count key } } } } } repository { cases { aggregations(filters: $filters) { samples__sample_type { buckets { doc_count key } } } } } } } `} variables={{ filters: props.filters }} /> ) ); export default EnhancedSummaryPageQuery;
components/Exam/components/List/List.js
yabeow/sinhvienuit
import React from 'react'; import PropTypes from 'prop-types'; import { FlatList, RefreshControl } from 'react-native'; import { View } from 'native-base'; import Exam from './Item'; import EmptyList from '../../../EmptyList'; import { ANDROID_PULL_TO_REFRESH_COLOR } from '../../../../config/config'; const sortExams = (exams) => { // Sắp xếp theo thứ tự thời gian còn lại tăng dần. const currentTime = new Date().getTime(); return exams.sort((a, b) => { let timeA = a.getTime().getTime(); let timeB = b.getTime().getTime(); if (timeA > currentTime) timeA -= 9999999999999; if (timeB > currentTime) timeB -= 9999999999999; if (timeA < timeB) return -1; if (timeA > timeB) return 1; return 0; }); }; class List extends React.Component { constructor(props) { super(props); const { exams } = this.props; this.state = { exams: sortExams(exams), }; } componentWillReceiveProps(nextProps) { const { exams } = nextProps; if (exams !== this.props.exams) { this.setState({ exams: sortExams(exams) }); } } render() { if ( typeof this.props.onRefresh !== 'undefined' && typeof this.props.refreshing !== 'undefined' ) { return ( <FlatList ListEmptyComponent={<EmptyList />} data={this.state.exams} horizontal={false} keyExtractor={item => item.getCode() + item.getTime()} renderItem={({ item }) => <Exam exam={item} />} refreshControl={ <RefreshControl refreshing={this.props.refreshing} onRefresh={() => this.props.onRefresh()} colors={ANDROID_PULL_TO_REFRESH_COLOR} /> } /> ); } return ( <View> {this.state.exams.map(item => <Exam exam={item} key={item.getCode() + item.getTime()} />)} </View> ); } } List.defaultProps = { refreshing: false, onRefresh: () => {}, }; List.propTypes = { exams: PropTypes.array.isRequired, refreshing: PropTypes.bool, onRefresh: PropTypes.func, }; export default List;
src/example/plot/custom-axis.js
jameskraus/react-vis
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import { XYPlot, XAxis, VerticalGridLines, HorizontalGridLines, LineSeries} from '../../'; export default class Example extends React.Component { render() { return ( <XYPlot width={300} height={300}> <VerticalGridLines /> <HorizontalGridLines /> <XAxis title="X" labelFormat={v => `Value is ${v}`} labelValues={[2]} tickValues={[1, 1.5, 2, 3]}/> <LineSeries data={[ {x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 15} ]}/> </XYPlot> ); } }
fields/types/email/EmailColumn.js
Tangcuyu/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; var EmailColumn = React.createClass({ displayName: 'EmailColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value) return; return ( <ItemsTableValue href={'mailto:' + value} padded exterior field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { const value = this.props.data.fields[this.props.col.path]; return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = EmailColumn;
src/svg-icons/content/flag.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFlag = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ContentFlag = pure(ContentFlag); ContentFlag.displayName = 'ContentFlag'; ContentFlag.muiName = 'SvgIcon'; export default ContentFlag;
client/src/app-components/password-recovery.js
opensupports/opensupports
import React from 'react'; import classNames from 'classnames'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import Form from 'core-components/form'; import FormField from 'core-components/form-field'; import Widget from 'core-components/widget'; import Button from 'core-components/button'; import SubmitButton from 'core-components/submit-button'; import Message from 'core-components/message'; class PasswordRecovery extends React.Component { static propTypes = { recoverSent: React.PropTypes.bool, formProps: React.PropTypes.object, onBackToLoginClick: React.PropTypes.func, renderLogo: React.PropTypes.bool }; static defaultProps = { renderLogo: false }; state = { showRecoverSentMessage: true } componentDidUpdate(prevProps) { if (!prevProps.recoverSent && this.props.recoverSent) { this.setState({showRecoverSentMessage : true}); } } render() { const { renderLogo, formProps, onBackToLoginClick, style } = this.props; return ( <Widget style={style} className={this.getClass()} title={!renderLogo ? i18n('RECOVER_PASSWORD') : ''}> {this.renderLogo()} <Form {...formProps}> <div className="password-recovery__inputs"> <FormField ref="email" placeholder={i18n('EMAIL_LOWERCASE')} name="email" className="password-recovery__input" validation="EMAIL" required/> </div> <div className="password-recovery__submit-button"> <SubmitButton type="primary">{i18n('RECOVER_PASSWORD')}</SubmitButton> </div> </Form> <Button className="password-recovery__forgot-password" type="link" onClick={onBackToLoginClick} onMouseDown={(event) => {event.preventDefault()}}> {i18n('BACK_LOGIN_FORM')} </Button> {this.renderRecoverStatus()} </Widget> ); } getClass() { return classNames({ 'password-recovery__content': true, [this.props.className]: (this.props.className) }); } renderLogo() { let logo = null; if (this.props.renderLogo) { logo = (<div className="password-recovery__image"><img width="100%" src={API.getURL() + '/images/logo.png'} alt="OpenSupports Login Panel"/></div>); } return logo; } renderRecoverStatus() { return ( this.props.recoverSent ? <Message showMessage={this.state.showRecoverSentMessage} onCloseMessage={this.onCloseMessage.bind(this, "showRecoverSentMessage")} className="password-recovery__message" type="info" leftAligned> {i18n('RECOVER_SENT')} </Message> : null ); } focusEmail() { this.refs.email.focus(); } onCloseMessage(showMessage) { this.setState({ [showMessage]: false }); } } export default PasswordRecovery;
docs-ui/components/qrcode.stories.js
ifduyue/sentry
import React from 'react'; import {storiesOf} from '@storybook/react'; import {withInfo} from '@storybook/addon-info'; // import {action} from '@storybook/addon-actions'; import Qrcode from 'app/components/qrcode'; storiesOf('Qrcode', module).add( 'default', withInfo('Description')(() => ( <Qrcode code={[ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]} /> )) );
docs/src/examples/jalaali.js
mberneti/react-datepicker2
import React from 'react' import momentJalaali from 'moment-jalaali' import DatePicker from '../../../src/components/DatePicker'; class component extends React.Component { constructor(props) { super(props); this.state = { value: momentJalaali('1396/7/6', 'jYYYY/jM/jD') }; } render() { return <DatePicker tetherAttachment="bottom center" isGregorian={false} value={this.state.value} onChange={value => this.setState({ value })} /> } } const title = 'Jalaali'; const code = `class component extends React.Component{ constructor(props) { super(props); this.state = { value: momentJalaali('1396/7/6', 'jYYYY/jM/jD') }; } render() { return <DatePicker isGregorian={false} value={this.state.value} onChange={value => this.setState({ value })} /> } } `; const Jalaali = { component, title, code }; export default Jalaali;
Console/app/node_modules/rc-select/es/OptGroup.js
RisenEsports/RisenEsports.github.io
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; var OptGroup = function (_React$Component) { _inherits(OptGroup, _React$Component); function OptGroup() { _classCallCheck(this, OptGroup); return _possibleConstructorReturn(this, (OptGroup.__proto__ || Object.getPrototypeOf(OptGroup)).apply(this, arguments)); } return OptGroup; }(React.Component); OptGroup.isSelectOptGroup = true; export default OptGroup;
node_modules/react-bootstrap/es/ModalTitle.js
WatkinsSoftwareDevelopment/HowardsBarberShop
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'h4' }; var ModalTitle = function (_React$Component) { _inherits(ModalTitle, _React$Component); function ModalTitle() { _classCallCheck(this, ModalTitle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalTitle.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalTitle; }(React.Component); ModalTitle.propTypes = propTypes; ModalTitle.defaultProps = defaultProps; export default bsClass('modal-title', ModalTitle);
src/components/Previewer/index.js
dachi023/snippets
import React from 'react' import {Divider} from 'material-ui' import marked from 'marked' class MarkdownPreview extends React.Component { constructor(props) { super(props) marked.setOptions({ gfm: true, tables: true, breaks: true, sanitize: true }) } getStyles() { return { divider: { marginTop: '8px', marginBottom: '8px' } } } renderMarkdown(value) { if (value == null || value.trim().length < 1) { return ( <h3>Nothing to preview</h3> ) } const markdown = marked(value) return ( <div> <span dangerouslySetInnerHTML={{__html: markdown}}></span> </div> ) } render() { const styles = this.getStyles() return ( <div> <h1>{this.props.title}</h1> <Divider style={styles.divider} /> {this.renderMarkdown(this.props.content)} </div> ) } } export default MarkdownPreview
src/components/TodoForm.js
woowoo/react-todo
import React from 'react'; import uuid from 'node-uuid'; export default class TodoForm extends React.Component { render() { return ( <form onSubmit={this.onSubmit.bind(this)}> <input ref="text" type="text" placeholder="What u wanna todo?" /> </form> ); } onSubmit(e) { e.preventDefault(); const newTodo = { id: uuid.v4(), text: this.refs.text.value, done: false }; console.log(this.props.onAdd); this.refs.text.value = ''; this.props.onAdd(newTodo); } }
internals/templates/containers/NotFoundPage/index.js
mikejong0815/Temp
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
public/js/components/trends/TrendContainer.react.js
rajikaimal/Coupley
import React from 'react'; import List from 'material-ui/lib/lists/list'; import Divider from 'material-ui/lib/divider'; import TextField from 'material-ui/lib/text-field'; import TrendsStore from '../../stores/TrendsStore'; import TrendsAction from '../../actions/TrendsAction'; import Trend from './trendbox.react'; import TrendPost from './trendactivityListComp.react'; var SearchCeck = true; var listClick = true; const style1={ width:200, height:300, }; const searchconvo = { marginTop:'-18', paddingLeft:10, paddingRight:50, width:150, }; function validateStatusText(textStatus) { if (textStatus.length > 250) { return { error: '*search is too long', }; } else if (textStatus.length == 0) { console.log('empty'); return { error: '*search cannot be empty', }; } else { return true; } }; const TrendContainer = React.createClass({ getInitialState: function() { return { trendsResult:TrendsStore.gettrendslist(), statusText: '', value:'', trendsPostResult:TrendsStore.getFirstTrendsSearchPost(), } }, componentDidMount: function() { TrendsStore.addChangeListener(this._onChange); TrendsAction.getTrendsList(); TrendsAction.getTrendsInitialSearchPosts(); }, _onChange: function () { if (SearchCeck) { this.setState({trendsResult:TrendsStore.gettrendslist()}); } else if (!SearchCeck) { this.setState({ trendsResult:TrendsStore.getTrendsSearchList()}); } this.setState({ trendsPostResult:TrendsStore. getFirstTrendsSearchPost()}); }, trendItem: function () { return this.state.trendsResult.map((result) => { return (<Trend abc={this.getHashtag} trends={result.trend} tid={result.id}/>); }); }, SearchTren:function () { var trd=this.refs.SearchT.getValue(); let ThisTrend ={ trend:trd, } console.log(ThisTrend.trend); if (validateStatusText(ThisTrend).error) { console.log('menna error'); this.setState({ statusText: validateStatusText(ThisTrend).error, }); val = false; } else { console.log('error na'); TrendsAction.getTrendsSearchList(ThisTrend); SearchCeck = false; this.setState({ statusText: '', }); } {this.trendSearchItem();} {this.clearText();} }, getHashtag:function (e) { console.log('clicked'); var E= e.substr(1); let trend={ strend:E, }; console.log(E); TrendsAction.getTrendsSearchPosts(trend); }, trendSearchItem: function () { this.setState({ trendsResult:TrendsStore.getTrendsSearchList()}); console.log('menna result'); console.log(this.state.trendsResult); return this.state.trendsResult.map((result) => { return (<Trend trends={result.trend} tid={result.id}/>); }); }, trendPostItem: function () { return this.state.trendsPostResult.map((result) => { return (<TrendPost firstName={result.firstname} postText={result.post_text} created_at={result.created_at}/>); }); }, clearText:function () { document.getElementById('SearchField').value = ''; }, EnterKey(e) { if (e.key === 'Enter') { console.log('enter una'); {this.SearchTren();} } }, render:function(){ return( <div> <div style={style1} className="col-xs-4"> <List zDepth={1}> <div><h4>Trends</h4></div> <Divider/> <div> <TextField hintText="#Trends" floatingLabelText="Search Trends" style={searchconvo} errorText={this.state.statusText} onKeyPress={this.EnterKey} ref="SearchT" id="SearchField"/> </div> <Divider/> {this.trendItem()} </List> </div> <div className="col-xs-8"> {this.trendPostItem()} </div> </div> ); } }); export default TrendContainer;
src/svg-icons/image/crop-din.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropDin = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/> </SvgIcon> ); ImageCropDin = pure(ImageCropDin); ImageCropDin.displayName = 'ImageCropDin'; ImageCropDin.muiName = 'SvgIcon'; export default ImageCropDin;
docs/src/SupportPage.js
roadmanfong/react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; export default class Page extends React.Component { render() { return ( <div> <NavMain activePage="support" /> <PageHeader title="Need help?" subTitle="Community resources for answering your React-Bootstrap questions." /> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead">Stay up to date on the development of React-Bootstrap and reach out to the community with these helpful resources.</p> <h3>Stack Overflow</h3> <p><a href="http://stackoverflow.com/questions/ask">Ask questions</a> about specific problems you have faced, including details about what exactly you are trying to do. Make sure you tag your question with <code className="js">react-bootstrap</code>. You can also read through <a href="http://stackoverflow.com/questions/tagged/react-bootstrap">existing React-Bootstrap questions</a>.</p> <h3>Live help</h3> <p>Bring your questions and pair with other react-bootstrap users in a <a href="http://start.thinkful.com/react/?utm_source=github&utm_medium=badge&utm_campaign=react-bootstrap">live Thinkful hangout</a>. Hear about the challenges other developers are running into, or screenshare your own code with the group for feedback.</p> <h3>Chat rooms</h3> <p>Discuss questions in the <code className="js">#react-bootstrap</code> channel on the <a href="http://www.reactiflux.com/">Reactiflux Slack</a> or on <a href="https://gitter.im/react-bootstrap/react-bootstrap">Gitter</a>.</p> <h3>GitHub issues</h3> <p>The issue tracker is the preferred channel for bug reports, features requests and submitting pull requests. See more about how we use issues in the <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md#issues">contribution guidelines</a>.</p> </div> </div> </div> </div> <PageFooter /> </div> ); } shouldComponentUpdate() { return false; } }
src/App.js
shcallaway/react-snake
import React, { Component } from 'react'; // import logo from './logo.svg'; import './App.css'; import Game from './game.js'; import { Header } from './interface.js'; class App extends Component { render() { return ( <div> <Header /> <Game /> </div> ); } } export default App;
assets/jqwidgets/jqwidgets-react/react_jqxtree.js
juannelisalde/holter
/* jQWidgets v4.5.4 (2017-June) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export default class JqxTree extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['animationShowDuration','animationHideDuration','allowDrag','allowDrop','checkboxes','dragStart','dragEnd','disabled','easing','enableHover','height','hasThreeStates','incrementalSearch','keyboardNavigation','rtl','selectedItem','source','toggleIndicatorSize','toggleMode','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxTree(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxTree('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxTree(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; animationShowDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('animationShowDuration', arg) } else { return JQXLite(this.componentSelector).jqxTree('animationShowDuration'); } }; animationHideDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('animationHideDuration', arg) } else { return JQXLite(this.componentSelector).jqxTree('animationHideDuration'); } }; allowDrag(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('allowDrag', arg) } else { return JQXLite(this.componentSelector).jqxTree('allowDrag'); } }; allowDrop(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('allowDrop', arg) } else { return JQXLite(this.componentSelector).jqxTree('allowDrop'); } }; checkboxes(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('checkboxes', arg) } else { return JQXLite(this.componentSelector).jqxTree('checkboxes'); } }; dragStart(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('dragStart', arg) } else { return JQXLite(this.componentSelector).jqxTree('dragStart'); } }; dragEnd(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('dragEnd', arg) } else { return JQXLite(this.componentSelector).jqxTree('dragEnd'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('disabled', arg) } else { return JQXLite(this.componentSelector).jqxTree('disabled'); } }; easing(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('easing', arg) } else { return JQXLite(this.componentSelector).jqxTree('easing'); } }; enableHover(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('enableHover', arg) } else { return JQXLite(this.componentSelector).jqxTree('enableHover'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('height', arg) } else { return JQXLite(this.componentSelector).jqxTree('height'); } }; hasThreeStates(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('hasThreeStates', arg) } else { return JQXLite(this.componentSelector).jqxTree('hasThreeStates'); } }; incrementalSearch(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('incrementalSearch', arg) } else { return JQXLite(this.componentSelector).jqxTree('incrementalSearch'); } }; keyboardNavigation(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('keyboardNavigation', arg) } else { return JQXLite(this.componentSelector).jqxTree('keyboardNavigation'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('rtl', arg) } else { return JQXLite(this.componentSelector).jqxTree('rtl'); } }; selectedItem(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('selectedItem', arg) } else { return JQXLite(this.componentSelector).jqxTree('selectedItem'); } }; source(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('source', arg) } else { return JQXLite(this.componentSelector).jqxTree('source'); } }; toggleIndicatorSize(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('toggleIndicatorSize', arg) } else { return JQXLite(this.componentSelector).jqxTree('toggleIndicatorSize'); } }; toggleMode(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('toggleMode', arg) } else { return JQXLite(this.componentSelector).jqxTree('toggleMode'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('theme', arg) } else { return JQXLite(this.componentSelector).jqxTree('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxTree('width', arg) } else { return JQXLite(this.componentSelector).jqxTree('width'); } }; addBefore(item, id) { JQXLite(this.componentSelector).jqxTree('addBefore', item, id); }; addAfter(item, id) { JQXLite(this.componentSelector).jqxTree('addAfter', item, id); }; addTo(item, id) { JQXLite(this.componentSelector).jqxTree('addTo', item, id); }; clear() { JQXLite(this.componentSelector).jqxTree('clear'); }; checkAll() { JQXLite(this.componentSelector).jqxTree('checkAll'); }; checkItem(item, checked) { JQXLite(this.componentSelector).jqxTree('checkItem', item, checked); }; collapseAll() { JQXLite(this.componentSelector).jqxTree('collapseAll'); }; collapseItem(item) { JQXLite(this.componentSelector).jqxTree('collapseItem', item); }; destroy() { JQXLite(this.componentSelector).jqxTree('destroy'); }; disableItem(item) { JQXLite(this.componentSelector).jqxTree('disableItem', item); }; ensureVisible(item) { JQXLite(this.componentSelector).jqxTree('ensureVisible', item); }; enableItem(item) { JQXLite(this.componentSelector).jqxTree('enableItem', item); }; enableAll() { JQXLite(this.componentSelector).jqxTree('enableAll'); }; expandAll() { JQXLite(this.componentSelector).jqxTree('expandAll'); }; expandItem(item) { JQXLite(this.componentSelector).jqxTree('expandItem', item); }; focus() { JQXLite(this.componentSelector).jqxTree('focus'); }; getCheckedItems() { return JQXLite(this.componentSelector).jqxTree('getCheckedItems'); }; getUncheckedItems() { return JQXLite(this.componentSelector).jqxTree('getUncheckedItems'); }; getItems() { return JQXLite(this.componentSelector).jqxTree('getItems'); }; getItem(element) { return JQXLite(this.componentSelector).jqxTree('getItem', element); }; getSelectedItem() { return JQXLite(this.componentSelector).jqxTree('getSelectedItem'); }; getPrevItem() { return JQXLite(this.componentSelector).jqxTree('getPrevItem'); }; getNextItem() { return JQXLite(this.componentSelector).jqxTree('getNextItem'); }; hitTest(left, top) { return JQXLite(this.componentSelector).jqxTree('hitTest', left, top); }; removeItem(item) { JQXLite(this.componentSelector).jqxTree('removeItem', item); }; performRender() { JQXLite(this.componentSelector).jqxTree('render'); }; refresh() { JQXLite(this.componentSelector).jqxTree('refresh'); }; selectItem(item) { JQXLite(this.componentSelector).jqxTree('selectItem', item); }; uncheckAll() { JQXLite(this.componentSelector).jqxTree('uncheckAll'); }; uncheckItem(item) { JQXLite(this.componentSelector).jqxTree('uncheckItem', item); }; updateItem(item, newItem) { JQXLite(this.componentSelector).jqxTree('updateItem', item, newItem); }; val(value) { if (value !== undefined) { JQXLite(this.componentSelector).jqxTree('val', value) } else { return JQXLite(this.componentSelector).jqxTree('val'); } }; render() { let id = 'jqxTree' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
app/components/Tabs/Timeline/index.js
theterra/newsb
import React from 'react'; import moment from 'moment'; import './timeline.css'; export default class Timeline extends React.Component { //eslint-disable-line constructor(props) { super(props); this.formatTime = this.formatTime.bind(this); this.formatDate = this.formatDate.bind(this); } formatTime(time) { return moment(time).locale('en').format('HH:mm'); } formatDate(date) { return moment(date).locale('en').format('YYYY/MM/DD'); } render() { const timeline = this.props.timeLine && this.props.timeLine.map((time, i) => (<div key={i} className="ink-flex"> <div className="timeline-date"> <div className="ink-flex vertical"> <div>{this.formatTime(time[1])}</div> <div>{this.formatDate(time[1])}</div> </div> </div> <div className="timeline-bar"> <div className={(i == this.props.timeLine.length - 1) ? 'pipe' : 'pipe bar'}></div> </div> <div className="timeline-info"> <div className="dot"></div> <div className="ink-flex vertical"> <div>{time[0]}</div> {/*<div className="timeline-box">Madhapur malakpet narcos street kondapur 50004</div>*/} </div> </div> </div>) ); return ( <section className="timeline" style={{ fontSize: '0.8em' }}> <div className="timeline-list" style={{ padding: '0 1.5em' }}> {/*<div className="ink-flex">*/} {/*<div className="timeline-date">*/} {/*<div className="ink-flex vertical">*/} {/*<div>12:30</div>*/} {/*<div>12/06/2016</div>*/} {/*</div>*/} {/*</div>*/} {/*<div className="timeline-bar">*/} {/*<div className="pipe bar"></div>*/} {/*</div>*/} {/*<div className="timeline-info">*/} {/*<div className="dot"></div>*/} {/*<div className="ink-flex">*/} {/*<div>Started</div>*/} {/*</div>*/} {/*</div>*/} {/*</div>*/} {/*<div className="ink-flex">*/} {/*<div className="timeline-date">*/} {/*<div className="ink-flex vertical">*/} {/*<div>12:30</div>*/} {/*<div>12/06/2016</div>*/} {/*</div>*/} {/*</div>*/} {/*<div className="timeline-bar">*/} {/*<div className="pipe bar"></div>*/} {/*</div>*/} {/*<div className="timeline-info">*/} {/*<div className="dot"></div>*/} {/*<div className="ink-flex vertical">*/} {/*<div>Picked Up</div>*/} {/*<div className="timeline-sub">Travelled so far 2km</div>*/} {/*<div className="timeline-box">Madhapur malakpet narcos street kondapur 50004</div>*/} {/*</div>*/} {/*</div>*/} {/*</div>*/} {/*<div className="ink-flex">*/} {/*<div className="timeline-date">*/} {/*<div className="ink-flex vertical">*/} {/*<div>12:30</div>*/} {/*<div>12/06/2016</div>*/} {/*</div>*/} {/*</div>*/} {/*<div className="timeline-bar">*/} {/*<div className="pipe"></div>*/} {/*</div>*/} {/*<div className="timeline-info">*/} {/*<div className="dot"></div>*/} {/*<div className="ink-flex vertical">*/} {/*<div>Delivered</div>*/} {/*<div className="timeline-sub">Travelled so far 2km</div>*/} {/*<div className="timeline-box">Madhapur malakpet narcos street kondapur 50004</div>*/} {/*</div>*/} {/*</div>*/} {/*</div>*/} {timeline} </div> </section> ); } }
src/components/video_list_item.js
dpano/redux-d
import React from 'react'; const VideoListItem = ({video, onVideoSelect}) =>{ const imageUrl = video.snippet.thumbnails.default.url; return ( <li className='list-group-item' onClick={()=>onVideoSelect(video)}> <div className='video-list media'> <div className='media-left'> <img className='media-object' src={imageUrl} /> </div> <div className='media-body'> <div className='media-heading'>{video.snippet.title}</div> </div> </div> </li> ) }; export default VideoListItem;
src/components/pages/Admin/Contents/TypeForms/AdminContentsArticle.js
ESTEBANMURUZABAL/my-ecommerce-template
/** * Imports */ import React from 'react'; import {FormattedMessage} from 'react-intl'; // Flux import IntlStore from '../../../../../stores/Application/IntlStore'; // Required components import FormLabel from '../../../../common/forms/FormLabel'; import InputField from '../../../../common/forms/InputField'; import MarkdownHTML from '../../../../common/typography/MarkdownHTML'; import MarkdownEditor from '../../../../common/forms/MarkdownEditor'; // Translation data for this component import intlData from './AdminContentsArticle.intl'; /** * Component */ class AdminContentsArticle extends React.Component { static contextTypes = { getStore: React.PropTypes.func.isRequired }; //*** Initial State ***// state = { fieldErrors: {} }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./AdminContentsArticle.scss'); } //*** View Controllers ***// handleLocaleFieldField = (field, locale, value) => { let body = this.props.body; body[field][locale] = value; this.props.onChange(body); }; //*** Template ***// render() { let intlStore = this.context.getStore(IntlStore); return ( <div className="admin-contents-article"> <div className="admin-contents-article__summary"> <div className="admin-contents-article__form-item"> <InputField label={ <div> <FormattedMessage message={intlStore.getMessage(intlData, 'summary')} locales={intlStore.getCurrentLocale()} /> &nbsp;({this.props.selectedLocale}) </div> } onChange={this.handleLocaleFieldField.bind(null, 'summary', this.props.selectedLocale)} value={this.props.body.summary[this.props.selectedLocale]} error={this.state.fieldErrors[`summary.${this.props.selectedLocale}`]} /> </div> </div> <div className="admin-contents-article__content"> <div className="admin-contents-article__markdown"> <MarkdownEditor key={this.props.selectedLocale} label={ <div> <FormattedMessage message={intlStore.getMessage(intlData, 'edit')} locales={intlStore.getCurrentLocale()} /> &nbsp;({this.props.selectedLocale}) </div> } value={this.props.body.markdown[this.props.selectedLocale]} onChange={this.handleLocaleFieldField.bind(null, 'markdown', this.props.selectedLocale)} /> </div> <div className="admin-contents-article__preview"> <div className="admin-contents-article__label"> <FormLabel> <FormattedMessage message={intlStore.getMessage(intlData, 'preview')} locales={intlStore.getCurrentLocale()} /> &nbsp;({this.props.selectedLocale}) </FormLabel> </div> <div className="admin-contents-article__markdown-preview"> <MarkdownHTML> {this.props.body.markdown[this.props.selectedLocale]} </MarkdownHTML> </div> </div> </div> </div> ); } } /** * Exports */ export default AdminContentsArticle;
app/layouts/authenticated.js
meddle0x53/react-koa-gulp-postgres-passport-example
import React, { Component } from 'react'; import { Link, RouteHandler } from 'react-router'; import { Jumbotron, Nav, Row, Col } from 'react-bootstrap'; import { NavItemLink } from 'react-router-bootstrap'; import AuthStore from '../stores/auth'; import SignIn from '../pages/signin'; export default class MainLayout extends Component { static displayName = 'MainLayout'; constructor() { super(); } static willTransitionTo(transition) { if (!AuthStore.isLoggedIn()) { SignIn.attemptedTransition = transition; transition.redirect('sign-in'); } } render() { return ( <div> <div className="container"> <Row> <Col md={2}> <h3>Links</h3> <Nav bsStyle="pills" stacked> <NavItemLink to="index">Index</NavItemLink> <NavItemLink to="null-page">Null</NavItemLink> </Nav> </Col> <Col md={10} className="well"> <RouteHandler /> </Col> </Row> </div> </div> ); } }
src/routes.js
TobiasBales/PlayuavOSDConfigurator
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import Config from './config/Config'; import Pixler from './pixler/Pixler'; export default ( <Route path="/" component={App}> <IndexRoute component={Config} /> <Route path="pixler" component={Pixler} /> </Route> );
src/containers/Header.js
eveafeline/D3-ID3-Naomi
import React, { Component } from 'react'; import { render } from 'react-dom'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getScatterPlot } from '../actions/ScatterPlotActions'; import { getD3ParserObj } from '../actions/D3ParserActions'; import { ScatterPlotReducer, D3ParserReducer } from '../reducers/index'; import HeaderToolbar from '../components/header/HeaderToolbar'; import {app, BrowserWindow} from 'electron'; class Header extends Component { // event handler for toggling the dropdown menu toggleDropDown(event) { document.getElementById("template-menu").classList.toggle("show"); } // testfunc(){ // console.log('---------checking if we can call two functions onclick') // } render() { return ( <header className="toolbar toolbar-header main"> <HeaderToolbar getD3ParserObj={this.props.getD3ParserObj} getScatterPlotAction={this.props.getScatterPlot} toggleDropDown={this.toggleDropDown} /> </header> ); } } function mapStateToProps({ ScatterPlotReducer, D3ParserReducer }) { return { ScatterPlotReducer, D3ParserReducer } } function mapDispatchToProps(dispatch) { return bindActionCreators({ getScatterPlot, getD3ParserObj }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Header); // componentDidMount() { // const dropDownMenu = document.getElementById('templates'); // const templateMenu = document.getElementById('template-menu'); // const scatterPlotTemp = document.getElementById('scatter-plot'); // // dropDownMenu.addEventListener('click', (event) => { // templateMenu.classList.toggle("show"); // }); // // scatterPlotTemp.addEventListener('click', (event) => { // // console.log(event); // this.props.getScatterPlot(); // }) // // window.onclick = function(event) { // if (!event.target.matches('.btn-dropdown')) { // // let dropdowns = document.getElementsByClassName("dropdown-menu"); // // for (let i = 0; i < dropdowns.length; i += 1) { // let openDropdown = dropdowns[i]; // if (openDropdown.classList.contains('show')) { // openDropdown.classList.remove('show'); // } // } // } // } // }
src/index.js
Oliboy50/oliver-thebault-front
/* eslint-disable import/default */ // React import React from 'react'; import {render} from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Router import { Router, browserHistory } from 'react-router'; import routes from './routes'; // Redux //import { Provider } from 'react-redux'; //import configureStore from './store/configureStore'; // Styles import '../node_modules/normalize.css/normalize.css'; import '../node_modules/font-awesome/css/font-awesome.min.css'; import './styles/styles.scss'; // Add tap events handling (for mobile devices) injectTapEventPlugin(); // react-dom root rendering render(( //<Provider store={configureStore()}> <Router history={browserHistory} routes={routes} /> //</Provider> ), document.getElementById('app'));
lib/main.js
jdknezek/mq-set-calc
import bootstrap from 'bootstrap'; import _ from 'lodash'; import React from 'react'; import App from './App.jsx!'; import sets from './sets'; React.render(React.createElement(App, {sets: sets}), document.getElementById('app'));
client/extensions/woocommerce/woocommerce-services/views/packages/packages-list-item.js
Automattic/woocommerce-services
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { localize } from 'i18n-calypso'; import { trim } from 'lodash'; import Gridicon from 'gridicons'; import classNames from 'classnames'; const PackagesListItem = ( { isPlaceholder, data, dimensionUnit, prefixActions, hasError, children, translate, } ) => { if ( isPlaceholder ) { return ( <div className="packages__packages-row placeholder"> <div className="packages__packages-row-icon"> <Gridicon icon="product" size={ 18 } /> </div> <div className="packages__packages-row-details"> <div className="packages__packages-row-details-name"> <span /> </div> </div> <div className="packages__packages-row-dimensions"> <span /> </div> <div className="packages__packages-row-actions">{ children }</div> </div> ); } const renderIcon = isLetter => { const icon = isLetter ? 'mail' : 'product'; return <Gridicon icon={ icon } size={ 18 } />; }; const renderName = name => { return name && '' !== trim( name ) ? name : translate( 'Untitled' ); }; const renderActions = () => <div className="packages__packages-row-actions">{ children }</div>; return ( <div className={ classNames( 'packages__packages-row', { prefixed: prefixActions } ) }> { prefixActions ? renderActions() : null } <div className="packages__packages-row-icon">{ renderIcon( data.is_letter, hasError ) }</div> <div className="packages__packages-row-details"> <div className="packages__packages-row-details-name"> { renderName( data.name, translate ) } </div> </div> <div className="packages__packages-row-dimensions"> { data.inner_dimensions } { dimensionUnit } </div> { prefixActions ? null : renderActions() } </div> ); }; PackagesListItem.propTypes = { siteId: PropTypes.number.isRequired, isPlaceholder: PropTypes.bool, data: PropTypes.shape( { name: PropTypes.string, is_letter: PropTypes.bool, inner_dimensions: PropTypes.string, } ).isRequired, prefixActions: PropTypes.bool, dimensionUnit: PropTypes.string, }; export default localize( PackagesListItem );
docs/app/Examples/elements/Header/Content/HeaderExampleImage.js
ben174/Semantic-UI-React
import React from 'react' import { Header, Image } from 'semantic-ui-react' const HeaderExampleImage = () => ( <Header as='h2'> <Image shape='circular' src='http://semantic-ui.com/images/avatar2/large/patrick.png' /> {' '}Patrick </Header> ) export default HeaderExampleImage
src/ButtonInput.js
azmenak/react-bootstrap
import React from 'react'; import Button from './Button'; import FormGroup from './FormGroup'; import InputBase from './InputBase'; import childrenValueValidation from './utils/childrenValueInputValidation'; class ButtonInput extends InputBase { renderFormGroup(children) { let {bsStyle, value, ...other} = this.props; return <FormGroup {...other}>{children}</FormGroup>; } renderInput() { let {children, value, ...other} = this.props; let val = children ? children : value; return <Button {...other} componentClass="input" ref="input" key="input" value={val} />; } } ButtonInput.types = ['button', 'reset', 'submit']; ButtonInput.defaultProps = { type: 'button' }; ButtonInput.propTypes = { type: React.PropTypes.oneOf(ButtonInput.types), bsStyle(props) { //defer to Button propTypes of bsStyle return null; }, children: childrenValueValidation, value: childrenValueValidation }; export default ButtonInput;
src/index.js
kikoruiz/react-course
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, Redirect, hashHistory, applyRouterMiddleware } from 'react-router'; import { useTransitions, withTransition } from 'react-router-transitions'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import App from './components/app'; import Demo from './components/demo'; import About from './components/about'; import './index.scss'; render( <Router history={hashHistory} render={applyRouterMiddleware( useTransitions({ TransitionGroup: ReactCSSTransitionGroup, defaultTransition: { transitionName: 'animate', transitionEnterTimeout: 300, transitionLeaveTimeout: 300 } }) )}> <Redirect from='/' to='es' /> <Route path='/:language' component={withTransition(App)}> <IndexRoute component={Demo} /> <Route path='about' component={About} /> </Route> </Router>, document.getElementById('demo') );
app/javascript/mastodon/features/account_timeline/containers/header_container.js
sylph-sin-tyaku/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import Header from '../components/header'; import { followAccount, unfollowAccount, unblockAccount, unmuteAccount, pinAccount, unpinAccount, } from '../../../actions/accounts'; import { mentionCompose, directCompose, } from '../../../actions/compose'; import { initMuteModal } from '../../../actions/mutes'; import { initBlockModal } from '../../../actions/blocks'; import { initReport } from '../../../actions/reports'; import { openModal } from '../../../actions/modal'; import { blockDomain, unblockDomain } from '../../../actions/domain_blocks'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { unfollowModal } from '../../../initial_state'; import { List as ImmutableList } from 'immutable'; const messages = defineMessages({ unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' }, blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId }) => ({ account: getAccount(state, accountId), domain: state.getIn(['meta', 'domain']), identity_proofs: state.getIn(['identity_proofs', accountId], ImmutableList()), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow (account) { if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) { if (unfollowModal) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), })); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock (account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(initBlockModal(account)); } }, onMention (account, router) { dispatch(mentionCompose(account, router)); }, onDirect (account, router) { dispatch(directCompose(account, router)); }, onReblogToggle (account) { if (account.getIn(['relationship', 'showing_reblogs'])) { dispatch(followAccount(account.get('id'), false)); } else { dispatch(followAccount(account.get('id'), true)); } }, onEndorseToggle (account) { if (account.getIn(['relationship', 'endorsed'])) { dispatch(unpinAccount(account.get('id'))); } else { dispatch(pinAccount(account.get('id'))); } }, onReport (account) { dispatch(initReport(account)); }, onMute (account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, onBlockDomain (domain) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable. You will not see content from that domain in any public timelines or your notifications. Your followers from that domain will be removed.' values={{ domain: <strong>{domain}</strong> }} />, confirm: intl.formatMessage(messages.blockDomainConfirm), onConfirm: () => dispatch(blockDomain(domain)), })); }, onUnblockDomain (domain) { dispatch(unblockDomain(domain)); }, onAddToList(account){ dispatch(openModal('LIST_ADDER', { accountId: account.get('id'), })); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Header));
TodoWonder/js/NavigationPager.js
lintonye/react-native-diary
/** * @flow */ import React from 'react' import { Animated, View, StyleSheet, NavigationExperimental, } from 'react-native' const { CardStack: NavCardStack, StateUtils: NavStateUtils, Transitioner: NavTransitioner, Card: NavCard, } = NavigationExperimental const { PagerPanResponder: NavigationPagerPanResponder, PagerStyleInterpolator: NavigationPagerStyleInterpolator, } = NavCard; const {PropTypes} = React class NavigationPager extends React.Component { constructor(props, context) { super(props, context) } static propTypes: { // selectedTab: PropTypes.string, // TODO change to oneOf(tabs) // switchTab: PropTypes.func.isRequired, } render() { return ( <NavTransitioner {...this.props} render={this._render.bind(this)} /> ) } _navigate(action) { const {index, routes} = this.props.navigationState const pageCount = routes.length const delta = action === 'back' ? -1 : 1 const newIdx = Math.max(0, Math.min(pageCount-1, index+delta)) this.props.navigatePage(newIdx) } _render(transitionProps) { const scenes = transitionProps.scenes.map((scene) => { const sceneProps = {...transitionProps, scene} return ( <Page {...sceneProps} navigate={this._navigate.bind(this)} key={scene.route.key+'_scene'} render={this.props.renderScene} /> ) }) return ( <View style={styles.navigator}> {scenes} </View> ); } } class Page extends React.Component { render() { const style = [ styles.scene, NavigationPagerStyleInterpolator.forHorizontal(this.props), ]; const panHandlers = NavigationPagerPanResponder.forHorizontal({ ...this.props, onNavigateBack: () => this.props.navigate('back'), onNavigateForward: () => this.props.navigate('forward'), }) return ( <Animated.View {...panHandlers} style={style}> <View> {this.props.render(this.props)} </View> </Animated.View> ) } } const styles = StyleSheet.create({ navigator: { flex: 1, }, scene: { bottom: 0, flex: 1, left: 0, position: 'absolute', right: 0, top: 0, }, }) module.exports = NavigationPager
src/js/components/icons/base/Document.js
odedre/grommet-final
/** * @description Document SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M14,1 L14,8 L21,8 M21,23 L3,23 L3,1 L15,1 L18,4 L21,7 L21,23 L21,23 L21,23 Z"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-document`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M14,1 L14,8 L21,8 M21,23 L3,23 L3,1 L15,1 L18,4 L21,7 L21,23 L21,23 L21,23 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Document'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/TextLinkElement/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './styles.css'; import Wrapper from '../Wrapper'; import Typography from '../Typography'; function TextLinkElement(props) { function openTab() { if (props.onClick) { props.onClick(); } const win = window.open(props.children, '_blank'); win.focus(); } return ( <Wrapper className={classNames(styles.wrapper, styles[props.category], { [props.className]: props.className })} size="side-bottom" > <div className={styles.link} onClick={openTab} target="_blank" > <Typography className={classNames(styles.text, styles[props.category])} type="bodyTextNormal" > {props.children} </Typography> </div> </Wrapper> ); } TextLinkElement.propTypes = { category: PropTypes.oneOf(['food', 'consumption', 'energy', 'transportation', 'social']), children: PropTypes.node, className: PropTypes.string, onClick: PropTypes.func }; export default TextLinkElement;
app/javascript/mastodon/components/loading_indicator.js
ambition-vietnam/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const LoadingIndicator = () => ( <div className='loading-indicator'> <div className='loading-indicator__figure' /> <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' /> </div> ); export default LoadingIndicator;
mobile/ClubLife/src/views/editProfile.js
Bcpoole/ClubLife
import React, { Component } from 'react'; import { AppRegistry, Alert, Button, StyleSheet, Text, View, TextInput, ScrollView, TouchableNativeFeedback, Image, TouchableOpacity, TouchableHighlight, Platform, } from 'react-native'; export default class EditProfile extends Component { constructor(props){ super(props); this.state = { textOp: 1, boxOp: 0, userState: Object.assign({},this.props.route.state.user), //should work, if we need a deeper copy, investigate later nextUserState: Object.assign({}, this.props.route.state.user, {clubs: this.props.route.state.user.clubs.slice()}), //hey, what do you know, we needed a deeper copy confirmingChanges: false }; this._onConfirmChanges = this._onConfirmChanges.bind(this); this._onCancelChanges = this._onCancelChanges.bind(this); this._performChanges = this._performChanges.bind(this); this._removeSelfFromClub = this._removeSelfFromClub.bind(this); this._postNewUserInfo = this._postNewUserInfo.bind(this); this._confirmClubAlert = this._confirmClubAlert.bind(this); this._onGoProfileWithChanges = this._onGoProfileWithChanges.bind(this); } render() { var clubList = this.props.clubList; var clubs = []; for(let userClubId of this.state.nextUserState.clubs) { for(let club of clubList) { if(club.id === userClubId) { clubs.push(club); break; } } } var TouchableElement = Platform.select({ ios: TouchableOpacity, android: TouchableNativeFeedback }); return ( <View style={styles.container}> <View style={styles.box}> <Image style = {styles.profilepic} source={require('./images/profile-default.png')} /> <View style={styles.longBox}> <TextInput style={styles.textEdit} autoCorrect={false} onChangeText={(text) => this.setState({nextUserState: Object.assign(this.state.nextUserState, {name: text})})} placeholder={this.state.nextUserState.name}/> <Text style = {{paddingTop: 10}}></Text> <Text> {this.state.nextUserState.username} </Text> </View> </View> <Text style = {styles.welcome}>Clubs:</Text> <ScrollView> {clubs.map((club,i) => { return ( <View style = {styles.clubs} key={'clubbbb-'+i}> <Text style = {styles.instructions}>{club.name}</Text> <TouchableHighlight onPress = {()=>this._confirmClubAlert()}> <Image style = {styles.deleteButton} source={require('./images/delete.png')} /> </TouchableHighlight> </View> ); })} </ScrollView> <Text style = {styles.welcome}>Events:</Text> {/*}<ScrollView> <View style = {styles.events}> <Text style = {styles.instructions}>Jellyfishing Practice</Text> <Text style = {styles.instructions}>[Tues. 6:00 pm]</Text> <TouchableHighlight onPress = {()=>{Alert.alert("Leave Event?", "Are you sure you want to leave this event?",[{text: 'Yes', onPress: () => console.log('Yes Pressed!')}, {text: 'No', onPress: () => console.log('No Pressed')}])}}> <Image style = {styles.deleteButton} source={require('./images/delete.png')} /> </TouchableHighlight> </View> <View style = {styles.events}> <Text style = {styles.instructions}>Bubble Party</Text> <Text style = {styles.instructions}>[Fri. 8:00 pm]</Text> <TouchableHighlight onPress = {()=>{Alert.alert("Leave Event?", "Are you sure you want to leave this event?",[{text: 'Yes', onPress: () => console.log('Yes Pressed!')}, {text: 'No', onPress: () => console.log('No Pressed')}])}}> <Image style = {styles.deleteButton} source={require('./images/delete.png')} /> </TouchableHighlight> </View> </ScrollView>*/} <View style={styles.events}> <Text style={styles.instructions}> RSVP Events Feature "Coming Soon" </Text> </View> <View style = {styles.finalize}> <TouchableHighlight onPress={()=>this._onConfirmChanges()}> <View style = {styles.bottomConfirm}> <Text style = {{color: 'black', fontSize: 25, fontWeight: 'bold', ...Platform.select({android: {textAlign: 'center'}})}}>Confirm</Text> </View> </TouchableHighlight> <TouchableHighlight onPress={()=>this._onCancelChanges()}> <View style = {styles.bottomCancel}> <Text style = {{color: 'black', fontSize: 25, fontWeight: 'bold', ...Platform.select({android: {textAlign: 'center'}})}}>Cancel</Text> </View> </TouchableHighlight> </View> <View><Text>{this.state.confirmingChanges ? "Confirming your changes..." : ""}</Text></View> </View> ); } _confirmClubAlert(club) { let removeClub = (clubId) => { //hypothetically, ids are unique within this array and this will work cleanly var arr = [...this.state.nextUserState.clubs] // so we don't manipulate state directly var index = arr.indexOf(clubId); if(index > -1) { arr.splice(index,1); this.setState({ nextUserState: Object.assign(this.state.nextUserState, {clubs: arr}) }); } //TODO: delete from club properly? need to fetch and stuff }; Alert.alert("Leave Club?", "Are you sure you want to leave this club?", [ {text: 'Yes', onPress: () => removeClub(club)}, {text: 'No', onPress: () => console.log('No Pressed')} ] ); } _onGoProfileWithChanges() { if(this.props.route.index > 1) { //assume we came here from the profile, but also we need to snag the new information this.props.navigator.replacePrevious({ type: "profile", index: this.props.route.index-1, state: Object.assign({}, this.props.route.state, {user: this.state.nextUserState}) }); this.props.navigator.pop(); } } _onConfirmChanges() { this.setState({ confirmingChanges: true }, this._performChanges); } _onCancelChanges() { //pop and go back to the profile this.props.navigator.pop(); } _performChanges() { //compare user state as the DB sees it and the next State, and if there are any discrepancies, make the API calls var cur = this.state.userState; var next = this.state.nextUserState; //only 2 conditions we can change are user's name and the clubs that they are in if(cur.clubs.length > next.clubs.length) { //if condition is sufficient because we can only remove clubs or stay the same var clubsToRemove = cur.clubs.filter(club => next.clubs.indexOf(club) === -1); for(let club of clubsToRemove) { this._removeSelfFromClub(club); } } if(cur.name !== next.name) { this._postNewUserInfo() } this._onGoProfileWithChanges(); } /* Function that actually performs the call with the updated information, if we have any updated information. */ _postNewUserInfo() { var url = "http://skeleton20161103012840.azurewebsites.net/api/Users/"+this.state.nextUserState.id; fetch(url, {method: "POST", body: JSON.stringify(this.state.nextUserState)}); let headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}; let parseResponse = res => res.text().then(text => text ? JSON.parse(text) : {}); fetch(url, {method: "POST", headers: headers, body: JSON.stringify(this.state.nextUserState)}) .then(parseResponse) .then(json => { Alert.alert("Success","Succesfully updated profile", [{text: "OK", onPress: ()=>{ this.props.navigator.pop(); }}]); }) .catch(e => { Alert.alert("Error","couldn't update profile", [{text: "Dang", onPress: ()=>{ this.props.navigator.pop(); }}]);}); } _removeSelfFromClub(club) { var url = "http://skeleton20161103012840.azurewebsites.net/api/Users/" + this.state.nextUserState.id + "/leave/" + club; let headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}; let parseResponse = res => res.text().then(text => text ? JSON.parse(text) : {}); fetch(url, {method: "POST", headers: headers}) .then(parseResponse) .then(json => { Alert.alert("left club","you left club",[{text: "OK", onPress: ()=>{ this.props.navigator.pop(); }}]); }) .catch(e => { Alert.alert("Error","couldn't leave club", [{text: "WAIT AM I TRAPPED?", onPress: ()=>{ this.props.navigator.pop(); }}]);}); } } const styles = StyleSheet.create({ container: { flex: 1, //justifyContent: 'center', //alignItems: 'center', backgroundColor: '#F5FCFF', marginTop: 40, }, welcome: { fontSize: 20, ...Platform.select({android: {textAlign: 'center'}}), alignItems: 'center', justifyContent: 'center', margin: 10, color: '#800000', }, instructions: { ...Platform.select({android: {textAlign: 'center'}}), color: '#333333', justifyContent: 'center', marginBottom: 5, paddingRight: 10, }, button: { ...Platform.select({android: {textAlign: 'center'}}), color: '#333333', marginBottom: 5, }, profilepic: { height: 100, width: 100 }, deleteButton: { height: 15, width: 15, }, textEdit: { height: 40, width: 200, borderColor: 'grey', backgroundColor: 'white', borderWidth: 1, }, box: { paddingTop: 25, flexDirection: 'row', flexWrap: 'wrap', }, longBox: { height: 125, flexDirection: 'column', alignItems: 'center', paddingLeft: 25, }, finalize: { bottom: 1, height: 125, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'flex-end', }, bottomConfirm: { height: 50, width: 100, backgroundColor: 'chartreuse', borderColor: 'black', borderWidth: 1, justifyContent: 'center', alignItems: 'center', }, bottomCancel: { height: 50, width: 100, backgroundColor: 'red', borderColor: 'black', borderWidth: 1, justifyContent: 'center', alignItems: 'center', }, clubs: { flexDirection: 'row', justifyContent: 'space-around', marginLeft: 100, marginRight: 125, marginBottom: 2, height: 25, }, events: { flexDirection: 'row', justifyContent: 'space-around', marginLeft: 50, marginRight: 50, marginBottom: 2, height: 25, }, });
server/sonar-web/src/main/js/apps/quality-gates/components/DetailsContent.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React, { Component } from 'react'; import Conditions from './Conditions'; import Projects from './Projects'; import { translate } from '../../../helpers/l10n'; export default class DetailsContent extends Component { render() { const { gate, canEdit, metrics } = this.props; const { onAddCondition, onDeleteCondition, onSaveCondition } = this.props; const conditions = gate.conditions || []; const defaultMessage = canEdit ? translate('quality_gates.projects_for_default.edit') : translate('quality_gates.projects_for_default'); return ( <div ref="container" className="search-navigator-workspace-details"> <Conditions qualityGate={gate} conditions={conditions} metrics={metrics} edit={canEdit} onAddCondition={onAddCondition} onSaveCondition={onSaveCondition} onDeleteCondition={onDeleteCondition} /> <div id="quality-gate-projects" className="quality-gate-section"> <h3 className="spacer-bottom"> {translate('quality_gates.projects')} </h3> {gate.isDefault ? defaultMessage : <Projects qualityGate={gate} edit={canEdit} />} </div> </div> ); } }
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentSimplifyTypeArgs/index.js
claudiopro/flow
/** * @format * @flow */ const path = require('path'); const Styled = require('../../../Styled'); exports.kind = 'codemod'; exports.title = 'Simplify React.Component type arguments.'; exports.description = ` A React.Component used to require three type arguments like this: React.Component<DefaultProps, Props, State>. However, requiring DefaultProps whenever using type arguments doesn't make much sense. Also, requiring State for a component that does not use state, or in a consumer that doesn't care about State also doesn't make much sense. So we changed Flow so that we only require Props. If you write: React.Component<Props> then State is assumed to be undefined and default props will be inferred from the statics of your component class. A component written without state but with default props in this new style looks like: ${Styled.codeblock( ` import React from 'react'; type Props = { /* ... */ }; class MyComponent extends React.Component<Props> { static defaultProps = { /* ... */ }; }`.slice(1), )} Default props is inferred from the static defaultProps object literal. If you want a component with state add a second type argument: ${Styled.codeblock( ` import React from 'react'; type Props = { /* ... */ }; type State = { /* ... */ }; class MyComponent extends React.Component<Props, State> { static defaultProps = { /* ... */ }; }`.slice(1), )} This upgrade will remove DefaultProps from the type arguments of all your React components.`.slice(1); exports.transformPath = path.join(__dirname, './codemod.js');
client/src/Views/AcctManagementLayout.js
deepankarmalhan/fd-website
import React, { Component } from 'react'; import { Route } from 'react-router-dom'; import DeleteAccountBox from './DeleteAccountBox'; import AcctInfoLayout from './AcctInfoLayout'; export default class AcctManagementLayout extends Component { componentWillMount() { if(!localStorage.clientName) { this.props.history.push(`/auth`); } } render() { var matchRoute = this.props.match.url; return ( <div> <div className="columns"> <div className="column is-6 is-offset-3"> <h1 className="title">Manage your account</h1> <hr /> <Route path={`${matchRoute}/delete`} component={DeleteAccountBox} /> <Route exact path={matchRoute} component={AcctInfoLayout} /> </div> </div> </div> ); } };
src/utils/childrenValueInputValidation.js
Firfi/meteor-react-bootstrap
import React from 'react'; import { singlePropFrom } from './CustomPropTypes'; const propList = ['children', 'value']; const typeList = [React.PropTypes.number, React.PropTypes.string]; export default function valueValidation(props, propName, componentName) { let error = singlePropFrom(propList)(props, propName, componentName); if (!error) { const oneOfType = React.PropTypes.oneOfType(typeList); error = oneOfType(props, propName, componentName); } return error; }
client/src/components/trucks/TruckModal.js
PCGeekBrain/TruckTrack
import React, { Component } from 'react'; // Components import { Modal, Button, FormControl } from 'react-bootstrap'; // Actions import { submitTruck, hideModal } from '../../actions/trucks'; // Redux import { connect } from 'react-redux'; class TruckModal extends Component { componentWillMount(){ this.setState({...this.props.truck}); } updateField = (event) => { this.setState({ [event.target.id]: event.target.value }) } hide = () => { this.props.hideModal(); } onSave = (event) => { if (event) {event.preventDefault();} this.props.submitTruck(this.state); this.hide(); } render(){ return ( <Modal show={true} onHide={this.hide}> <Modal.Header closeButton> <Modal.Title>Route</Modal.Title> </Modal.Header> <Modal.Body> <form onSubmit={this.onSave}> <FormControl autoFocus id="name" value={this.state.name} onChange={this.updateField} placeholder="Name*"/> <FormControl id="licence" value={this.state.licence} onChange={this.updateField} placeholder="Licence Plate"/> </form> </Modal.Body> <Modal.Footer> <Button bsStyle="primary" onClick={this.onSave}>Save Truck</Button> </Modal.Footer> </Modal> ) } } function mapStateToProps(state, ownProps) { return { truck: state.trucks.truck } } export default connect(mapStateToProps, { submitTruck, hideModal })(TruckModal)
imports/startup/client/routes.js
KyneSilverhide/team-manager
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { Meteor } from 'meteor/meteor'; import App from '../../ui/layouts/App.js'; import Teams from '../../ui/pages/teams/Teams.js'; import Versions from '../../ui/pages/versions/Versions.js'; import HolidaysList from '../../ui/containers/holidays/HolidaysList.js'; import Developers from '../../ui/pages/developers/Developers.js'; import Runs from '../../ui/pages/runs/Runs.js'; import NewTeam from '../../ui/pages/teams/NewTeam.js'; import EditTeam from '../../ui/containers/teams/EditTeam.js'; import NewVersion from '../../ui/pages/versions/NewVersion.js'; import NewHoliday from '../../ui/containers/holidays/NewHoliday.js'; import NewRun from '../../ui/containers/runs/NewRun.js'; import EditVersion from '../../ui/containers/versions/EditVersion.js'; import NewDeveloper from '../../ui/containers/developers/NewDeveloper.js'; import EditDeveloper from '../../ui/containers/developers/EditDeveloper.js'; import EditHoliday from '../../ui/containers/holidays/EditHoliday.js'; import EditRun from '../../ui/containers/runs/EditRun.js'; import Index from '../../ui/pages/Index.js'; import Login from '../../ui/pages/Login.js'; import NotFound from '../../ui/pages/NotFound.js'; import RecoverPassword from '../../ui/pages/RecoverPassword.js'; import ResetPassword from '../../ui/pages/ResetPassword.js'; import Signup from '../../ui/pages/Signup.js'; const authenticate = (nextState, replace) => { if (!Meteor.loggingIn() && !Meteor.userId()) { replace({ pathname: '/login', state: { nextPathname: nextState.location.pathname }, }); } }; Meteor.startup(() => { render( <Router history={ browserHistory }> <Route path="/" component={ App }> <IndexRoute name="index" component={ Index } /> <Route name="teams" path="/teams" component={ Teams } onEnter={ authenticate } /> <Route name="versions" path="/versions" component={ Versions } onEnter={ authenticate } /> <Route name="developers" path="/developers" component={ Developers } onEnter={ authenticate } /> <Route name="runs" path="/runs" component={ Runs } onEnter={ authenticate } /> <Route name="holidays" path="/holidays" component={ HolidaysList } onEnter={ authenticate } /> <Route name="holidays" path="/holidays/:developerId" component={ HolidaysList } onEnter={ authenticate } /> <Route name="newTeam" path="/teams/new" component={ NewTeam } onEnter={ authenticate } /> <Route name="newVersion" path="/versions/new" component={ NewVersion } onEnter={ authenticate } /> <Route name="newDeveloper" path="/developers/new" component={ NewDeveloper } onEnter={ authenticate } /> <Route name="newRun" path="/runs/new" component={ NewRun } onEnter={ authenticate } /> <Route name="newHoliday" path="/holidays/:developerId/new" component={ NewHoliday } onEnter={ authenticate } /> <Route name="editTeam" path="/teams/:_id/edit" component={ EditTeam } onEnter={ authenticate } /> <Route name="editVersion" path="/versions/:_id/edit" component={ EditVersion } onEnter={ authenticate } /> <Route name="editDeveloper" path="/developers/:_id/edit" component={ EditDeveloper } onEnter={ authenticate } /> <Route name="editRun" path="/runs/:_id/edit" component={ EditRun } onEnter={ authenticate } /> <Route name="editHolidays" path="/holidays/:_id/edit" component={ EditHoliday } onEnter={ authenticate } /> <Route name="login" path="/login" component={ Login } /> <Route name="recover-password" path="/recover-password" component={ RecoverPassword } /> <Route name="reset-password" path="/reset-password/:token" component={ ResetPassword } /> <Route name="signup" path="/signup" component={ Signup } /> <Route path="*" component={ NotFound } /> </Route> </Router>, document.getElementById('react-root') ); });
spec/components/link.js
rahultaglr/taglr-toolbox
import React from 'react'; import Link from '../../components/link'; const LinkTest = () => ( <section> <h5>Links</h5> <p>lorem ipsum...</p> <Link label="Github" route="http://www.github.com" icon="bookmark" /> <Link label="Inbox" route="http://mail.google.com" icon="inbox" /> </section> ); export default LinkTest;
client/src/components/ingredient/Create.js
noinc/SimpleStorefront
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/ingredient/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 Ingredient</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.ingredient.create; return { created, error, loading }; }; const mapDispatchToProps = dispatch => ({ create: values => dispatch(create(values)), reset: () => dispatch(reset()) }); export default connect( mapStateToProps, mapDispatchToProps )(Create);
demo/components/navbar/NavBarOptions.js
ctco/rosemary-ui
import React from 'react'; import {NavItem, NavHrefItem} from '../../../src'; import OptionsTable from '../../helper/OptionsTable'; export default () => { let commonPropDesc = { active: { values: 'boolean', description: 'Set link to be active' }, right: { values: 'boolean', description: 'Set link to float right' }, withHoverEffect: { values: 'boolean', description: 'on hover will show underline' } }; let navItemPropDesc = { ...commonPropDesc, onClick: { values: 'function', description: 'Is called when btn is clicked' } }; let navHrefItemPropDesc = { ...commonPropDesc }; return ( <div> NavItem: <OptionsTable component={NavItem} propDescription={navItemPropDesc} /> NavHrefItem: <OptionsTable component={NavHrefItem} propDescription={navHrefItemPropDesc} /> </div> ); };
src/svg-icons/action/loyalty.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLoyalty = (props) => ( <SvgIcon {...props}> <path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7zm11.77 8.27L13 19.54l-4.27-4.27C8.28 14.81 8 14.19 8 13.5c0-1.38 1.12-2.5 2.5-2.5.69 0 1.32.28 1.77.74l.73.72.73-.73c.45-.45 1.08-.73 1.77-.73 1.38 0 2.5 1.12 2.5 2.5 0 .69-.28 1.32-.73 1.77z"/> </SvgIcon> ); ActionLoyalty = pure(ActionLoyalty); ActionLoyalty.displayName = 'ActionLoyalty'; ActionLoyalty.muiName = 'SvgIcon'; export default ActionLoyalty;
Realization/frontend/czechidm-core/src/content/audit/identity/AuditIdentityPasswordChangeContent.js
bcvsolutions/CzechIdMng
import React from 'react'; import Helmet from 'react-helmet'; // import * as Basic from '../../../components/basic'; import AuditIdentityPasswordChangeTable from './AuditIdentityPasswordChangeTable'; /** * Audit for identity password change. * * @author Ondřej Kopr * @author Radek Tomiška */ export default class AuditIdentityPasswordChangeContent extends Basic.AbstractContent { getContentKey() { return 'content.audit'; } getNavigationKey() { return 'audit-identity-password-change'; } render() { return ( <div> <Helmet title={ this.i18n('title-identity-password-change') } /> <AuditIdentityPasswordChangeTable uiKey="audit-table-password-change-identities" /> </div> ); } }
app/public/src/js/App/Weather/Index.js
ShawnCC/magic-mirror
'use strict'; import React from 'react'; import { connect } from 'react-redux'; const CronJob = require('cron').CronJob; import { getForecast } from '../Actions/Weather'; import Current from './Current'; import Upcoming from './Upcoming'; class Weather extends React.Component { constructor() { super(); } /** * Setup cron job to run every minute, on event call the get time method */ handleCron() { this.cronJob = new CronJob('0 0 0-23 * * *', () => { this.getForecast(); }, null, true, 'America/Detroit'); } /** * Make call to get the forecast */ getForecast() { this.context.store.dispatch(getForecast()); } componentWillMount() { this.getForecast(); } componentDidMount() { this.handleCron(); } componentWillUnmount() { this.cronJob.stop(); } render() { const { WeatherVM } = this.props; const items = WeatherVM.Upcoming.map((item) => { return <Upcoming key={ item.Id } Item={ item }></Upcoming>; }); return ( <div className="weather"> <Current Item={ WeatherVM.Current }></Current> { items } </div> ); } } Weather.propTypes = { WeatherVM: React.PropTypes.object.isRequired }; Weather.contextTypes = { store: React.PropTypes.object }; function select(state) { return { WeatherVM: state.WeatherVM }; } export default connect(select)(Weather);
ReactJS/07.Async-Redux/chiper-spa/src/index.js
Martotko/JS-Web
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { BrowserRouter } from 'react-router-dom' import { Provider } from 'react-redux' import storeGen from './store/store' let store = storeGen ReactDOM.render( <Provider store={store}> <BrowserRouter> <App /> </BrowserRouter> </Provider> , document.getElementById('root')); registerServiceWorker();
src/components/pages/StaticContent/StoresPage.js
ESTEBANMURUZABAL/bananaStore
/** * Imports */ import React from 'react'; // Required components import Heading from '../../common/typography/Heading'; /** * Component */ class StoresPage extends React.Component { //*** Page Title and Snippets ***// static pageTitleAndSnippets = function (context, params, query) { return { title: 'As Nossas Lojas' } }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./StoresPage.scss'); } //*** Template ***// render() { return ( <div> <p className="stores-page__address"> <strong>Direccion:</strong><br /> Güemes 765 <a href="https://www.google.pt/maps/place/Arrabida+Shopping/@41.1412417,-8.6388583,17z/data=!3m1!4b1!4m2!3m1!1s0xd246514bd568699:0x58e4800a92a23109?hl=en" target="_blank">Google Maps</a><br /> CP 3500 - Resistencia Chaco<br /> </p> <p className="stores-page__schedule"> <strong>Horário:</strong><br /> Lunes a Viernes: de 07 a 12:30 y 17 a 20:30<br /> Sábados: de 09 a 12:30<br /> </p> <p className="stores-page__contacts"> <strong>Contáctos:</strong><br /> 3624-423398 </p> </div> ); } } /** * Exports */ export default StoresPage;
src/app/component/labeled-field/labeled-field.js
all3dp/printing-engine-client
import PropTypes from 'prop-types' import React from 'react' import cn from '../../lib/class-names' import propTypes from '../../prop-types' const LabeledField = ({classNames, label, children}) => ( <div className={cn('LabeledField', {}, classNames)}> <span className="LabeledField__label">{label}</span> <div className="LabeledField__field">{children}</div> </div> ) LabeledField.propTypes = { ...propTypes.component, label: PropTypes.string.isRequired, children: PropTypes.node.isRequired } export default LabeledField
docs/src/components/Demo/Code/Code.js
seek-oss/seek-style-guide
import styles from './Code.less'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Section, Text } from 'seek-style-guide/react'; import debounce from 'lodash/debounce'; import uniq from 'lodash/uniq'; import jsxToString from 'react-element-to-jsx-string'; import CopyToClipboard from 'react-copy-to-clipboard'; export default class Code extends Component { static propTypes = { jsx: PropTypes.element, less: PropTypes.string }; constructor() { super(); this.state = { copiedToClipboard: false }; this.handleMouseLeave = this.handleMouseLeave.bind(this); this.debouncedHandleMouseLeave = debounce(this.handleMouseLeave, 5000); this.handleCopy = this.handleCopy.bind(this); } handleMouseLeave() { this.setState({ copiedToClipboard: false }); } handleCopy() { this.setState( { copiedToClipboard: true }, this.debouncedHandleMouseLeave ); } render() { const { copiedToClipboard } = this.state; const { jsx, less } = this.props; let code = ''; if (jsx) { const componentCode = jsxToString(jsx, { showDefaultProps: false, filterProps: ['className', 'style'], useBooleanShorthandSyntax: false }) .replace(/\={true}/gi, '') .replace(/svgClassName=".*?"/gi, 'svgClassName="..."') .replace(/function noRefCheck\(\) \{\}/gi, '() => {...}') .replace('<MockContent />', 'Lorem ipsum'); const componentNames = uniq( (componentCode.match(/<([A-Z]\w*)(?=[\s>])/g) || []).map(x => x.replace('<', '') ) ); code = `import {\n ${componentNames.join( ',\n ' )}\n} from 'seek-style-guide/react';\n\n\n${componentCode}`; } else if (less) { code = `@import (reference) "~seek-style-guide/theme";\n\n\n.element {\n .${less}\n}`; } return ( <CopyToClipboard text={code} onCopy={this.handleCopy}> <Section header className={styles.root} onMouseLeave={this.handleMouseLeave} > <pre className={styles.code}> <code>{code}</code> </pre> <Text strong className={styles.message} positive={copiedToClipboard}> {copiedToClipboard ? 'Copied' : 'Click to copy'} </Text> </Section> </CopyToClipboard> ); } }
monkey/monkey_island/cc/ui/src/components/ui-components/LoadingScreen.js
guardicore/monkey
import React from 'react'; import monkeyLoader from '../../images/monkey_loading.gif'; import '../../styles/components/LoadingScreen.scss'; import ParticleBackground from './ParticleBackground'; export default function LoadingScreen(props) { return ( <div className={'loading-screen'}> <ParticleBackground/> <div className={'loading-component'}> <div className={'loading-image'}><img src={monkeyLoader}/></div> <div className={'loading-text'}>{props.text.toUpperCase()}</div> </div> </div>); }
src/docs/src/templates/docs.js
StarterInc/Ignite
import { graphql } from 'gatsby'; import Helmet from 'react-helmet'; import MDXRenderer from 'gatsby-mdx/mdx-renderer'; import React from 'react'; import SimpleFooter from '../components/SimpleFooter'; import Sidebar from '../components/Sidebar'; import LayoutNav from '../components/LayoutNav'; import CodeTabs from '../components/CodeTabs'; import CodeClipboard from '../components/CodeClipboard'; import Typography from '../components/Typography'; import Auth from '../components/Auth'; import { logout } from '../services/auth'; export default class Docs extends React.Component { constructor(props) { super(props); this.state = { navbarToggled: false } } componentDidMount() { this._codeTabs = new CodeTabs(); this._codeClipboard = new CodeClipboard(); } componentWillUnmount() { this._codeTabs = null; this._codeClipboard.dispose(); } _handleLogout() { logout().then(() => { this.forceUpdate(); }); } docsNavbarToggleClick() { this.setState(prevState => ({ navbarToggled: !prevState.navbarToggled })); } render() { const { data, location } = this.props; const { mdx: { code, frontmatter: {title, needsAuth}, excerpt, timeToRead } } = data; return ( <Auth needsAuth={needsAuth}> <div className="docs"> <Helmet> <title>{title}</title> <meta name="description" content={excerpt} /> <meta name="og:description" content={excerpt} /> <meta name="twitter:description" content={excerpt} /> <meta name="og:title" content={title} /> <meta name="og:type" content="article" /> <meta name="twitter.label1" content="Reading time" /> <meta name="twitter:data1" content={`${timeToRead} min read`} /> </Helmet> <header> <LayoutNav effect={true} static={true} sidebarHamburguerIcon={true} onNavbarToggleClick={this.docsNavbarToggleClick.bind(this)} /> </header> <main className="content"> <Sidebar location={location} navbarToggled={this.state.navbarToggled} /> <div className="sidebar-offset"> <header> <div className="clay-site-container container-fluid"> <h1>{title}</h1> </div> </header> <div className="clay-site-container container-fluid"> <div className="row"> <div className="col-md-12"> <article> <MDXRenderer components={{ h1: Typography.H1, h2: Typography.H2, h3: Typography.H3, h4: Typography.H4, p: Typography.P, }} > {code.body} </MDXRenderer> </article> </div> </div> </div> <SimpleFooter editContentURL={process.env.EDIT_CONTENT_URL} issuesURL={process.env.ISSUES_URL} slug={this.props["*"]}/> </div> </main> </div> </Auth> ); } } export const pageQuery = graphql` query($slug: String!) { mdx(fields: { slug: { eq: $slug } }) { excerpt timeToRead frontmatter { title needsAuth } code { body } } } `;
src/components/movie/component/_movie.js
chemoish/react-webpack
import React from 'react'; import Router from 'react-router'; var {Link} = Router; export default React.createClass({ render() { let movie = this.props.movie; return ( <Link className="movie" to="movie" params={{slug: movie.seoTitle}}> <div className="movie-image"> <img src={movie.imageUrl} /> </div> <span className="movie-title">{movie.title}!</span> </Link> ); } });
app/javascript/flavours/glitch/containers/account_container.js
glitch-soc/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { makeGetAccount } from 'flavours/glitch/selectors'; import Account from 'flavours/glitch/components/account'; import { followAccount, unfollowAccount, blockAccount, unblockAccount, muteAccount, unmuteAccount, } from 'flavours/glitch/actions/accounts'; import { openModal } from 'flavours/glitch/actions/modal'; import { initMuteModal } from 'flavours/glitch/actions/mutes'; import { unfollowModal } from 'flavours/glitch/util/initial_state'; const messages = defineMessages({ unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, props) => ({ account: getAccount(state, props.id), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow (account) { if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) { if (unfollowModal) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), })); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock (account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(blockAccount(account.get('id'))); } }, onMute (account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, onMuteNotifications (account, notifications) { dispatch(muteAccount(account.get('id'), notifications)); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));