path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/router.js
gusdewa/MultiStores
import React from 'react'; /* eslint-disable */ function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i++) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map(key => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
pages/about.js
willopez/project-seed
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import Layout from '../components/layout'; export default class About extends Component { static async getInitialProps({ req }) { if (req) { Helmet.renderStatic(); } return { title: 'About' }; } static propTypes = { title: PropTypes.string.isRequired }; render() { const { title } = this.props; return ( <Layout> <Helmet title={title} /> <h1 className="cover-heading">About</h1> <p className="lead"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </Layout> ); } }
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
thuongho/dream-machine
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/chrome/Chrome.js
casesandberg/react-color
import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue, Alpha, Checkboard } from '../common' import ChromeFields from './ChromeFields' import ChromePointer from './ChromePointer' import ChromePointerCircle from './ChromePointerCircle' export const Chrome = ({ width, onChange, disableAlpha, rgb, hsl, hsv, hex, renderers, styles: passedStyles = {}, className = '', defaultView }) => { const styles = reactCSS(merge({ 'default': { picker: { width, background: '#fff', borderRadius: '2px', boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)', boxSizing: 'initial', fontFamily: 'Menlo', }, saturation: { width: '100%', paddingBottom: '55%', position: 'relative', borderRadius: '2px 2px 0 0', overflow: 'hidden', }, Saturation: { radius: '2px 2px 0 0', }, body: { padding: '16px 16px 12px', }, controls: { display: 'flex', }, color: { width: '32px', }, swatch: { marginTop: '6px', width: '16px', height: '16px', borderRadius: '8px', position: 'relative', overflow: 'hidden', }, active: { absolute: '0px 0px 0px 0px', borderRadius: '8px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)', background: `rgba(${ rgb.r }, ${ rgb.g }, ${ rgb.b }, ${ rgb.a })`, zIndex: '2', }, toggles: { flex: '1', }, hue: { height: '10px', position: 'relative', marginBottom: '8px', }, Hue: { radius: '2px', }, alpha: { height: '10px', position: 'relative', }, Alpha: { radius: '2px', }, }, 'disableAlpha': { color: { width: '22px', }, alpha: { display: 'none', }, hue: { marginBottom: '0px', }, swatch: { width: '10px', height: '10px', marginTop: '0px', }, }, }, passedStyles), { disableAlpha }) return ( <div style={ styles.picker } className={ `chrome-picker ${ className }` }> <div style={ styles.saturation }> <Saturation style={ styles.Saturation } hsl={ hsl } hsv={ hsv } pointer={ ChromePointerCircle } onChange={ onChange } /> </div> <div style={ styles.body }> <div style={ styles.controls } className="flexbox-fix"> <div style={ styles.color }> <div style={ styles.swatch }> <div style={ styles.active } /> <Checkboard renderers={ renderers } /> </div> </div> <div style={ styles.toggles }> <div style={ styles.hue }> <Hue style={ styles.Hue } hsl={ hsl } pointer={ ChromePointer } onChange={ onChange } /> </div> <div style={ styles.alpha }> <Alpha style={ styles.Alpha } rgb={ rgb } hsl={ hsl } pointer={ ChromePointer } renderers={ renderers } onChange={ onChange } /> </div> </div> </div> <ChromeFields rgb={ rgb } hsl={ hsl } hex={ hex } view={ defaultView } onChange={ onChange } disableAlpha={ disableAlpha } /> </div> </div> ) } Chrome.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disableAlpha: PropTypes.bool, styles: PropTypes.object, defaultView: PropTypes.oneOf([ "hex", "rgb", "hsl", ]), } Chrome.defaultProps = { width: 225, disableAlpha: false, styles: {}, } export default ColorWrap(Chrome)
examples/transitions/app.js
cold-brew-coding/react-router
import React from 'react'; import { Router, Route, Link, History, Lifecycle } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/dashboard">Dashboard</Link></li> <li><Link to="/form">Form</Link></li> </ul> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return <h1>Home</h1>; } }); var Dashboard = React.createClass({ render() { return <h1>Dashboard</h1>; } }); var Form = React.createClass({ mixins: [ Lifecycle, History ], getInitialState() { return { textValue: 'ohai' }; }, routerWillLeave(nextLocation) { if (this.state.textValue) return 'You have unsaved information, are you sure you want to leave this page?'; }, handleChange(event) { this.setState({ textValue: event.target.value }); }, handleSubmit(event) { event.preventDefault(); this.setState({ textValue: '' }, () => { this.history.pushState(null, '/'); }); }, render() { return ( <div> <form onSubmit={this.handleSubmit}> <p>Click the dashboard link with text in the input.</p> <input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} /> <button type="submit">Go</button> </form> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="dashboard" component={Dashboard} /> <Route path="form" component={Form} /> </Route> </Router> ), document.getElementById('example'));
app/javascript/components/Accounts/Users/Password.js
luckypike/mint
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import axios from 'axios' // import { deserialize } from 'jsonapi-deserializer' import { path } from '../../Routes' import { useI18n } from '../../I18n' import { useForm, Errors } from '../../Form' import styles from './Password.module.css' import page from '../../Page.module.css' import form from '../../Form.module.css' import buttons from '../../Buttons.module.css' Password.propTypes = { user: PropTypes.object.isRequired, locale: PropTypes.string.isRequired } export default function Password ({ user: userJSON, locale }) { const I18n = useI18n(locale) const { values, // setValues, // saved, // setSaved, handleInputChange, errors, pending, setErrors, onSubmit, cancelToken } = useForm({ password: '', password_confirmation: '' }) const handleSubmit = async e => { e.preventDefault() await axios.patch( path('account_user_path', { format: 'json' }), { user: values }, { cancelToken: cancelToken.current.token } ).then(res => { if (res.headers.location) window.location = res.headers.location // setSaved(true) }).catch(error => { setErrors(error.response.data) }) } return ( <div className={page.gray}> <div className={page.title}> <h1>{I18n.t('accounts.users.password')}</h1> </div> <div className={styles.root}> <div className={form.tight}> <form className={classNames(form.root, styles.form)} onSubmit={onSubmit(handleSubmit)}> <Errors errors={errors.reset_password_token} /> <div className={form.item}> <label> <div className={form.label}> {I18n.t('accounts.passwords.password')} </div> <div className={form.input}> <input type="password" autoFocus autoComplete="new-password" value={values.password} name="password" onChange={handleInputChange} /> </div> </label> <Errors errors={errors.password} /> </div> <div className={form.item}> <label> <div className={form.label}> {I18n.t('accounts.passwords.password_confirmation')} </div> <div className={form.input}> <input type="password" autoComplete="off" value={values.password_confirmation} name="password_confirmation" onChange={handleInputChange} /> </div> </label> <Errors errors={errors.password_confirmation} /> </div> <div className={classNames(form.submit, styles.submit)}> <input type="submit" value={pending ? I18n.t('accounts.passwords.submiting') : I18n.t('accounts.passwords.submit')} className={classNames(buttons.main, { [buttons.pending]: pending })} disabled={pending} /> </div> </form> </div> </div> </div> ) }
src/ui/elements/logos/Backbone.js
gouxlord/dev-insight
import React from 'react' var Backbone = React.createClass({ render: function () { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 129.08 162" preserveAspectRatio="xMinYMin meet"> <polygon fill="#0071B5" points="108.083,64.441 108.083,39.751 85.755,51.576 64.33,39.25 129.08,0 129.08,76.5 "/> <polygon fill="#002A41" points="20.996,64.441 20.996,39.751 43.324,51.576 64.33,39.25 0,0 0,76.5 "/> <polygon fill="#0071B5" points="96.331,82.055 64.33,100.625 85.8,112.587 108.08,100.625 108.08,88.5 "/> <polygon fill="#002A41" points="32.329,82.055 64.33,100.625 42.859,112.587 20.58,100.625 20.58,88.5 "/> <polygon fill="#0071B5" points="0,162 0,76.5 64.33,39.25 64.75,64.5 21,88.5 21,125 64.33,100.625 64.33,126 "/> <polygon fill="#002A41" points="129.08,162 129.08,76.5 64.33,39.25 64.33,64.5 108.08,88.5 108.08,125 64.33,100.625 64.33,126 "/> </svg> ) } }); export default Backbone;
app/js/components/content/DropFileComponent.js
theappbusiness/tab-hq
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import GoogleDriveMixin from '../../mixins/GoogleDriveMixin'; const DropFileComponent = React.createClass({ mixins: [GoogleDriveMixin], uploadFile(e) { // console.log(e); }, addLinkFromDrive(elem, params) { this.props.addLinkFromDrive(elem, params); }, triggerFileUpload() { let uploadField = this.refs.upload; uploadField.click(); }, fileUploaded(event) { console.log(event); }, render() { let addLinkButton = ''; let googleDriveButton = ''; let classes = 'downloadButtons'; if (this.props.type === 'link') { addLinkButton = <button className='btn btn-default' onClick={this.props.addLink}>Add link</button>; classes += ' btn-group'; } googleDriveButton = <button id='google-button' className='btn btn-default' onClick={this.addFilesFromGoogleDrive}>Add from Google Drive</button>; if (this.props.userIsAdmin) { return ( <div className='text-center dropzone'> <a href='#'> <i className='fa fa-cloud-upload fa-3x' /> </a> <h3>Drag & Drop</h3> <input id='upload' onChange={this.fileUploaded} type='file' ref='upload' style={{display: 'none'}} /> <p>or <a href='#' onClick={this.triggerFileUpload}>browse</a></p> <div className={classes}> {addLinkButton} {googleDriveButton} </div> </div> ); } else { return null; } } }); module.exports = DropFileComponent;
stories/default-size/percent-size.js
pionl/react-resizable-box
/* eslint-disable */ import React from 'react'; import Resizable from '../../src'; const style = { display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'solid 1px #ddd', background: '#f0f0f0', }; export default () => ( <Resizable style={style} defaultSize={{ width: '30%', height: '20%', }} > 001 </Resizable> );
src/svg-icons/action/build.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBuild = (props) => ( <SvgIcon {...props}> <path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"/> </SvgIcon> ); ActionBuild = pure(ActionBuild); ActionBuild.displayName = 'ActionBuild'; export default ActionBuild;
packages/forms/src/UIForm/fields/FieldTemplate/FieldTemplate.component.js
Talend/ui
import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import { useTranslation } from 'react-i18next'; import { Button } from 'react-bootstrap'; import OverlayTrigger from '@talend/react-components/lib/OverlayTrigger'; import Icon from '@talend/react-components/lib/Icon'; import Message from '../../Message'; import { I18N_DOMAIN_FORMS } from '../../../constants'; import theme from './FieldTemplate.scss'; function Label({ id, label, ...rest }) { return ( <label htmlFor={id} className="control-label" {...rest}> {label} </label> ); } if (process.env.NODE_ENV !== 'production') { Label.propTypes = { id: PropTypes.string, label: PropTypes.string, }; } function FieldTemplate(props) { const { t } = useTranslation(I18N_DOMAIN_FORMS); const groupsClassNames = classNames('form-group', theme.template, props.className, { 'has-error': !props.isValid, required: props.required, [theme.updating]: props.valueIsUpdating, }); let title = <Label id={props.id} label={props.label} {...props.labelProps} />; if (props.hint) { title = ( <div className={theme['field-template-title']}> {title} <OverlayTrigger overlayId={`${props.id}-hint-overlay`} overlayPlacement={props.hint.overlayPlacement || 'right'} overlayComponent={props.hint.overlayComponent} > <Button id={`${props.id}-hint`} bsStyle="link" className={props.hint.className} aria-label={t('FIELD_TEMPLATE_HINT_LABEL', { defaultValue: 'Display the input {{inputLabel}} hint', inputLabel: props.label, })} aria-haspopup > <Icon name={props.hint.icon || 'talend-info-circle'} /> </Button> </OverlayTrigger> </div> ); } const labelAfter = props.hint ? false : props.labelAfter; return ( <div className={groupsClassNames} aria-busy={props.valueIsUpdating}> {props.label && !labelAfter && title} {props.children} {props.label && labelAfter && title} <Message description={props.description} descriptionId={props.descriptionId} errorId={props.errorId} errorMessage={props.errorMessage} isValid={props.isValid} /> </div> ); } if (process.env.NODE_ENV !== 'production') { FieldTemplate.propTypes = { children: PropTypes.node, hint: PropTypes.shape({ icon: PropTypes.string, className: PropTypes.string, overlayComponent: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired, overlayPlacement: PropTypes.string, }), className: PropTypes.string, description: PropTypes.string, descriptionId: PropTypes.string.isRequired, errorId: PropTypes.string.isRequired, errorMessage: PropTypes.string, id: PropTypes.string, isValid: PropTypes.bool, label: PropTypes.string, labelProps: PropTypes.object, labelAfter: PropTypes.bool, required: PropTypes.bool, valueIsUpdating: PropTypes.bool, }; } FieldTemplate.defaultProps = { isValid: true, }; FieldTemplate.displayName = 'FieldTemplate'; export default FieldTemplate;
analysis/demonhuntervengeance/src/modules/talents/SpiritBombSoulsConsume.js
yajinni/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import { formatPercentage } from 'common/format'; import { t } from '@lingui/macro'; import Events from 'parser/core/Events'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; const MS_BUFFER = 100; class SpiritBombSoulsConsume extends Analyzer { get totalGoodCasts() { return this.soulsConsumedByAmount[4] + this.soulsConsumedByAmount[5]; } get totalCasts() { return Object.values(this.soulsConsumedByAmount).reduce((total, casts) => total + casts, 0); } get percentGoodCasts() { return this.totalGoodCasts / this.totalCasts; } get suggestionThresholdsEfficiency() { return { actual: this.percentGoodCasts, isLessThan: { minor: 0.90, average: 0.85, major: .80, }, style: 'percentage', }; } castTimestamp = 0; castSoulsConsumed = 0; cast = 0; soulsConsumedByAmount = Array.from({ length: 6 }, x => 0); /* Feed The Demon talent is taken in defensive builds. In those cases you want to generate and consume souls as quickly as possible. So how you consume your souls down matter. If you dont take that talent your taking a more balanced build meaning you want to consume souls in a way that boosts your dps. That means feeding the souls into spirit bomb as efficiently as possible (cast at 4+ souls) for a dps boost and have soul cleave absorb souls as little as possible since it provides no extra dps. */ constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) && !this.selectedCombatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.SPIRIT_BOMB_TALENT), this.onCast); this.addEventListener(Events.changebuffstack.by(SELECTED_PLAYER).spell(SPELLS.SOUL_FRAGMENT_STACK), this.onChangeBuffStack); this.addEventListener(Events.fightend, this.onFightend); } onCast(event) { if (this.cast > 0) { this.countHits(); } this.castTimestamp = event.timestamp; this.cast += 1; } onChangeBuffStack(event) { if (event.oldStacks < event.newStacks) { return; } if (event.timestamp - this.castTimestamp < MS_BUFFER) { const soulsConsumed = event.oldStacks - event.newStacks; this.castSoulsConsumed += soulsConsumed; } } countHits() { if (!this.soulsConsumedByAmount[this.castSoulsConsumed]) { this.soulsConsumedByAmount[this.castSoulsConsumed] = 1; this.castSoulsConsumed = 0; return; } this.soulsConsumedByAmount[this.castSoulsConsumed] += 1; this.castSoulsConsumed = 0; } onFightend() { this.countHits(); } suggestions(when) { when(this.suggestionThresholdsEfficiency) .addSuggestion((suggest, actual, recommended) => suggest(<>Try to cast <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> at 4 or 5 souls.</>) .icon(SPELLS.SPIRIT_BOMB_TALENT.icon) .actual(t({ id: "demonhunter.vengeance.suggestions.spiritBomb.soulsConsumed", message: `${formatPercentage(this.percentGoodCasts)}% of casts at 4+ souls.` })) .recommended(`>${formatPercentage(recommended)}% is recommended`)); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(6)} category={STATISTIC_CATEGORY.TALENTS} size="flexible" dropdown={( <> <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Casts</th> </tr> </thead> <tbody> {Object.values(this.soulsConsumedByAmount).map((castAmount, stackAmount) => ( <tr key={stackAmount}> <th>{stackAmount}</th> <td>{castAmount}</td> </tr> ))} </tbody> </table> </> )} > <BoringSpellValueText spell={SPELLS.SPIRIT_BOMB_TALENT}> <> {formatPercentage(this.percentGoodCasts)}% <small>good casts</small> </> </BoringSpellValueText> </Statistic> ); } } export default SpiritBombSoulsConsume;
src/scenes/Home/Home.js
strues/react-universal-boiler
// @flow import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import type { Connector } from 'react-redux'; import { fetchPosts, fetchPostsIfNeeded } from '../../state/modules/posts'; import Post from '../../components/Post'; import type { PostsReducer, Dispatch, Reducer } from '../../types'; // $FlowIssue import styles from './style.scss'; type Props = { posts: PostsReducer, fetchPostsIfNeeded: () => void, }; export class Home extends Component<Props, *> { static displayName = 'Home'; static fetchData({ store }) { return store.dispatch(fetchPosts()); } componentDidMount() { this.props.fetchPostsIfNeeded(); } render() { return ( <div> <Helmet title="Home" /> <div className="row"> <div className="column"> <div className={styles.hero}> <h1>React Universal Boiler</h1> <p>A server rendering React project.</p> </div> </div> </div> <div className="posts-list"> {this.props.posts.list.map(p => ( <div className="column column-30" key={p.id}> <Post title={p.title} body={p.body} /> </div> ))} </div> </div> ); } } const connector: Connector<{}, Props> = connect( ({ posts }: Reducer) => ({ posts }), (dispatch: Dispatch) => ({ fetchPostsIfNeeded: () => dispatch(fetchPostsIfNeeded()), }), ); export default connector(Home);
app/components/H3/index.js
Cherchercher/Wedding-Llama
import React from 'react'; function H3(props) { return ( <h3 {...props} /> ); } export default H3;
packages/mineral-ui-icons/src/IconAlarmAdd.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconAlarmAdd(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9a9 9 0 0 0 0-18zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/> </g> </Icon> ); } IconAlarmAdd.displayName = 'IconAlarmAdd'; IconAlarmAdd.category = 'action';
src/src/Components/RulesEditor/components/CustomTime/index.js
ioBroker/ioBroker.javascript
import { TextField } from '@material-ui/core'; import React from 'react'; import cls from './style.module.scss'; import PropTypes from 'prop-types'; import clsx from 'clsx'; const CustomTime = ({ value, style, onChange, className }) => { return <TextField id="time" type="time" onChange={(e) => onChange(e.currentTarget.value)} value={value} className={clsx(cls.root, className)} fullWidth style={style} InputLabelProps={{ shrink: true, }} inputProps={{ step: 300, // 5 min }} />; } CustomTime.defaultProps = { value: '', className: null, table: false }; CustomTime.propTypes = { title: PropTypes.string, attr: PropTypes.string, style: PropTypes.object, onChange: PropTypes.func }; export default CustomTime;
src/AffixMixin.js
coderstudy/react-bootstrap
import React from 'react'; import domUtils from './utils/domUtils'; import EventListener from './utils/EventListener'; const AffixMixin = { propTypes: { offset: React.PropTypes.number, offsetTop: React.PropTypes.number, offsetBottom: React.PropTypes.number }, getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition() { let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom, affix, affixType, affixPositionTop; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = React.findDOMNode(this); scrollHeight = document.documentElement.offsetHeight; scrollTop = window.pageYOffset; position = domUtils.getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && (scrollTop + this.unpin <= position.top)) { affix = false; } else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) { affix = 'bottom'; } else if (offsetTop != null && (scrollTop <= offsetTop)) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop }); }, checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount() { this._onWindowScrollListener = EventListener.listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; export default AffixMixin;
fields/types/name/NameColumn.js
suryagh/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; import displayName from 'display-name'; var NameColumn = React.createClass({ displayName: 'NameColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value || (!value.first && !value.last)) return '(no name)'; return displayName(value.first, value.last); }, render () { return ( <ItemsTableCell> <ItemsTableValue href={this.props.linkTo} padded interior field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = NameColumn;
test/fixtures/fragment.js
zeit/styled-jsx
import React from 'react' export default () => ( <> <p>Testing!!!</p> <p className="foo">Bar</p> <> <h3 id="head">Title...</h3> <React.Fragment> <p>hello</p> <> <p>foo</p> <p>bar</p> </> <p>world</p> </React.Fragment> </> <style jsx>{` p { color: cyan; } .foo { font-size: 18px; color: hotpink; } #head { text-decoration: underline; } `}</style> </> ) function Component1() { return ( <> <div>test</div> </> ) } function Component2() { return ( <div> <style jsx>{` div { color: red; } `}</style> </div> ) }
app/javascript/mastodon/features/notifications/components/filter_bar.js
danhunsaker/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; const tooltips = defineMessages({ mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' }, favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favourites' }, boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' }, polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' }, follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' }, statuses: { id: 'notifications.filter.statuses', defaultMessage: 'Updates from people you follow' }, }); export default @injectIntl class FilterBar extends React.PureComponent { static propTypes = { selectFilter: PropTypes.func.isRequired, selectedFilter: PropTypes.string.isRequired, advancedMode: PropTypes.bool.isRequired, intl: PropTypes.object.isRequired, }; onClick (notificationType) { return () => this.props.selectFilter(notificationType); } render () { const { selectedFilter, advancedMode, intl } = this.props; const renderedElement = !advancedMode ? ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} > <FormattedMessage id='notifications.filter.mentions' defaultMessage='Mentions' /> </button> </div> ) : ( <div className='notification__filter-bar'> <button className={selectedFilter === 'all' ? 'active' : ''} onClick={this.onClick('all')} > <FormattedMessage id='notifications.filter.all' defaultMessage='All' /> </button> <button className={selectedFilter === 'mention' ? 'active' : ''} onClick={this.onClick('mention')} title={intl.formatMessage(tooltips.mentions)} > <Icon id='reply-all' fixedWidth /> </button> <button className={selectedFilter === 'favourite' ? 'active' : ''} onClick={this.onClick('favourite')} title={intl.formatMessage(tooltips.favourites)} > <Icon id='star' fixedWidth /> </button> <button className={selectedFilter === 'reblog' ? 'active' : ''} onClick={this.onClick('reblog')} title={intl.formatMessage(tooltips.boosts)} > <Icon id='retweet' fixedWidth /> </button> <button className={selectedFilter === 'poll' ? 'active' : ''} onClick={this.onClick('poll')} title={intl.formatMessage(tooltips.polls)} > <Icon id='tasks' fixedWidth /> </button> <button className={selectedFilter === 'status' ? 'active' : ''} onClick={this.onClick('status')} title={intl.formatMessage(tooltips.statuses)} > <Icon id='home' fixedWidth /> </button> <button className={selectedFilter === 'follow' ? 'active' : ''} onClick={this.onClick('follow')} title={intl.formatMessage(tooltips.follows)} > <Icon id='user-plus' fixedWidth /> </button> </div> ); return renderedElement; } }
src/svg-icons/device/signal-cellular-3-bar.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M17 7L2 22h15z"/> </SvgIcon> ); DeviceSignalCellular3Bar = pure(DeviceSignalCellular3Bar); DeviceSignalCellular3Bar.displayName = 'DeviceSignalCellular3Bar'; DeviceSignalCellular3Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular3Bar;
src/pages/Registry.js
btthomas/blakeandanna
import React from 'react' import popup from '../popup.js'; const links = [ { url: 'https://www.crateandbarrel.com/gift-registry/anna-hunter-and-blake-thomas/r5729048', imgSrc: 'https://images.crateandbarrel.com/is/image/Crate/WebsiteHeaderLogo/fmt=png-alpha/170805043136/WebsiteHeaderLogo.jpg' }, { url: 'https://www.bedbathandbeyond.com/store/giftregistry/view_registry_guest.jsp?registryId=544926178&eventType=Wedding&pwsurl=&eventType=Wedding', imgSrc: 'https://www.bedbathandbeyond.com/_assets/global/images/logo/logo_bbb.png', id: 'bath' }, ]; const RegistryPage = () => { return ( <div className="registry"> {links.map(link => { return ( <a key={link.url} href={link.url} onClick={popup.bind(null, link.url)}> <img src={link.imgSrc} id={link.id}/> </a> ); })} </div> ); } export default RegistryPage;
client/react/panel/inputs/InputEditableDateTimeField.js
uclaradio/uclaradio
// InputEditableDateTimeField.js import React from 'react'; import { ButtonGroup, DropdownButton, MenuItem, Input, Glyphicon, } from 'react-bootstrap'; import Dates from '../../common/Dates'; /** * Show current saved value for day/time and let user update data and submit changes * * @prop title: form title of the element * @prop placeholder: placeholder to show in field * @prop verified: should show indicator that the value was successfully... whatever * * @prop day: current saved day value * @prop time: current saved time value * @prop onDateSubmit -> function(day, time): parent's function to be called if 'Submit' is hit * * @state day: current day value being entered * @state time: current time value being entered * @state editable: should let the user edit the field */ const InputEditableDateTimeField = React.createClass({ getInitialState() { return { day: 'Mon', time: '10am', editable: false }; }, handleDayChange(e, day) { this.setState({ day }); }, handleTimeChange(e, time) { this.setState({ time }); }, toggleEditableField(e) { this.setState({ day: this.props.day, time: this.props.time, editable: !this.state.editable, }); }, handleSubmit(e) { e.preventDefault(); const day = this.state.day.trim(); const time = this.state.time.trim(); if (day && time) { this.props.onDateSubmit(day, time); this.setState({ day: 'Mon', time: '10am', editable: false }); } }, render() { const editButton = ( <a className="customInput" onClick={this.toggleEditableField}> Edit </a> ); // var cancelButton = <Button className="cancelLink" onClick={this.toggleEditableField}>Cancel</Button>; const actionButton = ( <span> <a onClick={this.handleSubmit}>{this.props.buttonTitle || 'Update'}</a> &emsp;&emsp;&emsp;<a className="cancelLink" onClick={this.toggleEditableField}> Cancel </a> </span> ); const days = Dates.availableDays.map(day => ( <MenuItem key={day} eventKey={day}> {Dates.dayFromVar(day)} </MenuItem> )); const times = Dates.availableTimes.map(time => ( <MenuItem key={time} eventKey={time}> {time} </MenuItem> )); return ( <div className="inputEditableDateTimeField"> <form className="form-horizontal"> <Input label={this.props.title} labelClassName="col-xs-3" wrapperClassName="inputEditWrapper col-xs-9" addonAfter={this.state.editable ? actionButton : editButton}> {this.state.editable ? ( // field edit/submittable <ButtonGroup> <DropdownButton id="day" title={ Dates.dayFromVar(this.state.day) || ( <span className="placeholder">Day</span> ) } onSelect={this.handleDayChange} key={this.state.day}> {days} </DropdownButton> <DropdownButton id="time" title={ this.state.time || <span className="placeholder">Time</span> } onSelect={this.handleTimeChange} key={this.state.time}> {times} </DropdownButton> </ButtonGroup> ) : ( // locked to user input <span className="customInput"> {this.props.day && this.props.time ? ( <span> {Dates.dayFromVar(this.props.day)} {this.props.time}{' '} {this.props.verified ? ( <Glyphicon className="verifiedGlyph" glyph="ok" /> ) : ( '' )} </span> ) : ( <span className="placeholder">{this.props.placeholder}</span> )} </span> )} </Input> </form> </div> ); }, }); export default InputEditableDateTimeField;
server/sonar-web/src/main/js/apps/account/components/Password.js
joansmith/sonarqube
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React, { Component } from 'react'; import { changePassword } from '../../../api/users'; import { translate } from '../../../helpers/l10n'; export default class Password extends Component { state = { success: false, errors: null }; handleSuccessfulChange () { this.refs.oldPassword.value = ''; this.refs.password.value = ''; this.refs.passwordConfirmation.value = ''; this.setState({ success: true, errors: null }); } handleFailedChange (e) { e.response.json().then(r => { this.refs.oldPassword.focus(); this.setErrors(r.errors.map(e => e.msg)); }); } setErrors (errors) { this.setState({ success: false, errors }); } handleChangePassword (e) { e.preventDefault(); const { user } = this.props; const oldPassword = this.refs.oldPassword.value; const password = this.refs.password.value; const passwordConfirmation = this.refs.passwordConfirmation.value; if (password !== passwordConfirmation) { this.refs.password.focus(); this.setErrors([translate('user.password_doesnt_match_confirmation')]); } else { changePassword(user.login, password, oldPassword) .then(this.handleSuccessfulChange.bind(this)) .catch(this.handleFailedChange.bind(this)); } } render () { const { success, errors } = this.state; return ( <section> <h2 className="spacer-bottom"> {translate('my_profile.password.title')} </h2> <form onSubmit={this.handleChangePassword.bind(this)}> {success && ( <div className="alert alert-success"> {translate('my_profile.password.changed')} </div> )} {errors && errors.map((e, i) => ( <div key={i} className="alert alert-danger">{e}</div> ))} <div className="modal-field"> <label htmlFor="old_password"> {translate('my_profile.password.old')} <em className="mandatory">*</em> </label> <input ref="oldPassword" autoComplete="off" id="old_password" name="old_password" required={true} type="password"/> </div> <div className="modal-field"> <label htmlFor="password"> {translate('my_profile.password.new')} <em className="mandatory">*</em> </label> <input ref="password" autoComplete="off" id="password" name="password" required={true} type="password"/> </div> <div className="modal-field"> <label htmlFor="password_confirmation"> {translate('my_profile.password.confirm')} <em className="mandatory">*</em> </label> <input ref="passwordConfirmation" autoComplete="off" id="password_confirmation" name="password_confirmation" required={true} type="password"/> </div> <div className="modal-field"> <button id="change-password" type="submit"> {translate('my_profile.password.submit')} </button> </div> </form> </section> ); } }
docs/app/Examples/views/Item/Content/ItemExampleLink.js
aabustamante/Semantic-UI-React
import React from 'react' import { Image as ImageComponent, Item } from 'semantic-ui-react' const paragraph = <ImageComponent src='/assets/images/wireframe/short-paragraph.png' /> const ItemExampleLink = () => ( <Item.Group> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content> <Item.Header>Arrowhead Valley Camp</Item.Header> <Item.Meta> <span className='price'>$1200</span> <span className='stay'>1 Month</span> </Item.Meta> <Item.Description>{paragraph}</Item.Description> </Item.Content> </Item> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content> <Item.Header>Buck's Homebrew Stayaway</Item.Header> <Item.Meta content='$1000 2 Weeks' /> <Item.Description>{paragraph}</Item.Description> </Item.Content> </Item> <Item> <Item.Image size='tiny' src='/assets/images/wireframe/image.png' /> <Item.Content header='Arrowhead Valley Camp' meta='$1200 1 Month' /> </Item> </Item.Group> ) export default ItemExampleLink
tp-3/euge/src/index.js
jpgonzalezquinteros/sovos-reactivo-2017
/* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from './components/Root'; require('./favicon.ico'); // Tell webpack to load favicon.ico render( <AppContainer> <Root/> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot /> </AppContainer>, document.getElementById('app') ); }); }
pootle/static/js/shared/components/AutosizeTextarea.js
evernote/zing
/* * Copyright (C) Pootle contributors. * Copyright (C) Zing contributors. * * This file is a part of the Zing project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import autosize from 'autosize'; import React from 'react'; const AutosizeTextarea = React.createClass({ componentDidMount() { autosize(this.refs.textarea); }, componentDidUpdate() { autosize.update(this.refs.textarea); }, componentWillUnmount() { autosize.destroy(this.refs.textarea); }, render() { return <textarea ref="textarea" {...this.props} />; }, }); export default AutosizeTextarea;
plugins/react/frontend/components/controls/base/ArrayControl/ConstraintsForm/index.js
carteb/carte-blanche
import React from 'react'; import controlTypes from '../../../../CustomMetadataForm/controlTypes'; import getControl from '../../../../../utils/getControl'; import renderConstraintForm from './renderConstraintForm'; import Row from '../../../../form/Grid/Row'; import LeftColumn from '../../../../form/Grid/LeftColumn'; import RightColumn from '../../../../form/Grid/RightColumn'; import ComboBox from '../../../../form/ComboBox'; /** * * Takes care of rendering of the selection & constraint form for nested arrays * * The props should have the following structure: * * constraints: { * controlType: "arrayOf", * constraints: { * controlType: "string" * } * } * * parsedMetadata: { * name: "arrayOf", * value: { * name: "string" * } * } * * * @param constraints * @param parsedMetadata * @param onUpdate * @returns {Object} * @constructor */ const ConstraintsForm = ({ constraints, parsedMetadata, onUpdate, nestedLevel }) => { const onChange = (event) => { const controlType = event.value; // check if the control type has constraints // if the type doesn't have constraints neglect the existing constraints. const control = getControl({ name: controlType }); const hasConstraints = control.type.ConstraintsForm; const newCustomMetadata = hasConstraints && constraints && constraints.constraints ? { ...constraints.constraints } : {}; newCustomMetadata.controlType = controlType; onUpdate({ ...newCustomMetadata }); }; const renderControl = ({ controlType, constraint }) => ( <Row> <LeftColumn nestedLevel={nestedLevel}>{controlType}</LeftColumn> <RightColumn> <ComboBox value={controlType} onChange={onChange} options={controlTypes.map((type) => ({ value: type }))} /> </RightColumn> {renderConstraintForm( controlType, onUpdate, constraints, parsedMetadata )} {constraint && renderControl(constraint)} </Row> ); return ( <Row> {renderControl(constraints)} </Row> ); }; export default ConstraintsForm;
app/components/Facebook.js
vietvd88/developer-crawler
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Facebook.css'; import SortTable from './SortTable' import { Button, FormControl, FormGroup, ControlLabel } from 'react-bootstrap'; export default class Home extends Component { constructor(props) { super(props); var queryString = this.props.location.query this.props.getFacebookDeveloperAsync(queryString.user) this.props.getFacebookJobAsync(queryString.user) this.onChange = this.onChange.bind(this); this.postComment = this.postComment.bind(this); this.comment = '' } postComment(evt) { this.props.postComment(this.props.developer.user_name, this.comment) } onChange(evt) { console.log(evt.target.value) this.comment = evt.target.value } render() { const columns = [ {name: 'Company', key: 'company', width: 200}, {name: 'Position', key: 'position', width: 200}, {name: 'Duration', key: 'duration', width: 200}, ]; var comments = this.props.commentList.map(function(comment) { return comment.comment }) var commentText = comments.join('\n\n') return ( <div> <div className={styles.container}> <h2>Job Search Crawler -- <Link to={{ pathname: '/' }}> HomePage </Link> </h2> <hr/> <div className={styles.userPanel}> <img src={this.props.developer.avatar} className={styles.avatar}/> <span className={styles.userName}>{this.props.developer.name}</span> </div> <div className={styles.repoTable}> <SortTable dataList={this.props.facebookJobList} columns={columns} onSortChange={this.props.sortFacebookJob} width={800} height={200} /> </div> <div className={styles.email}> Email: {this.props.developer.email} </div> <div className={styles.phone}> Website: {this.props.developer.website} </div> <FormGroup controlId="formControlsTextarea"> <FormControl componentClass="textarea" value={commentText} readOnly className={styles.comments}/> </FormGroup> <FormGroup> <FormControl type="text" placeholder="New Comment" onChange={this.onChange}/> </FormGroup> {' '} <Button bsStyle="primary" bsSize="small" className={styles.filterButton} onClick={this.postComment} > Post </Button> </div> </div> ); } }
packages/server/src/core/renderers.js
warebrained/basis
import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; // renderReactView export default (res, view, title, componentType, props) => { const element = React.createElement(componentType, props, null); const markup = renderToStaticMarkup(element); res.render(view, { title, markup }); };
clients/packages/admin-client/src/pages/admin/mobilizations/launch/page.js
nossas/bonde-client
import React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import * as paths from '../../../../paths'; import * as MobActions from '../../../../mobrender/redux/action-creators'; import { Loading } from '../../../../components/await'; import MobSelectors from '../../../../mobrender/redux/selectors'; import { PageCentralizedLayout, PageCentralizedLayoutTitle, } from '../../../../components/layout'; import { Tabs, Tab } from '../../../../components/navigation/tabs'; import { Button, FlatForm } from '../../../../ux/components'; import { StepsContainerStack, StepContent } from '../../../../components/steps'; import { FormDomain, FormShare } from '../../../../mobilizations/components'; if (require('exenv').canUseDOM) { require('./form-domain.scss'); require('./form-share.scss'); } const FormShareImplementation = injectIntl( FormShare( (state) => ({ initialValues: MobSelectors(state).getMobilization() }), { submit: MobActions.asyncUpdateMobilization }, (values, props) => { const errors = {}; const messageRequired = props.intl.formatMessage({ id: 'page--mobilizations-launch.form-share.validation.required', defaultMessage: 'Obrigatório', }); if (!values.facebook_share_image) { errors.facebook_share_image = messageRequired; } if (!values.facebook_share_title) { errors.facebook_share_title = messageRequired; } if (!values.facebook_share_description) { errors.facebook_share_description = messageRequired; } if (!values.twitter_share_text) { errors.twitter_share_text = messageRequired; } return errors; } ) ); const MobilizationsLaunchPage = ({ history, hostedZones, mobilization, isSaving, ...formProps }) => { const stepDomainValidation = () => !!mobilization.custom_domain; const stepShareValidation = () => !!mobilization.facebook_share_image && !!mobilization.facebook_share_title && !!mobilization.facebook_share_description && !!mobilization.twitter_share_text; const stepFinishValidation = () => mobilization.custom_domain && mobilization.facebook_share_image && mobilization.facebook_share_title && mobilization.facebook_share_description && mobilization.twitter_share_text; const savingButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.saving" defaultMessage="Salvando..." /> ); const launchButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.launch" defaultMessage="Lançar mobilização" /> ); const continueButtonMessage = ( <FormattedMessage id="page--mobilizations-launch.button.next" defaultMessage="Continuar" /> ); return ( <PageCentralizedLayout> <PageCentralizedLayoutTitle> <FormattedMessage id="page--mobilizations-launch.title" defaultMessage="Lançando sua mobilização" /> </PageCentralizedLayoutTitle> <StepsContainerStack ComponentPointerContainer={Tabs} ComponentPointerChildren={Tab} pointerChildrenProps={({ index, step }) => ({ isActive: index === step, index, })} progressValidations={[ stepDomainValidation, stepShareValidation, stepFinishValidation, ]} > <StepContent> <FormDomain {...formProps} formComponent={FlatForm} titleText={ <FormattedMessage id="page--mobilizations-launch.steps.form-domain.title" defaultMessage="Configure o endereço da mobilização" /> } buttonText={ isSaving ? savingButtonMessage : stepShareValidation() ? launchButtonMessage : continueButtonMessage } requiredField mobilization={mobilization} hostedZones={hostedZones} redirectToCreateDNS={() => { history.push( paths.communityDomainCreate( `?next=${paths.mobilizationLaunch(mobilization.id)}` ) ); }} /> </StepContent> <StepContent> <FormShareImplementation {...formProps} FormComponent={FlatForm} formClassNames="mobilization-launch--form-share" titleText={ <FormattedMessage id="page--mobilizations-launch.steps.form-share.title" defaultMessage="Configure as informações de compartilhamento" /> } buttonText={isSaving ? savingButtonMessage : launchButtonMessage} /> </StepContent> <StepContent> <div className="ux--flat-form"> <h1> <FormattedMessage id="page--mobilizations-launch.steps.done.title" defaultMessage="Seu BONDE está pronto!" /> </h1> <p className="h5"> <FormattedMessage id="page--mobilizations-launch.steps.done.helper-text" defaultMessage={ 'Em uma nova aba, digite o endereço que cadastrou na mobilização ' + 'para se certificar de que ela já está no ar. Se ainda não estiver, ' + 'cheque se cadastrou os domínios corretamente. Está tudo certo? Então ' + 'é só esperar ele propagar pela internet!' } /> </p> <Button href={`http://${mobilization.custom_domain}`} target="_blank" > <FormattedMessage id="page--mobilizations-launch.steps.done.button.open" defaultMessage="Visualizar mobilização" /> </Button> </div> </StepContent> </StepsContainerStack> {isSaving && <Loading />} </PageCentralizedLayout> ); }; export default MobilizationsLaunchPage;
src/parser/deathknight/blood/modules/features/BoneShield.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import StatisticBox from 'interface/others/StatisticBox'; import StatTracker from 'parser/shared/modules/StatTracker'; import BoneShieldTimesByStacks from './/BoneShieldTimesByStacks'; class BoneShield extends Analyzer { static dependencies = { statTracker: StatTracker, boneShieldTimesByStacks: BoneShieldTimesByStacks, }; get boneShieldTimesByStack() { return this.boneShieldTimesByStacks.boneShieldTimesByStacks; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration; } get uptimeSuggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.9, major: .8, }, style: 'percentage', }; } suggestions(when) { when(this.uptimeSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.') .icon(SPELLS.BONE_SHIELD.icon) .actual(`${formatPercentage(actual)}% Bone Shield uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.BONE_SHIELD.id} />} value={`${formatPercentage(this.uptime)} %`} label="Bone Shield uptime" > <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Time (s)</th> <th>Time (%)</th> </tr> </thead> <tbody> {Object.values(this.boneShieldTimesByStack).map((e, i) => ( <tr key={i}> <th>{i}</th> <td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td> <td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td> </tr> ))} </tbody> </table> </StatisticBox> ); } statisticOrder = STATISTIC_ORDER.CORE(5); } export default BoneShield;
app/javascript/mastodon/components/animated_number.js
primenumber/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
src/index.js
jcxk/ethercity
import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './container/Root'; import configureStore from './store/configureStore'; import { syncHistoryWithStore } from 'react-router-redux'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./container/Root', () => { const NewRoot = require('./container/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
ui/src/pages/404.js
danielbh/danielhollcraft.com-gatsbyjs
import React from 'react' export default ({ data }) => { return ( <section id="one"> <div className="container"> <header className="major" style={{paddingBottom: '45vh'}}> <h2>404 error!</h2> </header> </div> </section> ) }
src/components/project/ProjectView.js
omgunis/portfolio
import React from 'react'; {/* View for single project, /project/:id, imported into ManageProjectPage */} const ProjectView = ({ project }) => { return ( <form> <h1>{ project.title }</h1> </form> ); }; ProjectView.propTypes = { project: React.PropTypes.object.isRequired }; export default ProjectView;
modules/Route.js
RickyDan/react-router
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './PropTypes'; import warning from 'warning'; var { string, bool, func } = React.PropTypes; /** * A <Route> is used to declare which components are rendered to the page when * the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. */ export var Route = React.createClass({ statics: { createRouteFromReactElement(element) { var route = createRouteFromReactElement(element); if (route.handler) { warning(false, '<Route handler> is deprecated, use <Route component> instead'); route.component = route.handler; delete route.handler; } return route; } }, propTypes: { path: string, ignoreScrollBehavior: bool, handler: component, component, components, getComponents: func }, render() { invariant( false, '<Route> elements are for router configuration only and should not be rendered' ); } }); export default Route;
client/modules/App/__tests__/Components/Footer.spec.js
trantuthien/React-Test
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import { Footer } from '../../components/Footer/Footer'; test('renders the footer properly', t => { const wrapper = shallow( <Footer /> ); t.is(wrapper.find('p').length, 2); t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.'); });
src/common/components/Routes.js
GarciaEdgar/firstReactApplication
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import LoginPage from '../../pages/login/page'; import HomePage from '../../pages/home/page'; export default ( <Route path="/" component={App}> <IndexRoute component={LoginPage} /> <Route path="home" component={HomePage} /> </Route> );
app/javascript/src/pages/settings/VerificationView.js
michelson/chaskiq
import React from 'react' import Prism from 'prismjs' import { connect } from 'react-redux' import FilterMenu from '../../components/FilterMenu' import Button from '../../components/Button' import Input from '../../components/forms/Input' function VerificationView({app}){ const [currentLang, setCurrentLang] = React.useState("ruby") const [show, setShow] = React.useState(false) function setupScript () { const hostname = window.location.hostname const port = window.location.port ? ':' + window.location.port : '' const secure = window.location.protocol === 'https:' const httpProtocol = window.location.protocol const wsProtocol = secure ? 'wss' : 'ws' const hostnamePort = `${hostname}${port}` const code = ` <script> (function(d,t) { var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src="${httpProtocol}//${hostnamePort}/embed.js" s.parentNode.insertBefore(g,s); g.onload=function(){ new window.ChaskiqMessengerEncrypted({ domain: '${httpProtocol}//${hostnamePort}', ws: '${wsProtocol}://${hostnamePort}/cable', app_id: "${app ? app.key : ''}", data: { email: "[email protected]", identifier_key: "INSERT_HMAC_VALUE_HERE", properties: { } }, lang: "USER_LANG_OR_DEFAULTS_TO_BROWSER_LANG" }) } })(document,"script"); </script> ` return Prism.highlight(code, Prism.languages.javascript, 'javascript') } function keyGeneration () { const code = optionsForFilter().find( (o)=> o.id === currentLang ).code return Prism.highlight(code, Prism.languages.ruby, 'ruby') } function optionsForFilter(){ return [ { title: 'Ruby', description: 'ruby', id: 'ruby', state: 'archived', code: ` OpenSSL::HMAC.hexdigest( 'sha256', # hash function '${app.encryptionKey}', # secret key (keep safe!) current_user.email )` }, { title: 'NodeJs', description: 'nodejs', id: 'nodejs', code: ` const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', '${app.encryptionKey}'); hmac.update('Message'); console.log(hmac.digest('hex'));` }, { title: 'PHP', description: 'PHP', id: 'php', code: ` hash_hmac( 'sha256', // hash function $user->email, // user's id '${app.encryptionKey}' // secret key (keep safe!) );` }, { title: 'Python 3', description: 'python', id: 'python', code: ` import hmac import hashlib hmac.new( b'${app.encryptionKey}', # secret key (keep safe!) bytes(request.user.id, encoding='utf-8'), # user's id digestmod=hashlib.sha256 # hash function ).hexdigest() ` }, { title: 'Golang', description: 'golang', id: 'golang', code: ` package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" ) func ComputeHmac256(message string, secret string) string { key := []byte(secret) h := hmac.New(sha256.New, key) h.Write([]byte(message)) return hex.EncodeToString(h.Sum(nil)) } func main() { fmt.Println(ComputeHmac256("Message", "secret")) // ${app.encryptionKey} } ` } ] } function toggleButton(clickHandler) { return ( <div> <Button variant={'outlined'} onClick={clickHandler}> {currentLang} </Button> </div> ) } function changeLang(item){ setCurrentLang(item.id) } return ( <div className="space-y-6 mx-10-- py-6 text-sm"> <h2 className="text-lg font-bold-">{I18n.t("identified_users.title")}</h2> <div className="flex md:w-1/4 items-center"> <Input label="Identity verification secret" disabled={true} value={app.encryptionKey} type={show ? 'text' : 'password'} helperText={ "Don't share this code" } /> <Button className="ml-2" variant="success" style={{ marginTop: '-12px' }} onClick={()=>setShow(!show)}> show </Button> </div> <p className=""> {I18n.t("identified_users.hint1")} To configure identity verification, you will need to generate an HMAC on your server for each logged in user and submit it to Chaskiq. </p> <p className="font-bold">{I18n.t("identified_users.lang")}</p> <div className="flex justify-between items-center"> <p className="font-bold text-lg">{currentLang}:</p> <div className="flex justify-end"> <FilterMenu options={optionsForFilter()} value={null} filterHandler={changeLang} triggerButton={toggleButton} position={'right'} /> </div> </div> <CodeBox content={keyGeneration()}/> <p dangerouslySetInnerHTML={{__html: I18n.t("identified_users.hint2") }}/> <CodeBox content={setupScript()}/> </div> ) } function CodeBox ({content}){ return ( <pre className="p-3 bg-black rounded-md border-black border-2 dark:border-gray-100 text-white text-sm overflow-auto shadow-sm"> <div dangerouslySetInnerHTML={{__html: content }}/> </pre> ) } function mapStateToProps (state) { const { app } = state return { app } } export default connect(mapStateToProps)(VerificationView)
auth/src/components/LoginForm.js
carlosnavarro25/calculadora
import React, { Component } from 'react'; import { Text } from 'react-native'; import firebase from 'firebase'; import { Button, Card, CardSection, Input, Spinner } from './common'; class LoginForm extends Component { state = { email: '', password: '', error: '', loading: false }; onButtonPress(){ const { email, password } = this.state; this.setState({ error: '', loading: true }); firebase.auth().signInWithEmailAndPassword(email, password) .then(this.onLogInSuccess.bind(this)) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(this.onLogInSuccess.bind(this)) .catch(this.onLogInFail.bind(this)); }); } onLogInFail(){ this.setState({ error:'Authentication Failed', loading: false }); } onLogInSuccess(){ this.setState({ email: '', password: '', loading: false, error: '' }); } renderButton(){ if (this.state.loading){ return <Spinner size="small" />; } return ( <Button onPress={this.onButtonPress.bind(this)}> log in </Button> ); } render(){ return( <Card> <CardSection > <Input placeholder="[email protected]" label="Email" value={this.state.email} onChangeText={email => this.setState({ email })} /> </CardSection> <CardSection> <Input secureTextEntry placeholder="password" label="Pasword" value={this.state.password} onChangeText={password => this.setState({password})} /> </CardSection> <Text style={styles.errorTextStyle}> {this.state.error} </Text> <CardSection> {this.renderButton()} </CardSection> </Card> ); } } const styles ={ errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } } export default LoginForm;
src/Dropdown/__tests__/Dropdown_test.js
react-fabric/react-fabric
import React from 'react' import { render, mount } from 'enzyme' import test from 'tape' import Dropdown from '..' import events from '../../util/events.js' const defaultOptions = [ { label: 'Foo', value: 'foo' }, { label: 'Bar', value: 'bar' } ] test('Dropdown', t => { t.ok(Dropdown, 'export') t.equal(Dropdown.displayName, 'FabricComponent(Dropdown)') t.end() }) test('Dropdown#render - simple', t => { const container = render( <Dropdown options={defaultOptions} /> ).contents() t.assert(container.is('div.ms-Dropdown', 'container')) t.assert(container.is('[data-fabric="Dropdown"]'), 'data-fabric') t.equal(container.find('.ms-Dropdown-items > .ms-Dropdown-item').length, defaultOptions.length) t.end() }) test('Dropdown lifecycle - unmount', t => { t.plan(1) const removeEventsFromDocument = events.removeEventsFromDocument events.removeEventsFromDocument = ({ click }) => { t.ok(click) } const wrapper = mount( <Dropdown active options={defaultOptions} /> ) wrapper.unmount() events.removeEventsFromDocument = removeEventsFromDocument }) test('Dropdown lifecycle - update', t => { t.plan(2) const addEventsToDocument = events.addEventsToDocument const removeEventsFromDocument = events.removeEventsFromDocument events.addEventsToDocument = ({ click }) => { t.ok(click, 'add click handler') } events.removeEventsFromDocument = ({ click }) => { t.ok(click) } const wrapper = mount( <Dropdown options={defaultOptions} /> ) wrapper.setProps({ active: true }) wrapper.setProps({ active: false }) events.addEventsToDocument = addEventsToDocument events.removeEventsFromDocument = removeEventsFromDocument }) test('Dropdown - blur', t => { t.plan(1) const handleBlur = e => t.ok(e, 'blur called') const wrapper = mount( <Dropdown onBlur={handleBlur} options={defaultOptions} /> ) wrapper.setProps({ active: true }) const event = document.createEvent('HTMLEvents') event.initEvent('click', true, false) document.body.dispatchEvent(event) }) test('Dropdown - focus', t => { t.plan(1) const handleFocus = e => t.ok(e, 'focus called') const wrapper = mount( <Dropdown onFocus={handleFocus} options={defaultOptions} /> ) wrapper.find('.ms-Dropdown-title').simulate('mouseDown') }) test('Dropdown - select', t => { t.plan(2) const handleBlur = e => t.equal(e.target.value, 'foo', 'blur called') const handleChange = e => t.ok(e.target.value, 'foo', 'change called') const wrapper = mount( <Dropdown onBlur={handleBlur} onChange={handleChange} value={null} options={defaultOptions} /> ) wrapper.setProps({ active: true }) wrapper.find('.ms-Dropdown-item > div').first().simulate('mouseDown') t.end() })
src/components/GoogleMapContainer/RichMarker.js
joelvoss/react-gmaps
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOMServer from 'react-dom/server'; import createElementFromString from 'utilities/createElementFromString'; import CustomMarker from 'components/CustomMarker'; /** * This component represents an overlay view. */ class RichMarker extends Component { // PropTypes static propTypes = { google: PropTypes.object.isRequired, map: PropTypes.object.isRequired, data: PropTypes.object.isRequired, handleClick: PropTypes.func }; /** * On mount, initialize the factory OverlayView instance provided by google * and set the three default methods "onAdd", "draw" and "onRemove". */ componentDidMount() { const { google, map } = this.props; this.richMarker = new google.maps.OverlayView(); this.richMarker.onAdd = this.onAdd; this.richMarker.draw = this.draw; this.richMarker.onRemove = this.onRemove; this.richMarker.setMap(map); } /** * When the component unmounts, set the map of the overlayview to null. * This calls the "onRemove" method of this class. */ componentWillUnmount() { this.richMarker.setMap(null); } /** * Google maps calls this method as soon as the overlayview can be drawn onto * the overlay map pane. * * This method gets called only once! */ onAdd = () => { const { data, handleClick } = this.props; const html = ReactDOMServer.renderToStaticMarkup( <CustomMarker delay={Math.floor(Math.random() * 10) + 1} /> ); this.markerItem = createElementFromString(html); // Add a standard eventlistener for a click event of the static markup // react component, since a marker is not a seperate react app. this.markerItem.addEventListener('click', (e) => { // prevent event bubbling and propagation e.stopPropagation(); e.preventDefault(); // execute the custom click event handler which was passed down to the overlay component. handleClick(data.id) }); const panes = this.richMarker.getPanes(); panes.overlayMouseTarget.appendChild(this.markerItem); }; /** * This method gets called each time the current maps viewport or zoom-level changes. * In here we convert the lat/lng values to pixel values and position the overlay. */ draw = () => { const { google, data } = this.props; const latlng = new google.maps.LatLng(data.geometry.location.lat, data.geometry.location.lng); const point = this.richMarker.getProjection().fromLatLngToDivPixel(latlng); if (point) { this.markerItem.style.left = point.x + 'px'; this.markerItem.style.top = point.y + 'px'; } }; /** * This method gets called as soon as we set the map property of * the overlayview to null. We remove all event listener and delete the * dom representation. */ onRemove = () => { if (this.markerItem) { this.markerItem.parentNode.removeChild(this.markerItem); this.markerItem = null; } }; render() { return null; } } export default RichMarker;
src/app.js
fjoder/indecision-app
import React from 'react'; import ReactDOM from 'react-dom'; import IndecisionApp from './components/IndecisionApp'; import 'normalize.css/normalize.css'; import './styles/styles.scss'; ReactDOM.render(<IndecisionApp />, document.getElementById('app'));
src/svg-icons/maps/train.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsTrain = (props) => ( <SvgIcon {...props}> <path d="M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-7H6V6h5v4zm2 0V6h5v4h-5zm3.5 7c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); MapsTrain = pure(MapsTrain); MapsTrain.displayName = 'MapsTrain'; MapsTrain.muiName = 'SvgIcon'; export default MapsTrain;
src/assets/js/react/components/FontManager/AddFont.js
GravityPDF/gravity-forms-pdf-extended
/* Dependencies */ import React from 'react' import PropTypes from 'prop-types' import { sprintf } from 'sprintf-js' /* Components */ import FontVariant from './FontVariant' import AddUpdateFontFooter from './AddUpdateFontFooter' /** * @package Gravity PDF * @copyright Copyright (c) 2021, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 6.0 */ /** * Display add font panel UI * * @param label * @param onHandleInputChange * @param onHandleUpload * @param onHandleDeleteFontStyle * @param onHandleSubmit * @param fontStyles * @param validateLabel * @param validateRegular * @param msg * @param loading * @param tabIndexFontName * @param tabIndexFontFiles * @param tabIndexFooterButtons * * @since 6.0 */ export const AddFont = ( { label, onHandleInputChange, onHandleUpload, onHandleDeleteFontStyle, onHandleSubmit, fontStyles, validateLabel, validateRegular, msg, loading, tabIndexFontName, tabIndexFontFiles, tabIndexFooterButtons } ) => { const fontNameLabel = sprintf(GFPDF.fontManagerFontNameLabel, "<span class='required'>", '</span>') return ( <div data-test='component-AddFont' className='add-font'> <form onSubmit={onHandleSubmit}> <h2>{GFPDF.fontManagerAddTitle}</h2> <p>{GFPDF.fontManagerAddDesc}</p> <label htmlFor='gfpdf-font-name-input' dangerouslySetInnerHTML={{ __html: fontNameLabel }} /> <p id='gfpdf-font-name-desc-add'>{GFPDF.fontManagerFontNameDesc}</p> <input type='text' id='gfpdf-add-font-name-input' className={!validateLabel ? 'input-label-validation-error' : ''} aria-describedby='gfpdf-font-name-desc-add' name='label' value={label} maxLength='60' onChange={e => onHandleInputChange(e, 'addFont')} tabIndex={tabIndexFontName} /> <div aria-live='polite'> {!validateLabel && ( <span className='required' role='alert'> <em>{GFPDF.fontManagerFontNameValidationError}</em> </span> )} </div> <label id='gfpdf-font-files-label-add' aria-labelledby='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesLabel}</label> <p id='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesDesc}</p> <FontVariant state='addFont' fontStyles={fontStyles} validateRegular={validateRegular} onHandleUpload={onHandleUpload} onHandleDeleteFontStyle={onHandleDeleteFontStyle} msg={msg} tabIndex={tabIndexFontFiles} /> <AddUpdateFontFooter state='addFont' msg={msg} loading={loading} tabIndex={tabIndexFooterButtons} /> </form> </div> ) } /** * PropTypes * * @since 6.0 */ AddFont.propTypes = { label: PropTypes.string.isRequired, onHandleInputChange: PropTypes.func.isRequired, onHandleUpload: PropTypes.func.isRequired, onHandleDeleteFontStyle: PropTypes.func.isRequired, onHandleSubmit: PropTypes.func.isRequired, validateLabel: PropTypes.bool.isRequired, validateRegular: PropTypes.bool.isRequired, fontStyles: PropTypes.object.isRequired, msg: PropTypes.object.isRequired, loading: PropTypes.bool.isRequired, tabIndexFontName: PropTypes.string.isRequired, tabIndexFontFiles: PropTypes.string.isRequired, tabIndexFooterButtons: PropTypes.string.isRequired } export default AddFont
src/svg-icons/action/note-add.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionNoteAdd = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"/> </SvgIcon> ); ActionNoteAdd = pure(ActionNoteAdd); ActionNoteAdd.displayName = 'ActionNoteAdd'; ActionNoteAdd.muiName = 'SvgIcon'; export default ActionNoteAdd;
index.ios.js
denistakeda/LifeBalance
import React from 'react'; import { AppRegistry } from 'react-native'; import App from './src/mobile/App'; const LifeBalance = () => { return ( <App /> ); }; AppRegistry.registerComponent('LifeBalance', () => LifeBalance); export default LifeBalance;
lib/ui/core.js
Markcial/electro-corder
import React from 'react'; import range from '../misc/utils'; export class Button extends React.Component { constructor(props) { super(props); this.state = { label: props.label, click: props.click }; } click (evt) { this.state.click(evt); } render() { return ( <button onClick={(e) => this.click(e)}>{this.state.label}</button> ); } } Button.propTypes = { label: React.PropTypes.string, click: React.PropTypes.function }; Button.defaultProps = { label: 'Button', click: () => {} }; export class Slider extends React.Component { constructor(props) { super(props); this.state = { defaultValue:props.defaultValue, orientation:props.orientation, min:props.min, max:props.max, onSlide:props.onSlide } } componentDidMount () { React.findDOMNode(this).style['-webkit-appearance'] = `slider-${this.props.orientation}`; } onSlide (evt) { this.props.onSlide(evt); } render () { return ( <input type="range" onChange={(e) => this.onSlide(e)} defaultValue={this.props.defaultValue} min={this.props.min} max={this.props.max} orientation={this.props.orientation} /> ); } } Slider.PropTypes = { defaultValue: React.PropTypes.int, orientation: React.PropTypes.string, min: React.PropTypes.integer, max: React.PropTypes.integer, onSlide: React.PropTypes.func } Slider.defaultProps = { defaultValue: 0, orientation: "horizontal", min: 0, max: 100, onSlide: (e) => {} } export class Timer extends React.Component { constructor(props) { super(props); this.state = {seconds: props.seconds}; } onTimerTick (seconds) {} onTimerEnd () {} componentDidMount () {} stopTimer() { clearInterval(this.intervalID); } resetTimer() { this.stopTimer(); this.setState({seconds:this.props.seconds}); this.startTimer(); } startTimer () { this.stopTimer(); this.intervalID = setInterval(() => { if (this.state.seconds > 0) { this.onTimerTick(this.state.seconds); this.tick(); } else { this.stopTimer(); this.onTimerEnd(); } }, 1000); } tick() { this.setState({ seconds: this.state.seconds - 1 }); } render() { return ( <div> Seconds left: {this.state.seconds} </div> ); } } Timer.propTypes = { seconds: React.PropTypes.number }; Timer.defaultProps = { seconds: 10 }; export class Preview extends React.Component { startRecording () { navigator.webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'screen', maxWidth: screen.availWidth, maxHeight: screen.availHeight, maxFrameRate: 25 }, optional: [] } }, (stream) => this.onStartRecording(stream), (error) => this.onStreamError(error)); } onStartRecording (stream) { this.video = React.findDOMNode(this.refs.video); this.video.style.display = 'none'; this.video.muted = true; this.video.autoplay = true; this.video.src = URL.createObjectURL(stream); this.canvas = React.findDOMNode(this.refs.preview); this.context = this.canvas.getContext("2d"); this.enrichenCanvasContext(this.context); requestAnimationFrame(() => {this.drawPreview()}) } drawPreview() { requestAnimationFrame(() => {this.drawPreview()}); this.context.drawImage(this.video, 0, 0); } onStreamError (error) { console.log(error); } componentDidMount () { this.startRecording(); } onVideoClick (evt) { console.log(evt); } onWheel (evt) { var lastX=this.canvas.width/2, lastY=this.canvas.height/2; var pt = this.context.transformedPoint(lastX,lastY); console.log(evt.deltaY); if (evt.deltaY > 0) { var scale = 0.9; } else { var scale = 1.1; } this.context.translate(pt.x,pt.y); this.context.scale(scale, scale); this.context.translate(-pt.x,-pt.y); } enrichenCanvasContext(ctx) { var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg'); var xform = svg.createSVGMatrix(); ctx.getTransform = function(){ return xform; }; var savedTransforms = []; var save = ctx.save; ctx.save = function(){ savedTransforms.push(xform.translate(0,0)); return save.call(ctx); }; var restore = ctx.restore; ctx.restore = function(){ xform = savedTransforms.pop(); return restore.call(ctx); }; var scale = ctx.scale; ctx.scale = function(sx,sy){ xform = xform.scaleNonUniform(sx,sy); return scale.call(ctx,sx,sy); }; var rotate = ctx.rotate; ctx.rotate = function(radians){ xform = xform.rotate(radians*180/Math.PI); return rotate.call(ctx,radians); }; var translate = ctx.translate; ctx.translate = function(dx,dy){ xform = xform.translate(dx,dy); return translate.call(ctx,dx,dy); }; var transform = ctx.transform; ctx.transform = function(a,b,c,d,e,f){ var m2 = svg.createSVGMatrix(); m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f; xform = xform.multiply(m2); return transform.call(ctx,a,b,c,d,e,f); }; var setTransform = ctx.setTransform; ctx.setTransform = function(a,b,c,d,e,f){ xform.a = a; xform.b = b; xform.c = c; xform.d = d; xform.e = e; xform.f = f; return setTransform.call(ctx,a,b,c,d,e,f); }; var pt = svg.createSVGPoint(); ctx.transformedPoint = function(x,y){ pt.x=x; pt.y=y; return pt.matrixTransform(xform.inverse()); } } render () { return ( <div> <video ref="video" /> <canvas ref="preview" width="420" height="240" onWheel={(evt) => this.onWheel(evt)} onClick={(evt) => this.onVideoClick(evt)} /> </div> ) } }
app/javascript/mastodon/components/status_content.js
alarky/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import escapeTextContentForBrowser from 'escape-html'; import PropTypes from 'prop-types'; import emojify from '../emoji'; import { isRtl } from '../rtl'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, onExpandedToggle: PropTypes.func, onHeightUpdate: PropTypes.func, onClick: PropTypes.func, }; state = { hidden: true, }; componentDidMount () { const node = this.node; const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener'); link.setAttribute('title', link.href); } } } componentDidUpdate () { if (this.props.onHeightUpdate) { this.props.onHeightUpdate(); } } onMentionClick = (mention, e) => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, '').toLowerCase(); if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) { return; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const content = { __html: emojify(status.get('content')) }; const spoilerContent = { __html: emojify(escapeTextContentForBrowser(status.get('spoiler_text', ''))) }; const directionStyle = { direction: 'ltr' }; if (isRtl(status.get('search_index'))) { directionStyle.direction = 'rtl'; } if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className='status__content status__content--with-action' ref={this.setRef} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} /> {' '} <button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} /> </div> ); } else if (this.props.onClick) { return ( <div ref={this.setRef} className='status__content status__content--with-action' style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} dangerouslySetInnerHTML={content} /> ); } else { return ( <div ref={this.setRef} className='status__content' style={directionStyle} dangerouslySetInnerHTML={content} /> ); } } }
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2018-01-11/src/main/js-surface-react-native.js
js-works/js-surface
import adaptReactLikeComponentSystem from './adaption/adaptReactLikeComponentSystem'; import React from 'react'; import ReactNative from 'react-native'; const { createElement, defineComponent, isElement, mount, unmount, Adapter, Config } = adaptReactLikeComponentSystem({ name: 'react-native', api: { React, ReactNative }, createElement: React.createElement, createFactory: React.createFactory, isValidElement: React.isValidElement, mount: reactNativeMount, Component: React.Component, browserBased: false }); export { createElement, defineComponent, isElement, mount, unmount, Adapter, Config }; function reactNativeMount(Component) { ReactNative.AppRegistry.registerComponent('AppMainComponent', () => Component); }
src/routes/gallery/Gallery.js
malinowsky/dataroot_03
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Contact from '../../components/Contact'; import Gallery from '../../components/Gallery'; import s from './Gallery.scss'; class GalleryR extends React.Component { render() { return ( <div className={s.root}> <Gallery/> <Contact/> </div> ); } } export default withStyles(s)(GalleryR);
test/test_helper.js
YacYac/ReduxSimpleStarter
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/cart/cartCheckOut/CartCheckOutListItemComponent.js
bluebill1049/cart
'use strict'; import React from 'react'; require('styles/cart/cartCheckOut/CartCheckOutListItem.scss'); class CartCheckOutListItemComponent extends React.Component { constructor(props) { super(props) } render() { return ( <li className="cartlistitem-component clearfix"> <img src={this.props.assets[this.props.item.fields.itemImage.sys.id]} /> <div className="cartlistitem-component__brief"> <h3>{this.props.item.fields.itemName}</h3> <p>{this.props.item.fields.itemShortDescription}</p> <p className="cartlistitem-component__price">${this.props.item.fields.price}</p> </div> <div className="cartlistitem-component__price-section"> <button className="small round alert" onClick={this.props.removeItem.bind(this, this.props.item.id, this.props.itemIndex)}>删除</button> </div> </li> ); } } CartCheckOutListItemComponent.displayName = 'CartCartCheckOutCartCheckOutListItemComponent'; // Uncomment properties you need CartCheckOutListItemComponent.propTypes = { item : React.PropTypes.object.isRequired, removeItem : React.PropTypes.func.isRequired, itemIndex : React.PropTypes.number.isRequired // viewDetail : React.PropTypes.func.isRequired }; // CartCheckOutListItemComponent.defaultProps = {}; export default CartCheckOutListItemComponent;
src/components/SegmentedControl.js
pairyo/elemental
import classnames from 'classnames'; import React from 'react'; module.exports = React.createClass({ displayName: 'SegmentedControl', propTypes: { className: React.PropTypes.string, equalWidthSegments: React.PropTypes.bool, onChange: React.PropTypes.func.isRequired, options: React.PropTypes.array.isRequired, type: React.PropTypes.oneOf(['default', 'muted', 'danger', 'info', 'primary', 'success', 'warning']), value: React.PropTypes.string }, getDefaultProps () { return { type: 'default' }; }, onChange (value) { this.props.onChange(value); }, render () { let componentClassName = classnames('SegmentedControl', ('SegmentedControl--' + this.props.type), { 'SegmentedControl--equal-widths': this.props.equalWidthSegments }, this.props.className); let options = this.props.options.map((op) => { let buttonClassName = classnames('SegmentedControl__button', { 'is-selected': op.value === this.props.value }); return ( <span key={'option-' + op.value} className="SegmentedControl__item"> <button type="button" onClick={this.onChange.bind(this, op.value)} className={buttonClassName}> {op.label} </button> </span> ); }); return <div className={componentClassName}>{options}</div>; } });
src/app.react.js
JasonStoltz/test-runner-demo
import {connect} from 'react-redux'; import {List} from 'immutable'; import React from 'react'; import Promise from 'bluebird'; import PureComponent from 'react-pure-render/component'; import TestsService from './model/test'; import mapStateToProps from './lib/mapStateToProps'; import mapDispatchToProps from './lib/mapDispatchToProps'; import * as actions from './store/tests/actions'; import * as TestConstants from './model/test'; import Test from './model/test'; import * as TestsConstants from './store/tests/reducers'; import Tests from './components/runner/tests.react.js'; import Status from './components/runner/status.react'; @connect(mapStateToProps('tests'), mapDispatchToProps(actions)) export default class App extends PureComponent { static propTypes = { tests: React.PropTypes.object.isRequired, actions: React.PropTypes.object.isRequired }; constructor() { super(); this.run = this.run.bind(this); //So we don't break pure render } render() { const {tests} = this.props; return ( <div> <div> <h1>Tests</h1> {tests.get('status') === TestsConstants.FINISHED && <div>FINISHED!</div> } <Tests tests={tests.get('tests')} /> <div> <button onClick={this.run} disabled={tests.get('status') === TestsConstants.RUNNING}>Run</button> </div> <Status running={tests.get('running')} failed={tests.get('failed')} passed={tests.get('passed')} /> </div> </div> ); } componentDidMount() { const {actions} = this.props; const tests = Test.all(); actions.setTests(tests); } run(e) { e.preventDefault(); const {actions} = this.props; const tests = this.props.tests.get('tests'); tests.forEach(test => { actions.setStatus(test.get('id'), TestConstants.RUNNING); TestsService.run(test.get('id')).then(result => { actions.setStatus(test.get('id'), (result) ? TestConstants.PASSED : TestConstants.FAILED); }); }); } }
src/components/Scheme/HypertensionC.js
lethecoa/work-order-pc
import React from 'react'; import {Form, InputNumber, Row, Col} from 'antd'; import styles from './Scheme.less'; const FormItem = Form.Item; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; class HypertensionC extends React.Component { state = { scheme: {}, }; componentWillMount() { this.setState( { scheme: this.props.scheme } ); } componentWillReceiveProps( nextProps ) { this.setState( { scheme: nextProps.scheme } ); } render() { const { getFieldDecorator } = this.props.form; const disabled = this.props.disabled; const { scheme } = this.state; return ( <div className={styles.need}> <div className={styles.title}>随访项目</div> <div className={styles.form}> <Row> <Col span={12}> <FormItem {...formItemLayout} label="舒张压(mmHg)"> {getFieldDecorator( 'sbp', { initialValue: scheme.sbp } )( <InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/> )} </FormItem> </Col> <Col span={12}> <FormItem {...formItemLayout} label="收缩压(mmHg)"> {getFieldDecorator( 'dbp', { initialValue: scheme.dbp } )( <InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/> )} </FormItem> </Col> </Row> </div> </div> ); } } export default Form.create()( HypertensionC );
src/components/pages/NotFoundPage.js
mm-taigarevolution/tas_web_app
import React from 'react'; import { Link } from 'react-router-dom'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
app/views/Homepage/components/RetroTitanic.js
herereadthis/redwall
import React from 'react'; import AppConstants from 'AppConstants'; export default class RetroTitantic extends React.Component { constructor() { super(); } componentWillMount() { } componentDidMount() { } render() { var titanticStyle; titanticStyle = { paddingTop: '2rem', paddingBottom: '1rem' }; return ( <article id="retro_art" className="starfield parallax_scroll" data-parallax-speed="250" ref="starfield" style={titanticStyle}> <h2>Here are some awesome thing!</h2> <section className="bellmaker_container geocities_me"> <h3>1997 was the best year ever!</h3> <div className="centered_image"> {AppConstants.dataSprite('titanic_468x60')} </div> </section> </article> ); } }
src/js/component/ClearCompleted.js
dtk0528/TODOs
import React, { Component } from 'react'; class ClearCompleted extends Component { render() { let clearButton = null; if (this.props.itemCount > 0) { clearButton = ( <button className="clear-completed" onClick={ this.props.onButtonClick } >Clear</button> ); } return ( <div> { clearButton } </div> ); } } export default ClearCompleted;
src/mobile/routes.js
Perslu/rerebrace
import chalk from 'chalk'; import { injectReducer } from './redux/reducers'; import React from 'react'; import { Route, IndexRoute } from 'react-router/es6'; import App from './App' import GalleryView from './public/containers/GalleryView'; import ProfileView from './public/containers/ProfileView'; // import Home from './Home' import UserInfo from './UserInfo' import NotFound from './NotFound' const errorLoading = (err) => { console.error(chalk.red(`==> 😭 Dynamic page loading failed ${err}`)); }; const loadModule = cb => (Component) => { cb(null, Component.default); }; export default ( <Route path="/" component={App}> <IndexRoute component={GalleryView} /> <Route path="/userinfo" component={UserInfo} /> <Route path="/profile/:profileId" component={ProfileView} /> <Route path="/*" component={NotFound} /> </Route> ) // export default function createRoutes(store) { // return { // path: '/', // component: App, // indexRoute: Home, // childRoutes: [ // { // path: 'UserInfo/:id', // // getComponent(location, cb) { // const importModules = Promise.all([ // System.import('./UserInfo'), // // System.import('./UserInfo/reducer'), // ]); // // const renderRoute = loadModule(cb); // // importModules // .then(([Component/*, reducer*/]) => { // // injectReducer(store, 'userInfo', reducer.default); // // renderRoute(Component); // }) // .catch(errorLoading); // }, // }, // { // path: '*', // getComponent(location, cb) { // System.import('./NotFound') // .then(loadModule(cb)) // .catch(errorLoading); // }, // }, // ], // }; // }
app/javascript/mastodon/components/radio_button.js
kirakiratter/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class RadioButton extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, checked: PropTypes.bool, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, label: PropTypes.node.isRequired, }; render () { const { name, value, checked, onChange, label } = this.props; return ( <label className='radio-button'> <input name={name} type='radio' value={value} checked={checked} onChange={onChange} /> <span className={classNames('radio-button__input', { checked })} /> <span>{label}</span> </label> ); } }
client/src/components/Polls.js
NicholasAsimov/voting-app
import React from 'react'; import { connect } from 'react-redux'; import Poll from './Poll'; import { Link } from 'react-router'; import { LinkContainer } from 'react-router-bootstrap'; import { ListGroup, ListGroupItem } from 'react-bootstrap'; class Polls extends React.Component { render() { return ( <div> <h2>Public polls</h2> <p>Select a poll to see the results and vote, or make a <Link to="/newpoll">new poll</Link>!</p> <ListGroup> {this.props.polls.map((poll, index) => ( <LinkContainer to={"/poll/" + poll._id} key={index}> <ListGroupItem>{poll.title}</ListGroupItem> </LinkContainer> ))} </ListGroup> </div> ) } } function mapStateToProps(state) { return { polls: state.polls }; } export default connect(mapStateToProps)(Polls);
src/icons/AndroidAdd.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidAdd extends React.Component { render() { if(this.props.bare) { return <g> <g id="Icon_7_"> <g> <path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path> </g> </g> </g>; } return <IconBase> <g id="Icon_7_"> <g> <path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path> </g> </g> </IconBase>; } };AndroidAdd.defaultProps = {bare: false}
src/components/GroceryList.js
clayhan/reactserver
import React from 'react'; export default class GroceryList extends React.Component { constructor(props) { super(props); this.state = { clickedItems: [] }; this.handleClick = this.handleClick.bind(this); } handleClick(e) { const clickedItems = this.state.clickedItems.slice(); clickedItems.push(e.target.textContent); this.setState({ clickedItems: clickedItems }); } render() { console.log('FE Render: GroceryList'); return ( <div className='component grocerylist'> <div>GroceryList Component</div> <h3>Ingredients:</h3> <div> <ol> {this.props.ingredients.map((ingredient) => { return <li onClick={this.handleClick}>{ingredient}</li> })} </ol> </div> <div> <h6>Things I need to buy:</h6> <ul> {this.state.clickedItems.map((item) => { return <li>{item}</li> })} </ul> </div> </div> ); } }
src/Containers/Top10/Top10.js
rahulp959/airstats.web
import React from 'react' import {connect} from 'react-redux' import TableTop from './TableTop/TableTop' import './Top10.scss' import { fetchTop10 } from '../../ducks/top10.js' let top10Dispatcher const refreshTime = 60 * 30 * 1000 // Once per half-hour class Top10 extends React.Component { componentDidMount () { this.props.dispatch(fetchTop10()) top10Dispatcher = setInterval(() => this.props.dispatch(fetchTop10()), refreshTime) } componentWillUnmount () { clearInterval(top10Dispatcher) } render () { console.dir(this.props.top10) let html = '' if (this.props.top10.get('isFetching') === true) { html = 'Loading...' } else { html = ( <div className='top10'> <div className='topbox'> <div className='title'>Top Departures</div> <TableTop data={this.props.top10.getIn(['data', 'departures'])} /> </div> <div className='topbox'> <div className='title'>Top Arrivals</div> <TableTop data={this.props.top10.getIn(['data', 'arrivals'])} /> </div> </div> ) } return ( <div className='topcontainer'> <p>Top 10 airports by types of operations within the past 7 days.</p> {html} <p>Last updated: {this.props.top10.getIn(['data', 'updated'])}Z</p> </div> ) } } const mapStateToProps = state => { return { top10: state.get('top10') } } export default connect(mapStateToProps)(Top10)
src/router.js
ITenTeges/portfolioPage
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i += 1) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { // eslint-disable-line no-restricted-syntax const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; // eslint-disable-line no-continue } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map((key) => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
examples/huge-apps/routes/Course/components/Course.js
AnSavvides/react-router
import React from 'react'; import Dashboard from './Dashboard'; import Nav from './Nav'; var styles = {}; styles.sidebar = { float: 'left', width: 200, padding: 20, borderRight: '1px solid #aaa', marginRight: 20 }; class Course extends React.Component { render () { let { children, params } = this.props; let course = COURSES[params.courseId]; return ( <div> <h2>{course.name}</h2> <Nav course={course} /> {children && children.sidebar && children.main ? ( <div> <div className="Sidebar" style={styles.sidebar}> {children.sidebar} </div> <div className="Main" style={{padding: 20}}> {children.main} </div> </div> ) : ( <Dashboard /> )} </div> ); } } export default Course;
components/Login/ReviseUser.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import {navigateAction} from 'fluxible-router'; import {connectToStores} from 'fluxible-addons-react'; import checkEmail from '../../actions/user/registration/checkEmail'; import checkUsername from '../../actions/user/registration/checkUsername'; import UserRegistrationStore from '../../stores/UserRegistrationStore'; import SSOStore from '../../stores/SSOStore'; import common from '../../common'; import finalizeMergedUser from '../../actions/user/finalizeMergedUser'; import instances from '../../configs/instances.js'; import {FormattedMessage, defineMessages} from 'react-intl'; const headerStyle = { 'textAlign': 'center' }; const modalStyle = { top: '15%' }; class ReviseUser extends React.Component { constructor(props) { super(props); this.errorMessages = defineMessages({ error409: { id: 'SSOSignIn.errormessage.isForbidden', defaultMessage: 'Migration is not possible with this user. Please start all over again.' }, error404: { id: 'SSOSignIn.errormessage.accountNotFound', defaultMessage: 'This account was not prepared for migration. Please start all over again.' }, error500: { id: 'SSOSignIn.errormessage.badImplementation', defaultMessage: 'An unknown error occurred.' } }); } componentDidMount() { //Form validation const validationRules = { fields: { username: { identifier: 'username', rules: [{ type: 'empty', prompt: 'Please select your username' }, { type: 'uniqueUsername', prompt: 'The username is already in use' }, { type : 'maxLength[64]', prompt : 'Your username can not be longer than 64 characters' }, { type : 'regExp[/^[a-zA-Z0-9-.~_]+$/i]', prompt : 'The username must contain only alphanumeric characters plus the following: _ . - ~' }] }, email: { identifier: 'email', rules: [{ type: 'empty', prompt: 'Please enter your email address' }, { type: 'email', prompt: 'Please enter a valid email address' }, { type: 'uniqueEmail', prompt: 'The email address is already in use' }] } }, onSuccess: this.handleSignUp.bind(this) }; $.fn.form.settings.rules.uniqueEmail = (() => { const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed; return (emailNotAllowed !== undefined) ? !emailNotAllowed : true; }); $.fn.form.settings.rules.uniqueUsername = (() => { const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed; return (usernameNotAllowed !== undefined) ? !usernameNotAllowed : true; }); $(ReactDOM.findDOMNode(this.refs.ReviseUser_form)).form(validationRules); } componentWillReceiveProps(nextProps) { console.log('ReviseUser componentWillReceiveProps()', this.props.UserRegistrationStore.socialuserdata, nextProps.UserRegistrationStore.socialuserdata, this.props.SSOStore.username, nextProps.SSOStore.username); if (nextProps.SSOStore.username !== this.props.SSOStore.username) { this.refs.username.value = nextProps.SSOStore.username; this.refs.email.value = nextProps.SSOStore.email; this.checkUsername(); this.checkEmail(); } } handleSignUp(e) { e.preventDefault(); let user = {}; user.email = this.refs.email.value; user.username = this.refs.username.value; user.hash = this.props.SSOStore.hash; let language = common.getIntlLanguage(); user.language = language; user.url = instances[instances._self].finalize.replace('{hash}', user.hash); user.errorMessages = { error409: this.context.intl.formatMessage(this.errorMessages.error409), error404: this.context.intl.formatMessage(this.errorMessages.error404), error500: this.context.intl.formatMessage(this.errorMessages.error500) }; this.context.executeAction(finalizeMergedUser, user); $(ReactDOM.findDOMNode(this.refs.ReviseUser_Modal)).modal('hide'); return false; } checkEmail() { const email = this.refs.email.value; if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || email !== '') { this.context.executeAction(checkEmail, {email: email}); } } checkUsername() { const username = this.refs.username.value; if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || username !== '') { this.context.executeAction(checkUsername, {username: username}); } } render() { const signUpLabelStyle = {width: '150px'}; const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed; let emailClasses = classNames({ 'ui': true, 'field': true, 'inline': true, 'error': (emailNotAllowed !== undefined) ? emailNotAllowed : false }); let emailIconClasses = classNames({ 'icon': true, 'inverted circular red remove': (emailNotAllowed !== undefined) ? emailNotAllowed : false, 'inverted circular green checkmark': (emailNotAllowed !== undefined) ? !emailNotAllowed : false }); let emailToolTipp = emailNotAllowed ? 'This E-Mail has already been used by someone else. Please choose another one.' : undefined; const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed; let usernameClasses = classNames({ 'ui': true, 'field': true, 'inline': true, 'error': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false }); let usernameIconClasses = classNames({ 'icon': true, 'inverted circular red remove': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false, 'inverted circular green checkmark': (usernameNotAllowed !== undefined) ? !usernameNotAllowed : false }); let usernameToolTipp = usernameNotAllowed ? 'This Username has already been used by someone else. Please choose another one.' : undefined; if (this.props.UserRegistrationStore.suggestedUsernames.length > 0) { usernameToolTipp += '\n Here are some suggestions: ' + this.props.UserRegistrationStore.suggestedUsernames; } return ( <div> <div className="ui ssoregistration modal" id='signinModal' style={modalStyle} ref="ReviseUser_Modal" > <div className="header"> <h1 style={headerStyle}>Validate user information</h1> <h2 style={headerStyle}>Your account could not migrated automatically. In order to finialize the migration, please change the data which is already in use.</h2> <h3 style={headerStyle}>Hint: if your email or username is already in use, it could be possible that you have already an stand-alone account on this SlideWiki instance. In this case close the window and do a sign in.</h3> </div> <div className="content"> <form className="ui ssoregistrationmodalform form" ref="ReviseUser_form" > <div className={usernameClasses} data-tooltip={usernameToolTipp} data-position="top center" data-inverted="" onBlur={this.checkUsername.bind(this)}> <label style={signUpLabelStyle}>Username * </label> <div className="ui icon input"><i className={usernameIconClasses}/><input type="text" name="username" ref="username" placeholder="Username" aria-required="true" /></div> </div> <div className={emailClasses} data-tooltip={emailToolTipp} data-position="top center" data-inverted="" onBlur={this.checkEmail.bind(this)}> <label style={signUpLabelStyle}>Email * </label> <div className="ui icon input"><i className={emailIconClasses}/><input type="email" name="email" ref="email" placeholder="Email" aria-required="true" /></div> </div> <div className="ui error message" role="region" aria-live="polite"/> <button type="submit" className="ui blue labeled submit icon button" > <i className="icon add user"/> Migrate User </button> </form> </div> <div className="actions"> <div className="ui cancel button">Cancel</div> </div> </div> </div> ); } } ReviseUser.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; ReviseUser = connectToStores(ReviseUser, [UserRegistrationStore, SSOStore], (context, props) => { return { UserRegistrationStore: context.getStore(UserRegistrationStore).getState(), SSOStore: context.getStore(SSOStore).getState() }; }); export default ReviseUser;
Realization/frontend/czechidm-core/src/components/advanced/ProfileInfo/ProfileInfo.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // import * as Basic from '../../basic'; import { ProfileManager } from '../../../redux'; import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo'; import EntityInfo from '../EntityInfo/EntityInfo'; import TwoFactorAuthenticationTypeEnum from '../../../enums/TwoFactorAuthenticationTypeEnum'; // const manager = new ProfileManager(); /** * Component for rendering information about identity profile. * * @author Radek Tomiška * @since 12.0.0 */ export class ProfileInfo extends AbstractEntityInfo { getManager() { return manager; } showLink() { return false; } /** * Returns entity icon (null by default - icon will not be rendered) * * @param {object} entity */ getEntityIcon() { return 'fa:cog'; } getNiceLabel(entity) { const _entity = entity || this.getEntity(); let label = this.i18n('entity.Profile._type'); if (_entity && _entity._embedded && _entity._embedded.identity) { label = `${ label } - (${ _entity._embedded.identity.username })`; } return label; } /** * Returns popovers title * * @param {object} entity */ getPopoverTitle() { return this.i18n('entity.Profile._type'); } getTableChildren() { // component are used in #getPopoverContent => skip default column resolving return [ <Basic.Column property="label"/>, <Basic.Column property="value"/> ]; } /** * Returns popover info content * * @param {array} table data */ getPopoverContent(entity) { return [ { label: this.i18n('entity.Identity._type'), value: ( <EntityInfo entityType="identity" entity={ entity._embedded ? entity._embedded.identity : null } entityIdentifier={ entity.identity } face="popover" /> ) }, { label: this.i18n('entity.Profile.preferredLanguage.label'), value: entity.preferredLanguage }, { label: this.i18n('entity.Profile.systemInformation.label'), value: (entity.systemInformation ? this.i18n('label.yes') : this.i18n('label.no')) }, { label: this.i18n('entity.Profile.twoFactorAuthenticationType.label'), value: ( <Basic.EnumValue enum={ TwoFactorAuthenticationTypeEnum } value={ entity.twoFactorAuthenticationType }/> ) } ]; } } ProfileInfo.propTypes = { ...AbstractEntityInfo.propTypes, /** * Selected entity - has higher priority */ entity: PropTypes.object, /** * Selected entity's id - entity will be loaded automatically */ entityIdentifier: PropTypes.string, /** * Internal entity loaded by given identifier */ _entity: PropTypes.object, _showLoading: PropTypes.bool }; ProfileInfo.defaultProps = { ...AbstractEntityInfo.defaultProps, entity: null, face: 'link', _showLoading: true }; function select(state, component) { return { _entity: manager.getEntity(state, component.entityIdentifier), _showLoading: manager.isShowLoading(state, null, component.entityIdentifier) }; } export default connect(select)(ProfileInfo);
app/components/App/App.js
Tonnu/workflows-ecs-ecr-demo
import React from 'react'; import createStore from 'lib/createStore'; import { Provider } from 'react-redux'; import HelloApp from 'components/HelloApp/HelloApp'; const store = createStore(); class App extends React.Component { render() { return ( <Provider {...{ store }}> <HelloApp/> </Provider> ); } } export default App;
src/containers/DevTools/DevTools.js
svsool/react-redux-universal-hot-example
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-H" changePositionKey="ctrl-Q"> <LogMonitor /> </DockMonitor> );
app/javascript/mastodon/features/community_timeline/index.js
ebihara99999/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../ui/components/column'; import { refreshTimeline, updateTimeline, deleteFromTimelines, connectTimeline, disconnectTimeline, } from '../../actions/timelines'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import createStream from '../../stream'; const messages = defineMessages({ title: { id: 'column.community', defaultMessage: 'Local timeline' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'community', 'unread']) > 0, streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']), accessToken: state.getIn(['meta', 'access_token']), }); let subscription; class CommunityTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, streamingAPIBaseURL: PropTypes.string.isRequired, accessToken: PropTypes.string.isRequired, hasUnread: PropTypes.bool, }; componentDidMount () { const { dispatch, streamingAPIBaseURL, accessToken } = this.props; dispatch(refreshTimeline('community')); if (typeof subscription !== 'undefined') { return; } subscription = createStream(streamingAPIBaseURL, accessToken, 'public:local', { connected () { dispatch(connectTimeline('community')); }, reconnected () { dispatch(connectTimeline('community')); }, disconnected () { dispatch(disconnectTimeline('community')); }, received (data) { switch(data.event) { case 'update': dispatch(updateTimeline('community', JSON.parse(data.payload))); break; case 'delete': dispatch(deleteFromTimelines(data.payload)); break; } }, }); } componentWillUnmount () { // if (typeof subscription !== 'undefined') { // subscription.close(); // subscription = null; // } } render () { const { intl, hasUnread } = this.props; return ( <Column icon='users' active={hasUnread} heading={intl.formatMessage(messages.title)}> <ColumnBackButtonSlim /> <StatusListContainer {...this.props} scrollKey='community_timeline' type='community' emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />} /> </Column> ); } } export default connect(mapStateToProps)(injectIntl(CommunityTimeline));
features/filmStrip/components/web/DominantSpeakerIndicator.js
jitsi/jitsi-meet-react
import React, { Component } from 'react'; import Icon from 'react-fontawesome'; import { styles } from './styles'; /** * Thumbnail badge showing that the participant is the dominant speaker in * the conference. */ export class DominantSpeakerIndicator extends Component { /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { return ( <div style = { styles.dominantSpeakerIndicatorBackground }> <Icon name = 'bullhorn' style = { styles.dominantSpeakerIndicator } /> </div> ); } }
src/svg-icons/av/video-label.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLabel = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 13H3V5h18v11z"/> </SvgIcon> ); AvVideoLabel = pure(AvVideoLabel); AvVideoLabel.displayName = 'AvVideoLabel'; AvVideoLabel.muiName = 'SvgIcon'; export default AvVideoLabel;
examples/todomvc/containers/Root.js
dherault/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js
timlogemann/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; async function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } /* eslint-disable */ // Regression test for https://github.com/facebook/create-react-app/issues/3055 const x = async ( /* prettier-ignore */ y: void ) => { const z = await y; }; /* eslint-enable */ export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-async-await"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
src/Components/SearchHeader.stories.js
elderfo/elderfo-react-native-components
import React from 'react'; import { Text, View } from 'react-native'; import { storiesOf, action, linkTo, } from '@kadira/react-native-storybook'; import { Container, SearchHeader } from '../'; storiesOf('SearchHeader', module) .addDecorator(story => ( <Container> {story()} </Container> )) .add('with left button', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onSearch={action('onSearch')} /> )) .add('with right button', () => ( <SearchHeader onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with both buttons', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with custom placeholder', () => ( <SearchHeader placeholder='Custom Placeholder' onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-arrow-back' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' onSearch={action('onSearch')} /> )) .add('with a backgroundColor/foregroundColor', () => ( <SearchHeader onLeftButtonClick={action('onLeftButtonClick')} leftButtonIcon='md-menu' onRightButtonClick={action('onRightButtonClick')} rightButtonIcon='md-qr-scanner' backgroundColor='red' foregroundColor='silver' /> ))
examples/src/app.js
yonaichin/react-select
/* eslint react/prop-types: 0 */ import React from 'react'; import ReactDOM from 'react-dom'; import Select from 'react-select'; import Contributors from './components/Contributors'; import GithubUsers from './components/GithubUsers'; import CustomComponents from './components/CustomComponents'; import CustomRender from './components/CustomRender'; import Multiselect from './components/Multiselect'; import NumericSelect from './components/NumericSelect'; import Virtualized from './components/Virtualized'; import States from './components/States'; ReactDOM.render( <div> <States label="States" searchable /> <Multiselect label="Multiselect" /> <Virtualized label="Virtualized" /> <Contributors label="Contributors (Async)" /> <GithubUsers label="Github users (Async with fetch.js)" /> <NumericSelect label="Numeric Values" /> <CustomRender label="Custom Render Methods"/> <CustomComponents label="Custom Placeholder, Option and Value Components" /> {/* <SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's NOT in the list, then hit return" /> */} </div>, document.getElementById('example') );
src/app/components/team/TeamData/TeamDataComponent.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import SettingsHeader from '../SettingsHeader'; import { ContentColumn } from '../../../styles/js/shared'; const TeamDataComponent = ({ dataReportUrl }) => ( <ContentColumn large> <SettingsHeader title={ <FormattedMessage id="teamDataComponent.title" defaultMessage="Workspace data" description="Header for the stored data page of the current team" /> } subtitle={ <FormattedMessage id="teamDataComponent.subtitle" defaultMessage="Download data and metadata from Check. Get insight and analysis about workspace and tipline usage." /> } helpUrl="https://help.checkmedia.org/en/articles/4511362" /> <Card> <CardContent> { dataReportUrl ? <React.Fragment> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.notSet1" defaultMessage="Click the button below to open your data report in a new window." /> </Typography> <Box mt={2} mb={2}> <Button variant="contained" color="primary" onClick={() => { window.open(dataReportUrl); }} > <FormattedMessage id="teamDataComponent.viewDataReport" defaultMessage="View data report" /> </Button> </Box> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.notSet2" defaultMessage="To request any customization of your data report, please reach out to support." /> </Typography> </React.Fragment> : <React.Fragment> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.set1" defaultMessage="Fill {thisShortForm} to request access to your data report." values={{ thisShortForm: ( <a href="https://airtable.com/shrWpaztZ2SzD5TrA" target="_blank" rel="noopener noreferrer"> <FormattedMessage id="teamDataComponent.formLinkText" defaultMessage="this short form" /> </a> ), }} /> </Typography> <Typography variant="body1" component="p" paragraph> <FormattedMessage id="teamDataComponent.set2" defaultMessage="Your data report will be enabled within one business day." /> </Typography> </React.Fragment> } </CardContent> </Card> </ContentColumn> ); TeamDataComponent.defaultProps = { dataReportUrl: null, }; TeamDataComponent.propTypes = { dataReportUrl: PropTypes.string, // or null }; export default TeamDataComponent;
docs/src/NavMain.js
adampickeral/react-bootstrap
import React from 'react'; import { Link } from 'react-router'; import Navbar from '../../src/Navbar'; import Nav from '../../src/Nav'; const NAV_LINKS = { 'introduction': { link: 'introduction', title: 'Introduction' }, 'getting-started': { link: 'getting-started', title: 'Getting started' }, 'components': { link: 'components', title: 'Components' }, 'support': { link: 'support', title: 'Support' } }; const NavMain = React.createClass({ propTypes: { activePage: React.PropTypes.string }, render() { let brand = <Link to='home' className="navbar-brand">React-Bootstrap</Link>; let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([ <li key='github-link'> <a href='https://github.com/react-bootstrap/react-bootstrap' target='_blank'>GitHub</a> </li> ]); return ( <Navbar componentClass='header' brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}> <Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top"> {links} </Nav> </Navbar> ); }, renderNavItem(linkName) { let link = NAV_LINKS[linkName]; return ( <li className={this.props.activePage === linkName ? 'active' : null} key={linkName}> <Link to={link.link}>{link.title}</Link> </li> ); } }); export default NavMain;
src/admin/BedChart.js
ocelotconsulting/global-hack-6
/* eslint no-new: "off" */ import React from 'react' import { v4 } from 'uuid' import ChartKey from './ChartKey' import Row from 'react-bootstrap/lib/Row' import Col from 'react-bootstrap/lib/Col' import ChartistGraph from 'react-chartist' export default class BedChart extends React.Component { constructor(props) { super(props) this.state = { id: `chart_${v4().replace(/-/g, '')}` } } render() { const { total, available, pending } = this.props const data = { series: [total - available - pending, pending, available] } const options = { startAngle: 270, showLabel: false } return ( <div className='summary-chart'> <Row> <Col md={3}> <ChartKey/> </Col> <Col md={3}> <ChartistGraph data={data} options={options} type='Pie'/> </Col> </Row> </div> ) } }
src/components/auth/accountpage.js
Hommasoft/wappuapp-adminpanel
import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import * as Auth from '../../actions/auth'; class AccountPage extends Component { handleFormSubmit({ newpassword, oldpassword }) { this.props.changepassword({ newpassword, oldpassword }); } renderError() { if (this.props.errorMessage) { console.log(this.props.errorMessage); return <div className="alert alert-danger">{this.props.errorMessage}</div>; } } renderField({ input, label, type, meta: { error } }) { return ( <div> <label>{label}</label> <div> <input className="form-control" {...input} placeholder={label} type={type} /> {error && <span className="text-danger">{error}</span>} </div> </div> ); } render() { const { handleSubmit } = this.props; var accountType = localStorage.getItem('admin'); if (accountType === 'true') { accountType = 'admin'; } else { accountType = 'moderator'; } return ( <div> <div> <h3>User details</h3> Email: {localStorage.getItem('email')} <br /> Account type: {accountType} <br /> Activated: {localStorage.getItem('activated')} <br /> </div> <br /> <div align="center"> Change password <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <Field name="oldpassword" label="Old password" component={this.renderField} type="password" /> </fieldset> <br /> <fieldset className="form-group"> <Field name="newpassword" label="New password" component={this.renderField} type="password" /> </fieldset> <fieldset className="form-group"> <Field name="newpasswordagain" label="New password again" component={this.renderField} type="password" /> </fieldset> {this.renderError()} <button action="submit" className="btn btn-primary"> Change password </button> </form> </div> </div> ); } } const validate = values => { const errors = {}; //if (values.newpassword && values.newpassword.length < 8) { // errors.newpassword = 'Password has to be atleast 8 characters long' //} if (values.newpassword && values.oldpassword === values.newpassword) { errors.newpassword = 'New password can not be the same as old one'; } if (values.newpasswordagain && values.newpassword !== values.newpasswordagain) { errors.newpasswordagain = 'New passwords need to match'; } return errors; }; const mapStateToProps = state => { return { errorMessage: state.auth.error }; }; export default reduxForm({ form: 'auth', validate })(connect(mapStateToProps, Auth)(AccountPage));
src/plugins/position/components/SpacerRow.js
joellanciaux/Griddle
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from '../../../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import withHandlers from 'recompose/withHandlers'; const spacerRow = compose( getContext({ selectors: PropTypes.object, }), connect((state, props) => { const { topSpacerSelector, bottomSpacerSelector } = props.selectors; const { placement } = props; return { spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props), }; }), mapProps(props => ({ placement: props.placement, spacerHeight: props.spacerHeight, })) )(class extends Component { static propTypes = { placement: PropTypes.string, spacerHeight: PropTypes.number, } static defaultProps = { placement: 'top' } // shouldComponentUpdate(nextProps) { // const { currentPosition: oldPosition, placement: oldPlacement } = this.props; // const { currentPosition, placement } = nextProps; // // return oldPosition !== currentPosition || oldPlacement !== placement; // } render() { const { placement, spacerHeight } = this.props; let spacerRowStyle = { height: `${spacerHeight}px`, }; return ( <tr key={placement + '-' + spacerHeight} style={spacerRowStyle}></tr> ); } }); export default spacerRow;
node_modules/react-bootstrap/es/ModalBody.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 elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var ModalBody = function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalBody.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalBody; }(React.Component); ModalBody.propTypes = propTypes; ModalBody.defaultProps = defaultProps; export default bsClass('modal-body', ModalBody);
imports/ui/components/Routes/Authenticated.js
haraneesh/mydev
import React from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect } from 'react-router-dom'; /* const Authenticated = ({ layout: Layout, roles, authenticated, component, ...rest }) => ( <Route {...rest} render={props => ( authenticated ? (<Layout {...props} isAdmin={roles.indexOf('admin') !== -1} authenticated {...rest} > {(React.createElement(component, { ...props, authenticated, ...rest }))} </Layout>) : (<Redirect to="/about" />) )} /> ); */ const Authenticated = ({ layout: Layout, roles, authenticated, component: Component, ...rest }) => ( <Route {...rest} render={(props) => ( authenticated ? ( <Layout {...props} isAdmin={roles.indexOf('admin') !== -1} authenticated {...rest} > <Component {...props} authenticated {...rest} roles={roles} /> </Layout> ) : (<Redirect to="/about" />) )} /> ); Authenticated.propTypes = { routeName: PropTypes.string.isRequired, roles: PropTypes.array.isRequired, authenticated: PropTypes.bool.isRequired, component: PropTypes.func.isRequired, layout: PropTypes.node.isRequired, }; export default Authenticated;
packages/mcs-lite-ui/src/DataChannelAdapter/DataChannelAdapter.example.js
MCS-Lite/mcs-lite
import React from 'react'; import styled from 'styled-components'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import { action } from '@storybook/addon-actions'; import DataChannelCard from '../DataChannelCard'; import DATA_CHANNELS from './API'; import DataChannelAdapter from '.'; const CardWrapper = styled.div` display: flex; flex-wrap: wrap; > * { height: initial; padding: 8px 16px; margin: 4px; flex-basis: 100%; } > [data-width~=' half'] { flex-grow: 1; flex-basis: 40%; } `; storiesOf('DataChannelAdapter', module).add( 'API', withInfo({ text: ` ~~~js type Event = { type: 'SUBMIT'|'CHANGE'|'CLEAR', // event type id: string, // data channel id values: { // datapoint values value: ?string|number, period: ?number, }, } type DCEventHandler = DCEvent => void ~~~ `, inline: true, })(() => ( <CardWrapper> {DATA_CHANNELS.map(dataChannel => ( <DataChannelCard key={dataChannel.id} data-width="half" title={dataChannel.type} subtitle="Last data point time : 2015-06-12 12:00" description="You can input description of controller here. You can input description of You can input description of controller here. You can input description of" header={<a href=".">Link</a>} > <DataChannelAdapter dataChannelProps={dataChannel} eventHandler={action( 'DataChannelAdapter eventHandler(event: Event)', )} /> </DataChannelCard> ))} </CardWrapper> )), );
src/docs/components/header/HeaderExamplesDoc.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Header from 'grommet/components/Header'; import Title from 'grommet/components/Title'; import Search from 'grommet/components/Search'; import Menu from 'grommet/components/Menu'; import Box from 'grommet/components/Box'; import Anchor from 'grommet/components/Anchor'; import ActionsIcon from 'grommet/components/icons/base/Actions'; import InteractiveExample from '../../../components/InteractiveExample'; const PROPS_SCHEMA = { fixed: { value: true }, float: { value: true }, size: { options: ['small', 'medium', 'large', 'xlarge'] }, splash: { value: true } }; const CONTENTS_SCHEMA = { title: { value: <Title>Sample Title</Title>, initial: true }, search: { value: ( <Search inline={true} fill={true} size='medium' placeHolder='Search' dropAlign={{ right: 'right' }}/> ), initial: true }, menu: { value: ( <Menu icon={<ActionsIcon />} dropAlign={{right: 'right'}}> <Anchor href='#' className='active'>First</Anchor> <Anchor href='#'>Second</Anchor> <Anchor href='#'>Third</Anchor> </Menu> ), initial: true } }; export default class HeaderExamplesDoc extends Component { constructor () { super(); this.state = { contents: {}, elementProps: {} }; } render () { let { contents, elementProps } = this.state; const element = ( <Header {...elementProps}> {contents.title} <Box flex={true} justify='end' direction='row' responsive={false}> {contents.search} {contents.menu} </Box> </Header> ); return ( <InteractiveExample contextLabel='Header' contextPath='/docs/header' justify='start' align='stretch' preamble={`import Header from 'grommet/components/Header';`} propsSchema={PROPS_SCHEMA} contentsSchema={CONTENTS_SCHEMA} element={element} onChange={(elementProps, contents) => { this.setState({ elementProps, contents }); }} /> ); } };
packages/benchmarks/src/index.js
css-components/styled-components
/* eslint-disable no-param-reassign */ /* global document */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './app/App'; import impl from './impl'; import Tree from './cases/Tree'; import SierpinskiTriangle from './cases/SierpinskiTriangle'; const implementations = impl; const packageNames = Object.keys(implementations); const createTestBlock = fn => { return packageNames.reduce((testSetups, packageName) => { const { name, components, version } = implementations[packageName]; const { Component, getComponentProps, sampleCount, Provider, benchmarkType } = fn(components); testSetups[packageName] = { Component, getComponentProps, sampleCount, Provider, benchmarkType, version, name, }; return testSetups; }, {}); }; const tests = { 'Mount deep tree': createTestBlock(components => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 2, components, depth: 7, id: 0, wrap: 1 }), Provider: components.Provider, sampleCount: 500, })), 'Mount wide tree': createTestBlock(components => ({ benchmarkType: 'mount', Component: Tree, getComponentProps: () => ({ breadth: 6, components, depth: 3, id: 0, wrap: 2 }), Provider: components.Provider, sampleCount: 500, })), 'Update dynamic styles': createTestBlock(components => ({ benchmarkType: 'update', Component: SierpinskiTriangle, getComponentProps: ({ cycle }) => { return { components, s: 200, renderCount: cycle, x: 0, y: 0 }; }, Provider: components.Provider, sampleCount: 1000, })), }; ReactDOM.render(<App tests={tests} />, document.querySelector('.root'));
app/routes/routes/PaySuccess/components/PaySuccess.view.js
bugknightyyp/leyizhu
import React from 'react' import {observer} from 'mobx-react' import {Route, Link} from 'react-router-dom' import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros' import {setParamsToURL, dateToZh} from 'utils' import './paySuccess.less' export default observer( (props) => ( <div className="pay-success-container"> <div className="hotel-info"> <i className="iconfont icon-success" /> <h1>支付成功</h1> <div className="hotel-name">{props.store.hotelName}</div> <div className="hotel-address">{`酒店地址:${props.store.address}`}</div> <Link to={{pathname: `${props.match.url}/map`, search: `?longitude=${props.store.longitude}&latitude=${props.store.latitude}`}} className="go-hotel">前往酒店</Link> </div> <div className="how-to-checking"> <h6>如何入住</h6> <p> 1.前往酒店,并找到自助入住登记机<br /> 2.在自助机登记证件,并进行脸部识别<br /> 3.收取入住短信通知(含房间号和密码)<br /> *房门还可通过网络开锁功能开启</p> </div> <div className="safety-tips"> <i className="iconfont icon-tixing" />根据公安部法律规定,住宿需登记身份证信息 </div> </div> ) )
frontend/src/Factura/FacturaTable.js
GAumala/Facturacion
import React from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; import Delete from 'material-ui/svg-icons/action/delete'; import Math from 'facturacion_common/src/Math.js'; const black54p = '#757575'; const noPaddingStyle = { padding: '0px' }; const RenderTableHeader = props => { let regSanCol = ( <TableHeaderColumn width={80} style={noPaddingStyle}> Reg. Santario </TableHeaderColumn> ); let loteCol = ( <TableHeaderColumn width={60} style={noPaddingStyle}> Lote </TableHeaderColumn> ); let fechaExpCol = ( <TableHeaderColumn width={70} style={noPaddingStyle}> Fecha Exp. </TableHeaderColumn> ); if (props.isExamen) { //ocultar columnas que no se usan en examenes regSanCol = null; loteCol = null; fechaExpCol = null; } return ( <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn width={40} style={noPaddingStyle}> # </TableHeaderColumn> {regSanCol} <TableHeaderColumn width={170} style={noPaddingStyle}> Nombre </TableHeaderColumn> {loteCol} <TableHeaderColumn width={40} style={noPaddingStyle}> Cant. </TableHeaderColumn> {fechaExpCol} <TableHeaderColumn width={60} style={noPaddingStyle}> Precio </TableHeaderColumn> <TableHeaderColumn width={50} style={noPaddingStyle}> Importe </TableHeaderColumn> <TableHeaderColumn width={30} style={noPaddingStyle} /> </TableRow> </TableHeader> ); }; export default class FacturaTable extends React.Component { renderRow = (facturable, i) => { const { isExamen, onFacturableChanged, onFacturableDeleted } = this.props; let regSanCol = ( <TableRowColumn width={80} style={noPaddingStyle}> {facturable.codigo} </TableRowColumn> ); let loteCol = ( <TableRowColumn width={60} style={noPaddingStyle}> <TextField value={facturable.lote} style={{ width: '50px' }} name={'lote'} inputStyle={{ textAlign: 'right', fontSize: '13px' }} onChange={event => { onFacturableChanged(i, 'lote', event.target.value); }} /> </TableRowColumn> ); let fechaExpCol = ( <TableRowColumn width={70} style={noPaddingStyle}> <TextField value={facturable.fechaExp} hintText={'expiración'} style={{ width: '70px', fontSize: '13px' }} onChange={(event, date) => { onFacturableChanged(i, 'fechaExp', date); }} /> </TableRowColumn> ); if (isExamen) { //ocultar columnas que no se usan en examenes regSanCol = null; loteCol = null; fechaExpCol = null; } return ( <TableRow key={i}> <TableRowColumn width={40} style={noPaddingStyle}> {i + 1} </TableRowColumn> {regSanCol} <TableRowColumn width={170} style={noPaddingStyle}> {facturable.nombre} </TableRowColumn> {loteCol} <TableRowColumn width={40} style={noPaddingStyle}> <TextField style={{ width: '28px' }} value={facturable.countText} name={'count'} inputStyle={{ textAlign: 'right', fontSize: '13px' }} onChange={event => { onFacturableChanged(i, 'count', event.target.value); }} /> </TableRowColumn> {fechaExpCol} <TableRowColumn width={60} style={noPaddingStyle}> ${' '} <TextField style={{ width: '50px' }} name={'precio'} value={facturable.precioVentaText} onChange={event => { onFacturableChanged(i, 'precioVenta', event.target.value); }} inputStyle={{ fontSize: '13px' }} /> </TableRowColumn> <TableRowColumn width={50} style={{ padding: '0px', textOverflow: 'clip' }} > <span style={{ marginRight: '34px' }}> $ {Math.calcularImporteFacturable(facturable)} </span> </TableRowColumn> <TableRowColumn width={30} style={{ padding: '0px', textAlign: 'right' }} > <IconButton onTouchTap={() => onFacturableDeleted(i)}> <Delete color={black54p} /> </IconButton> </TableRowColumn> </TableRow> ); }; render() { return ( <Table height={'200px'} selectable={false}> {RenderTableHeader(this.props)} <TableBody displayRowCheckbox={false}> {this.props.items.map(this.renderRow)} </TableBody> </Table> ); } } FacturaTable.propTypes = { isExamen: React.PropTypes.bool, items: React.PropTypes.array.isRequired, onFacturableChanged: React.PropTypes.func.isRequired, onFacturableDeleted: React.PropTypes.func.isRequired }; FacturaTable.defaultProps = { isExamen: false };
lib/routes.js
codevlabs/filepizza
import React from 'react' import { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router' import App from './components/App' import DownloadPage from './components/DownloadPage' import UploadPage from './components/UploadPage' import ErrorPage from './components/ErrorPage' export default ( <Route handler={App}> <DefaultRoute handler={UploadPage} /> <Route name="download" path="/:a-:b-:c-:d" handler={DownloadPage} /> <Route name="error" path="error" handler={ErrorPage} /> <NotFoundRoute handler={ErrorPage} /> </Route> )
2016-04-declarative-charts/assets/highcharts.js
rosko/slides
import React from 'react'; import IframeExample from '../components/IframeExample'; function Highcharts() { return <IframeExample html={`<html><head> <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> </head><body> <div id="container" style="width: 100vw; height: 100vh; margin: 0 auto"></div> <script> ${require('raw!./highcharts.example')} </script> </body></html>`}/>; } Highcharts.displayName = 'Highcharts'; module.exports = Highcharts;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
Rmutek/rmutek.github.io
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
packages/ui/src/components/Sprinkle.stories.js
dino-dna/donut
import React from 'react' import { storiesOf } from '@storybook/react' import Sprinkle from './Sprinkle' export default storiesOf('Sprinkle', module) .add('basic', () => { return ( <svg viewport='0 0 60 60' width='60' height='60'> <Sprinkle /> </svg> ) }) .add('rotated', () => { return ( <svg viewport='0 0 60 60'> <Sprinkle deg={90} /> </svg> ) }) .add('rotated & translated', () => { return ( <svg viewport='0 0 60 60'> <g style={{ transform: `translate(${25}px, ${25}px)` }}> <Sprinkle deg={45} /> </g> </svg> ) })
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
JeeLiu/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const GroupProfileMembers = React.createClass({ propTypes: { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }, mixins: [PureRenderMixin], onClick(id) { DialogActionCreators.selectDialogPeerUser(id); }, onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); }, render() { let groupId = this.props.groupId; let members = this.props.members; let myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="profile__list__item row" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} size="small" title={member.peerInfo.title}/> </a> <div className="col-xs"> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <span className="title"> {member.peerInfo.title} </span> </a> {controls} </div> </li> ); }, this); return ( <ul className="profile__list profile__list--members"> <li className="profile__list__item profile__list__item--header">{members.length} members</li> {membersList} </ul> ); } }); export default GroupProfileMembers;
src/DataTables/DataTablesTableBody.js
hyojin/material-ui-datatables
import React from 'react'; import PropTypes from 'prop-types'; import {TableBody} from 'material-ui/Table'; import ClickAwayListener from 'material-ui/internal/ClickAwayListener'; class DataTablesTableBody extends TableBody { static muiName = 'TableBody'; static propTypes = { /** * @ignore * Set to true to indicate that all rows should be selected. */ allRowsSelected: PropTypes.bool, /** * Children passed to table body. */ children: PropTypes.node, /** * The css class name of the root element. */ className: PropTypes.string, /** * Controls whether or not to deselect all selected * rows after clicking outside the table. */ deselectOnClickaway: PropTypes.bool, /** * Controls the display of the row checkbox. The default value is true. */ displayRowCheckbox: PropTypes.bool, /** * @ignore * If true, multiple table rows can be selected. * CTRL/CMD+Click and SHIFT+Click are valid actions. * The default value is false. */ multiSelectable: PropTypes.bool, /** * @ignore * Callback function for when a cell is clicked. */ onCellClick: PropTypes.func, /** * @ignore * Customized handler * Callback function for when a cell is double clicked. */ onCellDoubleClick: PropTypes.func, /** * @ignore * Called when a table cell is hovered. rowNumber * is the row number of the hovered row and columnId * is the column number or the column key of the cell. */ onCellHover: PropTypes.func, /** * @ignore * Called when a table cell is no longer hovered. * rowNumber is the row number of the row and columnId * is the column number or the column key of the cell. */ onCellHoverExit: PropTypes.func, /** * @ignore * Called when a table row is hovered. * rowNumber is the row number of the hovered row. */ onRowHover: PropTypes.func, /** * @ignore * Called when a table row is no longer * hovered. rowNumber is the row number of the row * that is no longer hovered. */ onRowHoverExit: PropTypes.func, /** * @ignore * Called when a row is selected. selectedRows is an * array of all row selections. IF all rows have been selected, * the string "all" will be returned instead to indicate that * all rows have been selected. */ onRowSelection: PropTypes.func, /** * Controls whether or not the rows are pre-scanned to determine * initial state. If your table has a large number of rows and * you are experiencing a delay in rendering, turn off this property. */ preScanRows: PropTypes.bool, /** * @ignore * If true, table rows can be selected. If multiple * row selection is desired, enable multiSelectable. * The default value is true. */ selectable: PropTypes.bool, /** * If true, table rows will be highlighted when * the cursor is hovering over the row. The default * value is false. */ showRowHover: PropTypes.bool, /** * If true, every other table row starting * with the first row will be striped. The default value is false. */ stripedRows: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; createRows() { const numChildren = React.Children.count(this.props.children); let rowNumber = 0; const handlers = { onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCellHover: this.onCellHover, onCellHoverExit: this.onCellHoverExit, onRowHover: this.onRowHover, onRowHoverExit: this.onRowHoverExit, onRowClick: this.onRowClick, }; return React.Children.map(this.props.children, (child) => { if (React.isValidElement(child)) { const props = { hoverable: this.props.showRowHover, selected: this.isRowSelected(rowNumber), striped: this.props.stripedRows && (rowNumber % 2 === 0), rowNumber: rowNumber++, }; if (rowNumber === numChildren) { props.displayBorder = false; } const children = [ this.createRowCheckboxColumn(props), ]; React.Children.forEach(child.props.children, (child) => { children.push(child); }); return React.cloneElement(child, {...props, ...handlers}, children); } }); } onCellDoubleClick = (event, rowNumber, columnNumber) => { event.stopPropagation(); if (this.props.onCellDoubleClick) { this.props.onCellDoubleClick(rowNumber, this.getColumnId(columnNumber), event); } }; render() { const { style, allRowsSelected, // eslint-disable-line no-unused-vars multiSelectable, // eslint-disable-line no-unused-vars onCellClick, // eslint-disable-line no-unused-vars onCellDoubleClick, // eslint-disable-line no-unused-vars onCellHover, // eslint-disable-line no-unused-vars onCellHoverExit, // eslint-disable-line no-unused-vars onRowHover, // eslint-disable-line no-unused-vars onRowHoverExit, // eslint-disable-line no-unused-vars onRowSelection, // eslint-disable-line no-unused-vars selectable, // eslint-disable-line no-unused-vars deselectOnClickaway, // eslint-disable-line no-unused-vars showRowHover, // eslint-disable-line no-unused-vars stripedRows, // eslint-disable-line no-unused-vars displayRowCheckbox, // eslint-disable-line no-unused-vars preScanRows, // eslint-disable-line no-unused-vars ...other } = this.props; const {prepareStyles} = this.context.muiTheme; return ( <ClickAwayListener onClickAway={this.handleClickAway}> <tbody style={prepareStyles(Object.assign({}, style))} {...other}> {this.createRows()} </tbody> </ClickAwayListener> ); } } export default DataTablesTableBody;
src/svg-icons/action/settings-backup-restore.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBackupRestore = (props) => ( <SvgIcon {...props}> <path d="M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9c-4.97 0-9 4.03-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.51 0-2.91-.49-4.06-1.3l-1.42 1.44C8.04 20.3 9.94 21 12 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z"/> </SvgIcon> ); ActionSettingsBackupRestore = pure(ActionSettingsBackupRestore); ActionSettingsBackupRestore.displayName = 'ActionSettingsBackupRestore'; ActionSettingsBackupRestore.muiName = 'SvgIcon'; export default ActionSettingsBackupRestore;
server/middleware/reactApplication/index.js
dariobanfi/react-avocado-starter
import React from 'react'; import Helmet from 'react-helmet'; import { renderToString, renderToStaticMarkup } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom'; import { ServerStyleSheet } from 'styled-components'; import config from '../../../config'; import ServerHTML from './ServerHTML'; import Application from '../../../app/components/Application'; export default function reactApplicationMiddleware(request, response) { // Ensure a nonce has been provided to us. // See the server/middleware/security.js for more info. if (typeof response.locals.nonce !== 'string') { throw new Error('A "nonce" value has not been attached to the response'); } const nonce = response.locals.nonce; // It's possible to disable SSR, which can be useful in development mode. // In this case traditional client side only rendering will occur. if (config('disableSSR')) { if (process.env.BUILD_FLAG_IS_DEV === 'true') { // eslint-disable-next-line no-console console.log('==> Handling react route without SSR'); } // SSR is disabled so we will return an "empty" html page and // rely on the client to initialize and render the react application. const html = renderToStaticMarkup(<ServerHTML nonce={nonce} />); response.status(200).send(`<!DOCTYPE html>${html}`); return; } // Create a context for <StaticRouter>, which will allow us to // query for the results of the render. const reactRouterContext = {}; // Declare our React application. const app = ( <StaticRouter location={request.url} context={reactRouterContext}> <Application /> </StaticRouter> ); const appString = renderToString(app); // Generate the html response. const html = renderToStaticMarkup( <ServerHTML reactAppString={appString} nonce={nonce} sheet={new ServerStyleSheet()} helmet={Helmet.rewind()} />, ); // Check if the router context contains a redirect, if so we need to set // the specific status and redirect header and end the response. if (reactRouterContext.url) { response.status(302).setHeader('Location', reactRouterContext.url); response.end(); return; } response .status( reactRouterContext.missed ? 404 : 200, ) .send(`<!DOCTYPE html>${html}`); }
src/components/Feedback/Feedback.js
seriflafont/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;