path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
stories/simple.js
yiminghe/css-animation
import anim from '../src'; import React from 'react'; import ReactDOM from 'react-dom'; import { storiesOf } from '@storybook/react'; const style = ` .box { background:red; width:100px; height:100px; } .fade-enter { opacity: 0; animation-duration: 0.3s; animation-fill-mode: both; animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2); animation-play-state: paused; } .fade-leave { animation-duration: 0.3s; animation-fill-mode: both; animation-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2); animation-play-state: paused; } .fade-enter.fade-enter-active { animation-name: rcDialogFadeIn; animation-play-state: running; } .fade-leave.fade-leave-active { animation-name: rcDialogFadeOut; animation-play-state: running; } @keyframes rcDialogFadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes rcDialogFadeOut { 0% { opacity: 1; } 100% { opacity: 0; } } `; let show = true; function toggle() { const t = document.getElementById('t'); const b = document.getElementById('b'); b.disabled = true; t.style.visibility = ''; anim(t, `fade-${show ? 'leave' : 'enter'}`, () => { t.style.visibility = show ? '' : 'hidden'; b.disabled = false; }); show = !show; } const Demo = () => ( <div> <style dangerouslySetInnerHTML={{ __html: style }}></style> <div className="box" id="t"></div> <button onClick={toggle} id="b"> toggle </button> </div> ); Demo.story = 'simple'; storiesOf(Demo.story, module).add('demo', () => <Demo />); export default Demo;
prototypes/cra-boilerplate/src/app.js
yldio/joyent-portal
import React, { Component } from 'react'; import createHistory from 'history/createBrowserHistory'; import { ThemeProvider } from 'styled-components'; import pathToRegexp from 'path-to-regexp'; import pascalCase from 'pascal-case'; import qs from 'qs'; import NotFound from './404'; import { theme, RootContainer } from 'joyent-ui-toolkit'; import * as Routes from './routes'; const history = createHistory(); const path = pathToRegexp('/:page?', [], { end: false }); const query = search => qs.parse(search.replace(/^\?/, '')); const name = pathname => path.exec(pathname)[1] || 'index'; const toState = location => ({ name: name(location.pathname), location: { query: query(location.search), hash: location.hash, pathname: location.pathname } }); class Router extends Component { state = toState(history.location); componentWillMount = () => { this.unlisten = history.listen(this._onLocationChange); }; componentWillUnmount = () => this.unlisten(); _onLocationChange = location => this.setState(location); render = () => { const { name } = this.state; const route = pascalCase(name); const View = Routes[route]; return View ? ( <View location={this.state.location} /> ) : ( <NotFound name={name} route={route} /> ); }; } export default () => ( <ThemeProvider theme={theme}> <RootContainer> <Router /> </RootContainer> </ThemeProvider> );
src/components/ListItem.js
hannupekka/cocheck
// @flow import styles from 'styles/components/ListItem.less'; import React, { Component } from 'react'; import { pure } from 'recompose'; import { SortableElement, SortableHandle } from 'react-sortable-hoc'; import ClickOutside from 'react-click-outside'; import DebounceInput from 'react-debounce-input'; import CSSModules from 'react-css-modules'; type Props = { id: string, name: string, checked: boolean, isEdited: boolean, onEditStart: Function, onEditEnd: Function, onEditCancel: Function, onRemove: Function, onToggle: Function, }; type State = { name: string, }; const DragHandle = SortableHandle(() => <i className="fa fa-bars" aria-hidden />); export class ListItem extends Component { props: Props; state: State; constructor(props: Object) { super(props); this.state = { name: props.name, }; } componentWillReceiveProps = (nextProps: Object): void => { this.setState({ name: nextProps.name }); }; onToggle = (): void => { const itemId = this.props.id; const { checked } = this.props; this.props.onToggle({ checked, itemId }); }; onEdit = (): void => { this.props.onEditStart(this.props.id); requestAnimationFrame(() => { const field = document.getElementById(`input-${this.props.id}`); if (field) { field.focus(); } }); }; onEditSave = (e?: SyntheticInputEvent): void => { // Stop clicks bubbling. if (e) { e.stopPropagation(); } const { id } = this.props; const { name } = this.state; if (name === '') { this.props.onEditCancel(); } else { this.props.onEditEnd(name, id); } }; onKeyDown = (e: KeyboardEvent): void => { if (e.key === 'Enter') { this.onEditSave(); } else if (e.key === 'Escape') { this.props.onEditCancel(); } }; onChange = (e: SyntheticInputEvent): void => { this.setState({ name: e.target.value }); }; onDelete = (): void => { this.props.onRemove(this.props.name, this.props.id); }; renderName = (): React$Element<any> => <DebounceInput id={`input-${this.props.id}`} debounceTimeout={50} readOnly={!this.props.isEdited} styleName={this.props.isEdited ? 'name--edit' : 'name--display'} type="text" value={this.state.name} onKeyDown={this.onKeyDown} onChange={this.onChange} />; render() { const { checked, isEdited } = this.props; const icon = checked ? 'fa fa-check-square-o' : 'fa fa-square-o'; return ( <div styleName={checked ? 'item--checked' : 'item'}> <div styleName="handle"> {<DragHandle />} </div> <div styleName="check"> <i className={icon} aria-hidden onClick={this.onToggle} /> </div> <div styleName="name"> {this.props.isEdited ? <ClickOutside onClickOutside={this.onEditSave}> {this.renderName()} </ClickOutside> : this.renderName()} </div> <div styleName="edit"> <i className={isEdited ? 'fa fa-check' : 'fa fa-pencil'} aria-hidden onClick={isEdited ? this.onEditSave : this.onEdit} /> </div> <div styleName="delete"> <i className="fa fa-trash-o" aria-hidden onClick={this.onDelete} /> </div> </div> ); } } export default pure(SortableElement(CSSModules(ListItem, styles)));
src/components/About/index.js
badT/twitchBot
import React from 'react'; import { styles } from './styles.scss'; const emoChart = require('./assets/emotionChart.jpg'); const socChart = require('./assets/socialChart.jpg'); export function About() { return ( <section className={`${styles}`}> <div className="row"> <div className="col-xs-12"> <section> <p className="intro"> Chatson is a live chat analyzer created to give users insight into the emotional state and crowd mentality of Twitch chat streams. Twitch is the world’s leading social video platform and community for gamers. Expand the sidebar to see a list of Twitch's channels that currently have the most viewers. Select a channel for a real time visualization of its emotional and social tone, current chat stream, and chat statistics. </p> </section> <p className="tone"> Emotional and social tone data is calculated using <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/tone-analyzer.html"> IBM Watson&#8482; Tone Analyzer</a>. The main chart's legend icons grow and shrink proportionally with the intensity of their corresponding attribute. The most prominent attribute is highlighted in bold in addition to the background color of the chart taking on that attribute's color with the saturation level matching its intensity. When viewing the real time charts, be sure to mouse over features for more information. </p> </div> </div> <div className="row separate"> <div className="col-md-7 .col-md-pull-4"> <section className="msg-chart"> <img src={emoChart} className="img-responsive" role="presentation" /> </section> </div> <div className="col-md-5 .col-md-push-8"> <section className="msg-data"> <p> Emotional tone is inferred from different types of emotions and feelings commonly expressed in language. </p> <ul> <li> <b>Anger:</b> expressed either actively with targeted verbal attacks or passively through tension and hostility. </li> <li> <b>Sadness:</b> indicates a feeling of loss and disadvantage. </li> <li> <b>Disgust:</b> a response of revulsion to something considered offensive or unpleasant. </li> <li> <b>Fear:</b> a response to perceived danger or some negative stimulus. </li> <li> <b>Joy:</b> having a sense of well-being, inner peace, love, safety and contentment. </li> </ul> </section> </div> </div> <div className="row separate"> <div className="col-md-7 .col-md-pull-4"> <section className="msg-chart"> <img src={socChart} className="img-responsive" role="presentation" /> </section> </div> <div className="col-md-5 .col-md-push-8"> <section className="msg-data"> <p> Social tone data uses the Big Five personality characteristics. The Big Five is the first and most widely used personality model to describe how a person engages with the world. </p> <ul> <li> <b>Openness:</b> the extent to which a person is open to experiencing a variety of activities. </li> <li> <b>Conscientiousness:</b> a person's tendency to act in an organized or thoughtful way. </li> <li> <b>Extraversion:</b> a person's tendency to seek stimulation in the company of others. </li> <li> <b>Areeableness:</b> a person's tendency to be compassionate and cooperative toward others. </li> <li> <b>Neuroticism:</b> the extent to which a person's emotions are sensitive to their environment. </li> </ul> </section> </div> </div> <p className="text-center closing-copy"> An explanation of the science behind the Tone Analyzer, as well as research references, can be found <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/tone-analyzer/science.shtml"> here</a>. </p> </section> ); }
src/components/AppIcon/AppIcon.js
folio-org/stripes-core
/** * App Icon * * Used to display an app's icon * in various places across the application */ import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { withStripes } from '../../StripesContext'; import css from './AppIcon.css'; const AppIcon = ({ iconAlignment, iconAriaHidden, size, icon, alt, src, style, children, className, tag, app, iconKey, iconClassName, stripes, }) => { const getIcon = () => { let appIconProps; /** * Icon from context * * We get the icons from the metadata which is passed down via context. * The default app icon has an iconKey of "app". * * If no icon is found we display a placeholder. * */ let appIcon = stripes?.icons?.[app]?.[iconKey]; if (!appIcon) appIcon = stripes?.icons?.[`@folio/${app}`]?.[iconKey]; if (appIcon && appIcon.src) { appIconProps = { src: appIcon.src, alt: appIcon.alt, }; // Use PNGs (if available) for small app icons on non-retina screens const isRetina = window.matchMedia(` (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi) `).matches; // Ignoring next block in tests since it can't be tested consistently // istanbul ignore next if (!isRetina && size === 'small' && appIcon.low && appIcon.low.src) { appIconProps.src = appIcon.low.src; } } /* If we have an image passed as an object */ if (typeof icon === 'object') { appIconProps = { src: icon.src, alt: icon.alt, }; } // No image props - return nothing and the placeholder will be active if (!appIconProps) { return null; } return ( <img src={typeof src !== 'undefined' ? src : appIconProps.src} alt={typeof alt !== 'undefined' ? alt : appIconProps.alt} /> ); }; /** * Root CSS styles */ const rootStyles = classnames( /* Base app icon styling */ css.appIcon, /* Icon size */ css[size], /* Icon alignment */ css[`icon-alignment-${iconAlignment}`], /* Custom ClassName */ className, ); /** * Element - changeable by prop */ const Element = tag; /** * Render */ return ( <Element className={rootStyles} style={style}> <span className={classnames(css.icon, iconClassName)} aria-hidden={iconAriaHidden}> {getIcon()} </span> { children && <span className={css.label}>{children}</span> } </Element> ); }; AppIcon.propTypes = { alt: PropTypes.string, app: PropTypes.string, children: PropTypes.node, className: PropTypes.string, icon: PropTypes.shape({ alt: PropTypes.string, src: PropTypes.string.isRequired, }), iconClassName: PropTypes.string, iconAriaHidden: PropTypes.bool, iconAlignment: PropTypes.oneOf(['center', 'baseline']), iconKey: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large']), src: PropTypes.string, stripes: PropTypes.shape({ metadata: PropTypes.object, icons: PropTypes.object, }), style: PropTypes.object, tag: PropTypes.string, }; AppIcon.defaultProps = { iconAlignment: 'center', iconAriaHidden: true, iconKey: 'app', size: 'medium', tag: 'span', }; export default withStripes(AppIcon);
test/CollapseSpec.js
jakubsikora/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Collapse from '../src/Collapse'; describe('Collapse', function () { let Component, instance; beforeEach(function(){ Component = React.createClass({ render(){ let { children, ...props } = this.props; return ( <Collapse ref={r => this.collapse = r} getDimensionValue={()=> 15 } {...props} > <div> <div ref="panel"> {children} </div> </div> </Collapse> ); } }); }); it('Should default to collapsed', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok( instance.collapse.props.in === false); }); describe('collapsed', function(){ it('Should have collapse class', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse')); }); }); describe('from collapsed to expanded', function(){ let scrollHeightStub; beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); // since scrollHeight is gonna be 0 detached from the DOM scrollHeightStub = sinon.stub(instance.collapse, '_getScrollDimensionValue'); scrollHeightStub.returns('15px'); }); it('Should have collapsing class', function () { instance.setProps({ in: true }); let node = React.findDOMNode(instance); assert.equal(node.className, 'collapsing'); }); it('Should set initial 0px height', function (done) { let node = React.findDOMNode(instance); function onEnter(){ assert.equal(node.style.height, '0px'); done(); } assert.equal(node.style.height, ''); instance.setProps({ in: true, onEnter }); }); it('Should set node to height', function () { let node = React.findDOMNode(instance); assert.equal(node.styled, undefined); instance.setProps({ in: true }); assert.equal(node.style.height, '15px'); }); it('Should transition from collapsing to not collapsing', function (done) { let node = React.findDOMNode(instance); function onEntered(){ assert.equal(node.className, 'collapse in'); done(); } instance.setProps({ in: true, onEntered }); assert.equal(node.className, 'collapsing'); }); it('Should clear height after transition complete', function (done) { let node = React.findDOMNode(instance); function onEntered(){ assert.equal(node.style.height, ''); done(); } assert.equal(node.style.height, ''); instance.setProps({ in: true, onEntered }); assert.equal(node.style.height, '15px'); }); }); describe('from expanded to collapsed', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component in>Panel content</Component> ); }); it('Should have collapsing class', function () { instance.setProps({ in: false }); let node = React.findDOMNode(instance); assert.equal(node.className, 'collapsing'); }); it('Should set initial height', function () { let node = React.findDOMNode(instance); function onExit(){ assert.equal(node.style.height, '15px'); } assert.equal(node.style.height, ''); instance.setProps({ in: false, onExit }); }); it('Should set node to height', function () { let node = React.findDOMNode(instance); assert.equal(node.style.height, ''); instance.setProps({ in: false }); assert.equal(node.style.height, '0px'); }); it('Should transition from collapsing to not collapsing', function (done) { let node = React.findDOMNode(instance); function onExited(){ assert.equal(node.className, 'collapse'); done(); } instance.setProps({ in: false, onExited }); assert.equal(node.className, 'collapsing'); }); it('Should have 0px height after transition complete', function (done) { let node = React.findDOMNode(instance); function onExited(){ assert.ok(node.style.height === '0px'); done(); } assert.equal(node.style.height, ''); instance.setProps({ in: false, onExited }); }); }); describe('expanded', function(){ it('Should have collapse and in class', function () { instance = ReactTestUtils.renderIntoDocument( <Component in >Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse in')); }); }); describe('dimension', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); }); it('Defaults to height', function(){ assert.equal(instance.collapse._dimension(), 'height'); }); it('Uses getCollapsibleDimension if exists', function(){ function dimension(){ return 'whatevs'; } instance.setProps({ dimension }); assert.equal(instance.collapse._dimension(), 'whatevs'); }); }); describe('with a role', function() { beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component role="note">Panel content</Component> ); }); it('sets aria-expanded true when expanded', function() { let node = React.findDOMNode(instance); instance.setProps({ in: true}); assert.equal(node.getAttribute('aria-expanded'), 'true'); }); it('sets aria-expanded false when collapsed', function() { let node = React.findDOMNode(instance); instance.setProps({ in: false}); assert.equal(node.getAttribute('aria-expanded'), 'false'); }); }); });
index.ios.js
wangdicoder/JueJinClient
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import {AppRegistry} from 'react-native'; import Navigation from './js/config/entry'; export default class JueJinClient extends Component { render() { return ( <Navigation/> ); } } AppRegistry.registerComponent('JueJinClient', () => JueJinClient);
test/compoents.js
kris1226/clymer-metal-crafts
import expect from 'expect'; import React from 'react';
techCurriculum/ui/starter_code/cards-app/src/App.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; function App() { return ( <div> <h1>Hello World 2</h1> </div> ); } export default App;
src/components/editor/editorPane.js
Q42/CT-3000
import React from 'react'; import ReactDOM from 'react-dom'; import Reflux from 'reflux'; import Codemirror from 'react-codemirror'; import CMInstance from 'codemirror'; import CT3000 from '../../config/codemirrorCustomMode'; import 'codemirror/addon/mode/simple'; import 'codemirror/addon/selection/active-line'; import ObjectActions from '../../actions/object'; import ObjectStore from '../../stores/object'; import TranslationStore from '../../stores/translation' export default class EditorPane extends React.Component { constructor(props) { super(props); this.updateCode = this.updateCode.bind(this); this.parseUntilLine = this.parseUntilLine.bind(this); this.lineInterval = null; this.lineTimeoutDuration = 5000; this.previouslyFailedLines = []; let template = ''; if (this.props.template) { try { template = require('raw-loader!../../assets/templates/' + TranslationStore.language + '/' + this.props.template + '.txt'); } catch (ex) { console.warn('Cannot find template file /assets/templates/' + TranslationStore.language + '/' + this.props.template + '.txt'); } } this.state = { code: template, mode: '', languageInitiated: false }; } componentDidMount() { this.unsubscribe = ObjectStore.listen((data) => { this.onUpdate(data); }); this.cm = this.refs.editor.getCodeMirror(); this.cmDoc = this.cm.getDoc(); this.cm.on('cursorActivity', () => { this.parseUntilLine(); }); this.setLineInterval(); } componentWillUnmount() { this.clearLineInterval(); this.unsubscribe(); } onUpdate(data) { if(!this.state.languageInitiated) { this.initLanguage(); } // Remove previous syntax errors const linesToClear = this.previouslyFailedLines.filter(line => !data.failedLines.includes(line)); linesToClear.map(line => { this.cmDoc.removeLineClass(line, 'wrap', 'syntax-error'); }); // Highlight current syntax errors if(data.failedLines.length > 0) { const linesToAdd = data.failedLines.filter(line => !this.previouslyFailedLines.includes(line)); linesToAdd.map(line => { this.cmDoc.addLineClass(line, 'wrap', 'syntax-error'); }); } // Store for the next parse round this.previouslyFailedLines = data.failedLines; } initLanguage() { let availableObjects = ObjectStore.getAvailableObjects(); let availableValues = ObjectStore.getAvailableValues(); let keywords = [TranslationStore.mappingKeywords['if'], TranslationStore.mappingKeywords['then'], TranslationStore.mappingKeywords['and']]; var language = new CT3000(); CMInstance.defineSimpleMode('ct-3000', language.getMode(availableObjects, availableValues, keywords)); this.setState({ mode: 'ct-3000', languageInitiated: true }); } updateCode(newCode) { this.setState({ code: newCode }); } setLineInterval() { this.clearLineInterval(); this.lineInterval = setInterval(this.parseUntilLine, this.lineTimeoutDuration); } clearLineInterval() { clearInterval(this.lineInterval); } parseUntilLine() { const currentLineNr = this.cm.getCursor().line; let lines = {}; this.cm.eachLine(handle => { const lineNr = this.cm.getLineNumber(handle); const line = this.cm.getLine(lineNr); if(line && line.trim().length > 0) { lines[lineNr] = { code: line, current: currentLineNr === lineNr } } }); ObjectActions.parseMulti(lines); } render() { var options = { lineNumbers: true, lineWrapping: true, indentUnit: 2, tabSize: 2, theme: 'monokai', styleActiveLine: true, mode: this.state.mode }; return ( <div className="pane editor-pane"> <Codemirror ref="editor" value={ this.state.code } onChange={ this.updateCode } options={ options } /> </div> ); } }
src/components/Net/Net.js
teemuteemu/sp_modular
import React from 'react'; import Path from 'svg-path-generator'; import './net.scss'; class Net extends React.Component { constructor (props) { super(props); this.onMouseOver = this.onMouseOver.bind(this); this.onMouseOut = this.onMouseOut.bind(this); this.onMouseDown = this.onMouseDown.bind(this); this.state = { mouseOver: false }; } onMouseDown () { const { net, disconnectLets } = this.props; disconnectLets(net); } onMouseOver () { this.setState({ mouseOver: true }); } onMouseOut () { this.setState({ mouseOver: false }); } componentDidMount () { const net = this.refs.net; net.addEventListener('mouseover', this.onMouseOver); net.addEventListener('mouseout', this.onMouseOut); net.addEventListener('mousedown', this.onMouseDown); } componentWillUnmount () { const net = this.refs.net; net.removeEventListener('mouseover', this.onMouseOver); net.removeEventListener('mouseout', this.onMouseOut); net.removeEventListener('mousedown', this.onMouseDown); } render () { const { mouseOver } = this.state; const { net, netToCoords } = this.props const coordinates = netToCoords(net); const className = [ 'net', mouseOver ? 'net--selected' : '' ].join(' '); const diffs = [coordinates[1][0] - coordinates[0][0], coordinates[1][1] - coordinates[1][0]]; const bend_x = diffs[0] / 25; const bend_y = Math.abs(diffs[1]) / 7; const data = Path() .moveTo(coordinates[0][0], coordinates[0][1]) .smoothCurveTo(coordinates[0][0] + bend_x, coordinates[0][1] + bend_y, (coordinates[0][0] + coordinates[1][0]) / 2, coordinates[0][1] + bend_y) .smoothCurveTo(coordinates[1][0] - bend_x, coordinates[1][1] + bend_y, coordinates[1][0], coordinates[1][1]) .end(); return ( <path ref='net' className={className} d={data} /> ); } }; Net.propTypes = { net: React.PropTypes.array.isRequired, netToCoords: React.PropTypes.func.isRequired, disconnectLets: React.PropTypes.func.isRequired }; export default Net;
examples/simple/index.js
ChristopherBiscardi/library-boilerplate
import React from 'react'; import App from './components/App'; React.render( <App />, document.getElementById('root') );
src/components/UnitView/instructions/Headers.js
fkn/ndo
import _ from 'lodash'; import React from 'react'; import Base from './Base'; /** * gathering info about H1..6 tags */ export default class Headers extends Base { constructor(root, onHeadersChange) { super(root); this.onHeadersChange = onHeadersChange; } shouldProcessNode(node) { if (!this.onHeadersChange) return false; return /^[hH]([1-6])$/.exec(node.name); } processNode(node, children, index) { const level = +/^[hH]([1-6])$/.exec(node.name)[1]; const id = _.get(node, 'attribs.id') || _.get(node, 'attribs.name') || `header-${index}`; this.root.headers.push({ level, id, title: node.children .filter(c => c.type === 'text') .map(c => c.data) .join(' '), link: `#${id}`, }); const renderAttrs = { id, key: index }; const CustomTag = node.name; return <CustomTag {...renderAttrs}>{children}</CustomTag>; } }
src/svg-icons/av/video-label.js
w01fgang/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;
app/javascript/mastodon/features/ui/components/column.js
Chronister/mastodon
import React from 'react'; import ColumnHeader from './column_header'; import PropTypes from 'prop-types'; import { debounce } from 'lodash'; import { scrollTop } from '../../../scroll'; import { isMobile } from '../../../is_mobile'; export default class Column extends React.PureComponent { static propTypes = { heading: PropTypes.string, icon: PropTypes.string, children: PropTypes.node, active: PropTypes.bool, hideHeadingOnMobile: PropTypes.bool, }; handleHeaderClick = () => { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } scrollTop () { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleScroll = debounce(() => { if (typeof this._interruptScrollAnimation !== 'undefined') { this._interruptScrollAnimation(); } }, 200) setRef = (c) => { this.node = c; } render () { const { heading, icon, children, active, hideHeadingOnMobile } = this.props; const showHeading = heading && (!hideHeadingOnMobile || (hideHeadingOnMobile && !isMobile(window.innerWidth))); const columnHeaderId = showHeading && heading.replace(/ /g, '-'); const header = showHeading && ( <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} columnHeaderId={columnHeaderId} /> ); return ( <div ref={this.setRef} role='region' aria-labelledby={columnHeaderId} className='column' onScroll={this.handleScroll} > {header} {children} </div> ); } }
src/main/js/my-app/src/components/Dashboard.js
myapos/ClientManagerSpringBoot
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Tabs, TabLink, TabContent } from 'react-tabs-redux'; import * as actions from '../actions/'; import StudentClasses from './StudentClasses'; import PaymentRegisters from './PaymentRegisters'; import Registers from './Registers'; import StudentDataTable from './StudentDataTable'; import SendEmailsManually from './SendEmailsManually'; const styles = { tabs: { marginRight: '30px', verticalAlign: 'top', }, links: { margin: 0, padding: 0, }, tabLink: { height: '30px', lineHeight: '30px', cursor: 'pointer', borderBottom: '2px solid transparent', }, activeLinkStyle: { borderBottom: '2px solid #333', }, visibleTabStyle: { }, }; class Dashboard extends Component { static propTypes = { initRegistrations: PropTypes.array, initDataStudentClasses: PropTypes.array, initDataStudents: PropTypes.array, initPayments: PropTypes.array, changeSelectedTab: PropTypes.func, selectedTab: PropTypes.string, displayInitialMsg: PropTypes.bool, } constructor (props) { super(props); this.state = { ...props, }; } defaultTab (tab) { // get last active tab from local storage // Store const lastActiveTab = parseInt(localStorage.getItem('lastTabLoaded')); // extract last digit of tab const lastNum = parseInt(tab[tab.length - 1]); if (lastActiveTab === lastNum - 1) { return true; } else { return false; } } render () { const { initRegistrations, initDataStudentClasses, initDataStudents, initPayments, displayInitialMsg } = this.props; window.onbeforeunload = () => { const el = document.getElementById('tabLinks'); const nodeList = el.childNodes; const nodes = Array.from(nodeList); // convert to array from nodelist const positions = nodes.map((item, key) => { if (item.className.includes('active')) { return key; } else { return -1; } }); console.log('positions:', positions); const pos = positions.find(item => item !== -1); // Store localStorage.setItem('lastTabLoaded', pos); // return "Any string value here forces a dialog box to \n" + // "appear before closing the window."; }; return ( <div className="App" id="content"> <h2>Καλωσήρθατε στην διαχείριση πελατών ClientManager</h2> <div className="labelContainer"> <legend><span>Πίνακας Ελέγχου</span></legend> </div> <Tabs name="selectedTab" handleSelect={this.props.changeSelectedTab} selectedTab={this.props.selectedTab} activeLinkStyle={styles.activeLinkStyle} visibleTabStyle={styles.visibleTabStyle} style={styles.tabs} id="tabs"> <div id="tabLinks" style={styles.links}> <TabLink to="tab1" default={this.defaultTab('tab1')} style={styles.tabLink}>Διαχείριση Πελατών </TabLink> <TabLink to="tab2" default={this.defaultTab('tab2')} style={styles.tabLink}>Διαχείριση Τμημάτων </TabLink> <TabLink to="tab3" default={this.defaultTab('tab3')} style={styles.tabLink}>Διαχείριση Εγγραφών </TabLink> <TabLink to="tab4" default={this.defaultTab('tab4')} style={styles.tabLink}>Διαχείριση Πληρωμών </TabLink> <TabLink to="tab5" default={this.defaultTab('tab5')} style={styles.tabLink}>Επικοινωνία Τμημάτων </TabLink> </div> <div id="tabContent" style={styles.content}> <TabContent for="tab1"> <div id="tab1"> <StudentDataTable initDataStudents={initDataStudents} /> </div> </TabContent> <TabContent for="tab2"> <div id="tab2"> <StudentClasses initRegistrations={initRegistrations} initDataStudentClasses={initDataStudentClasses} initDataStudents={initDataStudents} /> </div> </TabContent> <TabContent for="tab3"> <div id="tab3"> <Registers initDataStudentClasses={initDataStudentClasses} /> </div> </TabContent> <TabContent for="tab4"> <div id="tab4"> <PaymentRegisters initPayments={initPayments} /> </div> </TabContent> <TabContent for="tab5"> <div id="tab5"> <SendEmailsManually displayInitialMsg={displayInitialMsg} /> </div> </TabContent> </div> </Tabs> </div> ); } } export default connect(state => state, actions)(Dashboard);
src/js/components/ui/forms/InputErrorMessage.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import PropTypes from 'prop-types'; import React from 'react'; export default class InputDescription extends React.Component { render() { const errorMessage = this.props.getErrorMessage(); return errorMessage ? ( <span className="help-block">{errorMessage}</span> ) : null; } } InputDescription.propTypes = { getErrorMessage: PropTypes.func.isRequired };
src/js/components/icons/base/Inspect.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-inspect`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'inspect'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M5.5,21 C7.98528137,21 10,18.9852814 10,16.5 C10,14.0147186 7.98528137,12 5.5,12 C3.01471863,12 1,14.0147186 1,16.5 C1,18.9852814 3.01471863,21 5.5,21 Z M1,16 L1,7 L1,6.5 C1,4.01471863 3.01471863,2 5.5,2 L6,2 M23,16 L23,7 L23,6.5 C23,4.01471863 20.9852814,2 18.5,2 L18,2 M18.5,21 C20.9852814,21 23,18.9852814 23,16.5 C23,14.0147186 20.9852814,12 18.5,12 C16.0147186,12 14,14.0147186 14,16.5 C14,18.9852814 16.0147186,21 18.5,21 Z M10,17 C10,17 10,15 12,15 C14,15 14,17 14,17"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Inspect'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/layout/Footer.js
petertrotman/critrolemoments
import React from 'react'; const Footer = () => <p>Footer</p>; export default Footer;
src/svg-icons/notification/system-update.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSystemUpdate = (props) => ( <SvgIcon {...props}> <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z"/> </SvgIcon> ); NotificationSystemUpdate = pure(NotificationSystemUpdate); NotificationSystemUpdate.displayName = 'NotificationSystemUpdate'; NotificationSystemUpdate.muiName = 'SvgIcon'; export default NotificationSystemUpdate;
example/es6/index.js
romagny13/react-form-validation
import React, { Component } from 'react'; import { render } from 'react-dom'; import App from './components/App'; render(<App />, document.getElementById('app'));
examples/src/app.js
Amirus/react-autosuggest
require('./app.less'); import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Badges from './Badges/Badges'; import Examples from './Examples'; import Footer from './Footer/Footer'; import ForkMeOnGitHub from './ForkMeOnGitHub/ForkMeOnGitHub'; class App extends Component { render() { return ( <div> <h1>react-autosuggest</h1> <Badges /> <Examples /> <Footer /> <ForkMeOnGitHub user="moroshko" repo="react-autosuggest" /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app'));
test/Debug-spec.js
dustinsanders/enzyme
import { expect } from 'chai'; import React from 'react'; import { spaces, indent, debugNode, } from '../src/Debug'; import { mount } from '../src/'; import { describeWithDOM, itIf } from './_helpers'; import { REACT013 } from '../src/version'; describe('debug', () => { describe('spaces(n)', () => { it('should return n spaces', () => { expect(spaces(4)).to.equal(' '); expect(spaces(2)).to.equal(' '); expect(spaces(0)).to.equal(''); }); }); describe('indent(depth, string)', () => { it('should indent a single-line string by (n) spaces', () => { expect(indent(4, 'hello')).to.equal(' hello'); expect(indent(2, 'hello')).to.equal(' hello'); expect(indent(0, 'hello')).to.equal('hello'); }); it('should intent a multiline string by (n) spaces', () => { expect(indent(2, 'foo\nbar')).to.equal(' foo\n bar'); }); }); describe('debugNode(node)', () => { it('should render a node with no props or children as single single xml tag', () => { expect(debugNode(<div />)).to.equal('<div />'); }); it('should render props inline inline', () => { expect(debugNode( <div id="foo" className="bar" /> )).to.equal( '<div id="foo" className="bar" />' ); }); it('should render children on newline and indented', () => { expect(debugNode( <div> <span /> </div> )).to.equal( `<div> <span /> </div>` ); }); it('should render props on root and children', () => { expect(debugNode( <div id="foo"> <span id="bar" /> </div> )).to.equal( `<div id="foo"> <span id="bar" /> </div>` ); }); it('should render text on new line and indented', () => { expect(debugNode( <span>some text</span> )).to.equal( `<span> some text </span>` ); }); it('should render composite components as tags w/ displayName', () => { class Foo extends React.Component { render() { return <div />; } } Foo.displayName = 'Bar'; expect(debugNode( <div> <Foo /> </div> )).to.equal( `<div> <Bar /> </div>` ); }); it('should render composite components as tags w/ name', () => { class Foo extends React.Component { render() { return <div />; } } expect(debugNode( <div> <Foo /> </div> )).to.equal( `<div> <Foo /> </div>` ); }); itIf(!REACT013, 'should render stateless components as tags w/ name', () => { const Foo = () => <div />; expect(debugNode( <div> <Foo /> </div> )).to.equal( `<div> <Foo /> </div>` ); }); it('should render mapped children properly', () => { expect(debugNode( <div> <i>not in array</i> {['a', 'b', 'c']} </div> )).to.equal( `<div> <i> not in array </i> a b c </div>` ); }); it('should render number children properly', () => { expect(debugNode( <div> {-1} {0} {1} </div> )).to.equal( `<div> -1 0 1 </div>` ); }); it('renders html entities properly', () => { expect(debugNode( <div>&gt;</div> )).to.equal( `<div> &gt; </div>` ); }); it('should not render falsy children ', () => { expect(debugNode( <div id="foo"> {false} {null} {undefined} {''} </div> )).to.equal('<div id="foo" />'); }); }); describeWithDOM('debugInst(inst)', () => { it('renders basic debug of mounted components', () => { class Foo extends React.Component { render() { return ( <div className="foo"> <span>Foo</span> </div> ); } } expect(mount(<Foo id="2" />).debug()).to.eql( `<Foo id="2"> <div className="foo"> <span> Foo </span> </div> </Foo>`); }); it('renders debug of compositional components', () => { class Foo extends React.Component { render() { return ( <div className="foo"> <span>Foo</span> </div> ); } } class Bar extends React.Component { render() { return ( <div className="bar"> <span>Non-Foo</span> <Foo baz="bax" /> </div> ); } } expect(mount(<Bar id="2" />).debug()).to.eql( `<Bar id="2"> <div className="bar"> <span> Non-Foo </span> <Foo baz="bax"> <div className="foo"> <span> Foo </span> </div> </Foo> </div> </Bar>`); }); it('renders a subtree of a mounted tree', () => { class Foo extends React.Component { render() { return ( <div className="foo"> <span>Foo</span> </div> ); } } class Bar extends React.Component { render() { return ( <div className="bar"> <span>Non-Foo</span> <Foo baz="bax" /> </div> ); } } expect(mount(<Bar id="2" />).find(Foo).debug()).to.eql( `<Foo baz="bax"> <div className="foo"> <span> Foo </span> </div> </Foo>`); }); it('renders passed children properly', () => { class Foo extends React.Component { render() { return ( <div className="foo"> <span>From Foo</span> {this.props.children} </div> ); } } class Bar extends React.Component { render() { return ( <div className="bar"> <Foo baz="bax"> <span>From Bar</span> </Foo> </div> ); } } expect(mount(<Bar id="2" />).debug()).to.eql( `<Bar id="2"> <div className="bar"> <Foo baz="bax"> <div className="foo"> <span> From Foo </span> <span> From Bar </span> </div> </Foo> </div> </Bar>`); }); }); });
frontend/jqwidgets/jqwidgets-react/react_jqxlayout.js
liamray/nexl-js
/* jQWidgets v5.7.2 (2018-Apr) Copyright (c) 2011-2018 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxLayout extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['contextMenu','height','layout','minGroupHeight','minGroupWidth','resizable','rtl','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxLayout(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxLayout('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxLayout(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; contextMenu(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('contextMenu', arg) } else { return JQXLite(this.componentSelector).jqxLayout('contextMenu'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('height', arg) } else { return JQXLite(this.componentSelector).jqxLayout('height'); } }; layout(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('layout', arg) } else { return JQXLite(this.componentSelector).jqxLayout('layout'); } }; minGroupHeight(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('minGroupHeight', arg) } else { return JQXLite(this.componentSelector).jqxLayout('minGroupHeight'); } }; minGroupWidth(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('minGroupWidth', arg) } else { return JQXLite(this.componentSelector).jqxLayout('minGroupWidth'); } }; resizable(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('resizable', arg) } else { return JQXLite(this.componentSelector).jqxLayout('resizable'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('rtl', arg) } else { return JQXLite(this.componentSelector).jqxLayout('rtl'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('theme', arg) } else { return JQXLite(this.componentSelector).jqxLayout('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('width', arg) } else { return JQXLite(this.componentSelector).jqxLayout('width'); } }; destroy() { JQXLite(this.componentSelector).jqxLayout('destroy'); }; loadLayout(Layout) { JQXLite(this.componentSelector).jqxLayout('loadLayout', Layout); }; refresh() { JQXLite(this.componentSelector).jqxLayout('refresh'); }; performRender() { JQXLite(this.componentSelector).jqxLayout('render'); }; saveLayout() { return JQXLite(this.componentSelector).jqxLayout('saveLayout'); }; render() { let id = 'jqxLayout' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
site/components/NavBar.js
numso/react-dnd
import React from 'react'; import { DOCS_DEFAULT, EXAMPLES_DEFAULT } from '../Constants'; import './NavBar.less'; const GITHUB_URL = 'https://github.com/gaearon/react-dnd'; const DOCS_LOCATION = DOCS_DEFAULT.location; const EXAMPLES_LOCATION = EXAMPLES_DEFAULT.location; export default class NavBar { render() { return ( <div className="NavBar"> <div className="NavBar-container"> <div className="NavBar-logo"> <a href="./" target="_self" className="NavBar-logoTitle">React <i>DnD</i></a> <p className="NavBar-logoDescription">Drag and Drop for React</p> </div> <div className="NavBar-item"> <a className="NavBar-link" href={DOCS_LOCATION} target="_self">Docs</a> <a className="NavBar-link" href={EXAMPLES_LOCATION} target="_self">Examples</a> <a className="NavBar-link" href={GITHUB_URL}>GitHub</a> </div> </div> </div> ); } }
src/Card/CardExpander.js
boldr/boldr-ui
/* eslint-disable react/prefer-stateless-function, no-unused-vars */ import React, { Component } from 'react'; import cn from 'classnames'; import Icon from '../Icons/Icon'; import contextTypes from './contextTypes'; /** * The CardExpander component is just a simple `IconButton` that * gets generated through the `Card`'s `contextTypes`. Props are not used * at all. * * Any component below a component that has this component inject into it * and has the prop `expandable={true}` will be toggleable when this is clicked. * * You can manually inject the `CardExpander` component yourself if you want to * use a component that is not a `CardActions` or a `CardTitle`. */ export default class CardExpander extends Component { static contextTypes = contextTypes; render() { const { expanded, onExpandClick, iconClassName, iconChildren, tooltipPosition, tooltipLabel, tooltipDelay, } = this.context; return ( <Icon className={cn('md-collapser md-collapser--card', { 'md-collapser--flipped': expanded, })} kind={!expanded ? 'chevron-down' : 'chevron-up'} color="#222" size="24px" onClick={onExpandClick} > {iconChildren} </Icon> ); } }
bitpig/__tests__/index.android.js
kuncloud/bitcoinHelper
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
actor-apps/app-web/src/app/components/common/ConnectionState.react.js
chenbk85/actor-platform
import React from 'react'; import classnames from 'classnames'; import ConnectionStateStore from 'stores/ConnectionStateStore'; const getStateFromStore = () => { return { connectionState: ConnectionStateStore.getState() }; }; class ConnectionState extends React.Component { constructor(props) { super(props); this.state = getStateFromStore(); ConnectionStateStore.addChangeListener(this.onStateChange); } componentWillUnmount() { ConnectionStateStore.removeChangeListener(this.onStateChange); } onStateChange = () => { this.setState(getStateFromStore); }; render() { const { connectionState } = this.state; const className = classnames('connection-state', { 'connection-state--online': connectionState === 'online', 'connection-state--connection': connectionState === 'connecting' }); switch (connectionState) { case 'online': return ( <div className={className}>'You're back online!'</div> ); case 'connecting': return ( <div className={className}> Houston, we have a problem! Connection to Actor server is lost. Trying to reconnect now... </div> ); default: return null; } } } export default ConnectionState;
fields/types/cloudinaryimage/CloudinaryImageColumn.js
woody0907/keystone
import React from 'react'; import CloudinaryImageSummary from '../../components/columns/CloudinaryImageSummary'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; var CloudinaryImageColumn = React.createClass({ displayName: 'CloudinaryImageColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue: function() { var value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return; return ( <ItemsTableValue field={this.props.col.type}> <CloudinaryImageSummary label="dimensions" image={value} /> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = CloudinaryImageColumn;
src/components/rails/plain/RailsPlain.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './RailsPlain.svg' /** RailsPlain */ function RailsPlain({ width, height, className }) { return ( <SVGDeviconInline className={'RailsPlain' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } RailsPlain.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default RailsPlain
code/src/components/channelParameters.js
GreatDanton/Thesis
import React from 'react'; // custom imports import { InputBox } from './commonParts/inputBoxes.js'; import { ScatterChart } from './commonParts/charts.js'; import GlobalStorage from '../scripts/globalStorage'; class RectangularChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.rectangular; this.state = ({ h: this.storage.h, B: this.storage.B, ng: this.storage.ng, φ: this.storage.φ, P: this.storage.P, S: this.storage.S }); this.handleChange = this.handleChange.bind(this); } circumference() { let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let P = 2 * h + B; return P; } area() { let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let S = h * B; return S; } handleChange(event) { let id = event.target.id; let value = event.target.value; let calculateIf = ['B', 'h']; this.setState({ [id]: value }, function () { if (calculateIf.indexOf(id) > -1) { this.storage.S = this.area(); this.storage.P = this.circumference(); } }); this.storage[id] = value; } render() { return ( <div> <div className="container-900"> <div className="row"> <div className="col-30"> <InputBox id="B" end="m" value={this.state.B} onChange={this.handleChange} /> <InputBox id="h" end="m" value={this.state.h} onChange={this.handleChange} /> <br /> <InputBox id="ng" end="/" value={this.state.ng} onChange={this.handleChange} /> <InputBox id="φ" end="%" value={this.state.φ} onChange={this.handleChange} /> </div> <div className="col-70"> <img className="img-guide" src="images/rectangularChannel_guide.svg" alt="Rectangular river channel" /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> </div> ) } } class TrapezoidChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.trapezoid; this.state = ({ B: this.storage.B, b: this.storage.b, h: this.storage.h, ng: this.storage.ng, φ: this.storage.φ, S: this.storage.S, P: this.storage.P }); this.handleChange = this.handleChange.bind(this); } circumference() { let b = parseFloat(this.state.b); let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let x = (B - b) / 2 let P = b + 2 * (x ** 2 + h ** 2) ** (1 / 2); return P } area() { let b = parseFloat(this.state.b); let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let x = (B - b) / 2; let S = b * h + x * h return S } handleChange(event) { let value = event.target.value; let id = event.target.id; let calculateIf = ['B', 'b', 'h']; this.setState({ [id]: value }, function () { // callback function if (calculateIf.indexOf(id) > 0) { this.storage.S = this.area(); this.storage.P = this.circumference(); } }); this.storage[id] = value; // save value of input into global storage } render() { return ( <div> <div className="container-900"> <div className="row"> <div className="col-30"> <InputBox id="B" end="m" value={this.state.B} onChange={this.handleChange} /> <InputBox id="b" end="m" value={this.state.b} onChange={this.handleChange} /> <InputBox id="h" end="m" value={this.state.h} onChange={this.handleChange} /> <br /> <InputBox id="ng" end="/" value={this.state.ng} onChange={this.handleChange} /> <InputBox id="φ" end="%" value={this.state.φ} onChange={this.handleChange} /> </div> <div className="col-70"> <img className="img-guide" src="images/trapezoidChannel_guide.svg" alt="Trapezoid river channel" /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> </div> ) } } class CustomChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.custom; this.state = { points: this.storage.points, x: '', y: '', ng: this.storage.ng, φ: this.storage.φ }; this.onChange = this.onChange.bind(this); this.addPoint = this.addPoint.bind(this); this.deleteClick = this.deleteClick.bind(this); } // add new point to state addPoint(e) { e.preventDefault(); // if x & y are numbers, add them to the table let X = parseFloat(this.state.x); let Y = parseFloat(this.state.y); if (!isNaN(X) && !isNaN(Y)) { // if x and y is number let p = { x: X, y: Y }; let points = this.state.points.slice(); points.push(p); this.setState({ points: points, x: '', y: '' }); // add new array, and reset input fields this.storage.points = points; // save points array into storage } } onChange(e) { this.setState({ [e.target.id]: e.target.value }); if (e.target.id === "ng") { this.storage.ng = parseFloat(e.target.value); } else if (e.target.id === "φ") { this.storage.φ = parseFloat(e.target.value); } } deleteClick(e) { let id = e.currentTarget.getAttribute('id'); let pointsArr = this.state.points.slice(); // copy state pointsArr.splice(id, 1); // remove point with index same as id (clicked element) this.setState({ points: pointsArr }); this.storage.points = pointsArr; // save new array into global storage } render() { return ( <div className="container-900"> <div className="row"> <div className="col-30"> {/* button press on enter click will submit the form => execute addPoint*/} <form onSubmit={this.addPoint}> <div className="row centered"> <InputBox id="x" end="" value={this.state.x} onChange={this.onChange} /> <InputBox id="y" end="" value={this.state.y} onChange={this.onChange} /> </div> <div className="row centered"> <button type="submit" className="btn btn-primary"> Add </button> </div> </form> <div className="margin-u-40"> <InputBox id="ng" value={this.state.ng} onChange={this.onChange} end={"/"} /> <InputBox id="φ" value={this.state.φ} onChange={this.onChange} end={"%"} /> </div> <div className="row"> <PointsTable data={this.state.points} onClick={this.deleteClick} /> </div> </div> <div className="col-70 padding-h-20"> <ScatterChart name={["custom channel"]} data={[this.state.points]} pointBorder={'y'} /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> ) } } // PointsTable component is used for displaying x,y points that define // custom river channel class PointsTable extends React.Component { render() { let TableRows = this.props.data.map((point, index) => { return ( <TableRow passIndex={index} x={point.x} y={point.y} key={index} onClick={this.props.onClick} /> ) }); return ( <table className="zebra"> <thead> <tr> <th> </th> <th className="padding-h-20"> x </th> <th className="padding-h-20"> y </th> </tr> </thead> <tbody> {TableRows} </tbody> </table> ) } } // TableRow is used to display one table row with x,y point coordinates // and x button that is used to delete the row. class TableRow extends React.Component { render() { return ( <tr> <td className="td-delete" onClick={this.props.onClick} x={this.props.x} y={this.props.y} id={this.props.passIndex}> × </td> <td className="padding-h-20"> {this.props.x} </td> <td className="padding-h-20"> {this.props.y} </td> </tr> ) } } export { RectangularChannel, TrapezoidChannel, CustomChannel };
public/js/components/user.js
AC287/wdi_final_arrowlense2.0_FE
import React from 'react' import {Link} from 'react-router' import Firebase from 'firebase' import InstructorView from './user_instructor' import StudentView from './user_student' const userRef = new Firebase('https://arrowlense2-0.firebaseio.com/'); const getUserInfo = new Firebase('https://arrowlense2-0.firebaseio.com/users'); export default React.createClass({ contextTypes: { user: React.PropTypes.string, userid: React.PropTypes.string, userinfo: React.PropTypes.object, router: React.PropTypes.object.isRequired, }, render: function() { // let { userRole } = this.props.params // console.log(this.context.userinfo); switch (this.context.userinfo.role) { case 'instructor': return ( <InstructorView/> ) break; case 'student': return( <StudentView/> ) break; default: return( <h3>Please log in to access this page.</h3> ) } } })
src/lib/ResizeGhost.js
maheshsenni/react-treelist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import '../css/resize-ghost.css'; class ResizeGhost extends Component { constructor(props) { super(props); this.displayName = 'ResizeGhost'; this.onMouseLeave = this.onMouseLeave.bind(this); this.onDragStart = this.onDragStart.bind(this); this.onDragEnd = this.onDragEnd.bind(this); this.documentDragoverHandler = this.documentDragoverHandler.bind(this); this.state = { resizing: false, dragX: 0 }; } onMouseLeave() { this.props.onLeave(); } onDragStart(event) { // setting 'event.dataTransfer' for firefox :( event.dataTransfer.setData('text', ''); this._initialX = event.clientX; this.props.onDragStart(event.clientX); } onDragEnd() { this.props.onDragEnd(); } documentDragoverHandler(event) { const movedX = event.clientX - this._initialX; this.props.onDrag(movedX); } componentDidMount() { document.addEventListener('dragover', this.documentDragoverHandler, false); } componentWillUnmount() { document.removeEventListener('dragover', this.documentDragoverHandler, false); } render() { return ( <div draggable='true' className='resize-handle' style={{...this.props}} onMouseLeave={this.onMouseLeave} onDragStart={this.onDragStart} onDragEnd={this.onDragEnd}></div> ); } } ResizeGhost.propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, top: PropTypes.number.isRequired, left: PropTypes.number.isRequired, onLeave: PropTypes.func.isRequired, onDragStart: PropTypes.func.isRequired, onDrag: PropTypes.func.isRequired, onDragEnd: PropTypes.func.isRequired }; export default ResizeGhost;
src/tests/Holdable.react.spec.js
phil303/react-touch
import { expect } from 'chai'; import sinon from 'sinon'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import { documentEvent, renderComponent } from './helpers'; import Holdable from '../Holdable.react'; import defineHold from '../defineHold'; /* eslint-disable no-unused-expressions */ let clock; const renderHoldable = renderComponent(Holdable); describe("Holdable", () => { beforeEach(() => { clock = sinon.useFakeTimers(); }); afterEach(() => { clock.restore(); }); it("should pass updates to callback child as 'holdProgress'", () => { const progressUpdates = []; const holdable = TestUtils.renderIntoDocument( <Holdable> {({ holdProgress }) => { progressUpdates.push(holdProgress); return <div></div>; }} </Holdable> ); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(progressUpdates).to.be.lengthOf(3); clock.tick(250); expect(progressUpdates[3]).to.be.above(progressUpdates[2]); }); it("should fire a callback 'onHoldProgress' when progress is made", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(1000); expect(spy.callCount).to.be.equal(4); }); it("should fire a callback 'onHoldComplete' after hold is completed", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(1500); expect(spy.calledOnce).to.be.true; }); it("should stop firing 'onHoldProgress' when touch is moved", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(spy.calledOnce).to.be.true; documentEvent('touchmove'); clock.tick(250); expect(spy.calledOnce).to.be.true; }); it("should not fire 'onHoldComplete' when touch is moved", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchmove'); expect(spy.notCalled).to.be.true; clock.tick(1000); expect(spy.notCalled).to.be.true; }); it("should stop firing 'onHoldProgress' when touch is released", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchend'); clock.tick(250); expect(spy.calledOnce).to.be.true; }); it("should not fire 'onHoldComplete' when touch is released", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchend'); clock.tick(1000); expect(spy.notCalled).to.be.true; }); it("should reset the state when touch is ended", () => { const holdable = renderHoldable(); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); documentEvent('touchend'); expect(holdable.state).to.eql({initial: null, current: null, duration: 0}); }); it("should alter its progress updates when 'updateEvery' is used", () => { const spy = sinon.spy(); const config = defineHold({updateEvery: 50}); const holdable = renderHoldable({ onHoldProgress: spy, config }); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); expect(spy.notCalled).to.be.true; clock.tick(50); expect(spy.calledOnce).to.be.true; clock.tick(50); expect(spy.calledTwice).to.be.true; clock.tick(50); expect(spy.calledThrice).to.be.true; }); it("should alter its hold length when 'holdFor' is used", () => { const spy = sinon.spy(); const config = defineHold({holdFor: 500}); const holdable = renderHoldable({ onHoldComplete: spy, config }); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(spy.notCalled).to.be.true; clock.tick(500); expect(spy.calledOnce).to.be.true; clock.tick(500); expect(spy.calledOnce).to.be.true; }); it("should render its child as its only output", () => { const renderer = TestUtils.createRenderer(); renderer.render(<Holdable><div></div></Holdable>); const output = renderer.getRenderOutput(); expect(output.type).to.be.equal('div'); }); it("should pass the correct props to its child", () => { const renderer = TestUtils.createRenderer(); renderer.render(<Holdable><div></div></Holdable>); const output = renderer.getRenderOutput(); expect(output.props).to.have.keys(['__passThrough', 'onMouseDown', 'onTouchStart']); }); it("should remove timers and listeners when the component unmounts", () => { const container = document.createElement('div'); const spy = sinon.spy(); const holdable = ReactDOM.render( <Holdable onHoldProgress={spy}> <div></div> </Holdable>, container ); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); ReactDOM.unmountComponentAtNode(container); clock.tick(250); expect(spy.notCalled).to.be.true; }); });
client/admin/info/RocketChatSection.stories.js
iiet/iiet-chat
import React from 'react'; import { dummyDate } from '../../../.storybook/helpers'; import { RocketChatSection } from './RocketChatSection'; export default { title: 'admin/info/RocketChatSection', component: RocketChatSection, decorators: [ (fn) => <div className='rc-old'>{fn()}</div>, ], }; const info = { marketplaceApiVersion: 'info.marketplaceApiVersion', }; const statistics = { version: 'statistics.version', migration: { version: 'statistics.migration.version', lockedAt: dummyDate, }, installedAt: dummyDate, process: { uptime: 10 * 24 * 60 * 60, pid: 'statistics.process.pid', }, uniqueId: 'statistics.uniqueId', instanceCount: 1, oplogEnabled: true, }; export const _default = () => <RocketChatSection info={info} statistics={statistics} />; export const loading = () => <RocketChatSection info={{}} statistics={{}} isLoading />;
packages/material-ui-icons/src/AccountBox.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z" /></g> , 'AccountBox');
react/features/invite/components/PasswordContainer.js
KalinduDN/kalindudn.github.io
import React, { Component } from 'react'; import { translate } from '../../base/i18n'; import { LOCKED_LOCALLY } from '../../room-lock'; import AddPasswordForm from './AddPasswordForm'; import LockStatePanel from './LockStatePanel'; import RemovePasswordForm from './RemovePasswordForm'; /** * React {@code Component} for displaying the current room lock state as well as * exposing features to modify the room lock. */ class PasswordContainer extends Component { /** * {@code PasswordContainer}'s property types. * * @static */ static propTypes = { /** * The JitsiConference for which to display a lock state and change the * password. * * @type {JitsiConference} */ conference: React.PropTypes.object, /** * The value for how the conference is locked (or undefined if not * locked) as defined by room-lock constants. */ locked: React.PropTypes.string, /** * The current known password for the JitsiConference. */ password: React.PropTypes.string, /** * Whether or not the password editing components should be displayed. */ showPasswordEdit: React.PropTypes.bool, /** * Invoked to obtain translated strings. */ t: React.PropTypes.func }; /** * Initializes a new {@code PasswordContainer} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); this.state = { /** * Whether or not the form to edit the password should display. If * true, the form should display. * * @type {boolean} */ isEditingPassword: false }; // Bind event handlers so they are only bound once for every instance. this._onTogglePasswordEdit = this._onTogglePasswordEdit.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <div className = 'password-overview'> <div className = 'password-overview-status'> <LockStatePanel locked = { Boolean(this.props.locked) } /> { this._renderShowPasswordLink() } </div> { this._renderPasswordEdit() } </div> ); } /** * Toggles the display of the ReactElements used to edit the password. * * @private * @returns {void} */ _onTogglePasswordEdit() { this.setState({ isEditingPassword: !this.state.isEditingPassword }); } /** * Creates a ReactElement used for setting or removing a password. * * @private * @returns {ReactElement|null} */ _renderPasswordEdit() { if (!this.state.isEditingPassword) { return null; } return ( this.props.locked ? <RemovePasswordForm conference = { this.props.conference } lockedLocally = { this.props.locked === LOCKED_LOCALLY } password = { this.props.password } /> : <AddPasswordForm conference = { this.props.conference } /> ); } /** * Creates a ReactElement that toggles displaying password edit components. * * @private * @returns {ReactElement|null} */ _renderShowPasswordLink() { if (!this.props.showPasswordEdit) { return null; } let toggleStatusKey; if (this.state.isEditingPassword) { toggleStatusKey = 'invite.hidePassword'; } else if (this.props.locked) { toggleStatusKey = 'invite.showPassword'; } else { toggleStatusKey = 'invite.addPassword'; } return ( <a className = 'password-overview-toggle-edit' onClick = { this._onTogglePasswordEdit }> { this.props.t(toggleStatusKey) } </a> ); } } export default translate(PasswordContainer);
src/layouts/layout-5-2.js
binary-com/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} {components[1]} {components[2]} {components[3]} </div> <div className="vertical"> {components[4]} </div> </div> );
app/component/app.js
caoqianjie/react-webpack-demo1
import $ from 'jquery'; import NewsList from './NewsList' import React from 'react'; import { render } from 'react-dom'; import '../src/css/app.css'; function get(url) { return Promise.resolve($.get(url)); } get('https://hacker-news.firebaseio.com/v0/topstories.json') .then(function (stories) { return Promise.all(stories.slice(0,30).map(itemId => get('https://hacker-news.firebaseio.com/v0/item/'+itemId+'.json'))); }) .then(function (items) { render(<NewsList items={items}/>,$('#app')[0]); }) .catch(function (err) { console.log('err occur', err); });
app/containers/PrototypeSearch/header.js
mhoffman/CatAppBrowser
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import ReactGA from 'react-ga'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import { withStyles } from 'material-ui/styles'; import { styles } from './styles'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <Grid container direction="row" justify="space-between"> <Grid item> <h1>Prototype Search</h1> </Grid> <Grid item> <Link to={'/catKitDemo'} className={this.props.classes.outboundLink} > <Button raised className={this.props.classes.publicationAction} > CatKit Slab Generator </Button> </Link> </Grid> <Grid> <div className={this.props.classes.infoText} >Powered by <ReactGA.OutboundLink eventLabel="https://gitlab.com/ankitjainmeiitk/Enumerator" to="https://gitlab.com/ankitjainmeiitk/Enumerator" target="_blank" > gitlab/ankitjainmeiitk/Enumerator </ReactGA.OutboundLink> </div> </Grid> </Grid> ); } } Header.propTypes = { classes: PropTypes.object, }; export default withStyles(styles, { withTheme: true })(Header);
app/javascript/mastodon/features/ui/components/compose_panel.js
tateisu/mastodon
import React from 'react'; import SearchContainer from 'mastodon/features/compose/containers/search_container'; import ComposeFormContainer from 'mastodon/features/compose/containers/compose_form_container'; import NavigationContainer from 'mastodon/features/compose/containers/navigation_container'; import LinkFooter from './link_footer'; const ComposePanel = () => ( <div className='compose-panel'> <SearchContainer openInRoute /> <NavigationContainer /> <ComposeFormContainer singleColumn /> <LinkFooter withHotkeys /> </div> ); export default ComposePanel;
imports/ui/admin/components/.stories/contact.js
dououFullstack/atomic
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { setComposerStub } from 'react-komposer'; import Contact from '../contact.jsx'; storiesOf('admin.Contact', module) .add('default view', () => { return ( <Contact /> ); })
src/cardPage.js
henyouqian/sale
import React, { Component } from 'react'; import { render } from 'react-dom'; import { SideMenu } from './sideMenu'; import FastClick from "fastclick"; import * as lwUtil from "./lwUtil" import $ from "jquery" import "velocity-animate" import { Dlg, DlgAlert } from"./dlg" // require("./cardPage.css"); let _rootEl = document.getElementById("root"); FastClick.attach(_rootEl); let _state = { card:{}, editable:lwUtil.getUrlParam("editable")?true:false } class CardPage extends Component { componentDidMount(){ var msg = { UserId:-1, } if (!_state.editable) { msg.UserId = parseInt(lwUtil.getUrlParam("userId")) if (!msg.UserId) { alert("need userId param") return } } lwUtil.post("catalog/getCard", msg).then(resp=>{ console.log(resp) if (resp.Card){ _state.card = JSON.parse(resp.Card) Object.keys(_state.card).forEach(k=>{ let ref = this.refs[k] if (ref) { ref.setState({"value": _state.card[k]}) } }) } }, err=>{ console.error(err) }) } render() { const card = _state.card let inputUIs = [ {key:"Company", label:"企业", icon:"building-o", placeholder:"必填"}, {key:"ContactPerson", label:"联系人", icon:"user", placeholder:"必填"}, {key:"Phone", label:"电话", icon:"phone", placeholder:"必填"}, {key:"Email", label:"邮箱", icon:"envelope-o"}, {key:"Weixin", label:"微信", icon:"wechat"} ] const editable = _state.editable let inputEls = inputUIs.map(v=>{ return <Input key={v.key} label={v.label} icon={v.icon} ref={v.key} placeholder={v.placeholder} editable={editable}/> }) const title = editable?"编辑我的联系方式":"供货商联系方式" const btn = editable?<button className="uk-button uk-button-large .uk-width-1-1" onClick={()=>this._onSave()}><i className="uk-icon-save"></i> 保存</button>:"" return ( <div className="uk-container uk-container-center"> <div className="uk-width-1-1" style={{maxWidth:"720px", margin:"15px auto"}}> <div className="uk-panel uk-panel-box widget_text"> <div className="uk-panel-badge uk-badge tm-badge-primary" data-uk-offcanvas="{target:'#offcanvas'}" style={{left:0, right:"auto"}}> <a href="#offcanvas" data-uk-offcanvas className="uk-icon-navicon" style={{color:"white"}}></a> </div> <SideMenu /> <div className="uk-panel-teaser"> <img src="/home_venice.jpg" width="722" height="407" alt=""/> </div> <h2>{title}</h2> <div> <form className="uk-form uk-form-stacked"> {inputEls} </form> </div> </div> {btn} </div> <div style={{height:"40px"}}></div> <DlgAlert ref="dlg" title="保存成功" msg=""></DlgAlert> </div> ); } _onSave() { let d = React.createElement(Dlg) console.log(d) // this.refs.dlg.show() // this.forceUpdate() const props = ["Company", "ContactPerson", "Phone", "Email", "Weixin"] const requiredProps = ["Company", "ContactPerson", "Phone"] let ok = true const card = props.reduce((r,k)=>{ let v = r[k] = this.refs[k].state.value; if (v.length == 0 && requiredProps.indexOf(k)>=0) { this.refs[k].setState({err: true}) ok = false } else { this.refs[k].setState({err: false}) } return r }, {}) if (ok){ this.props.onSave(card) lwUtil.post("catalog/editCard", card).then(resp=>{ console.log(resp) _state.card = card this.refs.dlg.show() }, err=>{ console.error(err) }) } } } class Input extends Component { constructor(props) { super(props) this.state = {err: false, value:""} } render() { let type = this.props.type?this.props.type:"text" let style = this.state.err?{border:"1px solid red"}:{} let placeholder = this.props.placeholder || "" let value = this.state.value let input = this.props.editable? <input className="uk-width-1-1 uk-form-large" type={type} style={style} placeholder={placeholder} ref="input" value={value} onChange={e=>{this.onChange(e)}}/> :<input disabled className="uk-width-1-1 uk-form-large" type={type} style={style} placeholder={placeholder} ref="input" value={value} onChange={e=>{this.onChange(e)}}/> return ( <div className="uk-form-row"> <label className="uk-form-label">{this.props.label}</label> <div className="uk-form-controls"> <div className="uk-form-icon uk-width-1-1"> <i className={"uk-icon-"+this.props.icon}></i> {input} </div> </div> </div> ) } onChange(e){ if (this.props.editable) { this.setState({value: e.target.value}) } } // render() { // var value = this.state.value; // return <input type="text" value={value} onChange={event=>{this.setState({value: event.target.value})}} />; // } } render(<div><CardPage onSave={(info) => console.log("onSave", info)}/></div>, document.getElementById('root')); let loadState = lwUtil.hisOnload() console.log(loadState)
docs/app/Examples/elements/Label/Types/LabelExampleFloating.js
mohammed88/Semantic-UI-React
import React from 'react' import { Icon, Label, Menu } from 'semantic-ui-react' const LabelExampleFloating = () => ( <Menu compact> <Menu.Item as='a'> <Icon name='mail' /> Messages <Label color='red' floating>22</Label> </Menu.Item> <Menu.Item as='a'> <Icon name='users' /> Friends <Label color='teal' floating>22</Label> </Menu.Item> </Menu> ) export default LabelExampleFloating
src/views/components/SettingValue.js
physiii/home-gateway
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; export const SettingValue = (props) => { let formatted; switch (props.type) { case 'percentage': formatted = Math.round(props.children * 100) + '%'; break; case 'time-of-day': formatted = moment.utc(props.children).format('h:mm A'); break; default: formatted = props.children; break; } return <React.Fragment>{formatted}</React.Fragment>; }; SettingValue.propTypes = { type: PropTypes.string, children: PropTypes.any }; export default SettingValue;
js/jqwidgets/demos/react/app/dockinglayout/righttoleftlayout/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDockingLayout from '../../../jqwidgets-react/react_jqxdockinglayout.js'; import JqxTree from '../../../jqwidgets-react/react_jqxtree.js'; class App extends React.Component { render() { let layout = [{ type: 'layoutGroup', orientation: 'horizontal', items: [{ type: 'autoHideGroup', alignment: 'left', width: 80, unpinnedWidth: 200, items: [{ type: 'layoutPanel', title: 'Toolbox', contentContainer: 'ToolboxPanel' }, { type: 'layoutPanel', title: 'Help', contentContainer: 'HelpPanel' }] }, { type: 'layoutGroup', orientation: 'vertical', width: 500, items: [{ type: 'documentGroup', height: 400, minHeight: 200, items: [{ type: 'documentPanel', title: 'Document 1', contentContainer: 'Document1Panel' }, { type: 'documentPanel', title: 'Document 2', contentContainer: 'Document2Panel' }] }, { type: 'tabbedGroup', height: 200, pinnedHeight: 30, items: [{ type: 'layoutPanel', title: 'Error List', contentContainer: 'ErrorListPanel' }] }] }, { type: 'tabbedGroup', width: 220, minWidth: 200, items: [{ type: 'layoutPanel', title: 'Solution Explorer', contentContainer: 'SolutionExplorerPanel', initContent: () => { // initialize a jqxTree inside the Solution Explorer Panel let source = [{ icon: '../../../images/earth.png', label: 'Project', expanded: true, items: [{ icon: '../../../images/folder.png', label: 'css', expanded: true, items: [{ icon: '../../../images/nav1.png', label: 'jqx.base.css' }, { icon: '../../../images/nav1.png', label: 'jqx.energyblue.css' }, { icon: '../../../images/nav1.png', label: 'jqx.orange.css' }] }, { icon: '../../../images/folder.png', label: 'scripts', items: [{ icon: '../../../images/nav1.png', label: 'jqxcore.js' }, { icon: '../../../images/nav1.png', label: 'jqxdata.js' }, { icon: '../../../images/nav1.png', label: 'jqxgrid.js' }] }, { icon: '../../../images/nav1.png', label: 'index.htm' }] }]; ReactDOM.render( <JqxTree style={{ border: 'none' }} width={190} source={source} rtl={true} /> , document.getElementById('solutionExplorerTree')); } }, { type: 'layoutPanel', title: 'Properties', contentContainer: 'PropertiesPanel' }] }] }, { type: 'floatGroup', width: 500, height: 300, position: { x: 350, y: 250 }, items: [{ type: 'layoutPanel', title: 'Output', contentContainer: 'OutputPanel', selected: true }] }]; return ( <JqxDockingLayout width={800} height={600} layout={layout} rtl={true}> <div data-container="ToolboxPanel"> List of tools </div> <div data-container="HelpPanel"> Help topics </div> <div data-container="Document1Panel"> Document 1 content </div> <div data-container="Document2Panel"> Document 2 content </div> <div data-container="ErrorListPanel"> List of errors </div> <div data-container="SolutionExplorerPanel"> <div id="solutionExplorerTree" /> </div> <div data-container="PropertiesPanel"> List of properties </div> <div data-container="OutputPanel"> <div style={{ fontFamily: 'Consolas' }}> <p> Themes installation complete. </p> <p> List of installed stylesheet files. Include at least one stylesheet Theme file and the images folder: </p> <ul> <li>styles/jqx.base.css: Stylesheet for the base Theme. The jqx.base.css file should be always included in your project.</li> <li>styles/jqx.arctic.css: Stylesheet for the Arctic Theme</li> <li>styles/jqx.web.css: Stylesheet for the Web Theme</li> <li>styles/jqx.bootstrap.css: Stylesheet for the Bootstrap Theme</li> <li>styles/jqx.classic.css: Stylesheet for the Classic Theme</li> <li>styles/jqx.darkblue.css: Stylesheet for the DarkBlue Theme</li> <li>styles/jqx.energyblue.css: Stylesheet for the EnergyBlue Theme</li> <li>styles/jqx.shinyblack.css: Stylesheet for the ShinyBlack Theme</li> <li>styles/jqx.office.css: Stylesheet for the Office Theme</li> <li>styles/jqx.metro.css: Stylesheet for the Metro Theme</li> <li>styles/jqx.metrodark.css: Stylesheet for the Metro Dark Theme</li> <li>styles/jqx.orange.css: Stylesheet for the Orange Theme</li> <li>styles/jqx.summer.css: Stylesheet for the Summer Theme</li> <li>styles/jqx.black.css: Stylesheet for the Black Theme</li> <li>styles/jqx.fresh.css: Stylesheet for the Fresh Theme</li> <li>styles/jqx.highcontrast.css: Stylesheet for the HighContrast Theme</li> <li>styles/jqx.blackberry.css: Stylesheet for the Blackberry Theme</li> <li>styles/jqx.android.css: Stylesheet for the Android Theme</li> <li>styles/jqx.mobile.css: Stylesheet for the Mobile Theme</li> <li>styles/jqx.windowsphone.css: Stylesheet for the Windows Phone Theme</li> <li>styles/jqx.ui-darkness.css: Stylesheet for the UI Darkness Theme</li> <li>styles/jqx.ui-lightness.css: Stylesheet for the UI Lightness Theme</li> <li>styles/jqx.ui-le-frog.css: Stylesheet for the UI Le Frog Theme</li> <li>styles/jqx.ui-overcast.css: Stylesheet for the UI Overcast Theme</li> <li>styles/jqx.ui-redmond.css: Stylesheet for the UI Redmond Theme</li> <li>styles/jqx.ui-smoothness.css: Stylesheet for the UI Smoothness Theme</li> <li>styles/jqx.ui-start.css: Stylesheet for the UI Start Theme</li> <li>styles/jqx.ui-sunny.css: Stylesheet for the UI Sunny Theme</li> <li>styles/images: contains images referenced in the stylesheet files</li> </ul> </div> </div> </JqxDockingLayout> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/index.js
w01fgang/react-static-boilerplate
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React from 'react'; export default class { render() { return ( <div> <h1>Home Page</h1> <p>Coming soon.</p> </div> ); } };
examples/official-storybook/components/DocgenButton.js
storybooks/react-storybook
import React from 'react'; import PropTypes from 'prop-types'; /** * DocgenButton component description imported from comments inside the component file, * * *Important Note*: Unlike with normal `<input>` elements, setting this will * not validate the input contents. This is because in this project we use * Formik and Yup to validate fields at the form-level, not at the individual * input level. It is still very important to set this value properly for * accessibility and user experience. * * Here's a list to test out formatting. * * * `"number"` Any number not represented by a more specific type. * * `"password"` A password. * * `"email"` An email address. * * `"tel"` A phone or fax number. Shows the phone number keypad on * mobile keyboards. */ export const DocgenButton = ({ disabled, label, onClick }) => ( <button type="button" disabled={disabled} onClick={onClick}> {label} </button> ); DocgenButton.defaultProps = { disabled: false, onClick: () => {}, optionalString: 'Default String', one: { key: 1 }, two: { thing: { id: 2, func: () => {}, arr: [], }, }, obj: { key: 'value', }, shape: { id: 3, func: () => {}, arr: [], shape: { shape: { foo: 'bar', }, }, }, arrayOf: [1, 2, 3], msg: new Set(), enm: 'News', enmEval: 'Photos', union: 'hello', }; /* eslint-disable react/no-unused-prop-types */ DocgenButton.propTypes = { /** Boolean indicating whether the button should render as disabled */ disabled: PropTypes.bool, /** button label. */ label: PropTypes.string.isRequired, /** onClick handler */ onClick: PropTypes.func, /** * A simple `objectOf` propType. */ one: PropTypes.objectOf(PropTypes.number), /** * A very complex `objectOf` propType. */ two: PropTypes.objectOf( PropTypes.shape({ /** * Just an internal propType for a shape. * It's also required, and as you can see it supports multi-line comments! */ id: PropTypes.number.isRequired, /** * A simple non-required function */ func: PropTypes.func, /** * An `arrayOf` shape */ arr: PropTypes.arrayOf( PropTypes.shape({ /** * 5-level deep propType definition and still works. */ index: PropTypes.number.isRequired, }) ), }) ), /** * Plain object propType (use shape!!) */ obj: PropTypes.object, // eslint-disable-line react/forbid-prop-types /** * propType for shape with nested arrayOf * * Also, multi-line description */ shape: PropTypes.shape({ /** * Just an internal propType for a shape. * It's also required, and as you can see it supports multi-line comments! */ id: PropTypes.number.isRequired, /** * A simple non-required function */ func: PropTypes.func, /** * An `arrayOf` shape */ arr: PropTypes.arrayOf( PropTypes.shape({ /** * 5-level deep propType definition and still works. */ index: PropTypes.number.isRequired, }) ), shape: PropTypes.shape({ shape: PropTypes.shape({ foo: PropTypes.string, }), }), }), /** * array of a certain type */ arrayOf: PropTypes.arrayOf(PropTypes.number), /** * `instanceOf` is also supported and the custom type will be shown instead of `instanceOf` */ msg: PropTypes.instanceOf(Set), /** * `oneOf` is basically an Enum which is also supported but can be pretty big. * * Testing a list: * * - `News` first * - `Photos` second */ enm: PropTypes.oneOf(['News', 'Photos']), enmEval: PropTypes.oneOf((() => ['News', 'Photos'])()), /** * A multi-type prop is also valid and is displayed as `Union<String|Message>` */ union: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Set)]), /** * test string with a comment that has * two identical lines * two identical lines */ optionalString: PropTypes.string, };
app/javascript/mastodon/features/ui/components/columns_area.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import HomeTimeline from '../../home_timeline'; import Notifications from '../../notifications'; import PublicTimeline from '../../public_timeline'; import CommunityTimeline from '../../community_timeline'; import HashtagTimeline from '../../hashtag_timeline'; import Compose from '../../compose'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, }; class ColumnsArea extends ImmutablePureComponent { static propTypes = { columns: ImmutablePropTypes.list.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; render () { const { columns, children, singleColumn } = this.props; if (singleColumn) { return ( <div className='columns-area'> {children} </div> ); } return ( <div className='columns-area'> {columns.map(column => { const SpecificComponent = componentMap[column.get('id')]; const params = column.get('params', null) === null ? null : column.get('params').toJS(); return <SpecificComponent key={column.get('uuid')} columnId={column.get('uuid')} params={params} multiColumn />; })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } } export default ColumnsArea;
src/components/Blog/Blog/Blog.spec.js
easingthemes/notamagic
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Blog from 'components/Blog'; function shallowRender (component) { const renderer = TestUtils.createRenderer(); renderer.render(component); return renderer.getRenderOutput(); } function shallowRenderWithProps (props = {}) { return shallowRender(<Blog {...props} />); } describe('(Component) Blog', () => { let _component; let _props; beforeEach(function () { // _props = { // location: { // pathname: '/' // } // }; _props = {}; _component = shallowRenderWithProps(_props); }); it('should have loaded.', () => { expect(Blog).to.exist; }); it('should render without problems', () => { expect(_component).to.exist; }); it('should render as a <div>.', () => { expect(_component.type).to.equal('div'); }); });
tests/Rules-isUrl-spec.js
bitgaming/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isUrl" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with "foo"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with "https://www.google.com/"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="https://www.google.com/"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); } };
src/frontend/src/components/GMDataList.js
blengerich/GenAMap
import React from 'react' import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table' import fetch from './fetch' import config from '../../config' const GMDataTable = React.createClass({ render: function () { const data = this.props.data.map((row, i) => { return ( <TableRow key={i} selectable={false}> { row.split(',').map((entry, j) => <TableRowColumn key={j}>{entry}</TableRowColumn> ) } </TableRow> ) }) const headers = this.props.headers.map((columnName, i) => <TableHeaderColumn key={i}>{columnName}</TableHeaderColumn> ) return ( <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> {headers} </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {data} </TableBody> </Table> ) } }) const GMDataList = React.createClass({ getInitialState: function () { return {data: [], headers: [], title: ''} }, componentDidMount: function () { this.loadData(this.props.params.id) }, loadData: function (id) { let dataRequest = { method: 'GET', headers: { 'Content-Type': 'application/json' } } fetch(`${config.api.dataUrl}/${id}`, dataRequest) .then(response => response.json().then(json => ({ json, response }))) .then(({ json, response }) => { if (!response.ok) { this.setState({ title: json.message, data: undefined }) Promise.reject(json.message) } else { const data = json.data.split('\n') const headers = data[0].split(',') data.splice(0, 1) this.setState({ title: json.file.name, data, headers }) } }).catch(err => console.log('Error: ', err)) }, componentWillReceiveProps: function (nextProps) { this.loadData(nextProps.params.id) }, render: function () { return this.state.data ? ( <div> <h1>{this.state.title}</h1> <GMDataTable data={this.state.data} headers={this.state.headers} /> </div> ) : ( <div> <h1>{this.state.title}</h1> </div> ) } }) export default GMDataList
client/src/components/Profile/Inbox/Inbox.js
wolnewitz/raptor-ads
import React, { Component } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { Container, Header, Loader } from 'semantic-ui-react'; import { getAllReceivedMessages } from '../../../actions/inboxActions'; import MessagesTable from './MessagesTable'; import { changeContactField, sendMessage } from '../../../actions/fullListingActions'; import { clearErrors } from '../../../actions/listingActions'; class Inbox extends Component { constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.convertTime = this.convertTime.bind(this); } componentDidMount() { this.props.dispatch(getAllReceivedMessages(this.props.userId)); } onSubmit(e, listingId, userId, senderId) { e.preventDefault(); const data = this.props.contactForm; const postId = listingId; const payload = { title: data.title, body: data.body, postId, userId, senderId }; this.props.dispatch(clearErrors()); this.props.dispatch(sendMessage(payload)); } onChange(e, data) { if (data) { this.props.dispatch(changeContactField('type', data.value)); } else { this.props.dispatch(changeContactField(e.target.name, e.target.value)); } } convertTime(time) { return moment(time).fromNow(); } render() { const { isFetching, allMessages } = this.props; if (isFetching) { return <Loader active inline="centered" />; } return ( <Container textAlign="center"> <Header as="h1" className="center">-- Inbox -- <br /></Header> <Container textAlign="left"> <MessagesTable allMessages={allMessages} convertTime={this.convertTime} onChange={this.onChange} onSubmit={this.onSubmit} /> </Container> </Container> ); } } const mapStateToProps = (state) => { const { contactForm } = state.messages; const { isFetching, allMessages } = state.inbox; const { id } = state.auth.loggedInUser; return { allMessages, isFetching, contactForm, }; }; Inbox.propTypes = { userId: React.PropTypes.number.isRequired, isFetching: React.PropTypes.bool.isRequired, contactForm: React.PropTypes.object.isRequired, allMessages: React.PropTypes.array.isRequired, dispatch: React.PropTypes.func.isRequired, }; export default connect(mapStateToProps)(Inbox);
client/pages/examples/advanced/winds/index.js
fdesjardins/webgl
import React from 'react' import PT from 'prop-types' import * as THREE from 'three' import Promise from 'bluebird' import droidSans from '-/assets/fonts/helvetiker_bold.typeface.json' import Example from '-/components/example' import notes from './readme.md' import stationsData from './stations.json' import threeOrbitControls from 'three-orbit-controls' const globals = { stations: [], particles: { vertices: [], }, fontLoader: new THREE.FontLoader(), font: null, colors: { stations: 0x4466ff, stationLabels: 0xffffff, }, } /** * Create a station mesh object */ const createStation = (station) => { const stationGeom = new THREE.IcosahedronBufferGeometry(0.35, 0) const stationMat = new THREE.MeshPhongMaterial({ color: globals.colors.stations, }) const polyhedron = new THREE.Mesh(stationGeom, stationMat) const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30) polyhedron.position.set(...pos) return polyhedron } /** * Create a station mesh label */ const createStationLabel = (station) => { const textMat = new THREE.MeshPhongMaterial({ color: globals.colors.stationLabels, }) const defaultTextBufferGeomOpts = { size: 0.25, height: 0.25, curveSegments: 3, bevelEnabled: false, } const textGeom = new THREE.TextBufferGeometry( station.stationName, Object.assign({}, defaultTextBufferGeomOpts, { font: globals.font, }) ) const text = new THREE.Mesh(textGeom, textMat) const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30) text.position.set(...pos) return text } /** * Load the stations data into the given scene */ const loadStations = async (scene) => { const font = globals.fontLoader.parse(droidSans) globals.font = font const loadStations = stationsData.stations.map((s) => async () => { const station = createStation(s) const label = createStationLabel(s) scene.add(station) scene.add(label) globals.stations.push(station) }) Promise.map(loadStations, (x) => Promise.resolve(x()).delay(100), { concurrency: 25, }) } const loadParticles = async (scene) => { const particleCount = 1800 const particleGeom = new THREE.Geometry() const particleMat = new THREE.PointsMaterial({ color: 0xffffff, size: 0.5, }) Array.from(new Array(particleCount).keys()).forEach(() => { const x = Math.random() * 150 - 75 const y = Math.random() * 100 - 50 const particle = new THREE.Vector3(x, y, 0) particleGeom.vertices.push(particle) }) globals.particles = particleGeom const particles = new THREE.Points(particleGeom, particleMat) scene.add(particles) } /** * didMount() */ const init = ({ canvas }) => { console.log(canvas) // Create the scene and renderer const scene = new THREE.Scene() const renderer = new THREE.WebGLRenderer({ canvas }) renderer.setSize(canvas.clientWidth, canvas.clientHeight) // Add the camera const camera = new THREE.PerspectiveCamera( 75, canvas.clientWidth / canvas.clientHeight, 1, 100000 ) camera.position.z = 50 const OrbitControls = threeOrbitControls(THREE) const controls = new OrbitControls(camera) controls.update() // Add the main light source const light = new THREE.PointLight(0xffffff, 2, 200) light.position.set(0, 40, 40) scene.add(light) let frame = 0 const animate = () => { requestAnimationFrame(animate) globals.stations.forEach((p, i) => { p.rotation.x += 0.01 }) controls.update() globals.particles.vertices.forEach((p, i) => { const newPos = updateParticlePosition(p, frame) p.x = newPos.x p.y = newPos.y }) globals.particles.verticesNeedUpdate = true renderer.render(scene, camera) frame += 0.1 } animate() loadStations(scene) loadParticles(scene) return () => { scene.dispose() renderer.dispose() } } const updateParticlePosition = (pos, frame) => { const [x, y, z] = [ pos.x + (Math.random() - 0.5) * 0.2, pos.y + (Math.random() - 0.5) * 0.2, pos.z, ] return new THREE.Vector3(x, y, z) } /** * Calculate a 3D position from a lat,lng pair and radius. */ // const calc3dPosFromLatLonRad = (lat, lon, radius) => { // const phi = (90 - lat) * (Math.PI / 180) // const theta = (lon + 180) * (Math.PI / 180) // // const x = -(radius * Math.sin(phi) * Math.cos(theta)) // const z = radius * Math.sin(phi) * Math.sin(theta) // const y = radius * Math.cos(phi) // // return [x, y, z] // } /** * Calculate a 3D position from a lat,lng pair and radius */ const calcPosFromLatLonRad = (lat, lon, radius) => { const shift = Math.PI * radius const x = (lon * shift) / 180 let y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180) y = (y * shift) / 180 return [x, y, 0] } const Winds = ({ color, id }) => { const canvas = React.useRef(null) console.log('effect') React.useEffect(() => { return init({ canvas: canvas.current }) }) return <canvas ref={canvas} /> } Winds.propTypes = { color: PT.string, id: PT.string, } const E = () => ( <div id="container"> <Example notes={notes} components={{ Winds }} init={() => () => {}} /> </div> ) export default E
src/js/Components/Common/BackgroundContent.js
mattgordils/DropSplash
import React, { Component } from 'react'; import 'sass/components/common/backgrounds'; export default class App extends Component { render () { var backgroundStyle = { backgroundImage: 'url(' + this.props.backgroundImage + ')' } var overlayStyle = { backgroundColor: this.props.overlayColor, opacity: this.props.overlayOpacity } var overlay = (<span className="bg-overlay" style={overlayStyle}></span>); return ( <div className="background-content" style={backgroundStyle}> {overlay} </div> ); } }
src/features/DocumentationModal/NavBar.js
erhathaway/cellular_automata
import React from 'react'; import styled from 'react-emotion'; const Container = styled('nav')` width: 100%; height: 80px; background-color: #252525; z-index: 999; display: flex; align-items: center; justify-content: flex-start; padding-left: 20px; @media (max-width: 500px) { height: 50px; } @media (min-width: 800px) { display: none; } `; export default ({ children }) => { return ( <Container> { children } </Container> ); };
test/components/App.spec.js
TheCbac/MICA-Desktop
/* ********************************************************** * File: test/components/App.spec.js * * Brief: Test for the app component * * Authors: George Whitfield, Craig Cheney * * 2017.10.12 CC - Refactored for App container * 2017.07.28 GW - Document Created * ********************************************************* */ import React from 'react'; import { shallow } from 'enzyme'; import App from '../../app/components/App'; const app = shallow(<App />); /* Test suite */ describe('App', () => { it('Renders one App', () => { expect(app).toHaveLength(1); }); it('Contains a header', () => { const header = app.find('Header'); expect(header).toBeDefined(); }); }); /* [] - END OF FILE */
modules/gui/src/app/home/body/process/recipe/classChange/panels/legend/legend.js
openforis/sepal
import {Form} from 'widget/form/form' import {Layout} from 'widget/layout' import {LegendBuilder, defaultColor} from 'app/home/map/legendBuilder' import {Panel} from 'widget/panel/panel' import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel' import {compose} from 'compose' import {msg} from 'translate' import {recipeActionBuilder} from 'app/home/body/process/recipe' import {selectFrom} from 'stateUtils' import {withRecipe} from 'app/home/body/process/recipeContext' import PropTypes from 'prop-types' import React from 'react' import _ from 'lodash' import guid from 'guid' import styles from './legend.module.css' const fields = { invalidEntries: new Form.Field() .predicate(invalid => !invalid, 'invalid'), entries: new Form.Field() .predicate((entries, {invalidEntries}) => !invalidEntries && entries.length, 'invalid') } const mapRecipeToProps = recipe => { return ({ toImage: selectFrom(recipe, 'model.toImage'), legendEntries: selectFrom(recipe, 'model.legend.entries') || [], fromImage: selectFrom(recipe, 'model.fromImage') }) } class _Legend extends React.Component { render() { const {legendEntries} = this.props return <LegendPanel legendEntries={legendEntries}/> } componentDidUpdate(prevProps) { const {fromImage: prevFromImage, toImage: prevToImage} = prevProps const {fromImage, toImage} = this.props if (!_.isEqual([prevFromImage, prevToImage], [fromImage, toImage])) { this.updateLegend() } } updateLegend() { const {recipeId, fromImage, toImage} = this.props if (!fromImage || !toImage) { return } const entries = fromImage.legendEntries .map(({label: fromLabel}) => toImage.legendEntries.map(({label: toLabel}) => { return `${fromLabel} -> ${toLabel}` }) ) .flat() .map((label, i) => ({ id: guid(), value: i + 1, color: defaultColor(i + 1), label })) const actionBuilder = recipeActionBuilder(recipeId) actionBuilder('UPDATE_LEGEND', {fromImage, toImage, entries}) .set('model.legend.entries', entries) .dispatch() } } class _LegendPanel extends React.Component { render() { return ( <RecipeFormPanel placement="bottom-right" className={styles.panel}> <Panel.Header icon="list" title={msg('process.classification.panel.legend.title')} /> <Panel.Content scrollable={false}> <Layout spacing='compact'> {this.renderContent()} </Layout> </Panel.Content> <Form.PanelButtons/> </RecipeFormPanel> ) } renderContent() { const {inputs: {entries}} = this.props return ( <LegendBuilder entries={entries.value} locked={true} onChange={(updatedEntries, invalid) => this.updateLegendEntries(updatedEntries, invalid)} /> ) } componentDidMount() { const {legendEntries, inputs} = this.props inputs.entries.set(legendEntries) } updateLegendEntries(legendEntries, invalidLegendEntries) { const {inputs} = this.props inputs.entries.set(legendEntries) inputs.invalidEntries.set(invalidLegendEntries) } } const valuesToModel = ({entries}) => ({ entries: _.sortBy(entries, 'value') }) const additionalPolicy = () => ({ _: 'disallow' }) const LegendPanel = compose( _LegendPanel, recipeFormPanel({id: 'legend', fields, additionalPolicy, valuesToModel}) ) export const Legend = compose( _Legend, withRecipe(mapRecipeToProps) ) Legend.propTypes = { recipeId: PropTypes.string }
src/widgets/GalleryHub/SnippetGallery.js
mydearxym/mastani
/* * * SnippetGallery * */ import React from 'react' import T from 'prop-types' import { ICON } from '@/config' import { buildLog } from '@/utils/logger' import IconText from '@/widgets/IconText' import { Wrapper, Block, Header, IntroHead, LangPrefix, Title, Footer, } from './styles/snippet_gallery' /* eslint-disable-next-line */ const log = buildLog('c:SnippetGallery:index') const tmpItems = [ { id: '0', title: '客户端校验文件大小', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '1', title: '模式匹配', lang: 'ex', langColor: '#704A7C', icon: 'https://assets.coderplanets.com/icons/pl/elixir.png', }, { id: '2', title: 'clojure', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '3', title: 'Teambition', lang: 'ts', langColor: '#177488', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '4', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, { id: '5', title: 'whatever', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '6', title: 'Teambition', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '7', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, { id: '8', title: 'whatever', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '9', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, ] const SnippetGallery = ({ items }) => { return ( <Wrapper> {items.map((item, index) => ( <Block key={item.id} borderTop={index <= 2} borderRight={(index + 1) % 3 !== 0} > <Header> <IntroHead> <LangPrefix color={item.langColor}>{item.lang}</LangPrefix> <Title>{item.title}</Title> </IntroHead> </Header> <div>---</div> <Footer> <IconText iconSrc={`${ICON}/shape/vote-up.svg`}>22</IconText> <IconText iconSrc={`${ICON}/shape/vote-up.svg`} size="tiny"> 类型转换 </IconText> </Footer> </Block> ))} </Wrapper> ) } SnippetGallery.propTypes = { items: T.arrayOf(T.object), } SnippetGallery.defaultProps = { items: tmpItems, } export default React.memo(SnippetGallery)
src/components/icons/MenuIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const MenuIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M0 0h24v24H0z" fill="none" /> <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" /> </svg> ); export default MenuIcon;
src/App.js
zero-coder/gamesfame
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1> GamesFame </h1> ); } }
src/title/TitlePlain.js
nashvail/zulip-mobile
import React from 'react'; import { StyleSheet, Text } from 'react-native'; import { CONTROL_SIZE } from '../styles'; const styles = StyleSheet.create({ title: { flex: 1, textAlign: 'center', fontSize: 16, paddingRight: CONTROL_SIZE, }, }); export default ({ text, color }) => <Text style={[styles.title, { color }]}>{text}</Text>;
packages/@lyra/components/src/lists/sortable/DragHandle.js
VegaPublish/vega-studio
// @flow import React from 'react' import DragBarsIcon from 'part:@lyra/base/bars-icon' import {createDragHandle} from '../sortable-factories' export default createDragHandle(props => ( <span className={props.className}> <DragBarsIcon /> </span> ))
example1/toilet/ios_views/setting/about.js
anchoretics/ztf-work-app
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, ScrollView } from 'react-native'; import Util from './../util'; class About extends Component{ render(){ return( <ScrollView style={styles.container}> <Text style={styles.text}>如果问题,请联系: wlhmyit@126.com</Text> </ScrollView> ); } } const styles = StyleSheet.create({ container:{ flex: 1 }, text:{ fontSize:16, fontWeight:'300', marginBottom:15, marginLeft:10, marginTop:3 } }); module.exports = About;
app/imports/ui/containers/NewsRoomsList.js
mondrus/meteor-starter
/** * @Author: philip * @Date: 2017-05-27T20:46:16+00:00 * @Filename: NewsRoomsList.js * @Last modified by: philip * @Last modified time: 2017-05-29T13:40:09+00:00 */ import React from 'react'; import { composeWithTracker } from 'react-komposer'; import { Meteor } from 'meteor/meteor'; import NewsRooms from '/lib/collections/newsRooms'; import Loading from '../components/Loading.js'; import NewsRoomsList from '../components/NewsRoomsList.js'; const composer = (params, onData) => { const subscription = Meteor.subscribe('newsRooms.all'); if (subscription.ready()) { const newsRooms = NewsRooms.find().fetch(); onData(null, { newsRooms, params }); } }; export default composeWithTracker(composer, Loading)(NewsRoomsList);
src/svg-icons/communication/contact-mail.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationContactMail = (props) => ( <SvgIcon {...props}> <path d="M21 8V7l-3 2-3-2v1l3 2 3-2zm1-5H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2zM8 6c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H2v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1zm8-6h-8V6h8v6z"/> </SvgIcon> ); CommunicationContactMail = pure(CommunicationContactMail); CommunicationContactMail.displayName = 'CommunicationContactMail'; CommunicationContactMail.muiName = 'SvgIcon'; export default CommunicationContactMail;
src/routes/home/Home.js
joaquingatica/git-demo
/** * 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 s from './Home.css'; class Home extends React.Component { static propTypes = { news: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string.isRequired, link: PropTypes.string.isRequired, content: PropTypes.string, })).isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>React.js News</h1> {this.props.news.map(item => ( <article key={item.link} className={s.newsItem}> <h1 className={s.newsTitle}><a href={item.link}>{item.title}</a></h1> <div className={s.newsDesc} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: item.content }} /> </article> ))} </div> </div> ); } } export default withStyles(s)(Home);
src/Router.js
sherlock221/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/svg-icons/av/music-video.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMusicVideo = (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 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/> </SvgIcon> ); AvMusicVideo = pure(AvMusicVideo); AvMusicVideo.displayName = 'AvMusicVideo'; export default AvMusicVideo;
src/hero/ReactTab.js
material-components/material-components-web-catalog
import {Component} from 'react'; import ReactTemplates from './CodeTemplates'; import equal from 'deep-equal'; import React from 'react'; import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'; import {prism} from 'react-syntax-highlighter/dist/esm/styles/prism'; import {CopyToClipboard} from 'react-copy-to-clipboard'; import {MDCRipple} from '@material/ripple/index'; import {gtagCopyCode} from '../constants'; import ReactGA from 'react-ga'; const customStyle = {background: 'transparent'}; export default class ReactTab extends Component { state = {codeString: ''}; ripples = []; initRipple = (el) => { if (el) { const ripple = MDCRipple.attachTo(el); ripple.unbounded = true; this.ripples.push(ripple); } }; initCodeString = () => { const {children, location} = this.props; const reactTemplateName = location.pathname.split('/component/')[1]; const val = ReactTemplates[reactTemplateName](children.props.config); const codeString = val ? val.replace(/\n\s*\n/g, '\n') : ''; this.setState({codeString}); }; componentDidMount() { this.initCodeString(); } componentDidUpdate(prevProps) { if (!equal(prevProps.config.options, this.props.config.options)) { this.initCodeString(); } } render() { return ( <React.Fragment> <SyntaxHighlighter lineProps={{style: {paddingBottom: 8}}} wrapLines showLineNumbers customStyle={customStyle} lineNumberStyle={{color: '#bab6b6'}} className='highlight-html' language='jsx' style={prism}>{this.state.codeString}</SyntaxHighlighter> <CopyToClipboard text={this.state.codeString} onCopy={() => { ReactGA.event({category: gtagCopyCode, action: 'react_code_copied', label: 'react_code_copied' }); this.setState({copied: true}) }}> <button className='mdc-icon-button material-icons copy-all-button' ref={this.initRipple}>file_copy</button> </CopyToClipboard> </React.Fragment> ); } }
src/js/components/input/grid_form/input_grid_form.js
rafaelfbs/realizejs
import React from 'react'; import _ from 'lodash'; import PropTypes from '../../../prop_types'; import { autobind, mixin } from '../../../utils/decorators'; import { uuid } from '../../../utils'; import GridForm from '../../grid_form/grid_form'; import InputGridFormFields from './input_grid_form_fields'; import InputHidden from '../input_hidden'; import InputBase from '../input_base'; import { CssClassMixin, } from '../../../mixins'; @mixin(CssClassMixin) export default class InputGridForm extends InputBase { static propTypes = { label: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]), fields: PropTypes.object, form: PropTypes.object, clientSide: PropTypes.bool, clientSideIdField: React.PropTypes.string, inputWrapperComponent: PropTypes.component, onSuccess: PropTypes.func, onDestroySuccess: PropTypes.func, }; static defaultProps = { themeClassKey: 'input.gridForm', className: '', fields: {}, form: {}, clientSide: true, clientSideIdField: '_clientSideId', inputWrapperComponent: null, onSuccess() {}, onDestroySuccess() {}, }; getDefaultFormProps() { return { formStyle: 'filter', inputWrapperComponent: this.props.inputWrapperComponent, }; } parseFormProp() { const formProp = _.merge(this.getDefaultFormProps(), this.props.form); formProp.inputs = Object.assign({}, this.props.inputs); return formProp; } parseColumnsProp() { const { columns } = this.props; return _.mapValues(columns, (column, key) => Object.assign(column, { name: column.name || key, })); } buildGridData() { const { value, clientSideIdField } = this.props; const dataRows = !value || value === '' ? [] : value.map((v) => { return { ...v, [clientSideIdField]: uuid.v4() }; }); return { dataRows }; } /* GridForm Result serializer */ serialize() { return { [this.props.name]: this.state.value }; } /* Event handling functions */ @autobind handleOnSuccess() { const gridFormValue = this.refs.gridForm.serialize(); this.setState({ value: gridFormValue }, () => ( this.props.onSuccess(gridFormValue) )); } @autobind handleOnDestroySuccess() { const gridFormValue = this.refs.gridForm.serialize(); this.setState({ value: gridFormValue }, () => ( this.props.onDestroySuccess(gridFormValue) )); } /* Renderers */ renderLabel() { const label = this.props.label; if (typeof label === 'boolean' && !label) { return []; } return ( <h5 className={this.themedClassName('input.gridForm.label')}> {label} </h5> ); } render() { return ( <div className={this.className()}> {this.renderLabel()} <GridForm {...this.propsWithoutCSS()} formComponent={InputGridFormFields} form={this.parseFormProp()} columns={this.parseColumnsProp()} data={this.buildGridData()} onSuccess={this.handleOnSuccess} onDestroySuccess={this.handleOnDestroySuccess} errors={this.props.errors} ref="gridForm" /> <InputHidden {...this.propsWithoutCSS()} value={this.serialize()} ref="input" /> </div> ); } }
src/modules/banner/BannerView.js
TheOne1006/TheOne1006-theone-io-app
/** * @flow */ import React, { Component } from 'react'; import { List } from 'immutable'; import Swiper from 'react-native-swiper'; import styles from './themes/light'; import Slide from './SlideView'; const imgList = [ 'https://res.cloudinary.com/theone/image/upload/v1430750900/o0ohnh0hb1t8dlc7o0ln.jpg', 'https://res.cloudinary.com/theone/image/upload/v1440311373/rxh0zcpxerpum2msj7hl.jpg', 'https://res.cloudinary.com/theone/image/upload/v1430750829/rjpkswtvxxte4105ttrg.jpg', ]; class Banner extends Component { state = { loadQueue: List([]), } componentWillMount() { this.setState({ loadQueue: List(new Array(imgList.length)), }); } loadHandle = (i: number) => { const { loadQueue } = this.state; const newLoadQueue = loadQueue.set(i, 1); this.setState({ loadQueue: newLoadQueue, }); } render() { const { loadQueue } = this.state; return ( <Swiper loadMinimal loadMinimalSize={1} height={240} style={styles.wrapper} > { imgList.map((item, i) => ( <Slide loadHandle={this.loadHandle} loaded={!!loadQueue.get(i)} uri={item} i={i} key={item} styles={styles} />), )} </Swiper> ); } } export default Banner;
src/svg-icons/notification/airline-seat-legroom-extra.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomExtra = (props) => ( <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/> </SvgIcon> ); NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra); NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra'; NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomExtra;
src/svg-icons/editor/format-indent-increase.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatIndentIncrease = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/> </SvgIcon> ); EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease); EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease'; EditorFormatIndentIncrease.muiName = 'SvgIcon'; export default EditorFormatIndentIncrease;
node_modules/react-bootstrap/es/SplitButton.js
NathanBWaters/jb_club
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 _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import Button from './Button'; import Dropdown from './Dropdown'; import SplitToggle from './SplitToggle'; import splitComponentProps from './utils/splitComponentProps'; var propTypes = _extends({}, Dropdown.propTypes, { // Toggle props. bsStyle: React.PropTypes.string, bsSize: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, /** * The content of the split button. */ title: React.PropTypes.node.isRequired, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: React.PropTypes.string, // Override generated docs from <Dropdown>. /** * @private */ children: React.PropTypes.node }); var SplitButton = function (_React$Component) { _inherits(SplitButton, _React$Component); function SplitButton() { _classCallCheck(this, SplitButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } SplitButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, toggleLabel = _props.toggleLabel, children = _props.children, props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']); var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent), dropdownProps = _splitComponentProps[0], buttonProps = _splitComponentProps[1]; return React.createElement( Dropdown, _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Button, _extends({}, buttonProps, { disabled: props.disabled, bsSize: bsSize, bsStyle: bsStyle }), title ), React.createElement(SplitToggle, { 'aria-label': toggleLabel || title, bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Dropdown.Menu, null, children ) ); }; return SplitButton; }(React.Component); SplitButton.propTypes = propTypes; SplitButton.Toggle = SplitToggle; export default SplitButton;
src/components/form/textarea.js
n7best/react-weui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from '../../utils/classnames'; /** * weui wrapper for textarea * */ export default class TextArea extends Component { static propTypes = { /** * display word counter * */ showCounter: PropTypes.bool, /** * max character allow for textarea * */ maxLength: PropTypes.number, defaultValue: PropTypes.string, }; static defaultProps = { showCounter: true, defaultValue: undefined }; state = { textCounter: this.props.defaultValue ? this.props.defaultValue.length : 0 }; handleChange(e){ this.setState({textCounter: e.target.value.length}); //forward event to props if any if (this.props.onChange) this.props.onChange(e); } render(){ const { className, children, showCounter, maxLength, onChange, ...others } = this.props; const cls = classNames({ 'weui-textarea': true, [className]: className }); return ( <div> <textarea className={cls} maxLength={maxLength} onChange={this.handleChange.bind(this)} {...others}> {children} </textarea> { showCounter ? <div className="weui-textarea-counter"> <span>{this.state.textCounter}</span>{maxLength ? '/' + maxLength : false} </div> : false } </div> ); } };
docs/src/examples/modules/Dropdown/Types/DropdownExampleMultipleSelection.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const options = [ { key: 'angular', text: 'Angular', value: 'angular' }, { key: 'css', text: 'CSS', value: 'css' }, { key: 'design', text: 'Graphic Design', value: 'design' }, { key: 'ember', text: 'Ember', value: 'ember' }, { key: 'html', text: 'HTML', value: 'html' }, { key: 'ia', text: 'Information Architecture', value: 'ia' }, { key: 'javascript', text: 'Javascript', value: 'javascript' }, { key: 'mech', text: 'Mechanical Engineering', value: 'mech' }, { key: 'meteor', text: 'Meteor', value: 'meteor' }, { key: 'node', text: 'NodeJS', value: 'node' }, { key: 'plumbing', text: 'Plumbing', value: 'plumbing' }, { key: 'python', text: 'Python', value: 'python' }, { key: 'rails', text: 'Rails', value: 'rails' }, { key: 'react', text: 'React', value: 'react' }, { key: 'repair', text: 'Kitchen Repair', value: 'repair' }, { key: 'ruby', text: 'Ruby', value: 'ruby' }, { key: 'ui', text: 'UI Design', value: 'ui' }, { key: 'ux', text: 'User Experience', value: 'ux' }, ] const DropdownExampleMultipleSelection = () => ( <Dropdown placeholder='Skills' fluid multiple selection options={options} /> ) export default DropdownExampleMultipleSelection
react-flux-mui/js/material-ui/src/svg-icons/av/replay-30.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay30 = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-2.4 8.5h.4c.2 0 .4-.1.5-.2s.2-.2.2-.4v-.2s-.1-.1-.1-.2-.1-.1-.2-.1h-.5s-.1.1-.2.1-.1.1-.1.2v.2h-1c0-.2 0-.3.1-.5s.2-.3.3-.4.3-.2.4-.2.4-.1.5-.1c.2 0 .4 0 .6.1s.3.1.5.2.2.2.3.4.1.3.1.5v.3s-.1.2-.1.3-.1.2-.2.2-.2.1-.3.2c.2.1.4.2.5.4s.2.4.2.6c0 .2 0 .4-.1.5s-.2.3-.3.4-.3.2-.5.2-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.4-.1-.6h.8v.2s.1.1.1.2.1.1.2.1h.5s.1-.1.2-.1.1-.1.1-.2v-.5s-.1-.1-.1-.2-.1-.1-.2-.1h-.6v-.7zm5.7.7c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5c0-.1-.1-.2-.1-.3s-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvReplay30 = pure(AvReplay30); AvReplay30.displayName = 'AvReplay30'; AvReplay30.muiName = 'SvgIcon'; export default AvReplay30;
packages/components/src/SubHeaderBar/SubHeader.stories.js
Talend/ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import FilterBar from '../FilterBar'; import Tag from '../Tag'; import SubHeaderBar from './SubHeaderBar.component'; const viewProps = { title: 'My Long Title is Long Long Lé Long La La La Lé Long Long Long Long', onEdit: action('onEdit'), onSubmit: action('onSubmit'), onCancel: action('onCancel'), onChange: action('onChange'), }; const backAction = action('onGoBack'); const injectedComponentsRight = [ { label: 'icon + text', bsStyle: 'link', icon: 'talend-share-alt', onClick: action('icon + text'), }, { label: 'action1', bsStyle: 'link', icon: 'talend-share-alt', onClick: action('return action1'), hideLabel: true, }, { label: 'Action2', bsStyle: 'link', icon: 'talend-activity', onClick: action('return action2'), displayMode: 'iconToggle', active: true, }, { label: 'action3', bsStyle: 'link', icon: 'talend-bell', onClick: action('return action3'), hideLabel: true, displayMode: 'iconToggle', }, ]; const componentAction = { label: 'action4', bsStyle: 'link', icon: 'talend-bell', onClick: action('return action4'), hideLabel: true, }; const center = ( <SubHeaderBar.Content center> <FilterBar t={() => action('t')} onFilter={() => action('onFilter')} navbar docked={false} dockable={false} /> </SubHeaderBar.Content> ); export default { title: 'Navigation/SubHeader', }; export const WithDefault = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} /> </div> ); export const WithEditable = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} editable /> </div> ); export const WithIcon = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" onGoBack={backAction} /> </div> ); export const WithSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitle="mySubTitle" onGoBack={backAction} /> </div> ); export const WithLoadingSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitleLoading onGoBack={backAction} /> </div> ); export const WithCustomSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitle="mySubTitle" onGoBack={backAction} subTitleAs={({ subTitle }) => <Tag bsStyle="info">{subTitle}</Tag>} /> </div> ); export const WithRightComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} right={injectedComponentsRight} /> </div> ); export const WithCenterComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} center={[componentAction]}> {center} </SubHeaderBar> </div> ); export const WithCenterComponentsWithTagProps = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction}> <SubHeaderBar.Content tag="form" center> <input id="inputTitle" type="text" onChange={action('onChange')} value="" /> </SubHeaderBar.Content> </SubHeaderBar> </div> ); export const WithCenterRightComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} right={injectedComponentsRight}> {center} </SubHeaderBar> </div> ); export const WithAll = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} right={injectedComponentsRight} > {center} </SubHeaderBar> </div> ); export const WithSkeleton = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} loading > {center} </SubHeaderBar> </div> ); export const WithInProgress = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} inProgress editable > {center} </SubHeaderBar> </div> ); export const WithRightActionsLoading = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} rightActionsLoading /> </div> );
app/containers/Home/subPage/List.js
owen1190/ele-react
import React from 'react' import PureRenderMixin from 'react-addons-pure-render-mixin' import {get} from '../../../fetch/get'; import { homeListData } from '../../../../mock/getData' import ListCompoent from '../../../components/ListComponent' import LoadMore from '../../../components/LoadMore' import {Link} from 'react-router'; import './style.less' class List extends React.Component{ constructor(props) { super(props); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); this.state = { data: [], hasMore: false, isLoadingMore: false, page: 0 } } render(){ return ( <div> <h2 className="home-list-title">推荐商家</h2> { this.state.data.length ? <ListCompoent data={this.state.data}/> : <div>{/* 加载中... */}</div> } { this.state.hasMore ? <LoadMore isLoadingMore={this.state.isLoadingMore} loadMoreFn={this.loadMoreData.bind(this)}/> : '' } </div> ) } componentDidMount(){ this.resultHandle(homeListData()) } resultHandle(result){ result.then(res =>{ this.setState({ data: res, hasMore:true, }) }) } loadMoreData(){ this.setState({ isLoadingMore:true }) const page = this.state.page; this.resultHandle(homeListData()) this.setState({ page:page+1 }) } } export default List
src/components/social-link.js
MozillaIndia/mozillaindia.github.io
import React from 'react' import { FaTwitterSquare, FaFacebookSquare, FaInstagram, FaMeetup, FaTelegramPlane, FaGithub, FaGlobe, } from 'react-icons/fa' const getIconByType = ({ type }) => { switch (type) { case 'website': return <FaGlobe size="25" color="#0088cc" /> case 'telegram': return <FaTelegramPlane size="25" color="#0088cc" /> case 'twitter': return <FaTwitterSquare size="25" color="#1da1f2" /> case 'github': return <FaGithub size="25" color="#000" /> case 'instagram': return <FaInstagram size="25" color="#000" /> case 'facebook': return <FaFacebookSquare size="25" color="#1da1f2" /> case 'meetup': return <FaMeetup size="25" color="#1da1f2" /> default: return <FaGlobe /> } } const SocialLink = ({ type, link }) => ( <a href={link}> <span className="icon-tile">{getIconByType({ type })}</span> </a> ) export default SocialLink
src/components/placeholder.js
samuelneff/react-play
import React from 'react'; class Placeholder extends React.Component { render() { return ( <div> <p>This is a starting point for a project that uses:</p> <ul> <li><a href="https://github.com/lukehoban/es6features">ES6 (aka EcmaScript 2015)</a></li> <li><a href="https://facebook.github.io/react/">React</a></li> <li><a href="https://babeljs.io/">Babel</a></li> <li><a href="http://browserify.org/">Browserify</a></li> <li><a href="https://github.com/babel/babelify">Babelify</a></li> <li><a href="http://gulpjs.com/">Gulp</a></li> <li><a href="https://nodejs.org/">Node</a></li> <li><a href="http://expressjs.com/">Express</a></li> </ul> <p> See the GitHub repository at: <a href="https://github.com/poshaughnessy/es6-react-babel-starter-template">github.com/poshaughnessy/es6-react-babel-starter-template</a> </p> <p>Feel free to fork, copy or use however you like.</p> <p> Also please get in touch via <a href="mailto:peter.oshaughnessy@gmail.com">email</a> or <a href="http://twitter.com/poshaughnessy">Twitter</a> if you have any comments/suggestions/questions. </p> <p><em>Peter O'Shaughnessy</em></p> </div> ); } } export default Placeholder;
source/Plx.js
Stanko/react-plx
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import BezierEasing from 'bezier-easing'; import ScrollManager from 'window-scroll-manager'; // Check if code is running in the browser (important for universal rendering) const WINDOW_EXISTS = typeof window !== 'undefined'; // Regex that checks for numbers in string // formatted as "{number}{unit}" where unit is "px", "vh", "%" or none const START_END_DURATION_REGEX = /^-?\d+(\.\d+)?(px|vh|%)?$/; const DEFAULT_UNIT = 'px'; const DEFAULT_ANGLE_UNIT = 'deg'; const ANGLE_PROPERTIES = [ 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY', 'skewZ', 'hueRotate', ]; const EASINGS = { ease: [0.25, 0.1, 0.25, 1.0], easeIn: [0.42, 0.0, 1.00, 1.0], easeOut: [0.00, 0.0, 0.58, 1.0], easeInOut: [0.42, 0.0, 0.58, 1.0], easeInSine: [0.47, 0, 0.745, 0.715], easeOutSine: [0.39, 0.575, 0.565, 1], easeInOutSine: [0.445, 0.05, 0.55, 0.95], easeInQuad: [0.55, 0.085, 0.68, 0.53], easeOutQuad: [0.25, 0.46, 0.45, 0.94], easeInOutQuad: [0.455, 0.03, 0.515, 0.955], easeInCubic: [0.55, 0.055, 0.675, 0.19], easeOutCubic: [0.215, 0.61, 0.355, 1], easeInOutCubic: [0.645, 0.045, 0.355, 1], easeInQuart: [0.895, 0.03, 0.685, 0.22], easeOutQuart: [0.165, 0.84, 0.44, 1], easeInOutQuart: [0.77, 0, 0.175, 1], easeInQuint: [0.755, 0.05, 0.855, 0.06], easeOutQuint: [0.23, 1, 0.32, 1], easeInOutQuint: [0.86, 0, 0.07, 1], easeInExpo: [0.95, 0.05, 0.795, 0.035], easeOutExpo: [0.19, 1, 0.22, 1], easeInOutExpo: [1, 0, 0, 1], easeInCirc: [0.6, 0.04, 0.98, 0.335], easeOutCirc: [0.075, 0.82, 0.165, 1], easeInOutCirc: [0.785, 0.135, 0.15, 0.86], }; // Color regexes // 0 - 199 | 200 - 249 | 250 - 255 const REGEX_0_255 = '(1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'; // 0.0 - 1.9999... const REGEX_0_1 = '([01](\\.\\d+)?)'; // 00 - FF const REGEX_TWO_HEX_DIGITS = '([a-f\\d]{2})'; const HEX_REGEX = new RegExp(`^#${ REGEX_TWO_HEX_DIGITS }${ REGEX_TWO_HEX_DIGITS }${ REGEX_TWO_HEX_DIGITS }$`, 'i'); const RGB_REGEX = new RegExp(`^rgb\\(${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_255 }\\)$`, 'i'); const RGBA_REGEX = new RegExp(`^rgba\\(${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_1 }\\)$`, 'i'); const SCROLL_OFFSET = 50; const RESIZE_DEBOUNCE_TIMEOUT = 150; // CSS transform map const TRANSFORM_MAP = { rotate: (value, unit = DEFAULT_ANGLE_UNIT) => `rotate(${ value }${ unit })`, rotateX: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateX(${ value }${ unit })`, rotateY: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateY(${ value }${ unit })`, rotateZ: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateZ(${ value }${ unit })`, scale: value => `scale(${ value })`, scaleX: value => `scaleX(${ value })`, scaleY: value => `scaleY(${ value })`, scaleZ: value => `scaleZ(${ value })`, skew: (value, unit = DEFAULT_UNIT) => `skew(${ value }${ unit })`, skewX: (value, unit = DEFAULT_UNIT) => `skewX(${ value }${ unit })`, skewY: (value, unit = DEFAULT_UNIT) => `skewY(${ value }${ unit })`, skewZ: (value, unit = DEFAULT_UNIT) => `skewZ(${ value }${ unit })`, translateX: (value, unit = DEFAULT_UNIT) => `translateX(${ value }${ unit })`, translateY: (value, unit = DEFAULT_UNIT) => `translateY(${ value }${ unit })`, translateZ: (value, unit = DEFAULT_UNIT) => `translateZ(${ value }${ unit })`, }; // Order of CSS transforms matters const ORDER_OF_TRANSFORMS = [ 'translateX', 'translateY', 'translateZ', 'skew', 'skewX', 'skewY', 'skewZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', ]; // CSS properties that use color values const COLOR_PROPERTIES = [ 'backgroundColor', 'borderBottomColor', 'borderColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'fill', 'stroke', ]; // CSS filter map // blur() // brightness() // contrast() // grayscale() // hue-rotate() // invert() // opacity() // use opacityFilter // saturate() // sepia() // Not supported // drop-shadow() // url() const FILTER_MAP = { blur: (value, unit = DEFAULT_UNIT) => `blur(${ value }${ unit })`, brightness: value => `brightness(${ value })`, contrast: value => `contrast(${ value })`, grayscale: value => `grayscale(${ value })`, hueRotate: (value, unit = DEFAULT_ANGLE_UNIT) => `hue-rotate(${ value }${ unit })`, invert: value => `invert(${ value })`, opacityFilter: value => `opacity(${ value })`, saturate: value => `saturate(${ value })`, sepia: value => `sepia(${ value })`, }; const FILTER_PROPERTIES = [ 'blur', 'brightness', 'contrast', 'grayscale', 'hueRotate', 'invert', 'opacityFilter', 'saturate', 'sepia', ]; // Props to be removed from passing directly to the component element const PROPS_TO_OMIT = [ 'animateWhenNotInViewport', 'children', 'className', 'freeze', 'parallaxData', 'style', 'tagName', 'onPlxStart', 'onPlxEnd', ]; // Get element's top offset function getElementTop(el) { let top = 0; let element = el; do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); return top; } // Returns CSS unit function getUnit(property, unit) { let propertyUnit = unit || DEFAULT_UNIT; if (ANGLE_PROPERTIES.indexOf(property) >= 0) { propertyUnit = unit || DEFAULT_ANGLE_UNIT; } return propertyUnit; } // Takes string value (in px/vh/%) and returns number function getValueInPx(value, maxScroll) { const floatValue = parseFloat(value); const unit = value.match(START_END_DURATION_REGEX)[2] || null; const vh = window.innerHeight / 100; let valueInPx = value; switch (unit) { case 'vh': valueInPx = vh * floatValue; break; case '%': valueInPx = maxScroll * floatValue / 100; break; default: valueInPx = floatValue; } return valueInPx; } // Takes start/end/duration props // and return number (in pixels) based on prop type (number, string, dom element) function convertPropToPixels(propName, propValue, maxScroll, offset = 0) { let propValueInPx = propValue; const isElement = propValue instanceof HTMLElement; const keyCodes = { ZERO: 48, NINE: 57, }; if (typeof propValue === 'number') { propValueInPx = propValue; } else if (START_END_DURATION_REGEX.test(propValue)) { propValueInPx = getValueInPx(propValue, maxScroll); } else if ( isElement || typeof propValue === 'string' && (propValue.charCodeAt(0) < keyCodes.ZERO || propValue.charCodeAt(0) > keyCodes.NINE) ) { const element = isElement ? propValue : document.querySelector(propValue); if (!element) { console.warn(`Plx, ERROR: ${ propName } selector matches no elements: "${ propValue }"`); // eslint-disable-line return null; } if (propName === 'start' || propName === 'end') { // START or END // Element enters the viewport propValueInPx = getElementTop(element) - window.innerHeight; } else if (propName === 'duration') { // DURATION // Height of the element propValueInPx = element.offsetHeight; } } else { console.warn(`Plx, ERROR: "${ propValue }" is not a valid ${ propName } value, check documenation`); // eslint-disable-line return null; } // Transform offset to px let offsetInPx = 0; if (typeof offset === 'number') { offsetInPx = offset; } else if (START_END_DURATION_REGEX.test(offset)) { offsetInPx = getValueInPx(offset, maxScroll); } // Add offset propValueInPx += offsetInPx; if (propValueInPx < 0) { propValueInPx = 0; } return propValueInPx; } // Convers color in hex format into object { r, g, b, a } function hexToObject(hex) { // Convert #abc to #aabbcc const color = hex.length === 4 ? `#${ hex[1] }${ hex[1] }${ hex[2] }${ hex[2] }${ hex[3] }${ hex[3] }` : hex; const result = HEX_REGEX.exec(color); // Safety check, if color is in the wrong format if (!result) { console.warn(`Plx, ERROR: hex color is not in the right format: "${ hex }"`); // eslint-disable-line no-console return null; } // All color functions are returning { r, g, b, a } object return { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), a: 1, }; } // Convers color in rgb format into object { r, g, b, a } function rgbToObject(rgb) { const isRgba = rgb.toLowerCase().indexOf('rgba') === 0; const color = rgb.replace(/ /g, ''); const result = isRgba ? RGBA_REGEX.exec(color) : RGB_REGEX.exec(color); // Safety check, if color is in the wrong format if (!result) { console.warn(`Plx, ERROR: rgb or rgba color is not in the right format: "${ rgb }"`); // eslint-disable-line return null; } // All color functions are returning { r, g, b, a } object return { r: parseInt(result[1], 10), g: parseInt(result[2], 10), b: parseInt(result[3], 10), a: isRgba ? parseFloat(result[4]) : 1, }; } // Calculates the current value for parallaxing property function parallax(scrollPosition, start, duration, startValue, endValue, easing) { let min = startValue; let max = endValue; const invert = startValue > endValue; // Safety check, if "startValue" is in the wrong format if (typeof startValue !== 'number') { console.warn(`Plx, ERROR: startValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "endValue" is in the wrong format if (typeof endValue !== 'number') { console.warn(`Plx, ERROR: endValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "duration" is in the wrong format if (typeof duration !== 'number' || duration === 0) { console.warn(`Plx, ERROR: duration is zero or not a number (type: "${ typeof duration }", value: "${ duration }")`); // eslint-disable-line return null; } if (invert) { min = endValue; max = startValue; } let percentage = ((scrollPosition - start) / duration); if (percentage > 1) { percentage = 1; } else if (percentage < 0) { percentage = 0; } // Apply easing if (easing) { const easingPropType = typeof easing; if (easingPropType === 'object' && easing.length === 4) { percentage = BezierEasing( easing[0], easing[1], easing[2], easing[3] )(percentage); } else if (easingPropType === 'string' && EASINGS[easing]) { percentage = BezierEasing( EASINGS[easing][0], EASINGS[easing][1], EASINGS[easing][2], EASINGS[easing][3] )(percentage); } else if (easingPropType === 'function') { percentage = easing(percentage); } } let value = percentage * (max - min); if (invert) { value = max - value; } else { value += min; } // Rounding to 4 decimals (.toFixed(4) returns a string) return Math.floor(value * 10000) / 10000; } // Calculates current value for color parallax function colorParallax(scrollPosition, start, duration, startValue, endValue, easing) { let startObject = null; let endObject = null; if (startValue[0].toLowerCase() === 'r') { startObject = rgbToObject(startValue); } else { startObject = hexToObject(startValue); } if (endValue[0].toLowerCase() === 'r') { endObject = rgbToObject(endValue); } else { endObject = hexToObject(endValue); } if (startObject && endObject) { const r = parallax(scrollPosition, start, duration, startObject.r, endObject.r, easing); const g = parallax(scrollPosition, start, duration, startObject.g, endObject.g, easing); const b = parallax(scrollPosition, start, duration, startObject.b, endObject.b, easing); const a = parallax(scrollPosition, start, duration, startObject.a, endObject.a, easing); return `rgba(${ parseInt(r, 10) }, ${ parseInt(g, 10) }, ${ parseInt(b, 10) }, ${ a })`; } return null; } // Applies property parallax to the style object function applyProperty(scrollPosition, propertyData, startPosition, duration, style, easing) { const { startValue, endValue, property, unit, } = propertyData; // If property is one of the color properties // Use it's parallax method const isColor = COLOR_PROPERTIES.indexOf(property) > -1; const parallaxMethod = isColor ? colorParallax : parallax; // Get new CSS value const value = parallaxMethod( scrollPosition, startPosition, duration, startValue, endValue, easing ); // Get transform function const transformMethod = TRANSFORM_MAP[property]; const filterMethod = FILTER_MAP[property]; const newStyle = style; if (transformMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Transforms, apply value to transform function newStyle.transform[property] = transformMethod(value, propertyUnit); if (!newStyle.willChange.includes('transform')) { newStyle.willChange.push('transform'); } } else if (filterMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Filters, apply value to filter function newStyle.filter[property] = filterMethod(value, propertyUnit); if (!newStyle.willChange.includes('filter')) { newStyle.willChange.push('filter'); } } else { // All other properties newStyle[property] = value; if (!newStyle.willChange.includes(property)) { newStyle.willChange.push(property); } // Add unit if it is passed if (unit) { newStyle[property] += unit; } } return newStyle; } // Returns CSS classes based on animation state function getClasses(lastSegmentScrolledBy, isInSegment, parallaxData) { let cssClasses = null; if (lastSegmentScrolledBy === null) { cssClasses = 'Plx--above'; } else if (lastSegmentScrolledBy === parallaxData.length - 1 && !isInSegment) { cssClasses = 'Plx--below'; } else if (lastSegmentScrolledBy !== null && isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; cssClasses = `Plx--active Plx--in Plx--in-${ segmentName }`; } else if (lastSegmentScrolledBy !== null && !isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; const nextSegmentName = parallaxData[lastSegmentScrolledBy + 1].name || lastSegmentScrolledBy + 1; cssClasses = `Plx--active Plx--between Plx--between-${ segmentName }-and-${ nextSegmentName }`; } return cssClasses; } // Checks if class contains 'active' function checkIfActive(classes) { return classes.indexOf('Plx--active') > -1; } // Omits "keysToOmit" from "object" function omit(object, keysToOmit) { const result = {}; Object.keys(object).forEach(key => { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } }); return result; } // Main update function // Returns new state object based on props and scroll position function getNewState(scrollPosition, props, state, element) { const { animateWhenNotInViewport, disabled, freeze, parallaxData, } = props; const { showElement, plxStyle, plxStateClasses, } = state; // Do nothing if animation is disabled, frozen // or if element is not rendered yet if ((freeze && showElement) || !element || disabled) { return null; } // Check if element is in viewport // Small offset is added to prevent page jumping if (!animateWhenNotInViewport) { const rect = element.getBoundingClientRect(); const isTopAboveBottomEdge = rect.top < window.innerHeight + SCROLL_OFFSET; const isBottomBelowTopEdge = rect.top + rect.height > -SCROLL_OFFSET; if (!isTopAboveBottomEdge || !isBottomBelowTopEdge) { return null; } } const newState = {}; // Style to be applied to our element let newStyle = { willChange: [], transform: {}, filter: {}, }; // This means "componentDidMount" did happen and that we should show our element if (!showElement) { newState.showElement = true; } const appliedProperties = []; const segments = []; let isInSegment = false; let lastSegmentScrolledBy = null; const bodyHeight = document.documentElement.scrollHeight || document.body.scrollHeight; const maxScroll = bodyHeight - window.innerHeight; for (let i = 0; i < parallaxData.length; i++) { const { duration, easing, endOffset, properties, startOffset, } = parallaxData[i]; const start = parallaxData[i].start === 'self' ? element : parallaxData[i].start; const end = parallaxData[i].end === 'self' ? element : parallaxData[i].end; const startInPx = convertPropToPixels('start', start, maxScroll, startOffset); let durationInPx = null; let endInPx = null; // End has higher priority than duration if (typeof end !== 'undefined') { endInPx = convertPropToPixels('end', end, maxScroll, endOffset); durationInPx = endInPx - startInPx; } else { durationInPx = convertPropToPixels('duration', duration, maxScroll); endInPx = startInPx + durationInPx; } // If segment is below scroll position skip it if (scrollPosition < startInPx) { break; } const isScrolledByStart = scrollPosition >= startInPx; if (isScrolledByStart) { lastSegmentScrolledBy = i; } // If active segment exists, apply his properties if (scrollPosition >= startInPx && scrollPosition <= endInPx) { isInSegment = true; properties.forEach(propertyData => { // eslint-disable-line no-loop-func const { property } = propertyData; // Save which properties are applied to the active segment // So they are not re-applied for other segments appliedProperties.push(property); // Apply property style newStyle = applyProperty( scrollPosition, propertyData, startInPx, durationInPx, newStyle, easing ); }); } else { // Push non active segments above the scroll position to separate array // This way "durationInPx" and "startInPx" are not calculated again // and segments below scroll position are skipped in the next step segments.push({ easing, durationInPx, properties, startInPx, }); } } // These are only segments that are completly above scroll position segments.forEach(data => { const { easing, durationInPx, properties, startInPx, } = data; properties.forEach((propertyData) => { const { property } = propertyData; // Skip propery that was changed for active segment if (appliedProperties.indexOf(property) > -1) { return; } // These styles that are the ones changed by segments // that are above active segment newStyle = applyProperty( scrollPosition, propertyData, startInPx, durationInPx, newStyle, easing ); }); }); // Sort transforms by ORDER_OF_TRANSFORMS // as order of CSS transforms matters const transformsOrdered = []; ORDER_OF_TRANSFORMS.forEach(transformKey => { if (newStyle.transform[transformKey]) { transformsOrdered.push(newStyle.transform[transformKey]); } }); // Concat transforms and add webkit prefix newStyle.transform = transformsOrdered.join(' '); newStyle.WebkitTransform = newStyle.transform; const filtersArray = []; FILTER_PROPERTIES.forEach(filterKey => { if (newStyle.filter[filterKey]) { filtersArray.push(newStyle.filter[filterKey]); } }); // Concat filters and add webkit prefix newStyle.filter = filtersArray.join(' '); newStyle.WebkitFilter = newStyle.filter; // "Stupid" check if style should be updated if (JSON.stringify(plxStyle) !== JSON.stringify(newStyle)) { newState.plxStyle = newStyle; } // Adding state class const newPlxStateClasses = getClasses(lastSegmentScrolledBy, isInSegment, parallaxData); if (newPlxStateClasses !== plxStateClasses) { newState.plxStateClasses = newPlxStateClasses; } if (Object.keys(newState).length) { return newState; } return null; } export default class Plx extends Component { constructor(props) { super(); // Binding handlers this.handleScrollChange = this.handleScrollChange.bind(this); this.handleResize = this.handleResize.bind(this); this.state = { element: null, showElement: false, plxStateClasses: '', plxStyle: {}, }; // Skipping type checking as PropTypes will give a warning if the props aren't functions this.plxStartEnabled = props.onPlxStart !== null; this.plxEndEnabled = props.onPlxEnd !== null; } componentDidMount() { // Get scroll manager singleton this.scrollManager = new ScrollManager(); // Add listeners window.addEventListener('window-scroll', this.handleScrollChange); window.addEventListener('resize', this.handleResize); this.update(); } componentDidUpdate(prevProps, prevState) { const wasActive = checkIfActive(prevState.plxStateClasses); const isActive = checkIfActive(this.state.plxStateClasses); // Update only if props changed if (prevProps !== this.props) { this.update(); } // Callbacks if ((this.plxStartEnabled || this.plxEndEnabled) && prevState.plxStateClasses !== this.state.plxStateClasses) { if (this.plxStartEnabled && !wasActive && isActive) { this.props.onPlxStart(); } else if (this.plxEndEnabled && wasActive && !isActive) { this.props.onPlxEnd(); } } } componentWillUnmount() { window.removeEventListener('window-scroll', this.handleScrollChange); window.removeEventListener('resize', this.handleResize); clearTimeout(this.resizeDebounceTimeoutID); this.resizeDebounceTimeoutID = null; if (this.scrollManager) { this.scrollManager.removeListener(); } } update(scrollPosition = null) { const currentScrollPosition = scrollPosition === null ? this.scrollManager.getScrollPosition().scrollPositionY : scrollPosition; const newState = getNewState( currentScrollPosition, this.props, this.state, this.element ); if (newState) { this.setState(newState); } } handleResize() { clearTimeout(this.resizeDebounceTimeoutID); this.resizeDebounceTimeoutID = setTimeout(() => { this.update(); }, RESIZE_DEBOUNCE_TIMEOUT); } handleScrollChange(e) { this.update(e.detail.scrollPositionY); } render() { const { children, className, disabled, style, tagName, } = this.props; const { showElement, plxStyle, plxStateClasses, } = this.state; const Tag = tagName; let elementStyle = style; if (!disabled) { elementStyle = { ...style, ...plxStyle, // Hide element before until it is rendered // This prevents jumps if page is scrolled and then refreshed visibility: showElement ? null : 'hidden', }; } return ( <Tag { ...omit(this.props, PROPS_TO_OMIT) } className={ `Plx ${ plxStateClasses } ${ className }` } style={ elementStyle } ref={ el => this.element = el } > { children } </Tag> ); } } const propertiesItemType = PropTypes.shape({ startValue: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, endValue: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, property: PropTypes.string.isRequired, unit: PropTypes.string, }); // Check for the universal rendering // HTMLElement in the proptypes breaks on server // https://github.com/Stanko/react-plx/issues/25 const SafeHTMLElement = WINDOW_EXISTS ? window.HTMLElement : {}; const parallaxDataType = PropTypes.shape({ start: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]).isRequired, startOffset: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]), duration: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]), end: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]), endOffset: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]), properties: PropTypes.arrayOf(propertiesItemType).isRequired, easing: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, PropTypes.func, ]), name: PropTypes.string, }); Plx.propTypes = { animateWhenNotInViewport: PropTypes.bool, children: PropTypes.any, className: PropTypes.string, disabled: PropTypes.bool, freeze: PropTypes.bool, parallaxData: PropTypes.arrayOf(parallaxDataType), style: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object])), tagName: PropTypes.string, onPlxStart: PropTypes.func, onPlxEnd: PropTypes.func, }; Plx.defaultProps = { animateWhenNotInViewport: false, children: null, className: '', disabled: false, freeze: false, parallaxData: [], style: {}, tagName: 'div', onPlxStart: null, onPlxEnd: null, };
node_modules/react-bootstrap/es/InputGroupButton.js
CallumRocks/ReduxSimpleStarter
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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var InputGroupButton = function (_React$Component) { _inherits(InputGroupButton, _React$Component); function InputGroupButton() { _classCallCheck(this, InputGroupButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } InputGroupButton.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return InputGroupButton; }(React.Component); export default bsClass('input-group-btn', InputGroupButton);
app/templates/src/components/Version/Version.js
KarolAltamirano/generator-react-web
// @flow /* eslint-disable no-console */ import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import styles from './styles.scss'; import config from '../../../config.json'; export default class Version extends Component { state: Object = { version: config.build.version, time: config.build.time, }; componentDidMount() { console.log( `\n%cv${this.state.version}%c %c${this.state.time}%c\n\n`, 'color: #ffffff; background: #00aa00; padding: 1px 5px;', 'color: #ffffff; background: #d1eeee; padding: 1px 5px;', 'color: #ffffff; background: #00aa00; padding: 1px 5px;', 'background: #ffffff;' ); } render(): ?React$Element<any> { return ( <div className={styles.wrapper}> <FormattedMessage {...messages.version} values={{ version: this.state.version, time: this.state.time }} /> </div> ); } }
src/routes/Pianoroll/components/Pianoroll.js
rkram5424/BentoBeats
import React from 'react' export const HomeView = () => ( <div> <h4>Pianoroll!</h4> </div> ) export default HomeView
internals/templates/app.js
williamsnieves/reactnews
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/routes/home/index.js
tlin108/chaf
/** * 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 Home from './Home'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,content}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Layout><Home news={data.news} /></Layout>, }; }, };
frontend/src/common/components/text-item.js
OptimusCrime/youkok2
import React from 'react'; export const TextItem = ({ text }) => ( <li className="list-group-item"> {text} </li> );
test/ListGroupSpec.js
pieter-lazzaro/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ListGroup from '../src/ListGroup'; import ListGroupItem from '../src/ListGroupItem'; describe('ListGroup', function () { it('Should output a "div" with the class "list-group"', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup/> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should support a single "ListGroupItem" child', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>Only Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); }); it('Should support a single "ListGroupItem" child contained in an array', function () { let child = [<ListGroupItem key={42}>Only Child in array</ListGroupItem>]; let instance = ReactTestUtils.renderIntoDocument( <ListGroup> {child} </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); }); it('Should output a "ul" when single "ListGroupItem" child is a list item', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>Only Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'LI'); }); it('Should output a "div" when single "ListGroupItem" child is an anchor', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem href="#test">Only Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'A'); }); it('Should support multiple "ListGroupItem" children', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[1], 'list-group-item')); }); it('Should support multiple "ListGroupItem" children including a subset contained in an array', function () { let itemArray = [ <ListGroupItem key={0}>2nd Child nested</ListGroupItem>, <ListGroupItem key={1}>3rd Child nested</ListGroupItem> ]; let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> {itemArray} <ListGroupItem>4th Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[1], 'list-group-item')); }); it('Should output a "ul" when children are list items', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'LI'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'LI'); }); it('Should output a "div" when "ListGroupItem" children are anchors and spans', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem href="#test">1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'A'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'SPAN'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should output a "div" when "ListGroupItem" children have an onClick handler', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem onClick={() => null}>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'A'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'SPAN'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should support an element id through "id" prop', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup id="testItem"> <ListGroupItem>Child</ListGroupItem> </ListGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).id, 'testItem'); }); });
BookSearch/index.ios.js
onezens/react-native-repo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import Featured from ('./Featured.js'); import Search from ('./Search.js'); export default class BookSearch extends Component { constructor(props) { super(props); this.state = { selectedTab: 'featured' }; } render() { return ( <TabBarIOS selectedTab={this.state.selectedTab}> <TabBarIOS.Item selected={this.state.selectedTab === 'featured'} icon={{uri:'featured'}} onPress={() => { this.setState({ selectedTab: 'featured' }); }}> <Featured/> </TabBarIOS.Item> <TabBarIOS.Item selected={this.state.selectedTab === 'search'} icon={{uri:'search'}} onPress={() => { this.setState({ selectedTab: 'search' }); }}> <Search/> </TabBarIOS.Item> </TabBarIOS> ); } } // const styles = StyleSheet.create({ // container: { // flex: 1, // justifyContent: 'center', // alignItems: 'center', // backgroundColor: '#F5FCFF', // }, // welcome: { // fontSize: 20, // textAlign: 'center', // margin: 10, // }, // instructions: { // textAlign: 'center', // color: '#333333', // marginBottom: 5, // }, // }); AppRegistry.registerComponent('BookSearch', () => BookSearch);
react/features/base/react/components/web/BaseIndicator.js
jitsi/jitsi-meet
/* @flow */ import { makeStyles } from '@material-ui/core'; import React from 'react'; import { translate } from '../../../i18n'; import { Icon } from '../../../icons'; import { Tooltip } from '../../../tooltip'; /** * The type of the React {@code Component} props of {@link BaseIndicator}. */ type Props = { /** * Additional CSS class name. */ className: string, /** * The icon component to use. */ icon: Object, /** * The CSS classnames to set on the icon element of the component. */ iconClassName: string, /** * The color of the icon. */ iconColor: ?string, /** * Id of the icon to be rendered. */ iconId?: string, /** * The font size for the icon. */ iconSize: string, /** * The ID attribute to set on the root element of the component. */ id: string, /** * Invoked to obtain translated strings. */ t: Function, /** * The translation key to use for displaying a tooltip when hovering over * the component. */ tooltipKey: string, /** * From which side of the indicator the tooltip should appear from, * defaulting to "top". */ tooltipPosition: string }; const useStyles = makeStyles(() => { return { indicator: { width: '20px', height: '20px', display: 'flex', alignItems: 'center', justifyContent: 'center' } }; }); /** * React {@code Component} for showing an icon with a tooltip. * * @returns {ReactElement} */ const BaseIndicator = ({ className = '', icon, iconClassName, iconColor, iconId, iconSize, id = '', t, tooltipKey, tooltipPosition = 'top' }: Props) => { const styles = useStyles(); const style = {}; if (iconSize) { style.fontSize = iconSize; } return ( <div className = { styles.indicator }> <Tooltip content = { t(tooltipKey) } position = { tooltipPosition }> <span className = { className } id = { id }> <Icon className = { iconClassName } color = { iconColor } id = { iconId } src = { icon } style = { style } /> </span> </Tooltip> </div> ); }; export default translate(BaseIndicator);
app/javascript/mastodon/features/notifications/components/clear_column_button.js
kazh98/social.arnip.org
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; export default class ClearColumnButton extends React.PureComponent { static propTypes = { onClick: PropTypes.func.isRequired, }; render () { return ( <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button> ); } }
src/Interpolate.js
Azerothian/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; import assign from './utils/Object.assign'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { format: React.PropTypes.string }, getDefaultProps() { return { component: 'span' }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = assign({}, this.props); delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
src/client.js
oxoooo/webpack-babel-react-startup
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './configureStore'; import App from './components/App'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
src/routes/content/index.js
mauphes/own-git-project
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Content from './Content'; import fetch from '../../core/fetch'; export default { path: '*', async action({ path }) { // eslint-disable-line react/prop-types const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: `{content(path:"${path}"){path,title,content,component}}`, }), credentials: 'include', }); if (resp.status !== 200) throw new Error(resp.statusText); const { data } = await resp.json(); if (!data || !data.content) return undefined; return <Content {...data.content} />; }, };
es6/Checkbox/CheckBoxButton.js
yurizhang/ishow
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import CheckBox from './CheckBox'; var CheckboxButton = function (_CheckBox) { _inherits(CheckboxButton, _CheckBox); function CheckboxButton() { _classCallCheck(this, CheckboxButton); return _possibleConstructorReturn(this, (CheckboxButton.__proto__ || Object.getPrototypeOf(CheckboxButton)).apply(this, arguments)); } _createClass(CheckboxButton, [{ key: 'render', value: function render() { var group = this.context.ElCheckboxGroup; return React.createElement( 'label', { style: this.style(), className: this.className('ishowcheckbox-button', group.props.size ? 'ishowcheckbox-button--' + group.props.size : '', { 'is-disabled': this.props.disabled, 'is-checked': this.state.checked, 'is-focus': this.state.focus }) }, React.createElement('input', { className: 'ishowcheckbox-button__original', type: 'checkbox', checked: this.state.checked, disabled: this.props.disabled, onFocus: this.onFocus.bind(this), onBlur: this.onBlur.bind(this), onChange: this.onChange.bind(this) }), React.createElement( 'span', { className: 'ishowcheckbox-button__inner', style: this.state.checked ? { boxShadow: '-1px 0 0 0 ' + group.props.fill, backgroundColor: group.props.fill || '', borderColor: group.props.fill || '', color: group.props.textColor || '' } : {} }, this.state.label || this.props.children ) ); } }]); return CheckboxButton; }(CheckBox); CheckboxButton.elementType = 'CheckboxButton'; export default CheckboxButton;
salt-frontend/react/dashboard/src/components/PortletUpdate.js
syakuis/salt-framework
import React from 'react'; import { connect } from 'react-redux'; import { updatePortlet } from '../actions'; class PortletUpdate extends React.Component { constructor(props) { super(props); this.initDataBind = this.initDataBind.bind(this); this.onUpdatePortlet = this.onUpdatePortlet.bind(this); } state = { ...this.props.dashboard[this.props.idx] } initDataBind(e) { let datatype = e.target.attributes.getNamedItem('datatype'); let value = e.target.value; if (datatype != null) { datatype = datatype.value; } switch(e.target.type) { case 'checkbox': value = e.target.checked; break; default: break; } switch(datatype) { case 'number': value = parseFloat(value); break; case 'boolean': if (typeof value === 'boolean') value = Boolean(value); break; } this.setState({[e.target.name]: value }); } onUpdatePortlet() { this.props.updatePortlet(this.state); this.props.onModalClose(); } render() { return ( <div> <div className="form-group"> <label htmlFor="padding">padding</label> <input type="text" className="form-control" placeholder="padding" name="padding" datatype="number" onChange={this.initDataBind} value={this.state.padding} /> </div> <div className="form-group"> <label htmlFor="static">static</label> <label className="checkbox-inline"> <input type="checkbox" name="static" datatype="boolean" checked={this.state.static} onChange={this.initDataBind} /> 사용 </label> </div> <div className="form-group"> <label htmlFor="draggable">draggable</label> <label className="checkbox-inline"> <input type="checkbox" name="isDraggable" datatype="boolean" onChange={this.initDataBind} checked={this.state.isDraggable} /> 사용 </label> </div> <div className="form-group"> <label htmlFor="resizable">resizable</label> <label className="checkbox-inline"> <input type="checkbox" name="isResizable" datatype="boolean" onChange={this.initDataBind} checked={this.state.isResizable} /> 사용 </label> </div> <button className="btn btn-default" type="button" onClick={this.onUpdatePortlet}>수정</button> </div> ); } } const mapStateToProps = (state) => { return { dashboard: state.portlet.dashboard }; } const mapDispatchToProps = (dispatch) => { return { updatePortlet: (portlet) => dispatch(updatePortlet(portlet)) } } export default PortletUpdate = connect( mapStateToProps, mapDispatchToProps )(PortletUpdate);
pootle/static/js/user/components/UserProfileForm.js
unho/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import { link } from 'autolinker'; import React from 'react'; import FormElement from 'components/FormElement'; import ModelFormMixin from 'mixins/ModelFormMixin'; import Avatar from 'components/Avatar'; // XXX: should probably live somewhere else function linkify(input) { return { __html: link(input), }; } export const UserProfileForm = React.createClass({ propTypes: { onDirty: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, }, mixins: [ModelFormMixin], /* Lifecycle */ componentWillUpdate(nextProps, nextState) { if (nextState.isDirty !== this.state.isDirty) { this.props.onDirty(nextState.isDirty); } }, fields: ['full_name', 'twitter', 'linkedin', 'website', 'bio'], /* Handlers */ handleSuccess(user) { this.props.onSuccess(user); }, /* Layout */ render() { const model = this.getResource(); const { errors } = this.state; const { formData } = this.state; const avatarHelpMsg = gettext( 'To set or change your avatar for your email address ' + '(%(email)s), please go to gravatar.com.' ); const avatarHelp = interpolate(avatarHelpMsg, { email: model.get('email') }, true); return ( <form method="post" id="item-form" autoComplete="off" onSubmit={this.handleFormSubmit} > <div className="fields"> <FormElement label={gettext('Full Name')} placeholder={gettext('Your Full Name')} autoFocus handleChange={this.handleChange} name="full_name" errors={errors.full_name} value={formData.full_name} /> <p> <label>{gettext('Avatar')}</label> <Avatar email={model.get('email')} size={48} /> <span className="helptext" dangerouslySetInnerHTML={linkify(avatarHelp)} /> </p> <p className="divider" /> <FormElement label={gettext('Twitter')} handleChange={this.handleChange} placeholder={gettext('Your Twitter username')} maxLength="15" name="twitter" errors={errors.twitter} value={formData.twitter} /> <FormElement label={gettext('LinkedIn')} handleChange={this.handleChange} placeholder={gettext('Your LinkedIn profile URL')} name="linkedin" errors={errors.linkedin} value={formData.linkedin} /> <FormElement label={gettext('Website')} handleChange={this.handleChange} placeholder={gettext('Your Personal website/blog URL')} name="website" errors={errors.website} value={formData.website} /> <FormElement type="textarea" label={gettext('Short Bio')} handleChange={this.handleChange} placeholder={gettext('Why are you part of our translation project? ' + 'Describe yourself, inspire others!')} name="bio" errors={errors.bio} value={formData.bio} /> </div> <p className="buttons"> <input type="submit" className="btn btn-primary" disabled={!this.state.isDirty} value={gettext('Save')} /> </p> </form> ); }, }); export default UserProfileForm;
components/connected/status/content/gallery/index.js
marrus-sh/mastodon-go
// <ConnectedStatusContentGallery> // =============================== // This component renders the attachments of a status in a nice // gallery. // * * * * * * * // // Imports: // -------- // Package imports. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; // Component imports. import { CommonButton, ConnectedMedia, } from 'themes/mastodon-go/components'; // Stylesheet imports. import './style.scss'; // * * * * * * * // // The component // ------------- // Component definition. export default class ConnectedStatusContentGallery extends React.PureComponent { // Constructor. constructor (props) { super(props); // State. this.state = { visible: !this.props.sensitive }; // Function binding. const { handleToggle } = Object.getPrototypeOf(this); this.handleToggle = handleToggle.bind(this); } // Handles showing and hiding media. handleToggle () { this.setState({ visible: !this.state.visible }); } // Renders. render () { const { handleToggle } = this; const { className, media, sensitive, ℳ, } = this.props; const { visible } = this.state; const computedClass = classNames('MASTODON_GO--CONNECTED--STATUS--CONTENT--GALLERY', 'size-' + media.size, className); // We can only use up to 4 attachments. const useäbleAttachments = media.take(4); // Renders the gallery. return ( <div className={computedClass}> {visible ? ( <CommonButton className='button' icon={visible ? 'eye' : 'eye-slash'} title={ℳ.hideMedia} onClick={handleToggle} /> ) : ( <CommonButton active className='curtain' title={ℳ.hideMedia} onClick={handleToggle} > <span> <strong>{sensitive ? ℳ.sensitive : ℳ.hidden}</strong> {ℳ.clickToView} </span> </CommonButton> )} {visible ? useäbleAttachments.map( attachment => ( <ConnectedMedia key={attachment.get('id')} id={attachment.get('id')} /> ) ) : null} </div> ); } } // Props. ConnectedStatusContentGallery.propTypes = { className: PropTypes.string, media: ImmutablePropTypes.list.isRequired, // A list of media to render in the gallery sensitive: PropTypes.bool, // `true` if the media is sensitive ℳ: PropTypes.func.isRequired, };