path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
client/src/app/install/install-step-3-database.js
opensupports/opensupports
import React from 'react'; import _ from 'lodash'; import history from 'lib-app/history'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import Button from 'core-components/button'; import Header from 'core-components/header'; import Form from 'core-components/form'; import FormField from 'core-components/form-field'; import SubmitButton from 'core-components/submit-button'; import Message from 'core-components/message'; class InstallStep3Database extends React.Component { state = { loading: false, error: false, showErrorMessage: true, errorMessage: '' }; render() { const { loading } = this.state; return ( <div className="install-step-3"> <Header title={i18n('STEP_TITLE', {title: i18n('DATABASE_CONFIGURATION'), current: 3, total: 6})} description={i18n('STEP_3_DESCRIPTION')} /> {this.renderMessage()} <Form loading={loading} onSubmit={this.onSubmit.bind(this)}> <FormField name="dbHost" label={i18n('DATABASE_HOST')} fieldProps={{size: 'large'}} required/> <FormField name="dbPort" label={i18n('DATABASE_PORT')} fieldProps={{size: 'large'}} infoMessage={i18n('DEFAULT_PORT')}/> <FormField name="dbName" label={i18n('DATABASE_NAME')} fieldProps={{size: 'large'}} infoMessage={i18n('LEFT_EMPTY_DATABASE')}/> <FormField name="dbUser" label={i18n('DATABASE_USER')} fieldProps={{size: 'large'}} required/> <FormField name="dbPassword" label={i18n('DATABASE_PASSWORD')} fieldProps={{size: 'large', password: true}}/> <div className="install-step-3__buttons"> <Button className="install-step-3__previous" disabled={loading} size="medium" onClick={this.onPreviousClick.bind(this)}>{i18n('PREVIOUS')}</Button> <SubmitButton className="install-step-3__next" size="medium" type="secondary">{i18n('NEXT')}</SubmitButton> </div> </Form> </div> ); } renderMessage() { const { error, errorMessage, showErrorMessage } = this.state; return ( error ? <Message showMessage={showErrorMessage} onCloseMessage={this.onCloseMessage.bind(this, "showErrorMessage")} className="install-step-3__message" type="error"> {i18n('ERROR_UPDATING_SETTINGS')}: {errorMessage} </Message> : null ); } onPreviousClick(event) { event.preventDefault(); history.push('/install/step-2'); } onSubmit(form) { this.setState({ loading: true }, () => { API.call({ path: '/system/init-database', data: _.extend({}, form, {dbPort: form.dbPort || 3306}) }) .then(() => history.push('/install/step-4')) .catch(({message}) => this.setState({ loading: false, error: true, showErrorMessage: true, errorMessage: message })); }); } onCloseMessage(showMessage) { this.setState({ [showMessage]: false }); } } export default InstallStep3Database;
src/SubcategoryList/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Spacer from '../Spacer'; import ProgressbarLabeledPercentage from '../ProgressbarLabeledPercentage'; import Typography from '../Typography'; import Wrapper from '../Wrapper'; import styles from './styles.css'; class SubcategoryList extends React.Component { renderBar() { const sortedCategories = this.props.sortedCategories; return sortedCategories.map((category, index) => { return ( <div key={index} > <ProgressbarLabeledPercentage categoryText={category.label} color={category.color} percent={category.percent} scaledPercent={category.scaledPercent} /> <Spacer size="double" /> </div> ); }); } render() { return ( <Wrapper className={styles.wrapper} size="standard" > <Typography type="bodyTextNormal" > {this.props.title} </Typography> <Spacer size="double" /> {this.renderBar()} </Wrapper> ); } } SubcategoryList.propTypes = { sortedCategories: PropTypes.array, title: PropTypes.string }; export default SubcategoryList;
src/lib/middlewares/htmlView.js
kaishui/pwfe-server
import React from 'react' import RenderFacade from './util/facade' import cache from '../common/cache' import env from '../common/env' const App = env.getParam('app') /** * 进行html模板渲染的组件。 * @param ctx * @param next */ async function htmlView(ctx, next) { if (ctx.isMatch) { //获取React静态文本和redux状态数据 const data = getData(ctx) writeCache(ctx) //写缓存 await ctx.render('index', { title: ctx.initName || env.getParam('defPageName'), root: data.document,//初始化Html state: data.state, //redux数据 seo: data.seo, //seo数据 params: { //服务器参数 initPath: ctx.url, //初始化访问的URL initId: ctx.initId //初始化访问的页面组件id } }) } else { return next() } } /** * 从上下文获取数据 * @param {object} ctx koa单次请求的上下文(request context) * @returns {object} {document:React渲染的HTML文本, state:store中的状态数据} */ const getData = (ctx) => { return ctx.isRender ? {document: ctx.reactDom, state: ctx.fluxStore.getState(), seo: ctx.seo} : {document: '', state: {}, seo :{}} } /** * 写缓存 * @param ctx */ const writeCache = (ctx) => { if (ctx.isCache) { const key = ctx.originalUrl //写缓存,缓存结构{html:,store:,component:} cache.get(key) || cache.set(key, { html: ctx.reactDom, store: ctx.fluxStore, component: {comp: ctx.initComp , id: ctx.initId}, dispathCount: ctx.dispathCount, seo : ctx.seo }, ctx.isCache.ttl) } } module.exports = htmlView
src/CarouselItem.js
omerts/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const CarouselItem = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, caption: React.PropTypes.node, index: React.PropTypes.number }, getInitialState() { return { direction: null }; }, getDefaultProps() { return { animation: true }; }, handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.handleAnimateOutEnd ); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render() { let classes = { item: true, active: (this.props.active && !this.props.animateIn) || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} {this.props.caption ? this.renderCaption() : null} </div> ); }, renderCaption() { return ( <div className="carousel-caption"> {this.props.caption} </div> ); } }); export default CarouselItem;
3-lifecycle-events/src/TodoList.js
mariusz-malinowski/tutorial-react
import React, { Component } from 'react'; import TodoItem from './TodoItem'; import AddTodo from './AddTodo'; class TodoList extends Component { constructor(props) { super(props); this.state = { todos: props.todos }; } onAddTodo = (todoName) => { this.setState({ todos: [{ name: todoName, completed: false }, ...this.state.todos] }); } render() { return ( <div> <AddTodo onAddTodo={this.onAddTodo} /> <ul> {this.state.todos.map((todo, index) => <TodoItem key={index} todo={todo}/>)} </ul> </div> ); } componentWillMount = () => { console.log('componentWillMount'); } componentDidMount = () => { console.log('componentDidMount'); } componentWillReceiveProps = (nextProps) => { console.log('componentWillReceiveProps'); // console.log('nextProps: ' + JSON.stringify(nextProps)); } shouldComponentUpdate = (nextProps, nextState) => { console.log('shouldComponentUpdate'); // console.log('nextProps: ' + JSON.stringify(nextProps)); // console.log('nextState: ' + JSON.stringify(nextState)); return true; } componentWillUpdate = (nextProps, nextState) => { console.log('componentWillUpdate'); // console.log('nextProps: ' + JSON.stringify(nextProps)); // console.log('nextState: ' + JSON.stringify(nextState)); } componentDidUpdate = (prevProps, prevState) => { console.log('componentDidUpdate'); // console.log('prevProps: ' + JSON.stringify(prevProps)); // console.log('prevState: ' + JSON.stringify(prevState)); } componentWillUnmount = () => { console.log('componentWillUnmount'); } } export default TodoList;
react-fundamentals-es6/lessons/06-refs/App.js
3mundi/React-Bible
// https://jsbin.com/qiwoxax/edit?js,output import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor(){ super(); this.state = { red: 0, green: 0, blue: 0 } this.update = this.update.bind(this) } update(e){ this.setState({ red: ReactDOM.findDOMNode(this.refs.red.refs.inp).value, green: ReactDOM.findDOMNode(this.refs.green.refs.inp).value, blue: ReactDOM.findDOMNode(this.refs.blue.refs.inp).value }) } render(){ return ( <div> <Slider ref="red" update={this.update} /> {this.state.red} <br /> <Slider ref="green" update={this.update} /> {this.state.green} <br /> <Slider ref="blue" update={this.update} /> {this.state.blue} <br /> </div> ); } } class Slider extends React.Component { render(){ return ( <div> <input ref="inp" type="range" min="0" max="255" onChange={this.props.update} /> </div> ); } } export default App
app/src/Frontend/modules/mission/components/page/index.js
ptphp/ptphp
/** * Created by jf on 15/12/10. */ "use strict"; import React from 'react'; var Tappable = require('react-tappable'); import './index.less'; export default React.createClass( { componentDidMount(){ const {title} = this.props; Utils.set_site_title(title); }, render() { const {title, subTitle, spacing, className, children,goBack,hideHeader} = this.props; let goBackFunc = ()=>{history.go(-1)}; if(typeof goBack == 'function') goBackFunc = goBack; //let h_style = Utils.is_weixin_browser() ? {display:"none"}:{}; let h_style = {}; if(hideHeader) h_style.display = "none"; return ( <section className={`page ${className}`}> <header style={h_style}> { goBack ? <Tappable component="button" onTap={goBackFunc} className="NavigationBarLeftButton has-arrow"> <span className="NavigationBarLeftArrow" >&#xe600;</span> </Tappable>:null } <h1 className="title">{title}</h1> <Tappable component="button" className="NavigationBarRightButton" /> </header> <div className={`bd ${spacing ? 'spacing' : ''}`}> {children} </div> </section> ); } });
src/components/animals/AnimalForm.spec.js
pisgrupo9/ash_web
import { expect } from 'chai'; import React from 'react'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import AnimalForm from './AnimalForm'; import { Checkbox } from 'react-bootstrap'; import ImagesDropzone from '../common/ImagesDropzone'; import ProfileDropzone from './ProfileDropzone'; import ModalAnimalButtons from '../common/ModalAnimalButtons'; import SelectInput from '../common/SelectInput'; import Input from '../common/Input'; function setup(animal, onSave, onCancel, speciesSelect) { let props = { animal, speciesSelect: speciesSelect, species: [], images: [], profilePic: '', onSave, onChange: () => {}, onCancel, onDrop: () => {}, onDelete: () => {}, onDropProfile: () => {}, errors: {} }; return shallow(<AnimalForm {...props}/>); } describe('Elementos del formulario de crear un animal', () => { it('exite el formulario', () => { expect(AnimalForm).to.exist; }); it('Existen los campos del formulario', () => { const animal = { species_id: '' }; const onSave = () => {}; const onCancel = () => {}; const wrapper = setup(animal, onSave, onCancel); expect(wrapper.find('div')).to.have.length(4); expect(wrapper.find(Input)).to.have.length(7); expect(wrapper.find(Input)['nodes'][0].props.name).to.equal('chip_num'); expect(wrapper.find(Input)['nodes'][1].props.name).to.equal('name'); expect(wrapper.find(Input)['nodes'][2].props.name).to.equal('weight'); expect(wrapper.find(Input)['nodes'][3].props.name).to.equal('admission_date'); expect(wrapper.find(Input)['nodes'][4].props.name).to.equal('race'); expect(wrapper.find(Input)['nodes'][5].props.name).to.equal('birthdate'); expect(wrapper.find(Input)['nodes'][6].props.name).to.equal('death_date'); expect(wrapper.find(SelectInput)).to.have.length(2); expect(wrapper.find(SelectInput)['node'].props.name).to.equal('sex'); expect(wrapper.find(SelectInput).last()['node'].props.name).to.equal('species_id'); expect(wrapper.find(ProfileDropzone)).to.have.length(1); expect(wrapper.find(ImagesDropzone)).to.have.length(1); }); it('Cuando el animal es perro se muestran las opciones de vacunado y castrado', () => { const animal = { species_id: '1' }; const speciesSelect = { id: 1, adoptable: true }; const onSave = () => {}; const onCancel = () => {}; const wrapper = setup(animal, onSave, onCancel, speciesSelect); expect(wrapper.find(Checkbox)['node'].props.name).to.equal('castrated'); expect(wrapper.find(Checkbox).last()['node'].props.name).to.equal('vaccines'); }); it('Cuando el animal es gato se muestran las opciones de vacunado y castrado', () => { const animal = { species_id: '2' }; const onSave = () => {}; const onCancel = () => {}; const speciesSelect = { id: 2, adoptable: true }; const wrapper = setup(animal, onSave, onCancel, speciesSelect); expect(wrapper.find(Checkbox)['node'].props.name).to.equal('castrated'); expect(wrapper.find(Checkbox).last()['node'].props.name).to.equal('vaccines'); }); it('Cuando el animal es de otra especie no se muestran las Checkbox', () => { const animal = { species_id: '3' }; const speciesSelect = { id: 2, adoptable: false }; const onSave = () => {}; const onCancel = () => {}; const wrapper = setup(animal, onSave, onCancel, speciesSelect); expect(wrapper.find(Checkbox).length).to.equal(0); }); it('Cuando el animal es de no tiene especie no se muestran las Checkbox', () => { const animal = {}; const speciesSelect = null; const onSave = () => {}; const onCancel = () => {}; const wrapper = setup(animal, onSave, onCancel, speciesSelect); expect(wrapper.find(Checkbox).length).to.equal(0); }); it('Donde están los botones dentro del formulario', () => { const animal = {}; const onSave = sinon.spy(); const onCancel = sinon.spy(); const wrapper = setup(animal, onSave, onCancel); expect(wrapper.find(ModalAnimalButtons)).to.have.length(1); expect(wrapper.find(ModalAnimalButtons)['node'].props.title).to.equal('INGRESAR'); }); });
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
TondaHack/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import './assets/style.css'; export default () => <p id="feature-css-inclusion">We love useless text.</p>;
src/style-controls-block.js
ryapapap/draft-editor
import React, { Component } from 'react'; import { EditorState, RichUtils } from 'draft-js'; import { StyleControls } from './style-controls-base'; export default class BlockStyleControls extends Component { static propTypes = { editorState: React.PropTypes.instanceOf(EditorState).isRequired, onChange: React.PropTypes.func.isRequired, } toggleBlockType = (type) => { this.props.onChange( RichUtils.toggleBlockType( this.props.editorState, type ) ); } isBlockActive = (type) => { const selection = this.props.editorState.getSelection(); const blockType = this.props.editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return type === blockType; } render() { return ( <StyleControls buttons={[ { icon: 'glyphicon glyphicon-header', style: 'header-two' }, { icon: 'glyphicon glyphicon-comment', style: 'blockquote' }, { icon: 'glyphicon glyphicon-list', style: 'unordered-list-item' }, { icon: 'glyphicon glyphicon-list-alt', style: 'ordered-list-item' }, { icon: 'glyphicon glyphicon-console', style: 'code-block' }, ]} isActive={this.isBlockActive} onToggle={this.toggleBlockType} /> ); } }
tests/components/Counter/Counter.spec.js
oliveirafabio/wut-blog
import React from 'react' import { bindActionCreators } from 'redux' import { Counter } from 'components/Counter/Counter' import { shallow } from 'enzyme' describe('(Component) Counter', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { counter: 5, ...bindActionCreators({ doubleAsync: (_spies.doubleAsync = sinon.spy()), increment: (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _wrapper = shallow(<Counter {..._props} />) }) it('Should render as a <div>.', () => { expect(_wrapper.is('div')).to.equal(true) }) it('Should render with an <h2> that includes Sample Counter text.', () => { expect(_wrapper.find('h2').text()).to.match(/Counter:/) }) it('Should render props.counter at the end of the sample counter <h2>.', () => { expect(_wrapper.find('h2').text()).to.match(/5$/) _wrapper.setProps({ counter: 8 }) expect(_wrapper.find('h2').text()).to.match(/8$/) }) it('Should render exactly two buttons.', () => { expect(_wrapper.find('button')).to.have.length(2) }) describe('An increment button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `increment` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.increment.should.have.been.called }); }) describe('A Double (Async) button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `doubleAsync` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.doubleAsync.should.have.been.called }); }) })
client/src/pages/Home.react.js
wenhao/fixed-asset
import React from 'react' import { RaisedButton, FontIcon, Paper, TextField } from 'material-ui' import { State } from 'react-router' import userApi from '../services/user' var Home = React.createClass({ mixins: [State], getInitialState() { return { title: '' } }, render() { return ( <Paper zDepth={1} className="page-auth"> <div className="login-group"> <RaisedButton className="login-button" secondary={true} onClick={this._login}> <FontIcon className="muidocs-icon-custom-github example-button-icon"/> <span className="mui-raised-button-label example-icon-button-label">Log in</span> </RaisedButton> </div> </Paper> ) }, _login(){ this.context.router.transitionTo('login'); } }); export default Home
example/examples/Callouts.js
jiaminglu/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, TouchableOpacity, } from 'react-native'; import MapView from 'react-native-maps'; import CustomCallout from './CustomCallout'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 31.23295; const LONGITUDE = 121.3822; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class Callouts extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, markers: [ { coordinate: { latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }, }, { coordinate: { latitude: LATITUDE, longitude: LONGITUDE, }, }, { coordinate: { latitude: LATITUDE + SPACE, longitude: LONGITUDE - SPACE, }, }, ], }; } show() { this.marker1.showCallout(); } hide() { this.marker1.hideCallout(); } render() { const { region, markers } = this.state; return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={region} > <MapView.Marker ref={ref => { this.marker1 = ref; }} coordinate={markers[0].coordinate} title="This is a native view" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation" // eslint-disable-line max-len /> <MapView.Marker coordinate={markers[1].coordinate} > <MapView.Callout style={styles.plainView}> <View> <Text>This is a plain view</Text> </View> </MapView.Callout> </MapView.Marker> <MapView.Marker coordinate={markers[2].coordinate} calloutOffset={{ x: -8, y: 28 }} calloutAnchor={{ x: 0.5, y: 0.4 }} > <MapView.Callout tooltip style={styles.customView}> <CustomCallout> <Text>This is a custom callout bubble view</Text> </CustomCallout> </MapView.Callout> </MapView.Marker> </MapView> <View style={styles.buttonContainer}> <View style={styles.bubble}> <Text>Tap on markers to see different callouts</Text> </View> </View> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => this.show()} style={[styles.bubble, styles.button]}> <Text>Show</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.hide()} style={[styles.bubble, styles.button]}> <Text>Hide</Text> </TouchableOpacity> </View> </View> ); } } Callouts.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ customView: { width: 140, height: 100, }, plainView: { width: 60, }, container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, bubble: { flex: 1, backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, latlng: { width: 200, alignItems: 'stretch', }, button: { width: 80, paddingHorizontal: 12, alignItems: 'center', marginHorizontal: 10, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = Callouts;
src/Parser/Warlock/Demonology/CHANGELOG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Chizu } from 'MAINTAINERS'; import Wrapper from 'common/Wrapper'; import ItemLink from 'common/ItemLink'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2017-09-30'), changes: <Wrapper>Added <ItemLink id={ITEMS.KAZZAKS_FINAL_CURSE.id} icon/> and <ItemLink id={ITEMS.WILFREDS_SIGIL_OF_SUPERIOR_SUMMONING.id} icon/> modules.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-30'), changes: <Wrapper>Added <ItemLink id={ITEMS.WAKENERS_LOYALTY.id} icon/>, <ItemLink id={ITEMS.RECURRENT_RITUAL.id} icon/>, <ItemLink id={ITEMS.SINDOREI_SPITE.id} icon/> modules.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-29'), changes: <Wrapper>Added T20 set bonuses.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-25'), changes: <Wrapper>Added rest of the talent modules - <SpellLink id={SPELLS.HAND_OF_DOOM_TALENT.id} icon/>, <SpellLink id={SPELLS.GRIMOIRE_OF_SACRIFICE_TALENT.id} icon/>, <SpellLink id={SPELLS.GRIMOIRE_OF_SYNERGY_TALENT.id} icon/>, <SpellLink id={SPELLS.SUMMON_DARKGLARE_TALENT.id} icon/> and <SpellLink id={SPELLS.DEMONBOLT_TALENT.id} icon/>.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-23'), changes: <Wrapper>Added second talent row modules - <SpellLink id={SPELLS.IMPENDING_DOOM_TALENT.id} icon/>, <SpellLink id={SPELLS.IMPROVED_DREADSTALKERS_TALENT.id} icon/> and <SpellLink id={SPELLS.IMPLOSION_TALENT.id} icon/>.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-19'), changes: <Wrapper>Added first talent row modules - <SpellLink id={SPELLS.SHADOWY_INSPIRATION_TALENT.id} icon/>, <SpellLink id={SPELLS.SHADOWFLAME_TALENT.id} icon/> and <SpellLink id={SPELLS.DEMONIC_CALLING_TALENT.id} icon/>.</Wrapper>, contributors: [Chizu], }, { date: new Date('2017-09-19'), changes: <Wrapper>Added the Soul Shard tracker.</Wrapper>, contributors: [Chizu], }, ];
src/components/CheckoutPane.js
longyarnz/WelFurnish-E-Commerce
import React, { Component } from 'react'; export default class CheckoutPane extends Component { constructor(props){ super(props); this._click = this._click.bind(this); this.state = { pane: "pane", mount: true } } _click(){ this.setState({pane: "delete-node"}); setTimeout(()=>this.props.remove(this.props.item), 800); } render(){ const { item, reNumber } = this.props; return !this.state.mount ? null : ( <div className={this.state.pane}> <aside className="checkout left-checkout"> <div>{item.title}</div> <div>₦ {reNumber(item.price)} &times; {item.qty}pcs</div> </aside> <aside className="checkout right-checkout"> <div>₦ {reNumber(item.price * item.qty)}</div> </aside> <aside className="checkout right-checkout final-checkout" onClick={this._click}> <div><i className="fa fa-times-circle" /></div> </aside> </div> ) } }
app/containers/HomePage/index.js
jilla720/messidge
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; // import Spinner from 'components/Spinner'; import Auth from 'containers/Auth'; import { LandingContainer } from './styled'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <LandingContainer> <Auth /> </LandingContainer> <div> zhjdkjhdjkjhsd </div> </div> ); } }
docs/src/app/components/pages/components/IconMenu/Page.js
tan-jerene/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconMenuReadmeText from './README'; import IconMenuExampleSimple from './ExampleSimple'; import iconMenuExampleSimpleCode from '!raw!./ExampleSimple'; import IconMenuExampleControlled from './ExampleControlled'; import iconMenuExampleControlledCode from '!raw!./ExampleControlled'; import IconMenuExampleScrollable from './ExampleScrollable'; import iconMenuExampleScrollableCode from '!raw!./ExampleScrollable'; import IconMenuExampleNested from './ExampleNested'; import iconMenuExampleNestedCode from '!raw!./ExampleNested'; import iconMenuCode from '!raw!material-ui/IconMenu/IconMenu'; const descriptions = { simple: 'Simple Icon Menus demonstrating some of the layouts possible using the `anchorOrigin` and `' + 'targetOrigin` properties.', controlled: 'Three controlled examples, the first allowing a single selection, the second multiple selections,' + ' the third using internal state.', scrollable: 'The `maxHeight` property limits the height of the menu, above which it will be scrollable.', nested: 'Example of nested menus within an IconMenu.', }; const IconMenusPage = () => ( <div> <Title render={(previousTitle) => `Icon Menu - ${previousTitle}`} /> <MarkdownElement text={iconMenuReadmeText} /> <CodeExample title="Icon Menu positioning" description={descriptions.simple} code={iconMenuExampleSimpleCode} > <IconMenuExampleSimple /> </CodeExample> <CodeExample title="Controlled Icon Menus" description={descriptions.controlled} code={iconMenuExampleControlledCode} > <IconMenuExampleControlled /> </CodeExample> <CodeExample title="Scrollable Icon Menu" description={descriptions.scrollable} code={iconMenuExampleScrollableCode} > <IconMenuExampleScrollable /> </CodeExample> <CodeExample title="Nested Icon Menus" description={descriptions.nested} code={iconMenuExampleNestedCode} > <IconMenuExampleNested /> </CodeExample> <PropTypeDescription code={iconMenuCode} /> </div> ); export default IconMenusPage;
server/frontend/src/index.js
cs472-spots/spots
// src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { hashHistory } from 'react-router'; import { Provider } from 'nectarine'; // eslint-disable-next-line import Store from './store/Store.js'; import Routes from './routes/index.js'; import './index.css'; //Renders the components passed by ReactDOM.render( <Provider store={Store}> <Routes history={hashHistory} /> </Provider>, document.getElementById('root') );
webapp/client/src/TourPage.js
mikemag/MonkeyCAM
/* * Copyright 2013-2017 Michael M. Magruder (https://github.com/mikemag) * * This source code is licensed under the Apache license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import { Grid, Row, Col, Panel, Thumbnail } from 'react-bootstrap'; import example_input_png from './media/Example_Input.png'; import example_results_png from './media/Example_Results.png'; import example_overview_svg from './media/Example_Overview.svg'; import example_core_jpg from './media/Example_Core.jpg'; class TourPage extends Component { componentDidMount() { window.scrollTo(0, 0); } render() { return ( <Grid> <Row> <Col sm={12}> <Panel header="How does it work?" bsStyle="primary"> <Row> <Col sm={12}> <h3 className="text-center"> Spend time building boards, not fiddling with CAD/CAM </h3> <br /> </Col> </Row> <Row> <Col sm={4}> <Panel> <h4>1. Design</h4> Enter your board design, binding layout, and CNC machine/materials config, then hit Run MonkeyCAM. </Panel> </Col> <Col sm={4}> <Panel> <h4>2. Download</h4> Confirm your design with the Results Overview, then download a .zip of all the G-Code files. </Panel> </Col> <Col sm={4}> <Panel> <h4>3. Build!</h4> Cut the core, base, and nose/tail fill with your CNC machine and get building! </Panel> </Col> </Row> <Row> <Col sm={8} smOffset={2}> <br /> <p className="text-center"> MonkeyCAM creates nine G-Code programs to cut all parts of a ski or snowboard on your CNC machine. For a real example of the results, see{' '} <span style={{ wordWrap: 'break-word' }}> <a href="https://monkeycam.org/results/5744863563743232"> https://monkeycam.org/results/5744863563743232 </a> </span> </p> <br /> </Col> </Row> </Panel> </Col> </Row> <Row> <Col sm={10} smOffset={1}> <Panel> <img style={{ maxWidth: '100%' }} src={example_input_png} alt="Example MonkeyCAM Input" /> <h3>Design</h3> <p> Enter your board design, binding layout, and machine/materials configuration in JSON format. Start with a sample ski, snowboard, or splitboard to make it easier. </p> <p> When you're ready, hit Run MonkeyCAM. The results will be ready in seconds. </p> </Panel> </Col> </Row> <Row> <Col sm={10} smOffset={1}> <Panel> <center> <img style={{ maxWidth: '100%' }} src={example_results_png} alt="Example MonkeyCAM Results" /> </center> <img width={'100%'} src={example_overview_svg} alt="Example MonkeyCAM Overview" /> <h3>Download</h3> <p> Check your output in the Results Overview, which shows the overall shape of the board and core, and a 2D visualization of every G-Code program. If you need to make adjustments, hit 'Change Design and Run Again' and tweak your design. </p> <p> When you're happy with the results, download a .zip of all of the G-Code files. These are kept in permanent storage at Google, so you can always go back and get them again. </p> </Panel> </Col> </Row> <Row> <Col sm={10} smOffset={1}> <Thumbnail style={{ maxWidth: '100%' }} src={example_core_jpg}> <h3>Build!</h3> <p> You get G-Code programs to cut the base, nose & tail spacers, and the core. Cut the parts with your CNC machine, and they'll all fit together perfectly! </p> <p> You'll be able to spend your time building boards and riding them. </p> </Thumbnail> </Col> </Row> </Grid> ); } } export default TourPage;
classic/src/scenes/wbfa/generated/FARBolt.pro.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faBolt } from '@fortawesome/pro-regular-svg-icons/faBolt' export default class FARBolt extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faBolt} />) } }
packages/vulcan-i18n/lib/modules/message.js
VulcanJS/Vulcan
import React, { Component } from 'react'; import { intlShape } from './shape'; import { registerComponent } from 'meteor/vulcan:lib'; const FormattedMessage = ({ id, values, defaultMessage = '', html = false, className = '' }, { intl }) => { let message = intl.formatMessage({ id, defaultMessage }, values); const cssClass = `i18n-message ${className}`; // if message is empty, use [id] if (message === '') { message = `[${id}]`; } return html ? <span data-key={id} className={cssClass} dangerouslySetInnerHTML={{__html: message}}/> : <span data-key={id} className={cssClass}>{message}</span>; }; FormattedMessage.contextTypes = { intl: intlShape }; registerComponent('FormattedMessage', FormattedMessage); export default FormattedMessage;
src/TPA/Label/Label.js
skyiea/wix-style-react
import React from 'react'; import {string} from 'prop-types'; import classNames from 'classnames'; import WixComponent from '../../BaseComponents/WixComponent'; import tpaStyleInjector from '../TpaStyleInjector'; let styles = {locals: {}}; try { styles = require('!css-loader?modules&camelCase&localIdentName="[path][name]__[local]__[hash:base64:5]"!sass-loader!./Label.scss'); } catch (e) { } class Label extends WixComponent { static propTypes = { LabelClassName: string }; static defaultProps = { LabelClassName: '' }; constructor(props) { super(props); //Used for testing enviorment, to mock the styles //TODO: remove this line once css loader mock solution will be found styles = props.styles || styles; } render() { return <label className={classNames(styles.locals.label, this.props.labelClassName)} htmlFor={this.props.for}>{this.props.children}</label>; } } Label.displayName = 'Label'; export default tpaStyleInjector(Label, styles);
src/components/views/globals/NewVersionBar.js
martindale/vector
/* Copyright 2015, 2016 OpenMarket Ltd 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. */ 'use strict'; import React from 'react'; import sdk from 'matrix-react-sdk'; import Modal from 'matrix-react-sdk/lib/Modal'; import PlatformPeg from 'matrix-react-sdk/lib/PlatformPeg'; import { _t } from 'matrix-react-sdk/lib/languageHandler'; /** * Check a version string is compatible with the Changelog * dialog ([vectorversion]-react-[react-sdk-version]-js-[js-sdk-version]) */ function checkVersion(ver) { const parts = ver.split('-'); return parts.length == 5 && parts[1] == 'react' && parts[3] == 'js'; } export default React.createClass({ propTypes: { version: React.PropTypes.string.isRequired, newVersion: React.PropTypes.string.isRequired, releaseNotes: React.PropTypes.string, }, displayReleaseNotes: function(releaseNotes) { const QuestionDialog = sdk.getComponent('dialogs.QuestionDialog'); Modal.createTrackedDialog('Display release notes', '', QuestionDialog, { title: _t("What's New"), description: <pre className="changelog_text">{releaseNotes}</pre>, button: _t("Update"), onFinished: (update) => { if(update && PlatformPeg.get()) { PlatformPeg.get().installUpdate(); } } }); }, displayChangelog: function() { const ChangelogDialog = sdk.getComponent('dialogs.ChangelogDialog'); Modal.createTrackedDialog('Display Changelog', '', ChangelogDialog, { version: this.props.version, newVersion: this.props.newVersion, onFinished: (update) => { if(update && PlatformPeg.get()) { PlatformPeg.get().installUpdate(); } } }); }, onUpdateClicked: function() { PlatformPeg.get().installUpdate(); }, render: function() { let action_button; // If we have release notes to display, we display them. Otherwise, // we display the Changelog Dialog which takes two versions and // automatically tells you what's changed (provided the versions // are in the right format) if (this.props.releaseNotes) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.displayReleaseNotes}> { _t("What's new?") } </button> ); } else if (checkVersion(this.props.version) && checkVersion(this.props.newVersion)) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.displayChangelog}> { _t("What's new?") } </button> ); } else if (PlatformPeg.get()) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.onUpdateClicked}> { _t("Update") } </button> ); } return ( <div className="mx_MatrixToolbar"> <img className="mx_MatrixToolbar_warning" src="img/warning.svg" width="24" height="23" alt="Warning"/> <div className="mx_MatrixToolbar_content"> {_t("A new version of Riot is available.")} </div> {action_button} </div> ); } });
app/javascript/mastodon/features/blocks/index.js
amazedkoumei/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchBlocks, expandBlocks } from '../../actions/blocks'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.blocks', defaultMessage: 'Blocked users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'blocks', 'items']), }); @connect(mapStateToProps) @injectIntl export default class Blocks extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchBlocks()); } handleLoadMore = debounce(() => { this.props.dispatch(expandBlocks()); }, 300, { leading: true }); render () { const { intl, accountIds, shouldUpdateScroll } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.blocks' defaultMessage="You haven't blocked any users yet." />; return ( <Column icon='ban' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='blocks' onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} > {accountIds.map(id => <AccountContainer key={id} id={id} /> )} </ScrollableList> </Column> ); } }
lib/component.js
bekher/hyperterm
import React from 'react'; import { StyleSheet, css } from 'aphrodite-simple'; import { shouldComponentUpdate } from 'react-addons-pure-render-mixin'; export default class Component extends React.Component { constructor () { super(); this.styles_ = this.createStyleSheet(); this.cssHelper = this.cssHelper.bind(this); if (!this.shouldComponentUpdate) { this.shouldComponentUpdate = shouldComponentUpdate.bind(this); } } createStyleSheet () { if (!this.styles) { return {}; } const styles = this.styles(); if ('object' !== typeof styles) { throw new TypeError('Component `styles` returns a non-object'); } return StyleSheet.create(this.styles()); } // wrap aphrodite's css helper for two reasons: // - we can give the element an unaltered global classname // that can be used to introduce global css side effects // for example, through the configuration, web inspector // or user agent extensions // - the user doesn't need to keep track of both `css` // and `style`, and we make that whole ordeal easier cssHelper (...args) { const classes = args .map((c) => { if (c) { // we compute the global name from the given // css class and we prepend the component name // it's important classes never get mangled by // uglifiers so that we can avoid collisions const component = this.constructor.name .toString() .toLowerCase(); const globalName = `${component}_${c}`; return [globalName, css(this.styles_[c])]; } }) // skip nulls .filter((v) => !!v) // flatten .reduce((a, b) => a.concat(b)); return classes.length ? classes.join(' ') : null; } render () { // convert static objects from `babel-plugin-transform-jsx` // to `React.Element`. if (!this.template) { throw new TypeError("Component doesn't define `template`"); } // invoke the template creator passing our css helper return this.template(this.cssHelper); } }
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/__tests__/Badge.spec.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import { shallow } from 'enzyme'; import { Badge } from '../'; describe('Badge', () => { it('should render a span by default', () => { const wrapper = shallow(<Badge>Yo!</Badge>); expect(wrapper.type()).toBe('span'); }); it('should render an anchor when when href is provided', () => { const wrapper = shallow(<Badge href="#">Yo!</Badge>); expect(wrapper.type()).toBe('a'); }); it('should render a custom tag when provided', () => { const wrapper = shallow(<Badge tag="main">Yo!</Badge>); expect(wrapper.type()).toBe('main'); }); it('should render children', () => { const wrapper = shallow(<Badge>Yo!</Badge>); expect(wrapper.text()).toBe('Yo!'); }); it('should render badges with secondary color', () => { const wrapper = shallow(<Badge>Default Badge</Badge>); expect(wrapper.hasClass('badge-secondary')).toBe(true); }); it('should render Badges with other colors', () => { const wrapper = shallow(<Badge color="danger">Danger Badge</Badge>); expect(wrapper.hasClass('badge-danger')).toBe(true); }); it('should render Badges as pills', () => { const wrapper = shallow(<Badge pill>Pill Badge</Badge>); expect(wrapper.hasClass('badge-pill')).toBe(true); }); });
test/components/Markdown-test.js
primozs/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import {test} from 'tape'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Markdown from '../../src/js/components/Markdown'; test('loads a paragraph Markdown', (t) => { t.plan(3); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(Markdown, { content: 'test', components: { p: { props: { className: 'testing', size: 'large' } } } })); const markdownElement = shallowRenderer.getRenderOutput(); t.equal( markdownElement.props.children.length, 1, 'Markdown has one children' ); const paragraph = markdownElement.props.children[0]; if (paragraph.props.className.indexOf('testing') > -1) { t.pass('Markdown paragraph has custom class'); } else { t.fail('Markdown paragraph does not have custom class'); } t.equal(paragraph.props.size, 'large', 'Markdown paragraph is large'); });
app/containers/LanguageProvider/index.js
shafeeqonline/xt-quiz-app
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
docs/src/sections/TransitionSection.js
mmarcant/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function TransitionSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="transitions">Transitions</Anchor> <small>Collapse, Fade</small> </h2> <p>Transition components animate their children transitioning in and out.</p> <h3> <Anchor id="transitions-collapse">Collapse</Anchor> </h3> <p>Add a collapse toggle animation to an element or component.</p> <div className="bs-callout bs-callout-info"> <h4>Smoothing animations</h4> <p> If you're noticing choppy animations, and the component that's being collapsed has non-zero margin or padding, try wrapping the contents of your <code>&lt;Collapse&gt;</code> {" "}inside a node with no margin or padding, like the <code>&lt;div&gt;</code> in the example below. This will allow the height to be computed properly, so the animation can proceed smoothly. </p> </div> <ReactPlayground codeText={Samples.Collapse} /> <h4><Anchor id="transitions-collapse-props">Props</Anchor></h4> <PropTable component="Collapse"/> <h3> <Anchor id="transitions-fade">Fade</Anchor> </h3> <p>Add a fade animation to a child element or component.</p> <ReactPlayground codeText={Samples.Fade} /> <h4><Anchor id="transitions-fade-props">Props</Anchor></h4> <PropTable component="Fade"/> </div> ); }
fluxArchitecture/src/js/main.js
3mundi/React-Bible
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/app' ReactDOM.render(<App />, document.getElementById('main'));
src/BootstrapMixin.js
kwnccc/react-bootstrap
import React from 'react'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const BootstrapMixin = { propTypes: { /** * bootstrap className * @private */ bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES), /** * Style variants * @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")} */ bsStyle: React.PropTypes.oneOf(styleMaps.STYLES), /** * Size variants * @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")} */ bsSize: CustomPropTypes.keyOf(styleMaps.SIZES) }, getBsClassSet() { let classes = {}; let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; let prefix = bsClass + '-'; let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } if (this.props.bsStyle) { if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) { classes[prefix + this.props.bsStyle] = true; } else { classes[this.props.bsStyle] = true; } } } return classes; }, prefixClass(subClass) { return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass; } }; export default BootstrapMixin;
web/react/src/client/pages/BadOS/BadOS.js
JamesMillercus/Portfolio-Website
import React, { Component } from 'react'; import Error from './../../components/locs/Error/Error'; class BadOS extends Component { render() { /** LOGIC FOR DISPLAYING CONTENT CORRECLTY ON DEVICE + BROWSER **/ const htext = "This website can't be displayed on old devices"; const ptext = 'Please update your device so it is running either iOS version 10.3 or Android version 4 (or higher). Alternatively please view this site on a newer device.'; return <Error header={htext} paragraph={ptext} />; } } // take props from admins and pass them into require Auth export default BadOS;
docs/src/stories/SubComponents.js
byumark/react-table
/* eslint-disable import/no-webpack-loader-syntax */ import React from 'react' import _ from 'lodash' import namor from 'namor' import ReactTable from '../../../lib/index' class Story extends React.PureComponent { constructor (props) { super(props) const data = _.map(_.range(5553), d => { return { firstName: namor.generate({words: 1, numLen: 0}), lastName: namor.generate({words: 1, numLen: 0}), age: Math.floor(Math.random() * 30) } }) this.state = { tableOptions: { loading: false, showPagination: true, showPageSizeOptions: true, showPageJump: true, collapseOnSortingChange: true, collapseOnPageChange: true, collapseOnDataChange: true, freezeWhenExpanded: false, filterable: false, sortable: true, resizable: true }, data: data } this.setTableOption = this.setTableOption.bind(this) } render () { const columns = [{ Header: 'Name', columns: [{ Header: 'First Name', accessor: 'firstName' }, { Header: 'Last Name', id: 'lastName', accessor: d => d.lastName }] }, { Header: 'Info', columns: [{ Header: 'Age', accessor: 'age' }] }] return ( <div> <div> <h1>Table Options</h1> <table> <tbody> { Object.keys(this.state.tableOptions).map(optionKey => { const optionValue = this.state.tableOptions[optionKey] return ( <tr key={optionKey}> <td>{optionKey}</td> <td style={{paddingLeft: 10, paddingTop: 5}}> <input type='checkbox' name={optionKey} checked={optionValue} onChange={this.setTableOption} /> </td> </tr> ) }) } </tbody> </table> </div> <div className='table-wrap'> <ReactTable className='-striped -highlight' data={this.state.data} columns={columns} defaultPageSize={10} {...this.state.tableOptions} SubComponent={(row) => { return ( <div style={{padding: '20px'}}> <em>You can put any component you want here, even another React Table!</em> <br /> <br /> <ReactTable data={this.state.data} columns={columns} defaultPageSize={3} showPagination={false} SubComponent={(row) => { return ( <div style={{padding: '20px'}}> <em>It even has access to the row data: </em> <CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight> </div> ) }} /> </div> ) }} /> </div> <div style={{textAlign: 'center'}}> <br /> <em>Tip: Hold shift when sorting to multi-sort!</em> </div> </div> ) } setTableOption (event) { const target = event.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name this.setState({ tableOptions: { ...this.state.tableOptions, [name]: value } }) } } // Source Code const CodeHighlight = require('./components/codeHighlight').default const source = require('!raw!./SubComponents') export default () => ( <div> <Story /> <CodeHighlight>{() => source}</CodeHighlight> </div> )
web/src/modules/icons/Museum.js
HobartMakers/DigitalWalkingTours
import React from 'react' const MuseumIcon = props => <svg width="15px" height="15px" viewBox="0 0 15 15" style={{enableBackground: 'new 0 0 15 15',}} {...props} > <path id="path7509" d="M7.5,0L1,3.4453V4h13V3.4453L7.5,0z M2,5v5l-1,1.5547V13h13v-1.4453L13,10 V5H2z M4.6152,6c0.169-0.0023,0.3318,0.0639,0.4512,0.1836L7.5,8.6172l2.4336-2.4336c0.2445-0.2437,0.6402-0.2432,0.884,0.0013 C10.9341,6.3017,10.9997,6.46,11,6.625v4.2422c0.0049,0.3452-0.271,0.629-0.6162,0.6338c-0.3452,0.0049-0.629-0.271-0.6338-0.6162 c-0.0001-0.0059-0.0001-0.0118,0-0.0177V8.1328L7.9414,9.9414c-0.244,0.2433-0.6388,0.2433-0.8828,0L5.25,8.1328v2.7344 c0.0049,0.3452-0.271,0.629-0.6162,0.6338C4.2887,11.5059,4.0049,11.2301,4,10.8849c-0.0001-0.0059-0.0001-0.0118,0-0.0177V6.625 C4,6.2836,4.2739,6.0054,4.6152,6z"/> </svg> export default MuseumIcon
src/svg-icons/device/airplanemode-inactive.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAirplanemodeInactive = (props) => ( <SvgIcon {...props}> <path d="M13 9V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5v3.68l7.83 7.83L21 16v-2l-8-5zM3 5.27l4.99 4.99L2 14v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-3.73L18.73 21 20 19.73 4.27 4 3 5.27z"/> </SvgIcon> ); DeviceAirplanemodeInactive = pure(DeviceAirplanemodeInactive); DeviceAirplanemodeInactive.displayName = 'DeviceAirplanemodeInactive'; DeviceAirplanemodeInactive.muiName = 'SvgIcon'; export default DeviceAirplanemodeInactive;
src/admin/src/components/controls/renderers/render_number.js
jgretz/zen-express
import React from 'react'; export const renderNumber = (data) => ( <span>{data ? data.toLocaleString() : ''}</span> );
docs-ui/components/tableChart.stories.js
ifduyue/sentry
import React from 'react'; import {storiesOf} from '@storybook/react'; import {withInfo} from '@storybook/addon-info'; import {number, text, boolean, array} from '@storybook/addon-knobs'; import TableChart from 'app/components/charts/tableChart'; storiesOf('Charts/TableChart', module).add( 'default', withInfo( 'A simple table that can calculate totals and relative share as a bar inside of a row' )(() => { const ERROR_TYPE_DATA = [ ['TypeError', 50, 40, 30], ['SyntaxError', 40, 30, 20], ['NameError', 15, 15, 15], ['ZeroDivisionError', 20, 10, 0], ]; return ( <TableChart data={ERROR_TYPE_DATA} dataStartIndex={number('Data Start Index', 1)} showRowTotal={boolean('Show Row Total', true)} showColumnTotal={boolean('Show Column Total', true)} shadeRowPercentage={boolean('Shade Row %', true)} headers={array('Headers', [ text('Column 1', 'Exception Type'), text('Column 2', 'Project 1'), text('Column 3', 'Project 2'), text('Column 4', 'Project 3'), ])} widths={array('Widths', [ number('Column 1', null), number('Column 2', 100), number('Column 3', 100), number('Column 4', 100), ])} rowTotalLabel={text('Row Total Label', 'Row Total')} rowTotalWidth={number('Row Total Column Width', 120)} /> ); }) );
text-dream/webapp/src/components/heads/DreamHeadComponent.js
PAIR-code/interpretability
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * 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'; import PropTypes from 'prop-types'; import {Grid, Typography, Tooltip, Paper} from '@material-ui/core'; import ReconstructSentence from '../reconstruct/ReconstructSentence'; /** * Providing a Heading Component for Dreaming Cards. */ class DreamHead extends React.Component { /** * Renders the heading component. * * @return {jsx} the heading component to be rendered. */ render() { return ( <Grid item> <Paper className='subHeadingPaper' style={{backgroundColor: '#DDDDDD'}} square> <Grid container direction='row' spacing={1} alignItems="center"> <Tooltip title="Input Sentence" placement="top"> <Grid item style={{width: this.props.sentenceParams.headWidth}}> <Typography variant="body1" color="inherit"> I </Typography> </Grid> </Tooltip> <Grid item> <ReconstructSentence sentence={this.props.params.tokens} target={this.props.sentenceParams.target} original={this.props.sentenceParams.target} colors={this.props.sentenceParams.colors}/> </Grid> </Grid> </Paper> </Grid> ); } } DreamHead.propTypes = { params: PropTypes.object.isRequired, sentenceParams: PropTypes.object.isRequired, }; export default DreamHead;
assets/javascripts/sso/components/AdminIndexCard.js
laincloud/sso
import StyleSheet from 'react-style'; import React from 'react'; import {History} from 'react-router'; let AdminIndexCard = React.createClass({ mixins: [History], render() { const buttons = [ { title: "我的应用管理", target: "apps" }, { title: "我的群组管理", target: "groups" }, { title: "用户管理-管理员特供", target: "users" }, ]; return ( <div className="mdl-card mdl-shadow--2dp" styles={[this.styles.card, this.props.style]}> <div className="mdl-card__title"> <h2 className="mdl-card__title-text">自助服务</h2> </div> <div className="mdl-card__supporting-text" style={this.styles.supporting}> 这里提供了一些应用和群组的管理功能,用户管理属于管理员特供功能,非管理员同学请勿操作,如果有需要,请联系 LAIN 集群管理员。 </div> <div style={{ padding: 8 }}> { _.map(buttons, (btn) => { return ( <button className="mdl-button mdl-js-button mdl-button--accent mdl-js-ripple-effect" onClick={(evt) => this.adminAuthorize(btn.target)} key={btn.target} style={this.styles.buttons}> {btn.title} </button> ); }) } </div> </div> ); }, adminAuthorize(target) { this.history.pushState(null, `/spa/admin/${target}`); }, styles: StyleSheet.create({ card: { width: '100%', marginBottom: 16, minHeight: 50, }, buttons: { display: 'block', }, supporting: { borderTop: '1px solid rgba(0, 0, 0, .12)', borderBottom: '1px solid rgba(0, 0, 0, .12)', }, }), }); export default AdminIndexCard;
src/__mocks__/react-intl.js
shayc/cboard
import React from 'react'; const Intl = jest.genMockFromModule('react-intl'); // Here goes intl context injected into component, feel free to extend const intl = { formatMessage: ({ defaultMessage }) => defaultMessage }; Intl.injectIntl = Node => { const renderWrapped = props => <Node {...props} intl={intl} />; renderWrapped.displayName = Node.displayName || Node.name || 'Component'; return renderWrapped; }; module.exports = Intl;
examples/js/custom/csv-button/fully-custom-csv-button.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn, InsertButton } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class FullyCustomInsertButtonTable extends React.Component { createCustomExportCSVButton = (onClick) => { return ( <button style={ { color: 'red' } } onClick={ onClick }>Custom Export CSV Btn</button> ); } render() { const options = { exportCSVBtn: this.createCustomExportCSVButton }; return ( <BootstrapTable data={ products } options={ options } exportCSV> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
js/components/Header/6.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; const { popRoute, } = actions; class Header6 extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Header</Title> </Body> <Right> <Button transparent><Icon name="search" /></Button> <Button transparent><Icon name="heart" /></Button> <Button transparent><Icon name="more" /></Button> </Right> </Header> <Content padder> <Text> Header With multiple Icon Buttons </Text> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Header6);
packages/react-instantsearch-core/src/core/__tests__/createInstantSearchManager.js
algolia/react-instantsearch
import React from 'react'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import Enzyme, { mount } from 'enzyme'; import algoliasearch from 'algoliasearch/lite'; import { SearchResults } from 'algoliasearch-helper'; import createInstantSearchManager from '../createInstantSearchManager'; import { runAllMicroTasks } from '../../../../../test/utils'; import { InstantSearch, Index, SortBy, Configure, } from 'react-instantsearch-dom'; Enzyme.configure({ adapter: new Adapter() }); jest.useFakeTimers(); const runOnlyNextMicroTask = () => Promise.resolve(); const createSearchClient = () => ({ search: jest.fn(() => Promise.resolve({ results: [ { params: 'query=&hitsPerPage=10&page=0&facets=%5B%5D&tagFilters=', page: 0, hits: [], hitsPerPage: 10, nbPages: 0, processingTimeMS: 4, query: '', nbHits: 0, index: 'index', }, ], }) ), }); describe('createInstantSearchManager', () => { it('initializes the manager with an empty state', () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); expect(ism.store.getState()).toEqual({ error: null, isSearchStalled: true, metadata: [], results: null, searching: false, searchingForFacetValues: false, widgets: {}, }); expect(ism.widgetsManager.getWidgets()).toEqual([]); expect(ism.transitionState({})).toEqual({}); expect(ism.getWidgetsIds()).toEqual([]); }); describe('client hydratation', () => { it('hydrates the `searchClient` for a single index results', () => { const searchClient = algoliasearch('appId', 'apiKey', { _cache: true, // cache is not enabled by default inside Node }); // Skip this test with Algoliasearch API Client >= v4 // (cache is handled by the client ifself) if (searchClient.transporter) { return; } const resultsState = { metadata: [], rawResults: [ { index: 'index', query: 'query', }, ], state: { index: 'index', query: 'query', }, }; expect(Object.keys(searchClient.cache)).toHaveLength(0); createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(Object.keys(searchClient.cache)).toHaveLength(1); Object.keys(searchClient.cache).forEach((key) => { expect(typeof searchClient.cache[key]).toBe('string'); expect(JSON.parse(searchClient.cache[key])).toEqual({ results: [ { index: 'index', query: 'query', }, ], }); }); }); it('hydrates the `searchClient` for a multi index results', () => { const searchClient = algoliasearch('appId', 'apiKey', { _cache: true, // cache is not enabled by default inside Node }); // Skip this test with Algoliasearch API Client >= v4 // (cache is handled by the client ifself) if (searchClient.transporter) { return; } const resultsState = { metadata: [], results: [ { _internalIndexId: 'index1', rawResults: [ { index: 'index1', query: 'query1', }, ], state: { index: 'index1', query: 'query1', }, }, { _internalIndexId: 'index2', rawResults: [ { index: 'index2', query: 'query2', }, ], state: { index: 'index2', query: 'query2', }, }, ], }; expect(Object.keys(searchClient.cache)).toHaveLength(0); createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(Object.keys(searchClient.cache)).toHaveLength(1); Object.keys(searchClient.cache).forEach((key) => { expect(typeof searchClient.cache[key]).toBe('string'); expect(JSON.parse(searchClient.cache[key])).toEqual({ results: [ { index: 'index1', query: 'query1', }, { index: 'index2', query: 'query2', }, ], }); }); }); it('does not hydrate the `searchClient` without results', () => { const searchClient = algoliasearch('appId', 'apiKey'); // Skip this test with Algoliasearch API Client >= v4 // (cache is handled by the client ifself) if (searchClient.transporter) { return; } expect(Object.keys(searchClient.cache)).toHaveLength(0); createInstantSearchManager({ indexName: 'index', searchClient, }); expect(Object.keys(searchClient.cache)).toHaveLength(0); }); it("does not hydrate the `searchClient` if it's not an Algolia client", () => { const searchClient = { _useCache: true, cache: {}, }; // Skip this test with Algoliasearch API Client >= v4 // (cache is handled by the client ifself) if (searchClient.transporter) { return; } const resultsState = { metadata: [], rawResults: [ { index: 'indexName', query: 'query', }, ], state: { index: 'indexName', query: 'query', }, }; expect(Object.keys(searchClient.cache)).toHaveLength(0); createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(Object.keys(searchClient.cache)).toHaveLength(0); }); it('does not hydrate the `searchClient` without cache enabled', () => { const searchClient = algoliasearch('appId', 'apiKey', { _cache: false, }); // Skip this test with Algoliasearch API Client >= v4 // (cache is handled by the client ifself) if (searchClient.transporter) { return; } const resultsState = { metadata: [], rawResults: [ { index: 'indexName', query: 'query', }, ], state: { index: 'indexName', query: 'query', }, }; expect(Object.keys(searchClient.cache)).toHaveLength(0); createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(Object.keys(searchClient.cache)).toHaveLength(0); }); it('when using algoliasearch@v4, it overrides search only once', () => { const searchClient = algoliasearch('appId', 'apiKey', { _cache: true, }); // Skip this test with Algoliasearch API Client < v4, as // search does not need to be overridden. if (!searchClient.transporter) { return; } const resultsState = { metadata: [], rawResults: [ { index: 'indexName', query: 'query', }, ], state: { index: 'indexName', query: 'query', }, }; const originalSearch = algoliasearch.search; createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(searchClient.search).not.toBe(originalSearch); const alreadyOverridden = jest.fn(); searchClient.search = alreadyOverridden; createInstantSearchManager({ indexName: 'index', searchClient, resultsState, }); expect(searchClient.search).toBe(alreadyOverridden); }); }); describe('results hydration', () => { it('initializes the manager with a single index hydrated results', () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), resultsState: { metadata: [], rawResults: [ { index: 'indexName', query: 'query', }, ], state: { index: 'indexName', query: 'query', }, }, }); expect(ism.store.getState().results).toBeInstanceOf(SearchResults); expect(ism.store.getState().results.query).toEqual('query'); }); it('initializes the manager with a multi index hydrated results', () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), resultsState: { metadata: [], results: [ { _internalIndexId: 'index1', rawResults: [ { index: 'index1', query: 'query1', }, ], state: { index: 'index1', query: 'query1', }, }, { _internalIndexId: 'index2', rawResults: [ { index: 'index2', query: 'query2', }, ], state: { index: 'index2', query: 'query2', }, }, ], }, }); expect(ism.store.getState().results.index1.query).toBe('query1'); expect(ism.store.getState().results.index1).toBeInstanceOf(SearchResults); expect(ism.store.getState().results.index2.query).toBe('query2'); expect(ism.store.getState().results.index2).toBeInstanceOf(SearchResults); }); }); describe('metadata hydration', () => { test('replaces value with a function returning empty search state', () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), resultsState: { metadata: [ { stuff: 1, items: [{ stuff: 2, items: [{ stuff: 3 }] }] }, ], rawResults: [ { index: 'indexName', query: 'query', }, ], state: { index: 'indexName', query: 'query', }, }, }); const hydratedMetadata = ism.store.getState().metadata; expect(hydratedMetadata).toEqual([ { value: expect.any(Function), stuff: 1, items: [ { value: expect.any(Function), stuff: 2, items: [ { value: expect.any(Function), stuff: 3, }, ], }, ], }, ]); expect(hydratedMetadata[0].value()).toEqual({}); expect(hydratedMetadata[0].items[0].value()).toEqual({}); expect(hydratedMetadata[0].items[0].items[0].value()).toEqual({}); }); }); describe('widget manager', () => { it('triggers a search when a widget is added', async () => { const searchClient = createSearchClient({}); const ism = createInstantSearchManager({ indexName: 'index', searchClient, }); ism.widgetsManager.registerWidget({ getSearchParameters: () => ({}), props: {}, context: {}, }); expect(ism.store.getState().searching).toBe(false); await runOnlyNextMicroTask(); expect(ism.store.getState().searching).toBe(true); await runAllMicroTasks(); expect(ism.store.getState().searching).toBe(false); }); }); describe('transitionState', () => { it('executes widgets hook', () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); ism.widgetsManager.registerWidget({ transitionState: (next, current) => { expect(next).toEqual({}); return { ...current, a: 1, }; }, }); ism.widgetsManager.registerWidget({ transitionState: (next, current) => { expect(next).toEqual({}); return { ...current, b: 2, }; }, }); expect(ism.transitionState()).toEqual({ a: 1, b: 2, }); }); }); describe('getWidgetsIds', () => { it('returns the list of ids of all registered widgets', async () => { const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); expect(ism.getWidgetsIds()).toEqual([]); ism.widgetsManager.registerWidget({ getMetadata: () => ({ id: 'a' }) }); ism.widgetsManager.registerWidget({ getMetadata: () => ({ id: 'b' }) }); ism.widgetsManager.registerWidget({ getMetadata: () => ({ id: 'c' }) }); ism.widgetsManager.registerWidget({ getMetadata: () => ({ id: 'd' }) }); await runAllMicroTasks(); expect(ism.getWidgetsIds()).toEqual(['a', 'b', 'c', 'd']); }); }); describe('getSearchParameters', () => { it('expects a widget top level to be shared between main and derived parameters', () => { // <InstantSearch indexName="index"> // <SearchBox defaultRefinement="shared" /> // <Index indexId="main" indexName="main" /> // </InstantSearch> const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); // <SearchBox defaultRefinement="shared" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setQuery('shared'); }, context: {}, props: {}, }); // <Index indexId="main" indexName="main" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setIndex('main'); }, props: { indexId: 'main', }, }); const { mainParameters, derivedParameters } = ism.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index', query: 'shared', }) ); expect(derivedParameters).toEqual([ { indexId: 'main', parameters: expect.objectContaining({ index: 'main', query: 'shared', }), }, ]); }); it('expects a widget with the same id than the indexName to be a main parameters', () => { // <InstantSearch indexName="index"> // <Index indexId="index" indexName="main" /> // </InstantSearch> const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); // <Index indexId="index" indexName="main" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setIndex('main'); }, context: {}, props: { indexId: 'index', }, }); const { mainParameters, derivedParameters } = ism.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'main', }) ); expect(derivedParameters).toEqual([]); }); it('expects a widget with a different id than the indexName to be a derived parameters', () => { // <InstantSearch indexName="index"> // <Index indexId="index_main" indexName="main" /> // </InstantSearch> const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); // <Index indexId="index_main" indexName="main" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setIndex('main'); }, context: {}, props: { indexId: 'index_main', }, }); const { mainParameters, derivedParameters } = ism.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index', }) ); expect(derivedParameters).toEqual([ { indexId: 'index_main', parameters: expect.objectContaining({ index: 'main', }), }, ]); }); it('expects a widget within a mutli index context with the same id than the indexName to be a main parameters', () => { // <InstantSearch indexName="index"> // <Index indexId="index" indexName="index" /> // <SearchBox defaultRefinement="main" /> // </Index> // </InstantSearch> const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); // <Index indexId="index" indexName="index" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setIndex('index'); }, context: {}, props: { indexId: 'index', }, }); // <Index indexId="index" indexName="index" /> // <SearchBox defaultRefinement="main" /> // </Index> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setQuery('main'); }, context: { multiIndexContext: { targetedIndex: 'index', }, }, props: {}, }); const { mainParameters, derivedParameters } = ism.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index', query: 'main', }) ); expect(derivedParameters).toEqual([]); }); it('expects a widget within a mutli index context with a different id than the indexName to be a derived parameters', () => { // <InstantSearch indexName="index"> // <Index indexId="index_with_refinement" indexName="index" /> // <SearchBox defaultRefinement="dervied" /> // </Index> // </InstantSearch> const ism = createInstantSearchManager({ indexName: 'index', searchClient: createSearchClient({}), }); // <Index indexId="index_with_refinement" indexName="index" /> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setIndex('index'); }, props: { indexId: 'index_with_refinement', }, }); // <Index indexId="index_with_refinement" indexName="index" /> // <SearchBox defaultRefinement="derived" /> // </Index> ism.widgetsManager.registerWidget({ getSearchParameters(state) { return state.setQuery('derived'); }, props: { indexContextValue: { targetedIndex: 'index_with_refinement', }, }, }); const { mainParameters, derivedParameters } = ism.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index', }) ); expect(derivedParameters).toEqual([ { indexId: 'index_with_refinement', parameters: expect.objectContaining({ index: 'index', query: 'derived', }), }, ]); }); it('expects widgets main parameters and derived parameters to be correctly calculated within a multi index context', () => { const wrapper = mount( <InstantSearch indexName="index1" searchClient={createSearchClient({})}> <Index indexName="bestbuy" /> <Index indexName="instant_search" /> <Index indexId="instant_search_apple" indexName="instant_search"> <Configure filters="brand:Apple" /> </Index> <Index indexId="instant_search_samsung" indexName="instant_search"> <Configure filters="brand:Samsung" /> </Index> <Index indexId="instant_search_microsoft" indexName="instant_search"> <Configure filters="brand:Microsoft" /> </Index> </InstantSearch> ); const { mainParameters, derivedParameters } = wrapper .instance() .state.instantSearchManager.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index1', }) ); expect(derivedParameters).toEqual([ expect.objectContaining({ indexId: 'bestbuy', parameters: expect.objectContaining({ index: 'bestbuy', }), }), expect.objectContaining({ indexId: 'instant_search', parameters: expect.objectContaining({ index: 'instant_search', }), }), expect.objectContaining({ indexId: 'instant_search_apple', parameters: expect.objectContaining({ index: 'instant_search', filters: 'brand:Apple', }), }), expect.objectContaining({ indexId: 'instant_search_samsung', parameters: expect.objectContaining({ index: 'instant_search', filters: 'brand:Samsung', }), }), expect.objectContaining({ indexId: 'instant_search_microsoft', parameters: expect.objectContaining({ index: 'instant_search', filters: 'brand:Microsoft', }), }), ]); }); it('expects widgets main parameters and derived parameters to be correctly calculated with SortBy within a multi index context', () => { const wrapper = mount( <InstantSearch indexName="index1" searchClient={createSearchClient({})}> <Index indexName="categories"> <SortBy defaultRefinement="bestbuy" items={[ { value: 'categories', label: 'Categories' }, { value: 'bestbuy', label: 'Best buy' }, ]} /> </Index> <Index indexName="products"> <SortBy defaultRefinement="brands" items={[ { value: 'products', label: 'Products' }, { value: 'brands', label: 'Brands' }, ]} /> </Index> </InstantSearch> ); const { mainParameters, derivedParameters } = wrapper .instance() .state.instantSearchManager.getSearchParameters(); expect(mainParameters).toEqual( expect.objectContaining({ index: 'index1', }) ); expect(derivedParameters).toEqual([ expect.objectContaining({ indexId: 'categories', parameters: expect.objectContaining({ index: 'bestbuy', }), }), expect.objectContaining({ indexId: 'products', parameters: expect.objectContaining({ index: 'brands', }), }), ]); }); }); describe('searchStalled', () => { it('should be updated if search is stalled', async () => { const searchClient = createSearchClient({}); const ism = createInstantSearchManager({ indexName: 'index', searchClient, }); ism.widgetsManager.registerWidget({ getMetadata: () => {}, transitionState: () => {}, }); expect(searchClient.search).not.toHaveBeenCalled(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: true, }); await runOnlyNextMicroTask(); expect(searchClient.search).toHaveBeenCalledTimes(1); expect(ism.store.getState()).toMatchObject({ isSearchStalled: true, }); jest.runAllTimers(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: true, }); await runOnlyNextMicroTask(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: false, }); ism.widgetsManager.update(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: false, }); await runOnlyNextMicroTask(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: false, }); jest.runAllTimers(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: true, }); await runOnlyNextMicroTask(); expect(ism.store.getState()).toMatchObject({ isSearchStalled: false, }); }); }); describe('client.search', () => { it('should be called when there is a new widget', async () => { const searchClient = createSearchClient({}); const ism = createInstantSearchManager({ indexName: 'index', searchClient, }); ism.widgetsManager.registerWidget({ getMetadata: () => {}, transitionState: () => {}, }); expect(searchClient.search).toHaveBeenCalledTimes(0); await runAllMicroTasks(); expect(searchClient.search).toHaveBeenCalledTimes(1); }); it('should be called when there is a new client', () => { const searchClient = createSearchClient({}); const nextSearchClient = createSearchClient({}); const ism = createInstantSearchManager({ indexName: 'index', searchClient, }); expect(searchClient.search).toHaveBeenCalledTimes(0); expect(nextSearchClient.search).toHaveBeenCalledTimes(0); ism.updateClient(nextSearchClient); expect(searchClient.search).toHaveBeenCalledTimes(0); expect(nextSearchClient.search).toHaveBeenCalledTimes(1); }); it('should not be called when the search is skipped', async () => { const searchClient = createSearchClient({}); const ism = createInstantSearchManager({ indexName: 'index', searchClient, }); ism.skipSearch(); ism.widgetsManager.registerWidget({ getMetadata: () => {}, transitionState: () => {}, }); await runAllMicroTasks(); expect(searchClient.search).toHaveBeenCalledTimes(0); }); }); });
app/components/material/Material_5.js
tw00089923/kcr_bom
import React from 'react'; import style from './Material.css'; import cx from 'classname'; import _ from 'lodash'; export default class Material_5 extends React.Component { constructor(props) { super(props); this.state ={ show_first:false, show_3_2_1:true, show_3_2_2:false, show_3_1:false, index_3_1_1:"00", index_3_1_2:"0", index_3_1_3:"00", index_3_1_4:"000" }; this.onChange = this.onChange.bind(this); this.upload = this.upload.bind(this); } show(){ this.setState({show_first:!this.state.show_first}); } upload(e){ let files = e.target.files; console.log(XLSX.read(files,{type: 'base64'})); console.log(f); } onChange(e){ if(e.target.name == "glup"){ this.setState({show_3_2_1:!this.state.show_3_2_1}); } if(e.target.name == "index_2_2"){ this.setState({index_2_1_2:e.target.value}); } if(e.target.name =="index_3_1"){ this.setState({index_3_1_1:e.target.value}); } if(e.target.name =="index_2_3"){ this.setState({index_2_1_3:e.target.value}); } if(e.target.name =="index_2_4"){ this.setState({index_2_1_4:e.target.value}); } } render() { const material_a_1 = ['塑膠粒、色母','普通式BB(COMMON)','分隔式BB(APART)','普通式BB-PCB','分隔式BB-PCB','普通式BB-KSP','分隔式BB-KSP','盒子式BOBBIN','盒子式COVER','抽式BOBBIN','抽式COVER','尼龍套、絕緣墊片','蓋子(網蓋、PT保護蓋)','支架、CHASSIS、CASE、底座、DOOR) 、間隔柱、銘板、腳墊','搖桿、滾子、插梢、輪','電源開關箱、輸入座','夾線槽、束線帶','護線環、固定扣(座)、櫬套、線材標示牌','端子板、補償片','把手、按鈕、開關','內外層式BB-內層P','內外層式BB-外層S','裝飾板、條、框、帶','KEYBOARD OVERLAY','LENS 透鏡','防水塞、滑槽,RING','其他(三通、由任)','雜項BOBBIN','SHEET PVC','MIRROR 鏡子','FORMER 玻璃纖維線軸','DAMPER 緩衝器','毛氈','球網、織布扣合','乒乓球','圍布','水槽' ]; const material_a_2 = ['固定用','稀釋用','硬化促進用','清潔用','塗裝用','散熱用','助焊用','COATING用','乾燥劑、防潮用','捺印用','防水/散熱','填充','營養液','其他']; const material_b_1 = [ 'ZYTEL NYLON RESIN 101L(N66)', 'ZYTEL 70G33L, 6410G5, 6210G6', 'FR-PET', 'VALOX THERMOPLASTIC', 'POPLYESTER (DR-48)', 'LEXAN POLYCARBONATE RESIN', '(P.C)', 'NORYL RESIN (N190J-7002)', ' (CFN3J-8007)', 'POLYCARBONATE MAKROLON', 'NO.6870', 'PHENLOIC MOLDING POWDER', '(電木)', 'P.V.C', 'POLYPHENYLENE SULFIDE', '(HW搖桿)', 'ABS', 'ACRYLICX, STYRENE-METHYL', 'METHACRYLATE', 'POLYDROPYLENE(聚丙稀)', 'RUBBER, EVA', 'DURACON(塑膠鋼)、POM', '其他,P.B.T', 'FLAME RETARDANT', 'POLYPROPYLENE SHEET', 'FRPP 301-18(FORMEX-18)', 'NORYL PPHOX SE-100 (F), AS', 'SPONGE(泡棉)', 'PP2654', 'MG-0033N', 'CM3001G-30', 'GFRP/CFRP', 'TEFLON', 'HPS', 'PC/ABS', 'VALOX M7002' ]; const material_b_2 =[ '凡立水、腊、樹脂', '固定劑、熱溶膠、膠粉', '稀釋劑', '硬化促進劑', '甲苯、汽油、香蕉水', '剝離劑', '凡士林、離形劑', '隔離膠、靜電劑', '潤滑油、防銹油', '油漆、噴漆、烤漆', '矽油膏', '助焊劑', '氣體 ', '防焊劑、', 'MTL CONATHANE', 'REDUCER (催化劑)', 'SILICA GEL (乾燥劑)', '墨水', '碳', '牛油', '其他', '營養液/肥料', '其他' ]; return ( <div> material_5 <div> <input type="file" onChange={this.upload}/> </div> </div> ); } }
node_modules/native-base/Components/Widgets/ProgressBar.android.js
tedsf/tiptap
/* @flow */ 'use strict'; import React from 'react'; import ProgressBar from "ProgressBarAndroid"; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; export default class SpinnerNB extends NativeBaseComponent { prepareRootProps() { var type = { height: 40 } var defaultProps = { style: type } return computeProps(this.props, defaultProps); } render() { return( <ProgressBar {...this.prepareRootProps()} styleAttr = "Horizontal" indeterminate = {false} progress={this.props.progress ? this.props.progress/100 : 0.5} color={this.props.color ? this.props.color : this.props.inverse ? this.getTheme().inverseProgressColor : this.getTheme().defaultProgressColor} /> ); } }
src/lib/plot/hint.js
jameskraus/react-vis
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import PureRenderComponent from '../pure-render-component'; import {getAttributeFunctor} from '../utils/scales-utils'; const ORIENTATION_AUTO = 'auto'; const ORIENTATION_TOPLEFT = 'topleft'; const ORIENTATION_BOTTOMLEFT = 'bottomleft'; const ORIENTATION_TOPRIGHT = 'topright'; const ORIENTATION_BOTTOMRIGHT = 'bottomright'; /** * Default format function for the value. * @param {Object} value Value. * @returns {Array} title-value pairs. */ function defaultFormat(value) { return Object.keys(value).map(function getProp(key) { return {title: key, value: value[key]}; }); } class Hint extends PureRenderComponent { static get propTypes() { return { marginTop: React.PropTypes.number, marginLeft: React.PropTypes.number, innerWidth: React.PropTypes.number, innerHeight: React.PropTypes.number, scales: React.PropTypes.object, value: React.PropTypes.object, format: React.PropTypes.func, orientation: React.PropTypes.oneOf([ ORIENTATION_AUTO, ORIENTATION_BOTTOMLEFT, ORIENTATION_BOTTOMRIGHT, ORIENTATION_TOPLEFT, ORIENTATION_TOPRIGHT ]) }; } static get defaultProps() { return { format: defaultFormat, orientation: ORIENTATION_AUTO }; } /** * Get the right coordinate of the hint. * @param {number} x X. * @returns {{right: *}} Mixin. * @private */ _getCSSRight(x) { const { innerWidth, marginRight} = this.props; return { right: `${marginRight + innerWidth - x}px` }; } /** * Get the left coordinate of the hint. * @param {number} x X. * @returns {{left: *}} Mixin. * @private */ _getCSSLeft(x) { const {marginLeft} = this.props; return { left: `${marginLeft + x}px` }; } /** * Get the bottom coordinate of the hint. * @param {number} y Y. * @returns {{bottom: *}} Mixin. * @private */ _getCSSBottom(y) { const { innerHeight, marginBottom} = this.props; return { bottom: `${marginBottom + innerHeight - y}px` }; } /** * Get the top coordinate of the hint. * @param {number} y Y. * @returns {{top: *}} Mixin. * @private */ _getCSSTop(y) { const {marginTop} = this.props; return { top: `${marginTop + y}px` }; } /** * Convert the "automatic" orientation to the real one depending on the values * of x and y. * @param {number} x X value. * @param {number} y Y value. * @returns {string} Orientation. * @private */ _getOrientationFromAuto(x, y) { const { innerWidth, innerHeight} = this.props; if (x > innerWidth / 2) { if (y > innerHeight / 2) { return ORIENTATION_TOPLEFT; } return ORIENTATION_BOTTOMLEFT; } if (y > innerHeight / 2) { return ORIENTATION_TOPRIGHT; } return ORIENTATION_BOTTOMRIGHT; } /** * Get a CSS mixin for a proper positioning of the element. * @param {string} orientation Orientation. * @param {number} x X position. * @param {number} y Y position. * @returns {Object} Object, that may contain `left` or `right, `top` or * `bottom` properties. * @private */ _getOrientationStyle(orientation, x, y) { let xCSS; let yCSS; if (orientation === ORIENTATION_BOTTOMLEFT || orientation === ORIENTATION_BOTTOMRIGHT) { yCSS = this._getCSSTop(y); } else { yCSS = this._getCSSBottom(y); } if (orientation === ORIENTATION_TOPLEFT || orientation === ORIENTATION_BOTTOMLEFT) { xCSS = this._getCSSRight(x); } else { xCSS = this._getCSSLeft(x); } return { ...xCSS, ...yCSS }; } /** * Get the class name from orientation value. * @param {string} orientation Orientation. * @returns {string} Class name. * @private */ _getOrientationClassName(orientation) { return `rv-hint--orientation-${orientation}`; } /** * Get the position for the hint and the appropriate class name. * @returns {{style: Object, className: string}} Style and className for the * hint. * @private */ _getPositionInfo() { const { value, orientation: initialOrientation} = this.props; const x = getAttributeFunctor(this.props, 'x')(value); const y = getAttributeFunctor(this.props, 'y')(value); const orientation = initialOrientation === ORIENTATION_AUTO ? this._getOrientationFromAuto(x, y) : initialOrientation; return { style: this._getOrientationStyle(orientation, x, y), className: this._getOrientationClassName(orientation) }; } render() { const { value, format, children} = this.props; const {style, className} = this._getPositionInfo(); return ( <div className={`rv-hint ${className}`} style={{ ... style, position: 'absolute' }}> {children ? children : <div className="rv-hint__content"> {format(value).map((formattedProp, i) => <div key={`rv-hint${i}`}> <span className="rv-hint__title">{formattedProp.title}</span> {': '} <span className="rv-hint__value">{formattedProp.value}</span> </div> )} </div> } </div> ); } } Hint.displayName = 'Hint'; export default Hint;
src/components/UserList/UserList.js
Pamplemaus/raincloud
import React from 'react'; import UserItem from '../UserItem/UserItem'; import styles from './UserList.scss'; const UserList = ({ users, removeUser, togglePlaylist }) => { return( <div className={styles.userlist}> { users.map((user) => ( <UserItem key={user.id} selected={user.selected} image={user.avatar_url} username={user.username} removeUser={removeUser} togglePlaylist={togglePlaylist}/> )) } </div> ); }; export default UserList;
frontend/src/components/common/pagination.js
unicef/un-partner-portal
import React, { Component } from 'react'; import withStyles from 'material-ui/styles/withStyles'; import IconButton from 'material-ui/IconButton'; import Input from 'material-ui/Input'; import { MenuItem } from 'material-ui/Menu'; import Select from 'material-ui/Select'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import KeyboardArrowLeft from 'material-ui-icons/KeyboardArrowLeft'; import KeyboardArrowRight from 'material-ui-icons/KeyboardArrowRight'; export const styles = theme => ({ root: { // Increase the specificity to override TableCell. '&:last-child': { padding: 0, }, }, toolbar: { height: 56, minHeight: 56, paddingRight: 2, }, spacer: { flex: '1 1 100%', }, caption: { flexShrink: 0, }, selectRoot: { marginRight: theme.spacing.unit * 4, }, select: { marginLeft: theme.spacing.unit, width: 34, textAlign: 'right', paddingRight: 22, color: theme.palette.text.secondary, height: 32, lineHeight: '32px', }, actions: { flexShrink: 0, color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); class Pagination extends Component { constructor() { super(); this.handleBackButtonClick = this.handleBackButtonClick.bind(this); this.handleNextButtonClick = this.handleNextButtonClick.bind(this); } componentWillReceiveProps({ count, onChangePage, rowsPerPage }) { const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); } handleBackButtonClick(event) { this.props.onChangePage(event, this.props.page - 1); } handleNextButtonClick(event) { this.props.onChangePage(event, this.props.page + 1); } render() { const { classes, colSpan: colSpanProp, count, labelDisplayedRows, labelRowsPerPage, onChangePage, onChangeRowsPerPage, page, rowsPerPage, rowsPerPageOptions, ...other } = this.props; let colSpan; return ( <div className={classes.root} colSpan={colSpan} {...other}> <Toolbar className={classes.toolbar}> <div className={classes.spacer} /> <Typography type="caption" className={classes.caption}> {labelRowsPerPage} </Typography> <Select classes={{ root: classes.selectRoot, select: classes.select }} input={<Input disableUnderline />} value={rowsPerPage} onChange={(event) => { onChangeRowsPerPage(event); }} > {rowsPerPageOptions.map(rowsPerPageOption => ( <MenuItem key={rowsPerPageOption} value={rowsPerPageOption}> {rowsPerPageOption} </MenuItem> ))} </Select> <Typography type="caption" className={classes.caption}> {labelDisplayedRows({ from: count === 0 ? 0 : (page - 1) * rowsPerPage + 1, to: Math.min(count, (page) * rowsPerPage), count, page, })} </Typography> <div className={classes.actions}> <IconButton onClick={this.handleBackButtonClick} disabled={page === 1}> <KeyboardArrowLeft /> </IconButton> <IconButton onClick={this.handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage)} > <KeyboardArrowRight /> </IconButton> </div> </Toolbar> </div> ); } } Pagination.defaultProps = { labelRowsPerPage: 'Items per page:', labelDisplayedRows: ({ from, to, count }) => `${from}-${to} of ${count}`, rowsPerPageOptions: [5, 10, 15], }; export default withStyles(styles, { name: 'Pagination' })(Pagination);
src/App.js
MichaelKohler/where
import React from 'react'; import Overview from './Overview'; import Footer from './Footer'; import './scss/app.scss'; const App = () => { return ( <div> <Overview /> <Footer /> </div> ); }; export default App;
src/Parser/DeathKnight/Shared/RuneDetails.js
hasseboulen/WoWAnalyzer
import React from 'react'; import { Scatter } from 'react-chartjs-2'; import Analyzer from 'Parser/Core/Analyzer'; import Tab from 'Main/Tab'; import { formatDuration } from 'common/format'; import RuneBreakdown from './RuneBreakdown'; import RuneTracker from './RuneTracker'; class RuneDetails extends Analyzer { static dependencies = { runeTracker: RuneTracker, }; formatLabel(number){ return formatDuration(number, 0); } render() { const labels = Array.from({length: Math.ceil(this.owner.fightDuration / 1000)}, (x, i) => i); const runeData = { labels: labels, datasets: [{ label: 'Runes', data: this.runeTracker.runesReady, backgroundColor: 'rgba(196, 31, 59, 0)', borderColor: 'rgb(196, 31, 59)', borderWidth: 2, pointStyle: 'line', }], }; const chartOptions = { showLines: true, elements: { point: { radius: 0 }, line: { tension: 0, skipNull: true, }, }, scales: { xAxes: [{ labelString: 'Time', ticks: { fontColor: '#ccc', callback: this.formatLabel, beginAtZero: true, stepSize: 10, max: this.owner.fightDuration / 1000, }, }], yAxes: [{ labelString: 'Runes', ticks: { fontColor: '#ccc', beginAtZero: true, }, }], }, }; return ( <div> <Scatter data={runeData} options={chartOptions} height={100} width={300} /> <RuneBreakdown tracker={this.runeTracker} showSpenders={true} /> </div> ); } tab() { return { title: 'Rune usage', url: 'rune-usage', render: () => ( <Tab title="Rune usage breakdown"> {this.render()} </Tab> ), }; } } export default RuneDetails;
src/svg-icons/device/usb.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceUsb = (props) => ( <SvgIcon {...props}> <path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"/> </SvgIcon> ); DeviceUsb = pure(DeviceUsb); DeviceUsb.displayName = 'DeviceUsb'; DeviceUsb.muiName = 'SvgIcon'; export default DeviceUsb;
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
yangchenghu/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import _ from 'lodash'; import React from 'react'; import classnames from 'classnames'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import Inputs from 'utils/Inputs'; import { KeyCodes } from 'constants/ActorAppConstants'; import MessageActionCreators from 'actions/MessageActionCreators'; import ComposeActionCreators from 'actions/ComposeActionCreators'; import GroupStore from 'stores/GroupStore'; import PreferencesStore from 'stores/PreferencesStore'; import ComposeStore from 'stores/ComposeStore'; import AvatarItem from 'components/common/AvatarItem.react'; import MentionDropdown from 'components/common/MentionDropdown.react'; import EmojiDropdown from 'components/common/EmojiDropdown.react'; let getStateFromStores = () => { return { text: ComposeStore.getText(), profile: ActorClient.getUser(ActorClient.getUid()), sendByEnter: PreferencesStore.isSendByEnterEnabled(), mentions: ComposeStore.getMentions() }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; constructor(props) { super(props); this.state = _.assign({ isEmojiDropdownShow: false }, getStateFromStores()); GroupStore.addChangeListener(this.onChange); ComposeStore.addChangeListener(this.onChange); PreferencesStore.addListener(this.onChange); } componentWillUnmount() { GroupStore.removeChangeListener(this.onChange); ComposeStore.removeChangeListener(this.onChange); } onChange = () => { this.setState(getStateFromStores()); }; onMessageChange = event => { const text = event.target.value; const { peer } = this.props; ComposeActionCreators.onTyping(peer, text, this.getCaretPosition()); }; onKeyDown = event => { const { mentions, sendByEnter } = this.state; if (mentions === null) { if (sendByEnter === true) { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } } else { if (event.keyCode === KeyCodes.ENTER && event.metaKey) { event.preventDefault(); this.sendTextMessage(); } } } }; sendTextMessage = () => { const { text } = this.state; const { peer } = this.props; if (text.trim().length !== 0) { MessageActionCreators.sendTextMessage(peer, text); } ComposeActionCreators.cleanText(); }; onSendFileClick = () => { const fileInput = React.findDOMNode(this.refs.composeFileInput); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = React.findDOMNode(this.refs.composePhotoInput); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const fileInput = React.findDOMNode(this.refs.composeFileInput); MessageActionCreators.sendFileMessage(this.props.peer, fileInput.files[0]); this.resetSendFileForm(); }; onPhotoInputChange = () => { console.debug('onPhotoInputChange'); const photoInput = React.findDOMNode(this.refs.composePhotoInput); MessageActionCreators.sendPhotoMessage(this.props.peer, photoInput.files[0]); this.resetSendFileForm(); }; resetSendFileForm = () => { const form = React.findDOMNode(this.refs.sendFileForm); form.reset(); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; onMentionSelect = (mention) => { const { peer } = this.props; const { text } = this.state; ComposeActionCreators.insertMention(peer, text, this.getCaretPosition(), mention); React.findDOMNode(this.refs.area).focus(); }; onMentionClose = () => { ComposeActionCreators.closeMention(); }; getCaretPosition = () => { const composeArea = React.findDOMNode(this.refs.area); const selection = Inputs.getInputSelection(composeArea); return selection.start; }; onEmojiDropdownSelect = (emoji) => { ComposeActionCreators.insertEmoji(this.state.text, this.getCaretPosition(), emoji); React.findDOMNode(this.refs.area).focus(); }; onEmojiDropdownClose = () => this.setState({isEmojiDropdownShow: false}); onEmojiShowClick = () => this.setState({isEmojiDropdownShow: true}); render() { const { text, profile, mentions, isEmojiDropdownShow } = this.state; const emojiOpenerClassName = classnames('emoji-opener material-icons hide', { 'emoji-opener--active': isEmojiDropdownShow }); return ( <section className="compose" onPaste={this.onPaste}> <MentionDropdown mentions={mentions} onSelect={this.onMentionSelect} onClose={this.onMentionClose}/> <EmojiDropdown isOpen={isEmojiDropdownShow} onSelect={this.onEmojiDropdownSelect} onClose={this.onEmojiDropdownClose}/> <i className={emojiOpenerClassName} onClick={this.onEmojiShowClick}>insert_emoticon</i> <AvatarItem className="my-avatar" image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onMessageChange} onKeyDown={this.onKeyDown} value={text} ref="area"/> <footer className="compose__footer row"> <button className="button attachment" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button attachment" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <button className="button button--lightblue" onClick={this.sendTextMessage}>Send</button> </footer> <form className="compose__hidden" ref="sendFileForm"> <input ref="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input ref="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </form> </section> ); } } export default ComposeSection;
src/components/SocialIcon/SocialIcon.js
denichodev/personal-web
import React from 'react'; import PropTypes from 'prop-types'; import './SocialIcon.css'; const SocialIcon = ({ to, className }) => { return ( <div> <a href={to} target="_blank" rel="noreferrer noopener"> <i className={`social-icon centered ${className}`} /> </a> </div> ); }; SocialIcon.propTypes = { to: PropTypes.string.isRequired, className: PropTypes.string.isRequired }; export default SocialIcon;
src/svg-icons/image/camera-front.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraFront = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/> </SvgIcon> ); ImageCameraFront = pure(ImageCameraFront); ImageCameraFront.displayName = 'ImageCameraFront'; ImageCameraFront.muiName = 'SvgIcon'; export default ImageCameraFront;
PeerAI/index.ios.js
peerism/peer.ai
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import MainApp from './src/MainApp'; AppRegistry.registerComponent('PeerAI', () => MainApp);
src/svg-icons/action/card-travel.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCardTravel = (props) => ( <SvgIcon {...props}> <path d="M20 6h-3V4c0-1.11-.89-2-2-2H9c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zM9 4h6v2H9V4zm11 15H4v-2h16v2zm0-5H4V8h3v2h2V8h6v2h2V8h3v6z"/> </SvgIcon> ); ActionCardTravel = pure(ActionCardTravel); ActionCardTravel.displayName = 'ActionCardTravel'; ActionCardTravel.muiName = 'SvgIcon'; export default ActionCardTravel;
Example/__tests__/index.ios.js
halilb/react-native-chess-board
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/components/bottomBar.item.js
pcyan/dva-example-rn
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, } from 'react-native'; import { IconToggle } from 'react-native-material-design'; const NORMAL_COLOR = '#2b2b2b'; const SELECTED_COLOR = '#006eff'; class Item extends Component { constructor(props) { super(props); let { onPress, selectedColor, normalColor, tabImage, tabText, isSelected } = props; if (!selectedColor) { selectedColor = SELECTED_COLOR; } if (!normalColor) { normalColor = NORMAL_COLOR; } if (!tabText) { tabText = ''; } if (!isSelected) { isSelected = false; } this.state = { onPress, selectedColor, normalColor, tabImage, tabText, isSelected, }; } render() { const { onPress, selectedColor, normalColor, tabImage, tabText } = this.state; return ( <IconToggle color="paperGrey900" style={{ padding: 4 }} onPress={onPress}> <View style={styles.item}> <Image style={styles.itemImage} tintColor={this.props.isSelected ? selectedColor : normalColor} source={tabImage} /> <Text style={styles.itemText}>{tabText}</Text> </View> </IconToggle> ); } } const styles = StyleSheet.create({ item: { minWidth: 60, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, itemText: { fontSize: 14, color: NORMAL_COLOR, }, itemImage: { height: 24, width: 24, }, }); export default Item;
examples/with-firebase-functions/src/server.js
jaredpalmer/react-production-starter
import App from './App'; import React from 'react'; import express from 'express'; import { renderToString } from 'react-dom/server'; const assets = require(process.env.RAZZLE_ASSETS_MANIFEST); const server = express(); server .disable('x-powered-by') .use(express.static(process.env.RAZZLE_PUBLIC_DIR)) .get('/*', (req, res) => { const markup = renderToString(<App />); res.send( `<!doctype html> <html lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charSet='utf-8' /> <title>Welcome to Razzle</title> <meta name="viewport" content="width=device-width, initial-scale=1"> ${assets.client.css ? `<link rel="stylesheet" href="${assets.client.css}">` : ''} ${process.env.NODE_ENV === 'production' ? `<script src="${assets.client.js}" defer></script>` : `<script src="${assets.client.js}" defer crossorigin></script>`} </head> <body> <div id="root">${markup}</div> </body> </html>` ); }); export default server;
docs/app/Examples/collections/Table/Variations/TableExampleTextAlign.js
clemensw/stardust
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleTextAlign = () => { return ( <Table striped> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell textAlign='right'>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row textAlign='center'> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell textAlign='right'>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell textAlign='right'>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell textAlign='right'>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleTextAlign
src/components/Header/Header.js
rickyduck/pp-frontend
import React from 'react' import { IndexLink, Link } from 'react-router' import './Header.scss' export const Header = () => ( <div> </div> ) export default Header
app/components/App.js
erlswtshrt/react-es6-boilerplate
import React from 'react'; class App extends React.Component { render() { return ( <div> {this.props.children} </div> ); } } export default App;
src/index.js
hartzis/react-redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, connect } = createAll(React);
frontend/src/Calendar/Legend/LegendItem.js
lidarr/Lidarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import titleCase from 'Utilities/String/titleCase'; import styles from './LegendItem.css'; function LegendItem(props) { const { name, status, tooltip, colorImpairedMode } = props; return ( <div className={classNames( styles.legendItem, styles[status], colorImpairedMode && 'colorImpaired' )} title={tooltip} > {name ? name : titleCase(status)} </div> ); } LegendItem.propTypes = { name: PropTypes.string, status: PropTypes.string.isRequired, tooltip: PropTypes.string.isRequired, colorImpairedMode: PropTypes.bool.isRequired }; export default LegendItem;
src/client/tests/components/home/hompage.spec.js
kingisaac95/docmanager
import React from 'react'; import expect from 'expect'; import { shallow } from 'enzyme'; import SignInForm from '../../../components/home/SignInForm'; import SignUpModal from '../../../components/modals/SignUpModal'; import { HomePage } from '../../../components/home/HomePage'; /** * @function * @returns {jsx} - hompage component */ function setup() { return shallow(<HomePage />); } describe('<HomePage />', () => { it('contains a <SignInForm /> component', () => { const wrapper = setup(); expect(wrapper.find(SignInForm).length).toBe(1); }); it('contains a <SignUpModal /> component', () => { const wrapper = setup(); expect(wrapper.find(SignUpModal).length).toBe(1); }); it('should have an h4', () => { const wrapper = setup(); expect(wrapper.find('h4').text()).toEqual('Create and manage your documents.'); }); it('should have an h6', () => { const wrapper = setup(); expect(wrapper.find('h6').text()).toEqual('See what others are up to!'); }); });
src/svg-icons/action/offline-pin.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOfflinePin = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z"/> </SvgIcon> ); ActionOfflinePin = pure(ActionOfflinePin); ActionOfflinePin.displayName = 'ActionOfflinePin'; ActionOfflinePin.muiName = 'SvgIcon'; export default ActionOfflinePin;
admin/client/components/ListFilters.js
efernandesng/keystone
import React from 'react'; import filterComponents from '../filters'; import CurrentListStore from '../stores/CurrentListStore'; import Popout from './Popout'; import { Pill } from 'elemental'; const Filter = React.createClass({ propTypes: { filter: React.PropTypes.object.isRequired }, getInitialState () { return { isOpen: false }; }, open () { this.setState({ isOpen: true, filterValue: this.props.filter.value }); }, close () { this.setState({ isOpen: false }); }, updateValue (filterValue) { this.setState({ filterValue: filterValue }); }, updateFilter (e) { CurrentListStore.setFilter(this.props.filter.field.path, this.state.filterValue); this.close(); e.preventDefault(); }, removeFilter () { CurrentListStore.clearFilter(this.props.filter.field.path); }, render () { let { filter } = this.props; let filterId = `activeFilter__${filter.field.path}`; let FilterComponent = filterComponents[filter.field.type]; return ( <span> <Pill label={filter.field.label} onClick={this.open} onClear={this.removeFilter} type="primary" id={filterId} showClearButton /> <Popout isOpen={this.state.isOpen} onCancel={this.close} relativeToID={filterId}> <form onSubmit={this.updateFilter}> <Popout.Header title="Edit Filter" /> <Popout.Body> <FilterComponent field={filter.field} filter={this.state.filterValue} onChange={this.updateValue} /> </Popout.Body> <Popout.Footer ref="footer" primaryButtonIsSubmit primaryButtonLabel="Apply" secondaryButtonAction={this.close} secondaryButtonLabel="Cancel" /> </form> </Popout> </span> ); } }); const ListFilters = React.createClass({ getInitialState () { return this.getStateFromStore(); }, componentDidMount () { CurrentListStore.addChangeListener(this.updateStateFromStore); }, componentWillUnmount () { CurrentListStore.removeChangeListener(this.updateStateFromStore); }, updateStateFromStore () { this.setState(this.getStateFromStore()); }, getStateFromStore () { return { filters: CurrentListStore.getActiveFilters() }; }, clearAllFilters () { CurrentListStore.clearAllFilters(); }, render () { if (!this.state.filters.length) return <div />; let currentFilters = this.state.filters.map((filter, i) => { return ( <Filter key={'f' + i} filter={filter} /> ); }); // append the clear button if (currentFilters.length > 1) { currentFilters.push(<Pill key="listFilters__clear" label="Clear All" onClick={this.clearAllFilters} />); } return ( <div className="ListFilters mb-2"> {currentFilters} </div> ); } }); module.exports = ListFilters;
src/routes/Home/components/Home/Home-Devs.js
Ryana513/ccproject
import React from 'react' import Paper from 'material-ui/Paper' import ryanj from '../../assets/ryanj.jpg' import drew from '../../assets/drew.jpg' import sdg from '../../assets/sdg.jpg' import ryanW from '../../assets/ryanW.jpg' import bghero from '../../assets/bg-hero-online.jpg' // import { BrowserRouter as NavLink } from "react-router-dom"; const style = { height: 212, width: 212, margin: 22, textAlign: 'center', display: 'inline-block', border: '15px solid teal', offset: 1, div: { margin: 'auto', width: '98%', padding: 10, backgroundImage: "url('../../assets/bg-hero-online.jpg')" } } const pic = { borderRadius: 85 } const devPic = img => { return <img style={pic} width={200} height={200} src={img} /> } export const HomeDevs = props => { return ( <div style={style.div}> <div className="col s5 pull-s7"> <Paper style={style} zDepth={5} circle children={devPic(ryanW)} /> <Paper style={style} zDepth={5} circle children={devPic(ryanj)} /> <Paper style={style} zDepth={5} circle children={devPic(sdg)} /> <Paper style={style} zDepth={5} circle children={devPic(drew)} /> </div> </div> ) } export default HomeDevs
src/lists.js
Zyj163/React_learning
/** * Created by ddn on 16/11/7. */ import React from 'react'; import ReactDOM from 'react-dom'; //A "key" is a special string attribute you need to include when creating lists of elements. //并且key必须是唯一的,在一个数组中 function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number, index) => <li key={index}>{number * 2}</li> ); return ( <ul>{listItems}</ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
src/js/ui/pages/welcome/loadDiary.js
hiddentao/heartnotes
import _ from 'lodash'; import React from 'react'; import Icon from '../../components/icon'; import Button from '../../components/button'; import Loading from '../../components/loading'; import Layout from './layout'; import { connectRedux, routing } from '../../helpers/decorators'; var Component = React.createClass({ render: function() { let activity = this.props.data.diary.loadingEntries; let progressMsg = ( <Loading text="Loading diary" /> ); let progressMsg2 = _.get(this.props, 'data.diary.decryptEntries.progressMsg'); let loadingError = null; if (activity.error) { progressMsg = 'Loading diary failed!'; let msg = ( <span>{activity.error.toString()}</span> ); loadingError = ( <div> <div className="error"> <Icon name="exclamation-triangle" /> {msg} </div> <Button size="xs" color="dark" onClick={this._goBack}>Back</Button> </div> ); } return ( <Layout> <div className="load-diary"> <p>{progressMsg}</p> <p className="progress-message">{progressMsg2}</p> {loadingError} </div> </Layout> ); }, componentDidMount: function(oldProps) { if (!_.get(this.props, 'data.diary.diaryMgr')) { return this.props.router.push('/welcome'); } this.props.actions.loadEntries() .then(() => { this.props.router.push('/newEntry'); if (this.props.data.diary.diaryMgr.auth.isLocalType) { this.props.actions.alertUser( 'You are using the app in local-only mode, meaning your diary ' + 'entries are stored locally within your browser. To enable cloud ' + 'sync and backup goto the settings page.', 'dialog' ); } }); }, _goBack: function() { this.props.actions.closeDiary(); this.props.router.push('/welcome'); }, }); module.exports = connectRedux([ 'closeDiary', 'loadEntries', 'alertUser', ])(routing()(Component));
src/frontend/components/survey-renderers/BSDPhonebankRSVPSurvey.js
al3x/ground-control
import React from 'react'; import Relay from 'react-relay' import BSDSurvey from './BSDSurvey' import {BernieColors, BernieText} from '../styles/bernie-css' import {GoogleMapLoader, GoogleMap, Marker} from 'react-google-maps'; import {FlatButton, Paper} from 'material-ui'; import moment from 'moment'; import FontIcon from 'material-ui/lib/font-icon'; import SideBarLayout from '../SideBarLayout' class BSDPhonebankRSVPSurvey extends React.Component { static propTypes = { onSubmitted : React.PropTypes.func, initialValues: React.PropTypes.object, survey: React.PropTypes.object } submit() { this.refs.survey.refs.component.submit() } state = { clickedMarker: null, selectedEventId: null } handleMarkerClick(marker) { this.setState({clickedMarker: marker}) } selectButton(marker) { return ( <FlatButton label='Select' style={{ ...BernieText.inputLabel, backgroundColor: BernieColors.green, marginTop: 10, }} onTouchTap={(event) => { this.setState({ clickedMarker: null, selectedEventId: marker.eventId }) this.refs.survey.refs.component.setFieldValue('event_id', marker.eventId) }} /> ) } deselectButton() { return ( <FlatButton label="Deselect" style={{ ...BernieText.inputLabel, backgroundColor: BernieColors.red, }} onTouchTap={() => { this.setState({ selectedEventId: null }) this.refs.survey.refs.component.setFieldValue('event_id', '') }} /> ) } renderSelectedEvent() { if (!this.state.selectedEventId) return <div></div> let event = this.props.interviewee.nearbyEvents.find((event) => event.eventIdObfuscated === this.state.selectedEventId) let content = ( <div> <p>Selected <strong>{event.name}</strong></p> <p>on <strong>{moment(event.startDate).utcOffset(event.localUTCOffset).format('MMM D')}</strong>.</p> </div> ) let sideBar = ( <div> {this.deselectButton()} </div> ) return ( <Paper zDepth={0} style={{ padding: '10px 10px 10px 10px', marginTop: 10, border: 'solid 1px ' + BernieColors.green, minHeight: 25 }}> <SideBarLayout containerStyle={{ 'border': 'none' }} sideBar={sideBar} content={content} contentViewStyle={{ border: 'none', paddingRight: 10 }} sideBarStyle={{ border: 'none', textAlign: 'right', marginTop: 'auto', marginBottom: 'auto' }} sideBarPosition='right' /> </Paper> ) } renderMarkerDescription(marker) { let description = <div></div> if (!marker) return <div></div>; if (marker.key === 'home') description = ( <div> <div style={{ ...BernieText.default, fontWeight: 600, fontSize: '1.0em' }}> {`${this.props.interviewee.firstName}'s home`} </div> </div> ) let button = <div></div>; if (marker.key !== 'home') description = ( <div> <div style={{ ...BernieText.secondaryTitle, color: BernieColors.gray, fontSize: '1.0em' }}> {moment(marker.startDate).utcOffset(marker.localUTCOffset).format('h:mm A - dddd, MMM D')} </div> <div style={{ ...BernieText.default, fontWeight: 600, fontSize: '1.0em' }}> {marker.name} </div> <div style={{ ...BernieText.default, fontSize: '1.0em' }}> <div>{marker.venueName}</div> <div>{marker.addr1}</div> <div>{marker.addr2}</div> <div>Capacity: {marker.capacity}</div> <div>Attendees: {marker.attendeesCount}</div> {this.state.selectedEventId === marker.eventId ? this.deselectButton() : this.selectButton(marker)} </div> </div> ) return ( <Paper zDepth={0} style={{ marginTop: 10, padding: '10px 10px 10px 10px', border: 'solid 1px ' + BernieColors.lightGray }}> {description} </Paper> ) } getEventAddr2(event) { let desc = '' if (event.venueAddr2) desc = desc + ' ' + event.venueAddr2; if (event.venueCity) desc = desc + ' ' + event.venueCity; if (event.venueState) desc = desc + ', ' + event.venueState return desc.trim(); } renderMap() { let center = { lat: this.props.interviewee.address.latitude, lng: this.props.interviewee.address.longitude } let homeIcon = { path: 'M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z', fillColor: BernieColors.blue, fillOpacity: 1.0, scale: 1, strokeColor: BernieColors.blue, strokeWeight: 2 }; let markers = [ { position: center, key: 'home', title: 'home', name: 'Interviewee home', icon: homeIcon } ]; this.props.interviewee.nearbyEvents.forEach((event) => { markers.push({ position: { lat: event.latitude, lng: event.longitude }, localUTCOffset: event.localUTCOffset, key: event.id, title: event.name, name: event.name, startDate: event.startDate, venueName: event.venueName, addr1: event.venueAddr1, addr2: this.getEventAddr2(event), eventId: event.eventIdObfuscated, capacity: event.capacity, attendeesCount: event.attendeesCount }) }) return ( <div style={{height: '100%', width: '100%'}}> <GoogleMapLoader containerElement={ <div style={{ height: '100%', width: '100%' }} /> } googleMapElement={ <GoogleMap ref='map' options={{ scrollwheel: false }} defaultZoom={9} defaultCenter={center}> {markers.map((marker, index) => { return ( <Marker {...marker} onClick={this.handleMarkerClick.bind(this, marker)} /> ); })} </GoogleMap> } /> </div> ) } render() { return ( <div> <div style={{width: '100%', height: 200}}> {this.renderMap()} </div> {this.renderSelectedEvent()} {this.renderMarkerDescription(this.state.clickedMarker)} <BSDSurvey ref='survey' survey={this.props.survey} interviewee={this.props.interviewee} onSubmitted={this.props.onSubmitted} /> </div> ) } } export default Relay.createContainer(BSDPhonebankRSVPSurvey, { initialVariables: { type: 'phonebank' }, fragments: { survey: () => Relay.QL` fragment on Survey { ${BSDSurvey.getFragment('survey')} } `, interviewee: () => Relay.QL` fragment on Person { ${BSDSurvey.getFragment('interviewee')} firstName email address { latitude longitude } nearbyEvents(within:20, type:$type) { id eventIdObfuscated name startDate localTimezone localUTCOffset venueName venueAddr1 venueAddr2 venueCity venueState description latitude longitude capacity attendeesCount } } ` } })
packages/react/src/components/ContentSwitcher/next/index.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { settings } from 'carbon-components'; import PropTypes from 'prop-types'; import React from 'react'; import cx from 'classnames'; import { match, matches, keys } from '../../../internal/keyboard'; import { useId } from '../../../internal/useId'; import { useControllableState } from './useControllableState'; const { prefix } = settings; // Used to manage the overall state of the ContentSwitcher const ContentSwitcherContext = React.createContext(); // Used to keep track of position in a tablist const ContentTabContext = React.createContext(); // Used to keep track of position in a list of tab panels const ContentPanelContext = React.createContext(); function ContentSwitcher({ children, defaultSelectedIndex = 0, onChange, selectedIndex: controlledSelectedIndex, }) { const baseId = useId('ccs'); // The active index is used to track the element which has focus in our tablist const [activeIndex, setActiveIndex] = React.useState(defaultSelectedIndex); // The selected index is used for the tab/panel pairing which is "visible" const [selectedIndex, setSelectedIndex] = useControllableState({ value: controlledSelectedIndex, defaultValue: defaultSelectedIndex, onChange: (value) => { if (onChange) { onChange({ selectedIndex: value }); } }, }); const value = { baseId, activeIndex, setActiveIndex, selectedIndex, setSelectedIndex, }; return ( <ContentSwitcherContext.Provider value={value}> {children} </ContentSwitcherContext.Provider> ); } ContentSwitcher.propTypes = { /** * Provide child elements to be rendered inside of the `ContentSwitcher`. * These elements should render either `ContentTabs` or `ContentPanels` */ children: PropTypes.node, /** * Specify which content tab should be initially selected when the component * is first rendered */ defaultSelectedIndex: PropTypes.number, /** * Provide an optional function which is called whenever the state of the * `ContentSwitcher` changes */ onChange: PropTypes.func, /** * Control which content panel is currently selected. This puts the component * in a controlled mode and should be used along with `onChange` */ selectedIndex: PropTypes.number, }; /** * A `ContentPanel` corresponds to a tablist in the Tabs pattern as written in * WAI-ARIA Authoring Practices. * * @see https://w3c.github.io/aria-practices/#tabpanel */ function ContentTabs({ activation = 'automatic', 'aria-label': label, children, className: customClassName, size = 'md', ...rest }) { const { activeIndex, selectedIndex, setSelectedIndex, setActiveIndex, } = React.useContext(ContentSwitcherContext); const ref = React.useRef(null); const className = cx(customClassName, `${prefix}--content-switcher`, { [`${prefix}--content-switcher--${size}`]: size, }); const count = React.Children.count(children); const tabs = []; function onKeyDown(event) { if ( matches(event, [keys.ArrowRight, keys.ArrowLeft, keys.Home, keys.End]) ) { const nextIndex = getNextIndex( event, count, activation === 'automatic' ? selectedIndex : activeIndex ); if (activation === 'automatic') { setSelectedIndex(nextIndex); } else if (activation === 'manual') { setActiveIndex(nextIndex); } tabs[nextIndex].current.focus(); } } return ( // eslint-disable-next-line jsx-a11y/interactive-supports-focus <div {...rest} aria-label={label} ref={ref} role="tablist" className={className} onKeyDown={onKeyDown}> {React.Children.map(children, (child, index) => { const ref = React.createRef(); tabs.push(ref); return ( <ContentTabContext.Provider value={index}> {React.cloneElement(child, { ref, })} </ContentTabContext.Provider> ); })} </div> ); } ContentTabs.propTypes = { /** * Specify whether the content tab should be activated automatically or * manually */ activation: PropTypes.oneOf(['automatic', 'manual']), /** * Provide an accessible label to be read when a user interacts with this * component */ 'aria-label': PropTypes.string.isRequired, /** * Provide child elements to be rendered inside of `ContentTabs`. * These elements should render a `ContentTab` */ children: PropTypes.node, /** * Specify an optional className to be added to the container node */ className: PropTypes.string, /** * Specify the size of the Content Switcher. Currently supports either `sm`, 'md' (default) or 'lg` as an option. */ size: PropTypes.oneOf(['sm', 'md', 'lg']), }; /** * Get the next index for a givne keyboard event given a count of the total * items and the current index * @param {Event} event * @param {number} total * @param {number} index * @returns {number} */ function getNextIndex(event, total, index) { if (match(event, keys.ArrowRight)) { return (index + 1) % total; } else if (match(event, keys.ArrowLeft)) { return (total + index - 1) % total; } else if (match(event, keys.Home)) { return 0; } else if (match(event, keys.End)) { return total - 1; } } const ContentTab = React.forwardRef(function ContentTab( { children, ...rest }, ref ) { const { selectedIndex, setSelectedIndex, baseId } = React.useContext( ContentSwitcherContext ); const index = React.useContext(ContentTabContext); const id = `${baseId}-tab-${index}`; const panelId = `${baseId}-tabpanel-${index}`; const className = cx(`${prefix}--content-switcher-btn`, { [`${prefix}--content-switcher--selected`]: selectedIndex === index, }); return ( <button {...rest} aria-controls={panelId} aria-selected={selectedIndex === index} ref={ref} id={id} role="tab" className={className} onClick={() => { setSelectedIndex(index); }} tabIndex={selectedIndex === index ? '0' : '-1'} type="button"> {children} </button> ); }); ContentTab.propTypes = { /** * Provide child elements to be rendered inside of `ContentTab`. * These elements must be noninteractive */ children: PropTypes.node, }; /** * Used to display all of the tab panels inside of a Content Switcher. This * components keeps track of position in for each ContentPanel. * * Note: children should either be a `ContentPanel` or should render a * `ContentPanel`. Fragments are not currently supported. */ function ContentPanels({ children }) { return React.Children.map(children, (child, index) => { return ( <ContentPanelContext.Provider value={index}> {child} </ContentPanelContext.Provider> ); }); } ContentPanels.propTypes = { /** * Provide child elements to be rendered inside of `ContentPanels`. * These elements should render a `ContentPanel` */ children: PropTypes.node, }; /** * A `ContentPanel` corresponds to a tabpanel in the Tabs pattern as written in * WAI-ARIA Authoring Practices. This component reads the selected * index and base id from context in order to determine the correct `id` and * display status of the component. * * @see https://w3c.github.io/aria-practices/#tabpanel */ const ContentPanel = React.forwardRef(function ContentPanel(props, ref) { const { children, ...rest } = props; const { selectedIndex, baseId } = React.useContext(ContentSwitcherContext); const index = React.useContext(ContentPanelContext); const id = `${baseId}-tabpanel-${index}`; const tabId = `${baseId}-tab-${index}`; // TODO: tabindex should only be 0 if no interactive content in children return ( <div {...rest} aria-labelledby={tabId} id={id} ref={ref} role="tabpanel" tabIndex="0" hidden={selectedIndex !== index}> {children} </div> ); }); ContentPanel.propTypes = { /** * Provide child elements to be rendered inside of `ContentPanel`. */ children: PropTypes.node, }; export { ContentSwitcher, ContentTabs, ContentTab, ContentPanels, ContentPanel, };
stories/typography.stories.js
buildkite/frontend
/* global module */ import React from 'react'; import PropTypes from 'prop-types'; import { storiesOf } from '@storybook/react'; const Example = function(props) { return <div className={`my3 border-left border-${props.border || "gray"} pl4 py2`}>{props.children}</div>; }; Example.propTypes = { children: PropTypes.node, border: PropTypes.string }; const Section = function(props) { return ( <div className="max-width-2"> {props.children} </div> ); }; Section.propTypes = { children: PropTypes.node }; const combinations = () => ( <Section> <Example> <p className="h1 m0" data-sketch-symbol="Text/h1" data-sketch-text="Heading - h1">Pipeline Settings — h1</p> <p className="h3 m0" data-sketch-symbol="Text/h3" data-sketch-text="Heading - h3">Manage your how your pipeline works — h3</p> </Example> <Example> <p className="h2 m0" data-sketch-symbol="Text/h2" data-sketch-text="Heading - h2">Pipeline Settings — h2</p> <p className="h4 m0" data-sketch-symbol="Text/h4" data-sketch-text="Text - h4">Manage your how your pipeline works — h4</p> </Example> <Example> <p className="h3 m0" data-sketch-symbol="Text/h3" data-sketch-text="Text - h4">Pipeline Settings — h3</p> <p className="h5 m0" data-sketch-symbol="Text/h5" data-sketch-text="Text - h5">Manage your how your pipeline works — h5</p> </Example> <Example> <p className="h4 m0" data-sketch-symbol="Text/h4" data-sketch-text="Text - h4">Pipeline Settings — h4</p> <p className="h5 m0 dark-gray" data-sketch-symbol="Text/h5 (Subdued)" data-sketch-text="Text - h5 Subdued">Manage your how your pipeline works — h5</p> </Example> <Example> <p className="h5 m0" data-sketch-symbol="Text/h5" data-sketch-text="Text - h4">Pipeline Settings — h5</p> <p className="h6 m0 dark-gray" data-sketch-symbol="Text/h6 (Subdued)" data-sketch-text="Text - h6 Subdued">Manage your how your pipeline works — h6</p> </Example> </Section> ); storiesOf('Typography', module) .add('Combinations', combinations); storiesOf('Typography', module) .add('Choosing Sizes', () => ( <Section> <p className="my3">You want enough contrast between type so that the hierarchy is clear. With our type scale, a good rule of thumb is to ensure text is at least two sizes different.</p> <p className="mt4 mb3">For example, the following lacks typographic contrast:</p> <Example border="red"> <p className="h1 m0" title="h1">Pipeline Settings — h1</p> <p className="h2 m0" title="h2">Manage your how your pipeline works — h2</p> </Example> <p className="mt4 mb3">The ideal solution is to make sure there’s two sizes between them, i.e. switch the second paragraph to a .h3:</p> <Example border="green"> <p className="h1 m0" title="h1">Pipeline Settings — h1</p> <p className="h3 m0" title="h2">Manage your how your pipeline works — h3</p> </Example> <p className="mt4 mb3">If you can’t adjust the size to have enough contrast, you can introduce colour to achieve some contrast:</p> <Example border="green"> <p className="h1 m0">Pipeline Settings — h1</p> <p className="h2 m0 dark-gray">Manage your how your pipeline works — h2</p> </Example> <p className="mt4 mb3">And finally, if size and colour can’t be adjusted, you can use weight:</p> <Example border="green"> <p className="h1 m0 bold">Pipeline Settings — h1</p> <p className="h2 m0">Manage your how your pipeline works — h2</p> </Example> <p className="my4">The general rule is to try to adjust font-size first, and then colour, and then weight.</p> </Section> )); export const Sketch = combinations;
react/redux-start/react-redux-todos-review/src/components/TodoList.js
kobeCan/practices
import React from 'react'; import Todo from './Todo' const TodoList = ({ todos, onClick }) => ( todos.map(todo => ( <Todo key={todo.id} {...todo} onClick={() => onClick(todo.id)} /> )) ); export default TodoList
examples/basic/app.js
revolunet/cmp1
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Cmp1 from '../../lib/index'; class App extends Component { click() { alert('Roger that !'); } render() { return ( <div className='example'> <h1>cmp1</h1> <Cmp1 click={ this.click } name='Click me'/> </div> ); } } ReactDOM.render(<App/>, document.getElementById('container'));
ReactNativeExampleApp/node_modules/react-native/Libraries/Text/Text.js
weien/Auth0Exercise
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactNativeComponentClass = require('createReactNativeComponentClass'); const merge = require('merge'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, lineBreakMode: true, allowFontScaling: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the `fontFamily` from *`styles.baseText`, but the title provides its own additional styles. The title and body will * stack on top of each other on account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}<br /><br /> * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // App registration and rendering * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` */ const Text = React.createClass({ propTypes: { /** * Line Break mode. This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * `numberOfLines` must be set in conjunction with this prop. * * > `clip` is working only for iOS */ lineBreakMode: React.PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `lineBreakMode`. */ numberOfLines: React.PropTypes.number, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}`` */ onPress: React.PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>`` */ onLongPress: React.PropTypes.func, /** * Lets the user select text, to use the native copy and paste functionality. * * @platform android */ selectable: React.PropTypes.bool, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * * @platform ios */ suppressHighlighting: React.PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: React.PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility setting on iOS. The * default is `true`. * * @platform ios */ allowFontScaling: React.PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](/react-native/docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: React.PropTypes.bool, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, lineBreakMode: 'tail', }; }, getInitialState: function(): Object { return merge(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, contextTypes: { isInAParentText: React.PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): ReactElement<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = () => { this.props.onPress && this.props.onPress(); }; this.touchableHandleLongPress = () => { this.props.onLongPress && this.props.onLongPress(); }; this.touchableGetPressRectOffset = function(): RectOffset { return PRESS_RECT_OFFSET; }; } return setResponder; }, onResponderGrant: function(e: SyntheticEvent, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number; left: number; right: number; bottom: number; } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass(viewConfig); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass({ validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', }); } module.exports = Text;
test/ButtonSpec.js
mcraiganthony/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Button from '../src/Button'; describe('Button', function () { it('Should output a button', function () { let instance = ReactTestUtils.renderIntoDocument( <Button> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'BUTTON'); }); it('Should output a component with button classes', function () { let instance = ReactTestUtils.renderIntoDocument( <Button componentClass='input'> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'INPUT'); assert.equal(React.findDOMNode(instance).getAttribute('class'), 'btn btn-default'); }); it('Should have type=button by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Button> Title </Button> ); assert.equal(React.findDOMNode(instance).getAttribute('type'), 'button'); }); it('Should show the type if passed one', function () { let instance = ReactTestUtils.renderIntoDocument( <Button type='submit'> Title </Button> ); assert.equal(React.findDOMNode(instance).getAttribute('type'), 'submit'); }); it('Should output an anchor if called with a href', function () { let href = '/url'; let instance = ReactTestUtils.renderIntoDocument( <Button href={href}> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'A'); assert.equal(React.findDOMNode(instance).getAttribute('href'), href); }); it('Should output an input if called with a href and an input component', function () { let href = '/url'; let instance = ReactTestUtils.renderIntoDocument( <Button href={href} componentClass='input'> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'INPUT'); assert.equal(React.findDOMNode(instance).getAttribute('href'), href); }); it('Should output an anchor if called with a target', function () { let target = '_blank'; let instance = ReactTestUtils.renderIntoDocument( <Button target={target}> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'A'); assert.equal(React.findDOMNode(instance).getAttribute('target'), target); }); it('Should call onClick callback', function (done) { let doneOp = function () { done(); }; let instance = ReactTestUtils.renderIntoDocument( <Button onClick={doneOp}> Title </Button> ); ReactTestUtils.Simulate.click(React.findDOMNode(instance)); }); it('Should be disabled', function () { let instance = ReactTestUtils.renderIntoDocument( <Button disabled> Title </Button> ); assert.ok(React.findDOMNode(instance).disabled); }); it('Should be disabled link', function () { let instance = ReactTestUtils.renderIntoDocument( <Button disabled href='#'> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bdisabled\b/)); }); it('Should have block class', function () { let instance = ReactTestUtils.renderIntoDocument( <Button block> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/)); }); it('Should apply bsStyle class', function () { let instance = ReactTestUtils.renderIntoDocument( <Button bsStyle='danger'> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/)); }); it('Should honour additional classes passed in, adding not overriding', function () { let instance = ReactTestUtils.renderIntoDocument( <Button className="bob" bsStyle="danger"> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/)); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/)); }); it('Should default to bsStyle="default"', function () { let instance = ReactTestUtils.renderIntoDocument( <Button bsStyle='default'> Title </Button> ); assert.equal(instance.props.bsStyle, 'default'); }); it('Should be active', function () { let instance = ReactTestUtils.renderIntoDocument( <Button active> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bactive\b/)); }); it('Should render an anchor in a list item when in a nav', function () { let instance = ReactTestUtils.renderIntoDocument( <Button navItem active> Title </Button> ); let li = React.findDOMNode(instance); let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'); assert.equal(li.nodeName, 'LI'); assert.ok(li.className.match(/\bactive\b/)); assert.ok(anchor.props.href, '#'); }); it('Should render an anchor when in a navDropdown', function () { let instance = ReactTestUtils.renderIntoDocument( <Button navDropdown> Title </Button> ); let anchor = React.findDOMNode(instance); assert.equal(anchor.nodeName, 'A'); assert.ok(anchor.getAttribute('href'), '#'); }); });
js/src/components/TextAlignControl/__test__/textAlignControlTest.js
andresin87/react-draft-wysiwyg
/* @flow */ import React from 'react'; import { expect, assert } from 'chai';// eslint-disable-line import/no-extraneous-dependencies import { spy } from 'sinon';// eslint-disable-line import/no-extraneous-dependencies import { shallow, mount } from 'enzyme';// eslint-disable-line import/no-extraneous-dependencies import { EditorState, convertFromHTML, ContentState, } from 'draft-js'; import TextAlignControl from '..'; import defaultToolbar from '../../../config/defaultToolbar'; describe('TextAlignControl test suite', () => { const contentBlocks = convertFromHTML('<div>test</div>'); const contentState = ContentState.createFromBlockArray(contentBlocks); const editorState = EditorState.createWithContent(contentState); it('should have a div when rendered', () => { expect(shallow( <TextAlignControl onChange={() => {}} editorState={editorState} config={defaultToolbar.textAlign} /> ).node.type).to.equal('div'); }); it('should have 4 child elements by default', () => { const control = mount( <TextAlignControl onChange={() => {}} editorState={editorState} config={defaultToolbar.textAlign} /> ); expect(control.children().length).to.equal(4); }); it('should have 1 child elements if inDropdown is true', () => { const control = mount( <TextAlignControl onChange={() => {}} editorState={editorState} config={{ ...defaultToolbar.textAlign, inDropdown: true }} /> ); expect(control.children().length).to.equal(1); expect(control.childAt(0).children().length).to.equal(2); }); it('should execute onChange when any of first any child elements is clicked', () => { const onChange = spy(); const control = mount( <TextAlignControl onChange={onChange} editorState={editorState} config={defaultToolbar.textAlign} /> ); control.childAt(0).simulate('click'); assert.isTrue(onChange.calledOnce); control.childAt(1).simulate('click'); assert.equal(onChange.callCount, 2); control.childAt(2).simulate('click'); assert.equal(onChange.callCount, 3); control.childAt(3).simulate('click'); assert.equal(onChange.callCount, 4); }); });
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js
mjw56/react-router
import React from 'react'; class Announcements extends React.Component { render () { return ( <div> <h3>Announcements</h3> {this.props.children || <p>Choose an announcement from the sidebar.</p>} </div> ); } } export default Announcements;
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleResponsiveWidth.js
mohammed88/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleResponsiveWidth = () => ( <div> <Grid> <Grid.Column mobile={16} tablet={8} computer={4}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column mobile={16} tablet={8} computer={4}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column mobile={16} tablet={8} computer={4}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column mobile={16} tablet={8} computer={4}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column mobile={16} tablet={8} computer={4}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> </Grid> <Grid> <Grid.Column largeScreen={2} widescreen={1}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column largeScreen={2} widescreen={1}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column largeScreen={2} widescreen={1}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column largeScreen={2} widescreen={1}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> </Grid> </div> ) export default GridExampleResponsiveWidth
app/components/Message.js
alexbooker/pusher-realtime-chat
import React from 'react' import Time from './Time' const Message = React.createClass({ render () { return ( <div className='message'> <div className='message__top'> <img className='message__author-avatar' src={this.props.message.user.avatarUrl} alt={this.props.message.user.username} /> <p className='message__text'>{this.props.message.text}</p> </div> <p className='message__time'> <Time value={this.props.message.createdAt} /> </p> </div> ) } }) export default Message
src/shared/tests/components.spec.js
stephan281094/react-blog
import expect from 'expect' import expectJSX from 'expect-jsx' import React from 'react' import TestUtils from 'react-addons-test-utils' import { Link } from 'react-router' import PostListItem from '../components/PostListItem' expect.extend(expectJSX) describe('component tests', () => { it('should render PostListItem properly', () => { const renderer = TestUtils.createRenderer() const post = { title: 'first post', content: 'hello world!', slug: 'first-post', } renderer.render( <PostListItem post={post} /> ) const output = renderer.getRenderOutput() expect(output).toEqualJSX( <Link className={undefined} to={'/' + post.slug}> <h2 className={undefined}>{post.title}</h2> </Link> ) }) })
docs/app/Examples/elements/Icon/Groups/IconExampleCornerGroup.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Icon } from 'semantic-ui-react' const IconExampleCornerGroup = () => ( <Icon.Group size='huge'> <Icon name='puzzle' /> <Icon corner name='add' /> </Icon.Group> ) export default IconExampleCornerGroup
src/js/components/icons/base/BackTen.js
kylebyerly-hp/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}-back-ten`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'back-ten'); 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="M3.11111111,7.55555556 C4.66955145,4.26701301 8.0700311,2 12,2 C17.5228475,2 22,6.4771525 22,12 C22,17.5228475 17.5228475,22 12,22 L12,22 C6.4771525,22 2,17.5228475 2,12 M2,4 L2,8 L6,8 M9,16 L9,9 L7,9.53333333 M17,12 C17,10 15.9999999,8.5 14.5,8.5 C13.0000001,8.5 12,10 12,12 C12,14 13,15.5000001 14.5,15.5 C16,15.4999999 17,14 17,12 Z M14.5,8.5 C16.9253741,8.5 17,11 17,12 C17,13 17,15.5 14.5,15.5 C12,15.5 12,13 12,12 C12,11 12.059,8.5 14.5,8.5 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'BackTen'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
resources/apps/frontend/src/pages/attendance/index.js
johndavedecano/PHPLaravelGymManagementSystem
import React from 'react'; import Loadable from 'components/Loadable'; import {PrivateLayout} from 'components/Layouts'; import renderRoutes from './../routes'; export default { exact: false, auth: true, path: '/attendance', component: ({routes}) => { return <PrivateLayout>{renderRoutes(routes)}</PrivateLayout>; }, routes: [ { exact: true, auth: true, path: '/attendance', component: Loadable({ loader: () => import('./lists'), }), }, ], };
src/parser/priest/discipline/modules/features/Checklist/Module.js
FaideWW/WoWAnalyzer
import React from 'react'; import BaseChecklist from 'parser/shared/modules/features/Checklist2/Module'; import CastEfficiency from 'parser/shared/modules/CastEfficiency'; import Combatants from 'parser/shared/modules/Combatants'; import ManaValues from 'parser/shared/modules/ManaValues'; import PreparationRuleAnalyzer from 'parser/shared/modules/features/Checklist2/PreparationRuleAnalyzer'; import AlwaysBeCasting from '../AlwaysBeCasting'; import Component from './Component'; class Checklist extends BaseChecklist { static dependencies = { combatants: Combatants, castEfficiency: CastEfficiency, alwaysBeCasting: AlwaysBeCasting, manaValues: ManaValues, preparationRuleAnalyzer: PreparationRuleAnalyzer, }; render() { return ( <Component combatant={this.combatants.selected} castEfficiency={this.castEfficiency} thresholds={{ ...this.preparationRuleAnalyzer.thresholds, nonHealingTimeSuggestionThresholds: this.alwaysBeCasting.nonHealingTimeSuggestionThresholds, downtimeSuggestionThresholds: this.alwaysBeCasting.downtimeSuggestionThresholds, manaLeft: this.manaValues.suggestionThresholds, }} /> ); } } export default Checklist;
src/components/MainLayout/Header.js
waltcow/newsApp
import React from 'react'; import { Menu, Icon } from 'antd'; import { Link } from 'dva/router'; function Header({ location }) { return ( <Menu selectedKeys={[location.pathname]} mode="horizontal" theme="dark" > <Menu.Item key="/users"> <Link to="/users"><Icon type="bars" />Users</Link> </Menu.Item> <Menu.Item key="/"> <Link to="/"><Icon type="home" />Home</Link> </Menu.Item> <Menu.Item key="/404"> <Link to="/page-you-dont-know"><Icon type="frown-circle" />404</Link> </Menu.Item> <Menu.Item key="/antd"> <a href="https://github.com/dvajs/dva">dva</a> </Menu.Item> </Menu> ); } export default Header;
react/features/room-lock/components/RoomLockPrompt.native.js
KalinduDN/kalindudn.github.io
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Dialog } from '../../base/dialog'; import { endRoomLockRequest } from '../actions'; /** * Implements a React Component which prompts the user for a password to lock a * conference/room. */ class RoomLockPrompt extends Component { /** * RoomLockPrompt component's property types. * * @static */ static propTypes = { /** * The JitsiConference which requires a password. * * @type {JitsiConference} */ conference: React.PropTypes.object, dispatch: React.PropTypes.func }; /** * Initializes a new RoomLockPrompt instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); // Bind event handlers so they are only bound once for every instance. this._onCancel = this._onCancel.bind(this); this._onSubmit = this._onSubmit.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <Dialog bodyKey = 'dialog.passwordLabel' onCancel = { this._onCancel } onSubmit = { this._onSubmit } titleKey = 'toolbar.lock' /> ); } /** * Notifies this prompt that it has been dismissed by cancel. * * @private * @returns {boolean} True to hide this dialog/prompt; otherwise, false. */ _onCancel() { // An undefined password is understood to cancel the request to lock the // conference/room. return this._onSubmit(undefined); } /** * Notifies this prompt that it has been dismissed by submitting a specific * value. * * @param {string} value - The submitted value. * @private * @returns {boolean} False because we do not want to hide this * dialog/prompt as the hiding will be handled inside endRoomLockRequest * after setting the password is resolved. */ _onSubmit(value) { this.props.dispatch(endRoomLockRequest(this.props.conference, value)); return false; // Do not hide. } } export default connect()(RoomLockPrompt);
src/components/Column/RadioButtonColumn.js
TheBurningRed/react-gridview
'use strict'; import React from 'react'; require('styles/GridView/RadioButtonColumn.css'); let RadioButtonColumnComponent = (props) => ( <div className="radiobuttoncolumn-component"> Please edit src/components/gridView//RadioButtonColumnComponent.js to update this component! </div> ); RadioButtonColumnComponent.displayName = 'GridViewRadioButtonColumnComponent'; // Uncomment properties you need // RadioButtonColumnComponent.propTypes = {}; // RadioButtonColumnComponent.defaultProps = {}; export default RadioButtonColumnComponent;
frontend/src/components/YoutubeVideo.js
carlosascari/opencollective-website
import React from 'react'; export default ({ video, width='560', height='315' }) => { if(!video || !video.match(/watch\?v=/)) { return; } const id = video.match(/watch\?v=([^&]*)/)[1]; return ( <div className='YoutubeVideo height-100'> <iframe width={width} height={height} src={`https://www.youtube.com/embed/${id}`} frameBorder='0' allowFullScreen> </iframe> </div> ); }
src/svg-icons/maps/directions-walk.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsWalk = (props) => ( <SvgIcon {...props}> <path d="M13.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9L7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1L6 8.3V13h2V9.6l1.8-.7"/> </SvgIcon> ); MapsDirectionsWalk = pure(MapsDirectionsWalk); MapsDirectionsWalk.displayName = 'MapsDirectionsWalk'; MapsDirectionsWalk.muiName = 'SvgIcon'; export default MapsDirectionsWalk;
src/svg-icons/action/gavel.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGavel = (props) => ( <SvgIcon {...props}> <path d="M1 21h12v2H1zM5.245 8.07l2.83-2.827 14.14 14.142-2.828 2.828zM12.317 1l5.657 5.656-2.83 2.83-5.654-5.66zM3.825 9.485l5.657 5.657-2.828 2.828-5.657-5.657z"/> </SvgIcon> ); ActionGavel = pure(ActionGavel); ActionGavel.displayName = 'ActionGavel'; ActionGavel.muiName = 'SvgIcon'; export default ActionGavel;
src/svg-icons/image/brightness-3.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness3 = (props) => ( <SvgIcon {...props}> <path d="M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54 0 4.48-2.94 8.27-7 9.54.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2z"/> </SvgIcon> ); ImageBrightness3 = pure(ImageBrightness3); ImageBrightness3.displayName = 'ImageBrightness3'; export default ImageBrightness3;
__tests__/app/app.js
pcstl/app-saber
import 'react-native'; import React from 'react'; import App from 'saber-app'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <App /> ); });
src/components/cropper-view/index.js
olofd/react-native-insta-photo-studio
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image, Animated, ScrollView, InteractionManager } from 'react-native'; import React, { Component } from 'react'; import ImageCopperView from './image-cropper-view'; import BlockView from 'react-native-scroll-block-view'; import { BlurView } from 'react-native-blur'; import { AnimatedCircularProgress } from '../../react-native-circular-progress'; import ToolBar from './tool-bar'; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const loadingViewScale = { inputRange: [ 0, 1 ], outputRange: [1.15, 1] }; const ACTIVE_POINTER = 'auto'; const INACTIVE_POINTER = 'none'; export default class CropperViewContainer extends Component { constructor(props) { super(props); const images = []; if (props.image) { images.push({ loaded: false, image: props.image }); } this.state = { currentImageIndex: 0, images: images, loadingViewAnim: new Animated.Value(0) }; } componentWillReceiveProps(nextProps) { const currentImage = this.state.images[this.state.currentImageIndex]; if (!currentImage || currentImage.image !== nextProps.image) { const nextPushIndex = this.getNextPushIndex(); const cropperImageObj = this.state.images[nextPushIndex]; if (cropperImageObj && (cropperImageObj.image === nextProps.image || cropperImageObj.image.uri === nextProps.image.uri)) { this.onPartialLoad(this.state.images[nextPushIndex], this.currentLoadingGuid); this.onLoad(this.state.images[nextPushIndex], this.currentLoadingGuid); } else { this.state.images[nextPushIndex] = { loaded: false, image: nextProps.image }; if (nextProps.image && nextProps.image.uri) { this.startLoadingTimer(this.state.images.length === 1); } } this.loadCircle && this.loadCircle.setAnimationValue(0); this.setState({ currentImageIndex: nextPushIndex, isLoading: false }); } } startLoadingTimer(firstImage) { const currentLoadingGuid = this.guid(); this.currentLoadingGuid = currentLoadingGuid; setTimeout(() => { if (this.currentLoadingGuid === currentLoadingGuid) { this.animateLoadingView(1, undefined, false); } }, 350); } animateLoadingView(toValue, cb, instant) { if (instant) { this.state.loadingViewAnim.setValue(toValue); } else { Animated.spring(this.state.loadingViewAnim, { toValue: toValue, tension: 10, friction: 7 }).start(cb); } } guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } getNextPushIndex() { console.log(this.props.numberOfCroppers); if (this.state.currentImageIndex < this.props.numberOfCroppers - 1) { if (this.state.images.length < this.props.numberOfCroppers) { return this.state.images.length; } return this.state.currentImageIndex + 1; } return 0; } getCurrentImage() { return this.state.images[this.state.currentImageIndex]; } onLoad(imageObj, currentLoadingGuid) { if (currentLoadingGuid === this.currentLoadingGuid) { this.currentLoadingGuid = null; this.loadCircle && this.loadCircle.animateFill(100, undefined, false); setTimeout(() => { this.animateLoadingView(0, undefined, true); }, 100); } this._setLoadedForImageObj(imageObj); } onPartialLoad(imageObj) { this._setLoadedForImageObj(imageObj); } _setLoadedForImageObj(imageObj) { if (!imageObj.loaded) { this.state.images.forEach(i => i.loaded = false); imageObj.loaded = true; this.forceUpdate(); } } onProgress(e) { const p = Math.round((e.nativeEvent.loaded / e.nativeEvent.total) * 100); this.loadCircle && this.loadCircle.animateFill(p, undefined, false); } renderCroppers(cropperProps) { const cropperViews = []; for (var j = 0; j < this.state.images.length; j++) { const imageObj = this.state.images[j]; const isActive = this.state.currentImageIndex === j; const style = [ styles.imageCropperView, styles.absoluteStyle, imageObj.loaded ? styles.activeCropperView : null ]; cropperViews.push(<ImageCopperView key={j} magnification={this.props.magnification} window={this.props.window} willStartAnimating={this.props.willStartAnimating} finnishAnimation={this.props.finnishAnimation} getAnimationValue={this.props.getAnimationValue} animate={this.props.animate} resetAnimation={this.props.resetAnimation} pointerEvents={isActive ? ACTIVE_POINTER : INACTIVE_POINTER} isActive={isActive} onProgress={this.onProgress.bind(this)} onLoad={this.onLoad.bind(this, imageObj, this.currentLoadingGuid)} onError={() => alert('error')} onPartialLoad={this.onPartialLoad.bind(this, imageObj, this.currentLoadingGuid)} style={style} image={imageObj.image} />); } return cropperViews; } render() { const { width, height } = this.props.window; const drawerContainer = { opacity: this.props.anim.interpolate({ inputRange: [ 0, width ], outputRange: [ 0, -0.35 ], extrapolate: 'extend' }) }; const widthHeightStyle = { width, height: width }; return ( <BlockView style={[styles.container, this.props.style]}> <ScrollView style={widthHeightStyle} scrollsToTop={false} bounces={false} contentContainerStyle={widthHeightStyle} scrollEnabled={true}> {this.renderCroppers()} </ScrollView> {this.renderToolbar()} <Animated.View pointerEvents={INACTIVE_POINTER} style={[styles.drawerContainer, styles.absoluteStyle, drawerContainer]}></Animated.View> {this.renderLoadingView(widthHeightStyle)} </BlockView> ); } renderToolbar() { return (<ToolBar appService={this.props.appService} image={this.props.image}></ToolBar>); } renderLoadingView(widthHeightStyle) { return ( <Animated.View pointerEvents={INACTIVE_POINTER} style={[ styles.absoluteStyle, styles.blurView, { backgroundColor: 'black', opacity: this.state.loadingViewAnim.interpolate({ inputRange: [ 0, 1 ], outputRange: [0, 0.65] }), transform: [ { scale: this.state.loadingViewAnim.interpolate(loadingViewScale) } ] } ]} blurType='dark'> <AnimatedCircularProgress ref={loadCircle => this.loadCircle = loadCircle} rotation={0} style={styles.animatedCircle} size={50} width={1.5} fill={5} tintColor='white' backgroundColor="rgba(170, 170, 170, 1)" /> </Animated.View> ); } } CropperViewContainer.defaultProps = { numberOfCroppers: 2 }; const styles = StyleSheet.create({ container: { overflow: 'hidden' }, animatedCircle: { backgroundColor: 'transparent' }, absoluteStyle: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }, imageCropperView: { opacity: 0 }, activeCropperView: { opacity: 1 }, drawerContainer: { backgroundColor: 'black', opacity: 0.6 }, blurView: { alignItems: 'center', justifyContent: 'center' } });
client/components/MasterPage.js
JSVillage/military-families-backend
import React from 'react'; import {Link} from 'react-router'; class MasterPage extends React.Component { render() { return <div> <div className="container"> <div className ="row"> <nav className="navbar navbar-default navbar-fixed-top"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-collapse" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a href="/" className="navbar-brand"> <i className="fa fa-heartbeat" aria-hidden="true"></i> Veteran Support</a> </div> <div className="navbar-collapse collapse" id="bs-collapse"> <ul className="nav navbar-nav navbar-right"> <li> <Link to="/services">Services</Link> </li> <li> <Link to="/events">Events</Link> </li> <li> <Link to="/forum">Forum</Link> </li> <li> <Link to="/resources">Resources</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </div> </div> </nav> </div> </div> {this.props.children} <footer className="text-center"> <p>&copy; JavaScript Village 2016</p> </footer> </div>; } } export default MasterPage;
app/packs/src/admin/text_templates/TextTemplateIcon.js
ComPlat/chemotion_ELN
import React from 'react'; import PropTypes from 'prop-types'; const TextTemplateIcon = ({ template }) => { if (!template) return <span />; const { data, name } = template; if (data.icon) { return ( <i className={data.icon} /> ); } const text = (data || {}).text || name; return ( <span>{text.toUpperCase()}</span> ); }; TextTemplateIcon.propTypes = { // eslint-disable-next-line react/forbid-prop-types template: PropTypes.object }; TextTemplateIcon.defaultProps = { template: null }; export default TextTemplateIcon;
packages/bonde-styleguide/src/content/IconColorful/svg/Abc.js
ourcities/rebu-client
import React from 'react' const Icon = () => ( <svg xmlns='http://www.w3.org/2000/svg' width='46' height='40' viewBox='0 0 46 40'> <g fill='none' fillRule='evenodd' transform='translate(-27)'> <circle cx='52' cy='20' r='20' fill='#E09' opacity='.297' /> <circle cx='52' cy='20' r='16' fill='#E09' opacity='.3' /> <circle cx='52' cy='20' r='12' fill='#E09' /> <text fill='#000' fontFamily='SourceSansPro-Bold, Source Sans Pro' fontSize='28' fontWeight='bold' > <tspan x='27.55' y='29.728'>Abc</tspan> </text> </g> </svg> ) Icon.displayName = 'IconColorful.Abc' export default Icon
src/components/Toggle/Toggle-story.js
jzhang300/carbon-components-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import Toggle from '../Toggle'; const toggleProps = { onToggle: action('toggle'), className: 'some-class', }; storiesOf('Toggle', module).addWithInfo( 'Default', ` Toggles are controls that are used to quickly switch between two possible states. The example below shows an uncontrolled Toggle component. To use the Toggle component as a controlled component, set the toggled property. Setting the toggled property will allow you to change the value dynamically, whereas setting the defaultToggled prop will only set the value initially. `, () => <Toggle {...toggleProps} className="some-class" id="toggle-1" /> );
fields/types/relationship/RelationshipFilter.js
ratecity/keystone
import _ from 'lodash'; import async from 'async'; import React from 'react'; import { findDOMNode } from 'react-dom'; import xhr from 'xhr'; import { FormField, FormInput, SegmentedControl, } from '../../../admin/client/App/elemental'; import PopoutList from '../../../admin/client/App/shared/Popout/PopoutList'; const INVERTED_OPTIONS = [ { label: 'Linked To', value: false }, { label: 'NOT Linked To', value: true }, ]; function getDefaultValue () { return { inverted: INVERTED_OPTIONS[0].value, value: [], }; } var RelationshipFilter = React.createClass({ propTypes: { field: React.PropTypes.object, filter: React.PropTypes.shape({ inverted: React.PropTypes.bool, value: React.PropTypes.array, }), onHeightChange: React.PropTypes.func, }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, getInitialState () { return { searchIsLoading: false, searchResults: [], searchString: '', selectedItems: [], valueIsLoading: true, }; }, componentDidMount () { this._itemsCache = {}; this.loadSearchResults(true); }, componentWillReceiveProps (nextProps) { if (nextProps.filter.value !== this.props.filter.value) { this.populateValue(nextProps.filter.value); } }, isLoading () { return this.state.searchIsLoading || this.state.valueIsLoading; }, populateValue (value) { async.map(value, (id, next) => { if (this._itemsCache[id]) return next(null, this._itemsCache[id]); xhr({ url: Keystone.adminPath + '/api/' + this.props.field.refList.path + '/' + id + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return next(err); this.cacheItem(data); next(err, data); }); }, (err, items) => { if (err) { // TODO: Handle errors better console.error('Error loading items:', err); } this.setState({ valueIsLoading: false, selectedItems: items || [], }, () => { findDOMNode(this.refs.focusTarget).focus(); }); }); }, cacheItem (item) { this._itemsCache[item.id] = item; }, buildFilters () { var filters = {}; _.forEach(this.props.field.filters, function (value, key) { if (value[0] === ':') return; filters[key] = value; }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, loadSearchResults (thenPopulateValue) { const searchString = this.state.searchString; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.field.refList.path + '?basic&search=' + searchString + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { // TODO: Handle errors better console.error('Error loading items:', err); this.setState({ searchIsLoading: false, }); return; } data.results.forEach(this.cacheItem); if (thenPopulateValue) { this.populateValue(this.props.filter.value); } if (searchString !== this.state.searchString) return; this.setState({ searchIsLoading: false, searchResults: data.results, }, this.updateHeight); }); }, updateHeight () { if (this.props.onHeightChange) { this.props.onHeightChange(this.refs.container.offsetHeight); } }, toggleInverted (inverted) { this.updateFilter({ inverted }); }, updateSearch (e) { this.setState({ searchString: e.target.value }, this.loadSearchResults); }, selectItem (item) { const value = this.props.filter.value.concat(item.id); this.updateFilter({ value }); }, removeItem (item) { const value = this.props.filter.value.filter(i => { return i !== item.id; }); this.updateFilter({ value }); }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, renderItems (items, selected) { const itemIconHover = selected ? 'x' : 'check'; return items.map((item, i) => { return ( <PopoutList.Item key={`item-${i}-${item.id}`} icon="dash" iconHover={itemIconHover} label={item.name} onClick={() => { if (selected) this.removeItem(item); else this.selectItem(item); }} /> ); }); }, render () { const selectedItems = this.state.selectedItems; const searchResults = this.state.searchResults.filter(i => { return this.props.filter.value.indexOf(i.id) === -1; }); const placeholder = this.isLoading() ? 'Loading...' : 'Find a ' + this.props.field.label + '...'; return ( <div ref="container"> <FormField> <SegmentedControl equalWidthSegments options={INVERTED_OPTIONS} value={this.props.filter.inverted} onChange={this.toggleInverted} /> </FormField> <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <FormInput autoFocus ref="focusTarget" value={this.state.searchString} onChange={this.updateSearch} placeholder={placeholder} /> </FormField> {selectedItems.length ? ( <PopoutList> <PopoutList.Heading>Selected</PopoutList.Heading> {this.renderItems(selectedItems, true)} </PopoutList> ) : null} {searchResults.length ? ( <PopoutList> <PopoutList.Heading style={selectedItems.length ? { marginTop: '2em' } : null}>Items</PopoutList.Heading> {this.renderItems(searchResults)} </PopoutList> ) : null} </div> ); }, }); module.exports = RelationshipFilter;