path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
docs/src/pages/StartPage.js
gocreating/react-tocas
import React from 'react'; import PageLayout from '../utils/PageLayout'; import CodeBlock from '../utils/CodeBlock'; import { Segment, Header, } from '../../../lib'; import 'codemirror/mode/htmlmixed/htmlmixed'; import 'codemirror/mode/jsx/jsx'; import 'codemirror/theme/solarized.css'; let JSX_DEMO = `import Button from 'react-tocas/lib/Button'; // or this way: // import { Button } from 'react-tocas'; let App = () => ( <div> <Button info onClick={() => alert('World')}> Hello </Button> </div> );`; let StartPage = () => ( <PageLayout> <Segment borderless basic> <Header level={1}> Installation </Header> <Header huge> Install react-tocas from npm. </Header> <CodeBlock theme="solarized light" readOnly lineNumbers > {'npm install --save react-tocas'} </CodeBlock> </Segment> <Segment borderless basic> <Header level={1}> Usage </Header> <Header huge> Import css file from CDN. </Header> <CodeBlock mode="htmlmixed" theme="solarized light" readOnly lineNumbers > {'<link rel="stylesheet" href="//cdn.rawgit.com/TeaMeow/TocasUI/master/dist/tocas.min.css">'} </CodeBlock> <Header huge> Start using great react components. </Header> <CodeBlock mode="jsx" theme="solarized light" readOnly lineNumbers > {JSX_DEMO} </CodeBlock> </Segment> </PageLayout> ); export default StartPage;
scr-app/src/redux/devtools/showDevTools.js
tlatoza/SeeCodeRun
import React from 'react'; import {render} from 'react-dom'; import DevTools from './DevTools'; /** * Renders Redux Dev tools * @param {Object} store - the Redux store to be debugged. * @return {number} - The timeout id in case of cancellation. */ export default function showDevTools(store) { return setTimeout(() => { const devtoolsDiv = document.createElement('div'); devtoolsDiv.id = 'react-devtools-root'; document.body.appendChild(devtoolsDiv); render( <DevTools store={store}/>, document.querySelector('#react-devtools-root') ); }, 100); }
src/components/containers/article-container.js
mberneti/ReactAdmin
import React from 'react'; import { connect } from 'react-redux'; import Article from '../views/article'; import store from '../../store'; import { loadDashboardCompleted } from '../../actions/dashboard-actions'; import { resetArticleModel } from '../../actions/article-actions'; import * as articleApi from '../../api/article-api'; class ArticleContainer extends React.Component { componentDidMount() { let _current = this; this.type = this.props.route.title; //this is the name of the route if (this.props.route.isEditRoute) { let id = this.props.params.itemId; //fetch tags list from api articleApi.getTags().then(function () { //fetch registered article data from api articleApi.getArticle(id); }); } else { //fetch tags list articleApi.getTags(); } } componentDidUpdate(prevProps) { if(!this.props.isLoaded && !this.props.route.isEditRoute){ this.refs.child.clearFiles(); store.dispatch(resetArticleModel()); store.dispatch(loadDashboardCompleted()); } } submit() { event.preventDefault(); let data = this.refs.child.getData(); console.log(data); // articleApi.addOrUpdate(data); } render() { return ( <Article submitHandler={this.submit} article={this.props.article} suggestions={this.props.suggestions} ref="child" /> ); } }; const mapStateToProps = store => { return { isLoaded: store.dashboardLayoutState.isLoaded, article: store.articleState.article, suggestions: store.articleState.suggestions }; }; export default connect(mapStateToProps)(ArticleContainer);
test/react/ModalFooter.spec.js
onap-sdc/sdc-ui
import React from 'react'; import ModalFooter from '../../src/react/ModalFooter.js'; import renderer from 'react-test-renderer'; describe('ModalFooter', () => { test('basic test', () => { const footer = renderer.create(<ModalFooter closeButtonText='Ok'/>).toJSON(); expect(footer).toMatchSnapshot(); }); });
examples/react-redux-example/test/todomvc/components/Footer.spec.js
demones/react-guide
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Footer from '../../../app/todomvc/components/Footer' import { SHOW_ALL, SHOW_ACTIVE } from '../../../app/todomvc/constants/TodoFilters' function setup(propOverrides) { const props = Object.assign({ completedCount: 0, activeCount: 0, filter: SHOW_ALL, onClearCompleted: expect.createSpy(), onShow: expect.createSpy() }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render(<Footer {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output } } function getTextContent(elem) { const children = Array.isArray(elem.props.children) ? elem.props.children : [ elem.props.children ] return children.reduce(function concatText(out, child) { // Children are either elements or text strings return out + (child.props ? getTextContent(child) : child) }, '') } describe('components', () => { describe('Footer', () => { it('should render container', () => { const { output } = setup() expect(output.type).toBe('footer') expect(output.props.className).toBe('footer') }) it('should display active count when 0', () => { const { output } = setup({ activeCount: 0 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('No items left') }) it('should display active count when above 0', () => { const { output } = setup({ activeCount: 1 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('1 item left') }) it('should render filters', () => { const { output } = setup() const [ , filters ] = output.props.children expect(filters.type).toBe('ul') expect(filters.props.className).toBe('filters') expect(filters.props.children.length).toBe(3) filters.props.children.forEach(function checkFilter(filter, i) { expect(filter.type).toBe('li') const a = filter.props.children expect(a.props.className).toBe(i === 0 ? 'selected' : '') expect(a.props.children).toBe({ 0: 'All', 1: 'Active', 2: 'Completed' }[i]) }) }) it('should call onShow when a filter is clicked', () => { const { output, props } = setup() const [ , filters ] = output.props.children const filterLink = filters.props.children[1].props.children filterLink.props.onClick({}) expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE) }) it('shouldnt show clear button when no completed todos', () => { const { output } = setup({ completedCount: 0 }) const [ , , clear ] = output.props.children expect(clear).toBe(undefined) }) it('should render clear button when completed todos', () => { const { output } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children expect(clear.type).toBe('button') expect(clear.props.children).toBe('Clear completed') }) it('should call onClearCompleted on clear button click', () => { const { output, props } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children clear.props.onClick({}) expect(props.onClearCompleted).toHaveBeenCalled() }) }) })
webapp/src/App.js
gcallah/Indra
import React from 'react'; import { HashRouter, Route, Switch } from 'react-router-dom'; import styled, { withTheme } from 'styled-components'; import Layout from './components/Layout'; import Home from './components/Home'; import WIP from './components/WIP'; import ModelDetail from './components/ModelDetail'; import ActionMenu from './components/ActionMenu'; import NotFoundPage from './components/NotFoundPage'; import ErrorCatching from './components/ErrorCatching'; const Wrapper = styled('div')` background: ${(props) => props.theme.background}; width: 100vw; min-height: 100vh; font-family: -apple-stem, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen"; h1 { color: ${(props) => props.theme.body}; } `; function App() { return ( <Wrapper> <HashRouter> <Layout> <IndraRoutes /> </Layout> </HashRouter> </Wrapper> ); } export function IndraRoutes() { return ( <Switch> <Route exact path="/" component={Home} /> <Route exact path="/wip" component={WIP} /> <Route exact path="/models/props/:id" component={ModelDetail} /> <Route exact path="/models/menu/:id" component={ActionMenu} /> <Route exact path="/errorCatching" component={ErrorCatching} /> <Route component={NotFoundPage} /> </Switch> ); } export default withTheme(App);
src/svg-icons/notification/wc.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationWc = (props) => ( <SvgIcon {...props}> <path d="M5.5 22v-7.5H4V9c0-1.1.9-2 2-2h3c1.1 0 2 .9 2 2v5.5H9.5V22h-4zM18 22v-6h3l-2.54-7.63C18.18 7.55 17.42 7 16.56 7h-.12c-.86 0-1.63.55-1.9 1.37L12 16h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z"/> </SvgIcon> ); NotificationWc = pure(NotificationWc); NotificationWc.displayName = 'NotificationWc'; NotificationWc.muiName = 'SvgIcon'; export default NotificationWc;
src/components/footer.js
jennywin/donate-for-good
import React, { Component } from 'react'; export default class Footer extends Component { render() { return ( <footer className="footer"> </footer> ); } }
app/components/TabContainer/index.js
JSSolutions/Perfi
import React from 'react'; import T from 'prop-types'; import { StyleSheet, View } from 'react-native'; const s = StyleSheet.create({ container: { position: 'absolute', top: 0, bottom: 0, }, show: { left: 0, right: 0, }, hide: { left: 90000, // over the screen, right: -90000, // over the screen, }, }); const TabContainer = ({ selectedTabIndex, tabIndex, children, topOffset, }) => ( <View style={[ s.container, topOffset && { top: topOffset }, selectedTabIndex === tabIndex ? s.show : s.hide, ]} > {children} </View> ); TabContainer.propTypes = { selectedTabIndex: T.number, tabIndex: T.number, topOffset: T.number, children: T.element, }; export default TabContainer;
app/main.js
wvicioso/dapr
import React, { Component } from 'react'; import { Navigator, StyleSheet, Text, TextInput, ScrollView, TouchableOpacity, View, Image, ListView, LayoutAnimation } from 'react-native'; const Carousel = require('react-native-carousel'); const SideMenu = require('react-native-side-menu'); import Day from './day'; import Dress from './dress'; import OverlayInfo from './overlay_info'; import Forcast from './forcast'; import Details from './details'; export default class Application extends React.Component { constructor() { super(); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([]), temp: [], cond: [], city: '', wind: '', icon: '', } } navigate(routeName) { this.props.navigator.push({ name : routeName }) } componentWillMount() { // Animate creation LayoutAnimation.linear(); } componentDidMount() { fetch("http://api.wunderground.com/api/ae341c3c3cc0ff78/forecast10day/q/NY/New_York_City.json", { method: 'get' }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); if (responseJson !== null) { var temp_arr = [] for(i = 0; i < 8; i++ ) { temp_arr.push(responseJson.forecast.simpleforecast.forecastday[i].high.fahrenheit) } var cond = responseJson.forecast.simpleforecast.forecastday[0].conditions var icon = responseJson.forecast.simpleforecast.forecastday[0].icon_url var city = responseJson.location.city this.setWeather(temp_arr, cond, icon, city) } }) .catch((error) => { throw new Error(error) }) } setWeather(temp, cond, icon, city){ this.setState({ temp: temp, cond: cond, icon: icon, city: city, }) } render() { return ( <View style={{ flex: 1 }} > <View style={{ marginBottom: 20 }}> </View> <Dress /> <Forcast /> <View style={{position: 'absolute', top: 130, left: 20}}> <Text style= {{ color: "black", fontSize: 40, backgroundColor: 'transparent', }}> 65° </Text> </View> <Details /> <View style={{position: 'absolute', top: 300, left: 20}}> <TouchableOpacity> <Text style={{ color: 'white', fontSize: 20, backgroundColor: 'transparent', textAlign: 'center', }}> - </Text> </TouchableOpacity> </View> <View style={{position: 'absolute', top: 300, right: 20}}> <TouchableOpacity> <Text style={{ color: 'white', fontSize: 20, backgroundColor: 'transparent', textAlign: 'center', }}> - </Text> </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ container: { width: 100, backgroundColor: 'transparent', }, });
client/src/containers/CategoryPage/CategoryDetail/index.js
steThera/react-mobx-koa
import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import { SlideLeftTransition } from 'components/RouteTransition'; import { mode } from 'components/FormMobx/utils'; import { getCategory, updateCategory } from '../DetailForm/actions'; import DetailForm from '../DetailForm'; class CategoryDetail extends Component { constructor(props) { super(props); } componentDidMount() { const { code } = this.props.params; if (code) { getCategory(code); } } render() { const { code } = this.props.params; return ( <SlideLeftTransition pathname="CategoryDetail" > <section className="content"> <DetailForm mode={mode.EDIT} onSubmit={(data) => updateCategory({...data, code})} /> </section> </SlideLeftTransition> ) } } export default CategoryDetail;
src/icons/BlurOffIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class BlurOffIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M28 14c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-.4 8.96c.13.02.26.04.4.04 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .14.02.27.04.41.18 1.32 1.23 2.37 2.56 2.55zM28 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-8 0c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm22 14c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-22-7c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm16 16c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-8 27c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM5 10.55l7.57 7.57c-.19-.06-.37-.12-.57-.12-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2c0-.2-.06-.38-.11-.57l5.62 5.62C18.08 25.29 17 26.51 17 28c0 1.66 1.34 3 3 3 1.49 0 2.71-1.08 2.95-2.5l5.62 5.62c-.18-.06-.37-.12-.57-.12-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2c0-.2-.06-.38-.11-.57L37.45 43 40 40.45 7.55 8 5 10.55zM20 34c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm22-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-30-1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm14 22c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-8-7c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/></svg>;} };
src/svg-icons/image/crop-7-5.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop75 = (props) => ( <SvgIcon {...props}> <path d="M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm0 8H5V9h14v6z"/> </SvgIcon> ); ImageCrop75 = pure(ImageCrop75); ImageCrop75.displayName = 'ImageCrop75'; ImageCrop75.muiName = 'SvgIcon'; export default ImageCrop75;
js/components/loaders/ProgressBar.android.js
phamngoclinh/PetOnline_vs2
/* @flow */ import React from 'react'; import ProgressBarAndroid from 'react-native'; import NativeBaseComponent from 'native-base/Components/Base/NativeBaseComponent'; import computeProps from 'native-base/Utils/computeProps'; export default class SpinnerNB extends NativeBaseComponent { prepareRootProps() { const type = { height: 40, }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { const getColor = () => { if (this.props.color) { return this.props.color; } else if (this.props.inverse) { return this.getTheme().inverseProgressColor; } return this.getTheme().defaultProgressColor; }; return ( <ProgressBarAndroid {...this.prepareRootProps()} styleAttr="Horizontal" indeterminate={false} progress={this.props.progress ? this.props.progress / 100 : 0.5} color={getColor()} /> ); } }
code/workspaces/web-app/src/components/common/ConfirmDialog.js
NERC-CEH/datalab
import React from 'react'; import PropTypes from 'prop-types'; import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContentText from '@material-ui/core/DialogContentText'; import PrimaryActionButton from './buttons/PrimaryActionButton'; import SecondaryActionButton from './buttons/SecondaryActionButton'; import theme from '../../theme'; function ConfirmDialog({ state, onSubmit, title, body, onCancel }) { if (!state.open) return null; return ( <Dialog open={state.open} maxWidth="md"> <DialogTitle>{title}</DialogTitle> <DialogContent> <DialogContentText>{body}</DialogContentText> </DialogContent> <DialogActions> <PrimaryActionButton onClick={onSubmit} > Confirm </PrimaryActionButton> <SecondaryActionButton style={{ marginLeft: theme.spacing(1) }} onClick={onCancel} > Cancel </SecondaryActionButton> </DialogActions> </Dialog> ); } ConfirmDialog.propTypes = { onSubmit: PropTypes.func.isRequired, onCancel: PropTypes.func.isRequired, state: PropTypes.object.isRequired, title: PropTypes.string.isRequired, body: PropTypes.string.isRequired, }; export default ConfirmDialog;
src/main.js
idealgardens/codeword
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' // ======================================================== // Browser History Setup // ======================================================== const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // ======================================================== // Store and History Instantiation // ======================================================== // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the routerKey "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) // ======================================================== // Developer Tools Setup // ======================================================== if (__DEBUG__) { if (window.devToolsExtension) { window.devToolsExtension.open() } } // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = (routerKey = null) => { const routes = require('./routes').default(store) ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, MOUNT_NODE ) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle // if (__DEV__ && module.hot) { // const renderApp = render // const renderError = (error) => { // const RedBox = require('redbox-react') // // ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) // } // render = () => { // try { // renderApp(Math.random()) // } catch (error) { // renderError(error) // } // } // module.hot.accept(['./routes'], () => render()) // } // ======================================================== // Go! // ======================================================== render()
src/data-table/DataTable.js
Synchro-TEC/apollo-11
import React from 'react'; import PropTypes from 'prop-types'; import DataTableBody from './data-table-body/DataTableBody'; import DataTableHeader from './data-table-header/DataTableHeader'; class DataTable extends React.Component { constructor(props) { super(props); this.keys = React.Children.map(props.children, child => { return child.props.dataKey; }); } render() { let { children, className, data, onSort } = this.props; return ( <div className="sv-table-responsive-vertical"> <table className={className}> <DataTableHeader onSort={onSort}>{children}</DataTableHeader> <DataTableBody dataTableHeader={this.keys} dataTableRows={data} /> </table> </div> ); } } DataTable.defaultProps = { className: 'sv-table with--hover with--borders', }; DataTable.propTypes = { className: PropTypes.string, data: PropTypes.array.isRequired, onSort: PropTypes.func, }; DataTable.displayName = 'DataTable'; export default DataTable;
cuttlebelle/code/listPosts.js
staystatic/staystatic
import PropTypes from 'prop-types'; import React from 'react'; /** * The listing posts component */ const ListPosts = ({ title, _pages, _relativeURL, _ID }) => ( <div> <b>{ title }</b> <ul className="news"> { Object.keys( _pages ) .filter( page => _pages[ page ]._url.startsWith('/posts/') ) .sort( ( a, b ) => new Date( _pages[ b ].date ) - new Date( _pages[ a ].date ) ) .map( ( page, i ) => <li key={ i }> <a href={ _relativeURL( _pages[ page ]._url, _ID ) }>{ _pages[ page ].pagetitle }</a> </li> ) } </ul> </div> ); ListPosts.propTypes = { /** * title: "News 'n' Updates" */ title: PropTypes.string.isRequired, }; ListPosts.defaultProps = {}; export default ListPosts;
resources/assets/javascript/components/plantsViewPage.js
colinjeanne/garden
import PlantList from './plantList'; import PlantListAddBox from './plantListAddBox'; import PlantView from './plantView'; import React from 'react'; const plantsViewPage = props => { let plantView; if (props.selectedPlant) { plantView = ( <PlantView plant={props.selectedPlant} editing={props.editing} onEdit={editing => props.onEdit(editing, props.selectedPlant)} onUpdatePlant={props.onUpdatePlant} /> ); } return ( <div id="content" className="plantsViewPage"> <div className="plantsViewSidebar"> <PlantListAddBox onAdd={props.onAddPlant} /> <PlantList onFilterPlants={props.onFilterPlants} onSelectPlant={props.onSelectPlant} onSortPlants={props.onSortPlants} plants={props.plants} visiblePlantNames={props.visiblePlantNames} /> </div> {plantView} </div> ); }; plantsViewPage.propTypes = { editing: React.PropTypes.bool.isRequired, onAddPlant: React.PropTypes.func.isRequired, onEdit: React.PropTypes.func.isRequired, onFilterPlants: React.PropTypes.func.isRequired, onSelectPlant: React.PropTypes.func.isRequired, onSortPlants: React.PropTypes.func.isRequired, onUpdatePlant: React.PropTypes.func.isRequired, plants: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, selectedPlant: React.PropTypes.object, visiblePlantNames: React.PropTypes.arrayOf( React.PropTypes.string).isRequired }; export default plantsViewPage;
examples/with-jsxstyle/src/Home.js
jaredpalmer/razzle
import { Block, InlineBlock } from 'jsxstyle'; import React, { Component } from 'react'; class Home extends Component { render() { return ( <Block textAlign="center"> <Block backgroundColor="#222"> <Block fontSize="3rem" color="#fff" padding="6rem 0" fontWeight="800"> Razzle x JSXStyle </Block> </Block> <Block margin="4rem auto"> <Block> To get started, edit <code>src/App.js</code> or{' '} <code>src/Home.js</code> and save to reload. </Block> <Block component="ul" margin="2rem auto"> <InlineBlock component="li" marginRight="1rem"> <a href="https://github.com/jaredpalmer/razzle">Docs</a> </InlineBlock> <InlineBlock component="li" marginRight="1rem"> <a href="https://github.com/jaredpalmer/razzle/issues">Issues</a> </InlineBlock> <InlineBlock component="li"> <a href="https://palmer.chat">Community Slack</a> </InlineBlock> </Block> </Block> </Block> ); } } export default Home;
code/web/node_modules/react-bootstrap/es/FormControlStatic.js
zyxcambridge/RecordExistence
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'p' }; var FormControlStatic = function (_React$Component) { _inherits(FormControlStatic, _React$Component); function FormControlStatic() { _classCallCheck(this, FormControlStatic); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormControlStatic.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return FormControlStatic; }(React.Component); FormControlStatic.propTypes = propTypes; FormControlStatic.defaultProps = defaultProps; export default bsClass('form-control-static', FormControlStatic);
src/index.js
koden-km/sc-react-redux
import SC from 'soundcloud'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { Provider } from 'react-redux'; import configureStore from './stores/configureStore'; import App from './components/App'; import Callback from './components/Callback'; import Stream from './components/Stream'; import { CLIENT_ID, REDIRECT_URI } from './constants/auth'; SC.initialize({ client_id: CLIENT_ID, redirect_uri: REDIRECT_URI }); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Stream} /> <Route path="/" component={Stream} /> <Route path="/callback" component={Callback} /> </Route> </Router> </Provider>, document.getElementById('app') );
src/ui/Item.js
touchstonejs/touchstonejs
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; module.exports = React.createClass({ displayName: 'Item', propTypes: { children: React.PropTypes.node.isRequired, component: React.PropTypes.any, className: React.PropTypes.string, showDisclosureArrow: React.PropTypes.bool }, getDefaultProps () { return { component: 'div' }; }, render () { var componentClass = classnames('Item', { 'Item--has-disclosure-arrow': this.props.showDisclosureArrow }, this.props.className); var props = blacklist(this.props, 'children', 'className', 'showDisclosureArrow'); props.className = componentClass; return React.createElement( this.props.component, props, this.props.children ); } });
node_modules/semantic-ui-react/dist/es/elements/Label/LabelDetail.js
mowbell/clickdelivery-fed-test
import _extends from 'babel-runtime/helpers/extends'; import _isNil from 'lodash/isNil'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; function LabelDetail(props) { var children = props.children, className = props.className, content = props.content; var classes = cx('detail', className); var rest = getUnhandledProps(LabelDetail, props); var ElementType = getElementType(LabelDetail, props); return React.createElement( ElementType, _extends({}, rest, { className: classes }), _isNil(children) ? content : children ); } LabelDetail.handledProps = ['as', 'children', 'className', 'content']; LabelDetail._meta = { name: 'LabelDetail', parent: 'Label', type: META.TYPES.ELEMENT }; process.env.NODE_ENV !== "production" ? LabelDetail.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand } : void 0; export default LabelDetail;
src/components/home/Home.js
uxlayouts/spidermonkey
import React from 'react' const Home = () => ( <div className="container-fluid padding-top-3 padding-bottom-3"> <h2>Home</h2> </div> ) export default Home
dist/frontend/app.js
angeloocana/freecomclub
import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import UserReport from './users/components/UserReport'; console.log('Hello app.tsx'); class HomeRoute extends Relay.Route { } HomeRoute.routeName = 'Home'; HomeRoute.queries = { store: (Component) => Relay.QL ` query MainQuery{ store { ${Component.getFragment('store')} } } ` }; ReactDOM.render(React.createElement(Relay.RootContainer, { Component: UserReport, route: new HomeRoute() }), document.getElementById('react'));
src/components/result.js
ShaneFairweather/React-iTunes
import React, { Component } from 'react'; const Result = (props) => { function parseTime(milliseconds) { var minutes = Math.floor(milliseconds / 60000); var seconds = ((milliseconds % 60000) / 1000).toFixed(0); return minutes + ":" + (seconds < 10 ? '0' : '') + seconds; } return ( <div className="result" onClick={() => props.onItemSelect(props)}> <div className="itunesButton"> <button>View on iTunes.com</button> </div> <div className="resultImg"> <img src={props.imageUrl} /> <div className="clearBox"></div> </div> <div className="resultInfo"> <h3>{props.trackName}</h3> <h5>{props.artistName}</h5> {/*<p className="price">${props.trackPrice}</p>*/} <p className="runTime">{parseTime(props.trackTime)}</p> <p>{props.releaseDate.slice(0, 4)}</p> </div> </div> ) } export default Result;
src/parser/shared/modules/features/BaseHealerStatValues.js
FaideWW/WoWAnalyzer
import React from 'react'; import InformationIcon from 'interface/icons/Information'; import SPELLS from 'common/SPELLS/index'; import { formatNumber } from 'common/format'; import { calculatePrimaryStat, calculateSecondaryStatDefault } from 'common/stats'; import Analyzer from 'parser/core/Analyzer'; import HIT_TYPES from 'game/HIT_TYPES'; import HealingValue from 'parser/shared/modules/HealingValue'; import DamageValue from 'parser/shared/modules/DamageValue'; import CritEffectBonus from 'parser/shared/modules/helpers/CritEffectBonus'; import StatTracker from 'parser/shared/modules/StatTracker'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import StatisticWrapper from 'interface/others/StatisticWrapper'; import CORE_SPELL_INFO from './SpellInfo'; import STAT, { getClassNameColor, getIcon, getName } from './STAT'; const DEBUG = false; // 5% int bonus from wearing all of the highest armor rating (Leather, Mail, Plate) means each new point of int worth 1.05 vs character sheet int export const ARMOR_INT_BONUS = .05; /** * This is currently completely focussed on Healer stat weights but it should be relatively easy to modify it to work for a DPS, it just requires some work. The only reason no effort was put towards this is that we currently have no DPS interested in implementing this so it would be wasted time. If you do want to implement stat weights for a DPS this should provide you with a very good basis. * @property {CritEffectBonus} critEffectBonus * @property {StatTracker} statTracker */ class BaseHealerStatValues extends Analyzer { static dependencies = { critEffectBonus: CritEffectBonus, statTracker: StatTracker, }; // region Spell info // We assume unlisted spells scale with vers only (this will mostly be trinkets) fallbackSpellInfo = { int: false, crit: true, hasteHpm: false, hasteHpct: false, mastery: false, vers: true, }; // This will contain shared settings for things like trinkets and Leech sharedSpellInfo = CORE_SPELL_INFO; // This is for spec specific implementations to override. It gets priority over defaultSpellInfo. spellInfo = {}; mentioned = []; _getSpellInfo(event) { const spellId = event.ability.guid; const specSpecific = this.spellInfo[spellId]; if (specSpecific) { return specSpecific; } const shared = this.sharedSpellInfo[spellId]; if (shared) { return shared; } if (process.env.NODE_ENV === 'development') { if (!this.mentioned.includes(spellId)) { console.warn(`Missing spell definition: ${spellId}: ${event.ability.name}, using fallback:`, this.fallbackSpellInfo); this.mentioned.push(spellId); } } return this.fallbackSpellInfo; } // endregion totalAdjustedHealing = 0; // total healing after excluding 'multiplier' spells like Leech / Velens // These are the total healing that would be gained if their respective stats ratings were increased by one. totalOneInt = 0; totalOneCrit = 0; totalOneHasteHpct = 0; totalOneHasteHpm = 0; totalOneMastery = 0; totalOneVers = 0; // from healing increase only totalOneVersDr = 0; // from damage reduced only totalOneLeech = 0; playerHealthMissing = 0; scaleWeightsWithHealth = false; on_heal(event) { if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) { const healVal = new HealingValue(event.amount, event.absorbed, event.overheal); this._handleHealEvent(event, healVal); } } on_absorbed(event) { if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) { const healVal = new HealingValue(event.amount, 0, 0); this._handleHealEvent(event, healVal); } } on_removebuff(event) { if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) { if (event.absorb) { const healVal = new HealingValue(0, 0, event.absorb); this._handleHealEvent(event, healVal); } } } _handleHealEvent(event, healVal) { const spellInfo = this._getSpellInfo(event); const targetHealthPercentage = (event.hitPoints - healVal.effective) / event.maxHitPoints; // hitPoints contains HP *after* the heal this._handleHeal(spellInfo, event, healVal, targetHealthPercentage); } /** * This actually does that stat weights calculations. * @param spellInfo An object containing information about how to treat the spell, like on what stats it scales. * @param eventForWeights The event that uses the stats to scale its healing. If we're tracking a multiplier (like Beacons), this should be the source of the multiplier. * @param {HealingValue} healVal The actual healing done, all child weight calculators should use this instead of the event data as that might be for another event. * @param targetHealthPercentage The percentage of health the target has remaining BEFORE the heal. * @private */ _handleHeal(spellInfo, eventForWeights, healVal, targetHealthPercentage) { // Most spells are counted in healing total, but some spells scale not on their own but 'second hand' from other spells // I adjust them out of total healing to preserve some accuracy in the "Rating per 1%" stat. // Good examples of multiplier spells are Leech and Velens. if (!spellInfo.multiplier) { this.totalAdjustedHealing += this._adjustGain(healVal.effective, targetHealthPercentage); } if (spellInfo.ignored) { return; } this.totalOneLeech += this._adjustGain(this._leech(eventForWeights, healVal, spellInfo), targetHealthPercentage); if (spellInfo.multiplier) { // Multiplier spells aren't counted for weights because they don't **directly** benefit from stat weights return; } if (spellInfo.int) { this.totalOneInt += this._adjustGain(this._intellect(eventForWeights, healVal), targetHealthPercentage); } if (spellInfo.crit) { this.totalOneCrit += this._adjustGain(this._criticalStrike(eventForWeights, healVal), targetHealthPercentage); } if (spellInfo.hasteHpct) { this.totalOneHasteHpct += this._adjustGain(this._hasteHpct(eventForWeights, healVal), targetHealthPercentage); } if (spellInfo.hasteHpm) { this.totalOneHasteHpm += this._adjustGain(this._hasteHpm(eventForWeights, healVal), targetHealthPercentage); } if (spellInfo.mastery) { this.totalOneMastery += this._adjustGain(this._mastery(eventForWeights, healVal), targetHealthPercentage); } if (spellInfo.vers) { this.totalOneVers += this._adjustGain(this._versatility(eventForWeights, healVal), targetHealthPercentage); } } _adjustGain(gain, targetHealthPercentage) { if (gain === 0) { return 0; } // We want 0-20% health to get value gain, and then linearly decay to 100% health const maxValueHealthPercentage = 0.3; const mult = 1 - Math.max(0, (targetHealthPercentage - maxValueHealthPercentage) / (1 - maxValueHealthPercentage)); return this.scaleWeightsWithHealth ? gain * mult : gain; } _leech(event, healVal, spellInfo) { if (event.type !== 'heal') { return 0; // leech doesn't proc from absorbs } // We have to calculate leech weight differently depending on if we already have any leech rating. // Leech is marked as a 'multplier' heal, so we have to check it before we do the early return below const hasLeech = this.statTracker.currentLeechPercentage > 0; if (hasLeech) { return this._leechHasLeech(event, healVal, spellInfo); } else { return this._leechPrediction(event, healVal, spellInfo); } } _leechHasLeech(event, healVal/*, spellInfo*/) { // When the user has Leech we can use the actual Leech healing to accuractely calculate its HPS value without having to do any kind of predicting const spellId = event.ability.guid; if (spellId !== SPELLS.LEECH.id) { return 0; } if (!healVal.overheal) { return healVal.effective / this.statTracker.currentLeechRating; // TODO: Make a generic method to account for base percentage } return 0; } _leechPrediction(event, healVal, spellInfo) { // Without Leech we will have to make an estimation so we can still provide the user with a decent value if (this.owner.toPlayer(event)) { return 0; // Leech doesn't proc from self-healing } if (spellInfo.multiplier) { return 0; // Leech doesn't proc from multipliers such as Velen's Future Sight } if (this.playerHealthMissing > 0) { // if the player is full HP this would have overhealed. const healIncreaseFromOneLeech = 1 / this.statTracker.leechRatingPerPercent; return healVal.raw * healIncreaseFromOneLeech; } return 0; } _intellect(event, healVal) { if (healVal.overheal) { // If a spell overheals, it could not have healed for more. Seeing as Int only adds HP on top of the existing heal we can skip it as increasing the power of this heal would only be more overhealing. return 0; } const currInt = this.statTracker.currentIntellectRating; // noinspection PointlessArithmeticExpressionJS const healIncreaseFromOneInt = (1 + ARMOR_INT_BONUS) / currInt; return healVal.effective * healIncreaseFromOneInt; } _getCritChance(event) { const rating = this.statTracker.currentCritRating; const baseCritChance = this.statTracker.baseCritPercentage; const ratingCritChance = rating / this.statTracker.critRatingPerPercent; return { baseCritChance, ratingCritChance }; } _isCrit(event) { return event.hitType === HIT_TYPES.CRIT; } _criticalStrike(event, healVal) { if (this._isCrit(event)) { // This collects the total effective healing contributed by the last 1 point of critical strike rating. // We don't make any predictions on normal hits based on crit chance since this would be guess work and we are a log analysis system so we prefer to only work with facts. Actual crit heals are undeniable facts, unlike speculating the chance a normal hit might have crit (and accounting for the potential overhealing of that). const { baseCritChance, ratingCritChance } = this._getCritChance(event); const totalCritChance = baseCritChance + ratingCritChance; if (totalCritChance > (1 + 1 / this.statTracker.critRatingPerPercent)) { // If the crit chance was more than 100%+1 rating, then the last rating was over the cap and worth 0. return 0; } const ratingCritChanceContribution = 1 - baseCritChance / totalCritChance; const critMult = this.critEffectBonus.getBonus(event); const rawBaseHealing = healVal.raw / critMult; const effectiveCritHealing = Math.max(0, healVal.effective - rawBaseHealing); const rating = this.statTracker.currentCritRating; return effectiveCritHealing * ratingCritChanceContribution / rating; } return 0; } _hasteHpct(event, healVal) { const currHastePerc = this.statTracker.currentHastePercentage; const healIncreaseFromOneHaste = 1 / this.statTracker.hasteRatingPerPercent; const baseHeal = healVal.effective / (1 + currHastePerc); return baseHeal * healIncreaseFromOneHaste; } _hasteHpm(event, healVal) { const healIncreaseFromOneHaste = 1 / this.statTracker.hasteRatingPerPercent; const noHasteHealing = healVal.effective / (1 + this.statTracker.currentHastePercentage); return noHasteHealing * healIncreaseFromOneHaste; } _mastery(event, healVal) { throw new Error('Missing custom Mastery implementation. This is different per spec.'); } _versatility(event, healVal) { if (healVal.overheal) { // If a spell overheals, it could not have healed for more. Seeing as Versatility only adds HP on top of the existing heal we can skip it as increasing the power of this heal would only be more overhealing. return 0; } const currVersPerc = this.statTracker.currentVersatilityPercentage; const healIncreaseFromOneVers = 1 / this.statTracker.versatilityRatingPerPercent; const baseHeal = healVal.effective / (1 + currVersPerc); return baseHeal * healIncreaseFromOneVers; } on_toPlayer_damage(event) { this._updateMissingHealth(event); const damageVal = new DamageValue(event.amount, event.absorbed, event.blocked, event.overkill); // const targetHealthPercentage = event.hitPoints / event.maxHitPoints; // hitPoints contains HP *after* the damage taken, which in this case is desirable // this.totalOneVersDr += this._adjustGain(this._versatilityDamageReduction(event, damageVal), targetHealthPercentage); // TODO: Figure out how to make this account for target health since damage event don't appear to have hitPoints info this.totalOneVersDr += this._versatilityDamageReduction(event, damageVal); } _versatilityDamageReduction(event, damageVal) { const amount = damageVal.effective; const currentVersDamageReductionPercentage = this.statTracker.currentVersatilityPercentage / 2; const damageReductionIncreaseFromOneVers = 1 / this.statTracker.versatilityRatingPerPercent / 2; // the DR part is only 50% of the Versa percentage const noVersDamage = amount / (1 - currentVersDamageReductionPercentage); return noVersDamage * damageReductionIncreaseFromOneVers; } on_toPlayer_heal(event) { this._updateMissingHealth(event); } _updateMissingHealth(event) { if (event.hitPoints && event.maxHitPoints) { // fields not always populated, don't know why // `maxHitPoints` is always the value *after* the effect applied this.playerHealthMissing = event.maxHitPoints - event.hitPoints; } } on_finished() { if (DEBUG) { console.log('total', formatNumber(this.totalAdjustedHealing)); console.log(`Int - ${formatNumber(this.totalOneInt)}`); console.log(`Crit - ${formatNumber(this.totalOneCrit)}`); console.log(`Haste HPCT - ${formatNumber(this.totalOneHasteHpct)}`); console.log(`Haste HPM - ${formatNumber(this.totalOneHasteHpm)}`); console.log(`Mastery - ${formatNumber(this.totalOneMastery)}`); console.log(`Vers - ${formatNumber(this.totalOneVers)}`); console.log(`Leech - ${formatNumber(this.totalOneLeech)}`); } } get hpsPerIntellect() { return this._getGain(STAT.INTELLECT) / this.owner.fightDuration * 1000; } get hpsPerCriticalStrike() { return this._getGain(STAT.CRITICAL_STRIKE) / this.owner.fightDuration * 1000; } get hpsPerHasteHPCT() { return this._getGain(STAT.HASTE_HPCT) / this.owner.fightDuration * 1000; } get hpsPerHasteHPM() { return this._getGain(STAT.HASTE_HPM) / this.owner.fightDuration * 1000; } get hpsPerHaste() { return this.hpsPerHasteHPCT + this.hpsPerHasteHPM; } get hpsPerMastery() { return this._getGain(STAT.MASTERY) / this.owner.fightDuration * 1000; } get hpsPerVersatility() { return this._getGain(STAT.VERSATILITY) / this.owner.fightDuration * 1000; } get hpsPerVersatilityDR() { return this._getGain(STAT.VERSATILITY_DR) / this.owner.fightDuration * 1000; } get hpsPerLeech() { return this._getGain(STAT.LEECH) / this.owner.fightDuration * 1000; } // region Item values calculateItemStatsHps(baseStats, itemLevel) { let hps = 0; if (baseStats.primary) { hps += calculatePrimaryStat(baseStats.itemLevel, baseStats.primary, itemLevel) * this.hpsPerIntellect; } if (baseStats.criticalStrike) { hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.criticalStrike, itemLevel) * this.hpsPerCriticalStrike; } if (baseStats.haste) { hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.haste, itemLevel) * this.hpsPerHaste; } if (baseStats.mastery) { hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.mastery, itemLevel) * this.hpsPerMastery; } if (baseStats.versatility) { hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.versatility, itemLevel) * this.hpsPerVersatility; } if (baseStats.leech) { hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.leech, itemLevel) * this.hpsPerLeech; } return hps; } // endregion // region statistic _ratingPerOnePercent(oneRatingHealing) { const onePercentHealing = this.totalAdjustedHealing / 100; return onePercentHealing / oneRatingHealing; } _getGain(stat) { switch (stat) { case STAT.INTELLECT: return this.totalOneInt; case STAT.CRITICAL_STRIKE: return this.totalOneCrit; case STAT.HASTE_HPCT: return this.totalOneHasteHpct; case STAT.HASTE_HPM: return this.totalOneHasteHpm; case STAT.MASTERY: return this.totalOneMastery; case STAT.VERSATILITY: return this.totalOneVers; case STAT.VERSATILITY_DR: return this.totalOneVers + this.totalOneVersDr; case STAT.LEECH: return this.totalOneLeech; default: return 0; } } _getTooltip(stat) { switch (stat) { case STAT.HASTE_HPCT: return 'HPCT stands for "Healing per Cast Time". This is the value that 1% Haste would be worth if you would cast everything you are already casting (and that can be casted quicker) 1% faster. Mana is not accounted for in any way and you should consider the Haste stat weight 0 if you run out of mana while doing everything else right.'; case STAT.HASTE_HPM: return 'HPM stands for "Healing per Mana". In valuing Haste, it considers only the faster HoT ticking and not the reduced cast times. Effectively it models haste\'s bonus to mana efficiency. This is typically the better calculation to use for raid encounters where mana is an issue.'; case STAT.VERSATILITY: return 'Weight includes only the boost to healing, and does not include the damage reduction.'; case STAT.VERSATILITY_DR: return 'Weight includes both healing boost and damage reduction, counting damage reduction as additional throughput.'; default: return null; } } moreInformationLink = null; statistic() { const results = this._prepareResults(); return ( <StatisticWrapper position={STATISTIC_ORDER.CORE(11)}> <div className="col-lg-3 col-md-6 col-sm-6 col-xs-12"> <div className="panel items"> <div className="panel-heading"> <h2> <dfn data-tip="These stat values are calculated using the actual circumstances of this encounter. These values reveal the value of the last 1 rating of each stat, they may not necessarily be the best way to gear. The stat values are likely to differ based on fight, raid size, items used, talents chosen, etc.<br /><br />DPS gains are not included in any of the stat values.">Stat Values</dfn> {this.moreInformationLink && ( <a href={this.moreInformationLink} className="pull-right"> More info </a> )} </h2> </div> <div className="panel-body" style={{ padding: 0 }}> <table className="data-table compact"> <thead> <tr> <th style={{ minWidth: 30 }}><b>Stat</b></th> <th className="text-right" style={{ minWidth: 30 }} colSpan={2}> <dfn data-tip="Normalized so Intellect is always 1.00."><b>Value</b></dfn> </th> </tr> </thead> <tbody> {results.map(row => { const stat = typeof row === 'object' ? row.stat : row; const tooltip = typeof row === 'object' ? row.tooltip : this._getTooltip(stat); const gain = this._getGain(stat); const weight = gain / (this.totalOneInt || 1); const ratingForOne = this._ratingPerOnePercent(gain); const Icon = getIcon(stat); return ( <tr key={stat}> <td className={getClassNameColor(stat)}> <Icon style={{ height: '1.6em', width: '1.6em', marginRight: 10, }} />{' '} {tooltip ? <dfn data-tip={tooltip}>{getName(stat)}</dfn> : getName(stat)} </td> <td className="text-right"> {stat === STAT.HASTE_HPCT && '0.00 - '}{gain !== null ? weight.toFixed(2) : 'NYI'} </td> <td style={{ padding: 6 }}> <InformationIcon data-tip={`${(gain / this.owner.fightDuration * 1000).toFixed(2)} HPS per 1 rating / ${gain !== null ? ( ratingForOne === Infinity ? '∞' : formatNumber(ratingForOne) ) : 'NYI'} rating per 1% throughput`} /> </td> </tr> ); })} </tbody> </table> </div> </div> </div> </StatisticWrapper> ); } // endregion } export default BaseHealerStatValues;
node_modules/react-router/es/RouterContext.js
NickingMeSpace/questionnaire
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import invariant from 'invariant'; import React from 'react'; import createReactClass from 'create-react-class'; import { array, func, object } from 'prop-types'; import getRouteParams from './getRouteParams'; import { ContextProvider } from './ContextUtils'; import { isReactChildren } from './RouteUtils'; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = createReactClass({ displayName: 'RouterContext', mixins: [ContextProvider('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
src/components/couchdb/plain/CouchdbPlain.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './CouchdbPlain.svg' /** CouchdbPlain */ function CouchdbPlain({ width, height, className }) { return ( <SVGDeviconInline className={'CouchdbPlain' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } CouchdbPlain.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default CouchdbPlain
Libraries/Components/WebView/WebView.ios.js
Andreyco/react-native
/** * 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 WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var ReactNative = require('ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var PropTypes = React.PropTypes; var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...View.propTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * A function that is invoked when the webview calls `window.postMessage`. * Setting this property will inject a `postMessage` global into your * webview, but will still call pre-existing values of `postMessage`. * * `window.postMessage` accepts one argument, `data`, which will be * available on the event object, `event.nativeEvent.data`. `data` * must be a string. */ onMessage: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: View.propTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } const messagingEnabled = typeof this.props.onMessage === 'function'; var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} messagingEnabled={messagingEnabled} onMessage={this._onMessage} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * Posts a message to the web view, which will emit a `message` event. * Accepts one argument, `data`, which must be a string. * * In your webview, you'll need to something like the following. * * ```js * document.addEventListener('message', e => { document.title = e.data; }); * ``` */ postMessage = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.postMessage, [String(data)] ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; _onMessage = (event: Event) => { var {onMessage} = this.props; onMessage && onMessage(event); } } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, onMessage: true, messagingEnabled: PropTypes.bool, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
node_modules/react-bootstrap/es/Jumbotron.js
okristian1/react-info
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Jumbotron = function (_React$Component) { _inherits(Jumbotron, _React$Component); function Jumbotron() { _classCallCheck(this, Jumbotron); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Jumbotron.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Jumbotron; }(React.Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; export default bsClass('jumbotron', Jumbotron);
node/webpack/react/es6/es6.js
wushi27/nodejs201606
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; class HelloWorld extends React.Component{ render(){ return ( <p> hello,you aaa! It is {this.props.date.toTimeString()} </p> ); } } var sampleNameSpace = { myDirective:HelloWorld }; setInterval(function(){ ReactDOM.render( <sampleNameSpace.myDirective date={new Date()} />, document.getElementById('test') ); },1000);
node_modules/react-bootstrap/es/SplitToggle.js
cmccandless/SolRFrontEnd
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import DropdownToggle from './DropdownToggle'; var SplitToggle = function (_React$Component) { _inherits(SplitToggle, _React$Component); function SplitToggle() { _classCallCheck(this, SplitToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } SplitToggle.prototype.render = function render() { return React.createElement(DropdownToggle, _extends({}, this.props, { useAnchor: false, noCaret: false })); }; return SplitToggle; }(React.Component); SplitToggle.defaultProps = DropdownToggle.defaultProps; export default SplitToggle;
app/components/TransferSelect/index.js
bruceli1986/react-qdp
/** * * TransferSelect * */ import React from 'react'; import _ from 'lodash'; import { Modal, Button, Input, Transfer } from 'antd'; import classNames from 'classnames'; import { FormattedMessage } from 'react-intl'; import styles from './styles.css'; const InputGroup = Input.Group; class TransferSelect extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props, context) { super(props, context); this.state = { visible: false, selectedRowKeys: [], query: '', }; } componentWillReceiveProps(nextProps) { if (!nextProps.value) { this.setState({ selectedRowKeys: [], query: '', }); } } getClassName = (record, index) => { const { selectedRowKeys } = this.state; if (selectedRowKeys.indexOf(record[this.props.valueField]) >= 0) { return 'qdp-row-selected'; } return ''; } showModal = () => { if (this.props.disabled !== true) { let show = true; if (this.props.onClick) { show = this.props.onClick(this.props.value); } this.setState({ visible: show, }); } } getValue() { const dataSource = this.filterDateSource(); const field = this.props.valueField; if (!field) { return ''; } const result = this.state.selectedRowKeys.map((x) => { const record = dataSource.find(function (y) { return y[field] === x; }); if (!record) { return []; } return record[field]; }); // console.log('getValue', result.toString()); return result.toString(); } getRecords() { const dataSource = this.props.dataSource; const field = this.props.valueField; if (!field) { return []; } const result = this.state.selectedRowKeys.map((x) => (dataSource.find(function (y) { return y[field] === x; }))); return result; } handleCancel = (e) => { this.setState({ visible: false, }); } getText() { const { textField, valueField, value, dataSource } = this.props; const _value = value ? value.split(',') : []; // console.log('_value:', _value); const field = textField ? textField : valueField; const records = dataSource ? dataSource.filter((x) => _value.indexOf(x[valueField]) >= 0) : []; // console.log('records:', records); const text = records ? records.map((x) => x[field]).toString() : ''; return text; } // setQuery = (fields) => { // this.setState({ // query: Object.assign(this.state.query, fields), // }); // } _Submit = (form) => { if (this.props.onSearch) { this.props.onSearch(form); } else { this.setState({ filter: form }); } } filterDateSource() { const { dataSource, searchField } = this.props; const { query } = this.state; let result = []; // if (dataSource) { // result = dataSource.filter(function (x) { // let a = true; // for (var key in filter) { // let reg = new RegExp(`${filter[key]}`, 'i'); // if (filter[key] && x[key].search(reg) < 0) { // return false; // } // } // return a; // }); // } // console.log('dataSource:', dataSource); if (dataSource) { let reg = new RegExp(query, 'i'); result = dataSource.filter((x) => { return searchField.some(y => reg.test(x[y])); // let str = searchField.reduce((a, b) => x[a] + x[b] ); // return reg.test(x[textField]) || reg.test(x[valueField]); }); if (result.length > 200) { result = result.slice(0, 200); } } return result; } render() { const { style, placeholder, multiple } = this.props; const { loading, selectedRowKeys } = this.state; const btnCls = classNames({ 'ant-search-btn': true, 'ant-search-btn-noempty': !!(this.props.value || '').trim(), }); const searchCls = classNames({ 'ant-search-input': true, 'ant-search-input-focus': true, }); const dataSource = this.filterDateSource(); return ( <div> <div className="ant-search-input-wrapper" style={style}> <InputGroup className={searchCls}> <Input placeholder={placeholder} onClick={this.showModal} value={this.getText()} disabled={this.props.disabled} /> <Input style={{ display: 'none' }} value={this.props.value} /> <div className="ant-input-group-wrap"> <Button icon="search" className={btnCls} size="small" onClick={this.handleSearch} style={{ height: '26px' }} /> </div> </InputGroup> </div> <Modal title={this.props.modalTitle} visible={this.state.visible} onCancel={this.handleCancel} width={this.props.modalWidth} footer={null} > <Transfer className={styles.transfer} listStyle={{ flex: '1', height: '300px' }} showSearch dataSource={dataSource} titles={this.props.title} targetKeys={this.props.targetKeys} selectedKeys={this.props.selectedKeys} rowKey={record => record.id} onChange={this.props.onChange} onSearchChange={(direction, event) => { if (direction === 'left') { this.setState({ query: event.target.value, }); } }} render={this.props.render} /> </Modal> </div> ); } } export default TransferSelect;
src/components/book_display_component.js
allenyin55/reading_with_Annie
import React from 'react'; import { Link } from 'react-router'; import moment from 'moment-timezone'; const BookDisplay = ({book, isInList}) => { if(isInList){ // for teh sake of the book that doesn't have bookinfo or volumeinfo if(book.bookinfo === null || book.bookinfo.volumeInfo === undefined) return <Link to={"books/" + book.id}> {book.title} </Link>; return( <div> <div> <div> <img src={ book.bookinfo.volumeInfo.imageLinks.thumbnail} style={{width: 128+"px"}}/> </div> <Link to={"books/" + book.id}> {book.title} </Link> </div> {(book.bookinfo.volumeInfo.authors !== undefined) ? (<div>{book.bookinfo.volumeInfo.authors[0]}</div>) : (<div>No author</div>)} <div>{moment.tz(book.dateadded, "Zulu").tz("America/Los_Angeles").format().substring(0, 10)} added</div> </div> ) } // for teh sake of the book that doesn't have bookinfo or volumeinfo if(book.bookinfo === null || book.bookinfo.volumeInfo === undefined) return <div>The book doesn't have book info</div> if (book.bookinfo.volumeInfo.description === undefined ){ book.bookinfo.volumeInfo.description = "No Description"; } return( <div> {(book.bookinfo.volumeInfo.authors !== undefined) ? (<div>by {book.bookinfo.volumeInfo.authors[0]}</div>) : (<div>No author</div>)} <div> <div> <img src={ book.bookinfo.volumeInfo.imageLinks.thumbnail} style={{width: 128+"px"}}/> </div> </div> {(book.bookinfo.volumeInfo.description.length<400) ? (<p>{book.bookinfo.volumeInfo.description}</p>) :(<p>{book.bookinfo.volumeInfo.description.slice(0,399)} ......</p>)} </div> ) }; export default BookDisplay;
app/javascript/flavours/glitch/components/status_list.js
glitch-soc/mastodon
import { debounce } from 'lodash'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from 'flavours/glitch/containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import LoadGap from './load_gap'; import ScrollableList from './scrollable_list'; import RegenerationIndicator from 'flavours/glitch/components/regeneration_indicator'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, alwaysPrepend: PropTypes.bool, emptyMessage: PropTypes.node, timelineId: PropTypes.string.isRequired, }; static defaultProps = { trackScroll: true, }; getFeaturedStatusCount = () => { return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0; } getCurrentStatusIndex = (id, featured) => { if (featured) { return this.props.featuredStatusIds.indexOf(id); } else { return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount(); } } handleMoveUp = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) - 1; this._selectChild(elementIndex, true); } handleMoveDown = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) + 1; this._selectChild(elementIndex, false); } handleLoadOlder = debounce(() => { this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined); }, 300, { leading: true }) _selectChild (index, align_top) { const container = this.node.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, onLoadMore, timelineId, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return <RegenerationIndicator />; } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map((statusId, index) => statusId === null ? ( <LoadGap key={'gap:' + statusIds.get(index + 1)} disabled={isLoading} maxId={index > 0 ? statusIds.get(index - 1) : null} onClick={onLoadMore} /> ) : ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} /> )).concat(scrollableContent); } return ( <ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
examples/basic/components/Input.js
babotech/redux-uniform
import React from 'react' const Input = (props) => { const style = { ...defaultStyle, borderColor: !props.dirty ? `none` : !props.valid ? `#ff0000` : `#363636` } return ( <input style={style} {...props} /> ) } export default Input const defaultStyle = { display: `block`, marginBottom: `10px`, width: `100%`, boxSizing: `border-box`, border: `1ps solid` }
app/components/TimelineEvent/index.js
samtgarson/MyFirstReactNativeApp
/* * * TimelineEvent * */ import ReactNative from 'react-native'; import React, { Component } from 'react'; import styles from './styles'; const { Animated, View, Text, ScrollView } = ReactNative; const FINAL_HEIGHT = 120 const RELEASE_OFFSET = 80 class TimelineEvent extends Component { constructor (props) { super(props) this.state = { rowHeight: new Animated.Value(0), scrollOffset: new Animated.Value(0), releaseToHide: false } } componentDidMount () { Animated.timing( this.state.rowHeight, {toValue: FINAL_HEIGHT} ).start(); this.state.scrollOffset.addListener(({value}) => { this.setState({ releaseToHide: value >= RELEASE_OFFSET }) }) } onRelease () { if (this.state.releaseToHide) this.props.hideEvent() } render () { const rowOpacity = this.state.rowHeight.interpolate({ inputRange: [0, FINAL_HEIGHT], outputRange: [0, 1] }) const onScroll = Animated.event( [{nativeEvent: {contentOffset: {x: this.state.scrollOffset}}}] ) const bgColor = this.state.scrollOffset.interpolate({ inputRange: [1, 2, RELEASE_OFFSET - 10, RELEASE_OFFSET], outputRange: ['white', 'rgb(207,216,220)', 'rgb(207,216,220)', 'rgb(211,47,47)'], extrapolate: 'clamp' }) return ( <Animated.View style={[styles.container, {opacity: rowOpacity, backgroundColor: bgColor}]}> <ScrollView scrollEventThrottle={16} horizontal={true} contentContainerStyle={styles.scroll} onScroll={onScroll} onTouchEnd={this.onRelease.bind(this)} > <Animated.View style={[styles.event, {height: this.state.rowHeight}]}> <Text>{this.props.text}</Text> <Text>{this.props.createdAt.getSeconds()}</Text> </Animated.View> </ScrollView> </Animated.View> ) } } export default TimelineEvent;
packages/showcase/plot/labeled-stacked-vertical-bar-chart.js
uber-common/react-vis
// Copyright (c) 2016 - 2017 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 ShowcaseButton from '../showcase-components/showcase-button'; import { XYPlot, XAxis, YAxis, VerticalGridLines, HorizontalGridLines, VerticalBarSeries, VerticalBarSeriesCanvas, LabelSeries } from 'react-vis'; export default class Example extends React.Component { state = { useCanvas: false }; render() { const {useCanvas} = this.state; const BarSeries = useCanvas ? VerticalBarSeriesCanvas : VerticalBarSeries; const content = useCanvas ? 'TOGGLE TO SVG' : 'TOGGLE TO CANVAS'; const data = [ [ {x: 1, y: 8}, {x: 3, y: 5}, {x: 4, y: 15} ], [ {x: 3, y: 9}, {x: 4, y: 2}, {x: 5, y: 7} ], [ {x: 2, y: 11}, {x: 3, y: 7}, {x: 4, y: 9} ] ]; const labelsData = data.map(value => value.map(tuple => ({x: tuple.x, y: tuple.y, label: tuple.y.toString()})) ); const bars = data.map((value, index) => ( <BarSeries data={value} key={index} /> )); const labels = labelsData.map((value, index) => ( <LabelSeries data={value} key={index} labelAnchorY="hanging" style={{fill: '#ff8c00'}} /> )); return ( <div> <ShowcaseButton onClick={() => this.setState({useCanvas: !useCanvas})} buttonContent={content} /> <XYPlot width={300} height={300} stackBy="y"> <VerticalGridLines /> <HorizontalGridLines /> <XAxis /> <YAxis /> {bars} {labels} </XYPlot> </div> ); } }
examples/src/components/StatesField.js
namuol/react-select-seamstress
import React from 'react'; import Select from 'react-select'; const STATES = require('../data/states'); var id = 0; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var StatesField = React.createClass({ displayName: 'StatesField', propTypes: { label: React.PropTypes.string, searchable: React.PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, id: ++id, selectValue: 'new-south-wales' }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { logChange('State changed to ' + newValue); this.setState({ selectValue: newValue || null }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var ops = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" options={ops} disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } }); module.exports = StatesField;
internals/templates/containers/App/index.js
gtct/wallet.eine.com
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * 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'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
src/routes.js
sylnp0201/react-redux-universal-hot-example
import React from 'react'; import {Route} from 'react-router'; import { App, Home, Widgets, About, Login, RequireLogin, LoginSuccess, Survey, NotFound, } from 'containers'; export default function(store) { return ( <Route component={App}> <Route path="/" component={Home}/> <Route path="/widgets" component={Widgets}/> <Route path="/about" component={About}/> <Route path="/login" component={Login}/> <Route component={RequireLogin} onEnter={RequireLogin.onEnter(store)}> <Route path="/loginSuccess" component={LoginSuccess}/> </Route> <Route path="/survey" component={Survey}/> <Route path="*" component={NotFound}/> </Route> ); }
dashboard/client/src/js/components/modules/VariationStats.js
jigarjain/sieve
import React from 'react'; import Loader from './base/Loader'; import Helpers from '../../utils/helpers'; const statTypes = [ { type: 'count', text: 'Counts' }, { type: 'convRate', text: 'Conversion Rate' }, { type: 'zScore', text: 'Z Score' }, { type: 'pValue', text: 'p Value' } ]; function getTableHeaderLabels(variations) { const labels = ['Variations']; statTypes.forEach(v => { labels.push(v.text); }); return labels; } function getTableRowItems(variations, variationStats, selectedEvent) { const rows = variations.map(v => { const values = [v.name]; statTypes.forEach(stat => { const stats = variationStats[v.id]; const valueExists = stats.some(s => { if (s.name === selectedEvent) { let value = s[stat.type]; if (value) { value = Helpers.roundFloatingNumber(value, 3); } values.push(value); } return s.name === selectedEvent; }); if (!valueExists) { values.push('NA'); } }); return values; }); return rows; } export default function (props) { if (props.statsApiStatus.isFetching) { return <Loader />; } if (props.statsApiStatus.errors) { return 'Some error occured'; } const tableHeaders = getTableHeaderLabels(props.variations); const tableItems = getTableRowItems( props.variations, props.variationStats, props.selectedEvent ); return ( <table className="table is-bordered stats-table"> <thead> <tr> { tableHeaders.map((t, i) => { return ( <th key={i}>{t}</th> ); }) } </tr> </thead> <tbody> { tableItems.map((items, i) => { return ( <tr key={i}> { items.map((item, j) => { return <td key={j}>{item || 'NA'}</td>; }) } </tr> ); }) } </tbody> </table> ); }
test/BootstrapMixinSpec.js
mengmenglv/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import BootstrapMixin from '../src/BootstrapMixin'; import styleMaps from '../src/styleMaps'; import { shouldWarn } from './helpers'; let Component; describe('BootstrapMixin', function () { beforeEach(function() { Component = React.createClass({ mixins: [BootstrapMixin], render() { return React.DOM.button(this.props); } }); }); describe('#getBsClassSet', function () { it('should return blank', function () { let instance = ReactTestUtils.renderIntoDocument( <Component> content </Component> ); assert.deepEqual(instance.getBsClassSet(), {}); }); it('maps and validates OK default classes', function () { function instanceClassSet(bsClass) { let instance = ReactTestUtils.renderIntoDocument( <Component bsClass={bsClass}> content </Component> ); return instance.getBsClassSet(); } assert.deepEqual(instanceClassSet('column'), {'col': true}); assert.deepEqual(instanceClassSet('button'), {'btn': true}); assert.deepEqual(instanceClassSet('button-group'), {'btn-group': true}); assert.deepEqual(instanceClassSet('label'), {'label': true}); assert.deepEqual(instanceClassSet('alert'), {'alert': true}); assert.deepEqual(instanceClassSet('input-group'), {'input-group': true}); assert.deepEqual(instanceClassSet('form'), {'form': true}); assert.deepEqual(instanceClassSet('panel'), {'panel': true}); }); describe('Predefined Bootstrap styles', function () { it('maps and validates OK default styles', function () { function instanceClassSet(style) { let instance = ReactTestUtils.renderIntoDocument( <Component bsClass='button' bsStyle={style}> content </Component> ); return instance.getBsClassSet(); } assert.deepEqual(instanceClassSet('default'), {'btn': true, 'btn-default': true}); assert.deepEqual(instanceClassSet('primary'), {'btn': true, 'btn-primary': true}); assert.deepEqual(instanceClassSet('success'), {'btn': true, 'btn-success': true}); assert.deepEqual(instanceClassSet('info'), {'btn': true, 'btn-info': true}); assert.deepEqual(instanceClassSet('link'), {'btn': true, 'btn-link': true}); assert.deepEqual(instanceClassSet('inline'), {'btn': true, 'btn-inline': true}); }); }); describe('Sizes', function () { it('maps english words for sizes to bootstrap sizes constants', function () { function instanceClassSet(size) { let instance = ReactTestUtils.renderIntoDocument( <Component bsClass='button' bsSize={size}> content </Component> ); return instance.getBsClassSet(); } assert.deepEqual(instanceClassSet('large'), {'btn': true, 'btn-lg': true}); assert.deepEqual(instanceClassSet('small'), {'btn': true, 'btn-sm': true}); assert.deepEqual(instanceClassSet('medium'), {'btn': true, 'btn-md': true}); assert.deepEqual(instanceClassSet('xsmall'), {'btn': true, 'btn-xs': true}); }); }); describe('Custom styles', function () { it('should validate OK custom styles added via "addStyle()"', function () { styleMaps.addStyle('wacky'); let instance = ReactTestUtils.renderIntoDocument( <Component bsClass='button' bsStyle='wacky'> content </Component> ); assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-wacky': true}); }); it('should allow custom styles as is but with validation warning', function () { let instance = ReactTestUtils.renderIntoDocument( <Component bsClass='button' bsStyle='my-custom-class'> content </Component> ); assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'my-custom-class': true}); shouldWarn('Invalid prop `bsStyle` of value `my-custom-class`'); }); }); }); // todo: fix bad naming describe('#prefixClass', function () { it('allows custom sub-classes', function () { let instance = ReactTestUtils.renderIntoDocument( <Component bsClass='button'> content </Component> ); assert.equal(instance.prefixClass('title'), 'btn-title'); }); }); });
examples/todomvc/containers/TodoApp.js
Lucifier129/redux
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Header from '../components/Header'; import MainSection from '../components/MainSection'; import * as TodoActions from '../actions/todos'; class TodoApp extends Component { render() { const { todos, dispatch } = this.props; const actions = bindActionCreators(TodoActions, dispatch); return ( <div> <Header addTodo={actions.addTodo} /> <MainSection todos={todos} actions={actions} /> </div> ); } } function select(state) { return { todos: state.todos }; } export default connect(select)(TodoApp);
src/svg-icons/editor/format-align-right.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatAlignRight = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"/> </SvgIcon> ); EditorFormatAlignRight = pure(EditorFormatAlignRight); EditorFormatAlignRight.displayName = 'EditorFormatAlignRight'; EditorFormatAlignRight.muiName = 'SvgIcon'; export default EditorFormatAlignRight;
examples/with-apollo-auth/lib/with-data.js
arunoda/next.js
import React from 'react' import cookie from 'cookie' import PropTypes from 'prop-types' import { ApolloProvider, getDataFromTree } from 'react-apollo' import initApollo from './init-apollo' function parseCookies (ctx = {}, options = {}) { return cookie.parse( ctx.req && ctx.req.headers.cookie ? ctx.req.headers.cookie : document.cookie, options ) } export default ComposedComponent => { return class WithData extends React.Component { static displayName = `WithData(${ComposedComponent.displayName})` static propTypes = { serverState: PropTypes.object.isRequired } static async getInitialProps (context) { let serverState = {} // Setup a server-side one-time-use apollo client for initial props and // rendering (on server) let apollo = initApollo({}, { getToken: () => parseCookies(context).token }) // Evaluate the composed component's getInitialProps() let composedInitialProps = {} if (ComposedComponent.getInitialProps) { composedInitialProps = await ComposedComponent.getInitialProps(context, apollo) } // Run all graphql queries in the component tree // and extract the resulting data if (!process.browser) { if (context.res && context.res.finished) { // When redirecting, the response is finished. // No point in continuing to render return } // Provide the `url` prop data in case a graphql query uses it const url = {query: context.query, pathname: context.pathname} // Run all graphql queries const app = ( <ApolloProvider client={apollo}> <ComposedComponent url={url} {...composedInitialProps} /> </ApolloProvider> ) await getDataFromTree(app) // Extract query data from the Apollo's store const state = apollo.getInitialState() serverState = { apollo: { // Make sure to only include Apollo's data state data: state.data } } } return { serverState, ...composedInitialProps } } constructor (props) { super(props) // Note: Apollo should never be used on the server side beyond the initial // render within `getInitialProps()` above (since the entire prop tree // will be initialized there), meaning the below will only ever be // executed on the client. this.apollo = initApollo(this.props.serverState, { getToken: () => parseCookies().token }) } render () { return ( <ApolloProvider client={this.apollo}> <ComposedComponent {...this.props} /> </ApolloProvider> ) } } }
src/svg-icons/maps/beenhere.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsBeenhere = (props) => ( <SvgIcon {...props}> <path d="M19 1H5c-1.1 0-1.99.9-1.99 2L3 15.93c0 .69.35 1.3.88 1.66L12 23l8.11-5.41c.53-.36.88-.97.88-1.66L21 3c0-1.1-.9-2-2-2zm-9 15l-5-5 1.41-1.41L10 13.17l7.59-7.59L19 7l-9 9z"/> </SvgIcon> ); MapsBeenhere = pure(MapsBeenhere); MapsBeenhere.displayName = 'MapsBeenhere'; MapsBeenhere.muiName = 'SvgIcon'; export default MapsBeenhere;
admin/client/components/Navigation/SecondaryNavigation.js
pswoodworth/keystone
import React from 'react'; import { Container } from 'elemental'; var SecondaryNavItem = React.createClass({ displayName: 'SecondaryNavItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, href: React.PropTypes.string.isRequired, path: React.PropTypes.string, title: React.PropTypes.string, }, render () { return ( <li className={this.props.className} data-list-path={this.props.path}> <a href={this.props.href} title={this.props.title} tabIndex="-1"> {this.props.children} </a> </li> ); }, }); var SecondaryNavigation = React.createClass({ displayName: 'SecondaryNavigation', propTypes: { currentListKey: React.PropTypes.string, lists: React.PropTypes.array.isRequired, }, getInitialState () { return {}; }, componentDidMount () { this.handleResize(); window.addEventListener('resize', this.handleResize); }, componentWillUnmount () { window.removeEventListener('resize', this.handleResize); }, handleResize () { this.setState({ navIsVisible: this.props.lists && this.props.lists.length > 1 && window.innerWidth >= 768, }); }, renderNavigation (lists) { const navigation = lists.map((list) => { const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; const className = (this.props.currentListKey && this.props.currentListKey === list.path) ? 'active' : null; return ( <SecondaryNavItem key={list.path} path={list.path} className={className} href={href}> {list.label} </SecondaryNavItem> ); }); return ( <ul className="app-nav app-nav--secondary app-nav--left"> {navigation} </ul> ); }, render () { if (!this.state.navIsVisible) return null; return ( <nav className="secondary-navbar"> <Container clearfix> {this.renderNavigation(this.props.lists)} </Container> </nav> ); }, }); module.exports = SecondaryNavigation;
app/components/Notice.js
Toreant/monster_web
/** * Created by apache on 15-10-30. */ import React from 'react'; import NoticeActions from '../actions/NoticeActions'; import NoticeStore from '../stores/NoticeStore'; import {Link} from 'react-router'; import Loading from './Loading'; class Notice extends React.Component { constructor(props) { super(props); this.state = NoticeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { NoticeStore.listen(this.onChange); NoticeActions.getNoticesList(); } componentWillUnmount() { NoticeStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } readed(_id) { NoticeActions.getNotice(_id); } render() { let Target = null; if(this.state.loading === false && this.state.notices.length !== 0) { Target = this.state.notices.map((data) => { return ( <div key={data.notice._id} data-item={data.notice._id} className="mon-conlist-item mon-notice-item media animated flipInX"> <div className="media-left"> <Link to={'/member/'+data.user.domain}> <img src={data.user.avatar_url} alt="loading" width="60"/> </Link> </div> <div className="media-body"> <p className="text-info"> {data.notice.content} </p> <div> <span> {(new Date(data.notice.create_time)).toLocaleDateString()} </span> </div> </div> <button className="btn btn-danger mon-read" onClick={this.readed.bind(this,data.notice._id)}> 已读 </button> </div> ); }); } else if(this.state.loading === false && this.state.notices.length === 0) { Target = ( <div className="bg-primary mon-padding"> 没有私信或通知 </div> ); } else if(this.state.loading === true) { Target = <Loading /> } return ( <div className='col-md-9 col-sm-9'> <p className="bg-info mon-bg-title mon-padding"> 通知/私信 </p> {Target} </div> ); } } export default Notice;
packages/cp-frontend/src/components/services/list-item.js
yldio/copilot
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import forceArray from 'force-array'; import sortBy from 'lodash.sortby'; import { isNot } from 'styled-is'; import { Col, Row } from 'react-styled-flexboxgrid'; import remcalc from 'remcalc'; import { InstancesIcon, HealthyIcon } from 'joyent-ui-toolkit'; import Status from './status'; import { Small, MetricGraph, Card, CardView, CardTitle, CardDescription, CardGroupView, CardOptions, CardHeader, CardInfo, Anchor } from 'joyent-ui-toolkit'; const StyledCardHeader = styled(CardHeader)`position: relative;`; const TitleInnerContainer = styled.div` display: flex; flex-direction: row; justify-content: left; align-items: center; `; const StyledAnchor = styled(Anchor)` ${isNot('active')` color: ${props => props.theme.text} `}; `; const GraphsContainer = styled(Row)` background: #f6f7fe; width: 50%; margin: 0; flex: 1; `; const GraphContainer = styled(Col)` position: relative; border-left: ${remcalc(1)} solid #d8d8d8; padding-top: ${remcalc(20)}; `; const GraphLeftShaddow = styled.div` z-index: 99; position: absolute; margin-left: ${remcalc(-8)}; margin-top: ${remcalc(-20)}; width: ${remcalc(12)}; height: 100%; background-image: linear-gradient( to right, rgba(213, 216, 231, 0.8), rgba(243, 244, 249, 0) ); `; const GraphTitle = Small.extend` z-index: 99; position: absolute; top: 0; left: 0; right: 0; height: ${remcalc(20)}; border-bottom: ${remcalc(1)} solid #d8d8d8; font-size: ${remcalc(13)}; text-align: center; color: #494949; `; const HealthyIconStyled = styled(HealthyIcon)` /* I SAID NO PRETTIER */ display: flex; `; const ChildTitle = styled(CardTitle)` padding: 0; flex: 0 1 auto; align-self: stretch; `; const ServiceView = styled(CardView)`height: ${remcalc(120)};`; const StatusContainer = styled(CardDescription)` display: flex; flex-direction: column; flex-wrap: nowrap; justify-content: center; align-content: center; align-items: stretch; `; const HealthInfoContainer = styled.div` flex: 0 1 auto; align-self: flex-end; position: absolute; bottom: 0; `; const ServiceListItem = ({ onQuickActionsClick = () => {}, deploymentGroup = '', service, isChild = false }) => { const handleCardOptionsClick = evt => { onQuickActionsClick(evt, service); }; const children = sortBy(forceArray(service.children), ['slug']); // const isServiceInactive = service.status && service.status !== 'ACTIVE'; const to = `/deployment-groups/${deploymentGroup}/services/${service.slug}`; const instancesCount = children.length ? children.reduce((count, child) => count + child.instances.length, 0) : service.instances.length; const childrenItems = children.length ? children.map(service => ( <ServiceListItem key={service.id} deploymentGroup={deploymentGroup} service={service} isChild /> )) : null; const title = isChild ? ( <ChildTitle>{service.name}</ChildTitle> ) : ( <CardTitle> <TitleInnerContainer> <StyledAnchor to={to} secondary active={service.instancesActive}> {service.name} </StyledAnchor> </TitleInnerContainer> </CardTitle> ); const header = !isChild ? ( <StyledCardHeader> {title} <CardDescription> <CardInfo icon={<InstancesIcon />} iconPosition="left" label={`${instancesCount} ${instancesCount > 1 ? 'instances' : 'instance'}`} color={!service.instancesActive ? 'disabled' : 'light'} /> </CardDescription> <CardOptions onClick={handleCardOptionsClick} /> </StyledCardHeader> ) : null; let healthyInfo = null; if (service.instancesActive) { const { total, healthy } = service.instancesHealthy; const iconHealthy = total === healthy ? 'HEALTHY' : 'NOT HEALTHY'; const icon = <HealthyIconStyled healthy={iconHealthy} />; const label = `${healthy} of ${total} healthy`; healthyInfo = ( <CardInfo icon={icon} iconPosition="left" label={label} color="dark" /> ); } const graphs = !children.length && service.metrics && Object.keys(service.metrics).length ? Object.keys(service.metrics).map(key => ( <GraphContainer xs={4}> <GraphLeftShaddow /> <GraphTitle>{key}</GraphTitle> <MetricGraph key={key} metricsData={service.metrics[key]} graphDurationSeconds={90} /> </GraphContainer> )) : null; const metrics = graphs ? <GraphsContainer>{graphs}</GraphsContainer> : null; const view = children.length ? ( <CardGroupView>{childrenItems}</CardGroupView> ) : ( <ServiceView> <StatusContainer> {isChild && title} <Status service={service} /> <HealthInfoContainer>{healthyInfo}</HealthInfoContainer> </StatusContainer> {metrics} </ServiceView> ); return ( <Card collapsed={service.collapsed} active={service.instancesActive} flat={isChild} headed={!isChild} key={service.id} stacked={isChild && service.instances > 1} > {header} {view} </Card> ); }; ServiceListItem.propTypes = { onQuickActionsClick: PropTypes.func, deploymentGroup: PropTypes.string, service: PropTypes.object.isRequired // Define better }; export default ServiceListItem;
app/javascript/mastodon/features/standalone/public_timeline/index.js
ashfurrow/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandPublicTimeline, expandCommunityTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { local }) => { const timeline = state.getIn(['timelines', local ? 'community' : 'public'], ImmutableMap()); return { statusIds: timeline.get('items', ImmutableList()), isLoading: timeline.get('isLoading', false), hasMore: timeline.get('hasMore', false), }; }; export default @connect(mapStateToProps) class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, local: PropTypes.bool, }; componentDidMount () { this._connect(); } componentDidUpdate (prevProps) { if (prevProps.local !== this.props.local) { this._connect(); } } _connect () { const { dispatch, local } = this.props; dispatch(local ? expandCommunityTimeline() : expandPublicTimeline()); } handleLoadMore = () => { const { dispatch, statusIds, local } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(local ? expandCommunityTimeline({ maxId }) : expandPublicTimeline({ maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
packages/ringcentral-widgets-demo/dev-server/containers/App/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import sleep from 'ringcentral-integration/lib/sleep'; import AlertContainer from 'ringcentral-widgets/containers/AlertContainer'; import ConnectivityBadgeContainer from 'ringcentral-widgets/containers/ConnectivityBadgeContainer'; import LoginPage from 'ringcentral-widgets/containers/LoginPage'; import CallingSettingsPage from 'ringcentral-widgets/containers/CallingSettingsPage'; import RegionSettingsPage from 'ringcentral-widgets/containers/RegionSettingsPage'; import AudioSettingsPage from 'ringcentral-widgets/containers/AudioSettingsPage'; import DialerPage from 'ringcentral-widgets/containers/DialerPage'; import ComposeTextPage from 'ringcentral-widgets/containers/ComposeTextPage'; import ConversationPage from 'ringcentral-widgets/containers/ConversationPage'; import ConferencePage from 'ringcentral-widgets/containers/ConferencePage'; import ConferenceCommands from 'ringcentral-widgets/components/ConferenceCommands'; import ConversationsPage from 'ringcentral-widgets/containers/ConversationsPage'; import SettingsPage from 'ringcentral-widgets/containers/SettingsPage'; import ActiveCallsPage from 'ringcentral-widgets/containers/ActiveCallsPage'; import CallsListPage from 'ringcentral-widgets/containers/CallsListPage'; import IncomingCallPage from 'ringcentral-widgets/containers/IncomingCallPage'; import CallCtrlPage from 'ringcentral-widgets/containers/CallCtrlPage'; import CallBadgeContainer from 'ringcentral-widgets/containers/CallBadgeContainer'; import RecentActivityContainer from 'ringcentral-widgets/containers/RecentActivityContainer'; import ContactsPage from 'ringcentral-widgets/containers/ContactsPage'; import ContactDetailsPage from 'ringcentral-widgets/containers/ContactDetailsPage'; import FeedbackPage from 'ringcentral-widgets/containers/FeedbackPage'; import UserGuidePage from 'ringcentral-widgets/containers/UserGuidePage'; import ConferenceCallDialerPage from 'ringcentral-widgets/containers/ConferenceCallDialerPage'; import CallsOnholdPage from 'ringcentral-widgets/containers/CallsOnholdPage'; import DialerAndCallsTabContainer from 'ringcentral-widgets/containers/DialerAndCallsTabContainer'; import ConferenceParticipantPage from 'ringcentral-widgets/containers/ConferenceParticipantPage'; import TransferPage from 'ringcentral-widgets/containers/TransferPage'; import FlipPage from 'ringcentral-widgets/containers/FlipPage'; import SimpleActiveCallCtrlPage from 'ringcentral-widgets/containers/SimpleActiveCallCtrlPage'; import MeetingPage from 'ringcentral-widgets/containers/MeetingPage'; import ContactSourceFilter from 'ringcentral-widgets/components/ContactSourceFilter'; import MeetingScheduleButton from 'ringcentral-widgets/components/MeetingScheduleButton'; import { PhoneProvider } from 'ringcentral-widgets/lib/phoneContext'; import MainView from '../MainView'; import AppView from '../AppView'; export default function App({ phone, icon }) { const sourceIcons = { brandIcon: icon, }; const getAvatarUrl = async (contact) => { const avatarUrl = await phone.contacts.getProfileImage(contact, true); return avatarUrl; }; return ( <PhoneProvider phone={phone}> <Provider store={phone.store}> <Router history={phone.routerInteraction.history}> <Route component={(routerProps) => ( <AppView> {routerProps.children} <CallBadgeContainer defaultOffsetX={0} defaultOffsetY={73} hidden={ routerProps.location.pathname.indexOf('/calls/active') === 0 || routerProps.location.pathname.indexOf( '/conferenceCall/dialer', ) === 0 || routerProps.location.pathname.indexOf( '/conferenceCall/callsOnhold', ) === 0 || routerProps.location.pathname.indexOf( '/conferenceCall/participants', ) === 0 } goToCallCtrl={(sessionId) => { phone.routerInteraction.push(`/calls/active/${sessionId}`); }} /> <IncomingCallPage showContactDisplayPlaceholder={false} sourceIcons={sourceIcons} getAvatarUrl={getAvatarUrl} showCallQueueName > <AlertContainer /> <RecentActivityContainer getSession={() => phone.webphone.ringSession || {}} navigateTo={(path) => { phone.webphone.toggleMinimized( phone.webphone.ringSession && phone.webphone.ringSession.id, ); phone.routerInteraction.push(path); }} useContact /> </IncomingCallPage> <UserGuidePage /> <ConnectivityBadgeContainer /> </AppView> )} > <Route path="/" component={() => ( <LoginPage version={phone.version}> <AlertContainer /> </LoginPage> )} /> <Route path="/" component={(props) => ( <MainView> {props.children} <AlertContainer /> </MainView> )} > <Route path="/dialer" component={() => ( <DialerAndCallsTabContainer> {({ showTabs }) => <DialerPage withTabs={showTabs} />} </DialerAndCallsTabContainer> )} /> <Route path="/settings" component={(routerProps) => ( <SettingsPage params={routerProps.location.query} showQuickAccess /> )} /> <Route path="/settings/region" component={RegionSettingsPage} /> <Route path="/settings/calling" component={CallingSettingsPage} /> <Route path="/settings/audio" component={AudioSettingsPage} /> <Route path="/settings/feedback" component={FeedbackPage} /> <Route path="/calls" component={() => ( <DialerAndCallsTabContainer> <ActiveCallsPage showRingoutCallControl onLogCall={async () => { await sleep(1000); }} onCreateContact={() => {}} onCallsEmpty={() => {}} sourceIcons={sourceIcons} getAvatarUrl={getAvatarUrl} useV2 showSwitchCall /> </DialerAndCallsTabContainer> )} /> <Route path="/calls/active(/:sessionId)" component={(routerProps) => ( <CallCtrlPage showContactDisplayPlaceholder={false} sourceIcons={sourceIcons} getAvatarUrl={getAvatarUrl} params={routerProps.params} onBackButtonClick={() => { phone.routerInteraction.push('/calls'); }} showCallQueueName > <RecentActivityContainer getSession={() => phone.webphone.activeSession || {}} navigateTo={(path) => { phone.routerInteraction.push(path); }} /> </CallCtrlPage> )} /> <Route path="/transfer/:sessionId(/:type)" component={(routerProps) => ( <TransferPage params={routerProps.params} /> )} /> <Route path="/flip/:sessionId" component={(routerProps) => ( <FlipPage params={routerProps.params} /> )} /> <Route path="/simplifycallctrl/:sessionId" component={(routerProps) => ( <SimpleActiveCallCtrlPage params={routerProps.params} /> )} /> <Route path="/history" component={() => ( <CallsListPage showContactDisplayPlaceholder={false} onLogCall={async () => { await sleep(1000); }} onCreateContact={() => {}} /> )} /> <Route path="/conference" component={() => <ConferencePage enableAutoEnterHostKey />} /> <Route path="/conference/commands" component={() => ( <ConferenceCommands currentLocale={phone.locale.currentLocale} onBack={() => phone.routerInteraction.goBack()} /> )} /> <Route path="/composeText" component={ComposeTextPage} /> <Route path="/conversations/:conversationId" component={(routerProps) => ( <ConversationPage params={routerProps.params} onLogConversation={async () => { sleep(1000); }} showContactDisplayPlaceholder={false} sourceIcons={sourceIcons} showGroupNumberName /> )} /> <Route path="/messages" component={() => ( <ConversationsPage showContactDisplayPlaceholder={false} onLogConversation={async () => { await sleep(1000); }} onCreateContact={() => {}} sourceIcons={sourceIcons} showGroupNumberName /> )} /> <Route path="/contacts" component={(props) => !props.location.query.direct ? ( <ContactsPage contactSourceFilterRenderer={(props) => ( <ContactSourceFilter {...props} /> )} > {props.children} </ContactsPage> ) : ( props.children ) } > <Route path=":contactType/:contactId" component={(routerProps) => ( <ContactDetailsPage params={routerProps.params}> <RecentActivityContainer navigateTo={(path) => { phone.routerInteraction.push(path); }} contact={phone.contactDetailsUI.getContact({ id: routerProps.params.contactId, type: routerProps.params.contactType, })} useContact /> </ContactDetailsPage> )} /> </Route> <Route path="/meeting" component={() => ( <MeetingPage scheduleButton={MeetingScheduleButton} /> )} /> <Route path="/conferenceCall/dialer/:fromNumber/:fromSessionId" component={ConferenceCallDialerPage} /> <Route path="/conferenceCall/participants" component={() => <ConferenceParticipantPage />} /> <Route path="/conferenceCall/callsOnhold/:fromNumber/:fromSessionId" component={(routerProps) => ( <CallsOnholdPage params={routerProps.params} onLogCall={async () => { await sleep(1000); }} onCreateContact={() => {}} onCallsEmpty={() => {}} sourceIcons={sourceIcons} getAvatarUrl={getAvatarUrl} /> )} /> </Route> </Route> </Router> </Provider> </PhoneProvider> ); } App.propTypes = { phone: PropTypes.object.isRequired, icon: PropTypes.func, }; App.defaultProps = { icon: undefined, };
tests/lib/rules/vars-on-top.js
ronkorving/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/vars-on-top"), EslintTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new EslintTester(); ruleTester.run("vars-on-top", rule, { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), ecmaFeatures: { blockBindings: true } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
src/svg-icons/image/grid-on.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGridOn = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"/> </SvgIcon> ); ImageGridOn = pure(ImageGridOn); ImageGridOn.displayName = 'ImageGridOn'; ImageGridOn.muiName = 'SvgIcon'; export default ImageGridOn;
docs/app/Examples/views/Card/Types/CardExampleGroupProps.js
shengnian/shengnian-ui-react
import React from 'react' import { Card } from 'shengnian-ui-react' const items = [ { header: 'Project Report - April', description: 'Leverage agile frameworks to provide a robust synopsis for high level overviews.', meta: 'ROI: 30%', }, { header: 'Project Report - May', description: 'Bring to the table win-win survival strategies to ensure proactive domination.', meta: 'ROI: 34%', }, { header: 'Project Report - June', description: 'Capitalise on low hanging fruit to identify a ballpark value added activity to beta test.', meta: 'ROI: 27%', }, ] const CardExampleGroupProps = () => ( <Card.Group items={items} /> ) export default CardExampleGroupProps
src/App.js
xindeling/Kyo-Demo
import React, { Component } from 'react'; import Scroll from 'react-scroll'; import logo from './logo.svg'; import './stylesheets/style.css'; let Link = Scroll.Link; let Element = Scroll.Element; let Events = Scroll.Events; let scroll = Scroll.animateScroll; let scrollSpy = Scroll.scrollSpy; class App extends Component { /** * Constructor. * @constructor */ constructor (props){ super(props); this.scrollToTop = this.scrollToTop.bind(this); } componentDidMount() { Events.scrollEvent.register('begin', function(to, element) { console.log("begin", to, element); }); Events.scrollEvent.register('end', function(to, element) { console.log("begin", to, element); }); scrollSpy.update(); } scrollToTop() { scroll.scrollToTop(); } componentWillUnmount() { Events.scrollEvent.remove('begin'); Events.scrollEvent.remove('end'); } render() { return ( <div className="App"> <header className="header-bar flex-column flex-md-row"> <a ariaLabel="Kyo" className="link-home" onClick={this.scrollToTop}><img src={logo} className="logo" alt="Kyo logo" /></a> <nav> <ul className="nav-bar flex-row"> <li className="nav-item"> <Link className="nav-link" activeClass="active" to="what" spy={true} smooth={true} offset={-45} duration={500}> What <span className="hide-on-md">is Kyo</span> </Link> </li> <li className="nav-item"> <Link className="nav-link" activeClass="active" to="who" spy={true} smooth={true} offset={-45} duration={500}> Who <span className="hide-on-md">is this for</span> </Link> </li> <li className="nav-item"> <Link className="nav-link" activeClass="active" to="how" spy={true} smooth={true} offset={-45} duration={600}> How <span className="hide-on-md">does it work</span> </Link> </li> <li className="nav-item"> <Link className="nav-link" activeClass="active" to="contact" spy={true} smooth={true} offset={-45} duration={700}> Contact <span className="hide-on-md">us</span> </Link> </li> </ul> </nav> </header> <div className="container-fluid container-intro"> <div className="row"> <div className="container"> <div className="row"> <div className="col-md-6 ml-md-auto"> </div> <div className="kyo-intro col-6 ml-md-auto"> <h1 className="intro-title">Meet Kyo</h1> <p className="intro-subtitle">Your personal color stylist that provides outfits solutions through fashion illustrations</p> </div> </div> </div> </div> </div> <section className="container section-what" id="what"> <div className="row justify-content-center align-items-center container-section"> <div className="col-sm-12 col-md-6 col-lg-5 order-2 order-md-1"> <img src={require('./images/onboarding-tutorial.gif')} className="demo-gif" alt="Kyo logo" /> </div> <div className="col-sm-12 col-md-6 col-lg-6 order-1 order-md-2"> <h2>What is Kyo</h2> <p> Kyo is your personal fashion color app that delivers an artful dressing experience. Weather, occasion, your skin tone, preferred colors and materials will all be taken care by Kyo. Kyo provides aesthetic coordinated outfits based on intensive research from popular brands, books and paintings. It has never been easier and more fun to mix and match colors with Kyo’s inspirational illustrations. Kyo’s travel feature enables you to pack fashionable outfits with cultural awareness. </p> </div> </div> </section> <section className="container section-why" id="who"> <div className="row justify-content-center align-items-center container-section" > <div className="col-sm-12 col-md-6 col-lg-6"> <h2>Who is this for</h2> <p> If you ever wondered what colors you should wear, Kyo is the perfect app for you. No matter who you are and where you are going, Kyo is able to find you a great outfit with beautiful colors you will fall in love with. </p> <p> Jen is one of many who want her outfit colors to be playful and perhaps a bit experimental. Let’s show you how Kyo has improved Jen’s daily life. </p> </div> <div className="col-sm-12 col-md-6 col-lg-5"> <img src={require('./images/jen.jpg')} className="demo-img" alt="Kyo logo" /> </div> </div> </section> <section className="container section-how" id="how"> <div className="row justify-content-center align-items-center container-section" > <div className="col-sm-12 col-md-6 col-lg-5 order-2 order-md-1"> <img src={require('./images/kyo-rain-day.gif')} className="demo-gif" alt="Kyo logo" /> </div> <div className="col-sm-12 col-md-6 col-lg-6 order-1 order-md-2"> <h2>How does it work</h2> <h3> Daily Outfit Recommendations </h3> <p> Every morning, Jen opens Kyo before opening her wardrobe to check what to wear. She knows Kyo will recommend the right outfit for the day based on her fashion preferences and weather. On a rainy day, Kyo suggests Jen to wear a yellow raincoat with green jeans and purple rain boots. </p> </div> </div> <div className="row justify-content-center align-items-center container-section" > <div className="col-sm-12 col-md-6 col-lg-5 order-2 order-md-1"> <img src={require('./images/Occasion.png')} srcSet={require('./images/Occasion@2x.png')} className="demo-gif" alt="Kyo logo" /> </div> <div className="col-sm-12 col-md-6 col-lg-6 order-1 order-md-2"> <h2>How does it work</h2> <h3> Special Occasion </h3> <p> Last weekend, Jen went to a friend’s wedding. She chose to check out some suggestions from Kyo. Kyo suggested a navy floral dress with white flowers. She gladly took the advice. She posted her look on Kyo’s social media platform, many likes received. A week later, she received a gift from Kyo as she won the weekly fashion contest. </p> </div> </div> <div className="row justify-content-center align-items-center container-section" > <div className="col-sm-12 col-md-6 col-lg-5 order-2 order-md-1"> <img src={require('./images/travelwithkyo.png')} srcSet={require('./images/travelwithkyo@2x.png')} className="demo-gif" alt="Kyo logo" /> </div> <div className="col-sm-12 col-md-6 col-lg-6 order-1 order-md-2"> <h2>How does it work</h2> <h3> Travel with Kyo </h3> <p> Jen is planning a one-week trip to Tokyo for Christmas. She asks Kyo what to pack. She simply enters her travel destination and dates. Kyo quickly populates several outfits based on local weather and culture through its AI engine. Jen is very happy with the recommendations. She also adds items she doesn’t own to her shopping list. Kyo will remind Jen before the trip to be prepared with her outfits. She manages to pack everything in her suitcase and ready to board for Tokyo. </p> </div> </div> </section> <section className="container section-contact" id="contact"> <div className="row justify-content-center align-items-center container-section"> <div className="col-sm-12 col-md-6 col-lg-6"> <h2>Contact us</h2> <p> Kyo is currently under development. If you’re interested in investment, or just want to chat about your passion on fashion, message us at <a href="mailto:dresswithkyo@gmail.com">dresswithkyo@gmail.com</a> </p> </div> <div className="col-sm-12 col-md-6 col-lg-5"> <img src={require('./images/contact.jpg')} className="demo-img" alt="Kyo logo" /> </div> </div> </section> <footer className="container-fluid"> <div className="row align-items-center"> <div className="col-12"> <p className="font-size-sm copyright">Copyright Kyo 2017</p> </div> </div> </footer> </div> ); } } export default App;
src/frontend/components/AdminEventsSection.js
al3x/ground-control
import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import EventPreview from './EventPreview'; import EventEdit from './EventEdit'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle, SelectField, DropDownMenu, DropDownIcon, Dialog, Tabs, Tab, FlatButton, RaisedButton, IconButton, FontIcon, Checkbox, TextField} from 'material-ui'; import {Table, Column, ColumnGroup, Cell} from 'fixed-data-table'; import {BernieText, BernieColors} from './styles/bernie-css'; import moment from 'moment'; import {states} from './data/states'; import IconMenu from 'material-ui/lib/menus/icon-menu'; import MenuItem from 'material-ui/lib/menus/menu-item'; import MutationHandler from './MutationHandler'; import DeleteEvents from '../mutations/DeleteEvents'; import EditEvents from '../mutations/EditEvents'; const keyboardActionStyles = { text: {fontSize: '0.9em', top: '-7px', color: BernieColors.gray, cursor: 'default'}, icon: {cursor: 'default'} }; const KeyboardActionsInfo = () => ( <div style={{float:'left',position:'relative',top:'-6px'}}> <IconButton tooltip="Close" style={keyboardActionStyles.text}>esc</IconButton> <IconButton tooltip="Approve" style={keyboardActionStyles.text}>a</IconButton> <IconButton tooltip="Preview" style={keyboardActionStyles.text}>p</IconButton> <IconButton tooltip="Edit" style={keyboardActionStyles.text}>e</IconButton> <IconButton tooltip="Delete" style={{fontSize: '0.9em',top:'-7px',color:BernieColors.gray,cursor:'default'}} >d</IconButton> <IconButton iconClassName="material-icons" style={keyboardActionStyles.icon} iconStyle={{color:BernieColors.gray}} tooltip="Previous Event">keyboard_arrow_up</IconButton> <IconButton iconClassName="material-icons" style={keyboardActionStyles.icon} iconStyle={{color:BernieColors.gray}} tooltip="Next Event">keyboard_arrow_down</IconButton> </div> ); class AdminEventsSection extends React.Component { constructor(props) { super(props); this.state = { showDeleteEventDialog: false, showEventPreview: false, showCreateEventDialog: false, windowWidth: window.innerWidth, windowHeight: window.innerHeight, selectedRows: [], indexesMarkedForDeletion: [], activeEventIndex: null, previewTabIndex: 0, userMessage: '', approveOnUpdate: true, undoAction: function(){console.log('undo')} }; window.addEventListener('resize', this._handleResize); } _handleResize = (e) => { this.setState({ windowWidth: window.innerWidth, windowHeight: window.innerHeight }); } HeaderCell = ({content, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '14px', fontWeight: 400, color: '#9e9e9e', }} > {content} </Cell> ) SortControllerCell = ({content, attribute, ...props}) => ( <Cell {...props} onClick={(event) => { let sortDir = 'ASC'; let columnWasAlreadySelected = (this.props.relay.variables.sortField == attribute); if (columnWasAlreadySelected && this.props.relay.variables.sortDirection == 'ASC'){ sortDir = 'DESC'; }; this.props.relay.setVariables({ sortField: attribute, sortDirection: sortDir }); this.setState({selectedRows: []}); }} style={{ fontFamily: 'Roboto', fontSize: '14px', fontWeight: 400, color: '#9e9e9e', cursor: 'pointer' }} > {content}{(this.props.relay.variables.sortField == attribute) ? <FontIcon className="material-icons" style={{display: 'inline', float: 'right', position: 'relative', top: '-3px'}} >{(this.props.relay.variables.sortDirection == 'ASC') ? 'arrow_drop_up' : 'arrow_drop_down'}</FontIcon> : ''} </Cell> ) SelectCell = ({rowIndex, data, col, selectedRows, ...props}) => ( <Cell {...props}> <Checkbox name="checkboxName1" value="checkboxValue1" checked={selectedRows.indexOf(rowIndex) > -1} eventIndex={rowIndex} onCheck={() => { this._handleEventSelect(rowIndex); }} style={{marginLeft: '15px'}} /> </Cell> ) TextCell = ({rowIndex, data, col, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '13px', lineHeight: '18px', }} > {data[rowIndex]['node'][col]} </Cell> ) HostInfoCell = ({rowIndex, data, col, info, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '13px', lineHeight: '18px', }} > {(info == 'name' && data[rowIndex]['node'] && data[rowIndex]['node'][col]) ? data[rowIndex]['node'][col]['firstName'] + ' ' + data[rowIndex]['node'][col]['lastName'] : (data[rowIndex] && data[rowIndex]['node'] && data[rowIndex]['node'][col] ? data[rowIndex]['node'][col][info] : '')} </Cell> ) EventTypeCell = ({rowIndex, data, col, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '13px', lineHeight: '18px', }} > {data[rowIndex]['node'] ? data[rowIndex]['node'][col]['name'] : ''} </Cell> ) DateCell = ({rowIndex, data, col, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '13px', lineHeight: '18px', }} > {moment(data[rowIndex]['node']['startDate']).utcOffset(data[rowIndex]['node']['localUTCOffset']).format('l LT')}<br/> {data[rowIndex]['node']['localTimezone']} </Cell> ) DurationCell = ({rowIndex, data, col, ...props}) => ( <Cell {...props} style={{ fontFamily: 'Roboto', fontSize: '13px', lineHeight: '18px', }} > {(data[rowIndex]['node'][col]/60).toString().split('.')[0] + ' hours'} <br/> {data[rowIndex]['node'][col] % 60 + ' minutes'} </Cell> ) ActionCell = ({rowIndex, data, col, ...props}) => ( <Cell {...props}> <div style={{position: 'relative', left: '-5px'}}> {/* <IconButton title="preview" onTouchTap={function(){ this._handleEventPreviewOpen(rowIndex, 0); }.bind(this)} > <FontIcon className="material-icons" hoverColor={BernieColors.blue}>search</FontIcon> </IconButton> <IconButton title="view public event" onTouchTap={function(){ this._handlePublicEventOpen(rowIndex); }.bind(this)} > <FontIcon className="material-icons" hoverColor={BernieColors.blue}>open_in_new</FontIcon> </IconButton> <IconButton title="edit" onTouchTap={function(){ this._handleEventPreviewOpen(rowIndex, 1); }.bind(this)} > <FontIcon className="material-icons" hoverColor={BernieColors.blue}>edit</FontIcon> </IconButton> <IconButton title="duplicate" onTouchTap={function(){ this._handleEventPreviewOpen(rowIndex, 1); }.bind(this)} > <FontIcon className="material-icons" hoverColor={BernieColors.blue}>content_copy</FontIcon> </IconButton> */} <IconButton title="delete" onTouchTap={() => { this._handleEventDeletion([rowIndex]); }} > <FontIcon className="material-icons" hoverColor={BernieColors.red}>delete</FontIcon> </IconButton> <IconButton title="approve" onTouchTap={() => { this._handleEventConfirmation([rowIndex]); }} > <FontIcon className="material-icons" hoverColor={BernieColors.blue}>event_available</FontIcon> </IconButton> {/* IconMenu does not not work inside of fixed-data-table cells because of overflow:hidden on parent divs; The plan is to use https://github.com/tajo/react-portal to overcome this limitation */} {/* <IconMenu iconButtonElement={<FontIcon className="material-icons" hoverColor={BernieColors.blue}>more_vert</FontIcon>} desktop={true} openDirection="bottom-right" > <MenuItem index={0} primaryText="Refresh" leftIcon={<FontIcon className="material-icons">delete</FontIcon>} /> <MenuItem index={1} primaryText="Send feedback" leftIcon={<FontIcon className="material-icons">delete</FontIcon>} /> <MenuItem index={2} primaryText="Settings" leftIcon={<FontIcon className="material-icons">delete</FontIcon>} /> </IconMenu> */} </div> </Cell> ) renderToolbar() { let filterOptions = [ { payload: '0', text: 'Pending Approval' }, { payload: '1', text: 'Approved Events' }, // { payload: '3', text: 'Past Events' } ]; let filterOptionsIndex = 0; filterOptions.forEach((option, index)=>{ if (!(option.payload) == this.props.relay.variables.filters.flagApproval){ filterOptionsIndex = index; } }); let resultLengthOptions = [ { payload: 10, text: '10 Events' }, { payload: 25, text: '25 Events' }, { payload: 50, text: '50 Events' }, { payload: 100, text: '100 Events' }, // { payload: 500, text: '500 Events' }, ]; let resultLengthOptionsIndex = 0; resultLengthOptions.forEach((option, index)=>{ if (option.payload == this.props.relay.variables.numEvents){ resultLengthOptionsIndex = index; } }); this._handleEventRequestLengthChange = (event, selectedIndex, menuItem) => { this.props.relay.setVariables({ numEvents: menuItem.payload, }); // Remove selection of rows that are now beyond the view let currentSelectedRows = this.state.selectedRows; let i = currentSelectedRows.length; while (i--) { if (currentSelectedRows[i] >= menuItem.payload){ currentSelectedRows.splice(i, 1); } } this.setState({ selectedRows: currentSelectedRows }); } return ( <Toolbar> <ToolbarGroup key={0} float="left"> <DropDownMenu menuItems={filterOptions} selectedIndex={filterOptionsIndex} onChange={(event, value) => { this._handleRequestFiltersChange('flagApproval', !(value)); }} menuItemStyle={BernieText.menuItem} style={{marginRight: '0'}} /> <DropDownMenu menuItems={resultLengthOptions} selectedIndex={resultLengthOptionsIndex} menuItemStyle={BernieText.menuItem} onChange={this._handleEventRequestLengthChange} autoWidth={false} style={{width: '140px', marginRight: '0'}} /> {/*IconMenus are just broken right now <IconMenu iconButtonElement={<FontIcon className="material-icons" hoverColor={BernieColors.blue}>filter_list</FontIcon>} desktop={true} // multiple={true} closeOnItemTouchTap={false} openDirection="bottom-right" style={{ position: 'relative', top: '15px' }} menuStyle={{ maxHeight: '300px' }} > {states.map((item, index) => { return <MenuItem index={index} key={index} primaryText={item.abbreviation} /> })} </IconMenu>*/} <div style={{ position: 'relative', top: '20px', display: 'inline' }} > <label htmlFor="stateSelect" style={{ display: 'inline', marginRight: '0.5em', fontSize: '0.8em' }}>Filter by State</label> <select id='stateSelect' onChange={(event) => { let updatedValue = event.target.value; if (updatedValue == 'none'){updatedValue = null} this._handleRequestFiltersChange('venueState', updatedValue); }} > <option value='none'>--</option> {states.map((item, index) => { return <option key={index} value={item.abbreviation}>{item.name}</option> })} </select> </div> {/*<IconButton iconClassName="material-icons" tooltipPosition="bottom-center" title="Refresh Events" style={{float: 'left', top: '5px'}} tooltipStyles={{zIndex: 10}} onTouchTap={() => { this._handleRequestRefresh(); }} >refresh</IconButton>*/} </ToolbarGroup> <ToolbarGroup key={1} float="right"> <RaisedButton label="Create" onTouchTap={() => { //this._handleEventCreation(this.state.selectedRows); window.location = '/admin/events/create' }} /> <ToolbarSeparator style={{marginLeft: 0}} /> <RaisedButton label="Delete" primary={true} disabled={(this.state.selectedRows.length == 0)} onTouchTap={() => { this._handleEventDeletion(this.state.selectedRows); }} /> <RaisedButton label="Approve Selected" style={{marginLeft: 0}} secondary={true} disabled={(this.state.selectedRows.length == 0)} onTouchTap={() => { this._handleEventConfirmation(this.state.selectedRows); }} /> </ToolbarGroup> </Toolbar> ) } _deleteEvent = () => { let events = this.props.listContainer.events.edges; let eventsToDelete = this.state.indexesMarkedForDeletion.map((index) => { return events[index].node.id }) this.refs.eventDeletionHandler.send({ listContainer: this.props.listContainer, eventIDs: eventsToDelete }) this._handleDeleteModalRequestClose(); this._deselectRows({indexesToRemove: this.state.indexesMarkedForDeletion}); } renderDeleteModal() { let standardActions = [ { text: 'Cancel' }, { text: 'Delete', onTouchTap: () => { if (!this.refs.deleteConfirmationInput || this.refs.deleteConfirmationInput.getValue() === 'DELETE') this._deleteEvent() }, ref: 'submit' } ]; this._handleDeleteModalRequestClose = () => { if (this.state.activeEventIndex) { this.setState({ showDeleteEventDialog: false, showEventPreview: true }); } else { this.setState({ showDeleteEventDialog: false }); } } let numEvents = this.state.indexesMarkedForDeletion.length; let s = (numEvents > 1) ? 's.' : '.'; let dialogTitle = 'You are about to delete ' + numEvents + ' event' + s; let textConfirm = ( <div> <p>Type <span style={{color: BernieColors.red}}>DELETE</span> to confirm.</p> <TextField hintText="TYPE HERE" underlineFocusStyle={{borderColor: BernieColors.red}} ref="deleteConfirmationInput" /> </div> ) if (numEvents < 5) textConfirm = <div></div> return ( <Dialog title={dialogTitle} actions={standardActions} open={this.state.showDeleteEventDialog} onRequestClose={this._handleDeleteModalRequestClose} > {textConfirm} </Dialog> ) } renderCreateModal() { let standardActions = [ { text: 'Cancel' } ]; this._handleCreateModalRequestClose = () => { this.setState({ showCreateEventDialog: false }); } return ( <Dialog title='Create an Event' actions={standardActions} open={this.state.showCreateEventDialog} onRequestClose={this._handleCreateModalRequestClose} bodyStyle={{paddingBottom: '0'}} > <iframe ref="creationForm" src="create" style={{width: '100%', height: this.state.windowHeight*0.6, border: 'none'}} /> </Dialog> ) } renderEventPreviewModal() { let events = this.props.listContainer.events.edges; let customActions = [ // <KeyboardActionsInfo key="0" />, <FlatButton label="Close" key="1" onTouchTap={this._handlePreviewRequestClose} />, <FlatButton label="Delete" key="2" primary={true} onTouchTap={() => { this._handleEventDeletion([this.state.activeEventIndex]); }} />, <FlatButton label={(this.state.previewTabIndex == 0) ? 'Approve' : (this.state.approveOnUpdate ? 'Update and Approve' : 'Update')} key="3" secondary={true} onTouchTap={() => { this.refs.eventEdit.refs.component.submit() }} /> ]; this._handlePreviewRequestClose = () => { this.setState({ showEventPreview: false, activeEventIndex: null }); } let activeEvent = events[this.state.activeEventIndex] ? events[this.state.activeEventIndex].node : null; return ( <Dialog actions={customActions} actionFocus="submit" open={this.state.showEventPreview} onRequestClose={this._handlePreviewRequestClose} contentStyle={{maxWidth: '1200px', width: '90%'}} autoScrollBodyContent={true} > <Tabs value={String(this.state.previewTabIndex)} tabItemContainerStyle={{position: 'absolute', top: '0', left: '0', zIndex: '2'}} inkBarStyle={{position: 'absolute', top: '48px', zIndex: '2'}} contentContainerStyle={{paddingTop: '24px'}} onChange={(tabValue, touchEvent, tab) => { if (!tab.props){return}; this.setState({previewTabIndex: tab.props.tabIndex}); }} > <Tab label="Preview" value={'0'} > <EventPreview event={activeEvent} onChangeEventIndex={(n) => { this._iterateActiveEvent(n); }} onEventConfirm={(indexArray) => { this._handleEventConfirmation(indexArray); }} onTabRequest={(eventIndex, tabIndex) => { this._handleEventPreviewOpen(eventIndex, tabIndex); }} onEventDelete={(indexArray) => { this._handleEventDeletion(indexArray); }} /> </Tab> <Tab label="Edit" value={'1'} > <EventEdit ref="eventEdit" onSubmit={ (data) => { this._handleEventEdit(activeEvent, data) }} event={activeEvent} listContainer={this.props.listContainer} onFieldChanged={(fieldName, val) => { if (fieldName === 'flagApproval') { if (val === true) this.setState({approveOnUpdate: false}) else this.setState({approveOnUpdate: true}) } }} /> </Tab> </Tabs> </Dialog> ) } _handleRequestRefresh = () => { this.forceUpdate() } _handleRequestFiltersChange = (prop, value) => { let newVar = {} newVar[prop] = value; let oldVars = this.props.relay.variables.filters; this.props.relay.setVariables(Object.assign(oldVars, newVar)); this.setState({selectedRows: []}); } _handleEventPreviewOpen = (eventIndex, tabIndex) => { tabIndex = tabIndex ? tabIndex : 0; this.setState({ showEventPreview: true, activeEventIndex: eventIndex, previewTabIndex: tabIndex, approveOnUpdate: true }); } _handlePublicEventOpen = (eventIndex) => { let events = this.props.listContainer.events.edges; window.open('https://secure.berniesanders.com/page/event/detail/' + events[eventIndex]['node']['eventIdObfuscated']); } _iterateActiveEvent = (n) => { // Do not iterate if there are no more events available before/after current event let events = this.props.listContainer.events.edges; if (this.state.activeEventIndex === null || this.state.activeEventIndex + n < 0 || this.state.activeEventIndex + n == events.length){ return } this.setState({ activeEventIndex: this.state.activeEventIndex + n }); var element = ReactDOM.findDOMNode(this.refs.eventEdit) element.scrollIntoView && element.scrollIntoView() } _handleEventCreation = () => { this.setState({ showCreateEventDialog: true }); } _handleEventDeletion = (eventIndexes) => { this.setState({ showEventPreview: false, showDeleteEventDialog: true, indexesMarkedForDeletion: eventIndexes }); } _handleEventConfirmation = (eventIndexes) => { let events = this.props.listContainer.events.edges; let eventsToConfirm = [] events.forEach((event, index) => { if (eventIndexes.indexOf(index) !== -1) { let node = event.node // Bit of a hack, but BSD requires all these fields let eventToConfirm = { flagApproval: false, id: node.id, name: node.name, eventIdObfuscated: node.eventIdObfuscated, eventTypeId: node.eventType.id, description: node.description, venueName: node.venueName, venueZip: node.venueZip, venueCity: node.venueCity, venueState: node.venueState, startDate: node.startDate, localTimezone: node.localTimezone, duration: node.duration, capacity: node.capacity } eventsToConfirm.push(eventToConfirm) } }) this.refs.eventEditHandler.send({ events: eventsToConfirm, listContainer: this.props.listContainer }) this._deselectRows({indexesToRemove: eventIndexes}); } _handleEventEdit = (event, newData) => { this._handlePreviewRequestClose() newData.id = event.id newData.eventIdObfuscated = event.eventIdObfuscated newData.hostId = event.host.id this.refs.eventEditHandler.send({ events: [newData], listContainer: this.props.listContainer }) } _handleEventSelect = (eventIndex) => { let currentSelectedRows = this.state.selectedRows; let i = currentSelectedRows.indexOf(eventIndex); if ( i > -1){ currentSelectedRows.splice(i, 1); } else { currentSelectedRows.push(eventIndex); } this.setState({ selectedRows: currentSelectedRows }); } _deselectRows = ({indexesToRemove}) => { // indexesToRemove argument is optional let currentSelectedRows = this.state.selectedRows; if (indexesToRemove && currentSelectedRows.length != indexesToRemove.length){ indexesToRemove.forEach((eventIndex) => { let i = currentSelectedRows.indexOf(eventIndex); console.log(i, currentSelectedRows, indexesToRemove); if (i > -1){ currentSelectedRows.splice(i, 1); } }); currentSelectedRows.forEach((eventIndex, i) => { if (eventIndex > indexesToRemove[0]){ currentSelectedRows.splice(i, 1, eventIndex-1); } }); this.setState({selectedRows: currentSelectedRows}); } else { this.setState({selectedRows: []}); } } _handleRowClick = (clickEvent, targetRowIndex) => { this._handleEventPreviewOpen(targetRowIndex, 1); } _masterCheckBoxChecked = (checkEvent, checked) => { let currentSelectedRows = []; let events = this.props.listContainer.events.edges; if (checked){ for (let i=0; i<events.length; i++){ currentSelectedRows.push(i); } } this.setState({ selectedRows: currentSelectedRows }); } render() { let events = this.props.listContainer.events.edges; console.log(events[0].startDate) return ( <div> <MutationHandler ref='eventDeletionHandler' successMessage='Event deleted!' mutationClass={DeleteEvents} /> <MutationHandler ref='eventEditHandler' mutationClass={EditEvents} successMessage="Events edited successfully!" /> {this.renderDeleteModal()} {this.renderCreateModal()} {this.renderEventPreviewModal()} {this.renderToolbar()} <Table rowHeight={83} groupHeaderHeight={35} headerHeight={50} rowsCount={events.length} width={this.state.windowWidth} height={this.state.windowHeight - 112} onRowDoubleClick={this._handleRowClick} {...this.props}> <ColumnGroup fixed={true} header={<this.HeaderCell content="Actions" />}> <Column header={ <Cell> <Checkbox checked={(this.state.selectedRows.length > 0)} onCheck={this._masterCheckBoxChecked} checkedIcon={(this.state.selectedRows.length == events.length) ? <FontIcon className="material-icons">check_box</FontIcon> : <FontIcon className="material-icons">indeterminate_check_box</FontIcon>} style={{marginLeft: '15px'}} iconStyle={{color: BernieColors.blue}} /> </Cell> } cell={<this.SelectCell data={events} col="select" selectedRows={this.state.selectedRows} />} fixed={true} width={73} /> <Column header={<this.HeaderCell content="Manage" />} cell={<this.ActionCell data={events} col="actions" />} fixed={true} width={115} align='center' /> </ColumnGroup> <ColumnGroup header={<this.HeaderCell content="Event Host" />}> <Column flexGrow={1} header={<this.HeaderCell content="Name" />} cell={<this.HostInfoCell data={events} col="host" info="name" />} width={150} /> <Column flexGrow={1} header={<this.SortControllerCell content="Phone" attribute="contactPhone" />} cell={<this.TextCell data={events} col="contactPhone" />} width={100} /> <Column flexGrow={1} header={<this.HeaderCell content="Email" />} cell={<this.HostInfoCell data={events} col="host" info="email" />} width={220} /> </ColumnGroup> <ColumnGroup header={<this.HeaderCell content="Time" />}> <Column header={<this.SortControllerCell content="Datetime" attribute="startDate" />} cell={<this.DateCell data={events} col="startDate" />} flexGrow={1} width={170} /> <Column header={<this.SortControllerCell content="Duration" attribute="duration" />} cell={<this.DurationCell data={events} col="duration" />} flexGrow={1} width={110} /> </ColumnGroup> <ColumnGroup header={<this.HeaderCell content="Event Location" />}> <Column header={<this.SortControllerCell content="Venue" attribute="venueName" />} cell={<this.TextCell data={events} col="venueName" />} flexGrow={1} width={150} /> <Column header={<this.SortControllerCell content="Address" attribute="venueAddr1" />} cell={<this.TextCell data={events} col="venueAddr1" />} flexGrow={1} width={150} /> <Column header={<this.SortControllerCell content="City" attribute="venueCity" />} cell={<this.TextCell data={events} col="venueCity" />} flexGrow={1} width={150} /> <Column header={<this.SortControllerCell content="State" attribute="venueState" />} cell={<this.TextCell data={events} col="venueState" />} flexGrow={1} width={80} align='center' /> <Column header={<this.SortControllerCell content="Zip Code" attribute="venueZip" />} cell={<this.TextCell data={events} col="venueZip" />} flexGrow={1} width={120} align='center' /> </ColumnGroup> <ColumnGroup header={<this.HeaderCell content="About" />}> <Column flexGrow={1} header={<this.SortControllerCell content="Event Type" attribute="eventTypeId" />} cell={ <this.EventTypeCell data={events} col="eventType" /> } width={120} /> <Column flexGrow={1} header={<this.SortControllerCell content="Event Name" attribute="name" />} cell={<this.TextCell data={events} col="name" />} width={250} /> <Column flexGrow={1} header={<this.SortControllerCell content="Description" attribute="description" />} cell={<this.TextCell data={events} col="description" />} width={250} /> <Column flexGrow={1} header={<this.SortControllerCell content="Capacity" attribute="capacity" />} cell={<this.TextCell data={events} col="capacity" />} width={100} align='center' /> <Column flexGrow={1} header={<this.HeaderCell content="RSVPs" />} cell={<this.TextCell data={events} col="attendeesCount" />} width={100} align='center' /> <Column flexGrow={1} header={<this.HeaderCell content="ID" />} cell={<this.TextCell data={events} col="eventIdObfuscated" />} width={100} align='center' /> </ColumnGroup> </Table> </div> ) } } export default Relay.createContainer(AdminEventsSection, { initialVariables: { numEvents: 100, sortField: 'startDate', sortDirection: 'ASC', filters: {flagApproval: true} }, fragments: { listContainer: () => Relay.QL` fragment on ListContainer { ${EventEdit.getFragment('listContainer')} ${DeleteEvents.getFragment('listContainer')} ${EditEvents.getFragment('listContainer')} events( first: $numEvents filterOptions: $filters sortField: $sortField sortDirection: $sortDirection ) { edges { cursor node { name id host { id firstName lastName email } eventType { id name } eventIdObfuscated flagApproval description venueName latitude longitude venueZip venueCity venueState venueAddr1 venueAddr2 venueCountry venueDirections startDate localTimezone localUTCOffset duration capacity attendeeVolunteerShow attendeeVolunteerMessage isSearchable publicPhone contactPhone hostReceiveRsvpEmails rsvpUseReminderEmail rsvpEmailReminderHours attendeesCount } } } } `, }, });
src/components/Account.js
opsukka/fantasy-map
import React from 'react'; import { connect } from 'react-redux'; import { compose } from 'recompose'; import { PasswordForgetForm } from './PasswordForget'; import PasswordChangeForm from './PasswordChange'; import withAuthorization from './Session/withAuthorization'; const AccountPage = ({ authUser }) => <div className="account-body"> <div className="account-main"> <h1>Account: {authUser.email}</h1> {/* <PasswordForgetForm /> */} <PasswordChangeForm /> </div> </div> const mapStateToProps = (state) => ({ authUser: state.sessionState.authUser, }); const authCondition = (authUser) => !!authUser; export default compose( withAuthorization(authCondition), connect(mapStateToProps) )(AccountPage);
src/auth/screens/auth-profile.screen.js
dyesseyumba/git-point
import React, { Component } from 'react'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { RefreshControl, View, ActivityIndicator, Dimensions, } from 'react-native'; import { ListItem } from 'react-native-elements'; import { ViewContainer, UserProfile, SectionList, ParallaxScroll, UserListItem, EntityInfo, } from 'components'; import { colors, fonts, normalize } from 'config'; import { getUser, getOrgs, getStarCount } from 'auth'; import { emojifyText, openURLInView, translate } from 'utils'; const mapStateToProps = state => ({ user: state.auth.user, orgs: state.auth.orgs, locale: state.auth.locale, starCount: state.auth.starCount, isPendingUser: state.auth.isPendingUser, isPendingOrgs: state.auth.isPendingOrgs, hasInitialUser: state.auth.hasInitialUser, }); const mapDispatchToProps = dispatch => bindActionCreators( { getUser, getOrgs, getStarCount, }, dispatch ); const Note = styled.Text` font-size: ${normalize(11)}; color: ${colors.primaryDark}; ${fonts.fontPrimaryLight}; text-align: center; padding: 10px; `; const NoteLink = styled.Text` ${fonts.fontPrimarySemiBold}; `; const BioListItem = styled(ListItem).attrs({ containerStyle: { borderBottomColor: colors.greyLight, borderBottomWidth: 1, }, titleStyle: { color: colors.greyDark, ...fonts.fontPrimary, }, })``; class AuthProfile extends Component { props: { getUser: Function, getOrgs: Function, getStarCount: Function, user: Object, orgs: Array, locale: string, starCount: string, isPendingUser: boolean, isPendingOrgs: boolean, hasInitialUser: boolean, navigation: Object, }; componentDidMount() { this.refreshProfile(); } refreshProfile = () => { this.props.getUser(); this.props.getOrgs(); this.props.getStarCount(); }; render() { const { user, orgs, isPendingUser, isPendingOrgs, locale, starCount, navigation, hasInitialUser, } = this.props; const hasBackButton = navigation.state.routeName === 'AuthProfile'; const isPending = isPendingUser || isPendingOrgs; return ( <ViewContainer> <ParallaxScroll renderContent={() => ( <UserProfile type="user" initialUser={hasInitialUser ? user : {}} user={hasInitialUser ? user : {}} starCount={hasInitialUser ? starCount : ''} locale={locale} navigation={navigation} /> )} refreshControl={ <RefreshControl refreshing={isPendingUser} onRefresh={this.refreshProfile} /> } stickyTitle={user.login} navigateBack={hasBackButton} navigation={navigation} showMenu menuIcon="gear" menuAction={() => navigation.navigate('UserOptions', { title: translate('auth.userOptions.title', locale), })} > {isPending && ( <ActivityIndicator animating={isPending} style={{ height: Dimensions.get('window').height / 3 }} size="large" /> )} {hasInitialUser && user.bio && user.bio !== '' && ( <SectionList title={translate('common.bio', locale)}> <BioListItem titleNumberOfLines={0} title={emojifyText(user.bio)} hideChevron /> </SectionList> )} {!isPending && ( <EntityInfo entity={user} orgs={orgs} navigation={navigation} locale={locale} /> )} {!isPending && ( <View> <SectionList title={translate('common.orgs', locale)} noItems={orgs.length === 0} noItemsMessage={translate('common.noOrgsMessage', locale)} > {orgs.map(item => ( <UserListItem key={item.id} user={item} navigation={navigation} /> ))} <Note> {translate('auth.profile.orgsRequestApprovalTop', locale)} {'\n'} <NoteLink onPress={() => openURLInView('https://github.com/settings/applications')} > {translate( 'auth.profile.orgsRequestApprovalBottom', locale )} </NoteLink> </Note> </SectionList> </View> )} </ParallaxScroll> </ViewContainer> ); } } export const AuthProfileScreen = connect(mapStateToProps, mapDispatchToProps)( AuthProfile );
src/index.js
ernestofreyreg/react-calendar-month
import React from 'react'; import classNames from 'classnames'; export function zfill(num, len) { return (Array(len).join('0') + num).slice(-len); } export function isFirsDay(day) { return day.ordinal === 1; } export function monthDays(date) { const d = new Date(date.getFullYear(), date.getMonth() + 1, 0); return d.getDate(); } export function createWeeksArray(daysInMonth, firstWeekDay, data) { function createOrdinalDay(ordinal) { return Object.assign({}, { ordinal }, data[ordinal.toString()] || {}); } const days = Array.apply(null, Array(daysInMonth)).map((x, i) => (i + 1)); return days.reduce((reduced, ordinal) => { if (reduced.length === 0) { reduced.push([createOrdinalDay(ordinal)]); return reduced; } if (reduced.length === 1) { const firstWeek = reduced[0]; if (firstWeek.length < 7 - firstWeekDay) { firstWeek.push(createOrdinalDay(ordinal)); return reduced; } reduced.push([createOrdinalDay(ordinal)]); return reduced; } const week = reduced[reduced.length - 1]; if (week.length < 7) { week.push(createOrdinalDay(ordinal)); return reduced; } reduced.push([createOrdinalDay(ordinal)]); return reduced; }, []); } export default class Month extends React.Component { static propTypes = { year: React.PropTypes.number.isRequired, month: React.PropTypes.number.isRequired, className: React.PropTypes.string, data: React.PropTypes.object, }; render() { const date = new Date(this.props.year, this.props.month - 1, 1); const firstWeekDay = date.getDay(); const weeks = createWeeksArray(monthDays(date), firstWeekDay, this.props.data || {}); return ( <div className={classNames('Month', this.props.className && this.props.className)}> {weeks.map((week, i) => <Week days={week} key={i} />)} </div> ); } } class Week extends React.Component { static propTypes = { days: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, }; render() { const leftEmptyCells = (this.props.days.length < 7 && isFirsDay(this.props.days[0])) ? Array.apply(null, Array(7 - this.props.days.length)) : []; const rightEmptyCells = (this.props.days.length < 7 && !isFirsDay(this.props.days[0])) ? Array.apply(null, Array(7 - this.props.days.length)) : []; return ( <div className="Week"> {leftEmptyCells.map((x, i) => <EmptyCell key={`empty${i}`} />)} {this.props.days.map((day, i) => <Day day={day} key={`day${i}`} />)} {rightEmptyCells.map((x, i) => <EmptyCell key={`empty${i}`} />)} </div> ); } } class Day extends React.Component { static propTypes = { day: React.PropTypes.object.isRequired, }; render() { return ( <div className={classNames('Day', { [this.props.day.className]: this.props.day.className })}> <div className="Day__container"> {(this.props.day.component) ? this.props.day.component : null} </div> <div className="Day__number">{zfill(this.props.day.ordinal, 2)}</div> </div> ); } } class EmptyCell extends React.Component { render() { return <div className="EmptyCell"></div>; } }
todomvc/test/components/Footer.spec.js
samlatif-uk/redux-tdd-hw
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Footer from '../../components/Footer' import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters' function setup(propOverrides) { const props = Object.assign({ completedCount: 0, activeCount: 0, filter: SHOW_ALL, onClearCompleted: expect.createSpy(), onShow: expect.createSpy(), onReverseList: expect.createSpy() }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render(<Footer {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output } } function getTextContent(elem) { const children = Array.isArray(elem.props.children) ? elem.props.children : [ elem.props.children ] return children.reduce(function concatText(out, child) { // Children are either elements or text strings return out + (child.props ? getTextContent(child) : child) }, '') } describe('components', () => { describe('Footer', () => { it('should render container', () => { const { output } = setup() expect(output.type).toBe('footer') expect(output.props.className).toBe('footer') }) it('should display active count when 0', () => { const { output } = setup({ activeCount: 0 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('No items left') }) it('should display active count when above 0', () => { const { output } = setup({ activeCount: 1 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('1 item left') }) it('should render filters', () => { const { output } = setup() const [ , filters ] = output.props.children expect(filters.type).toBe('ul') expect(filters.props.className).toBe('filters') expect(filters.props.children.length).toBe(3) filters.props.children.forEach(function checkFilter(filter, i) { expect(filter.type).toBe('li') const a = filter.props.children expect(a.props.className).toBe(i === 0 ? 'selected' : '') expect(a.props.children).toBe({ 0: 'All', 1: 'Active', 2: 'Completed' }[i]) }) }) it('should call onShow when a filter is clicked', () => { const { output, props } = setup() const [ , filters ] = output.props.children const filterLink = filters.props.children[1].props.children filterLink.props.onClick({}) expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE) }) it('shouldnt show clear button when no completed todos', () => { const { output } = setup({ completedCount: 0 }) const [ , , clear ] = output.props.children expect(clear).toBe(undefined) }) it('should render clear button when completed todos', () => { const { output } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children expect(clear.type).toBe('button') expect(clear.props.children).toBe('Clear completed') }) it('should call onClearCompleted on clear button click', () => { const { output, props } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children clear.props.onClick({}) expect(props.onClearCompleted).toHaveBeenCalled() }) it('should render reverse list', () => { const { output, props } = setup() const [ , , , reverse ] = output.props.children expect(reverse.type).toBe('button') expect(reverse.props.children).toBe('Reverse List') }) it('should call onReverseList on reverse list button click', () => { const { output, props } = setup() const [ , , , reverse ] = output.props.children reverse.props.onClick({}) expect(props.onReverseList).toHaveBeenCalled() }) }) })
assets/jqwidgets/demos/react/app/expander/fluidsize/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxExpander from '../../../jqwidgets-react/react_jqxexpander.js'; class App extends React.Component { render() { return ( <JqxExpander width={'50%'} height={'50%'}> <div>Early History of the Internet</div> <div> <ul> <li>1961 First packet-switching papers</li> <li>1966 Merit Network founded</li> <li>1966 ARPANET planning starts</li> <li>1969 ARPANET carries its first packets</li> <li>1970 Mark I network at NPL (UK)</li> <li>1970 Network Information Center (NIC)</li> <li>1971 Merit Networks packet-switched network operational</li> <li>1971 Tymnet packet-switched network</li> <li>1972 Internet Assigned Numbers Authority (IANA) established</li> <li>1973 CYCLADES network demonstrated</li> <li>1974 Telenet packet-switched network</li> <li>1976 X.25 protocol approved</li> <li>1979 Internet Activities Board (IAB)</li> <li>1980 USENET news using UUCP</li> <li>1980 Ethernet standard introduced</li> <li>1981 BITNET established</li> </ul> </div> </JqxExpander> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/pages/TodoList.js
marktani/react-native-express-1
import React from 'react' import markdown from 'markdown-in-js' import markdownOptions from '../utils/MarkdownOptions' import Page from './Page' import { PageHeader } from '../components' const content = markdown(markdownOptions)` Our first exercise will be a simple Todo List. If you get stuck at any point, you can look to the examples in this guide, as there will be a lot of overlap in code. Let's build the app on the right. We'll break it down into smaller sections and build it piece-by-piece. Feel free to reference previous sections. ## Project Setup 1. Download the basic project template [here](https://raw.githubusercontent.com/gabergg/ReactNativeTodoList/starting-point/boilerplate/TodoList.zip) 2. Unzip the project directory 3. After downloading, \`npm install\` in the project directory 4. Run \`react-native run-ios\` to build and launch the app ## Completed You can view the completed project on github [here](https://github.com/gabergg/ReactNativeTodoList). ## Sections - [Step 1 - App setup](todo_list_1) - [Step 2 - Input and ADD_ITEM](todo_list_2) - [Step 3 - List and Checkbox](todo_list_3) - [Step 4 - Remove completed items and styling](todo_list_4) ` const containerStyle = { display: 'flex', flexDirection: 'row', } const contentStyle = { paddingRight: '30px', marginTop: '-15px', } export default props => <Page {...props}> <div style={containerStyle}> <div style={contentStyle}> <PageHeader title={props.title} author={"Gabe G'Sell"} authorURL={'http://gabegsell.com/'} /> {content} </div> <div> <img style={{border: '1px solid black'}} width={280} src={'todo-screenshot.png'} /> </div> </div> </Page>
examples/blockly-react/src/App.js
google/blockly-samples
/** * @license * * Copyright 2019 Google LLC * * 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. */ /** * @fileoverview Main React component that includes the Blockly component. * @author samelh@google.com (Sam El-Husseini) */ import React from 'react'; import './App.css'; import logo from './logo.svg'; import BlocklyComponent, { Block, Value, Field, Shadow } from './Blockly'; import BlocklyJS from 'blockly/javascript'; import './blocks/customblocks'; import './generator/generator'; class App extends React.Component { constructor(props) { super(props); this.simpleWorkspace = React.createRef(); } generateCode = () => { var code = BlocklyJS.workspaceToCode( this.simpleWorkspace.current.workspace ); console.log(code); } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <button onClick={this.generateCode}>Convert</button> <BlocklyComponent ref={this.simpleWorkspace} readOnly={false} trashcan={true} media={'media/'} move={{ scrollbars: true, drag: true, wheel: true }} initialXml={` <xml xmlns="http://www.w3.org/1999/xhtml"> <block type="controls_ifelse" x="0" y="0"></block> </xml> `}> <Block type="test_react_field" /> <Block type="test_react_date_field" /> <Block type="controls_ifelse" /> <Block type="logic_compare" /> <Block type="logic_operation" /> <Block type="controls_repeat_ext"> <Value name="TIMES"> <Shadow type="math_number"> <Field name="NUM">10</Field> </Shadow> </Value> </Block> <Block type="logic_operation" /> <Block type="logic_negate" /> <Block type="logic_boolean" /> <Block type="logic_null" disabled="true" /> <Block type="logic_ternary" /> <Block type="text_charAt"> <Value name="VALUE"> <Block type="variables_get"> <Field name="VAR">text</Field> </Block> </Value> </Block> </BlocklyComponent> </header> </div> ); } } export default App;
src/RadioGroup.js
sazl/react-bootstrap-validation
import React from 'react'; import Radio from './Radio'; import InputContainer from './InputContainer'; import classNames from 'classnames'; export default class RadioGroup extends InputContainer { constructor(props) { super(props); this.state = { value: props.defaultValue || props.value }; } componentWillMount() { super.componentWillMount(); this.props._registerInput(this); } componentWillUnmount() { super.componentWillUnmount(); this.props._unregisterInput(this); } getValue() { let input = this._inputs[ this.props.name ]; let value; input.forEach(ipt => { if (ipt.getChecked()) { value = ipt.getValue(); } }); return value; } render() { let label; if (this.props.label) { label = ( <label className={classNames('control-label', this.props.labelClassName)}> {this.props.label} </label> ); } let groupClassName = { 'form-group' : !this.props.standalone, 'form-group-lg': !this.props.standalone && this.props.bsSize === 'large', 'form-group-sm': !this.props.standalone && this.props.bsSize === 'small', 'has-feedback' : this.props.hasFeedback, 'has-success' : this.props.bsStyle === 'success', 'has-warning' : this.props.bsStyle === 'warning', 'has-error' : this.props.bsStyle === 'error' }; return ( <div className={classNames(groupClassName, this.props.groupClassName)}> {label} <div className={this.props.wrapperClassName}> {this._renderChildren()} {this._renderHelp()} </div> </div> ); } _renderChildren() { return React.Children.map(this.props.children, child => { if (child.type !== Radio) { throw new Error('Only Radio component is allowed inside RadioGroup'); } return React.cloneElement(child, { type : 'radio', standalone : true, checked : this.state.value === child.props.value, name : this.props.name, onChange : this._onChange.bind(this), _registerInput : this.registerInput.bind(this), _unregisterInput: this.unregisterInput.bind(this) }); }); } _renderHelp() { return this.props.help ? ( <span className="help-block" key="help"> {this.props.help} </span> ) : null; } _onChange(e) { if (!e.target) { return; } this.setState({ value: e.target.value }); this.props.onChange(e); } } RadioGroup.propTypes = { standalone : React.PropTypes.bool, hasFeedback : React.PropTypes.bool, bsSize (props) { if (props.standalone && props.bsSize !== undefined) { return new Error('bsSize will not be used when `standalone` is set.'); } return React.PropTypes.oneOf([ 'small', 'medium', 'large' ]) .apply(null, arguments); }, bsStyle : React.PropTypes.oneOf([ 'success', 'warning', 'error' ]), groupClassName : React.PropTypes.string, wrapperClassName: React.PropTypes.string, labelClassName : React.PropTypes.string, validationEvent : React.PropTypes.oneOf([ 'onChange' ]), validate : React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.string ]), errorHelp : React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.object ]) }; RadioGroup.defaultProps = { standalone : false, validationEvent: 'onChange', onChange : () => {} };
stories/ChangingContent/index.js
henrybuilt/react-sticky-table
import React, { Component } from 'react'; import { StickyTable, Row, Cell } from '../../src'; import Button from '../Button'; export default class ChangingContent extends Component { constructor(props) { super(props); var rows = []; var cells; for (var r = 0; r < 50; r++) { cells = []; for (var c = 0; c < 20; c++) { cells.push(<Cell key={c}>{(r === 0 ? 'Header ' : 'Cell ') + c}</Cell>); } rows.push(<Row key={r}>{cells}</Row>); } this.state = { rows: rows }; } changeContent() { var rows = []; var cells; for (var r = 0; r < 50; r++) { cells = []; for (var c = 0; c < 20; c++) { cells.push( <Cell key={c}>{(r === 0 ? 'New Header ' : 'Cell ') + c}</Cell> ); } rows.push(<Row key={r}>{cells}</Row>); } this.setState({ rows }); } render() { return ( <div> <Button onClick={this.changeContent.bind(this)}>Change content</Button> <br /> <br /> <div style={{ width: '100%', height: '200px' }}> <StickyTable stickyColumnCount={0}>{this.state.rows}</StickyTable> </div> </div> ); } }
src/routes/workTeam/NavSidebar/NavSidebar.js
nambawan/g-old
import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/withStyles'; import s from './NavSidebar.css'; import Sidebar from '../../../components/Sidebar'; import Label from '../../../components/Label'; import Heading from '../../../components/Heading'; import Image from '../../../components/Image'; import Box from '../../../components/Box'; import Button from '../../../components/Button'; class Navbar extends React.Component { static propTypes = { logo: PropTypes.string, displayName: PropTypes.string.isRequired, numMembers: PropTypes.number.isRequired, handleNavClicks: PropTypes.func.isRequired, }; static defaultProps = { logo: null, }; render() { const { logo, displayName, numMembers, handleNavClicks } = this.props; let groupImage; if (logo) { groupImage = <Image src={logo} />; } else { groupImage = ( <svg version="1.1" viewBox="0 0 24 24" role="img" width="100px" height="100px" aria-label="cloud" > <path fill="none" stroke="#000" strokeWidth="2" d="M18,17 L18,18 C18,21 16,22 13,22 L11,22 C8,22 6,21 6,18 L6,17 C3.23857625,17 1,14.7614237 1,12 C1,9.23857625 3.23857625,7 6,7 L12,7 M6,7 L6,6 C6,3 8,2 11,2 L13,2 C16,2 18,3 18,6 L18,7 C20.7614237,7 23,9.23857625 23,12 C23,14.7614237 20.7614237,17 18,17 L12,17" /> </svg> ); } const links = [ { path: 'proposals', label: 'Votings' }, { path: 'discussions', label: 'Discussions' }, ].map(page => ( <div // eslint-disable-line onClick={e => { handleNavClicks(e, page.path); }} className={s.menuLink} > <Label>{page.label}</Label> </div> )); return ( <Sidebar column className={s.sidebar} fixed size> <Box column align> {groupImage} <Heading tag="h2">{displayName}</Heading> </Box> <Box column> <Box between align pad> <Label>Members</Label> <Button plain icon={ <svg viewBox="0 0 24 24" width="24px" height="24px" role="img"> <path fill="none" stroke="#000" strokeWidth="2" d="M12,13 C14.209139,13 16,11.209139 16,9 C16,6.790861 14.209139,5 12,5 C9.790861,5 8,6.790861 8,9 C8,11.209139 9.790861,13 12,13 Z M6,22 L6,19 C6,15.6862915 8.6862915,13 12,13 C15.3137085,13 18,15.6862915 18,19 L18,22 M13,5 C13.4037285,3.33566165 15.0151447,2 17,2 C19.172216,2 20.98052,3.790861 21,6 C20.98052,8.209139 19.172216,10 17,10 L16,10 L17,10 C20.287544,10 23,12.6862915 23,16 L23,18 M11,5 C10.5962715,3.33566165 8.98485529,2 7,2 C4.82778404,2 3.01948003,3.790861 3,6 C3.01948003,8.209139 4.82778404,10 7,10 L8,10 L7,10 C3.71245602,10 1,12.6862915 1,16 L1,18" /> </svg> } label={numMembers} /> </Box> <div>{links}</div> </Box> </Sidebar> ); } } export default withStyles(s)(Navbar);
app/components/H3/index.js
ReelTalkers/reeltalk-web
import React from 'react' function H3(props) { return ( <h3 { ...props } /> ) } export default H3
MobileApp/node_modules/react-native-elements/src/checkbox/CheckBox.js
VowelWeb/CoinTradePros.com
import PropTypes from 'prop-types'; import React from 'react'; import { StyleSheet, TouchableOpacity, View, Platform, Text as NativeText, } from 'react-native'; import TextElement from '../text/Text'; import fonts from '../config/fonts'; import colors from '../config/colors'; import FAIcon from 'react-native-vector-icons/FontAwesome'; import getIconType from '../helpers/getIconType'; const CheckBox = props => { const { component, checked, iconRight, title, center, right, containerStyle, textStyle, onPress, onLongPress, onIconPress, onLongIconPress, checkedIcon, uncheckedIcon, iconType, checkedColor, uncheckedColor, checkedTitle, fontFamily, ...attributes } = props; let Icon = FAIcon; if (iconType) { Icon = getIconType(iconType); } const Component = component || TouchableOpacity; let iconName = uncheckedIcon; if (checked) { iconName = checkedIcon; } return ( <Component onLongPress={onLongPress} onPress={onPress} style={[styles.container, containerStyle && containerStyle]} {...attributes} > <View style={[ styles.wrapper, right && { justifyContent: 'flex-end' }, center && { justifyContent: 'center' }, ]} > {!iconRight && <Icon color={checked ? checkedColor : uncheckedColor} name={iconName} size={24} onLongPress={onLongIconPress} onPress={onIconPress} />} <TextElement style={[ styles.text, textStyle && textStyle, fontFamily && { fontFamily }, ]} > {checked ? checkedTitle || title : title} </TextElement> {iconRight && <Icon color={checked ? checkedColor : uncheckedColor} name={iconName} size={24} onLongPress={onLongIconPress} onPress={onIconPress} />} </View> </Component> ); }; CheckBox.defaultProps = { checked: false, iconRight: false, right: false, center: false, checkedColor: 'green', uncheckedColor: '#bfbfbf', checkedIcon: 'check-square-o', uncheckedIcon: 'square-o', }; CheckBox.propTypes = { component: PropTypes.any, checked: PropTypes.bool, iconRight: PropTypes.bool, title: PropTypes.string, center: PropTypes.bool, right: PropTypes.bool, containerStyle: View.propTypes.style, textStyle: NativeText.propTypes.style, onPress: PropTypes.func, onLongPress: PropTypes.func, checkedIcon: PropTypes.string, uncheckedIcon: PropTypes.string, iconType: PropTypes.string, checkedColor: PropTypes.string, uncheckedColor: PropTypes.string, checkedTitle: PropTypes.string, onIconPress: PropTypes.func, onLongIconPress: PropTypes.func, fontFamily: PropTypes.string, }; const styles = StyleSheet.create({ wrapper: { flexDirection: 'row', alignItems: 'center', }, container: { margin: 5, marginLeft: 10, marginRight: 10, backgroundColor: '#fafafa', borderColor: '#ededed', borderWidth: 1, padding: 10, borderRadius: 3, }, text: { marginLeft: 10, marginRight: 10, color: colors.grey1, ...Platform.select({ ios: { fontWeight: 'bold', }, android: { ...fonts.android.bold, }, }), }, }); export default CheckBox;
ui/src/containers/municipalities-grid/index.js
indraneel/sustainability-dashboard
import React, { Component } from 'react'; import {GridList, GridTile} from 'material-ui/GridList'; import style from './municipalities-grid.style.js'; import MunicipalitiesGridTile from '../../components/municipalities-grid-tile'; import CategoryMapper from '../../constants/category-map'; import {LoadingIndicator} from 'lucid-ui'; import orderBy from 'lodash/orderBy'; class MunicipalitiesGrid extends Component { sortMunicipalities(actions) { let output = []; output = orderBy(actions, [function(o) { return Number.parseInt(o.points); }], ['desc']); console.log(actions); return output; } renderTiles(municipalities, selectedMunicipality = null) { let output = []; if (!selectedMunicipality) { municipalities.forEach((muniObj) => { output.push( <MunicipalitiesGridTile municipality={muniObj} /> ); }); } else { municipalities.forEach((muniObj) => { if (muniObj.town === selectedMunicipality) { output.push( <MunicipalitiesGridTile municipality={muniObj} /> ); } }); } return output; } render() { let municipalities = this.sortMunicipalities(this.props.municipalities); let tiles = this.renderTiles(municipalities, this.props.selectedMunicipality); return( <div style={style.root}> <LoadingIndicator isLoading={this.props.isFetching}> <GridList cellHeight={'auto'} cols={3} padding={25} style={style.gridList} > {tiles} </GridList> </LoadingIndicator> </div> ) } } export default MunicipalitiesGrid;
src/esm/components/graphics/icons/envelope-icon/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "title"]; import React from 'react'; import PropTypes from 'prop-types'; export var EnvelopeIcon = function EnvelopeIcon(_ref) { var color = _ref.color, title = _ref.title, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("svg", _extends({ width: "17", height: "14", viewBox: "0 0 17 14", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", { d: "M14.115 0h-11.2c-.637 0-1.247.255-1.697.71a2.435 2.435 0 0 0-.703 1.713v9.154c0 .643.253 1.259.703 1.713.45.455 1.06.71 1.697.71h11.2a2.382 2.382 0 0 0 1.697-.71 2.425 2.425 0 0 0 .703-1.713V2.423A2.443 2.443 0 0 0 15.812.71 2.399 2.399 0 0 0 14.115 0Zm-11.2 1.615h11.2c.212 0 .415.085.565.237.15.151.235.357.235.571v.967L9.984 6.793a2.512 2.512 0 0 1-2.952 0L2.115 3.39v-.967c0-.214.084-.42.234-.571a.796.796 0 0 1 .566-.237Zm11.2 10.77h-11.2a.796.796 0 0 1-.566-.237.811.811 0 0 1-.234-.571v-6.23l4 2.762a4.101 4.101 0 0 0 4.786 0l4.014-2.762v6.23c0 .214-.085.42-.235.571a.796.796 0 0 1-.565.237Z", fill: color })); }; EnvelopeIcon.propTypes = { color: PropTypes.string, title: PropTypes.string }; EnvelopeIcon.defaultProps = { color: '#222', title: '' };
common/containers/ArticleBrowser/ArticleBrowser.js
kherrick/postpress
import { connect } from 'react-redux' import { getArticles } from '../../actions/creators/articleBrowser/thunks/articleBrowser' import Article from './Article' import config from '../../../config/config' import InfiniteScroll from 'react-infinite-scroller' import PropTypes from 'prop-types' import React from 'react' const handleScroll = ({ categorySlug, dispatch, browserTypeState, location, type }) => () => { const segments = location.pathname === '/' ? ['root', null] // hack to support "root" category : location.pathname.split('/') const lastSegment = segments.pop() || segments.pop() // the last segment does not equal the categorySlug // investigate infinite scroll usage... if (lastSegment !== categorySlug) { return } // prevent scroll events from previous views from dispatching if (type === browserTypeState) { // @todo -- dynamically fetching from the config seems fragile const perPage = config.get(`site.api.${type}.posts.per_page`) const postsUrl = config.get(`site.api.${type}.posts.url`) dispatch(getArticles({ browserTypeState, perPage, postsUrl, type })) } } const ArticleBrowserWrapper = ({ type }) => { const ArticleBrowser = ({ articleBrowser, dispatch, location }) => { const articles = articleBrowser.items.map(article => <Article key={article.id} {...article} />) return ( <div data-test="infinite-scroll"> <InfiniteScroll hasMore={articleBrowser.hasMore} loadMore={handleScroll({ browserTypeState: articleBrowser.browserType, categorySlug: articleBrowser.categorySlug, dispatch, location, type })} loader={<div className="loader">{`Loading ...`}</div>} pageStart={0} useWindow={(() => true)()} > {articles} </InfiniteScroll> </div> ) } ArticleBrowser.propTypes = { articleBrowser: PropTypes.shape({}).isRequired, dispatch: PropTypes.func.isRequired, location: PropTypes.shape({ pathname: PropTypes.string.isRequired }).isRequired } return ArticleBrowser } const mapStateToProps = state => { return { articleBrowser: state.articleBrowser, location: state.router.location } } export default ({ type }) => { return connect(mapStateToProps)(ArticleBrowserWrapper({ type })) }
src/Parser/Mage/Frost/Modules/Features/WintersChill.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import EnemyInstances from 'Parser/Core/Modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import { formatMilliseconds, formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; const debug = false; const HARDCAST_HITS = [ SPELLS.FROSTBOLT_DAMAGE.id, SPELLS.EBONBOLT_DAMAGE.id, SPELLS.GLACIAL_SPIKE_DAMAGE.id, ]; class WintersChillTracker extends Analyzer { static dependencies = { combatants: Combatants, enemies: EnemyInstances, }; hasGlacialSpike; totalProcs = 0; hardcastHits = 0; missedHardcasts = 0; singleHardcasts = 0; iceLanceHits = 0; missedIceLanceCasts = 0; singleIceLanceCasts = 0; doubleIceLanceCasts = 0; on_initialized() { this.hasGlacialSpike = this.combatants.selected.hasTalent(SPELLS.GLACIAL_SPIKE_TALENT.id); } on_byPlayer_damage(event) { const spellId = event.ability.guid; const enemy = this.enemies.getEntity(event); if (!enemy || !enemy.hasBuff(SPELLS.WINTERS_CHILL.id)) { return; } if (spellId === SPELLS.ICE_LANCE_DAMAGE.id) { this.iceLanceHits += 1; if(debug) { console.log("Ice Lance into Winter's Chill"); } } else if(HARDCAST_HITS.includes(spellId)) { this.hardcastHits += 1; if(debug) { console.log(`${event.ability.name} into Winter's Chill`); } } } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.iceLanceHits = 0; this.hardcastHits = 0; } on_byPlayer_removedebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.totalProcs += 1; if (this.iceLanceHits === 0) { this.missedIceLanceCasts += 1; } else if (this.iceLanceHits === 1) { this.singleIceLanceCasts += 1; } else if (this.iceLanceHits === 2) { this.doubleIceLanceCasts += 1; } else { console.error(`Unexpected number of Ice Lances inside Winter's Chill @ ${formatMilliseconds(this.owner.currentTimestamp - this.owner.fight.start_time)} -> ${this.iceLanceHits}`); } if (this.hardcastHits === 0) { this.missedHardcasts += 1; } else if (this.hardcastHits === 1) { this.singleHardcasts += 1; } else { console.error(`Unexpected number of Frostbolt hits inside Winter's Chill @ ${formatMilliseconds(this.owner.currentTimestamp - this.owner.fight.start_time)} -> ${this.hardcastHits}`); } } get iceLanceMissedPercent() { return (this.missedIceLanceCasts / this.totalProcs) || 0; } get iceLanceUtil() { return 1 - this.iceLanceMissedPercent; } get iceLanceUtilSuggestionThresholds() { return { actual: this.iceLanceUtil, isLessThan: { minor: 0.95, average: 0.85, major: 0.75, }, style: 'percentage', }; } get hardcastMissedPercent() { return (this.missedHardcasts / this.totalProcs) || 0; } get hardcastUtil() { return 1 - this.hardcastMissedPercent; } // less strict than the ice lance suggestion both because it's less important, // and also because using a Brain Freeze after being forced to move is a good excuse for missing the hardcast. get hardcastUtilSuggestionThresholds() { return { actual: this.hardcastUtil, isLessThan: { minor: 0.90, average: 0.80, major: 0.60, }, style: 'percentage', }; } get doubleIceLancePercentage() { return this.doubleIceLanceCasts / this.totalProcs || 0; } suggestions(when) { when(this.iceLanceUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>You failed to Ice Lance into <SpellLink id={SPELLS.WINTERS_CHILL.id}/> {this.missedIceLanceCasts} times ({formatPercentage(this.iceLanceMissedPercent)}%). Make sure you cast <SpellLink id={SPELLS.ICE_LANCE.id}/> after each <SpellLink id={SPELLS.FLURRY.id}/> to benefit from <SpellLink id={SPELLS.SHATTER.id}/>.</Wrapper>) .icon(SPELLS.ICE_LANCE.icon) .actual(`${formatPercentage(this.iceLanceMissedPercent)}% Winter's Chill not shattered with Ice Lance`) .recommended(`<${formatPercentage(1 - this.iceLanceUtilSuggestionThresholds.isLessThan.minor)}% is recommended`); }); if(this.hasGlacialSpike) { // Different suggestion text depending on talent choice (which includes a SpellLink, so can't switch inside suggestion) when(this.hardcastUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>You failed to <SpellLink id={SPELLS.FROSTBOLT.id}/>, <SpellLink id={SPELLS.GLACIAL_SPIKE_TALENT.id}/>, or <SpellLink id={SPELLS.EBONBOLT.id}/> into <SpellLink id={SPELLS.WINTERS_CHILL.id}/> {this.missedHardcasts} times ({formatPercentage(this.hardcastMissedPercent)}%}). Make sure you hard cast just before each instant <SpellLink id={SPELLS.FLURRY.id}/> to benefit from <SpellLink id={SPELLS.SHATTER.id}/>.</Wrapper>) .icon(SPELLS.FROSTBOLT.icon) .actual(`${formatPercentage(this.hardcastMissedPercent)}% Winter's Chill not shattered with Frostbolt, Glacial Spike, or Ebonbolt`) .recommended(`${formatPercentage(1 - recommended)}% is recommended`); }); } else { when(this.hardcastUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>You failed to <SpellLink id={SPELLS.FROSTBOLT.id}/> or <SpellLink id={SPELLS.EBONBOLT.id}/> into <SpellLink id={SPELLS.WINTERS_CHILL.id}/> {this.missedHardcasts} times ({formatPercentage(this.hardcastMissedPercent)}%}). Make sure you hard cast just before each instant <SpellLink id={SPELLS.FLURRY.id}/> to benefit from <SpellLink id={SPELLS.SHATTER.id}/>.</Wrapper>) .icon(SPELLS.FROSTBOLT.icon) .actual(`${formatPercentage(this.hardcastMissedPercent)}% Winter's Chill not shattered with Frostbolt or Ebonbolt`) .recommended(`${formatPercentage(1 - recommended)}% is recommended`); }); } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.WINTERS_CHILL.id} />} value={( <span> <SpellIcon id={SPELLS.ICE_LANCE.id} style={{ height: '1.2em', marginBottom: '.15em', }} /> {' '}{formatPercentage(this.iceLanceUtil, 0)}{' %'} <br /> <SpellIcon id={SPELLS.FROSTBOLT.id} style={{ height: '1.2em', marginBottom: '.15em', }} /> {' '}{formatPercentage(this.hardcastUtil, 0)}{' %'} </span> )} label="Winter's Chill Utilization" tooltip={`Every Brain Freeze Flurry should be preceded by a Frostbolt${this.hasGlacialSpike ? `, Glacial Spike, ` : ` `}or Ebonbolt and followed by an Ice Lance, so that both the preceding and following spells benefit from Shatter. <br><br> You double Ice Lance'd into Winter's Chill ${this.doubleIceLanceCasts} times (${formatPercentage(this.doubleIceLancePercentage, 1)}%). Note this is usually impossible, it can only be done with strong haste buffs active and by moving towards the target while casting. It should mostly be considered 'extra credit'.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(14); } export default WintersChillTracker;
src/index.js
rmoliva/bacon_react_pet
/* import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; */ // Render the main component into the dom // ReactDOM.render(<App />, document.getElementById('app')); import React from 'react'; import ReactDOM from 'react-dom'; import ToDo from './views/todo'; var onHandleClick = function(options) { console.log(options) }; ReactDOM.render(<ToDo handleAction={onHandleClick} />, document.getElementById('app'));
src/Interpolate.js
pandoraui/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { component: React.PropTypes.node, format: React.PropTypes.string, unsafe: React.PropTypes.bool }, getDefaultProps() { return { component: 'span', unsafe: false }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
src/components/Root.js
qkevinto/kevinto.me
import React from 'react'; import { root } from './Root.module.scss'; import About from '../components/About'; import SocialActivities from '../components/SocialActivities'; export default class Root extends React.Component { render() { return ( <div className={root}> <About></About> <SocialActivities></SocialActivities> </div> ); } }
src/components/video_list.js
IanY57/ReduxSimpleStarter
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} /> ); }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
tests/client/ui/components/TestSwitch.js
jasonthomas/addons-frontend
import React from 'react'; import { Simulate, renderIntoDocument } from 'react-addons-test-utils'; import { findDOMNode } from 'react-dom'; import Switch from 'ui/components/Switch'; describe('<Switch />', () => { function renderButton(props = {}) { const renderProps = { dispatch: sinon.spy(), label: 'Hey', name: 'sup', ...props, }; return renderIntoDocument(<Switch {...renderProps} />); } it('is off when not checked or disabled', () => { const button = renderButton(); const root = findDOMNode(button); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.hasAttribute('disabled'), false); assert.equal(checkbox.checked, false); }); it('is inactive when disabled', () => { const button = renderButton({ disabled: true }); const root = findDOMNode(button); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.hasAttribute('disabled'), true); assert.equal(checkbox.checked, false); }); it('is active when checked and not disabled', () => { const button = renderButton({ checked: true }); const root = findDOMNode(button); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.hasAttribute('disabled'), false); assert.equal(checkbox.checked, true); }); it('is inactive when checked and disabled', () => { const button = renderButton({ checked: true, disabled: true }); const root = findDOMNode(button); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.hasAttribute('disabled'), true); assert.equal(checkbox.checked, true); }); it('shows success when success is set', () => { const button = renderButton({ success: true }); const root = findDOMNode(button); assert.ok(root.classList.contains('Switch--success')); }); it('does not include the progress when it is undefined', () => { const button = renderButton(); const root = findDOMNode(button); assert.equal(root.getAttribute('data-progress'), 0); }); it('reflects valid progress values', () => { const button = renderButton({ progress: 50 }); const root = findDOMNode(button); assert.ok(root.classList.contains('Switch--progress')); assert.equal(root.getAttribute('data-progress'), 50); }); it('reflects indefinite progress', () => { const button = renderButton({ checked: true, progress: Infinity }); const root = findDOMNode(button); assert.ok(root.classList.contains('Switch--indefinite')); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.checked, true, 'checked is true'); assert.equal(root.getAttribute('data-progress'), 100); }); it('reflects indefinite reverse progress', () => { const button = renderButton({ checked: false, progress: -Infinity }); const root = findDOMNode(button); assert.ok(root.classList.contains('Switch--indefinite-reverse')); const checkbox = root.querySelector('input[type=checkbox]'); assert.equal(checkbox.checked, false, 'checked is false'); assert.equal(root.getAttribute('data-progress'), 0); }); it('passes change calls to onChange', () => { const onChange = sinon.spy(); const root = findDOMNode(renderButton({ onChange })); const checkbox = root.querySelector('input[type=checkbox]'); Simulate.change(checkbox); assert.ok(onChange.calledWith()); }); it('associates the label and input with id and for attributes', () => { const button = renderButton({ name: 'foo' }); const root = findDOMNode(button); assert.equal(root.querySelector('input').getAttribute('id'), 'install-button-foo', 'id is set'); assert.equal(root.querySelector('label').getAttribute('for'), 'install-button-foo', 'for attribute matches id'); }); });
src/BootstrapMixin.js
insionng/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;
front_end/src/pages/Reporting/Reporting-Reports.js
oyiptong/splice
import React from 'react'; import {connect} from 'react-redux'; import moment from 'moment'; import Select from 'react-select'; import {Table} from 'react-tabular'; import {fetchCampaigns, fetchCampaign, campaignSetFilter} from 'actions/Campaigns/CampaignActions'; import {fetchAccounts} from 'actions/Accounts/AccountActions'; import {fetchStats} from 'actions/Stats/StatsActions'; import CampaignSummary from './CampaignSummary'; import { FILTERS, DEFAULT_REPORT_SETTINGS, GROUP_BY_OPTIONS, GROUP_BY_FIELDS, BASE_FIELDS } from './reportingConsts'; import {createFieldSet, queryParser} from './reportingUtils'; const ReportingReports = React.createClass({ getInitialState: function() { return _.assign({}, DEFAULT_REPORT_SETTINGS, { showEditor: true, showAllFilters: false }); }, componentWillMount: function() { this.props.dispatch(campaignSetFilter('past', true)); this.props.dispatch(fetchAccounts()); const query = queryParser(this.props.location.query); if (query.account_id) { this.props.dispatch(fetchCampaigns(query.account_id)); this.setState(_.assign({}, query, {showEditor: false})); this.generateReport(query); } }, componentWillUpdate: function(prevProps) { if (this.props.Stat.rows !== prevProps.Stat.rows && !_.isEqual(queryParser(this.props.location.query), this.state)) { this.props.history.pushState( this.props.location.state, this.props.location.pathname, queryParser(this.state) ); } }, onSelectAccount: function(accountId) { if (accountId) this.props.dispatch(fetchCampaigns(accountId)); this.setState({account_id: accountId, campaign_id: null}); }, onSelectCampaign: function(campaignId) { if (!campaignId) return this.setState({campaign_id: null}); const {start_date, end_date} = campaignId ? this.campaignById(campaignId) : null; this.setState({ campaign_id: campaignId, start_date: moment(start_date, 'YYYY-MM-DD').format('YYYY-MM-DD'), end_date: moment(end_date, 'YYYY-MM-DD').format('YYYY-MM-DD') }); }, render: function() { const reportSettings = this.state; const currentCampaign = this.props.Campaign.details; const stats = this.props.Stat.rows || []; const query = this.props.Stat.query; const fields = createFieldSet(query.group_by); return (<div> <aside className={'sidebar' + (this.state.showEditor ? '' : ' collapsed')}> <div className="report-settings"> <section> <div className="form-group"> <label>Account</label> {this.props.Account.rows.length && <Select value={reportSettings.account_id} options={this.props.Account.rows.map(a => { return {value: a.id, label: a.name}; })} onChange={this.onSelectAccount} />} </div> <div className="form-group" hidden={!reportSettings.account_id || !this.props.Campaign.rows.length}> <label>Campaign</label> {this.props.Campaign.rows.length && <Select value={this.props.Campaign.rows ? reportSettings.campaign_id : ''} options={this.props.Campaign.rows.map(c => { return {value: c.id, label: c.name}; })} onChange={this.onSelectCampaign} />} </div> </section> <div hidden={!this.state.campaign_id}> <section className="flex-wrapper"> <div className="form-group half"> <label>Start Date</label> <input className="form-control" value={reportSettings.start_date} onChange={(e) => this.setState({start_date: e.target.value})} /> </div> <div className="form-group half"> <label>End Date</label> <input className="form-control" value={reportSettings.end_date} onChange={(e) => this.setState({end_date: e.target.value})} /> </div> </section> <section> <div className="form-group"> <label>Group By</label> <div className="form-group"> {this.state.group_by.map((groupBy, index) => { return (<Select key={index} value={groupBy} options={GROUP_BY_OPTIONS} onChange={value => this.setGroupBy(value, index)} />); })} </div> <div className="form-group"> <button className="btn btn-default btn-emphasis" onClick={() => this.addGroupBy()}>Add field</button> </div> </div> </section> <section className="extra" hidden={!this.showAllFilters()}> <div className="form-group"> <label>Type</label> <Select value={reportSettings.adgroup_type} options={[ {value: null, label: 'All'}, {value: 'directory', label: 'Directory'}, {value: 'suggested', label: 'Suggested'} ]} placeholder="All" onChange={(value) => this.setState({adgroup_type: value})} /> </div> <div className="form-group"> <label>Channel</label> <Select value={reportSettings.channel_id} options={[{value: null, label: 'All'}].concat(this.props.Init.channels.map(c => { return {value: c.id, label: c.name}; }))} placeholder="All" onChange={(value) => this.setState({channel_id: value})} /> </div> <div className="form-group"> <label>Locale</label> <Select value={reportSettings.locale} options={[{value: null, label: 'All'}].concat(this.props.Init.locales.map(l => { return {value: l, label: l}; }))} placeholder="All" onChange={(value) => this.setState({locale: value})} /> </div> <div className="form-group"> <label>Country</label> <Select value={reportSettings.country_code} options={[{value: null, label: 'All'}].concat(this.props.Init.countries.map(c => { return {value: c.country_code, label: c.country_name}; }))} placeholder="All" onChange={(value) => this.setState({country_code: value})} /> </div> <div className="form-group"> <button className="btn btn-default btn-emphasis" onClick={() => this.setState({ showAllFilters: false, channel_id: null, adgroup_type: null })}> Clear extra filters </button> </div> </section> <section hidden={this.showAllFilters()}> <button className="btn btn-default btn-emphasis" onClick={() => this.setState({showAllFilters: true})}> <span className="fa fa-sliders" /> Show more fitlers </button> </section> <section> <button onClick={() => this.generateReport(this.state)} className="btn btn-pink btn-emphasis"> Generate Report </button> </section> </div> </div> </aside> <main className="main" hidden={!currentCampaign.id}> <h2> Report for {currentCampaign.name} by {query.group_by && query.group_by.map(field => GROUP_BY_FIELDS[field].label).join(' / ')} <div className="pull-right"> <button hidden={this.state.showEditor} className="btn btn-pink btn-emphasis" onClick={() => this.setState({showEditor: true})}> <span className="fa fa-pencil" /> Edit report </button> <button className="btn btn-default btn-emphasis" onClick={() => this.refs.table.download(`${currentCampaign.name}-stats.csv`)}> <span className="fa fa-file-o" /> Download as .csv </button> </div> </h2> <CampaignSummary campaign={currentCampaign} query={query} /> <Table ref="table" fields={fields} data={stats} fieldsEditable={true} /> </main> </div>); }, setGroupBy: function(value, index) { const groupBy = this.state.group_by.slice(); if (value) { groupBy[index] = value; } else { if (index > 0) groupBy.splice(index, 1); } this.setState({group_by: groupBy}); }, addGroupBy: function() { const groupBy = this.state.group_by.slice(); groupBy.push('date'); this.setState({group_by: groupBy}); }, campaignById: function(id) { const campaigns = this.props.Campaign.rows; let result; campaigns.forEach(c => { if (+c.id === +id) result = c; }); return result || {}; }, generateReport: function(query) { const params = queryParser(query); Object.keys(params).forEach(param => { if (!params[param]) delete params[param]; }); this.props.dispatch(fetchStats(params)); if (query.campaign_id) this.props.dispatch(fetchCampaign(query.campaign_id)); }, showAllFilters: function() { if (this.state.showAllFilters) return true; if (this.state.adgroup_type || this.state.channel_id) return true; return false; } }); function select(state) { return { Account: state.Account, Campaign: state.Campaign, Init: state.Init, Stat: state.Stat }; } // Wrap the component to inject dispatch and state into it export default connect(select)(ReportingReports);
__tests__/index.android.js
yarikgenza/gainster
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
packages/icons/src/md/action/ViewModule.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdViewModule(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M7 23h10V11H7v12zm0 14h10V25H7v12zm12 0h10V25H19v12zm12 0h10V25H31v12zM19 23h10V11H19v12zm12-12v12h10V11H31z" /> </IconBase> ); } export default MdViewModule;
site/src/components/ExampleColumnGroupsNoHeader.js
pbeshai/react-taco-table
import React from 'react'; import { TacoTable, DataType, SortDirection, Formatters } from 'react-taco-table'; import cellLinesData from '../data/cell_lines.json'; /** * An example demonstrating how to use column groups without headers */ const columns = [ { id: 'name', value: rowData => rowData.cellLine, header: 'Cell Line', renderer: cellData => <b>{cellData.label}</b>, sortValue: cellData => cellData.label, type: DataType.String, width: 250, }, { id: 'receptorStatus', header: 'Receptor Status', renderer: cellData => cellData.label, sortValue: cellData => cellData.label, type: DataType.String, }, { id: 'MLL3', type: DataType.String, }, { id: 'value', type: DataType.Number, renderer: Formatters.plusMinusFormat(1), firstSortDirection: SortDirection.Ascending, }, { id: 'rating', type: DataType.Number, renderer: Formatters.plusMinusFormat(2), }, { id: 'level', type: DataType.NumberOrdinal, }, ]; const columnGroups = [ { columns: ['name', 'receptorStatus'] }, { columns: ['value', 'rating', 'level'] }, ]; class ExampleColumnGroups extends React.Component { render() { return ( <TacoTable columns={columns} columnGroups={columnGroups} data={cellLinesData} striped sortable /> ); } } export default ExampleColumnGroups;
app/javascript/mastodon/features/status/components/action_bar.js
ikuradon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import IconButton from '../../../components/icon_button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; import { me, isStaff } from '../../../initial_state'; import classNames from 'classnames'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' }, direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost with original visibility' }, cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, quote: { id: 'status.quote', defaultMessage: 'Quote' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' }, more: { id: 'status.more', defaultMessage: 'More' }, mute: { id: 'status.mute', defaultMessage: 'Mute @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, block: { id: 'status.block', defaultMessage: 'Block @{name}' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, share: { id: 'status.share', defaultMessage: 'Share' }, pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, embed: { id: 'status.embed', defaultMessage: 'Embed' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, admin_status: { id: 'status.admin_status', defaultMessage: 'Open this status in the moderation interface' }, copy: { id: 'status.copy', defaultMessage: 'Copy link to status' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, }); const mapStateToProps = (state, { status }) => ({ relationship: state.getIn(['relationships', status.getIn(['account', 'id'])]), }); export default @connect(mapStateToProps) @injectIntl class ActionBar extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, relationship: ImmutablePropTypes.map, onReply: PropTypes.func.isRequired, onReblog: PropTypes.func.isRequired, onQuote: PropTypes.func.isRequired, onFavourite: PropTypes.func.isRequired, onBookmark: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onDirect: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onMute: PropTypes.func, onUnmute: PropTypes.func, onBlock: PropTypes.func, onUnblock: PropTypes.func, onBlockDomain: PropTypes.func, onUnblockDomain: PropTypes.func, onMuteConversation: PropTypes.func, onReport: PropTypes.func, onPin: PropTypes.func, onEmbed: PropTypes.func, intl: PropTypes.object.isRequired, }; handleReplyClick = () => { this.props.onReply(this.props.status); } handleReblogClick = (e) => { this.props.onReblog(this.props.status, e); } handleQuoteClick = () => { this.props.onQuote(this.props.status, this.context.router.history); } handleFavouriteClick = () => { this.props.onFavourite(this.props.status); } handleBookmarkClick = (e) => { this.props.onBookmark(this.props.status, e); } handleDeleteClick = () => { this.props.onDelete(this.props.status, this.context.router.history); } handleRedraftClick = () => { this.props.onDelete(this.props.status, this.context.router.history, true); } handleDirectClick = () => { this.props.onDirect(this.props.status.get('account'), this.context.router.history); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { const { status, relationship, onMute, onUnmute } = this.props; const account = status.get('account'); if (relationship && relationship.get('muting')) { onUnmute(account); } else { onMute(account); } } handleBlockClick = () => { const { status, relationship, onBlock, onUnblock } = this.props; const account = status.get('account'); if (relationship && relationship.get('blocking')) { onUnblock(account); } else { onBlock(status); } } handleBlockDomain = () => { const { status, onBlockDomain } = this.props; const account = status.get('account'); onBlockDomain(account.get('acct').split('@')[1]); } handleUnblockDomain = () => { const { status, onUnblockDomain } = this.props; const account = status.get('account'); onUnblockDomain(account.get('acct').split('@')[1]); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } handleReport = () => { this.props.onReport(this.props.status); } handlePinClick = () => { this.props.onPin(this.props.status); } handleShare = () => { navigator.share({ text: this.props.status.get('search_index'), url: this.props.status.get('url'), }); } handleEmbed = () => { this.props.onEmbed(this.props.status); } handleCopy = () => { const url = this.props.status.get('url'); const textarea = document.createElement('textarea'); textarea.textContent = url; textarea.style.position = 'fixed'; document.body.appendChild(textarea); try { textarea.select(); document.execCommand('copy'); } catch (e) { } finally { document.body.removeChild(textarea); } } render () { const { status, relationship, intl } = this.props; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const mutingConversation = status.get('muted'); const account = status.get('account'); const writtenByMe = status.getIn(['account', 'id']) === me; let menu = []; if (publicStatus) { menu.push({ text: intl.formatMessage(messages.copy), action: this.handleCopy }); menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed }); menu.push(null); } if (writtenByMe) { if (publicStatus) { menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick }); menu.push(null); } menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); menu.push({ text: intl.formatMessage(messages.redraft), action: this.handleRedraftClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick }); menu.push({ text: intl.formatMessage(messages.direct, { name: status.getIn(['account', 'username']) }), action: this.handleDirectClick }); menu.push(null); if (relationship && relationship.get('muting')) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.handleMuteClick }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.handleMuteClick }); } if (relationship && relationship.get('blocking')) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.handleBlockClick }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.handleBlockClick }); } menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport }); if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (relationship && relationship.get('domain_blocking')) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.handleUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.handleBlockDomain }); } } if (isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: status.getIn(['account', 'username']) }), href: `/admin/accounts/${status.getIn(['account', 'id'])}` }); menu.push({ text: intl.formatMessage(messages.admin_status), href: `/admin/accounts/${status.getIn(['account', 'id'])}/statuses/${status.get('id')}` }); } } const shareButton = ('share' in navigator) && publicStatus && ( <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShare} /></div> ); let replyIcon; if (status.get('in_reply_to_id', null) === null) { replyIcon = 'reply'; } else { replyIcon = 'reply-all'; } const reblogPrivate = status.getIn(['account', 'id']) === me && status.get('visibility') === 'private'; let reblogTitle; if (status.get('reblogged')) { reblogTitle = intl.formatMessage(messages.cancel_reblog_private); } else if (publicStatus) { reblogTitle = intl.formatMessage(messages.reblog); } else if (reblogPrivate) { reblogTitle = intl.formatMessage(messages.reblog_private); } else { reblogTitle = intl.formatMessage(messages.cannot_reblog); } return ( <div className='detailed-status__action-bar'> <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.reply)} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} /></div> <div className='detailed-status__button' ><IconButton className={classNames({ reblogPrivate })} disabled={!publicStatus && !reblogPrivate} active={status.get('reblogged')} title={reblogTitle} icon='retweet' onClick={this.handleReblogClick} /></div> <div className='detailed-status__button'><IconButton className='star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} /></div> <div className='detailed-status__button'><IconButton disabled={!publicStatus} title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.quote)} icon='quote-right' onClick={this.handleQuoteClick} /></div> {shareButton} <div className='detailed-status__button'><IconButton className='bookmark-icon' active={status.get('bookmarked')} title={intl.formatMessage(messages.bookmark)} icon='bookmark' onClick={this.handleBookmarkClick} /></div> <div className='detailed-status__action-bar-dropdown'> <DropdownMenuContainer size={18} icon='ellipsis-h' status={status} items={menu} direction='left' title={intl.formatMessage(messages.more)} /> </div> </div> ); } }
src/containers/icons.js
BryceKrah/Portfolio
import React, { Component } from 'react'; import Nav from './nav_bar'; export default class Icons extends Component { render() { return ( <div className="icon-container"> <a href="//github.com/brycekrah"><div className="icon-image icon-github"></div></a> <a href="//linkedin.com/in/brycekrah"><div className="icon-image icon-linkedin"></div></a> <a href="mailto:krahbryce@yahoo.com"><div className="icon-image icon-email"></div></a> </div> ); } }
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionTypeFormatter.js
cfouant/katello
import React from 'react'; import { Link } from 'react-router-dom'; import helpers from '../../../../move_to_foreman/common/helpers'; export const subscriptionTypeFormatter = (value, { rowData }) => { let cellContent; if (rowData.virt_only === false) { cellContent = __('Physical'); } else if (rowData.hypervisor) { cellContent = ( <span> {__('Guests of')} {' '} <Link to={helpers.urlBuilder('content_hosts', '', rowData.hypervisor.id)}>{rowData.hypervisor.name}</Link> </span> ); } else if (rowData.unmapped_guest) { cellContent = __('Temporary'); } else { cellContent = __('Virtual'); } return ( <td> {cellContent} </td> ); }; export default subscriptionTypeFormatter;
docs/src/app/index.js
ButuzGOL/constructor
require('./assets/styles/main.less'); import React from 'react'; import Router from 'react-router'; import routes from './routes'; window.React = React; Router.run(routes, (Handler) => { React.render(<Handler />, document.body); });
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/es/NavItem.js
GoogleCloudPlatform/prometheus-engine
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; var _excluded = ["className", "cssModule", "active", "tag"]; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; var propTypes = { tag: tagPropType, active: PropTypes.bool, className: PropTypes.string, cssModule: PropTypes.object }; var defaultProps = { tag: 'li' }; var NavItem = function NavItem(props) { var className = props.className, cssModule = props.cssModule, active = props.active, Tag = props.tag, attributes = _objectWithoutPropertiesLoose(props, _excluded); var classes = mapToCssModules(classNames(className, 'nav-item', active ? 'active' : false), cssModule); return /*#__PURE__*/React.createElement(Tag, _extends({}, attributes, { className: classes })); }; NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
src/js/admin/articles/filters/state-filter/state-filter.js
ucev/blog
import React from 'react' import { connect } from 'react-redux' import FilterSelect from '../filter-select' const STATE_OPTIONS = [ { value: '-1', title: '全部' }, { value: 'on', title: '已上线' }, { value: 'off', title: '已下线' }, ] const StateFilter = ({ value }) => ( <FilterSelect key="state" title="state" label="状态" value={value} options={STATE_OPTIONS} /> ) const mapStateToProps = state => ({ value: state.filters.state, }) const mapDispatchToProps = () => ({}) const _StateFilter = connect( mapStateToProps, mapDispatchToProps )(StateFilter) export default _StateFilter
src/svg-icons/communication/present-to-all.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPresentToAll = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z"/> </SvgIcon> ); CommunicationPresentToAll = pure(CommunicationPresentToAll); CommunicationPresentToAll.displayName = 'CommunicationPresentToAll'; export default CommunicationPresentToAll;
src/components/Post/Meta/Meta.js
bapti/blog
// @flow strict import React from 'react'; import moment from 'moment'; import styles from './Meta.module.scss'; type Props = { date: string }; const Meta = ({ date }: Props) => ( <div className={styles['meta']}> <p className={styles['meta__date']}>Published {moment(date).format('D MMM YYYY')}</p> </div> ); export default Meta;
test/components/OpenClose.spec.js
martinkwan/HNGRY
import React from 'react'; import { shallow } from 'enzyme'; import OpenClose from '../../src/components/openClose'; describe('(Component) OpenClose', () => { let wrapper; beforeEach(() => { wrapper = shallow(<OpenClose />); }); it('renders self successfully', () => { expect(wrapper).to.have.length(1); }); });
definitions/npm/styled-components_v2.x.x/flow_v0.53.x-/test_styled-components_native_v2.x.x.js
davidohayon669/flow-typed
// @flow import nativeStyled, { ThemeProvider as NativeThemeProvider, withTheme as nativeWithTheme, keyframes as nativeKeyframes, } from 'styled-components/native' import React from 'react' import type { Theme as NativeTheme, Interpolation as NativeInterpolation, ReactComponentFunctional as NativeReactComponentFunctional, ReactComponentFunctionalUndefinedDefaultProps as NativeReactComponentFunctionalUndefinedDefaultProps, ReactComponentClass as NativeReactComponentClass, ReactComponentStyled as NativeReactComponentStyled, ReactComponentStyledTaggedTemplateLiteral as NativeReactComponentStyledTaggedTemplateLiteral, ReactComponentUnion as NativeReactComponentUnion, ReactComponentIntersection as NativeReactComponentIntersection, } from 'styled-components' const NativeTitleTaggedTemplateLiteral: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.Text; const NativeTitleStyled: NativeReactComponentStyled<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleGeneric: NativeReactComponentIntersection<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleFunctional: NativeReactComponentFunctional<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleClass: NativeReactComponentClass<*> = nativeStyled.Text` font-size: 1.5em; `; declare var nativeNeedsReactComponentFunctional: NativeReactComponentFunctional<*> => void declare var nativeNeedsReactComponentClass: NativeReactComponentClass<*> => void nativeNeedsReactComponentFunctional(NativeTitleStyled) nativeNeedsReactComponentClass(NativeTitleStyled) const NativeExtendedTitle: NativeReactComponentIntersection<*> = nativeStyled(NativeTitleStyled)` font-size: 2em; `; const NativeWrapper: NativeReactComponentIntersection<*> = nativeStyled.View` padding: 4em; background: ${({theme}) => theme.background}; `; // ---- EXTEND ---- const NativeAttrs0ReactComponent: NativeReactComponentStyled<*> = nativeStyled.View.extend``; const NativeAttrs0ExtendReactComponent: NativeReactComponentIntersection<*> = NativeAttrs0ReactComponent.extend``; const NativeAttrs0SyledComponent: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View; const NativeAttrs0ExtendStyledComponent: NativeReactComponentIntersection<*> = NativeAttrs0SyledComponent.extend``; // ---- ATTRIBUTES ---- const NativeAttrs1: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View.attrs({ testProp: 'foo' }); // $ExpectError const NativeAttrs1Error: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View.attrs({ testProp: 'foo' })``; declare var needsString: string => void nativeNeedsReactComponentFunctional(nativeStyled.View.attrs({})``) nativeNeedsReactComponentClass(nativeStyled.View.attrs({})``) // $ExpectError needsString(nativeStyled.View.attrs({})``) const NativeAttrs2: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View .attrs({ testProp1: 'foo' }) .attrs({ testProp2: 'bar' }); const NativeAttrs3Styled: NativeReactComponentStyled<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Generic: NativeReactComponentIntersection<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Functional: NativeReactComponentFunctional<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Class: NativeReactComponentClass<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const nativeTheme: NativeTheme = { background: "papayawhip" }; // ---- WithComponent ---- const NativeWithComponent1: NativeReactComponentStyled<*> = nativeStyled.View.withComponent('Text'); const NativeWithComponent2: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(NativeWithComponent1); const NativeWithComponent3: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(NativeAttrs3Class); const NativeWithComponent4: NativeReactComponentStyled<*> = nativeStyled('View').withComponent('Text'); const NativeWithComponent5: NativeReactComponentStyled<*> = nativeStyled('View').withComponent(NativeWithComponent1); const NativeWithComponent6: NativeReactComponentStyled<*> = nativeStyled('View').withComponent(NativeAttrs3Class); // $ExpectError const NativeWithComponentError1: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(0); // $ExpectError const NativeWithComponentError2: NativeReactComponentStyled<*> = nativeStyled.View.withComponent('NotHere'); class NativeCustomComponentError3 extends React.Component<{ foo: string }> { render() { return <div />; } } // $ExpectError const NativeWithComponentError3 = nativeStyled(NativeCustomComponentError3).withComponent('Text'); // $ExpectError const NativeWithComponentError4 = nativeStyled(NativeCustomComponentError3).withComponent(NativeWithComponent1); // $ExpectError const NativeWithComponentError5 = nativeStyled(NativeCustomComponentError3).withComponent(NativeAttrs3Class); // $ExpectError const NativeWithComponentError6 = nativeStyled(NativeCustomComponentError3).withComponent(0); // $ExpectError const NativeWithComponentError7 = nativeStyled(NativeCustomComponentError3).withComponent('NotHere'); // ---- WithTheme ---- const NativeComponent: NativeReactComponentFunctionalUndefinedDefaultProps<{ theme: NativeTheme }> = ({ theme }) => ( <NativeThemeProvider theme={theme}> <NativeWrapper> <NativeTitleStyled>Hello World, this is my first styled component!</NativeTitleStyled> </NativeWrapper> </NativeThemeProvider> ); const NativeComponentWithTheme: NativeReactComponentFunctionalUndefinedDefaultProps<{}> = nativeWithTheme(NativeComponent); const NativeComponent2: NativeReactComponentFunctionalUndefinedDefaultProps<{}> = () => ( <NativeThemeProvider theme={outerTheme => outerTheme}> <NativeWrapper> <NativeTitleStyled>Hello World, this is my first styled component!</NativeTitleStyled> </NativeWrapper> </NativeThemeProvider> ); const NativeOpacityKeyFrame: string = nativeKeyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; // $ExpectError const NativeNoExistingElementWrapper = nativeStyled.nonexisting` padding: 4em; background: papayawhip; `; const nativeNum: 9 = 9 // $ExpectError const NativeNoExistingComponentWrapper = nativeStyled()` padding: 4em; background: papayawhip; `; // $ExpectError const NativeNumberWrapper = nativeStyled(nativeNum)` padding: 4em; background: papayawhip; `; // ---- COMPONENT CLASS TESTS ---- class NativeNeedsThemeReactClass extends React.Component<{ foo: string, theme: NativeTheme }> { render() { return <div />; } } class NativeReactClass extends React.Component<{ foo: string }> { render() { return <div />; } } const NativeStyledClass: NativeReactComponentClass<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeNeedsThemeReactClass)` color: red; `; const NativeNeedsFoo1Class: NativeReactComponentClass<{ foo: string }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo0ClassError: NativeReactComponentClass<{ foo: string }> = nativeWithTheme(NativeReactClass); // $ExpectError const NativeNeedsFoo1ClassError: NativeReactComponentClass<{ foo: string }> = nativeWithTheme(NeedsFoo1Class); // $ExpectError const NativeNeedsFoo1ErrorClass: NativeReactComponentClass<{ foo: number }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo2ErrorClass: NativeReactComponentClass<{ foo: string }, { theme: string }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo3ErrorClass: NativeReactComponentClass<{ foo: string, theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1Class); // $ExpectError const NativeNeedsFoo4ErrorClass: NativeReactComponentClass<{ foo: number }> = nativeWithTheme(NativeNeedsFoo1Class); // $ExpectError const NativeNeedsFoo5ErrorClass: NativeReactComponentClass<{ foo: string, theme: string }> = nativeWithTheme(NativeNeedsFoo1Class); // ---- INTERPOLATION TESTS ---- const nativeInterpolation: Array<NativeInterpolation> = nativeStyled.css` background-color: red; `; // $ExpectError const nativeInterpolationError: Array<NativeInterpolation | boolean> = nativeStyled.css` background-color: red; `; // ---- DEFAULT COMPONENT TESTS ---- const NativeDefaultComponent: NativeReactComponentIntersection<{}> = nativeStyled.View` background-color: red; `; // $ExpectError const NativeDefaultComponentError: {} => string = nativeStyled.View` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS ---- declare var View: ({}) => React$Element<*> const NativeFunctionalComponent: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: NativeTheme }> = props => <View />; const NativeNeedsFoo1: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; // $ExpectError const NativeNeedsFoo1Error: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: number }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; const NativeNeedsFoo2: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; // $ExpectError const NativeNeedsFoo2Error: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: number }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; const NativeNeedsNothingInferred = nativeStyled(() => <View />); // ---- FUNCTIONAL COMPONENT TESTS (nativeWithTheme)---- const NativeNeedsFoo1Functional: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: string }> = nativeWithTheme(NativeFunctionalComponent); const NativeNeedsFoo2Functional: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: string }> = nativeWithTheme(NativeNeedsFoo1Functional); const NativeNeedsFoo1FunctionalDefaultProps: NativeReactComponentFunctional<{ foo: string }, { theme: NativeTheme }> = nativeWithTheme(NativeFunctionalComponent); const NativeNeedsFoo2FunctionalDefaultProps: NativeReactComponentFunctional<{ foo: string }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1FunctionalDefaultProps); // $ExpectError const NativeNeedsFoo1ErrorFunctional: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: number }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo2ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo3ErrorFunctional: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: number, theme: NativeTheme }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo4ErrorFunctional: NativeReactComponentFunctionalUndefinedDefaultProps<{ foo: number }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo5ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo6ErrorFunctional: NativeReactComponentFunctional<{ foo: number }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1Functional);
stories/modal/modal.js
JerryBerton/dh-component
import React from 'react'; import { Modal, Button, Menu, Dropdown, Form, Input } from '../../src'; class ModalDemo extends React.Component { constructor(props) { super(props); this.state = { visible: false, visibleForm: false }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ visible: true }); } handleConfirm = () => { Modal.confirm({ title: 'Confirm', content: 'Bla bla ...', onOk: () => { console.log('我是confirm'); }, onCancel: () => {} }) }; handleForm = () => { this.setState({ visibleForm: true }); } render() { const menu = ( <Menu> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/">1st menu item</a> </Menu.Item> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">2nd menu item</a> </Menu.Item> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.tmall.com/">3d menu item</a> </Menu.Item> </Menu> ); return ( <div> <Button type="primary" onClick={this.handleClick}>打开</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <Button type="primary" onClick={this.handleConfirm}>confirm</Button> <br/> <Button type="primary" onClick={this.handleForm}>form弹窗</Button> <Modal title="我是一个测试数据" visible={this.state.visible} okText="" onCancel={() => { this.setState({visible: false})}} onOk={() => {console.log('modal onOk')}} > <div style={{ backgroundColor: "#cdac00", height: 300}}> 我是模态框的body, 随便塞元素 </div> </Modal> <Modal title="我是一个测试数据" visible={this.state.visibleForm} onCancel={() => { this.setState({visibleForm: false})}} onOk={() => {console.log('modal onOk')}} > <Form layout="horizontal" > <Form.Item label="新邮新邮箱箱" width={74}> <Input placeholder="请输入有效的邮箱地址"/> </Form.Item> <Form.Item label="新邮箱" width={74}> <Input placeholder="请输入有效的邮箱地址"/> </Form.Item> <Form.Item label="新邮箱" width={74}> <Input placeholder="请输入有效的邮箱地址"/> </Form.Item> </Form> </Modal> </div> ) } } export default ModalDemo;
example/examples/SetNativePropsOverlays.js
j0ergo/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, TouchableOpacity, Dimensions, } from 'react-native'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class SetNativePropsOverlays extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, circle: { center: { latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }, radius: 700, }, polygon: [ { latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }, { latitude: LATITUDE - SPACE, longitude: LONGITUDE - SPACE, }, { latitude: LATITUDE - SPACE, longitude: LONGITUDE + SPACE, }, ], polyline: [ { latitude: LATITUDE + SPACE, longitude: LONGITUDE - SPACE, }, { latitude: LATITUDE - (2 * SPACE), longitude: LONGITUDE + (2 * SPACE), }, { latitude: LATITUDE - SPACE, longitude: LONGITUDE - SPACE, }, { latitude: LATITUDE - (2 * SPACE), longitude: LONGITUDE - SPACE, }, ], }; } handleColorChange(color) { const props = { strokeColor: color }; this.circle.setNativeProps(props); this.polygon.setNativeProps(props); this.polyline.setNativeProps(props); } render() { const { region, circle, polygon, polyline } = this.state; return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={region} > <MapView.Circle ref={ref => { this.circle = ref; }} center={circle.center} radius={circle.radius} fillColor="rgba(255, 255, 255, 0.6)" strokeColor="green" zIndex={3} strokeWidth={3} /> <MapView.Polygon ref={ref => { this.polygon = ref; }} coordinates={polygon} fillColor="rgba(255, 255, 255, 0.6)" strokeColor="green" strokeWidth={2} /> <MapView.Polyline ref={ref => { this.polyline = ref; }} coordinates={polyline} strokeColor="green" strokeWidth={3} /> </MapView> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => { this.handleColorChange('green'); }}> <View style={styles.bubble}> <Text>Green</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => { this.handleColorChange('black'); }}> <View style={styles.bubble}> <Text>Black</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => { this.handleColorChange('red'); }}> <View style={styles.bubble}> <Text>Red</Text> </View> </TouchableOpacity> </View> </View> ); } } SetNativePropsOverlays.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ 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, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = SetNativePropsOverlays;
packages/material-ui-icons/src/PictureInPictureAlt.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let PictureInPictureAlt = props => <SvgIcon {...props}> <path d="M19 11h-8v6h8v-6zm4 8V4.98C23 3.88 22.1 3 21 3H3c-1.1 0-2 .88-2 1.98V19c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H3V4.97h18v14.05z" /> </SvgIcon>; PictureInPictureAlt = pure(PictureInPictureAlt); PictureInPictureAlt.muiName = 'SvgIcon'; export default PictureInPictureAlt;
app/components/RButton.js
qinfuji/vpt
import React from 'react'; import styles from '../styles/button.less'; import classnames from 'classnames'; export default class RButton extends React.Component { componentWillUnmount(){ let {remove , id} = this.props; remove(id); } clickHandle(e){ this.props.onClick(e); } render() { let className = classnames('button'); return ( <button className={className} onClick={this.clickHandle.bind(this) }> {this.props.label} </button> ); } }
app/containers/Spa/SpaReport/index.js
vollmerr/app-hub
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { compose } from 'redux'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { createStructuredSelector } from 'reselect'; import { SelectionMode } from 'office-ui-fabric-react/lib/DetailsList'; import json2csv from 'json2csv'; import toJS from '../../../hocs/toJS'; import Loading from '../../../components/Loading'; import { downloadFile, formatList } from '../../../utils/data'; import { formattedDate } from '../../../utils/date'; import { shouldFetch } from '../../../utils/api'; import List from '../../../components/List'; import theme from '../../../utils/theme'; import LoadCommandBar from '../../App/LoadCommandBar'; import * as hubSelectors from '../../AppHub/selectors'; import { reportColumns, adminCsv, recipient } from '../data'; import * as selectors from '../selectors'; import * as actions from '../actions'; import * as C from '../constants'; import PieChart from './PieChart'; import Details from './Details'; import DisableModal from './DisableModal'; import EmailModal from './EmailModal'; export const Wrapper = styled.div` display: flex; flex-wrap: wrap; width: 100%; padding: ${theme.hub.padding / 2}px; min-height: calc( 100vh - \ ${theme.hub.headerHeight}px - \ ${theme.app.commandBarHeight}px ); `; export const Section = styled.div` flex: 1; display: flex; flex-direction: column; width: 100%; min-height: 250px; @media (min-width: ${theme.breakpoints.sm}px) { min-width: ${theme.breakpoints.sm - 40}px; } `; export const RecipientList = styled(List) ` margin: ${theme.hub.padding / 2}px; `; const titles = { [C.REPORT.PENDING]: 'Pending Recipients', [C.REPORT.PREVIOUS]: 'Acknowledged Recipients', }; const modal = { email: 'email', disable: 'disable', }; export class SpaReport extends React.PureComponent { constructor(props) { super(props); this.state = { loading: true, modals: { [modal.email]: false, [modal.disable]: false, }, chartData: [{}, {}], }; } async componentDidMount() { const { match, report, reportData, onGetReportDataRequest } = this.props; const id = match.params.id; if (shouldFetch(report.lastFetchedById[id])) { await onGetReportDataRequest(match.params.id); } this.buildReportData(reportData); this.setState({ loading: false }); // eslint-disable-line } componentWillReceiveProps(nextProps) { const { reportData } = nextProps; // if there is report data, map it out to [{ key, value }, {...}] this.buildReportData(reportData); } // items to display in command bar by default getCommands = () => { const { report } = this.props; // add back button, naviagtes to admin page const items = [{ key: 'back', name: 'Back', icon: 'navBack', ariaLabel: 'Back to Admin Page', onClick: this.handleBack, }]; // is NOT in pending status if (report.item[C.ACK.STATUS] !== C.STATUS.PENDING) { // add cancel button items.push({ key: 'download', name: 'Download', icon: 'download', ariaLabel: 'Download Report', onClick: this.handleDownload, }); } // is in pending status if (report.item[C.ACK.STATUS] === C.STATUS.PENDING) { // add cancel button items.push({ key: 'cancel', name: 'Cancel', icon: 'Clear', ariaLabel: 'Cancel Pending Acknowledgment', onClick: this.handleShowModal(modal.disable), }); } // is in active status if (report.item[C.ACK.STATUS] === C.STATUS.ACTIVE) { // add disable button items.push({ key: 'disable', name: 'Disable', icon: 'Clear', ariaLabel: 'Disable Exisiting Acknowledgment', onClick: this.handleShowModal(modal.disable), }); // add email button items.push({ key: 'email', name: 'Email', icon: 'email', ariaLabel: 'Email acknowledgment recipients', onClick: this.handleShowModal(modal.email), }); } return { items }; } buildReportData = (reportData) => { if (reportData) { const chartData = []; Object.values(C.REPORT).forEach((key) => { chartData[key] = { key, value: reportData[key].length, }; }); this.setState({ chartData }); } } // handles navigating back to the admin page handleBack = () => { const { history } = this.props; history.push('/spa/admin'); } // handles downloading the csv export handleDownload = () => { const { report, reportData } = this.props; const csv = json2csv({ data: formatList(reportData[report.key], recipient), newLine: '\r\n', ...adminCsv }); const name = `${report.item[C.ACK.TITLE]} - ${formattedDate(new Date())}.csv`; const type = 'data:text/csv;charset=utf-8;'; downloadFile(csv, name, type); } // handles displaying a modal by name handleShowModal = (name) => () => { this.setState({ modals: { ...this.state.modals, [name]: true } }); } // handles hiding a modal by name handleHideModal = (name) => () => { this.setState({ modals: { ...this.state.modals, [name]: false } }); } // handles submitting a disable handleSubmitDisable = () => { const { report, onDeactivateAckRequest } = this.props; onDeactivateAckRequest(report.item); this.handleHideModal(modal.disable)(); } // handles submitting an email handleSubmitEmail = () => { // const { report, onEmailRequest } = this.props; // onEmailRequest(...); this.handleHideModal(modal.email)(); } // handles clicking on the report or legend to swicth the key handleClickReport = (d) => { const key = d.data ? d.data.key : d; this.props.onSetReportKey(key); } render() { const { app, report, reportData, enums, setCommandBar } = this.props; const { loading, chartData, modals } = this.state; const isLoading = app.loading || loading; const { key, item } = report; // LOADING if (isLoading || app.error) { const loadingProps = { loading: isLoading, error: app.error, to: app.home.path, }; return <Loading {...loadingProps} />; } // build stats for chart lengend const pendingCount = reportData[C.REPORT.PENDING].length; const acknowledgedCount = reportData[C.REPORT.PREVIOUS].length; const totalCount = pendingCount + acknowledgedCount; const pendingPercent = Math.round((pendingCount / totalCount) * 100); const acknowldgedPercent = 100 - pendingPercent; const detailsProps = { item, enums, }; const pieChartProps = { dataKey: key, data: chartData, stats: { pending: { count: pendingCount, percent: pendingPercent, }, acknowledged: { count: acknowledgedCount, percent: acknowldgedPercent, }, }, onClick: this.handleClickReport, hasData: Boolean(chartData.some((x) => x.value)), }; const recipientListProps = { items: reportData[key], columns: reportColumns[key], title: titles[key], empty: { message: 'No Recipients', }, selectionMode: SelectionMode.none, style: { padding: theme.hub.padding + theme.app.commandBarHeight, }, }; const disableProps = { item, type: item[C.ACK.STATUS] === C.STATUS.PENDING ? 'cancel' : 'disable', hidden: !modals.disable, onClose: this.handleHideModal(modal.disable), onSubmit: this.handleSubmitDisable, }; const emailProps = { item, hidden: !modals.email, recipients: reportData[key], onClose: this.handleHideModal(modal.email), onSubmit: this.handleSubmitEmail, }; const commandBarProps = { setCommandBar, commandBar: this.getCommands(), disabled: isLoading || app.error, }; return ( <Wrapper> <Section> <Details {...detailsProps} /> <PieChart {...pieChartProps} /> </Section> <Section> <RecipientList {...recipientListProps} /> </Section> <DisableModal {...disableProps} /> <EmailModal {...emailProps} /> <LoadCommandBar {...commandBarProps} /> </Wrapper> ); } } const { func, object } = PropTypes; SpaReport.propTypes = { app: object.isRequired, report: object.isRequired, reportData: object, enums: object, onGetReportDataRequest: func.isRequired, // eslint-disable-line onSetReportKey: func.isRequired, onDeactivateAckRequest: func.isRequired, setCommandBar: func.isRequired, history: object.isRequired, match: object.isRequired, }; const mapStateToProps = createStructuredSelector({ app: hubSelectors.getApp, report: selectors.getReport, reportData: selectors.getReportData, enums: selectors.getEnums, }); export const mapDispatchToProps = (dispatch) => ({ onGetReportDataRequest: (id) => dispatch(actions.getReportDataRequest(id)), onSetReportKey: (key) => dispatch(actions.setReportKey(key)), onDeactivateAckRequest: (item) => dispatch(actions.deactivateAckRequest(item)), }); const withConnect = connect(mapStateToProps, mapDispatchToProps); export default compose( withRouter, withConnect, toJS, )(SpaReport);