path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
_theme/template/NotFound.js
ElemeFE/react-amap
import React from 'react'; import Layout from './Layout'; export default class NotFound extends React.Component { render() { return <Layout> <div id="notfound"> <img src="https://cloud.githubusercontent.com/assets/3898898/23833528/2e1e198c-0782-11e7-8e13-664b39a29d4b.png" alt=""/> <div className="guide"> You Got Lost </div> </div> </Layout>; } }
assets/node_modules/react-easy-chart/modules/pie-chart/hybrid/index.js
janta-devs/nyumbani
import React from 'react'; import { scale, layout, svg, select, event as lastEvent, interpolate } from 'd3'; import { createUniqueID, defaultStyles } from '../../shared'; import { createElement } from 'react-faux-dom'; import { Style } from 'radium'; import merge from 'lodash.merge'; const color = scale.category20(); const pie = layout.pie() .value((d) => d.value) .sort(null); const getSliceFill = (d, i) => ( (d.data.color) ? d.data.color : color(i)); const getLabelText = (d) => d.data.key; export default class PieChart extends React.Component { static get propTypes() { return { data: React.PropTypes.array.isRequired, innerHoleSize: React.PropTypes.number, size: React.PropTypes.number, padding: React.PropTypes.number, labels: React.PropTypes.bool, styles: React.PropTypes.object, mouseOverHandler: React.PropTypes.func, mouseOutHandler: React.PropTypes.func, mouseMoveHandler: React.PropTypes.func, clickHandler: React.PropTypes.func }; } static get defaultProps() { return { size: 400, innerHoleSize: 0, padding: 2, labels: false, styles: {}, mouseOverHandler: () => {}, mouseOutHandler: () => {}, mouseMoveHandler: () => {}, clickHandler: () => {} }; } constructor(props) { super(props); this.uid = createUniqueID(props); this.currentSlices = []; this.currentLabels = []; this.tweenSlice = (slice, index) => { const currentSlice = this.currentSlices[index]; const i = interpolate(currentSlice, slice); this.currentSlices[index] = slice; return (t) => this.getSliceArc()(i(t)); }; } componentDidMount() { this.initialise(); } componentDidUpdate() { this.transition(); } getSliceArc() { const { padding } = this.props; const innerRadius = this.getInnerRadius(); const outerRadius = this.getOuterRadius(); return svg.arc() .innerRadius(innerRadius - padding) .outerRadius(outerRadius - padding); } getLabelArc() { const { padding } = this.props; const outerRadius = this.getOuterRadius(); const radius = outerRadius - padding - ((20 * outerRadius) / 100); return svg.arc() .outerRadius(radius) .innerRadius(radius); } getOuterRadius() { return this.props.size * 0.5; } getInnerRadius() { return this.props.innerHoleSize * 0.5; } getSlices() { const { data } = this.props; const uid = this.uid; return select(`#slices-${uid}`) .datum(data) .selectAll('path'); } getLabels() { const { data } = this.props; const uid = this.uid; return select(`#labels-${uid}`) .datum(data) .selectAll('text'); } createSvgNode({ size }) { const node = createElement('svg'); node.setAttribute('width', size); node.setAttribute('height', size); return node; } createSvgRoot({ node }) { return select(node); } initialiseLabels() { const text = this.getLabels() .data(pie); const getLabelArcTransform = (d) => { const [labelX, labelY] = this.getLabelArc().centroid(d); return `translate(${labelX}, ${labelY})`; }; const currentLabels = this.currentLabels; text .enter() .append('text') .attr('dy', '.35em') .attr('class', 'pie-chart-label') .attr('transform', getLabelArcTransform) .text(getLabelText) .each((d) => currentLabels.push(d)); } initialiseSlices() { const { mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const currentSlices = this.currentSlices; const path = this.getSlices() .data(pie); path .enter() .append('path') .attr('class', 'pie-chart-slice') .attr('fill', getSliceFill) .attr('d', this.getSliceArc()) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click) .each((d) => currentSlices.push(d)); } initialise() { const { labels } = this.props; this.initialiseSlices(); if (labels) { this.initialiseLabels(); } } transitionSlices() { const { data, mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const n = data.length; const currentSlices = this.currentSlices; const path = this.getSlices() .data(pie); if (n) { // we don't need to do this, but it's fun /* * Change current slices * Transition current slice dimensions */ path .attr('fill', getSliceFill) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click) .transition() .duration(750) .attrTween('d', this.tweenSlice); /* * Add new slices */ path .enter() .append('path') .attr('class', 'pie-chart-slice') .attr('fill', getSliceFill) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click) .each((d, i) => currentSlices.splice(i, 1, d)) .transition() .duration(750) .attrTween('d', this.tweenSlice); } /* * Remove old slices */ path .exit() .remove(); currentSlices.length = n; // = this.currentSlices.slice(0, n) } transitionLabels() { const { data } = this.props; const getLabelArcTransform = (d) => { const [labelX, labelY] = this.getLabelArc().centroid(d); return `translate(${labelX}, ${labelY})`; }; const n = data.length; const currentLabels = this.currentLabels; const text = this.getLabels() .data(pie); if (n) { // we don't need to do this, but it's fun /* * Change current labels */ text .transition() .duration(750) .attr('transform', getLabelArcTransform) .text(getLabelText); /* * Add new labels */ text .enter() .append('text') .attr('dy', '.35em') .attr('class', 'pie-chart-label') .attr('transform', getLabelArcTransform) .text(getLabelText) .each((d, i) => currentLabels.splice(i, 1, d)) .transition() .duration(750); } /* * Remove old labels */ text .exit() .remove(); currentLabels.length = n; } transition() { const { labels } = this.props; this.transitionSlices(); if (labels) { this.transitionLabels(); } } createSlices({ root }) { const uid = this.uid; const radius = this.getOuterRadius(); root .append('g') .attr('id', `slices-${uid}`) .attr('transform', `translate(${radius}, ${radius})`); } createLabels({ root }) { const uid = this.uid; const radius = this.getOuterRadius(); root .append('g') .attr('id', `labels-${uid}`) .attr('transform', `translate(${radius}, ${radius})`); } createStyle() { const { styles } = this.props; const uid = this.uid; const scope = `.pie-chart-${uid}`; const rules = merge({}, defaultStyles, styles); return ( <Style scopeSelector={scope} rules={rules} /> ); } calculateChartParameters() { const { size } = this.props; const node = this.createSvgNode({ size }); const root = this.createSvgRoot({ node }); return { node, root }; } render() { const { labels } = this.props; const p = this.calculateChartParameters(); this.createSlices(p); if (labels) { this.createLabels(p); } const uid = this.uid; const className = `pie-chart-${uid}`; const { node } = p; return ( <div className={className}> {this.createStyle()} {node.toReact()} </div> ); } }
frontend/src/components/login/login.js
unicef/un-partner-portal
import React from 'react'; import Card from '../common/cardLogin'; import LoginForm from './loginForm'; const messages = { title: 'UN Partner Portal', }; const Login = () => ( <Card title={messages.title}> <LoginForm /> </Card> ); export default Login;
packages/material-ui-icons/src/AddCircleOutline.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let AddCircleOutline = props => <SvgIcon {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /> </SvgIcon>; AddCircleOutline = pure(AddCircleOutline); AddCircleOutline.muiName = 'SvgIcon'; export default AddCircleOutline;
server/dashboard/js/components/BenchLog.react.js
machinezone/mzbench
import React from 'react'; import ReactDOM from 'react-dom'; import LogsStore from '../stores/LogsStore'; import MZBenchActions from '../actions/MZBenchActions'; import MZBenchRouter from '../utils/MZBenchRouter'; import BenchLogEntry from './BenchLogEntry.react'; import LoadingSpinner from './LoadingSpinner.react'; import PropTypes from 'prop-types'; const LOGS_PER_PAGE = 100; class BenchLog extends React.Component { constructor(props) { super(props); this.streamId = 0; this.autoSearchHandler = null; this.filtered = 0; this.state = this._resolveState(); this.state.tempQ = this.state.form.query; this.state.tempK = this.state.form.kind; this.state.tempE = this.state.form.errors; this.state.logShown = LOGS_PER_PAGE; this.followFlag = false; this._onChange = this._onChange.bind(this); this._onChangeSearch = this._onChangeSearch.bind(this); this._onUser = this._onUser.bind(this); this._onSystem = this._onSystem.bind(this); this._onErrors = this._onErrors.bind(this); this._onScroll = this._onScroll.bind(this); this._onResize = this._onResize.bind(this); this._onFollow = this._onFollow.bind(this); this._onTop = this._onTop.bind(this); this.lastLogShown = 0; } componentDidMount() { LogsStore.onChange(this._onChange); this.streamId = LogsStore.subscribeToLogs(this.props.bench.id); window.addEventListener("scroll", this._onScroll); window.addEventListener("resize", this._onResize); ReactDOM.findDOMNode(this.refs.loglookup).focus(); this._updateFollowPos(); this._updateTopPos(); } componentWillUnmount() { LogsStore.off(this._onChange); LogsStore.unsubscribeFromLogs(this.streamId); window.removeEventListener("resize", this._onResize); window.removeEventListener("scroll", this._onScroll); } componentDidUpdate() { if (this.state.isFollow) { this.goBottom(); } this._updateFollowPos(); this._updateTopPos(); } render() { const url = '/' + (this.state.form.kind == 0 ? 'userlog' : 'log') + '?id=' + this.props.bench.id; let classUser = "btn btn-" + (this.state.form.kind == 0 ? "primary":"default"); let classSystem = "btn btn-" + (this.state.form.kind == 1 ? "primary":"default"); let classError = "btn btn-" + (this.state.form.errors == 1 ? "danger":"default"); let currentLog = this.state.form.kind == 1 ? this.state.logs.system : this.state.logs.user; let overflow = this.state.form.kind == 1 ? this.state.logs.systemOverflow : this.state.logs.userOverflow; let loaded = this.state.form.kind == 1 ? this.state.logs.isSystemLoaded : this.state.logs.isUserLoaded; let logAfterQuery = this.state.logAfterQuery; let logsToShow = (logAfterQuery.length < this.state.logShown) ? logAfterQuery.length : this.state.logShown; this.lastLogShown = logsToShow; return ( <div> <form className="form-inline log-lookup-form"> <div className="input-group col-xs-4"> <div className="input-group-addon"><span className="glyphicon glyphicon-search" aria-hidden="true"></span></div> <input ref="loglookup" type="text" className="form-control" onKeyDown={this._onKeyDown.bind(this)} onChange={this._onChangeSearch} value={this.state.tempQ} placeholder="Lookup Logs" /> </div> <div className="btn-group" role="group"> <button type="button" className={classUser} onClick={this._onUser}>User</button> <button type="button" className={classSystem} onClick={this._onSystem}>System</button> </div> <button type="button" className={classError} onClick={this._onErrors}>Errors only</button> </form> { !loaded ? (<LoadingSpinner>Loading...</LoadingSpinner>) : <div> <div className="top-raw-fixed" ref="followdiv"> <span className="btn-raw"> <a href={url} target="_blank">Raw log</a> </span> <span className="btn-raw btn-bottom" style={{fontWeight: this.state.isFollow && this.props.isBenchActive ? 'bold' : 'normal'}} ref="followbtn"> <a href="#" onClick={this._onFollow}>{this.props.isBenchActive ? "Follow log" : "Scroll to end"}</a> </span> </div> <div className="bottom-raw-fixed" ref="topbtn"> <span className="btn-raw btn-top"> <a href="#" onClick={this._onTop}>Top</a> </span> </div> <div className="log-window" ref="logwindow"> <table className="table table-striped table-logs"> <tbody> {overflow ? <tr className="warning"><td>Warning: due to big size, this log is trimmed</td></tr> : null} {!currentLog.length ? <tr className="warning"><td>Warning: this log is empty</td></tr> : (!logAfterQuery.length ? <tr className="warning"><td>Query not found</td></tr> : null)} </tbody> </table> {this.formatLogs(logsToShow, logAfterQuery)} </div> </div> } </div> ); } formatLogs(logsToShow, log) { let nPages = Math.round(logsToShow / LOGS_PER_PAGE) + 1; let form = this.state.form; let prefix = form.kind + "-" + form.errors + "-" + form.query + "-"; let res = []; for (var page = 0; page < nPages; page++) { res.push(<BenchLogEntry key={prefix + page} log={log} from={page*LOGS_PER_PAGE} to={(page + 1)*LOGS_PER_PAGE} query={this.state.form.query}/>); } return res; } filterLogs(form, logs, needRefilter) { let filtered = (needRefilter || !this.state) ? 0 : this.filtered; var logAfterQuery = (needRefilter || !this.state) ? [] : this.state.logAfterQuery; let currentLog = form.kind == 1 ? logs.system : logs.user; let query = form.query; let errors = form.errors; if (needRefilter) this.lastLogShown = 0; if (!query && !errors) { this.filtered = currentLog.length; return currentLog; } for (; filtered < currentLog.length; filtered++) { let line = currentLog[filtered]; if (!line) break; if (query) { let fullText = line.time + " " + line.severity + " " + line.text; if (fullText.indexOf(query) == -1) continue; } if (errors && line.severity!="[error]") continue; logAfterQuery.push(line); }; this.filtered = filtered; return logAfterQuery; } _onScroll(scrollEvent) { this._updateFollowPos(); this._updateTopPos(); if (this.updatePage()) return; if (this.followFlag) { this.followFlag = false; } else if(this.state.isFollow) { this.setState({isFollow: false}); } } _onResize(resizeEvent) { this._updateFollowPos(); this._updateTopPos(); } _updateFollowPos() { let logElement = ReactDOM.findDOMNode(this.refs.logwindow); if (!logElement) return; var rect = logElement.getBoundingClientRect(); let top = (rect.top > 0) ? rect.top : 0; let right = (document.body.clientWidth - rect.right); let followDiv = ReactDOM.findDOMNode(this.refs.followdiv); followDiv.style.top = top + 'px'; followDiv.style.right = right + 'px'; let followBtn = ReactDOM.findDOMNode(this.refs.followbtn); let visible = document.body.scrollHeight > window.innerHeight; followBtn.style.visibility = visible ? "visible" : "hidden"; } _updateTopPos() { let logElement = ReactDOM.findDOMNode(this.refs.logwindow); if (!logElement) return; var rect = logElement.getBoundingClientRect(); let right = (document.body.clientWidth - rect.right); let topBtn = ReactDOM.findDOMNode(this.refs.topbtn); topBtn.style.visibility = (window.pageYOffset > 0 ? 'visible' : 'hidden'); topBtn.style.right = right + 'px'; } _resolveState() { let currentState = this.state ? this.state : {form: {query: "", kind: 0, errors: 0}, logAfterQuery: [], isFollow: false}; let newForm = LogsStore.getQueryData(this.props.bench.id); let needRefilter = (!currentState.form || currentState.form.query != newForm.query || currentState.form.kind != newForm.kind || currentState.form.errors != newForm.errors); currentState.form.kind = newForm.kind; currentState.form.query = newForm.query; currentState.form.errors = newForm.errors; currentState.logs = LogsStore.getLogData(this.streamId); currentState.logAfterQuery = this.filterLogs(newForm, currentState.logs, needRefilter); return currentState; } _onChange() { this.setState(this._resolveState()); if (this.state.isFollow) this.updatePage(); } _runSearch() { this.state.logShown = LOGS_PER_PAGE; if (this.autoSearchHandler) { clearTimeout(this.autoSearchHandler); } MZBenchRouter.navigate("/bench/" + this.props.bench.id + "/logs/" + (this.state.tempK ? "system": "user") + "/" + (this.state.tempE ? "errors": "all") + (this.state.tempQ ? "/" + encodeURIComponent(this.state.tempQ).replace(/'/g, "%27") : ""), {}); } _onKeyDown(event) { if (event.key === 'Enter') { event.preventDefault(); this._runSearch(); } } _onChangeSearch(event) { let state = this.state; if (this.autoSearchHandler) { clearTimeout(this.autoSearchHandler); } state.tempQ = event.target.value; this.setState(state); this.autoSearchHandler = setTimeout(() => this._runSearch(), this.props.autoSearchInterval); } _onUser() { this.state.tempK = 0; ReactDOM.findDOMNode(this.refs.loglookup).focus(); this._runSearch(); } _onSystem() { this.state.tempK = 1; ReactDOM.findDOMNode(this.refs.loglookup).focus(); this._runSearch(); } _onFollow(event) { event.preventDefault(); this.setState({isFollow: !this.state.isFollow}); let logLen = this.state.logAfterQuery.length; if (this.state.logShown < logLen) { this.setState({logShown: logLen}); } if (this.state.isFollow) this.goBottom(); } _onTop(event) { event.preventDefault(); this.setState({isFollow: false}); ReactDOM.findDOMNode(this.refs.loglookup).focus(); this.goTop(); } _onErrors() { this.state.tempE = !this.state.tempE; ReactDOM.findDOMNode(this.refs.loglookup).focus(); this._runSearch(); } goBottom() { var newValue = document.body.scrollHeight - window.innerHeight; if (window.pageYOffset < newValue) { window.scrollTo(0, newValue); this.followFlag = true; } } goTop() { window.scrollTo(0, 0); } updatePage () { let node = document.body; var shouldIncrementPage = (window.pageYOffset + window.innerHeight + 2000 > node.scrollHeight); let endReached = (this.state.logAfterQuery.length <= this.state.logShown); if (shouldIncrementPage && !endReached) { this.setState({logShown: this.state.logShown + LOGS_PER_PAGE}); return true; } return false; } }; BenchLog.propTypes = { bench: PropTypes.object.isRequired, autoSearchInterval: PropTypes.number }; BenchLog.defaultProps = { autoSearchInterval: 500 }; export default BenchLog;
src/javascripts/utils.js
aAXEe/online_chart_ol3
/** * @license AGPL-3.0 * @author aAXEe (https://github.com/aAXEe) */ import viewSize from 'screen-size' import React from 'react' import { FormattedMessage } from 'react-intl' export function floatEqual (num1, num2, eps = 0.0001) { if (num1 === num2) return true return Math.abs(num1 - num2) <= eps } export function positionsEqual (pos1, pos2) { if (pos1 === pos2) return true let epsilon = 0.0001 return floatEqual(pos1.lat, pos2.lat, epsilon) && floatEqual(pos1.lan, pos2.lan, epsilon) && floatEqual(pos1.zoom, pos2.zoom, epsilon) } export function isMobile () { return (viewSize().x <= 768) } export function hashCode (str) { return str.split('').reduce((prevHash, currVal) => ((prevHash << 5) - prevHash) + currVal.charCodeAt(0), 0) } export const ClickOnMarkersMessage = () => ( <FormattedMessage id='click-on-markers' description='Inform users about interactive map elements' defaultMessage='Click on the markers on the map.' /> )
src/components/ReplConsole.js
boneskull/Mancy
import React from 'react'; import _ from 'lodash'; import ReplConsoleStore from '../stores/ReplConsoleStore'; import ReplDOM from '../common/ReplDOM'; import ReplConsoleMessageFilters from './ReplConsoleMessageFilters'; import ReplConsoleHook from '../common/ReplConsoleHook'; export default class ReplConsole extends React.Component { constructor(props) { super(props); this.state = _.extend({}, ReplConsoleStore.getStore(), { debug: true, log: true, info: true, warn: true, error: true, all: true }); _.each([ 'onConsoleChange', 'getTypedClassName', 'onAll', 'onFilter', 'onClear', 'getDupCountStyle', 'getDupTooltip' ], (field) => { this[field] = this[field].bind(this); }); _.each(['debug', 'log', 'info', 'warn', 'error'], (msg) => { let key = 'on' + _.capitalize(msg); this[key] = () => this.onFilter(msg); this[key] = this[key].bind(this); }); } componentDidMount() { this.unsubscribe = ReplConsoleStore.listen(this.onConsoleChange); this.element = React.findDOMNode(this); } componentWillUnmount() { this.unsubscribe(); } onFilter(type) { let flag = !this.state[type]; let newState = _.extend({}, this.state); newState[type] = flag; newState.entries = _.filter(ReplConsoleStore.getStore().entries, (entry) => { return newState[entry.type]; }); this.setState(newState); } onClear() { ReplConsoleStore.clear(); } onAll() { let newState; if(!this.state.all) { newState = _.extend({}, ReplConsoleStore.getStore(), { debug: true, log: true, info: true, warn: true, error: true, all: true }); } else { newState = { all: false } } this.setState(newState); } onConsoleChange() { this.setState(ReplConsoleStore.getStore()); } getTypedClassName(className, type) { return className + ' ' + type; } getDupCountStyle(count) { let widthLength = `${count}`.length; return { width: `${widthLength + 0.2}em` }; } getDupTooltip(count, type) { return `${count} ${type} messages`; } render() { //scroll to bottom ReplDOM.scrollToEnd(this.element); return ( <div className='repl-console-message'> <ReplConsoleMessageFilters filter={this.state} onAll={this.onAll} onError={this.onError} onWarn={this.onWarn} onInfo={this.onInfo} onLog={this.onLog} onClear={this.onClear} onDebug={this.onDebug}/> { _.map(this.state.entries, ({type, data, time, count}) => { return ( <div className={this.getTypedClassName('repl-console-message-entry', type)} key={time}> {count > 1 ? <span className='console-message-count' title={this.getDupTooltip(count, type)} style={this.getDupCountStyle(count)}>{count}</span>: null} {ReplConsole.getTypeIcon[type]} <span className={this.getTypedClassName('repl-console-message-entry-content', type)}> {data} </span> </div> ); }) } <div className="repl-status-bar-cover" key='cover'></div> </div> ); } static getTypeIcon = (() => { let cache = {}; cache.error = <i className="fa fa-exclamation-circle repl-console-message-error" title='error'></i> cache.warn = <i className="fa fa-exclamation-triangle repl-console-message-warning" title='warning'></i> cache.info = <i className="fa fa-info-circle repl-console-message-info" title='info'></i> return cache; })(); }
app/js/components/ui/containers/field.js
blockstack/blockstack-browser
import React from 'react' import PropTypes from 'prop-types' import { StyledField } from '@ui/components/form' import { slugify } from '@ui/common' import AlertCircleIcon from 'mdi-react/AlertCircleIcon' import CheckCircleOutlineIcon from 'mdi-react/CheckCircleOutlineIcon' /* eslint-disable */ class Field extends React.Component { static propTypes = { label: PropTypes.string.isRequired, type: PropTypes.string, value: PropTypes.string, message: PropTypes.node, autoFocus: PropTypes.bool, error: PropTypes.any, positive: PropTypes.bool, overlay: PropTypes.node, name: PropTypes.node, mh: PropTypes.any, handleChange: PropTypes.func, handleChangeOverride: PropTypes.func, handleBlur: PropTypes.func, onBlur: PropTypes.func } ref = React.createRef() componentDidMount() { if (this.props.autoFocus) { this.ref.current.focus() } } render() { /* eslint-enable */ const { label, type = 'text', message, autoFocus, error, positive, overlay, name = slugify(label), mh, value, handleChange, handleChangeOverride, handleBlur, // these are here to prevent them from being used (fixes form bug double click) onBlur, // these are here to prevent them from being used (fixes form bug double click) ...rest } = this.props const InputComponent = type === 'textarea' ? StyledField.Textarea : StyledField.Input const LabelIconComponent = positive ? CheckCircleOutlineIcon : AlertCircleIcon const LabelIcon = (error || positive) && ( <StyledField.Label.Icon positive={positive}> <LabelIconComponent size={16} /> </StyledField.Label.Icon> ) /** * TODO: abstract out qualified message to one component that takes multiple states */ const MessageComponent = error ? StyledField.Input.Error : StyledField.Input.Positive const Message = p => positive || error ? ( <MessageComponent overlay={!!overlay} {...p}> {positive || error} </MessageComponent> ) : null const Overlay = overlay ? ( <StyledField.Input.Overlay>{overlay}</StyledField.Input.Overlay> ) : null const _handleChange = e => { if (handleChangeOverride) { handleChangeOverride(e, handleChange) } else { handleChange(e) } } const Label = () => ( <StyledField.Label htmlFor={name}> {label} {LabelIcon} </StyledField.Label> ) return ( <StyledField.Group error={error} {...rest}> <StyledField.Input.Wrapper> {Overlay} <InputComponent ref={this.ref} placeholder={label} autoComplete="new-password" required name={name} type={type} defaultValue={value} mh={mh} onChange={_handleChange} lowercase={type !== 'password'} /> <Message /> <Label /> <StyledField.Input.Bar /> </StyledField.Input.Wrapper> {message && ( <StyledField.Input.Message>{message}</StyledField.Input.Message> )} </StyledField.Group> ) } } // eslint-enable export { Field }
src/scenes/home/families/facts/facts.js
tal87/operationcode_frontend
import React from 'react'; import styles from './facts.css'; import family3 from '../../../../images/Family-3.jpg'; const Facts = () => ( <div className={styles.facts}> <div className={styles.factsList}> <div className={styles.factsHeading}> <h5>The Facts</h5> </div> <ul> <li className={styles.factItem}> There are approximately 710,000 active duty spouses, 93% of whom are female. An additional 500,000 spouses are married to a Reservist or National Guardsman. </li> <li className={styles.factItem}> 84% have some college education; 25% hold an undergraduate degree; and 10% hold a postgraduate degree. </li> <li className={styles.factItem}> 77% of spouses report that they want or need to work. 38% of military spouses are underemployed, compared to approximately 6% rate for civilian spouses. </li> <li className={styles.factItem}> Only 19% of military spouses have adequate full-time employment. </li> </ul> </div> <div className={styles.factsRight}> <img className={styles.factsImage} src={family3} alt="" /> </div> </div> ); export default Facts;
src/scenes/home/chapterLeader/chapterLeader.js
hollomancer/operationcode_frontend
import React from 'react'; import Section from 'shared/components/section/section'; const chapterLeaders = () => ( <div> <Section title="Chapter Leaders" theme="white"> <div> <p> Operation Code is looking for volunteer Chapter Leaders to build local communities nationwide! Tell us more about yourself <a href="http://op.co.de/chapter-leader-volunteer" target="_blank" rel="noopener noreferrer" > &nbsp;here&nbsp; </a> and help further our mission to get the military community into the tech industry! </p> <p> {' '} An Operation Code Chapter Leader organizes meetups and events at the local level, and establishes relationships with local companies, educational institutions, and other organizations, in order to help build the community and support the mission. </p> <h5>Who is a Chapter Leader?</h5> <ul> <li>Represents the Operation Code values.</li> <li> Dedicated, reliable and has consistently displayed participation in the community. </li> <li> Understands the community dynamics and encourages members to have a voice. Empowers people. </li> <li> Organized, and able to stay on top of their multiple responsibilities, such as managing events and recruiting new members. </li> <li> Passionate communicators that have a strong desire to connect with like-minded people. </li> <li> Able to explain basic programming concepts to chapter members if necessary, as new chapter members may range from being senior software developers, to having little or no experience with software development. </li> </ul> <h5>Responsibilities</h5> <ul> <li>Enforce the Code of Conduct on Operation Code web communities.</li> <li>Host events, including trainings, talks, hack nights, etc.</li> <li>Build partnerships in the local community.</li> <li> <a href="https://opencollective.com/operationcode" target="_blank" rel="noopener noreferrer" > Raise funds&nbsp; </a> and in-kind donations in support of the mission. </li> <li>Build and integrate the infrastructure necessary to sustain the chapter.</li> <li>Reach out to potential new members, receiving and integrating them to the team.</li> <li>Advocate for and promote the organization in the local community.</li> <li>Help members learn, grow, and find jobs!</li> </ul> <p> Think you are interested in becoming a Chapter Leader? Click <a href="http://op.co.de/chapter-leader-volunteer" target="_blank" rel="noopener noreferrer" > &nbsp;here.&nbsp; </a> </p> </div> </Section> </div> ); export default chapterLeaders;
src/svg-icons/action/group-work.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGroupWork = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5zM9.5 8c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8zm6.5 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); ActionGroupWork = pure(ActionGroupWork); ActionGroupWork.displayName = 'ActionGroupWork'; ActionGroupWork.muiName = 'SvgIcon'; export default ActionGroupWork;
web-server/v0.4/src/pages/Summary/index.js
k-rister/pbench
import React from 'react'; import { connect } from 'dva'; import { Spin, Tag, Card, List, Typography, Divider } from 'antd'; import { filterIterations } from '../../utils/parse'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import Table from '@/components/Table'; import TableFilterSelection from '@/components/TableFilterSelection'; const tabList = [ { key: 'iterations', tab: 'Iterations', }, { key: 'toc', tab: 'Table of Contents', }, { key: 'metadata', tab: 'Metadata', }, { key: 'tools', tab: 'Tools & Parameters', }, ]; const tocColumns = [ { title: 'Name', dataIndex: 'name', key: 'name', width: '60%', }, { title: 'Size', dataIndex: 'size', key: 'size', width: '20%', }, { title: 'Mode', dataIndex: 'mode', key: 'mode', }, ]; @connect(({ global, dashboard, loading }) => ({ iterations: dashboard.iterations, iterationParams: dashboard.iterationParams, iterationPorts: dashboard.iterationPorts, result: dashboard.result, tocResult: dashboard.tocResult, datastoreConfig: global.datastoreConfig, selectedControllers: global.selectedControllers, selectedResults: global.selectedResults, selectedIndices: global.selectedIndices, loadingSummary: loading.effects['dashboard/fetchIterations'] || loading.effects['dashboard/fetchResult'] || loading.effects['dashboard/fetchTocResult'], })) class Summary extends React.Component { constructor(props) { super(props); const { iterations } = props; this.state = { activeSummaryTab: 'iterations', resultIterations: iterations[0], }; } componentDidMount() { const { dispatch, datastoreConfig, selectedIndices, selectedResults } = this.props; dispatch({ type: 'dashboard/fetchIterations', payload: { selectedResults, datastoreConfig }, }); dispatch({ type: 'dashboard/fetchResult', payload: { datastoreConfig, selectedIndices, result: selectedResults[0]['run.name'], }, }); dispatch({ type: 'dashboard/fetchTocResult', payload: { datastoreConfig, selectedIndices, id: selectedResults[0].id, }, }); } componentWillReceiveProps(nextProps) { const { iterations } = this.props; if (nextProps.iterations !== iterations) { this.setState({ resultIterations: nextProps.iterations[0] }); } } onFilterTable = (selectedParams, selectedPorts) => { const { iterations } = this.props; const filteredIterations = filterIterations(iterations, selectedParams, selectedPorts); this.setState({ resultIterations: filteredIterations[0] }); }; onTabChange = key => { this.setState({ activeSummaryTab: key }); }; render() { const { activeSummaryTab, resultIterations } = this.state; const { selectedResults, loadingSummary, iterationParams, iterationPorts, selectedControllers, tocResult, result, } = this.props; const contentList = { iterations: ( <Card title="Result Iterations" style={{ marginTop: 32 }}> <Spin spinning={loadingSummary} tip="Loading Iterations..."> <TableFilterSelection onFilterTable={this.onFilterTable} filters={iterationParams} ports={iterationPorts} /> <Table style={{ marginTop: 16 }} columns={resultIterations ? resultIterations.columns : []} dataSource={resultIterations ? resultIterations.iterations : []} bordered /> </Spin> </Card> ), toc: ( <Card title="Table of Contents" style={{ marginTop: 32 }}> <Table columns={tocColumns} dataSource={tocResult} defaultExpandAllRows /> </Card> ), metadata: ( <Card title="Run Metadata" style={{ marginTop: 32 }}> {result.runMetadata && ( <List size="small" bordered dataSource={Object.entries(result.runMetadata)} renderItem={([label, value]) => ( <List.Item key={label}> <Typography.Text strong>{label}</Typography.Text> <Divider type="vertical" /> {value} </List.Item> )} /> )} </Card> ), tools: ( <Card title="Host Tools & Parameters" style={{ marginTop: 32 }}> {result.hostTools && result.hostTools.map(host => ( <List key={host.hostname} style={{ marginBottom: 16 }} size="small" bordered header={ <div> <Typography.Text strong>hostname</Typography.Text> <Divider type="vertical" /> {host.hostname} </div> } dataSource={Object.entries(host.tools)} renderItem={([label, value]) => ( <List.Item key={label}> <Typography.Text strong>{label}</Typography.Text> <Divider type="vertical" /> {value} </List.Item> )} /> ))} </Card> ), }; return ( <div style={{ display: 'flex', flexDirection: 'column' }}> <div> <PageHeaderLayout title={selectedResults[0]['run.name']} content={ <Tag color="blue" key={selectedControllers[0]}> {`controller: ${selectedControllers[0]}`} </Tag> } tabList={tabList} tabActiveKey={activeSummaryTab} onTabChange={this.onTabChange} /> {contentList[activeSummaryTab]} </div> </div> ); } } export default connect(() => ({}))(Summary);
code/web/node_modules/react-bootstrap/es/DropdownToggle.js
zyxcambridge/RecordExistence
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 React from 'react'; import classNames from 'classnames'; import Button from './Button'; import SafeAnchor from './SafeAnchor'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; var propTypes = { noCaret: React.PropTypes.bool, open: React.PropTypes.bool, title: React.PropTypes.string, useAnchor: React.PropTypes.bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = function (_React$Component) { _inherits(DropdownToggle, _React$Component); function DropdownToggle() { _classCallCheck(this, DropdownToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DropdownToggle.prototype.render = function render() { var _props = this.props; var noCaret = _props.noCaret; var open = _props.open; var useAnchor = _props.useAnchor; var bsClass = _props.bsClass; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? SafeAnchor : Button; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return React.createElement( Component, _extends({}, props, { role: 'button', className: classNames(className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && React.createElement('span', { className: 'caret' }) ); }; return DropdownToggle; }(React.Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; export default setBsClass('dropdown-toggle', DropdownToggle);
src/layouts/CoreLayout/CoreLayout.js
harijoe/redux-dollar
import React from 'react' import Header from '../../components/Header' import './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className='core-layout__viewport'> {children} </div> </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
actor-apps/app-web/src/app/components/common/MessageItem.react.js
Ajunboys/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import memoize from 'memoizee'; import classNames from 'classnames'; import emojify from 'emojify.js'; import hljs from 'highlight.js'; import marked from 'marked'; import emojiCharacters from 'emoji-named-characters'; import VisibilitySensor from 'react-visibility-sensor'; import AvatarItem from 'components/common/AvatarItem.react'; import Image from './Image.react'; import DialogActionCreators from 'actions/DialogActionCreators'; import { MessageContentTypes } from 'constants/ActorAppConstants'; let lastMessageSenderId = null, lastMessageContentType = null; var MessageItem = React.createClass({ displayName: 'MessageItem', propTypes: { message: React.PropTypes.object.isRequired, newDay: React.PropTypes.bool, index: React.PropTypes.number, onVisibilityChange: React.PropTypes.func }, mixins: [PureRenderMixin], onClick() { DialogActionCreators.selectDialogPeerUser(this.props.message.sender.peer.id); }, onVisibilityChange(isVisible) { this.props.onVisibilityChange(this.props.message, isVisible); }, render() { const message = this.props.message; const newDay = this.props.newDay; const isFirstMessage = this.props.index === 0; let header, visibilitySensor, leftBlock; let isSameSender = message.sender.peer.id === lastMessageSenderId && lastMessageContentType !== MessageContentTypes.SERVICE && message.content.content !== MessageContentTypes.SERVICE && !isFirstMessage && !newDay; let messageClassName = classNames({ 'message': true, 'row': true, 'message--same-sender': isSameSender }); if (isSameSender) { leftBlock = ( <div className="message__info text-right"> <time className="message__timestamp">{message.date}</time> <MessageItem.State message={message}/> </div> ); } else { leftBlock = ( <div className="message__info message__info--avatar"> <a onClick={this.onClick}> <AvatarItem image={message.sender.avatar} placeholder={message.sender.placeholder} title={message.sender.title}/> </a> </div> ); header = ( <header className="message__header"> <h3 className="message__sender"> <a onClick={this.onClick}>{message.sender.title}</a> </h3> <time className="message__timestamp">{message.date}</time> <MessageItem.State message={message}/> </header> ); } if (message.content.content === MessageContentTypes.SERVICE) { leftBlock = null; header = null; } if (this.props.onVisibilityChange) { visibilitySensor = <VisibilitySensor onChange={this.onVisibilityChange}/>; } lastMessageSenderId = message.sender.peer.id; lastMessageContentType = message.content.content; return ( <li className={messageClassName}> {leftBlock} <div className="message__body col-xs"> {header} <MessageItem.Content content={message.content}/> {visibilitySensor} </div> </li> ); } }); emojify.setConfig({ mode: 'img', img_dir: 'assets/img/emoji' // eslint-disable-line }); const mdRenderer = new marked.Renderer(); // target _blank for links mdRenderer.link = function(href, title, text) { let external, newWindow, out; external = /^https?:\/\/.+$/.test(href); newWindow = external || title === 'newWindow'; out = '<a href=\"' + href + '\"'; if (newWindow) { out += ' target="_blank"'; } if (title && title !== 'newWindow') { out += ' title=\"' + title + '\"'; } return (out + '>' + text + '</a>'); }; const markedOptions = { sanitize: true, breaks: true, highlight: function (code) { return hljs.highlightAuto(code).value; }, renderer: mdRenderer }; const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character)); const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) { return name.replace(/\+/g, '\\+'); }); const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi'); const processText = function(text) { let markedText = marked(text, markedOptions); // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127 const noPTag = markedText.replace(/<p>/g, '<p> '); let emojifiedText = emojify .replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':')); return emojifiedText; }; const memoizedProcessText = memoize(processText, { length: 1000, maxAge: 60 * 60 * 1000, max: 10000 }); MessageItem.Content = React.createClass({ propTypes: { content: React.PropTypes.object.isRequired }, render() { const content = this.props.content; // TODO: move all types to subcomponents let contentClassName = classNames('message__content', { 'message__content--service': content.content === MessageContentTypes.SERVICE, 'message__content--text': content.content === MessageContentTypes.TEXT, 'message__content--document': content.content === MessageContentTypes.DOCUMENT, 'message__content--unsupported': content.content === MessageContentTypes.UNSUPPORTED }); switch (content.content) { case 'service': return ( <div className={contentClassName}> {content.text} </div> ); case 'text': return ( <div className={contentClassName} dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}> </div> ); case 'photo': return ( <Image content={content} loadingClassName="message__content--photo" loadedClassName="message__content--photo message__content--photo--loaded"/> ); case 'document': contentClassName = classNames(contentClassName, 'row'); let availableActions; if (content.isUploading === true) { availableActions = <span>Loading...</span>; } else { availableActions = <a href={content.fileUrl}>Open</a>; } return ( <div className={contentClassName}> <div className="document row"> <div className="document__icon"> <i className="material-icons">attach_file</i> </div> <div className="col-xs"> <span className="document__filename">{content.fileName}</span> <div className="document__meta"> <span className="document__meta__size">{content.fileSize}</span> <span className="document__meta__ext">{content.fileExtension}</span> </div> <div className="document__actions"> {availableActions} </div> </div> </div> <div className="col-xs"></div> </div> ); default: } } }); MessageItem.State = React.createClass({ propTypes: { message: React.PropTypes.object.isRequired }, render() { const message = this.props.message; if (message.content.content === MessageContentTypes.SERVICE) { return null; } else { let icon = null; switch(message.state) { case 'pending': icon = <i className="status status--penging material-icons">access_time</i>; break; case 'sent': icon = <i className="status status--sent material-icons">done</i>; break; case 'received': icon = <i className="status status--received material-icons">done_all</i>; break; case 'read': icon = <i className="status status--read material-icons">done_all</i>; break; case 'error': icon = <i className="status status--error material-icons">report_problem</i>; break; default: } return ( <div className="message__status">{icon}</div> ); } } }); export default MessageItem;
packages/benchmarks/src/implementations/radium/Dot.js
css-components/styled-components
/* eslint-disable react/prop-types */ import Radium from 'radium'; import React from 'react'; const styles = { root: { position: 'absolute', cursor: 'pointer', width: 0, height: 0, borderColor: 'transparent', borderStyle: 'solid', borderTopWidth: 0, transform: 'translate(50%, 50%)', }, }; export default Radium(({ size, x, y, children, color }) => ( <div style={[ styles.root, { borderBottomColor: color, borderRightWidth: `${size / 2}px`, borderBottomWidth: `${size / 2}px`, borderLeftWidth: `${size / 2}px`, marginLeft: `${x}px`, marginTop: `${y}px`, }, ]} > {children} </div> ));
examples/counter/containers/App.js
mikekidder/redux-devtools
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import * as reducers from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(combineReducers(require('../reducers'))) ); } export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <CounterApp />} </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} visibleOnLoad={true} /> </DebugPanel> </div> ); } }
app/assets/scripts/views/location/metadata.js
openaq/openaq.org
import React from 'react'; import { PropTypes as T } from 'prop-types'; import moment from 'moment'; import { schemas } from 'openaq-data-format'; import config from '../../config'; const locationSchema = schemas.location; export default function Metadata({ loc, loc: { data: { metadata }, }, }) { if (!metadata) return null; const exclude = [ 'id', 'coordinates', 'city', 'country', 'instruments', 'parameters', 'attribution', ]; const allProperties = Object.keys(locationSchema.properties).filter(key => { return !exclude.includes(key) && metadata[key]; }); const propertiesMain = []; const propertiesSec = []; const length = Math.ceil(allProperties.length / 2); allProperties.forEach((key, i) => { const prop = locationSchema.properties[key]; prop.key = key; let val = metadata[prop.key]; if (prop.format && prop.format === 'date-time') { val = moment.utc(val).format('YYYY/MM/DD'); } if (prop.type && prop.type === 'boolean') { val = val ? 'Yes' : 'No'; } const sectionIndex = Math.floor(i / length); switch (sectionIndex) { case 0: { propertiesMain.push( <dt key={`${key}-${prop.title}`} className="metadata-detail-title"> {prop.title} </dt> ); propertiesMain.push(<dd key={`${key}-${prop.title}-val`}>{val}</dd>); break; } case 1: { propertiesSec.push( <dt key={`${key}-${prop.title}`} className="metadata-detail-title"> {prop.title} </dt> ); propertiesSec.push(<dd key={`${key}-${prop.title}-val`}>{val}</dd>); break; } } }); return ( <section className="fold" id="location-fold-metadata"> <div className="inner"> <header className="fold__header"> <h1 className="fold__title">Metadata</h1> </header> <div className="fold__body"> <div className="col-main"> <dl className="global-details-list">{propertiesMain}</dl> </div> <div className="col-sec"> <dl className="global-details-list">{propertiesSec}</dl> </div> </div> <div className="update-metadata-callout"> <p> Have more information about this location?{' '} <a href={`${config.metadata}/location/${loc.data.id}`} title="Update the metadata" > Update the metadata </a> </p> </div> </div> </section> ); } Metadata.propTypes = { loc: T.shape({ fetching: T.bool, fetched: T.bool, error: T.string, data: T.object, }), };
client/source/js/models/u_groups_m.js
Vladimir37/Planshark
import React from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; import {submitting, getData} from '../submitting.js'; import {Waiting, Error, Empty, Menu, Forbidden} from './templates.js'; import toast from '../toaster.js'; import {colorpick} from '../picker.js'; //responses var actions_r = ['Success!', 'Server error' , 'Required fields are empty', 'Incorrect color']; //RegExp var re_color = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"); //refresh groups list var refresh; var Creating = React.createClass({ getInitialState() { return null; }, componentDidMount() { setTimeout(colorpick, 100); }, submit(elem) { var ajax_data = getData(elem.target); if(!ajax_data) { toast(actions_r[2]); } else if(!re_color.test(ajax_data.color)) { toast(actions_r[3]); $(elem.target).parent().find('input[name="color"]').val(''); } else { submitting(ajax_data, '/api/user_manage/create', 'POST', function(data) { var response_status = +data; if(isNaN(response_status)) { response_status = 1; } if(response_status == 0) { toast(actions_r[0]); $(elem.target).parent().find('input[type="text"]').val(''); refresh(); } else { toast(actions_r[response_status]); } }, function(err) { toast(actions_r[1]); }); } }, switching() { $('.creatingFormBody').slideToggle(); }, render() { return <section className="creatingForm"> <article className="creatingFormHead" onClick={this.switching}>Creating user group</article> <article className="creatingFormBody"> <article className="creatingFormTop"> <input type="text" name="name" placeholder="Name" data-req="true" /> <input type="text" name="color" placeholder="Color" className="color_field" data-req="true" /> </article> <article className="creatingFormMiddle"> <table> <tr> <td><label>Creating tasks<input type="checkbox" name="creating" value="1" /></label></td> <td><label>Editing tasks<input type="checkbox" name="editing" value="1" /></label></td> </tr> <tr> <td><label>Reassignment tasks<input type="checkbox" name="reassignment" value="1" /></label></td> <td><label>Deleting tasks<input type="checkbox" name="deleting" value="1" /></label></td> </tr> <tr> <td><label>Users control<input type="checkbox" name="user_manage" value="1" /></label></td> <td><label>Tasks control<input type="checkbox" name="task_manage" value="1" /></label></td> </tr> <tr> <td><label>View all tasks<input type="checkbox" name="all_view" value="1"/></label></td> </tr> </table> </article> <button className="sub" onClick={this.submit}>Create</button> </article> </section>; } }); var UserGroup = React.createClass({ getInitialState() { var data = this.props.data; return { id: data.id, name: data.name, color: data.color, creating: data.creating, editing: data.editing, reassignment: data.reassignment, deleting: data.deleting, task_manage: data.t_group_manage, user_manage: data.u_group_manage, all_view: data.all_view, users_count: data.users.length, users: data.users } }, expand(elem) { var target = $(elem.target).closest('.user'); target.find('.user_additional').slideToggle(); }, actions(type) { return function(elem) { var target = $(elem.target).closest('.user'); target.find('.user_action:not(.user_' + type + ')').hide(); target.find('.user_' + type).slideToggle(); } }, submit(type) { var self = this; return function(elem) { var target = elem.target; var ajax_data = {}; ajax_data = getData(target); ajax_data.id = self.state.id; if(ajax_data) { submitting(ajax_data, '/api/user_manage/' + type, 'POST', function (data) { var response_status = +data; if (isNaN(response_status)) { response_status = 1; } toast(actions_r[response_status]); refresh(); }, function (err) { toast(actions_r[1]); }); } else if(!re_color.test(ajax_data.color)) { toast(actions_r[3]); $(elem.target).parent().find('input[name="color"]').val(''); } else { toast(actions_r[2]); } } }, selectBoxes(elem) { var target = $(elem.target); var elemParent = target.closest('.select_box'); elemParent.find('label').removeClass('active_elem'); target.parent().addClass('active_elem'); }, render() { var self = this; var group_classes = 'user user_group_color user_group_color_' + this.state.id; //all users in groups var users_list = []; this.state.users.forEach(function(task) { users_list.push(<article className="item_list">{task.name}</article>); }); var user_list_block = <article className="select_box"> {users_list} </article>; //all groups var groups_list = []; groups_list.push(<label className='active_elem'>No group<input type="radio" name="u_group" defaultChecked onChange={self.selectBoxes} value=''/></label>); this.props.all_groups.forEach(function(group) { if(group.id != self.state.id) { groups_list.push(<label>{group.name}<input type="radio" name="u_group" onChange={self.selectBoxes} value={group.id}/></label>); } }); var group_list_block = <article className="select_box"> {groups_list} </article>; var user_group_buttons = ''; if(this.state.id != 0) { user_group_buttons = <article className="user_bottom"> <button onClick={this.actions('edit')} className="solve_but">Edit</button> <button onClick={this.actions('delete')}>Delete</button> </article>; } //classes var create_c = this.state.creating ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var edit_c = this.state.editing ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var reassign_c = this.state.reassignment ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var delete_c = this.state.deleting ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var users_c = this.state.user_manage ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var tasks_c = this.state.task_manage ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; var view_c = this.state.all_view ? 'detect_elem active_elem' : 'detect_elem inactive_elem'; return <article className={group_classes}> <article className="user_top"> <article className="user_head"> <span className="user_name">{this.state.name}</span><br/> <span className="user_group">Users: {this.state.users_count}</span> </article> <article className="user_expand" onClick={this.expand}></article> </article> <article className="user_additional"> <article className="user_middle"> <article className="column_half"> <h3>Rights</h3> <article className={create_c}>Creating</article> <article className={edit_c}>Editing</article> <br/> <article className={reassign_c}>Reassignment</article> <article className={delete_c}>Deleting</article> <br/> <article className={users_c}>Users manage</article> <article className={tasks_c}>Tasks manage</article> <br/> <article className={view_c}>View all tasks</article> </article> <article className="column_half"> <h3>Users</h3> {user_list_block} </article> </article> {user_group_buttons} <article className="user_action user_edit hidden"> <form> <input type="text" name="name" placeholder="Name" defaultValue={this.state.name}/><br/> <input type="text" name="color" placeholder="Color" defaultValue={this.state.color} className="color_field"/><br/> <table> <tr> <td><label>Creating<input type="checkbox" name="creating" value="1" defaultChecked={this.state.creating}/></label></td> <td><label>Editing<input type="checkbox" name="editing" value="1" defaultChecked={this.state.editing}/></label></td> </tr> <tr> <td><label>Reassignment<input type="checkbox" name="reassignment" value="1" defaultChecked={this.state.reassignment}/></label></td> <td><label>Deleting<input type="checkbox" name="deleting" value="1" defaultChecked={this.state.deleting}/></label></td> </tr> <tr> <td><label>Users manage<input type="checkbox" name="user_manage" value="1" defaultChecked={this.state.user_manage}/></label></td> <td><label>Tasks manage<input type="checkbox" name="task_manage" value="1" defaultChecked={this.state.task_manage}/></label></td> </tr> <tr> <td><label>View all tasks<input type="checkbox" name="all_view" value="1" defaultChecked={this.state.all_view}/></label></td> </tr> </table> </form> <button onClick={this.submit('edit')}>Edit</button> </article> <article className="user_action user_delete hidden"> <h3>Move all users in {this.state.name} to other group?</h3> <form> {group_list_block} </form> <button onClick={this.submit('deleting')}>Delete</button> </article> </article> </article>; } }); var UsersGroupsList = React.createClass({ getInitialState() { return { received: false, error: false, status: null, groups: null, masters: null } }, receive() { var self = this; submitting(null, '/api/account/status', 'GET', function(status) { if (typeof status == 'string') { status = JSON.parse(status); } submitting(null, '/api/manage_data/users_group', 'GET', function (data) { if (typeof data == 'string') { data = JSON.parse(data); } submitting(null, '/api/data_viewing/masters', 'GET', function (masters) { if (typeof masters == 'string') { masters = JSON.parse(masters); } if (data.status == 0 && masters.status == 0) { data.body.reverse(); self.setState({ received: true, error: false, status, groups: data.body, masters: masters.body }); } else { self.setState({ error: true }); } }, function (err) { self.setState({ error: true }); }); }, function (err) { self.setState({ error: true }); }); }, function(err) { self.setState({ error: true }); }); }, render() { var self = this; refresh = this.receive; //first load if(!this.state.received && !this.state.error) { this.receive(); return <Waiting />; } else if(!this.state.received && this.state.error) { return <Error />; } else if(!Boolean(this.state.status.u_manage || this.state.room)) { return <Forbidden />; } //render else { var groups = []; //master group var master_group_data = { id: 0, name: 'Masters', color: 'none', creating: 1, editing: 1, reassignment: 1, deleting: 1, t_group_manage: 1, u_group_manage: 1, all_view: 1, users_count: this.state.masters.length, users: this.state.masters }; groups.push(<UserGroup key='0' data={master_group_data} all_groups={self.state.groups} />); //user groups this.state.groups.forEach(function(group) { groups.push(<UserGroup key={group.id + new Date().getTime()} data={group} all_groups={self.state.groups} />); }); return <article className="task_group_page_inner"> <Menu active="u_groups" data={this.state.status} /> <Creating /> {groups} </article>; } } }); export default UsersGroupsList;
index.android.js
kilimondjaro/react-native-couchsurfing-app
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class CouchsurfingApp extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('CouchsurfingApp', () => CouchsurfingApp);
src/client/components/profile/ProfileUpdateUser.component.js
DBCDK/content-first
import React from 'react'; import Spinner from '../general/Spinner/Spinner.component'; import T from '../base/T'; export default class ProfileUpdateUser extends React.Component { onSubmit = e => { const obj = { name: this.state.name, image: this.props.imageId, acceptedTerms: true, over13: this.props.acceptedAge }; e.preventDefault(); this.props.updateProfile(e, obj); }; constructor(props) { super(props); this.state = { name: props.name, acceptedAge: props.acceptedAge }; } componentDidUpdate(prevProps) { if (this.props.name !== prevProps.name) { this.setState({name: this.props.name}); } } render() { const checkActive = () => { if (this.props.deactivate) { return { color: 'var(--silver-chalice)', backgroundColor: 'var(--alto)' }; } return { color: 'var(--petroleum)', backgroundColor: 'var(--korn)' }; }; return ( <div className="d-flex"> <div className="profile__accept-buttonbuffer" /> <button className="btn Button profile__cancel-button" data-cy="profile-cancel-btn" onClick={this.props.cancelLogin} > <T component="general" name="cancel" /> </button> <button className={'btn Button profile__accept-button'} style={checkActive()} onClick={this.onSubmit} disabled={this.props.deactivate} data-cy="user-form-submit" > <T component="profile" name="acceptAndSubmit" /> {(this.props.isSaving && ( <Spinner size={12} color="white" style={{marginLeft: '10px'}} /> )) || ''} </button> </div> ); } }
js/components/loaders/Spinner.ios.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { ActivityIndicatorIOS } from 'react-native'; export default class SpinnerNB extends Component { prepareRootProps() { const type = { height: 80, }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { const getColor = () => { if (this.props.color) { return this.props.color; } else if (this.props.inverse) { return this.getTheme().inverseSpinnerColor; } return this.getTheme().defaultSpinnerColor; }; return ( <ActivityIndicatorIOS {...this.prepareRootProps()} color={getColor()} size={this.props.size ? this.props.size : 'large'} /> ); } }
node_modules/react-color/src/components/sketch-2/Sketch.js
ottomajik/react-demo
'use strict'; /* @flow */ import React from 'react'; import ReactCSS from 'reactcss'; import { Saturation, Hue, Alpha, Checkboard } from '../common'; import SketchFields from './SketchFields'; import SketchPresetColors from './SketchPresetColors'; export class Sketch extends ReactCSS.Component { constructor() { super(); this.handleChange = this.handleChange.bind(this); } classes(): any { return { 'default': { picker: { width: this.props.width, padding: '10px 10px 0', boxSizing: 'initial', background: '#fff', borderRadius: '4px', boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)', }, saturation: { width: '100%', paddingBottom: '75%', position: 'relative', overflow: 'hidden', }, Saturation: { radius: '3px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, controls: { display: 'flex', }, sliders: { padding: '4px 0', flex: '1', }, color: { width: '24px', height: '24px', position: 'relative', marginTop: '4px', marginLeft: '4px', borderRadius: '3px', }, activeColor: { Absolute: '0 0 0 0', borderRadius: '2px', background: 'rgba(' + this.props.rgb.r + ', ' + this.props.rgb.g + ', ' + this.props.rgb.b + ', ' + this.props.rgb.a + ')', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', zIndex: '2', }, hue: { position: 'relative', height: '10px', overflow: 'hidden', }, Hue: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, alpha: { position: 'relative', height: '10px', marginTop: '4px', overflow: 'hidden', }, Alpha: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, }, }; } handleChange(data: any) { this.props.onChange(data); } render(): any { return ( <div is="picker"> <div is="saturation"> <Saturation is="Saturation" {...this.props} onChange={ this.handleChange }/> </div> <div is="controls" className="flexbox-fix"> <div is="sliders"> <div is="hue"> <Hue is="Hue" {...this.props} onChange={ this.handleChange } /> </div> <div is="alpha"> <Alpha is="Alpha" {...this.props} onChange={ this.handleChange } /> </div> </div> <div is="color"> <div is="activeColor"/> <Checkboard /> </div> </div> <div is="fields"> <SketchFields {...this.props} onChange={ this.handleChange } /> </div> <div is="presets"> <SketchPresetColors colors={ this.props.presetColors } onClick={ this.handleChange } /> </div> </div> ); } } Sketch.defaultProps = { presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF'], width: 200, }; export default Sketch;
components/Table/Holders/Card/Modifiers/Face.js
mattbajorek/blackJackReact
import React, { Component } from 'react'; import center from './Positions/posFace'; import selector from './Positions/symbol'; class Face extends Component { render() { let symbol = this.props.symbol; let number = this.props.number; // Fixes club positioning issue if (symbol === '\u2663') { center[2]['top'] = '68.5714285714%' } else { center[2]['top'] = '65.7142857143%' } return ( <div> {center.map((x,i) => { var insert; if (i === 0) insert = <img src={require('../../../../../images/'+ selector(symbol) + number + '.png')} /> else insert = symbol return <div key={i} style={x} className="center-symbol">{insert}</div>; })} </div> ) } } export default Face
test/GridSpec.js
pombredanne/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ReactDOM from 'react-dom'; import Grid from '../src/Grid'; describe('Grid', () => { it('uses "div" by default', () => { let instance = ReactTestUtils.renderIntoDocument( <Grid /> ); assert.equal(ReactDOM.findDOMNode(instance).nodeName, 'DIV'); }); it('has "container" class by default', () => { let instance = ReactTestUtils.renderIntoDocument( <Grid /> ); assert.equal(ReactDOM.findDOMNode(instance).className, 'container'); }); it('turns grid into "full-width" layout via "fluid" property set', () => { let instance = ReactTestUtils.renderIntoDocument( <Grid fluid /> ); assert.equal(ReactDOM.findDOMNode(instance).className, 'container-fluid'); }); it('should merge additional classes passed in', () => { let instance = ReactTestUtils.renderIntoDocument( <Grid className="whatever" fluid /> ); assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bwhatever\b/)); assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bcontainer-fluid\b/)); }); it('allows custom elements instead of "div"', () => { let instance = ReactTestUtils.renderIntoDocument( <Grid componentClass='section' /> ); assert.equal(ReactDOM.findDOMNode(instance).nodeName, 'SECTION'); }); });
app/javascript/mastodon/components/timeline_hint.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; const TimelineHint = ({ resource, url }) => ( <div className='timeline-hint'> <strong><FormattedMessage id='timeline_hint.remote_resource_not_displayed' defaultMessage='{resource} from other servers are not displayed.' values={{ resource }} /></strong> <br /> <a href={url} target='_blank'><FormattedMessage id='account.browse_more_on_origin_server' defaultMessage='Browse more on the original profile' /></a> </div> ); TimelineHint.propTypes = { resource: PropTypes.node.isRequired, url: PropTypes.string.isRequired, }; export default TimelineHint;
test/async-suggestions/AutosuggestApp.js
JacksonKearl/react-autosuggest-ie11-compatible
import React, { Component } from 'react'; import sinon from 'sinon'; import Autosuggest from '../../src/Autosuggest'; import languages from '../plain-list/languages'; import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js'; const getMatchingLanguages = value => { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp('^' + escapedValue, 'i'); return languages.filter(language => regex.test(language.name)); }; let app = null; export const getSuggestionValue = sinon.spy(suggestion => suggestion.name); export const renderSuggestion = sinon.spy(suggestion => suggestion.name); export const onChange = sinon.spy((event, { newValue }) => { app.setState({ value: newValue }); }); const loadSuggestions = value => { setTimeout(() => { if (value === app.state.value) { app.setState({ suggestions: getMatchingLanguages(value) }); } }, 100); }; export const onSuggestionsFetchRequested = sinon.spy(({ value }) => { loadSuggestions(value); }); export const onSuggestionsClearRequested = sinon.spy(() => { app.setState({ suggestions: [] }); }); export default class AutosuggestApp extends Component { constructor() { super(); app = this; this.state = { value: '', suggestions: [] }; } render() { const { value, suggestions } = this.state; const inputProps = { value, onChange }; return ( <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={onSuggestionsFetchRequested} onSuggestionsClearRequested={onSuggestionsClearRequested} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} highlightFirstSuggestion={true} /> ); } }
app/javascript/mastodon/features/public_timeline/index.js
yukimochi/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandPublicTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectPublicStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']); const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']); const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, onlyRemote, }; }; export default @connect(mapStateToProps) @injectIntl class PublicTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasUnread: PropTypes.bool, onlyMedia: PropTypes.bool, onlyRemote: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia, onlyRemote } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) { const { dispatch, onlyMedia, onlyRemote } = this.props; this.disconnect(); dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote })); } render () { const { intl, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='globe' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} trackScroll={!pinned} scrollKey={`public_timeline-${columnId}`} emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />} bindToDocument={!multiColumn} /> </Column> ); } }
components/Deck/ActivityFeedPanel/ActivityItem.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import likeActivity from '../../../actions/activityfeed/likeActivity'; import {formatDate} from './util/ActivityFeedUtil'; import {navigateAction} from 'fluxible-router'; import {connectToStores} from 'fluxible-addons-react'; import cheerio from 'cheerio'; import DeckTreeStore from '../../../stores/DeckTreeStore'; import Util from '../../common/Util'; import {getLanguageName} from '../../../common'; import {FormattedMessage, defineMessages} from 'react-intl'; class ActivityItem extends React.Component { handleLike() { this.context.executeAction(likeActivity, { id: this.props.activity.id }); } //return the position of the node in the deck getPath(node){ const flatTree = this.props.DeckTreeStore.flatTree; let path = ''; for (let i=0; i < flatTree.size; i++) { if (flatTree.get(i).get('type') === node.content_kind && flatTree.get(i).get('id') === node.content_id) { path = flatTree.get(i).get('path'); let nodeSelector = {id: this.props.selector.id, stype: node.content_kind, sid: node.content_id, spath: path}; let nodeURL = Util.makeNodeURL(nodeSelector, 'deck', 'view', undefined, undefined, true); return nodeURL; } } return path; } handleRefClick(e) { e.preventDefault(); this.context.executeAction(navigateAction, { url: this.getPath(this.props.activity) }); // return false; } render() { const node = this.props.activity; let IconNode = ''; let SummaryNode = ''; const DateDiv = ( <div className="date"> {formatDate(node.timestamp)} </div> ); const commentStyles = { fontStyle: 'italic', fontWeight: 400 }; const cheerioContentName = (node.content_name) ? cheerio.load(node.content_name).text() : ''; const viewPath = ((node.content_kind === 'slide') ? '/deck/' + this.props.selector.id + '/slide/' : '/deck/') + node.content_id; let contentType = node.content_kind; if (contentType === 'deck') { contentType = <FormattedMessage id='activity.feed.item.deck' defaultMessage='deck'/>; } else if (contentType === 'slide') { contentType = <FormattedMessage id='activity.feed.item.slide' defaultMessage='slide'/>; } const nodeRef = (node.content_kind === this.props.selector.stype && node.content_id.split('-')[0] === this.props.selector.sid.split('-')[0]) ? (<span><FormattedMessage id='activity.feed.item.this' defaultMessage='this'/> {contentType}</span>) : (<span>{contentType} <a href={this.getPath(node)} onClick={this.handleRefClick.bind(this)}>{cheerioContentName}</a></span>); if (node.user_id === '0'|| node.user_id === 'undefined') { node.user_id = undefined; } switch (node.activity_type) { case 'translate': IconNode = (<i className="ui translate icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.translated' defaultMessage='translated'/> {nodeRef} <FormattedMessage id='activity.feed.item.to' defaultMessage='to'/> {/*<a href={'/slideview/' + node.translation_info.content_id}>{node.translation_info.language}</a>*/} {getLanguageName(node.translation_info.language)} <br/> {DateDiv} </div> ); break; case 'share': IconNode = (<i className="ui share alternate icon"></i>); const onPlatform = (node.share_info.platform === 'E-mail') ? 'by E-mail' : (' on ' + node.share_info.platform); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.shared' defaultMessage='shared'/> {nodeRef} {onPlatform} <br/> {DateDiv} </div> ); break; case 'add': IconNode = (<i className="ui pencil alternate icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.created' defaultMessage='created'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'edit': IconNode = (<i className="ui edit icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.edited' defaultMessage='edited'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'move': IconNode = (<i className="ui arrows alternate icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.moved' defaultMessage='moved'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'comment': IconNode = (<i className="ui comment outline icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.commented' defaultMessage='commented on'/> {nodeRef} <br/> <span style={commentStyles}>{'"' + node.comment_info.text + '"'}</span> <br/> {DateDiv} </div> ); break; case 'reply': IconNode = (<i className="ui comment outline icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <span> <FormattedMessage id='activity.feed.item.reply' defaultMessage='replied to a comment on'/> </span> {nodeRef} <br/> <span style={commentStyles}>{'"' + node.comment_info.text + '"'}</span> <br/> {DateDiv} </div> ); break; case 'use': IconNode = (<i className="ui clone outline icon"></i>); const title = (node.use_info.target_name !== '') ? node.use_info.target_name : node.use_info.target_id; SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.used' defaultMessage='used'/> {nodeRef} <FormattedMessage id='activity.feed.item.indeck' defaultMessage='in deck'/> <a href={'/deck/' + node.use_info.target_id}>{title}</a> <br/> {DateDiv} </div> ); break; case 'attach': IconNode = (<i className="ui attach icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.attached' defaultMessage='attached'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'rate'://TODO modify rate display IconNode = (<i className="ui star outline icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.rated' defaultMessage='rated'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'react'://TODO modify react display IconNode = (<i className="ui thumbs outline up icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ?node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.liked' defaultMessage='liked'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'download': IconNode = (<i className="ui download icon"></i>); SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.downloaded' defaultMessage='downloaded'/> {nodeRef} <br/> {DateDiv} </div> ); break; case 'fork': IconNode = (<i className="ui fork icon"></i>); const forkRef = (node.fork_info) ? (<span>, creating a <a href={'/deck/' + node.fork_info.content_id}>new deck</a></span>) : ''; SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <FormattedMessage id='activity.feed.item.forked' defaultMessage='forked'/> {nodeRef}{forkRef} <br/> {DateDiv} </div> ); break; case 'delete': IconNode = (<i className="ui trash alternate icon"></i>); const cheerioDeletedName = (node.delete_info.content_name) ? cheerio.load(node.delete_info.content_name).text() : ''; SummaryNode = ( <div className="summary"> <a className="user" href={node.user_id ? '/user/' + node.user_id : ''} target="_blank"> {node.author ? node.author.displayName || node.author.username : 'unknown'} </a> <span> <FormattedMessage id='activity.feed.item.deleted' defaultMessage='deleted'/> {node.delete_info.content_kind + ' "' + cheerioDeletedName + '" '}</span> <br/> <span><FormattedMessage id='activity.feed.item.from' defaultMessage='from'/> {nodeRef}</span> <br/> {DateDiv} </div> ); break; default: } return ( <div className="ui feed"> <div className="event"> <div className="activity-icon"> {IconNode} </div> <div className="content" style={{marginLeft: '1em'}}> {SummaryNode} </div> </div> </div> ); } } ActivityItem.contextTypes = { executeAction: PropTypes.func.isRequired }; ActivityItem = connectToStores(ActivityItem, [DeckTreeStore], (context, props) => { return { DeckTreeStore: context.getStore(DeckTreeStore).getState() }; }); export default ActivityItem;
lib/DragContainer.js
deanmcpherson/react-native-drag-drop
import React from 'react'; import { View, PanResponder, Modal, Easing, Animated, TouchableOpacity, TouchableWithoutFeedback, } from 'react-native'; global.Easing = Easing; const allOrientations = [ 'portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right' ]; class DragModal extends React.Component { render() { let {startPosition} = this.props.content; return <Modal transparent={true} supportedOrientations={allOrientations}> <TouchableWithoutFeedback onPressIn={this.props.drop}> <Animated.View style={this.props.location.getLayout()}> {this.props.content.children} </Animated.View> </TouchableWithoutFeedback> </Modal> } } class DragContainer extends React.Component { constructor(props) { super(props); this.displayName = 'DragContainer'; this.containerLayout; let location = new Animated.ValueXY(); this.state = { location } this.dropZones = []; this.draggables = []; this.onDrag = this.onDrag.bind(this); this._handleDragging = this._handleDragging.bind(this); this._handleDrop = this._handleDrop.bind(this); this._listener = location.addListener(this._handleDragging); this.updateZone = this.updateZone.bind(this); this.removeZone = this.removeZone.bind(this); } static propTypes = { onDragStart: React.PropTypes.func, onDragEnd: React.PropTypes.func, } componentWillUnmount() { if (this._listener) this.state.location.removeListener(this._listener); } getDragContext() { return { dropZones: this.dropZones, onDrag: this.onDrag, container: this.containerLayout, dragging: this.state.draggingComponent, updateZone: this.updateZone, removeZone: this.removeZone } } getChildContext() { return {dragContext: this.getDragContext()} } static childContextTypes = { dragContext: React.PropTypes.any } updateZone(details) { let zone = this.dropZones.find(x => x.ref === details.ref); if (!zone) { this.dropZones.push(details); } else { let i = this.dropZones.indexOf(zone); this.dropZones.splice(i, 1, details); } } removeZone(ref) { let i = this.dropZones.find(x => x.ref === ref); if (i !== -1) { this.dropZones.splice(i, 1); } } inZone({x, y}, zone) { return zone.x <= x && (zone.width + zone.x) >= x && zone.y <= y && (zone.height + zone.y) >= y; } _addLocationOffset(point) { if (!this.state.draggingComponent) return point; return { x: point.x + (this.state.draggingComponent.startPosition.width / 2), y: point.y + (this.state.draggingComponent.startPosition.height / 2), } } _handleDragging(point) { this._point = point; if (this._locked || !point) return; this.dropZones.forEach((zone) => { if (this.inZone(point, zone)) { zone.onEnter(point); } else { zone.onLeave(point); } }) } _handleDrop() { let hitZones = [] this.dropZones.forEach((zone) => { if (!this._point) return; if (this.inZone(this._point, zone)) { hitZones.push(zone); zone.onDrop(this.state.draggingComponent.data); } }) if (this.props.onDragEnd) this.props.onDragEnd(this.state.draggingComponent, hitZones); if (!hitZones.length && this.state.draggingComponent && this.state.draggingComponent.ref) { this._locked = true; return Animated .timing(this.state.location, { duration: 400, easing:Easing.elastic(1), toValue: { x: 0, //this._offset.x - x, y: 0 //his._offset.y - y } }).start(() => { this._locked = false; this._handleDragging({x: -100000, y: -100000}); this.setState({ draggingComponent: null }) }) } this._handleDragging({x: -100000, y: -100000}); this.setState({ draggingComponent: null }) } componentWillMount() { this._panResponder = PanResponder.create({ // Ask to be the responder: onStartShouldSetPanResponder: () => { if (this.state.draggingComponent) { this._handleDrop(); } return false }, onMoveShouldSetPanResponder: (evt, gestureState) => !!this.state.draggingComponent, // onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderMove: (...args) => Animated.event([null, { dx: this.state.location.x, // x,y are Animated.Value dy: this.state.location.y, }]).apply(this, args), onPanResponderTerminationRequest: (evt, gestureState) => true, onPanResponderRelease: (evt, gestureState) => { if (!this.state.draggingComponent) return; //Ensures we exit all of the active drop zones this._handleDrop(); } }); } onDrag(ref, children, data) { ref.measure((...args) => { if (this._listener) this.state.location.removeListener(this._listener); let location = new Animated.ValueXY(); this._listener = location.addListener(args => this._handleDragging(this._addLocationOffset(args))); this._offset = {x: args[4], y: args[5]}; location.setOffset(this._offset); this.setState({ location, draggingComponent: { ref, data, children: React.Children.map(children, child => { return React.cloneElement(child, {dragging: true}) }), startPosition: { x: args[4], y: args[5], width: args[2], height: args[3] } }}, () => { if (this.props.onDragStart) this.props.onDragStart(this.state.draggingComponent); }) }); } render() { return <View style={[{flex: 1}, this.props.style]} onLayout={e => this.containerLayout = e.nativeEvent.layout} {...this._panResponder.panHandlers}> {this.props.children} {this.state.draggingComponent ? <DragModal content={this.state.draggingComponent} location={this.state.location} drop={this._handleDrop} /> : null} </View>; } } export default DragContainer;
blueprints/layout/files/__test__/layouts/__name__Layout.spec.js
dingchaoyan1983/ReactRedux
import React from 'react' describe('(Layout) <%= pascalEntityName %>', () => { it('should exist', () => { }) })
blueprints/view/files/__root__/views/__name__View/__name__View.js
PetrosGit/poker-experiment
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/svg-icons/av/pause-circle-filled.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPauseCircleFilled = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z"/> </SvgIcon> ); AvPauseCircleFilled = pure(AvPauseCircleFilled); AvPauseCircleFilled.displayName = 'AvPauseCircleFilled'; AvPauseCircleFilled.muiName = 'SvgIcon'; export default AvPauseCircleFilled;
Prac/js/ClientApp.js
JRFrazier/complete-intro-to-react
import React from 'react' import { render } from 'react-dom' import '../public/normalize.css' import '../public/style.css' const App = React.createClass ({ render () { return ( <div className='app'> <div className='landing'> <h1>svideo</h1> <input type='text' placeholder='Search' /> <a> or Growse All</a> </div> </div> ) } }) render(<App />, document.getElementById('app'))
node_modules/react-bootstrap/es/Button.js
rblin081/drafting-client
import _Object$values from 'babel-runtime/core-js/object/values'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _extends from 'babel-runtime/helpers/extends'; 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 PropTypes from 'prop-types'; import elementType from 'prop-types-extra/lib/elementType'; import { bsClass, bsSizes, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import { Size, State, Style } from './utils/StyleConfig'; import SafeAnchor from './SafeAnchor'; var propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, block: PropTypes.bool, onClick: PropTypes.func, componentClass: elementType, href: PropTypes.string, /** * Defines HTML button type attribute * @defaultValue 'button' */ type: PropTypes.oneOf(['button', 'reset', 'submit']) }; var defaultProps = { active: false, block: false, disabled: false }; var Button = function (_React$Component) { _inherits(Button, _React$Component); function Button() { _classCallCheck(this, Button); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Button.prototype.renderAnchor = function renderAnchor(elementProps, className) { return React.createElement(SafeAnchor, _extends({}, elementProps, { className: classNames(className, elementProps.disabled && 'disabled') })); }; Button.prototype.renderButton = function renderButton(_ref, className) { var componentClass = _ref.componentClass, elementProps = _objectWithoutProperties(_ref, ['componentClass']); var Component = componentClass || 'button'; return React.createElement(Component, _extends({}, elementProps, { type: elementProps.type || 'button', className: className })); }; Button.prototype.render = function render() { var _extends2; var _props = this.props, active = _props.active, block = _props.block, className = _props.className, props = _objectWithoutProperties(_props, ['active', 'block', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = { active: active }, _extends2[prefix(bsProps, 'block')] = block, _extends2)); var fullClassName = classNames(className, classes); if (elementProps.href) { return this.renderAnchor(elementProps, fullClassName); } return this.renderButton(elementProps, fullClassName); }; return Button; }(React.Component); Button.propTypes = propTypes; Button.defaultProps = defaultProps; export default bsClass('btn', bsSizes([Size.LARGE, Size.SMALL, Size.XSMALL], bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY, Style.LINK]), Style.DEFAULT, Button)));
packages/material-ui-icons/src/CropSquare.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H6V6h12v12z" /></g> , 'CropSquare');
src/components/App.spec.js
chrisvogt/teacher-salaries
import React from 'react' import { shallow } from 'enzyme' import App from './App' const setup = () => { return shallow(<App />) } it('renders without crashing', () => { setup() }) it('renders with the correct attributes', () => { const wrapper = setup() const notice = <div className='App' /> expect(wrapper.find('.App').length).toEqual(1) })
src/lens/positive-space/index.js
ethanselzer/react-image-magnify
import React, { Component } from 'react'; import objectAssign from 'object-assign'; import LensPropTypes from '../../prop-types/Lens'; import clamp from 'clamp'; import dataUri from './assets/textured-lens-data-uri'; export default class PositiveSpaceLens extends Component { static propTypes = LensPropTypes static defaultProps = { style: {} } get dimensions() { const { cursorOffset: { x: cursorOffsetX, y: cursorOffsetY } } = this.props; return { width: cursorOffsetX * 2, height: cursorOffsetY * 2 }; } get positionOffset() { const { cursorOffset: { x: cursorOffsetX, y: cursorOffsetY }, position: { x: positionX, y: positionY }, smallImage: { height: imageHeight, width: imageWidth } } = this.props; const { width, height } = this.dimensions const top = positionY - cursorOffsetY; const left = positionX - cursorOffsetX; const maxTop = imageHeight - height; const maxLeft = imageWidth - width; const minOffset = 0; return { top: clamp(top, minOffset, maxTop), left: clamp(left, minOffset, maxLeft) }; } get defaultStyle() { const { fadeDurationInMs } = this.props; return { transition: `opacity ${fadeDurationInMs}ms ease-in`, backgroundImage: `url(${dataUri})` }; } get userSpecifiedStyle() { const { style } = this.props; return style; } get isVisible() { const { isActive, isPositionOutside } = this.props; return ( isActive && !isPositionOutside ); } get priorityStyle() { const { width, height } = this.dimensions const { top, left } = this.positionOffset return { position: 'absolute', top: `${top}px`, left: `${left}px`, width: `${width}px`, height: `${height}px`, opacity: this.isVisible ? 1 : 0 }; } get compositStyle() { return objectAssign( this.defaultStyle, this.userSpecifiedStyle, this.priorityStyle ); } render() { return ( <div style={this.compositStyle} /> ); } }
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/__tests__/ButtonDropdown.spec.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import { mount } from 'enzyme'; import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from '../'; describe('ButtonDropdown', () => { let isOpen; let toggle; beforeEach(() => { isOpen = false; toggle = () => { isOpen = !isOpen; }; }); it('should render a single child', () => { const wrapper = mount(<ButtonDropdown isOpen={isOpen} toggle={toggle}>Ello world</ButtonDropdown>); expect(wrapper.find('.btn-group').hostNodes().text()).toBe('Ello world'); expect(wrapper.find('.btn-group').hostNodes().length).toBe(1); }); it('should render multiple children when isOpen', () => { isOpen = true; const wrapper = mount( <ButtonDropdown isOpen={isOpen} toggle={toggle}> <DropdownToggle>Toggle</DropdownToggle> <DropdownMenu> <DropdownItem>Test</DropdownItem> </DropdownMenu> </ButtonDropdown> ); expect(wrapper.find('.btn').hostNodes().text()).toBe('Toggle'); expect(wrapper.find('.btn-group').hostNodes().length).toBe(1); expect(wrapper.find('.dropdown-item').hostNodes().length).toBe(1); expect(wrapper.childAt(0).childAt(0).childAt(0).children().length).toBe(2); }); });
src/MyProfilePage/Team/Team.js
velesin/retroinator
import React from 'react'; import { Link } from 'react-router-dom'; import { Icon, ICONS } from '../../shared'; export function Team({ team }) { return ( <Link to={`/team/${team.$key}`} className="MyProfilePage_Teams_Team"> <Icon>{ICONS.TEAM}</Icon> <div>{team.name}</div> </Link> ); }
src/js/components/Drop/stories/AllNotStretched.js
grommet/grommet
import React from 'react'; import PropTypes from 'prop-types'; import { Box, Drop, Text, ThemeContext } from 'grommet'; const OneDrop = ({ align, target }) => ( <Drop align={align} target={target} stretch={false}> <Box pad="small" /> </Drop> ); OneDrop.propTypes = { align: PropTypes.shape({}).isRequired, target: PropTypes.shape({}).isRequired, }; const Set = ({ aligns, label }) => { const [target, setTarget] = React.useState(); const targetRef = React.useCallback(setTarget, [setTarget]); return ( <Box border pad="small"> <Text>{label}</Text> <Box margin="xlarge" background="dark-3" pad={{ horizontal: 'large', vertical: 'medium' }} align="center" justify="center" ref={targetRef} > &nbsp; </Box> {target && ( <> {aligns.map((align, index) => ( <OneDrop // eslint-disable-next-line react/no-array-index-key key={index} align={align} target={target} /> ))} </> )} </Box> ); }; Set.propTypes = { aligns: PropTypes.arrayOf(PropTypes.shape({})).isRequired, label: PropTypes.string.isRequired, }; const AllDrops = () => ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <ThemeContext.Extend value={{ global: { drop: { background: { color: 'white', opacity: 'medium' } }, }, }} > <Box direction="row" wrap pad="large" align="center" justify="center"> <Set label="left: left" aligns={[ { top: 'top', left: 'left' }, { top: 'bottom', left: 'left' }, { bottom: 'top', left: 'left' }, { bottom: 'bottom', left: 'left' }, ]} /> <Set label="left: right" aligns={[ { top: 'top', left: 'right' }, { top: 'bottom', left: 'right' }, { bottom: 'top', left: 'right' }, { bottom: 'bottom', left: 'right' }, ]} /> <Set label="(center horizontal)" aligns={[ { top: 'top' }, { top: 'bottom' }, { bottom: 'top' }, { bottom: 'bottom' }, ]} /> <Set label="right: left" aligns={[ { top: 'top', right: 'left' }, { top: 'bottom', right: 'left' }, { bottom: 'top', right: 'left' }, { bottom: 'bottom', right: 'left' }, ]} /> <Set label="right: right" aligns={[ { top: 'top', right: 'right' }, { top: 'bottom', right: 'right' }, { bottom: 'top', right: 'right' }, { bottom: 'bottom', right: 'right' }, ]} /> <Set label="top: top" aligns={[ { left: 'left', top: 'top' }, { left: 'right', top: 'top' }, { right: 'left', top: 'top' }, { right: 'right', top: 'top' }, ]} /> <Set label="top: bottom" aligns={[ { left: 'left', top: 'bottom' }, { left: 'right', top: 'bottom' }, { right: 'left', top: 'bottom' }, { right: 'right', top: 'bottom' }, ]} /> <Set label="(center vertical)" aligns={[ { left: 'left' }, { left: 'right' }, { right: 'left' }, { right: 'right' }, ]} /> <Set label="bottom: top" aligns={[ { left: 'left', bottom: 'top' }, { left: 'right', bottom: 'top' }, { right: 'left', bottom: 'top' }, { right: 'right', bottom: 'top' }, ]} /> <Set label="bottom: bottom" aligns={[ { left: 'left', bottom: 'bottom' }, { left: 'right', bottom: 'bottom' }, { right: 'left', bottom: 'bottom' }, { right: 'right', bottom: 'bottom' }, ]} /> <Set label="(center vertical and horizontal)" aligns={[{}]} /> </Box> </ThemeContext.Extend> // </Grommet> ); export const AllNotStretched = () => <AllDrops />; AllNotStretched.storyName = 'All not stretched'; export default { title: 'Controls/Drop/All not stretched', };
src/index.js
sebpearce/cycad-react
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { App } from './App'; import { Provider } from 'react-redux'; import createBrowserHistory from 'history/createBrowserHistory'; import { store } from './store'; import { saveState } from './localStorage'; import { throttle } from 'lodash'; import './index.scss'; const history = createBrowserHistory(); ReactDOM.render( <Provider store={store}> <Router history={history}> <App /> </Router> </Provider>, document.getElementById('root'), ); store.subscribe(throttle(() => { saveState({ transactions: store.getState().transactions, categories: store.getState().categories, }); }, 1000));
src/assets/icons/check.js
HackArdennes2017/Project06
import React from 'react' export default props => <svg viewBox="0 0 100 125" {...props}> <path d="M47.215 8.002a42.128 42.128 0 0 0-11.063 1.437C13.799 15.43.476 38.522 6.466 60.877c5.99 22.355 29.083 35.677 51.438 29.687 22.355-5.99 35.677-29.082 29.687-51.437a4 4 0 1 0-7.719 2.062c4.871 18.179-5.852 36.785-24.03 41.656-18.18 4.871-36.786-5.852-41.657-24.03-4.871-18.18 5.852-36.786 24.031-41.657a34.018 34.018 0 0 1 28.844 5.375 4.003 4.003 0 1 0 4.719-6.469 41.972 41.972 0 0 0-24.563-8.062zm43.563 2.969a4 4 0 0 0-2.72 1.28C77.516 23.284 56.444 46.077 44.747 58.409L30.684 46.002a4.007 4.007 0 1 0-5.313 6l17 15a4 4 0 0 0 5.563-.25c11.185-11.702 34.869-37.452 45.906-49a4 4 0 0 0-3.062-6.781z" overflow="visible" style={{ textIndent: '0', textTransform: 'none', direction: 'ltr', blockProgression: 'tb', baselineShift: 'baseline', color: '#000', enableBackground: 'accumulate', }} /> </svg>
src/helpers/__tests__/getDataDependencies-test.js
ThatCheck/AutoLib
import { expect } from 'chai'; import React from 'react'; import { div } from 'react-dom'; import getDataDependencies from '../getDataDependencies'; describe('getDataDependencies', () => { let getState; let dispatch; let location; let params; let CompWithFetchData; let CompWithNoData; let CompWithFetchDataDeferred; const NullComponent = null; beforeEach(() => { getState = 'getState'; dispatch = 'dispatch'; location = 'location'; params = 'params'; CompWithNoData = () => <div />; CompWithFetchData = () => <div />; CompWithFetchData.fetchData = (_getState, _dispatch, _location, _params) => { return `fetchData ${_getState} ${_dispatch} ${_location} ${_params}`; }; CompWithFetchDataDeferred = () => <div />; CompWithFetchDataDeferred.fetchDataDeferred = (_getState, _dispatch, _location, _params) => { return `fetchDataDeferred ${_getState} ${_dispatch} ${_location} ${_params}`; }; }); it('should get fetchDatas', () => { const deps = getDataDependencies([ NullComponent, CompWithFetchData, CompWithNoData, CompWithFetchDataDeferred ], getState, dispatch, location, params); expect(deps).to.deep.equal([ 'fetchData getState dispatch location params' ]); }); it('should get fetchDataDeferreds', () => { const deps = getDataDependencies([ NullComponent, CompWithFetchData, CompWithNoData, CompWithFetchDataDeferred ], getState, dispatch, location, params, true); expect(deps).to.deep.equal([ 'fetchDataDeferred getState dispatch location params' ]); }); });
src/components/CardSection.js
shabib87/Albums
import React from 'react'; import { View } from 'react-native'; const CardSection = (props) => ( <View style={styles.containerStyle}> {props.children} </View> ); const styles = { containerStyle: { borderBottomWidth: 1, padding: 5, backgroundColor: '#fff', justifyContent: 'flex-start', flexDirection: 'row', borderColor: '#ddd', position: 'relative' } }; export default CardSection;
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
gaolichuang/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import classnames from 'classnames'; import ActorClient from 'utils/ActorClient'; import confirm from 'utils/confirm' import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; import Fold from 'components/common/Fold.React'; const getStateFromStores = (userId) => { const thisPeer = PeerStore.getUserPeer(userId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer) }; }; @ReactMixin.decorate(IntlMixin) class UserProfile extends React.Component { static propTypes = { user: React.PropTypes.object.isRequired }; constructor(props) { super(props); this.state = _.assign({ isActionsDropdownOpen: false }, getStateFromStores(props.user.id)); DialogStore.addNotificationsListener(this.onChange); } componentWillUnmount() { DialogStore.removeNotificationsListener(this.onChange); } componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.user.id)); } addToContacts = () => { ContactActionCreators.addContact(this.props.user.id); }; removeFromContacts = () => { const { user } = this.props; const confirmText = 'You really want to remove ' + user.name + ' from your contacts?'; confirm(confirmText).then( () => ContactActionCreators.removeContact(user.id) ); }; onNotificationChange = (event) => { const { thisPeer } = this.state; DialogActionCreators.changeNotificationsEnabled(thisPeer, event.target.checked); }; onChange = () => { const { user } = this.props; this.setState(getStateFromStores(user.id)); }; toggleActionsDropdown = () => { const { isActionsDropdownOpen } = this.state; if (!isActionsDropdownOpen) { this.setState({isActionsDropdownOpen: true}); document.addEventListener('click', this.closeActionsDropdown, false); } else { this.closeActionsDropdown(); } }; closeActionsDropdown = () => { this.setState({isActionsDropdownOpen: false}); document.removeEventListener('click', this.closeActionsDropdown, false); }; clearChat = (uid) => { confirm('Do you really want to delete this conversation?').then( () => { const peer = ActorClient.getUserPeer(uid); DialogActionCreators.clearChat(peer); }, () => { } ); }; deleteChat = (uid) => { confirm('Do you really want to delete this conversation?').then( () => { const peer = ActorClient.getUserPeer(uid); DialogActionCreators.deleteChat(peer); }, () => { } ); }; render() { const { user } = this.props; const { isNotificationsEnabled, isActionsDropdownOpen } = this.state; const actions = (user.isContact === false) ? ( <li className="dropdown__menu__item" onClick={this.addToContacts}> <FormattedMessage message={this.getIntlMessage('addToContacts')}/> </li> ) : ( <li className="dropdown__menu__item" onClick={this.removeFromContacts}> <FormattedMessage message={this.getIntlMessage('removeFromContacts')}/> </li> ); const dropdownClassNames = classnames('dropdown pull-left', { 'dropdown--opened': isActionsDropdownOpen }); const about = user.about ? ( <div className="user_profile__meta__about"> {user.about} </div> ) : null; const nickname = user.nick ? ( <li> <svg className="icon icon--pink" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#username"/>'}}/> <span className="title">{user.nick}</span> <span className="description">nickname</span> </li> ) : null; const email = user.email ? ( <li className="hide"> <i className="material-icons icon icon--blue">mail</i> <span className="title">{user.email}</span> <span className="description">email</span> </li> ) : null; const phone = user.phones[0] ? ( <li> <i className="material-icons icon icon--green">call</i> <span className="title">{'+' + user.phones[0].number}</span> <span className="description">mobile</span> </li> ) : null; return ( <div className="activity__body user_profile"> <ul className="profile__list"> <li className="profile__list__item user_profile__meta"> <header> <AvatarItem image={user.bigAvatar} placeholder={user.placeholder} size="large" title={user.name}/> <h3 className="user_profile__meta__title">{user.name}</h3> <div className="user_profile__meta__presence">{user.presence}</div> </header> {about} <footer> <div className={dropdownClassNames}> <button className="dropdown__button button button--flat" onClick={this.toggleActionsDropdown}> <i className="material-icons">more_horiz</i> <FormattedMessage message={this.getIntlMessage('actions')}/> </button> <ul className="dropdown__menu dropdown__menu--left"> {actions} <li className="dropdown__menu__item dropdown__menu__item--light" onClick={() => this.clearChat(user.id)}> <FormattedMessage message={this.getIntlMessage('clearConversation')}/> </li> <li className="dropdown__menu__item dropdown__menu__item--light" onClick={() => this.deleteChat(user.id)}> <FormattedMessage message={this.getIntlMessage('deleteConversation')}/> </li> </ul> </div> </footer> </li> <li className="profile__list__item user_profile__contact_info no-p"> <ul className="user_profile__contact_info__list"> {nickname} {phone} {email} </ul> </li> <li className="profile__list__item user_profile__media no-p hide"> <Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}> <ul> <li><a>230 Shared Photos and Videos</a></li> <li><a>49 Shared Links</a></li> <li><a>49 Shared Files</a></li> </ul> </Fold> </li> <li className="profile__list__item user_profile__notifications no-p"> <label htmlFor="notifications"> <i className="material-icons icon icon--squash">notifications_none</i> <FormattedMessage message={this.getIntlMessage('notifications')}/> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </label> </li> </ul> </div> ); } } export default UserProfile;
internals/templates/app.js
mmaedel/react-boilerplate
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved, import/extensions */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import LanguageProvider from 'containers/LanguageProvider'; import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
src/GoalProgressBarGeneral/index.js
christianalfoni/ducky-components
import Typography from '../Typography'; import IconImage from '../IconImage'; import ProgressCircle from '../ProgressCircle'; import LabelSmall from '../LabelSmall'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './styles.css'; function GoalProgressBarGeneral(props) { let opt = ( <Typography className={styles.typo} type={'header1'} > {props.percentage}{" %"} </Typography> ); let labelIcon = 'icon-assignment_turned_in'; if (props.type.toUpperCase() === 'ACTIVITY') { labelIcon = 'icon-check_circle'; } else if (props.type.toUpperCase() === 'CO2') { labelIcon = 'icon-leaf'; } else if (props.type.toUpperCase() === 'POINTS') { labelIcon = 'icon-brightness_high'; } if (props.type.toUpperCase() === 'HABIT' || props.type.toUpperCase() === 'ACTIVITY') { opt = ( <IconImage className={styles.innerElement} icon={props.icon} size={"large"} /> ); } return ( <div className={classNames(styles.wrapper, { [props.className]: props.className })} > <div> <ProgressCircle percent={props.percentage} type={props.type} /> {opt} </div> <div className={styles.innerWrapper}> <LabelSmall className={classNames(styles.labelSmall, {[styles.pointsIcon]: labelIcon === 'icon-brightness_high'}, {[styles.co2Icon]: labelIcon === 'icon-leaf'}, {[styles.activityIcon]: labelIcon === 'icon-check_circle'}, {[styles.habitIcon]: labelIcon === 'icon-assignment_turned_in'}, )} content={props.content} icon={labelIcon} onClick={props.handleButtonClick} type={"caption2Normal"} /> </div> </div> ); } GoalProgressBarGeneral.propTypes = { className: PropTypes.string, content: PropTypes.string, handleButtonClick: PropTypes.func, icon: PropTypes.string, percentage: PropTypes.number, type: PropTypes.string }; export default GoalProgressBarGeneral;
node_modules/react-bootstrap/es/NavbarHeader.js
firdiansyah/crud-req
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 PropTypes from 'prop-types'; import { prefix } from './utils/bootstrapUtils'; var contextTypes = { $bs_navbar: PropTypes.shape({ bsClass: PropTypes.string }) }; var NavbarHeader = function (_React$Component) { _inherits(NavbarHeader, _React$Component); function NavbarHeader() { _classCallCheck(this, NavbarHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } NavbarHeader.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = prefix(navbarProps, 'header'); return React.createElement('div', _extends({}, props, { className: classNames(className, bsClassName) })); }; return NavbarHeader; }(React.Component); NavbarHeader.contextTypes = contextTypes; export default NavbarHeader;
stories/Durations.js
intljusticemission/react-big-calendar
import React from 'react' import { storiesOf } from '@storybook/react' import moment from 'moment' import { Calendar, Views, DragableCalendar } from './helpers' storiesOf('Event Durations', module) .add('Daylight savings starts', () => { return ( <DragableCalendar defaultView={Views.DAY} min={moment('12:00am', 'h:mma').toDate()} max={moment('11:59pm', 'h:mma').toDate()} events={[ { title: 'on DST', start: new Date(2017, 2, 12, 1), end: new Date(2017, 2, 12, 2, 30), allDay: false, }, { title: 'crosses DST', start: new Date(2017, 2, 12, 1), end: new Date(2017, 2, 12, 6, 30), allDay: false, }, { title: 'After DST', start: new Date(2017, 2, 12, 7), end: new Date(2017, 2, 12, 9, 30), allDay: false, }, ]} defaultDate={new Date(2017, 2, 12)} /> ) }) .add('Daylight savings ends', () => { return ( <DragableCalendar defaultView={Views.DAY} min={moment('12:00am', 'h:mma').toDate()} max={moment('11:59pm', 'h:mma').toDate()} events={[ { title: 'on DST', start: new Date(2017, 10, 5, 1), end: new Date(2017, 10, 5, 3, 30), allDay: false, }, { title: 'crosses DST', start: new Date(2017, 10, 5, 1), end: new Date(2017, 10, 5, 6, 30), allDay: false, }, { title: 'After DST', start: new Date(2017, 10, 5, 7), end: new Date(2017, 10, 5, 7, 45), allDay: false, }, ]} defaultDate={new Date(2017, 10, 5)} /> ) }) .add('Daylight savings starts, after 2am', () => { return ( <DragableCalendar defaultView={Views.DAY} min={moment('3:00am', 'h:mma').toDate()} max={moment('11:59pm', 'h:mma').toDate()} events={[ { title: 'After DST', start: new Date(2017, 2, 12, 7), end: new Date(2017, 2, 12, 9, 30), allDay: false, }, ]} defaultDate={new Date(2017, 2, 12)} /> ) }) .add('Daylight savings ends, after 2am', () => { return ( <DragableCalendar defaultView={Views.DAY} min={moment('3:00am', 'h:mma').toDate()} max={moment('11:59pm', 'h:mma').toDate()} events={[ { title: 'After DST', start: new Date(2017, 10, 5, 7), end: new Date(2017, 10, 5, 9, 30), allDay: false, }, ]} defaultDate={new Date(2017, 10, 5)} /> ) })
app/javascript/mastodon/components/button.js
pso2club/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class Button extends React.PureComponent { static propTypes = { text: PropTypes.node, onClick: PropTypes.func, disabled: PropTypes.bool, block: PropTypes.bool, secondary: PropTypes.bool, size: PropTypes.number, className: PropTypes.string, style: PropTypes.object, children: PropTypes.node, }; static defaultProps = { size: 36, }; handleClick = (e) => { if (!this.props.disabled) { this.props.onClick(e); } } setRef = (c) => { this.node = c; } focus() { this.node.focus(); } render () { const style = { padding: `0 ${this.props.size / 2.25}px`, height: `${this.props.size}px`, lineHeight: `${this.props.size}px`, ...this.props.style, }; const className = classNames('button', this.props.className, { 'button-secondary': this.props.secondary, 'button--block': this.props.block, }); return ( <button className={className} disabled={this.props.disabled} onClick={this.handleClick} ref={this.setRef} style={style} > {this.props.text || this.props.children} </button> ); } }
src/containers/Asians/TabControls/PreliminaryRounds/CreateRooms/6_AdjudicatorsPreview/AdjudicatorTable/AdjudicatorDragAndDrop.js
westoncolemanl/tabbr-web
import React from 'react' import ItemTypes from './ItemTypes' import { DragSource } from 'react-dnd' import { connect } from 'react-redux' import withStyles from 'material-ui/styles/withStyles' import AdjudicatorChip from 'containers/Asians/TabControls/_components/AdjudicatorChips/AdjudicatorChip' const styles = theme => ({ root: { marginBottom: theme.spacing.unit } }) const adjudicatorSource = { beginDrag (props) { props.onDrag(true) return { adjudicator: props.adjudicator, position: props.position, room: props.room } }, endDrag (props) { props.onDrag(false) } } function collect (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() } } const AdjudicatorDragAndDrop = connect(mapStateToProps)(withStyles(styles)(({ isDragging, connectDragSource, adjudicator, adjudicatorsById, adjudicatorStandings, institutionsById, round, minimumRelevantAdjudicatorPoint, margin, room, classes }) => { return connectDragSource( <div className={margin ? classes.root : ''} > <AdjudicatorChip room={room} adjudicator={adjudicator} round={round} minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint} /> </div> ) })) export default DragSource(ItemTypes.ADJUDICATOR, adjudicatorSource, collect)(AdjudicatorDragAndDrop) function mapStateToProps (state, ownProps) { return { institutionsById: state.institutions.data, adjudicatorsById: state.adjudicators.data, adjudicatorStandings: state.standings.adjudicators } }
awsmobilecognitocustomui/src/components/Loading.js
adrianhall/blog-code
import React from 'react'; import { StyleSheet, View } from 'react-native'; import Spinner from 'react-native-spinkit'; import colors from '../theme/colors'; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.headerBackgroundColor, } }); const Loading = (props) => { return ( <View style={styles.container}> <Spinner type="Wave" size={100} color="white" isVisible={true} /> </View> ); }; export default Loading;
src/forms/formElement/formElementUtilsSpec.js
ikanedo/react-redux-simple-validate
import React from 'react'; import Adapter from 'enzyme-adapter-react-16'; import { shallow, configure } from 'enzyme'; import { getFormInputType, getFormElementType, getFormElementRefName } from './formElementUtils'; configure({ adapter: new Adapter() }); describe('FormElementUtils', () => { describe('getFormInputType', () => { describe(`Returns the input type, tested elements include text, number, email, password number, checkbox, radio. Other input elements like hidden, date, week etc. are not tested. `, () => { const getInputElement = type => <input type={type} />; it('SHOULD return default for unknown types (text, number, email, etc.)', () => { const text = shallow(getInputElement('text')).prop('type'); const email = shallow(getInputElement('email')).prop('type'); const password = shallow(getInputElement('password')).prop('type'); const number = shallow(getInputElement('number')).prop('type'); expect(getFormInputType(text)).toBe('default'); expect(getFormInputType(email)).toBe('default'); expect(getFormInputType(password)).toBe('default'); expect(getFormInputType(number)).toBe('default'); }); it('SHOULD return checkbox if the input type is checkbox', () => { const checkbox = shallow(getInputElement('checkbox')).prop('type'); expect(getFormInputType(checkbox)).toBe('checkbox'); }); it('SHOULD return radio if the input type is radio', () => { const radio = shallow(getInputElement('radio')).prop('type'); expect(getFormInputType(radio)).toBe('radio'); }); }); }); describe('getFormElementType', () => { describe(`Returns the React element type and filters form elements like select, textarea and input. Other possible form element types are not considered until use case arises. `, () => { it('SHOULD return select for select elements', () => { expect(getFormElementType(<select />)).toBe('select'); }); it('SHOULD return default for textarea', () => { expect(getFormElementType(<textarea />)).toBe('default'); }); it('SHOULD return default for regular input elements', () => { expect(getFormElementType(<input />)).toBe('default'); }); it('SHOULD return radio for radio input elements', () => { expect(getFormElementType(<input type="radio" />)).toBe('radio'); }); it('SHOULD return checkbox for checkbox input elements', () => { expect(getFormElementType(<input type="checkbox" />)).toBe('checkbox'); }); }); }); describe('getFormElementRefName', () => { describe(`Returns the ref name for form elements. Radio ref name is returned as (name + value) WHY? since radio buttons have 1 name with multiple values, we need to identify which value belongs to which name. This is not an issue with other form elements. `, () => { it('SHOULD return the correct name for Radio', () => { expect(getFormElementRefName(<input type="radio" name="myName" value="myVal" />)).toBe('myNamemyVal'); }); it(` SHOULD return the correct name for Other form elements. Assumption: each form element name is unique `, () => { expect(getFormElementRefName(<select name="mySelect" />)).toBe('mySelect'); }); }); }); });
src/App.js
isuruAb/chat.susi.ai
import Blog from './components/Blog/Blog.react'; import ChatApp from './components/ChatApp/ChatApp.react'; import Contact from './components/Contact/Contact.react'; import Devices from './components/Devices/Devices.react'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import Logout from './components/Auth/Logout.react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import PropTypes from 'prop-types'; import NotFound from './components/NotFound/NotFound.react'; import Overview from './components/Overview/Overview.react'; import Settings from './components/ChatApp/Settings/Settings.react'; import Support from './components/Support/Support.react'; import Team from './components/Team/Team.react'; import Terms from './components/Terms/Terms.react'; import Privacy from './components/Privacy/Privacy.react'; import { Switch, Route } from 'react-router-dom'; import React, { Component } from 'react'; const muiTheme = getMuiTheme({ toggle: { thumbOnColor: '#5ab1fc', trackOnColor: '#4285f4' } }); class App extends Component{ closeVideo = () => this.setState({ video: false }) render(){ if(location.pathname!=='/'){ document.body.className = 'white-body'; } return( <MuiThemeProvider muiTheme={muiTheme}> <div> <Switch> <Route exact path='/' component={ChatApp}/> <Route exact path="/overview" component={Overview} /> <Route exact path="/devices" component={Devices} /> <Route exact path='/team' component={Team} /> <Route exact path='/blog' component={Blog} /> <Route exact path='/contact' component={Contact} /> <Route exact path="/support" component={Support} /> <Route exact path="/terms" component={Terms} /> <Route exact path="/privacy" component={Privacy} /> <Route exact path="/logout" component={Logout} /> <Route exact path="/settings" component={Settings} /> <Route exact path="*" component={NotFound} /> </Switch> </div> </MuiThemeProvider> ); } } App.propTypes = { history: PropTypes.object, location: PropTypes.object, closeVideo: PropTypes.func } export default App;
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
zomeelee/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
src/svg-icons/content/clear.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentClear = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); ContentClear = pure(ContentClear); ContentClear.displayName = 'ContentClear'; ContentClear.muiName = 'SvgIcon'; export default ContentClear;
src/components_youtube_p/video_detail.js
vikasv/ReactWithRedux
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return <div>Loading...</div>; } const videoId = video.id.videoId; const url = 'https://www.youtube.com/embed/' + videoId; //Below es6 syntax //const url = `https://www.youtube.com/embed/$(videoId)`; return ( <div className = "video-detail col-md-8"> <div className = "embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url} allowFullScreen></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
src/components/orders/orders_table.js
hojberg/mastering-react
import React from 'react'; import OrderRow from './order_row'; class OrdersTable extends React.Component { render() { const rows = this.props.orders.map((order, i) => { return <OrderRow order={order} key={i} />; }); return ( <table className='orders-table'> <thead> <tr> <th>Order #</th> <th>Customer</th> <th className='sorted-by'>Ordered at</th> <th>Product(s)</th> <th className='amount'>Amount</th> <th className='status'>Payment status</th> <th className='status'>Order status</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } export default OrdersTable;
test/components/SearchResultsComponentTest.js
cised-ca/se-dir-frontend-react
/* eslint-env node, mocha */ /* global expect */ /* eslint no-console: 0 */ 'use strict'; import React from 'react'; import { shallow } from 'enzyme'; import { SearchResultsComponent } from 'components/SearchResultsComponent.js'; describe('SearchResultsComponent', () => { let component; var searchTextProp = 'restore'; beforeEach(() => { component = shallow( <SearchResultsComponent t={key => key} searchText={searchTextProp} /> ); component.setState({ searchResults: { enterprises: [ { id: '1' } ] } }); }); it('should have its component name as default className', () => { expect(component.hasClass('searchresults-component')).to.equal(true); }); });
tests/format/misc/flow-babel-only/class_with_generics.js
jlongster/prettier
import React from 'react'; /*:: type Props = { foo?: ?string, bar: number, }; */ /*:: type State = { baz: number }; */ class Component extends React.Component/*:: <Props, State> */ { }
src/internal/Overlay.js
rscnt/material-ui
import React from 'react'; import transitions from '../styles/transitions'; import AutoLockScrolling from './AutoLockScrolling'; function getStyles(props, context) { const {overlay} = context.muiTheme; const style = { root: { position: 'fixed', height: '100%', width: '100%', top: 0, left: '-100%', opacity: 0, backgroundColor: overlay.backgroundColor, WebkitTapHighlightColor: 'rgba(0, 0, 0, 0)', // Remove mobile color flashing (deprecated) // Two ways to promote overlay to its own render layer willChange: 'opacity', transform: 'translateZ(0)', transition: props.transitionEnabled && `${transitions.easeOut('0ms', 'left', '400ms')}, ${ transitions.easeOut('400ms', 'opacity')}`, }, }; if (props.show) { Object.assign(style.root, { left: 0, opacity: 1, transition: `${transitions.easeOut('0ms', 'left')}, ${ transitions.easeOut('400ms', 'opacity')}`, }); } return style; } class Overlay extends React.Component { static propTypes = { autoLockScrolling: React.PropTypes.bool, show: React.PropTypes.bool.isRequired, /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, transitionEnabled: React.PropTypes.bool, }; static defaultProps = { autoLockScrolling: true, transitionEnabled: true, style: {}, }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; setOpacity(opacity) { this.refs.overlay.style.opacity = opacity; } render() { const { autoLockScrolling, show, style, ...other, } = this.props; const {prepareStyles} = this.context.muiTheme; const styles = getStyles(this.props, this.context); return ( <div {...other} ref="overlay" style={prepareStyles(Object.assign(styles.root, style))}> {autoLockScrolling && <AutoLockScrolling lock={show} />} </div> ); } } export default Overlay;
app/javascript/mastodon/features/account_timeline/components/moved_note.js
yi0713/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import AvatarOverlay from '../../../components/avatar_overlay'; import DisplayName from '../../../components/display_name'; import Icon from 'mastodon/components/icon'; export default class MovedNote extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { from: ImmutablePropTypes.map.isRequired, to: ImmutablePropTypes.map.isRequired, }; handleAccountClick = e => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/@${this.props.to.get('acct')}`); } e.stopPropagation(); } render () { const { from, to } = this.props; const displayNameHtml = { __html: from.get('display_name_html') }; return ( <div className='account__moved-note'> <div className='account__moved-note__message'> <div className='account__moved-note__icon-wrapper'><Icon id='suitcase' className='account__moved-note__icon' fixedWidth /></div> <FormattedMessage id='account.moved_to' defaultMessage='{name} has moved to:' values={{ name: <bdi><strong dangerouslySetInnerHTML={displayNameHtml} /></bdi> }} /> </div> <a href={to.get('url')} onClick={this.handleAccountClick} className='detailed-status__display-name'> <div className='detailed-status__display-avatar'><AvatarOverlay account={to} friend={from} /></div> <DisplayName account={to} /> </a> </div> ); } }
test/index.spec.js
loggur/provide-id-gen
import 'react-redux-provide/lib/install'; import expect from 'expect'; import React from 'react'; import PropTypes from 'prop-types'; import { Simulate } from 'react-dom/test-utils'; import { renderTest } from 'react-redux-provide-test-utils'; import { Test } from './components/index'; import { idGen } from './providers/index'; const defaultProps = { providers: { idGen: { ...idGen, state: { newTestId: '10' } } } }; const test = renderTest(Test, defaultProps); const testNode = test.node; const testButtonNode = testNode.childNodes[0]; const testItemNode = testNode.childNodes[1]; describe('provide-id-gen', () => { it('should render correctly', () => { expect(testNode.tagName).toBe('DIV'); expect(testNode.className).toBe('test'); expect(testButtonNode.tagName).toBe('BUTTON'); expect(testItemNode.tagName).toBe('DIV'); expect(testItemNode.className).toBe('test-item'); expect(testItemNode.textContent).toBe('10'); }); it('should generate a newTestId', () => { Simulate.click(testButtonNode); expect(testItemNode.textContent).toBe('11'); }); });
src/test/xy-plot.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 test from 'tape'; import React from 'react'; import {shallow} from 'enzyme'; import VerticalBarSeries from '../lib/plot/series/vertical-bar-series'; import XAxis from '../lib/plot/axis/x-axis'; import XYPlot from '../lib/plot/xy-plot'; test('Render a stacked bar chart', assert => { const wrapper = shallow( <XYPlot width={300} height={300} stackBy="y"> <VerticalBarSeries data={[ {x: 1, y: 0}, {x: 2, y: 1}, {x: 3, y: 2} ]} /> <VerticalBarSeries data={[ {x: 1, y: 2}, {x: 2, y: 1}, {x: 3, y: 0} ]}/> </XYPlot> ); const renderedVerticalBarsWrapper = wrapper.find(VerticalBarSeries); assert.deepEqual( renderedVerticalBarsWrapper.at(0).prop('data'), [ {x: 1, y: 0}, {x: 2, y: 1}, {x: 3, y: 2} ], 'First bar series data is the same' ); assert.deepEqual( renderedVerticalBarsWrapper.at(1).prop('data'), [ {x: 1, y: 2, y0: 0}, {x: 2, y: 2, y0: 1}, {x: 3, y: 2, y0: 2} ], 'Second bar series data contains y0 values' ); assert.end(); }); test('Render a stacked bar chart with other children', assert => { const wrapper = shallow( <XYPlot width={300} height={300} stackBy="y"> <XAxis /> <VerticalBarSeries data={[ {x: 1, y: 0} ]} /> <VerticalBarSeries data={[ {x: 1, y: 2} ]}/> { /* Empty div here is intentional, for testing series children handling */ } <div></div> </XYPlot> ); const renderedVerticalBarsWrapper = wrapper.find(VerticalBarSeries); assert.deepEqual( renderedVerticalBarsWrapper.at(0).prop('data'), [ {x: 1, y: 0} ], 'First bar series data is the same' ); assert.deepEqual( renderedVerticalBarsWrapper.at(1).prop('data'), [ {x: 1, y: 2, y0: 0} ], 'Second bar series data contains y0 values' ); assert.end(); });
app/javascript/mastodon/features/account/components/account_note.js
glitch-soc/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Textarea from 'react-textarea-autosize'; import { is } from 'immutable'; const messages = defineMessages({ placeholder: { id: 'account_note.placeholder', defaultMessage: 'Click to add a note' }, }); class InlineAlert extends React.PureComponent { static propTypes = { show: PropTypes.bool, }; state = { mountMessage: false, }; static TRANSITION_DELAY = 200; componentWillReceiveProps (nextProps) { if (!this.props.show && nextProps.show) { this.setState({ mountMessage: true }); } else if (this.props.show && !nextProps.show) { setTimeout(() => this.setState({ mountMessage: false }), InlineAlert.TRANSITION_DELAY); } } render () { const { show } = this.props; const { mountMessage } = this.state; return ( <span aria-live='polite' role='status' className='inline-alert' style={{ opacity: show ? 1 : 0 }}> {mountMessage && <FormattedMessage id='generic.saved' defaultMessage='Saved' />} </span> ); } } export default @injectIntl class AccountNote extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, value: PropTypes.string, onSave: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { value: null, saving: false, saved: false, }; componentWillMount () { this._reset(); } componentWillReceiveProps (nextProps) { const accountWillChange = !is(this.props.account, nextProps.account); const newState = {}; if (accountWillChange && this._isDirty()) { this._save(false); } if (accountWillChange || nextProps.value === this.state.value) { newState.saving = false; } if (this.props.value !== nextProps.value) { newState.value = nextProps.value; } this.setState(newState); } componentWillUnmount () { if (this._isDirty()) { this._save(false); } } setTextareaRef = c => { this.textarea = c; } handleChange = e => { this.setState({ value: e.target.value, saving: false }); }; handleKeyDown = e => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { e.preventDefault(); this._save(); if (this.textarea) { this.textarea.blur(); } } else if (e.keyCode === 27) { e.preventDefault(); this._reset(() => { if (this.textarea) { this.textarea.blur(); } }); } } handleBlur = () => { if (this._isDirty()) { this._save(); } } _save (showMessage = true) { this.setState({ saving: true }, () => this.props.onSave(this.state.value)); if (showMessage) { this.setState({ saved: true }, () => setTimeout(() => this.setState({ saved: false }), 2000)); } } _reset (callback) { this.setState({ value: this.props.value }, callback); } _isDirty () { return !this.state.saving && this.props.value !== null && this.state.value !== null && this.state.value !== this.props.value; } render () { const { account, intl } = this.props; const { value, saved } = this.state; if (!account) { return null; } return ( <div className='account__header__account-note'> <label htmlFor={`account-note-${account.get('id')}`}> <FormattedMessage id='account.account_note_header' defaultMessage='Note' /> <InlineAlert show={saved} /> </label> <Textarea id={`account-note-${account.get('id')}`} className='account__header__account-note__content' disabled={this.props.value === null || value === null} placeholder={intl.formatMessage(messages.placeholder)} value={value || ''} onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleBlur} ref={this.setTextareaRef} /> </div> ); } }
www/components/Navigation/Navigation.js
DremyGit/dremy-blog
import React from 'react'; import { Link, withRouter } from 'react-router'; import CSSModules from 'react-css-modules'; import styles from './Navigation.scss'; @withRouter @CSSModules(styles) class Navigation extends React.Component { constructor(props) { super(props); this.state = { searchInput: false, searchContent: '', }; } isActiveMenu(menu) { const { routes } = this.props; const part = (routes[1] && routes[1].path) || 'blog'; return menu.pattern.test(part); } doSearch() { const { router } = this.props; router.push(`/search/${this.state.searchContent}`); } handleSearch() { if (!this.state.searchInput) { this.setState({ searchInput: true }); this.input.focus(); } else if (this.state.searchContent) { this.doSearch(); setTimeout(() => this.setState({ searchContent: '' }), 500); } else { this.setState({ searchInput: false }); } } handleKeyDown(e) { if (e.keyCode === 13 && this.state.searchContent !== '') { this.doSearch(); } } render() { const menus = [ { href: '', pattern: /blog/, name: '首页' }, { href: 'category', pattern: /category/, name: '分类' }, { href: 'tag', pattern: /tag/, name: '标签' }, { href: 'archive', pattern: /archive/, name: '归档' }, { href: 'about', pattern: /about/, name: '关于' }, ]; const { maxWidth } = this.props; const menuList = menus.map((menu) => { return ( <li key={menu.href} className={styles.listItem} styleName={this.isActiveMenu(menu) ? 'active' : null}> <Link styleName={'menuLink'} to={`/${menu.href}`}>{menu.name}</Link> </li> ); }); return ( <div styleName="header"> <div styleName="navigation" style={{ maxWidth }}> <Link to="/"> <span styleName="logo">Dremy_博客</span> </Link> <ul styleName="menu"> {menuList} </ul> <div className={styles.search} styleName={this.state.searchInput && 'active'}> <input styleName="searchInput" ref={(input) => { this.input = input; }} value={this.state.searchContent} onChange={e => this.setState({ searchContent: e.target.value })} onKeyDown={e => this.handleKeyDown(e)} placeholder="搜索标题或关键词" onBlur={() => setTimeout(() => this.setState({ searchInput: false }), 300)} /> <a onClick={() => this.handleSearch()}> <i className="fa fa-search" aria-hidden="true" /> </a> </div> </div> </div> ); } } Navigation.PropTypes = { maxWidth: React.PropTypes.string.isRequired, }; export default Navigation;
src/client/course/EditVenturerCourse.js
jmicmoore/merit-badge-university
import React from 'react'; import {connect} from 'react-redux'; import {withRouter} from 'react-router-dom'; import TextArea from "../common/components/TextArea"; import SingleSelect from '../common/components/SingleSelect'; import SimpleList from '../common/components/SimpleList'; import {updateCourse, getCourseById, resetCurrentCourse, getVenturingClassNames} from './courseActions'; import {validate} from '../common/util/validation'; import validationConfig from './VenturerCourseValidationConfig'; import {COURSE_TYPE} from './constants'; const recommendedLengthChoices = [ {value: '1 hour', label: '1 hour'}, {value: '2 hours', label: '2 hours'}, {value: '3 hours', label: '3 hours'}, {value: '4 hours', label: '4 hours'}, {value: 'more than 4 hours', label: 'more than 4 hours'} ]; const recommendedSizeChoices = [ {value: '2-6 students', label: '2-6 students'}, {value: '4-8 students', label: '4-8 students'}, {value: '6-12 students', label: '6-12 students'}, {value: '10-20 students', label: '10-20 students'}, {value: 'more than 20 students', label: 'more than 20 students'} ]; class EditVenturerCourse extends React.Component { constructor(){ super(); this.state = { venturingClass: '', recommendedLength: '', recommendedSize: '', notes: '', teachers: ['Joe Smith'] }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleAddMe = this.handleAddMe.bind(this); this.handleRemoveMe = this.handleRemoveMe.bind(this); } componentDidMount() { if(this.props.match.params.courseId){ getCourseById(this.props.match.params.courseId); } getVenturingClassNames(); }; componentWillUnmount(){ resetCurrentCourse(); } currentCourseIsChanging(nextProps){ return nextProps.currentCourse !== this.props.currentCourse; } componentWillReceiveProps(nextProps){ if(this.currentCourseIsChanging(nextProps)){ const courseLocalCopy = Object.assign({}, nextProps.currentCourse); this.setState(courseLocalCopy); } }; handleAddMe(){ const newTeachers = this.state.teachers.slice(); newTeachers.push("Jerry Moore"); this.setState({teachers: newTeachers}); } handleRemoveMe(){ const index = this.state.teachers.indexOf("Jerry Moore"); let newTeachers = this.state.teachers.slice(); if(index !== -1){ newTeachers.splice(index, 1); } this.setState({teachers: newTeachers}) } handleChange(field, value) { this.setState({[field]: value}); }; handleSubmit(event) { event.preventDefault(); const report = validate(this.state, validationConfig); if(report.allValid){ const newCourse = Object.assign( {}, this.state, { courseType : COURSE_TYPE.Venturing, } ); updateCourse(newCourse); this.setState({ displayErrors: false }); this.props.history.push('/admin/venturer-courses'); // go back to courses screen } else { this.setState({ displayErrors: true }); } this.setState({errorReport: report}); }; render(){ const venturingClassChoices = this.props.venturingClassNames || []; const classInfo = this.state; const index = this.state.teachers.indexOf("Jerry Moore"); let teachingAlready = false; if(index !== -1){ teachingAlready = true; } return ( <div className="container"> <div className="row"> <div id="form-container-registration" className="col-sm-offset-1 col-sm-10 well"> <form onSubmit={this.handleSubmit} noValidate className={this.state.displayErrors ? 'displayErrors' : ''} > <h2 className="text-info">Edit Course</h2> <div className="col-sm-4 col-xs-12"> <SingleSelect propertyName='venturingClass' propertyValue={classInfo.venturingClass} displayName='Venturing Class' options={venturingClassChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/> </div> <div className="col-sm-4 col-xs-12"> <SingleSelect propertyName='recommendedLength' propertyValue={classInfo.recommendedLength} displayName='Recommended Class Length' options={recommendedLengthChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/> </div> <div className="col-sm-4 col-xs-12"> <SingleSelect propertyName='recommendedSize' propertyValue={classInfo.recommendedSize} displayName='Recommended Number of Students' options={recommendedSizeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/> </div> <div className="clearfix"></div> <div className="col-sm-8 col-xs-12"> <TextArea propertyName='notes' propertyValue={classInfo.notes} displayName='Notes' errors={this.state.errorReport} changeHandler={this.handleChange}/> </div> <div className="col-sm-4 col-xs-12"> <div className="row"> <div className="col-sm-12 col-xs-12"> <SimpleList propertyName='teachers' displayName='Venturer Instructors' dataList={classInfo.teachers}/> </div> </div> <div className="row"> <div className="col-sm-3 col-xs-12"> <button type="button" className="btn btn-sm" disabled={teachingAlready} onClick={this.handleAddMe}>Add Me</button> </div> <div className="col-sm-3 col-xs-12"> <button type="button" className="btn btn-sm" onClick={this.handleRemoveMe}>Remove Me</button> </div> </div> </div> <div className="clearfix"></div> <div style={{marginTop: '20px'}} className="col-sm-offset-4 col-sm-2 col-xs-12 pull-right"> <button type="submit" className="btn btn-success btn-lg btn-block">Save</button> </div> </form> </div> </div> </div> ); } }; const mapStateToProps = ({course}) => { return course; }; export default withRouter(connect(mapStateToProps)(EditVenturerCourse));
src/index.js
JasonAForral/quiz-client-json-rpc-react
import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import App from './containers/App' import reducer from './reducers' import './index.css'; const middleware = [ thunk ] if ('production' !== process.env.NODE_ENV) { middleware.push(createLogger()) } const store = createStore( reducer, applyMiddleware(...middleware) ) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
packages/material-ui-icons/src/PanoramaVertical.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M19.94 21.12c-1.1-2.94-1.64-6.03-1.64-9.12 0-3.09.55-6.18 1.64-9.12.04-.11.06-.22.06-.31 0-.34-.23-.57-.63-.57H4.63c-.4 0-.63.23-.63.57 0 .1.02.2.06.31C5.16 5.82 5.71 8.91 5.71 12c0 3.09-.55 6.18-1.64 9.12-.05.11-.07.22-.07.31 0 .33.23.57.63.57h14.75c.39 0 .63-.24.63-.57-.01-.1-.03-.2-.07-.31zM6.54 20c.77-2.6 1.16-5.28 1.16-8 0-2.72-.39-5.4-1.16-8h10.91c-.77 2.6-1.16 5.28-1.16 8 0 2.72.39 5.4 1.16 8H6.54z" /></g> , 'PanoramaVertical');
src/Main.js
connectordb/connectordb-android
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from './actions'; import { StatusBar, View } from 'react-native'; import FacebookTabBar from './components/FacebookTabBar'; import ErrorBar from './components/ErrorBar'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import Downlinks from './Downlinks'; import Inputs from './Inputs'; import Settings from './Settings'; const Main = ({state, actions}) => ( <View style={{ flex: 1 }}> <StatusBar backgroundColor="#009e42" barStyle="light-content" /> <ScrollableTabView renderTabBar={() => <FacebookTabBar />} locked={true} > <Inputs tabLabel="ios-star" /> <Downlinks tabLabel="ios-bulb" /> <Settings tabLabel="ios-settings" /> </ScrollableTabView> <ErrorBar error={state.error} /> </View> ); export default connect( (state) => ({ state: state }), (dispatch) => ({ actions: bindActionCreators(Actions, dispatch) }) )(Main);
webpack/scenes/RedHatRepositories/components/RepositorySetRepositories.js
cfouant/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert, Spinner } from 'patternfly-react'; import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories'; import RepositorySetRepository from './RepositorySetRepository/'; import { yStream } from './RepositorySetRepositoriesHelpers'; class RepositorySetRepositories extends Component { componentDidMount() { const { contentId, productId } = this.props; if (this.props.data.loading) { this.props.loadRepositorySetRepos(contentId, productId); } } sortedRepos = repos => [...repos.filter(({ enabled }) => !enabled)] .sort((repo1, repo2) => { const repo1YStream = yStream(repo1.releasever || ''); const repo2YStream = yStream(repo2.releasever || ''); if (repo1YStream < repo2YStream) { return -1; } if (repo2YStream < repo1YStream) { return 1; } if (repo1.arch === repo2.arch) { const repo1MajorMinor = repo1.releasever.split('.'); const repo2MajorMinor = repo2.releasever.split('.'); const repo1Major = parseInt(repo1MajorMinor[0], 10); const repo2Major = parseInt(repo2MajorMinor[0], 10); if (repo1Major === repo2Major) { const repo1Minor = parseInt(repo1MajorMinor[1], 10); const repo2Minor = parseInt(repo2MajorMinor[1], 10); if (repo1Minor === repo2Minor) { return 0; } return (repo1Minor > repo2Minor) ? -1 : 1; } return (repo1Major > repo2Major) ? -1 : 1; } return (repo1.arch > repo2.arch) ? -1 : 1; }); render() { const { data, type } = this.props; if (data.error) { return ( <Alert type="danger"> <span>{data.error.displayMessage}</span> </Alert> ); } const availableRepos = this.sortedRepos(data.repositories).map(repo => ( <RepositorySetRepository key={repo.arch + repo.releasever} type={type} {...repo} /> )); const repoMessage = (data.repositories.length > 0 && availableRepos.length === 0 ? __('All available architectures for this repo are enabled.') : __('No repositories available.')); return ( <Spinner loading={data.loading}> {availableRepos.length ? availableRepos : <div>{repoMessage}</div>} </Spinner> ); } } RepositorySetRepositories.propTypes = { loadRepositorySetRepos: PropTypes.func.isRequired, contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, type: PropTypes.string, data: PropTypes.shape({ loading: PropTypes.bool.isRequired, repositories: PropTypes.arrayOf(PropTypes.object), }).isRequired, }; RepositorySetRepositories.defaultProps = { type: '', }; const mapStateToProps = ( { katello: { redHatRepositories: { repositorySetRepositories } } }, props, ) => ({ data: repositorySetRepositories[props.contentId] || { loading: true, repositories: [], error: null, }, }); export default connect(mapStateToProps, { loadRepositorySetRepos, })(RepositorySetRepositories);
docs/app/Examples/addons/Radio/States/ReadOnly.js
jamiehill/stardust
import React from 'react' import { Radio } from 'stardust' const RadioReadOnlyExample = () => ( <Radio label='This radio is read-only' readOnly /> ) export default RadioReadOnlyExample
src/components/user/avatar-editor.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import { User as UserPropType } from '../../prop-types/users'; import { AVATAR_SIZE } from '../../consts/profileConstants'; import UpdatePicture from '../update-picture/update-picture'; export default class AvatarEditor extends React.Component { static displayName = 'AvatarEditor'; static propTypes = { flexible: PropTypes.bool, limits: PropTypes.shape({}), onUpdateAvatar: PropTypes.func, preview: PropTypes.shape({}), user: UserPropType.isRequired }; static defaultProps = { flexible: false, limits: { min: AVATAR_SIZE }, preview: AVATAR_SIZE, onUpdateAvatar: () => {} }; render() { const { user, flexible, limits, preview, onUpdateAvatar } = this.props; let modalName = <span className="font-bold">{user.get('username')}</span>; if (user.getIn(['more', 'firstName']) || user.getIn(['more', 'lastName'])) { modalName = [ <span className="font-bold" key="avatarEditorName">{user.getIn(['more', 'firstName'])} {user.getIn(['more', 'lastName'])}</span>, ` (${user.get('username')})` ]; } return ( <UpdatePicture flexible={flexible} limits={limits} preview={preview} what="profile picture" where={modalName} onSubmit={onUpdateAvatar} /> ); } }
src/main.js
luigiplr/area51-launcher
import React from 'react' import ReactDOM from 'react-dom' import Framework from './js/components/Framework.react' import webUtil from './js/utils/webUtil' webUtil.disableGlobalBackspace() ReactDOM.render(<Framework />, document.getElementById('app'))
src/components/mail/mailTags.js
EncontrAR/backoffice
import React from 'react'; const tags = [ 'Friend', 'Family', 'Colleague', 'Teachers', 'Students', 'ClassMates', ]; const tagColor = [ '#CD3131', '#74B49B', '#0962EA', '#141829', '#FFCD38', '#61105E', ]; function gettags(mails, filterAttr) { const tags = {}; mails.forEach(mail => { if (mail.tags && mail.bucket === filterAttr.bucket) { mail.tags.split(' ').forEach(tag => tags[tag] = 1); } }); return tags; } export default function mailtags( mails, filterAction, filterAttr, onDrawerClose, ) { const Tags = gettags(mails, filterAttr); const renderSingleTag = (tag, key) => { const onClick = () => { filterAction({ tag }); if (onDrawerClose) { onDrawerClose(); } }; const selectedTag = tag === filterAttr.tag; const activeClass = selectedTag ? 'active' : ''; const background = tagColor[tags.findIndex(tags => tags === tag)]; return ( <li key={`tag${key}`} onClick={onClick} className={`isoMailTag ${activeClass}`} > <span className="isoLabelIndicatorColor" style={{ background }} /> <span>{tag}</span> </li> ); }; return ( <ul className="isoMailTagList"> <p className="isoSectionLabel">Label</p> {Object.keys(Tags).map((tag, index) => renderSingleTag(tag, index))} </ul> ); } export { tags, tagColor };
submissions/masiulis/src/components/components/components/sith-list-item.js
staltz/flux-challenge
import React from 'react'; export default class extends React.Component { static propTypes = { name: React.PropTypes.string, homeworld: React.PropTypes.string, obiPlanet: React.PropTypes.string, } render() { const textColor = this.props.homeworld === this.props.obiPlanet ? 'red' : ''; return ( <li className="css-slot" style={{color: textColor}}> <h3>{this.props.name}</h3> <h6>{this.props.homeworld && `Homeworld: ${this.props.homeworld}`}</h6> </li> ) } }
packages/bonde-admin/src/components/navigation/tabs/tab-border.js
ourcities/rebu-client
import PropTypes from 'prop-types' import React from 'react' import classnames from 'classnames' if (require('exenv').canUseDOM) { require('./tab-border.scss') } const TabBorder = ({ children, Component, path, className, isActive, style }) => { const optionalProps = {} if (path) optionalProps.to = path return ( <Component {...optionalProps} className={classnames( 'tab components--tab-border', { 'is-active': isActive }, className )} style={style} > {children} </Component> ) } TabBorder.propTypes = { children: PropTypes.node.isRequired, Component: PropTypes.node.isRequired, className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), path: PropTypes.string, isActive: PropTypes.bool, style: PropTypes.string } export default TabBorder
src/components/Elements/SocialIcons/index.js
jmikrut/keen-2017
import React, { Component } from 'react'; import Facebook from '../../Icons/Facebook'; import LinkedIn from '../../Icons/LinkedIn'; import Dribbble from '../../Icons/Dribbble'; import Behance from '../../Icons/Behance'; import YouTube from '../../Icons/YouTube'; import Medium from '../../Icons/Medium'; import GitHub from '../../Icons/GitHub'; import './SocialIcons.css'; class SocialIcons extends Component { render() { const originalClasses = "social-icons"; const additionalClasses = this.props.className; const classes = additionalClasses ? `${originalClasses} ${additionalClasses}` : originalClasses return ( <ul className={classes}> <li> <a href="https://www.facebook.com/keen2015/" target="_blank" rel="noopener noreferrer"> <Facebook /> </a> </li> <li> <a href="https://www.linkedin.com/company/10183058/" target="_blank" rel="noopener noreferrer"> <LinkedIn /> </a> </li> <li> <a href="https://dribbble.com/keen_studio" target="_blank" rel="noopener noreferrer"> <Dribbble /> </a> </li> <li> <a href="https://www.behance.net/keenstudio" target="_blank" rel="noopener noreferrer"> <Behance /> </a> </li> <li> <a href="https://www.youtube.com/channel/UCOrm7cXv_flN9Hzah-5ucKg/videos" target="_blank" rel="noopener noreferrer"> <YouTube /> </a> </li> <li> <a href="https://medium.com/keen-studio" target="_blank" rel="noopener noreferrer"> <Medium/> </a> </li> <li> <a href="https://github.com/keen-studio" target="_blank" rel="noopener noreferrer"> <GitHub/> </a> </li> </ul> ); } } export default SocialIcons;
packages/veritone-react-common/src/components/FilePicker/FileUploader/index.js
veritone/veritone-sdk
import React, { Component } from 'react'; import { noop, startsWith, endsWith } from 'lodash'; import cx from 'classnames'; import Button from '@material-ui/core/Button'; import { DropTarget } from 'react-dnd'; import { string, func, arrayOf, bool, shape, any } from 'prop-types'; import { withStyles } from '@material-ui/styles'; import { NativeTypes } from 'react-dnd-html5-backend'; const { FILE } = NativeTypes; import ExtensionPanel from './ExtensionPanel'; import styles from './styles'; const boxTarget = { drop(props, monitor) { const droppedFiles = monitor.getItem().files; const allowableDroppedFiles = droppedFiles.filter(({ type }) => { // only accept dropped files of the correct type. This tries to duplicate // the functionality of the html5 file input. return ( props.acceptedFileTypes.includes(type) || props.acceptedFileTypes.some(acceptedType => { // deal with video/*, audio/* etc if (endsWith(acceptedType, '/*')) { const typePrefix = acceptedType.match(/(.*)\/\*/)[1]; return startsWith(type, typePrefix); } return false; }) ); }); if (props.acceptedFileTypes.length) { if (allowableDroppedFiles.length) { props.onFilesSelected(allowableDroppedFiles); } const numRejectedFiles = droppedFiles.length - allowableDroppedFiles.length; if (numRejectedFiles > 0) { props.onFilesRejected(numRejectedFiles); } } else { props.onFilesSelected(droppedFiles); } } }; const collect = (connect, monitor) => { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop() }; }; @DropTarget(FILE, boxTarget, collect) @withStyles(styles) class FileUploader extends Component { static propTypes = { acceptedFileTypes: arrayOf(string), onFilesSelected: func.isRequired, useFlatStyle: bool, // eslint-disable-next-line react/no-unused-prop-types onFilesRejected: func, isOver: bool.isRequired, connectDropTarget: func.isRequired, multiple: bool, classes: shape({ any }), }; static defaultProps = { acceptedFileTypes: [], onFilesRejected: noop }; state = { showExtensionList: false }; handleFileSelection = () => { if (this._input.files.length > 0) { this.props.onFilesSelected(Array.from(this._input.files)); } this._input.value = null; }; openExtensionList = () => { this.setState({ showExtensionList: true }); }; closeExtensionList = () => { this.setState({ showExtensionList: false }); }; setInputRef = r => (this._input = r); render() { const { acceptedFileTypes, connectDropTarget, isOver, classes } = this.props; const { showExtensionList } = this.state; const acceptMessage = 'Drag & Drop'; const subMessage = 'your file(s) here, or '; return connectDropTarget( <div className={cx([ classes.fileUploader, { [classes.flat]: this.props.useFlatStyle } ])}> {showExtensionList ? ( <ExtensionPanel acceptedFileTypes={acceptedFileTypes} closeExtensionList={this.closeExtensionList} /> ) : ( <div className={classes.uploaderContainer}> {!!acceptedFileTypes.length && ( <span className={classes.extensionListOpenButton} data-veritone-element="uploader-extension-open-btn" onClick={this.openExtensionList}> Extension Types </span> )} <span> <i className={cx(classes.fileUploadIcon, 'icon-ingest')} /> </span> <span className={classes.fileUploaderAcceptText}>{acceptMessage}</span> <label htmlFor="file"> <Button component="span" disableFocusRipple disableRipple> <span className={classes.fileUploaderSubtext}>{subMessage}</span> <span className={cx(classes.fileUploaderSubtext, classes.subtextBlue)}>browse</span> </Button> </label> <input accept={acceptedFileTypes.join(',')} style={{ display: 'none' }} id="file" multiple={this.props.multiple} type="file" onChange={this.handleFileSelection} ref={this.setInputRef} /> </div> )} {isOver && <div className={classes.uploaderOverlay} />} </div> ); } } export default FileUploader;
src/components/CodeForm.js
MattMcFarland/codepix-client
import React from 'react'; import ajax from 'superagent'; import Select from 'react-select'; import { Expander, Radio } from './partials/Elements'; import { ProtoFormClass, FormErrors } from './partials'; import { codeOptions } from './config'; export class CodeForm extends React.Component { constructor() { super(); var isOptionsExpanded = localStorage.getItem('isOptionsExpanded'); if (isOptionsExpanded && isOptionsExpanded === 'false') { isOptionsExpanded = false; } this.state = { isOptionsExpanded, visibility: localStorage.getItem('visibility') || 'public', codeLang: localStorage.getItem('pform_codeLang') || 'auto', textAreaValue: localStorage.getItem('pform_textAreaValue') || '', titleValue: localStorage.getItem('pform_titleValue') || '', descriptionValue: localStorage.getItem('pform_descriptionValue') || '' }; } clearLocalStorage = () => { localStorage.removeItem('pform_textAreaValue'); localStorage.removeItem('pform_titleValue'); localStorage.removeItem('pform_descriptionValue'); } clearState = () => { this.setState({textAreaValue: ''}); } handleTextAreaChange = (e) => { let val = e.target.value; this.setState({textAreaValue: val}); localStorage.setItem('pform_textAreaValue', val); } handleTitleChange = (e) => { let val = e.target.value; this.setState({titleValue: val}); localStorage.setItem('pform_titleValue', val); } handleDescriptionChange = (e) => { let val = e.target.value; this.setState({descriptionValue: val}); localStorage.setItem('pform_descriptionValue', val); } handleVisibilityChange = (e) => { this.setState({visibility: e.currentTarget.value}); localStorage.setItem('visibility', e.currentTarget.value); } handleCodeStyleChange = (value) => { this.setState({codeLang: value}); localStorage.setItem('pform_codeLang', value); } handleToggleOptions = () => { let newSetting = !this.state.isOptionsExpanded; localStorage.setItem('isOptionsExpanded', newSetting); this.setState({isOptionsExpanded: newSetting}); } componentWillMount() { window.ga('send', 'pageview', window.location.pathname); } validate = () => { var errors = []; var { textAreaValue, codeLang } = this.state; const rules = [ { failOn: textAreaValue.trim().length < 10, error: 'Please use at least 10 characters.' }, { failOn: codeLang === '', error: 'Please select a language.' } ]; rules.forEach((rule) => { if (rule.failOn) { errors.push(rule); } }); if (errors.length) { return { errors: errors, valid: false }; } else { return { errors: null, valid: true }; } } handleSubmit = (e) => { e.preventDefault(); let val = this.state.textAreaValue.trim(); this.setState({textAreaValue: val}); localStorage.setItem('pform_textAreaValue', val); var valid = this.validate(); if (valid.errors) { let article = valid.errors.length > 1 ? 'are' : 'is'; let noun = valid.errors.length > 1 ? 'errors' : 'error'; let count = valid.errors.length > 1 ? valid.errors.length : 'one'; this.setState({ error: { message: `There ${article} ${count} ${noun}, please try again.`, data: valid.errors } }); return; } { /* Ajax Post */ ajax.post('/api/add') .send({ title: this.state.titleValue, content: this.state.descriptionValue, language: this.state.codeLang, visibility: this.state.visibility, code: this.state.textAreaValue }) .set('Content-Type', 'application/json') .set('Accept', 'application/json') .set('X-no-legacy') .end((err, res) => { if (!err) { this.clearLocalStorage(); this.clearState(); this.props.history.pushState(null, '/code/' + res.body.shasum); } }); } } render() { // handlers let { handleSubmit, handleTextAreaChange, handleToggleOptions, handleVisibilityChange, handleCodeStyleChange, handleTitleChange, handleDescriptionChange } = this; // state let { codeLang, isOptionsExpanded, error, textAreaValue, titleValue, descriptionValue, visibility } = this.state; return ( <section> {error ? <FormErrors {...error} /> : ''} <ProtoFormClass onSubmit={handleSubmit}> <textarea placeholder="Put some code in here to convert to an image." value = {textAreaValue} onChange = {handleTextAreaChange} /> <div style={{ marginTop: '-15px', marginLeft: '-10px', marginBottom: '10px'}}> <Expander isExpanded={isOptionsExpanded} onToggle={handleToggleOptions} title="Options"> <hr/> <div style={{marginLeft: '15px'}}> <fieldset className="form-group"> <label style={{display: 'block'}}>Language: <Select name="codestyle" value={codeLang} options={codeOptions} onChange={handleCodeStyleChange}/> </label> </fieldset> <fieldset className="form-group"> <Radio name="visibility" value="public" set={visibility} onChange={handleVisibilityChange}> Public </Radio> <Radio disabled name="visibility" value="private" set={visibility} onChange={handleVisibilityChange}> Private (soon) </Radio> </fieldset> <fieldset className="form-group"> <label style={{display: 'block'}}>Title: <input type="text" value={titleValue} onChange={handleTitleChange} className="form-control"/> </label> </fieldset> <fieldset className="form-group"> <label style={{display: 'block'}}>Description: <textarea value={descriptionValue} onChange={handleDescriptionChange} className="form-control"/> </label> </fieldset> </div> </Expander> </div> </ProtoFormClass> </section> ); } }
src/components/Timetable/TimetableBackground.js
momomods/momomods
import React from 'react'; import _ from 'lodash'; import classnames from 'classnames'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { CELLS_COUNT } from '../../utils/timetable'; import s from './timetable.scss'; // Ref: https://github.com/yangshun/nusmods-v3/tree/master/src/js const TimetableBackground = () => ( <div className={classnames('timetable', 'timetable-bg')}> <div className={classnames('timetable-day')}> <div className={classnames('timetable-day-row')}> <div className={classnames('timetable-day-cell', 'timetable-d')}><span /></div> {_.map(_.range(CELLS_COUNT), (i) => ( <div key={i} className={classnames('timetable-cell', { 'timetable-cell-alt': i % 4 < 2, })} /> ) )} </div> </div> </div> ); export default withStyles(s)(TimetableBackground);
src/card.js
joxoo/react-material
import React from 'react'; import { getClassesStatic } from './addons/get-classes'; const Card = (props) => ( <div className={ getClassesStatic('card', props) }> { props.children } </div> ); export default Card;
src/components/common/svg-icons/notification/airline-seat-legroom-normal.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomNormal = (props) => ( <SvgIcon {...props}> <path d="M5 12V3H3v9c0 2.76 2.24 5 5 5h6v-2H8c-1.66 0-3-1.34-3-3zm15.5 6H19v-7c0-1.1-.9-2-2-2h-5V3H6v8c0 1.65 1.35 3 3 3h7v7h4.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5z"/> </SvgIcon> ); NotificationAirlineSeatLegroomNormal = pure(NotificationAirlineSeatLegroomNormal); NotificationAirlineSeatLegroomNormal.displayName = 'NotificationAirlineSeatLegroomNormal'; NotificationAirlineSeatLegroomNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomNormal;
src/handleReactRouter.js
nheyn/express-react-router
/** * @flow */ import React from 'react'; import { Router } from 'react-router'; import ReactDOMServer from 'react-dom/server'; import express from 'express'; import { match, RouterContext } from 'react-router'; import getReactRouterRoute from './router-traversal/getReactRouterRoute'; import getExpressRouter from './router-traversal/getExpressRouter'; import wasMadeUsing from './router-traversal/wasMadeUsing'; import addPropsToRouter from './addPropsToRouter'; import type { $Request as Request, Router as ExpressRouter } from 'express'; type ReactRouter = React.Element<*>; type PropArg = Object | (req: Request) => Object; /** * Create an express router for the given react-router routes. * * @param routes {ReactRouter} The router to render * @param PageComponent {ReactClass} A class that takes the render html string, reactHtml, and a * express request, req, as a prop and returns markup for the * entire page. * NOTE: This is render using 'renderToStaticMarkdown(...)' with * '<!DOCTYPE html>' placed before it. * @param ...propArgs {Array<Object | Func>} All arguments after routes is used to add props to the top-level * components in the router * * @return {ExpressRouter} The express router to add to the express application */ export default function handleReactRouter( routes: ReactRouter, //ERROR, aperently React.Component<*, *, *> is not a component: "Expected React component instead of React$Component" PageComponent: any, ...propArgs: Array<PropArg> ): ExpressRouter { // Check args route if(!routes) throw new Error('Route is required for the server'); if(!PageComponent) throw new Error('PageComponent is required for the server'); // Combine props const getAllProps = (req) => { let currProps = {}; propArgs.forEach((nextProps) => { const newProps = typeof nextProps === 'function'? nextProps(req): nextProps; currProps = { ...currProps, ...newProps }; }); return currProps; }; // Parse Routes const reactRouterRoutes = getReactRouterRoute(routes); const expressRouterFromRoute = getExpressRouter(routes); // Create express router let router = express.Router(); //$FlowFixMe router.use(expressRouterFromRoute); // $FlowFixMe router.use((req, res, next) => { // Skip wrapper components (like react-redux Provider) const { routes, rewrapRouter } = unwrapRouter(reactRouterRoutes); // Render current route match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if(err) { // Handle errors below next(err); } else if(redirectLocation) { // Handle redirect res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if(renderProps) { let routerContextElement = <RouterContext {...renderProps} />; // Add props if(propArgs.length) routerContextElement = addPropsToRouter(routerContextElement, getAllProps(req)); // Render page with current element from router const renderedReactHtml = ReactDOMServer.renderToString(rewrapRouter(routerContextElement)); const pageHtml = ReactDOMServer.renderToStaticMarkup( //TODO, rewrap router agian because match(...) is a horibly written function <PageComponent req={req} reactHtml={renderedReactHtml} /> ); // Send entire page to client res .status(isPageNotFoundRoutes(renderProps.routes)? 404: 200) .send(`<!DOCTYPE html> ${pageHtml}`); } else { // Render page with error const pageHtml = ReactDOMServer.renderToStaticMarkup( <PageComponent req={req} error={new Error(`Invalid url: ${req.url}`)} is404 /> ); // Send entire page to client res .status(404) .send(`<!DOCTYPE html> ${pageHtml}`); } }); }); // $FlowFixMe router.use((err, req, res, next) => { // Skip this middleware if the request doesn't not accept html if(!req.accepts('html')) { next(err); return; } // Render page with error const pageHtml = ReactDOMServer.renderToStaticMarkup( <PageComponent req={req} error={err} /> ); // Send entire page to client res .status(500) .send(`<!DOCTYPE html> ${pageHtml}`); }); return router; } function isPageNotFoundRoutes(routes: Array<any>): bool { const currRoutes = routes[routes.length - 1]; if(!currRoutes.path) return false; // Check if last char is wild chard, NOTE: means any wildcard (non-404) pages must use params const lastCharInPath = currRoutes.path.charAt(currRoutes.path.length-1); return lastCharInPath === '*'; } function unwrapRouter( el: React.Element<*>, rewrapRouter?: (el: React.Element<*>) => React.Element<*>, ): { routes: React.Element<*>, rewrapRouter: (el: React.Element<*>) => React.Element<*> } { if(wasMadeUsing(el, Router)) { return { routes: el, rewrapRouter(currEl) { return rewrapRouter? rewrapRouter(currEl): currEl; }, }; } if(React.Children.count(el.props.children) !== 1) throw new Error('Must be given a single root Router.'); const child = React.Children.only(el.props.children); return unwrapRouter( child, (childEl) => { const wrappedEl = React.cloneElement(el, null, childEl); return rewrapRouter? rewrapRouter(wrappedEl): wrappedEl; }, ); }
src/core/markers/PolylineMarker.js
mocheer/react-map
import React from 'react'; export const PolylineMarker = React.createClass({ render: function () { var state = this.state; return null; } });
app/containers/LanguageProvider/index.js
fenderface66/spotify-smart-playlists
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
src/index.js
tomorrowshine/cra-app
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import leaveWord from './containers/leaveWord'; import list from './containers/list/list'; import registerServiceWorker from './registerServiceWorker'; import { Provider } from 'react-redux' import store from './store'; import { Router, Route,Switch } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import history from './component/History' syncHistoryWithStore(history, store)//时光之旅 ReactDOM.render( <Provider store={store}> <Router history={history}> <Switch> <Route exact path='/' component={App}/> <Route path='/leaveWord' component={leaveWord}/> <Route path='/list' component={list}/> </Switch> </Router> </Provider>, document.getElementById('root')); registerServiceWorker();
src/components/Dock/Dock.js
bibleexchange/be-front-new
import React from 'react'; import { createFragmentContainer, graphql, } from 'react-relay/compat'; import { Link } from 'react-router'; import Loading from '../ListWidget/Loading' //import SoundCloudPlayer from './SoundCloudPlayer' import NoteEditor from '../NoteEditor/NoteEditorWidget' import './Dock.scss'; import NoteOptions from '../Note/NoteOptions'; import NotesWidget from '../Note/NotesWidget'; import MagnifyingGlass from '../Svg/MagnifyingGlass'; import Bookmark from '../Bookmark/BookmarkComponent'; class Search extends React.Component { render() { let that = 'p'; return ( <form id='main-search' onSubmit={this.props.searchIt} > <input id='search-text' type='text' name='search' placeholder='search notes...' onChange={this.props.handleUpdateSearch} /> <button onClick={this.props.searchIt}>&nbsp; <MagnifyingGlass /> </button> </form> ); } } class Dock extends React.Component { componentWillMount() { this.state = { filterBy: this.props.notesWidget.filter }; } render() { let status = this.props.status let playStatus = null let notepadButton = null let notepadMain = null let audioButton = null let verseButton = null let verseMain= null let audioMain = null let shareMain = null let shareButton = null if (this.props.user.authenticated){ notepadButton = <li className={"menu-"+ status.notepad}><button onClick={this.props.showInDockMenu} data-name="notepad">notepad</button></li> notepadMain = <li id="notepad" className={"main-"+ status.notepad}> <NoteEditor myNotesWidget={this.props.myNotesWidget} handleUpdateMyNoteFilter={this.props.handleUpdateMyNoteFilter} handleUpdateNote={this.props.handleUpdateNote} moreNotes={this.props.moreMyNotes} user={this.props.user} note={this.props.note} notes={this.props.myNotes} handleEditThis={this.props.handleEditThisNote}/> </li> }else{ notepadButton = null notepadMain = null } if(this.props.player.playStatus === true){ playStatus = '(!)' } if(this.props.player === undefined || this.props.player === null || this.props.player.playStatus === false){ audioButton = null audioMain = null }else{ audioButton = <li id="audio-player" className={"menu-"+ status.soundcloud}><button onClick={this.props.showInDockMenu} data-name="soundcloud">audio {playStatus}</button></li> //audioMain = <li id="soundcloud" className={"main-"+ status.soundcloud}><SoundCloudPlayer id={this.props.player.currentSoundId} status={this.props.player.playStatus} handleCloseAudio={this.props.handleCloseAudio}/></li> } if(this.props.bibleVerse === undefined || this.props.bibleVerse === null || this.props.bibleVerse.reference === null){ verseButton = null verseMain = null }else{ verseButton = <li id="verse" className={"menu-"+ status.verse}><button onClick={this.props.showInDockMenu} data-name="verse">{this.props.crossReferences.edges.length} related verses ({this.props.bibleVerse.reference})</button></li> verseMain = <li id="verse" className={"main-"+ status.verse}>{this.renderVerse()}</li> } shareButton = <li id="share" className={"menu-"+ status.share}><button onClick={this.props.showInDockMenu} data-name="share">share</button></li> shareMain = <li id="share" className={"main-"+ status.share}> <NoteOptions note={this.props.note} user={this.props.user} editThisNote={this.props.handleEditThisNote} location={this.props.location}/></li> let notesButton = <li id="notes" className={"menu-"+ status.notes}><button onClick={this.props.showInDockMenu} data-name="notes">{this.props.notesWidget.filter} ({this.props.notes.totalCount} notes)</button></li> let notesMain = <li id="notes" className={"main-"+ status.notes}>{this.renderNotes()}</li> return ( <div id='dock-widget'> <div id="dock-main"> <nav id="dock-menu"> <ul> {audioButton} {notepadButton} {shareButton} {verseButton} {notesButton} </ul> </nav> <ul className="main"> {shareMain} {audioMain} {notepadMain} {verseMain} {notesMain} </ul> </div> </div> ); } renderNotes(){ return (<NotesWidget status={this.props.notesWidget} notes={this.props.notes} selectNote={this.props.handleEditThisNote} handleUpdateNoteFilter={this.props.handleUpdateNoteFilter} handleNextNotePage={this.props.handleNextNotePage} handleNotesAreReady={this.props.handleNotesAreReady} user={this.props.user} />) } renderVerse(){ let cr = [] if(this.props.crossReferences !== undefined && this.props.crossReferences.edges !== undefined){ cr = this.props.crossReferences.edges } return ( <span> <p> <strong> {this.props.reference} cross references: </strong> {cr.map(function(c){ let verses = '' c.node.verses.edges.map(function(v){ verses += v.node.order_by + " " + v.node.body + " " }) return <Link key={c.node.id} to={c.node.url} title={verses} >| {c.node.reference} </Link>; })} </p> </span>) } } Dock.propTypes = { user: React.PropTypes.object.isRequired, note: React.PropTypes.object, notes: React.PropTypes.object.isRequired, relay: React.PropTypes.object.isRequired }; Dock.contextTypes = { router: React.PropTypes.object.isRequired }; export default createFragmentContainer(Dock, { note: ()=> Relay.QL`fragment on Note { ...NoteEditor_note ...NoteOptions_note id title type body tags_string verse{ id reference } }`, user: graphql` fragment Dock_user on User { ...NoteOptions_user ...NotesWidget_user authenticated name email ...NoteEditor_user } `, bibleVerse: () => Relay.QL`fragment on BibleVerse { id reference notesCount }`, crossReferences: () => Relay.QL`fragment on CrossReferenceConnection { pageInfo{hasNextPage} edges{ node { id url reference verses(first:50){ edges{ node{ id order_by body } } } } } }`, notes: graphql` fragment Dock_notes on NoteConnection { ...NotesWidget_notes pageInfo{hasNextPage} totalCount totalPagesCount currentPage edges{ node { id title verse {id, reference} } } }`, });
examples/cra/src/components/RandomButton.js
styleguidist/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import sample from 'lodash/sample'; import './RandomButton.css'; /** * Button that changes label on every click. */ export default class RandomButton extends Component { static propTypes = { /** * List of possible labels. */ variants: PropTypes.array.isRequired, }; constructor(props) { super(); this.state = { label: sample(props.variants), }; } handleClick = () => { this.setState({ label: sample(this.props.variants), }); }; render() { return ( <button className="random-button" onClick={this.handleClick}> {this.state.label} </button> ); } }
src/containers/App/index.js
hasibsahibzada/quran.com-frontend
/* eslint-disable react/prefer-stateless-function */ import React, { Component } from 'react'; import * as customPropTypes from 'customPropTypes'; import { metrics } from 'react-metrics'; import { connect } from 'react-redux'; import { asyncConnect } from 'redux-connect'; import Helmet from 'react-helmet'; import Modal from 'react-bootstrap/lib/Modal'; import Loadable from 'react-loadable'; import ComponentLoader from 'components/ComponentLoader'; import debug from 'helpers/debug'; import config from 'config'; import metricsConfig from 'helpers/metrics'; import Footer from 'components/Footer'; import NoScript from 'components/NoScript'; import PropTypes from 'prop-types'; import { removeMedia } from 'redux/actions/media'; import Loader from 'quran-components/lib/Loader'; import authConnect from './connect'; const ModalHeader = Modal.Header; const ModalTitle = Modal.Title; const ModalBody = Modal.Body; const GlobalNav = Loadable({ loader: () => import(/* webpackChunkName: "globalnav" */ 'components/GlobalNav'), LoadingComponent: ComponentLoader }); const GlobalSidebar = Loadable({ loader: () => import(/* webpackChunkName: "globalsidebar" */ 'components/GlobalSidebar'), LoadingComponent: ComponentLoader }); const SmartBanner = Loadable({ loader: () => import(/* webpackChunkName: "smartbanner" */ 'components/SmartBanner'), LoadingComponent: ComponentLoader }); class App extends Component { static contextTypes = { store: PropTypes.object.isRequired }; state = { sidebarOpen: false }; renderModalBody() { const { media } = this.props; if (media.loading) { return ( <div className="embed-responsive embed-responsive-16by9"> <Loader isActive relative /> </div> ); } return ( <div className={`embed-responsive embed-responsive-16by9 ${media.wrapperClass}`} dangerouslySetInnerHTML={{ __html: media.content.body }} /> ); } render() { const { main, nav, footer, children, media, removeMedia, // eslint-disable-line no-shadow ...props } = this.props; debug('component:APPLICATION', 'Render'); return ( <div> <Helmet {...config.app.head} /> <NoScript> <div className="row noscript-warning"> <div className="col-md-12"> <p> Looks like either your browser does not support Javascript or its disabled. Quran.com workes best with JavaScript enabled. For more instruction on how to enable javascript <a href="http://www.enable-javascript.com/"> Click here </a> </p> </div> </div> </NoScript> {React.cloneElement(nav || <GlobalNav isStatic {...props} />, { handleSidebarToggle: () => this.setState({ sidebarOpen: !this.state.sidebarOpen }) })} {__CLIENT__ && <GlobalSidebar open={this.state.sidebarOpen} handleOpen={open => this.setState({ sidebarOpen: open })} />} {children || main} <SmartBanner title="The Noble Quran - القرآن الكريم" button="Install" /> {footer || <Footer />} {__CLIENT__ && media.show && <Modal bsSize={media.size} show={media.show} onHide={removeMedia}> <ModalHeader closeButton> <ModalTitle className="montserrat"> {media.content.title} </ModalTitle> </ModalHeader> <ModalBody> {this.renderModalBody()} </ModalBody> </Modal>} </div> ); } } const metricsApp = metrics(metricsConfig)(App); const AsyncApp = asyncConnect([{ promise: authConnect }])(metricsApp); App.propTypes = { media: customPropTypes.media.isRequired, removeMedia: PropTypes.func.isRequired, children: PropTypes.element, main: PropTypes.element, nav: PropTypes.element, footer: PropTypes.element, sidebar: PropTypes.element, footNote: customPropTypes.footNoteType, loadingFootNote: PropTypes.bool }; export default connect( state => ({ media: state.media }), { removeMedia } )(AsyncApp);
ui/js/dfv/src/fields/pick/checkbox-select.js
pods-framework/pods
import React from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import { PICK_OPTIONS } from 'dfv/src/config/prop-types'; import './checkbox-select.scss'; const CheckboxSelect = ( { htmlAttributes, name, value, options = [], setValue, isMulti, readOnly = false, } ) => { const toggleValueOption = ( option ) => { if ( value.some( ( valueItem ) => valueItem.toString() === option.toString() ) ) { setValue( value.filter( ( item ) => item.toString() !== option.toString() ) ); } else { setValue( [ ...value, option ] ); } }; const totalOptions = options.length; return ( <ul className={ classnames( 'pods-checkbox-pick', options.length === 1 && 'pods-checkbox-pick--single' ) } id={ name } > { options.map( ( { id: optionValue, name: optionLabel, }, optionIndex, allOptions ) => { const nameBase = htmlAttributes.name || name; const nameAttribute = allOptions.length > 1 ? `${ nameBase }[${ optionIndex }]` : nameBase; let idAttribute = !! htmlAttributes.id ? htmlAttributes.id : `pods-form-ui-${ name }`; if ( 1 < totalOptions ) { idAttribute += `-${ optionValue }`; } return ( <li key={ optionValue } className={ classnames( 'pods-checkbox-pick__option', options.length === 1 && 'pods-checkbox-pick__option--single' ) } > <div className="pods-field pods-boolean"> { /* eslint-disable-next-line jsx-a11y/label-has-for */ } <label className="pods-form-ui-label pods-checkbox-pick__option__label" > <input name={ nameAttribute } id={ idAttribute } checked={ isMulti ? value.some( ( valueItem ) => valueItem.toString() === optionValue.toString() ) : value.toString() === optionValue.toString() } className="pods-form-ui-field-type-pick" type="checkbox" value={ optionValue } onChange={ () => { if ( readOnly ) { return; } if ( isMulti ) { toggleValueOption( optionValue ); } else { // Workaround for boolean fields: const unsetValue = ( 1 === options.length && optionValue === '1' ) ? '0' : undefined; setValue( value === optionValue ? unsetValue : optionValue ); } } } readOnly={ !! readOnly } /> { optionLabel } </label> </div> </li> ); } ) } </ul> ); }; CheckboxSelect.propTypes = { htmlAttributes: PropTypes.shape( { id: PropTypes.string, class: PropTypes.string, name: PropTypes.string, } ), name: PropTypes.string.isRequired, value: PropTypes.oneOfType( [ PropTypes.arrayOf( PropTypes.oneOfType( [ PropTypes.string, PropTypes.number, ] ) ), PropTypes.string, PropTypes.number, ] ), setValue: PropTypes.func.isRequired, options: PICK_OPTIONS.isRequired, isMulti: PropTypes.bool.isRequired, readOnly: PropTypes.bool, }; export default CheckboxSelect;
src/Calendar.js
Hanse/react-calendar
import React, { Component } from 'react'; import moment from 'moment'; import PropTypes from 'prop-types'; import cx from 'classnames'; import createDateObjects from './createDateObjects'; export default class Calendar extends Component { static propTypes = { /** Week offset*/ weekOffset: PropTypes.number.isRequired, /** The current date as a moment objecct */ date: PropTypes.object.isRequired, /** Function to render a day cell */ renderDay: PropTypes.func, /** Function to render the header */ renderHeader: PropTypes.func, /** Called on next month click */ onNextMonth: PropTypes.func, /** Called on prev month click */ onPrevMonth: PropTypes.func, /** Called when some of the navigation controls are clicked */ onChangeMonth: PropTypes.func, /** Called when a date is clicked */ onPickDate: PropTypes.func, /** classname for div wrapping the whole calendar */ containerClassName: PropTypes.string, /** classname for the div wrapping the grid */ contentClassName: PropTypes.string }; static defaultProps = { weekOffset: 0, renderDay: ({ day, classNames, onPickDate }) => ( <div key={day.format()} className={cx( 'Calendar-grid-item', day.isSame(moment(), 'day') && 'Calendar-grid-item--current', classNames )} onClick={e => onPickDate(day)} > {day.format('D')} </div> ), renderHeader: ({ date, onPrevMonth, onNextMonth }) => ( <div className="Calendar-header"> <button onClick={onPrevMonth}>«</button> <div className="Calendar-header-currentDate"> {date.format('MMMM YYYY')} </div> <button onClick={onNextMonth}>»</button> </div> ) }; handleNextMonth = () => { if (this.props.onNextMonth) { return this.props.onNextMonth(); } this.props.onChangeMonth(this.props.date.clone().add(1, 'months')); }; handlePrevMonth = () => { if (this.props.onPrevMonth) { return this.props.onPrevMonth(); } this.props.onChangeMonth(this.props.date.clone().subtract(1, 'months')); }; render() { const { date, weekOffset, renderDay, renderHeader, onPickDate, contentClassName, containerClassName } = this.props; return ( <div className={cx('Calendar', containerClassName)}> {renderHeader({ date, onPrevMonth: this.handlePrevMonth, onNextMonth: this.handleNextMonth })} <div className={cx('Calendar-grid', contentClassName)}> {createDateObjects(date, weekOffset).map((day, i) => renderDay({ ...day, onPickDate }) )} </div> </div> ); } }
src/components/Auth/PrivateRoute.js
dovydasvenckus/time-tracker-web
import React from 'react'; import PropTypes from 'prop-types'; import { Route } from 'react-router-dom'; import { AuthConsumer } from '../../utils/auth/authProvider'; const PrivateRoute = ({ component, ...rest }) => { const renderFn = (Component) => (props) => ( <AuthConsumer> {({ isAuthenticated, signInRedirect }) => { if (!!Component && isAuthenticated()) { return <Component {...props} />; } signInRedirect(); return <span>loading</span>; }} </AuthConsumer> ); return <Route {...rest} render={renderFn(component)} />; }; PrivateRoute.propTypes = { component: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), }; export default PrivateRoute;
src/todo/input.js
corgisamurai/spary_react
import React from 'react' import { Component } from 'react' class TodoInput extends Component { _onAddToDo(){ var newTodo = this.refs.todo.value.trim(); this.props.onAddToDo(newTodo); this.refs.todo.value=""; } _getOnsen(){ axios.post('/api/onsen/list') .then(function (res) { console.log(res.data); }); } render () { return ( <div> <input type="text" ref="todo" /> <input type="button" value="submit" onClick={this._onAddToDo.bind(this)} /> <input type="button" value="温泉を取得" onClick={this._getOnsen.bind(this)} /> </div> ) } } export default TodoInput
src/components/Main.js
jerwu/graduationProject
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom'; //获取图片相关的数据 var imageDatas = require('../data/imageDatas.json'); //利用自执行函数,将图片名信息转成图片URL路径信息 imageDatas=(function genImageURL(imageDatasArr){ for(var i = 0,j = imageDatas.length;i < j;i++){ var singleImageData=imageDatasArr[i]; singleImageData.imageURL=require('../images/'+singleImageData.fileName); imageDatasArr[i]=singleImageData; } return imageDatasArr; })(imageDatas); //获取区间的一个随机值 function getRangeRandom(low,high){ return Math.ceil(Math.random() * (high - low) + low); } //获取0~30度的旋转角度值 function get30DegRandom(){ return ((Math.random() > 0.5 ? '' : '') + Math.ceil(Math.random() * 30)); } class ImgFigureComponent extends React.Component{ //聚焦到该图片所对应的位置 focus(){ var map = new BMap.Map(this.props.data.id); // map.centerAndZoom(new BMap.Point(this.props.data.geoPos[0],this.props.data.geoPos[1]), 15); var lng = this.props.data.geoPos[0]; var lat = this.props.data.geoPos[1]; var point = new BMap.Point(lng, lat); map.centerAndZoom(point, 13); //设置点的弹跳动画 var marker = new BMap.Marker(point); // 创建标注 map.addOverlay(marker); // 将标注添加到地图中 marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画 //缩放地图 setTimeout(function(){ map.setZoom(15); }, 2000); map.enableScrollWheelZoom(true);//允许缩放地图 // map.disableDragging();//禁止拖拽 } //mapClick mapClick = (ev) => { ev.preventDefault(); ev.stopPropagation(); } //imgFigure的点击处理函数 handleClick = (ev) => { if (this.props.arrange.isCenter) { this.props.inverse(); this.focus(); }else{ this.props.center(); } ev.preventDefault(); ev.stopPropagation(); } shareBtnClick = (ev) => { ev.preventDefault(); ev.stopPropagation(); } render(){ let styleObj = {}; //如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } //如何图片有软砖角度且不为0,添加旋转角度 if (this.props.arrange.rotate) { (['MozTransform','msTransform','WebkitTransform','transform']).forEach((value => { styleObj[value] = 'rotate('+this.props.arrange.rotate + 'deg)'; }).bind(this)); } //把中心图片的zindex设成11 if (this.props.arrange.isCenter) { styleObj.zIndex = 11; } let imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return ( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick} > <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <div className="bd-map" id={this.props.data.id} onClick={this.mapClick} > </div> </div> </figcaption> </figure> ); } } // <div className="shareBlock"> // <button type="button">分享到微博</button> // </div> //添加控制组件coomponent class ControllerUnitComponent extends React.Component{ // 写法有问题:会提示报错cannot read property 'props' of null 在95行 //原因:还不知道????? // handleClick(ev){ // //如果点击的是当前正在选中态的图片,则翻转图片,否则将对应的图片居中 // if (this.props.arrange.isCenter) { // this.props.inverse(); // }else{ // this.props.center(); // } // ev.preventDefault(); // ev.stopPropagation(); // } handleClick = (ev) => { //如果点击的是当前正在选中态的图片,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); }else{ this.props.center(); } ev.preventDefault(); ev.stopPropagation(); } render(){ let controllerUnitClassName = 'controller-unit'; //如果对应的是居中图片,显示控制按钮的居中态 if (this.props.arrange.isCenter) { controllerUnitClassName += ' is-center'; if (this.props.arrange.isInverse) { controllerUnitClassName += ' is-inverse'; } } return( <span className={controllerUnitClassName} onClick={this.handleClick} /> ); } } class AppComponent extends React.Component { //因为react版本太高,要使用支持es6语法把下面属性定义到app类的构造函数中 // Constant:{ // centerPos:{ // left:0, // top:0 // }, // hPosRange:{ //水平方向的取值范围(左右分区) // leftSecX:[0,0], // rightSecX:[0,0], // y:[0,0] // }, // vPosRange:{ //垂直方向上的取值范围(上分区) // x:[0,0], // topY:[0,0] // } // }; //闭包this问题 center(index){ return (() =>{this.reArrange(index)}).bind(this); } // getInitialState(){ // return { // imgsArrangeArr:[ // { // pos:{ // left:'0', // top:'0' // }, // rotate: 0, //图片旋转 // isInverse: false //图片翻转 // isCenter:false // } // ] // } // } //因为getInitialState不支持es6 classes constructor(props){ super(props); this.state = { imgsArrangeArr:[ { pos:{ left:'0', top:'0' }, rotate: 0, isInverse: false, isCenter: false } ] }; this.Constant = { centerPos:{ left:0, top:0 }, hPosRange:{ //水平方向的取值范围(左右分区) leftSecX:[0,0], rightSecX:[0,0], y:[0,0] }, vPosRange:{ //垂直方向上的取值范围(上分区) x:[0,0], topY:[0,0] } }; // this.inverse = function (){ // return function (){ // var imgsArrangeArr = this.state.imgsArrangeArr; // imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; // this.setState({ // imgsArrangeArr:imgsArrangeArr // }); // }.bind(this) // } } /* *翻转图片 *@params index 输出当前被执行inverse操作的图片在对应的图片信息数组中的index值 *@return {function} 返回一个闭包函数,其内return一个真正待被执行的函数 *?????:搞清楚为什么使用闭包(图片翻转课程05;55) */ //闭包this问题:说return is not defined; inverse(index){ return ((()=>{ var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr:imgsArrangeArr }); }).bind(this)); } //重新布局所有图片, //@params centerIndex 指定居中排布哪个图片 reArrange(centerIndex){ var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeX = vPosRange.x, vPosRangeTopY = vPosRange.topY, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), //取1个或者不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1); //首先居中 centerIndex 的图片,centerIndex 的图片不用旋转 imgsArrangeCenterArr[0] = { pos:centerPos, rotate:0, isCenter:true } //取出要布局上侧图片的状态信息??????? topImgSpliceIndex = Math.ceil(Math.random() *(imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum); //布局位于上侧的图片 imgsArrangeTopArr.forEach(function(value,index){ imgsArrangeTopArr[index]={ pos:{ left:getRangeRandom(vPosRangeX[0],vPosRangeX[1]), top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]) }, rotate:get30DegRandom(), isCenter:false }; }); //布局左右两侧的图片 for(var i = 0, j = imgsArrangeArr.length, k = j / 2;i < j;i++){ var hPosRangeLORX = null; //前半部分布局左边,后半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; }else{ hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos:{ left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1]), top:getRangeRandom(hPosRangeY[0],hPosRangeY[1]) }, rotate:get30DegRandom(), isCenter:false }; } if (imgsArrangeTopArr && imgsArrangeTopArr[0]){ imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr:imgsArrangeArr }); } //组件加载之后,为每张图片计算其位置的范围 componentDidMount(){ //首先拿到舞台的大小 let stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW =stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //拿到imgFigure的大小 let imgFigureDom = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDom.scrollWidth, imgH = imgFigureDom.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //计算中心图片的位置点 this.Constant.centerPos={ left:halfStageW - halfImgW, top:halfStageH - halfImgH }; //计算左右分区图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[0] = stageH - halfImgH; //计算上分区图片排布位置的取值范围 this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.reArrange(0); } render() { let controllerUnits = [], imgFigures=[]; imageDatas.forEach(((value,index) => { if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index] = { pos:{ left:'0', top:'0' }, rotate: 0, isInverse: false, isCenter: false } } //在遍历或者循环输出去渲染子组件的时候,key必不可少 imgFigures.push(<ImgFigureComponent key={index} index={index} data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); controllerUnits.push(<ControllerUnitComponent key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); }).bind(this)); // imageDatas.forEach(function(value,index){ // if(!this.state.imgsArrangeArr[index]){ // this.state.imgsArrangeArr[index] = { // pos:{ // left:'0', // top:'0' // } // }; // } // imgFigures.push(<ImgFigure data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]}/>) // }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
client/src/app/routes/graphs/containers/ChartJs.js
zraees/sms-project
import React from 'react' import request from 'then-request' import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../components' import ChartJsGraph from '../../../components/graphs/chartjs/ChartJsGraph' export default class ChartJs extends React.Component { state = {}; componentWillMount() { request('GET', 'assets/api/graphs/chartjs.json', {json: true}).done((res)=> { this.setState(JSON.parse(res.getBody())); }) } render() { return ( <div id="content"> <div className="row"> <BigBreadcrumbs items={['ChartJs']} icon="fa fa-fw fa-bar-chart-o" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/> <Stats /> </div> <WidgetGrid> <div className="row"> <article className="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Line Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="line" data={this.state['line-chart']}/> </div> </div> </JarvisWidget> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Radar Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="radar" data={this.state['radar-chart']}/> </div> </div> </JarvisWidget> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Polar Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="polarArea" data={this.state['polar-chart']}/> </div> </div> </JarvisWidget> </article> <article className="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Bar Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="bar" data={this.state['bar-chart']}/> </div> </div> </JarvisWidget> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Doughnut Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="doughnut" data={this.state['doughnut-chart']}/> </div> </div> </JarvisWidget> <JarvisWidget editbutton={false}> <header> <span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span> <h2>Pie Chart</h2> </header> <div> <div className="widget-body"> <ChartJsGraph type="pie" data={this.state['pie-chart']}/> </div> </div> </JarvisWidget> </article> </div> </WidgetGrid> </div> ) } }
samples/react-redux-patient-demographics-example/src/routes/Patient/Demographics/PatientDemographicsComponent.js
GoTeamEpsilon/angular-to-react-redux
import React from 'react' import { browserHistory } from 'react-router' import Basic from './Basic/BasicComponent' import Contact from './Contact/ContactComponent' class PatientDemographics extends React.Component { constructor() { super() this.TABS = { BASIC: 'basic', CONTACTS: 'contacts' } this.state = { tab: this.TABS.BASIC, isLoading: false } } setPatientInContext() { this.setState({ isLoading: true }) this.props.setPatientInContext(this.props.routeParams.pid) .then(() => { this.setState({ isLoading: false }) }); } addNewContact() { this.props.startAddingNewContact(this.props.routeParams.pid) } determineIfRouteIsValid() { return this.props.routeParams.pid } componentDidMount() { if (!this.determineIfRouteIsValid()) { browserHistory.push('/patient/1337') location.reload() } else { this.setPatientInContext() } } mockedTab() { alert('This tab is just here for completeness. The real tabs are basic and contacts') } changeTab(newTab) { console.debug(`Setting tab to ${newTab}`) this.setState({ tab: newTab }) } render() { let children = null let addContactVisibility = 'hidden' switch (this.state.tab) { case this.TABS.BASIC: children = <Basic basic={this.props.basic} updatePatientData={this.props.updatePatientData} /> break; case this.TABS.CONTACTS: if (this.props.contacts) { children = this.props.contacts.map((contact) => { return <Contact updateContactData={this.props.updateContactData} deleteContact={this.props.deleteContact} key={contact.id} contact={contact}/> } ) } addContactVisibility = 'visible' break; } return ( <div> <h3 className={this.state.isLoading ? '' : 'hidden'}>Loading...</h3> <div className={this.state.isLoading ? 'hidden' : ''}> <div> <ul className='nav nav-tabs'> <li className={this.state.tab === this.TABS.BASIC ? 'active' : ''}> <a onClick={() => this.changeTab(this.TABS.BASIC)}>Basic</a> </li> <li className={this.state.tab === this.TABS.CONTACTS ? 'active' : ''}> <a onClick={() => this.changeTab(this.TABS.CONTACTS)}>Contacts</a> </li> <li><a onClick={this.mockedTab}>Choices</a></li> <li><a onClick={this.mockedTab}>Employer</a></li> <li><a onClick={this.mockedTab}>Stats</a></li> <li><a onClick={this.mockedTab}>Misc</a></li> </ul> </div> {children} <br /> <button type='button' className={['btn', 'btn-default', 'btn-sm', addContactVisibility].join(' ')} onClick={this.addNewContact.bind(this)}>ADD NEW CONTACT</button> </div> </div> ) } } export default PatientDemographics
fields/types/color/ColorColumn.js
webteckie/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var ColorColumn = React.createClass({ displayName: 'ColorColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value) return null; const colorBoxStyle = { backgroundColor: value, borderRadius: 3, display: 'inline-block', height: 18, marginRight: 10, verticalAlign: 'middle', width: 18, }; return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <div style={{ lineHeight: '18px' }}> <span style={colorBoxStyle} /> <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{value}</span> </div> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = ColorColumn;
app/javascript/mastodon/components/icon_button.js
ashfurrow/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import AnimatedNumber from 'mastodon/components/animated_number'; export default class IconButton extends React.PureComponent { static propTypes = { className: PropTypes.string, title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, onClick: PropTypes.func, onMouseDown: PropTypes.func, onKeyDown: PropTypes.func, onKeyPress: PropTypes.func, size: PropTypes.number, active: PropTypes.bool, pressed: PropTypes.bool, expanded: PropTypes.bool, style: PropTypes.object, activeStyle: PropTypes.object, disabled: PropTypes.bool, inverted: PropTypes.bool, animate: PropTypes.bool, overlay: PropTypes.bool, tabIndex: PropTypes.string, counter: PropTypes.number, obfuscateCount: PropTypes.bool, href: PropTypes.string, }; static defaultProps = { size: 18, active: false, disabled: false, animate: false, overlay: false, tabIndex: '0', }; state = { activate: false, deactivate: false, } componentWillReceiveProps (nextProps) { if (!nextProps.animate) return; if (this.props.active && !nextProps.active) { this.setState({ activate: false, deactivate: true }); } else if (!this.props.active && nextProps.active) { this.setState({ activate: true, deactivate: false }); } } handleClick = (e) => { e.preventDefault(); if (!this.props.disabled) { this.props.onClick(e); } } handleKeyPress = (e) => { if (this.props.onKeyPress && !this.props.disabled) { this.props.onKeyPress(e); } } handleMouseDown = (e) => { if (!this.props.disabled && this.props.onMouseDown) { this.props.onMouseDown(e); } } handleKeyDown = (e) => { if (!this.props.disabled && this.props.onKeyDown) { this.props.onKeyDown(e); } } render () { const style = { fontSize: `${this.props.size}px`, width: `${this.props.size * 1.28571429}px`, height: `${this.props.size * 1.28571429}px`, lineHeight: `${this.props.size}px`, ...this.props.style, ...(this.props.active ? this.props.activeStyle : {}), }; const { active, className, disabled, expanded, icon, inverted, overlay, pressed, tabIndex, title, counter, obfuscateCount, href, } = this.props; const { activate, deactivate, } = this.state; const classes = classNames(className, 'icon-button', { active, disabled, inverted, activate, deactivate, overlayed: overlay, 'icon-button--with-counter': typeof counter !== 'undefined', }); if (typeof counter !== 'undefined') { style.width = 'auto'; } let contents = ( <React.Fragment> <Icon id={icon} fixedWidth aria-hidden='true' /> {typeof counter !== 'undefined' && <span className='icon-button__counter'><AnimatedNumber value={counter} obfuscate={obfuscateCount} /></span>} </React.Fragment> ); if (href) { contents = ( <a href={href} target='_blank' rel='noopener noreferrer'> {contents} </a> ); } return ( <button aria-label={title} aria-pressed={pressed} aria-expanded={expanded} title={title} className={classes} onClick={this.handleClick} onMouseDown={this.handleMouseDown} onKeyDown={this.handleKeyDown} onKeyPress={this.handleKeyPress} style={style} tabIndex={tabIndex} disabled={disabled} > {contents} </button> ); } }